Unnamed: 0
int64
0
0
repo_id
stringlengths
5
186
file_path
stringlengths
15
223
content
stringlengths
1
32.8M
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/release/findRegressions-nightly.py
#!/usr/bin/env python import re, string, sys, os, time DEBUG = 0 testDirName = 'llvm-test' test = ['compile', 'llc', 'jit', 'cbe'] exectime = ['llc-time', 'jit-time', 'cbe-time',] comptime = ['llc', 'jit-comptime', 'compile'] (tp, exp) = ('compileTime_', 'executeTime_') def parse(file): f=open(file, 'r') d = f.read() #Cleanup weird stuff d = re.sub(r',\d+:\d','', d) r = re.findall(r'TEST-(PASS|FAIL|RESULT.*?):\s+(.*?)\s+(.*?)\r*\n', d) test = {} fname = '' for t in r: if DEBUG: print t if t[0] == 'PASS' or t[0] == 'FAIL' : tmp = t[2].split(testDirName) if DEBUG: print tmp if len(tmp) == 2: fname = tmp[1].strip('\r\n') else: fname = tmp[0].strip('\r\n') if not test.has_key(fname) : test[fname] = {} for k in test: test[fname][k] = 'NA' test[fname][t[1]] = t[0] if DEBUG: print test[fname][t[1]] else : try: n = t[0].split('RESULT-')[1] if DEBUG: print n; if n == 'llc' or n == 'jit-comptime' or n == 'compile': test[fname][tp + n] = float(t[2].split(' ')[2]) if DEBUG: print test[fname][tp + n] elif n.endswith('-time') : test[fname][exp + n] = float(t[2].strip('\r\n')) if DEBUG: print test[fname][exp + n] else : print "ERROR!" sys.exit(1) except: continue return test # Diff results and look for regressions. def diffResults(d_old, d_new): for t in sorted(d_old.keys()) : if DEBUG: print t if d_new.has_key(t) : # Check if the test passed or failed. for x in test: if d_old[t].has_key(x): if d_new[t].has_key(x): if d_old[t][x] == 'PASS': if d_new[t][x] != 'PASS': print t + " *** REGRESSION (" + x + ")\n" else: if d_new[t][x] == 'PASS': print t + " * NEW PASS (" + x + ")\n" else : print t + "*** REGRESSION (" + x + ")\n" # For execution time, if there is no result, its a fail. for x in exectime: if d_old[t].has_key(tp + x): if not d_new[t].has_key(tp + x): print t + " *** REGRESSION (" + tp + x + ")\n" else : if d_new[t].has_key(tp + x): print t + " * NEW PASS (" + tp + x + ")\n" for x in comptime: if d_old[t].has_key(exp + x): if not d_new[t].has_key(exp + x): print t + " *** REGRESSION (" + exp + x + ")\n" else : if d_new[t].has_key(exp + x): print t + " * NEW PASS (" + exp + x + ")\n" else : print t + ": Removed from test-suite.\n" #Main if len(sys.argv) < 3 : print 'Usage:', sys.argv[0], \ '<old log> <new log>' sys.exit(-1) d_old = parse(sys.argv[1]) d_new = parse(sys.argv[2]) diffResults(d_old, d_new)
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/release/test-release.sh
#!/usr/bin/env bash #===-- test-release.sh - Test the LLVM release candidates ------------------===# # # The LLVM Compiler Infrastructure # # This file is distributed under the University of Illinois Open Source # License. # #===------------------------------------------------------------------------===# # # Download, build, and test the release candidate for an LLVM release. # #===------------------------------------------------------------------------===# if [ `uname -s` = "FreeBSD" ]; then MAKE=gmake else MAKE=make fi # Base SVN URL for the sources. Base_url="http://llvm.org/svn/llvm-project" Release="" Release_no_dot="" RC="" Triple="" use_gzip="no" do_checkout="yes" do_debug="no" do_asserts="no" do_compare="yes" do_rt="yes" do_libs="yes" do_libunwind="yes" do_test_suite="yes" do_openmp="no" BuildDir="`pwd`" use_autoconf="no" ExtraConfigureFlags="" function usage() { echo "usage: `basename $0` -release X.Y.Z -rc NUM [OPTIONS]" echo "" echo " -release X.Y.Z The release version to test." echo " -rc NUM The pre-release candidate number." echo " -final The final release candidate." echo " -triple TRIPLE The target triple for this machine." echo " -j NUM Number of compile jobs to run. [default: 3]" echo " -build-dir DIR Directory to perform testing in. [default: pwd]" echo " -no-checkout Don't checkout the sources from SVN." echo " -test-debug Test the debug build. [default: no]" echo " -test-asserts Test with asserts on. [default: no]" echo " -no-compare-files Don't test that phase 2 and 3 files are identical." echo " -use-gzip Use gzip instead of xz." echo " -configure-flags FLAGS Extra flags to pass to the configure step." echo " -use-autoconf Use autoconf instead of cmake" echo " -no-rt Disable check-out & build Compiler-RT" echo " -no-libs Disable check-out & build libcxx/libcxxabi/libunwind" echo " -no-libunwind Disable check-out & build libunwind" echo " -no-test-suite Disable check-out & build test-suite" echo " -openmp Check out and build the OpenMP run-time (experimental)" } if [ `uname -s` = "Darwin" ]; then # compiler-rt doesn't yet build with CMake on Darwin. use_autoconf="yes" fi while [ $# -gt 0 ]; do case $1 in -release | --release ) shift Release="$1" Release_no_dot="`echo $1 | sed -e 's,\.,,g'`" ;; -rc | --rc | -RC | --RC ) shift RC="rc$1" ;; -final | --final ) RC=final ;; -triple | --triple ) shift Triple="$1" ;; -configure-flags | --configure-flags ) shift ExtraConfigureFlags="$1" ;; -j* ) NumJobs="`echo $1 | sed -e 's,-j\([0-9]*\),\1,g'`" if [ -z "$NumJobs" ]; then shift NumJobs="$1" fi ;; -build-dir | --build-dir | -builddir | --builddir ) shift BuildDir="$1" ;; -no-checkout | --no-checkout ) do_checkout="no" ;; -test-debug | --test-debug ) do_debug="yes" ;; -test-asserts | --test-asserts ) do_asserts="yes" ;; -no-compare-files | --no-compare-files ) do_compare="no" ;; -use-gzip | --use-gzip ) use_gzip="yes" ;; -use-autoconf | --use-autoconf ) use_autoconf="yes" ;; -no-rt ) do_rt="no" ;; -no-libs ) do_libs="no" ;; -no-libunwind ) do_libunwind="no" ;; -no-test-suite ) do_test_suite="no" ;; -openmp ) do_openmp="yes" ;; -help | --help | -h | --h | -\? ) usage exit 0 ;; * ) echo "unknown option: $1" usage exit 1 ;; esac shift done # Check required arguments. if [ -z "$Release" ]; then echo "error: no release number specified" exit 1 fi if [ -z "$RC" ]; then echo "error: no release candidate number specified" exit 1 fi if [ -z "$Triple" ]; then echo "error: no target triple specified" exit 1 fi # Figure out how many make processes to run. if [ -z "$NumJobs" ]; then NumJobs=`sysctl -n hw.activecpu 2> /dev/null || true` fi if [ -z "$NumJobs" ]; then NumJobs=`sysctl -n hw.ncpu 2> /dev/null || true` fi if [ -z "$NumJobs" ]; then NumJobs=`grep -c processor /proc/cpuinfo 2> /dev/null || true` fi if [ -z "$NumJobs" ]; then NumJobs=3 fi # Projects list projects="llvm cfe clang-tools-extra" if [ $do_rt = "yes" ]; then projects="$projects compiler-rt" fi if [ $do_libs = "yes" ]; then projects="$projects libcxx libcxxabi" if [ $do_libunwind = "yes" ]; then projects="$projects libunwind" fi fi if [ $do_test_suite = "yes" ]; then projects="$projects test-suite" fi if [ $do_openmp = "yes" ]; then projects="$projects openmp" fi # Go to the build directory (may be different from CWD) BuildDir=$BuildDir/$RC mkdir -p $BuildDir cd $BuildDir # Location of log files. LogDir=$BuildDir/logs mkdir -p $LogDir # Final package name. Package=clang+llvm-$Release if [ $RC != "final" ]; then Package=$Package-$RC fi Package=$Package-$Triple # Errors to be highlighted at the end are written to this file. echo -n > $LogDir/deferred_errors.log function deferred_error() { Phase="$1" Flavor="$2" Msg="$3" echo "[${Flavor} Phase${Phase}] ${Msg}" | tee -a $LogDir/deferred_errors.log } # Make sure that a required program is available function check_program_exists() { local program="$1" if ! type -P $program > /dev/null 2>&1 ; then echo "program '$1' not found !" exit 1 fi } if [ `uname -s` != "Darwin" ]; then check_program_exists 'chrpath' check_program_exists 'file' check_program_exists 'objdump' fi # Make sure that the URLs are valid. function check_valid_urls() { for proj in $projects ; do echo "# Validating $proj SVN URL" if ! svn ls $Base_url/$proj/tags/RELEASE_$Release_no_dot/$RC > /dev/null 2>&1 ; then echo "$proj $Release release candidate $RC doesn't exist!" exit 1 fi done } # Export sources to the build directory. function export_sources() { check_valid_urls for proj in $projects ; do if [ -d $proj.src ]; then echo "# Reusing $proj $Release-$RC sources" continue fi echo "# Exporting $proj $Release-$RC sources" if ! svn export -q $Base_url/$proj/tags/RELEASE_$Release_no_dot/$RC $proj.src ; then echo "error: failed to export $proj project" exit 1 fi done echo "# Creating symlinks" cd $BuildDir/llvm.src/tools if [ ! -h clang ]; then ln -s ../../cfe.src clang fi cd $BuildDir/llvm.src/tools/clang/tools if [ ! -h extra ]; then ln -s ../../../../clang-tools-extra.src extra fi cd $BuildDir/llvm.src/projects if [ -d $BuildDir/test-suite.src ] && [ ! -h test-suite ]; then ln -s ../../test-suite.src test-suite fi if [ -d $BuildDir/compiler-rt.src ] && [ ! -h compiler-rt ]; then ln -s ../../compiler-rt.src compiler-rt fi if [ -d $BuildDir/libcxx.src ] && [ ! -h libcxx ]; then ln -s ../../libcxx.src libcxx fi if [ -d $BuildDir/libcxxabi.src ] && [ ! -h libcxxabi ]; then ln -s ../../libcxxabi.src libcxxabi fi if [ -d $BuildDir/libunwind.src ] && [ ! -h libunwind ]; then ln -s ../../libunwind.src libunwind fi cd $BuildDir } function configure_llvmCore() { Phase="$1" Flavor="$2" ObjDir="$3" case $Flavor in Release ) BuildType="Release" Assertions="OFF" ConfigureFlags="--enable-optimized --disable-assertions" ;; Release+Asserts ) BuildType="Release" Assertions="ON" ConfigureFlags="--enable-optimized --enable-assertions" ;; Debug ) BuildType="Debug" Assertions="ON" ConfigureFlags="--disable-optimized --enable-assertions" ;; * ) echo "# Invalid flavor '$Flavor'" echo "" return ;; esac echo "# Using C compiler: $c_compiler" echo "# Using C++ compiler: $cxx_compiler" cd $ObjDir echo "# Configuring llvm $Release-$RC $Flavor" if [ "$use_autoconf" = "yes" ]; then echo "#" env CC="$c_compiler" CXX="$cxx_compiler" \ $BuildDir/llvm.src/configure \ $ConfigureFlags --disable-timestamps $ExtraConfigureFlags \ 2>&1 | tee $LogDir/llvm.configure-Phase$Phase-$Flavor.log env CC="$c_compiler" CXX="$cxx_compiler" \ $BuildDir/llvm.src/configure \ $ConfigureFlags --disable-timestamps $ExtraConfigureFlags \ 2>&1 | tee $LogDir/llvm.configure-Phase$Phase-$Flavor.log else echo "#" env CC="$c_compiler" CXX="$cxx_compiler" \ cmake -G "Unix Makefiles" \ -DCMAKE_BUILD_TYPE=$BuildType -DLLVM_ENABLE_ASSERTIONS=$Assertions \ -DLLVM_ENABLE_TIMESTAMPS=OFF -DLLVM_CONFIGTIME="(timestamp not enabled)" \ $ExtraConfigureFlags $BuildDir/llvm.src \ 2>&1 | tee $LogDir/llvm.configure-Phase$Phase-$Flavor.log env CC="$c_compiler" CXX="$cxx_compiler" \ cmake -G "Unix Makefiles" \ -DCMAKE_BUILD_TYPE=$BuildType -DLLVM_ENABLE_ASSERTIONS=$Assertions \ -DLLVM_ENABLE_TIMESTAMPS=OFF -DLLVM_CONFIGTIME="(timestamp not enabled)" \ $ExtraConfigureFlags $BuildDir/llvm.src \ 2>&1 | tee $LogDir/llvm.configure-Phase$Phase-$Flavor.log fi cd $BuildDir } function build_llvmCore() { Phase="$1" Flavor="$2" ObjDir="$3" DestDir="$4" cd $ObjDir echo "# Compiling llvm $Release-$RC $Flavor" echo "# ${MAKE} -j $NumJobs VERBOSE=1" ${MAKE} -j $NumJobs VERBOSE=1 \ 2>&1 | tee $LogDir/llvm.make-Phase$Phase-$Flavor.log echo "# Installing llvm $Release-$RC $Flavor" echo "# ${MAKE} install" ${MAKE} install \ DESTDIR="${DestDir}" \ 2>&1 | tee $LogDir/llvm.install-Phase$Phase-$Flavor.log cd $BuildDir } function test_llvmCore() { Phase="$1" Flavor="$2" ObjDir="$3" cd $ObjDir if ! ( ${MAKE} -j $NumJobs -k check-all \ 2>&1 | tee $LogDir/llvm.check-Phase$Phase-$Flavor.log ) ; then deferred_error $Phase $Flavor "check-all failed" fi if [ "$use_autoconf" = "yes" ]; then # In the cmake build, unit tests are run as part of check-all. if ! ( ${MAKE} -k unittests 2>&1 | \ tee $LogDir/llvm.unittests-Phase$Phase-$Flavor.log ) ; then deferred_error $Phase $Flavor "unittests failed" fi fi cd $BuildDir } # Clean RPATH. Libtool adds the build directory to the search path, which is # not necessary --- and even harmful --- for the binary packages we release. function clean_RPATH() { if [ `uname -s` = "Darwin" ]; then return fi local InstallPath="$1" for Candidate in `find $InstallPath/{bin,lib} -type f`; do if file $Candidate | grep ELF | egrep 'executable|shared object' > /dev/null 2>&1 ; then if rpath=`objdump -x $Candidate | grep 'RPATH'` ; then rpath=`echo $rpath | sed -e's/^ *RPATH *//'` if [ -n "$rpath" ]; then newrpath=`echo $rpath | sed -e's/.*\(\$ORIGIN[^:]*\).*/\1/'` chrpath -r $newrpath $Candidate 2>&1 > /dev/null 2>&1 fi fi fi done } # Create a package of the release binaries. function package_release() { cwd=`pwd` cd $BuildDir/Phase3/Release mv llvmCore-$Release-$RC.install/usr/local $Package if [ "$use_gzip" = "yes" ]; then tar cfz $BuildDir/$Package.tar.gz $Package else tar cfJ $BuildDir/$Package.tar.xz $Package fi mv $Package llvmCore-$Release-$RC.install/usr/local cd $cwd } # Build and package the OpenMP run-time. This is still experimental and not # meant for official testing in the release, but as a way for providing # binaries as a convenience to those who want to try it out. function build_OpenMP() { cwd=`pwd` rm -rf $BuildDir/Phase3/openmp rm -rf $BuildDir/Phase3/openmp.install mkdir -p $BuildDir/Phase3/openmp cd $BuildDir/Phase3/openmp clang=$BuildDir/Phase3/Release/llvmCore-$Release-$RC.install/usr/local/bin/clang echo "#" cmake -DCMAKE_C_COMPILER=${clang} -DCMAKE_CXX_COMPILER=${clang}++ \ -DCMAKE_BUILD_TYPE=Release -DLIBOMP_MICRO_TESTS=on \ $BuildDir/openmp.src/runtime cmake -DCMAKE_C_COMPILER=${clang} -DCMAKE_CXX_COMPILER=${clang}++ \ -DCMAKE_BUILD_TYPE=Release -DLIBOMP_MICRO_TESTS=on \ $BuildDir/openmp.src/runtime echo "# Building OpenMP run-time" echo "# ${MAKE} -j $NumJobs VERBOSE=1" ${MAKE} -j $NumJobs VERBOSE=1 echo "# ${MAKE} libomp-micro-tests VERBOSE=1" ${MAKE} libomp-micro-tests VERBOSE=1 echo "# ${MAKE} install DESTDIR=$BuildDir/Phase3/openmp.install" ${MAKE} install DESTDIR=$BuildDir/Phase3/openmp.install OpenMPPackage=OpenMP-$Release if [ $RC != "final" ]; then OpenMPPackage=$OpenMPPackage-$RC fi OpenMPPackage=$OpenMPPackage-$Triple mv $BuildDir/Phase3/openmp.install/usr/local $BuildDir/$OpenMPPackage cd $BuildDir tar cvfJ $BuildDir/$OpenMPPackage.tar.xz $OpenMPPackage mv $OpenMPPackage $BuildDir/Phase3/openmp.install/usr/local cd $cwd } # Exit if any command fails # Note: pipefail is necessary for running build commands through # a pipe (i.e. it changes the output of ``false | tee /dev/null ; echo $?``) set -e set -o pipefail if [ "$do_checkout" = "yes" ]; then export_sources fi ( Flavors="Release" if [ "$do_debug" = "yes" ]; then Flavors="Debug $Flavors" fi if [ "$do_asserts" = "yes" ]; then Flavors="$Flavors Release+Asserts" fi for Flavor in $Flavors ; do echo "" echo "" echo "********************************************************************************" echo " Release: $Release-$RC" echo " Build: $Flavor" echo " System Info: " echo " `uname -a`" echo "********************************************************************************" echo "" c_compiler="$CC" cxx_compiler="$CXX" llvmCore_phase1_objdir=$BuildDir/Phase1/$Flavor/llvmCore-$Release-$RC.obj llvmCore_phase1_destdir=$BuildDir/Phase1/$Flavor/llvmCore-$Release-$RC.install llvmCore_phase2_objdir=$BuildDir/Phase2/$Flavor/llvmCore-$Release-$RC.obj llvmCore_phase2_destdir=$BuildDir/Phase2/$Flavor/llvmCore-$Release-$RC.install llvmCore_phase3_objdir=$BuildDir/Phase3/$Flavor/llvmCore-$Release-$RC.obj llvmCore_phase3_destdir=$BuildDir/Phase3/$Flavor/llvmCore-$Release-$RC.install rm -rf $llvmCore_phase1_objdir rm -rf $llvmCore_phase1_destdir rm -rf $llvmCore_phase2_objdir rm -rf $llvmCore_phase2_destdir rm -rf $llvmCore_phase3_objdir rm -rf $llvmCore_phase3_destdir mkdir -p $llvmCore_phase1_objdir mkdir -p $llvmCore_phase1_destdir mkdir -p $llvmCore_phase2_objdir mkdir -p $llvmCore_phase2_destdir mkdir -p $llvmCore_phase3_objdir mkdir -p $llvmCore_phase3_destdir ############################################################################ # Phase 1: Build llvmCore and clang echo "# Phase 1: Building llvmCore" configure_llvmCore 1 $Flavor $llvmCore_phase1_objdir build_llvmCore 1 $Flavor \ $llvmCore_phase1_objdir $llvmCore_phase1_destdir clean_RPATH $llvmCore_phase1_destdir/usr/local ######################################################################## # Phase 2: Build llvmCore with newly built clang from phase 1. c_compiler=$llvmCore_phase1_destdir/usr/local/bin/clang cxx_compiler=$llvmCore_phase1_destdir/usr/local/bin/clang++ echo "# Phase 2: Building llvmCore" configure_llvmCore 2 $Flavor $llvmCore_phase2_objdir build_llvmCore 2 $Flavor \ $llvmCore_phase2_objdir $llvmCore_phase2_destdir clean_RPATH $llvmCore_phase2_destdir/usr/local ######################################################################## # Phase 3: Build llvmCore with newly built clang from phase 2. c_compiler=$llvmCore_phase2_destdir/usr/local/bin/clang cxx_compiler=$llvmCore_phase2_destdir/usr/local/bin/clang++ echo "# Phase 3: Building llvmCore" configure_llvmCore 3 $Flavor $llvmCore_phase3_objdir build_llvmCore 3 $Flavor \ $llvmCore_phase3_objdir $llvmCore_phase3_destdir clean_RPATH $llvmCore_phase3_destdir/usr/local ######################################################################## # Testing: Test phase 3 echo "# Testing - built with clang" test_llvmCore 3 $Flavor $llvmCore_phase3_objdir ######################################################################## # Compare .o files between Phase2 and Phase3 and report which ones # differ. if [ "$do_compare" = "yes" ]; then echo echo "# Comparing Phase 2 and Phase 3 files" for p2 in `find $llvmCore_phase2_objdir -name '*.o'` ; do p3=`echo $p2 | sed -e 's,Phase2,Phase3,'` # Substitute 'Phase2' for 'Phase3' in the Phase 2 object file in # case there are build paths in the debug info. On some systems, # sed adds a newline to the output, so pass $p3 through sed too. if ! cmp -s <(sed -e 's,Phase2,Phase3,g' $p2) <(sed -e '' $p3) \ 16 16 ; then echo "file `basename $p2` differs between phase 2 and phase 3" fi done fi done if [ $do_openmp = "yes" ]; then build_OpenMP fi ) 2>&1 | tee $LogDir/testing.$Release-$RC.log package_release set +e # Woo hoo! echo "### Testing Finished ###" if [ "$use_gzip" = "yes" ]; then echo "### Package: $Package.tar.gz" else echo "### Package: $Package.tar.xz" fi echo "### Logs: $LogDir" echo "### Errors:" if [ -s "$LogDir/deferred_errors.log" ]; then cat "$LogDir/deferred_errors.log" exit 1 else echo "None." fi exit 0
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/release/merge.sh
#!/bin/sh #===-- merge.sh - Test the LLVM release candidates -------------------------===# # # The LLVM Compiler Infrastructure # # This file is distributed under the University of Illinois Open Source # License. # #===------------------------------------------------------------------------===# # # Merge a revision into a project. # #===------------------------------------------------------------------------===# set -e rev="" proj="" function usage() { echo "usage: `basename $0` [OPTIONS]" echo " -proj PROJECT The project to merge the result into" echo " -rev NUM The revision to merge into the project" } while [ $# -gt 0 ]; do case $1 in -rev | --rev | -r ) shift rev=$1 ;; -proj | --proj | -project | --project | -p ) shift proj=$1 ;; -h | -help | --help ) usage ;; * ) echo "unknown option: $1" echo "" usage exit 1 ;; esac shift done if [ "x$rev" = "x" -o "x$proj" = "x" ]; then echo "error: need to specify project and revision" echo usage exit 1 fi if ! svn ls http://llvm.org/svn/llvm-project/$proj/trunk > /dev/null 2>&1 ; then echo "error: invalid project: $proj" exit 1 fi tempfile=`mktemp /tmp/merge.XXXXXX` || exit 1 echo "Merging r$rev:" > $tempfile svn log -c $rev http://llvm.org/svn/llvm-project/$proj/trunk >> $tempfile 2>&1 cd $proj.src echo "# Updating tree" svn up echo "# Merging r$rev into $proj locally" svn merge -c $rev https://llvm.org/svn/llvm-project/$proj/trunk . || exit 1 echo echo "# To commit the merge, run the following in $proj.src/:" echo svn commit -F $tempfile exit 0
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/release/export.sh
#!/bin/sh #===-- tag.sh - Tag the LLVM release candidates ----------------------------===# # # The LLVM Compiler Infrastructure # # This file is distributed under the University of Illinois Open Source # License. # #===------------------------------------------------------------------------===# # # Create branches and release candidates for the LLVM release. # #===------------------------------------------------------------------------===# set -e projects="llvm cfe test-suite compiler-rt libcxx libcxxabi clang-tools-extra polly lldb lld openmp libunwind" base_url="https://llvm.org/svn/llvm-project" release="" rc="" function usage() { echo "Export the SVN sources and build tarballs from them" echo "usage: `basename $0`" echo " " echo " -release <num> The version number of the release" echo " -rc <num> The release candidate number" echo " -final The final tag" } function export_sources() { release_no_dot=`echo $release | sed -e 's,\.,,g'` tag_dir="tags/RELEASE_$release_no_dot/$rc" if [ "$rc" = "final" ]; then rc="" fi for proj in $projects; do echo "Exporting $proj ..." svn export \ $base_url/$proj/$tag_dir \ $proj-$release$rc.src echo "Creating tarball ..." tar cfJ $proj-$release$rc.src.tar.xz $proj-$release$rc.src done } while [ $# -gt 0 ]; do case $1 in -release | --release ) shift release=$1 ;; -rc | --rc ) shift rc="rc$1" ;; -final | --final ) rc="final" ;; -h | -help | --help ) usage exit 0 ;; * ) echo "unknown option: $1" usage exit 1 ;; esac shift done if [ "x$release" = "x" ]; then echo "error: need to specify a release version" exit 1 fi # Make sure umask is not overly restrictive. umask 0022 export_sources exit 0
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/release/tag.sh
#!/bin/sh #===-- tag.sh - Tag the LLVM release candidates ----------------------------===# # # The LLVM Compiler Infrastructure # # This file is distributed under the University of Illinois Open Source # License. # #===------------------------------------------------------------------------===# # # Create branches and release candidates for the LLVM release. # #===------------------------------------------------------------------------===# set -e release="" rc="" rebranch="no" projects="llvm cfe test-suite compiler-rt libcxx libcxxabi clang-tools-extra polly lldb lld openmp libunwind" dryrun="" revision="HEAD" base_url="https://llvm.org/svn/llvm-project" function usage() { echo "usage: `basename $0` -release <num> [-rebranch] [-revision <num>] [-dry-run]" echo "usage: `basename $0` -release <num> -rc <num> [-dry-run]" echo " " echo " -release <num> The version number of the release" echo " -rc <num> The release candidate number" echo " -rebranch Remove existing branch, if present, before branching" echo " -final Tag final release candidate" echo " -revision <num> Revision to branch off (default: HEAD)" echo " -dry-run Make no changes to the repository, just print the commands" } function tag_version() { set -x for proj in $projects; do if svn ls $base_url/$proj/branches/release_$branch_release > /dev/null 2>&1 ; then if [ $rebranch = "no" ]; then continue fi ${dryrun} svn remove -m "Removing old release_$branch_release branch for rebranching." \ $base_url/$proj/branches/release_$branch_release fi ${dryrun} svn copy -m "Creating release_$branch_release branch off revision ${revision}" \ -r ${revision} \ $base_url/$proj/trunk \ $base_url/$proj/branches/release_$branch_release done set +x } function tag_release_candidate() { set -x for proj in $projects ; do if ! svn ls $base_url/$proj/tags/RELEASE_$tag_release > /dev/null 2>&1 ; then ${dryrun} svn mkdir -m "Creating release directory for release_$tag_release." $base_url/$proj/tags/RELEASE_$tag_release fi if ! svn ls $base_url/$proj/tags/RELEASE_$tag_release/$rc > /dev/null 2>&1 ; then ${dryrun} svn copy -m "Creating release candidate $rc from release_$tag_release branch" \ $base_url/$proj/branches/release_$branch_release \ $base_url/$proj/tags/RELEASE_$tag_release/$rc fi done set +x } while [ $# -gt 0 ]; do case $1 in -release | --release ) shift release=$1 ;; -rc | --rc ) shift rc="rc$1" ;; -rebranch | --rebranch ) rebranch="yes" ;; -final | --final ) rc="final" ;; -revision | --revision ) shift revision="$1" ;; -dry-run | --dry-run ) dryrun="echo" ;; -h | --help | -help ) usage exit 0 ;; * ) echo "unknown option: $1" usage exit 1 ;; esac shift done if [ "x$release" = "x" ]; then echo "error: need to specify a release version" echo usage exit 1 fi branch_release=`echo $release | sed -e 's,\([0-9]*\.[0-9]*\).*,\1,' | sed -e 's,\.,,g'` tag_release=`echo $release | sed -e 's,\.,,g'` if [ "x$rc" = "x" ]; then tag_version else if [ "$revision" != "HEAD" ]; then echo "error: cannot use -revision with -rc" echo usage exit 1 fi tag_release_candidate fi exit 0
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/release/findRegressions-simple.py
#!/usr/bin/env python import re, string, sys, os, time, math DEBUG = 0 (tp, exp) = ('compile', 'exec') def parse(file): f = open(file, 'r') d = f.read() # Cleanup weird stuff d = re.sub(r',\d+:\d', '', d) r = re.findall(r'TEST-(PASS|FAIL|RESULT.*?):\s+(.*?)\s+(.*?)\r*\n', d) test = {} fname = '' for t in r: if DEBUG: print t if t[0] == 'PASS' or t[0] == 'FAIL' : tmp = t[2].split('llvm-test/') if DEBUG: print tmp if len(tmp) == 2: fname = tmp[1].strip('\r\n') else: fname = tmp[0].strip('\r\n') if not test.has_key(fname): test[fname] = {} test[fname][t[1] + ' state'] = t[0] test[fname][t[1] + ' time'] = float('nan') else : try: n = t[0].split('RESULT-')[1] if DEBUG: print "n == ", n; if n == 'compile-success': test[fname]['compile time'] = float(t[2].split('program')[1].strip('\r\n')) elif n == 'exec-success': test[fname]['exec time'] = float(t[2].split('program')[1].strip('\r\n')) if DEBUG: print test[fname][string.replace(n, '-success', '')] else : # print "ERROR!" sys.exit(1) except: continue return test # Diff results and look for regressions. def diffResults(d_old, d_new): regressions = {} passes = {} removed = '' for x in ['compile state', 'compile time', 'exec state', 'exec time']: regressions[x] = '' passes[x] = '' for t in sorted(d_old.keys()) : if d_new.has_key(t): # Check if the test passed or failed. for x in ['compile state', 'compile time', 'exec state', 'exec time']: if not d_old[t].has_key(x) and not d_new[t].has_key(x): continue if d_old[t].has_key(x): if d_new[t].has_key(x): if d_old[t][x] == 'PASS': if d_new[t][x] != 'PASS': regressions[x] += t + "\n" else: if d_new[t][x] == 'PASS': passes[x] += t + "\n" else : regressions[x] += t + "\n" if x == 'compile state' or x == 'exec state': continue # For execution time, if there is no result it's a fail. if not d_old[t].has_key(x) and not d_new[t].has_key(x): continue elif not d_new[t].has_key(x): regressions[x] += t + "\n" elif not d_old[t].has_key(x): passes[x] += t + "\n" if math.isnan(d_old[t][x]) and math.isnan(d_new[t][x]): continue elif math.isnan(d_old[t][x]) and not math.isnan(d_new[t][x]): passes[x] += t + "\n" elif not math.isnan(d_old[t][x]) and math.isnan(d_new[t][x]): regressions[x] += t + ": NaN%\n" if d_new[t][x] > d_old[t][x] and d_old[t][x] > 0.0 and \ (d_new[t][x] - d_old[t][x]) / d_old[t][x] > .05: regressions[x] += t + ": " + "{0:.1f}".format(100 * (d_new[t][x] - d_old[t][x]) / d_old[t][x]) + "%\n" else : removed += t + "\n" if len(regressions['compile state']) != 0: print 'REGRESSION: Compilation Failed' print regressions['compile state'] if len(regressions['exec state']) != 0: print 'REGRESSION: Execution Failed' print regressions['exec state'] if len(regressions['compile time']) != 0: print 'REGRESSION: Compilation Time' print regressions['compile time'] if len(regressions['exec time']) != 0: print 'REGRESSION: Execution Time' print regressions['exec time'] if len(passes['compile state']) != 0: print 'NEW PASSES: Compilation' print passes['compile state'] if len(passes['exec state']) != 0: print 'NEW PASSES: Execution' print passes['exec state'] if len(removed) != 0: print 'REMOVED TESTS' print removed # Main if len(sys.argv) < 3 : print 'Usage:', sys.argv[0], '<old log> <new log>' sys.exit(-1) d_old = parse(sys.argv[1]) d_new = parse(sys.argv[2]) diffResults(d_old, d_new)
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/PerfectShuffle/PerfectShuffle.cpp
//===-- PerfectShuffle.cpp - Perfect Shuffle Generator --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file computes an optimal sequence of instructions for doing all shuffles // of two 4-element vectors. With a release build and when configured to emit // an altivec instruction table, this takes about 30s to run on a 2.7Ghz // PowerPC G5. // //===----------------------------------------------------------------------===// #include <cassert> #include <cstdlib> #include <iomanip> #include <iostream> #include <vector> struct Operator; // Masks are 4-nibble hex numbers. Values 0-7 in any nibble means that it takes // an element from that value of the input vectors. A value of 8 means the // entry is undefined. // Mask manipulation functions. static inline unsigned short MakeMask(unsigned V0, unsigned V1, unsigned V2, unsigned V3) { return (V0 << (3*4)) | (V1 << (2*4)) | (V2 << (1*4)) | (V3 << (0*4)); } /// getMaskElt - Return element N of the specified mask. static unsigned getMaskElt(unsigned Mask, unsigned Elt) { return (Mask >> ((3-Elt)*4)) & 0xF; } static unsigned setMaskElt(unsigned Mask, unsigned Elt, unsigned NewVal) { unsigned FieldShift = ((3-Elt)*4); return (Mask & ~(0xF << FieldShift)) | (NewVal << FieldShift); } // Reject elements where the values are 9-15. static bool isValidMask(unsigned short Mask) { unsigned short UndefBits = Mask & 0x8888; return (Mask & ((UndefBits >> 1)|(UndefBits>>2)|(UndefBits>>3))) == 0; } /// hasUndefElements - Return true if any of the elements in the mask are undefs /// static bool hasUndefElements(unsigned short Mask) { return (Mask & 0x8888) != 0; } /// isOnlyLHSMask - Return true if this mask only refers to its LHS, not /// including undef values.. static bool isOnlyLHSMask(unsigned short Mask) { return (Mask & 0x4444) == 0; } /// getLHSOnlyMask - Given a mask that refers to its LHS and RHS, modify it to /// refer to the LHS only (for when one argument value is passed into the same /// function twice). #if 0 static unsigned short getLHSOnlyMask(unsigned short Mask) { return Mask & 0xBBBB; // Keep only LHS and Undefs. } #endif /// getCompressedMask - Turn a 16-bit uncompressed mask (where each elt uses 4 /// bits) into a compressed 13-bit mask, where each elt is multiplied by 9. static unsigned getCompressedMask(unsigned short Mask) { return getMaskElt(Mask, 0)*9*9*9 + getMaskElt(Mask, 1)*9*9 + getMaskElt(Mask, 2)*9 + getMaskElt(Mask, 3); } static void PrintMask(unsigned i, std::ostream &OS) { OS << "<" << (char)(getMaskElt(i, 0) == 8 ? 'u' : ('0'+getMaskElt(i, 0))) << "," << (char)(getMaskElt(i, 1) == 8 ? 'u' : ('0'+getMaskElt(i, 1))) << "," << (char)(getMaskElt(i, 2) == 8 ? 'u' : ('0'+getMaskElt(i, 2))) << "," << (char)(getMaskElt(i, 3) == 8 ? 'u' : ('0'+getMaskElt(i, 3))) << ">"; } /// ShuffleVal - This represents a shufflevector operation. struct ShuffleVal { unsigned Cost; // Number of instrs used to generate this value. Operator *Op; // The Operation used to generate this value. unsigned short Arg0, Arg1; // Input operands for this value. ShuffleVal() : Cost(1000000) {} }; /// ShufTab - This is the actual shuffle table that we are trying to generate. /// static ShuffleVal ShufTab[65536]; /// TheOperators - All of the operators that this target supports. static std::vector<Operator*> TheOperators; /// Operator - This is a vector operation that is available for use. struct Operator { unsigned short ShuffleMask; unsigned short OpNum; const char *Name; unsigned Cost; Operator(unsigned short shufflemask, const char *name, unsigned opnum, unsigned cost = 1) : ShuffleMask(shufflemask), OpNum(opnum), Name(name), Cost(cost) { TheOperators.push_back(this); } ~Operator() { assert(TheOperators.back() == this); TheOperators.pop_back(); } bool isOnlyLHSOperator() const { return isOnlyLHSMask(ShuffleMask); } const char *getName() const { return Name; } unsigned getCost() const { return Cost; } unsigned short getTransformedMask(unsigned short LHSMask, unsigned RHSMask) { // Extract the elements from LHSMask and RHSMask, as appropriate. unsigned Result = 0; for (unsigned i = 0; i != 4; ++i) { unsigned SrcElt = (ShuffleMask >> (4*i)) & 0xF; unsigned ResElt; if (SrcElt < 4) ResElt = getMaskElt(LHSMask, SrcElt); else if (SrcElt < 8) ResElt = getMaskElt(RHSMask, SrcElt-4); else { assert(SrcElt == 8 && "Bad src elt!"); ResElt = 8; } Result |= ResElt << (4*i); } return Result; } }; static const char *getZeroCostOpName(unsigned short Op) { if (ShufTab[Op].Arg0 == 0x0123) return "LHS"; else if (ShufTab[Op].Arg0 == 0x4567) return "RHS"; else { assert(0 && "bad zero cost operation"); abort(); } } static void PrintOperation(unsigned ValNo, unsigned short Vals[]) { unsigned short ThisOp = Vals[ValNo]; std::cerr << "t" << ValNo; PrintMask(ThisOp, std::cerr); std::cerr << " = " << ShufTab[ThisOp].Op->getName() << "("; if (ShufTab[ShufTab[ThisOp].Arg0].Cost == 0) { std::cerr << getZeroCostOpName(ShufTab[ThisOp].Arg0); PrintMask(ShufTab[ThisOp].Arg0, std::cerr); } else { // Figure out what tmp # it is. for (unsigned i = 0; ; ++i) if (Vals[i] == ShufTab[ThisOp].Arg0) { std::cerr << "t" << i; break; } } if (!ShufTab[Vals[ValNo]].Op->isOnlyLHSOperator()) { std::cerr << ", "; if (ShufTab[ShufTab[ThisOp].Arg1].Cost == 0) { std::cerr << getZeroCostOpName(ShufTab[ThisOp].Arg1); PrintMask(ShufTab[ThisOp].Arg1, std::cerr); } else { // Figure out what tmp # it is. for (unsigned i = 0; ; ++i) if (Vals[i] == ShufTab[ThisOp].Arg1) { std::cerr << "t" << i; break; } } } std::cerr << ") "; } static unsigned getNumEntered() { unsigned Count = 0; for (unsigned i = 0; i != 65536; ++i) Count += ShufTab[i].Cost < 100; return Count; } static void EvaluateOps(unsigned short Elt, unsigned short Vals[], unsigned &NumVals) { if (ShufTab[Elt].Cost == 0) return; // If this value has already been evaluated, it is free. FIXME: match undefs. for (unsigned i = 0, e = NumVals; i != e; ++i) if (Vals[i] == Elt) return; // Otherwise, get the operands of the value, then add it. unsigned Arg0 = ShufTab[Elt].Arg0, Arg1 = ShufTab[Elt].Arg1; if (ShufTab[Arg0].Cost) EvaluateOps(Arg0, Vals, NumVals); if (Arg0 != Arg1 && ShufTab[Arg1].Cost) EvaluateOps(Arg1, Vals, NumVals); Vals[NumVals++] = Elt; } int main() { // Seed the table with accesses to the LHS and RHS. ShufTab[0x0123].Cost = 0; ShufTab[0x0123].Op = nullptr; ShufTab[0x0123].Arg0 = 0x0123; ShufTab[0x4567].Cost = 0; ShufTab[0x4567].Op = nullptr; ShufTab[0x4567].Arg0 = 0x4567; // Seed the first-level of shuffles, shuffles whose inputs are the input to // the vectorshuffle operation. bool MadeChange = true; unsigned OpCount = 0; while (MadeChange) { MadeChange = false; ++OpCount; std::cerr << "Starting iteration #" << OpCount << " with " << getNumEntered() << " entries established.\n"; // Scan the table for two reasons: First, compute the maximum cost of any // operation left in the table. Second, make sure that values with undefs // have the cheapest alternative that they match. unsigned MaxCost = ShufTab[0].Cost; for (unsigned i = 1; i != 0x8889; ++i) { if (!isValidMask(i)) continue; if (ShufTab[i].Cost > MaxCost) MaxCost = ShufTab[i].Cost; // If this value has an undef, make it be computed the cheapest possible // way of any of the things that it matches. if (hasUndefElements(i)) { // This code is a little bit tricky, so here's the idea: consider some // permutation, like 7u4u. To compute the lowest cost for 7u4u, we // need to take the minimum cost of all of 7[0-8]4[0-8], 81 entries. If // there are 3 undefs, the number rises to 729 entries we have to scan, // and for the 4 undef case, we have to scan the whole table. // // Instead of doing this huge amount of scanning, we process the table // entries *in order*, and use the fact that 'u' is 8, larger than any // valid index. Given an entry like 7u4u then, we only need to scan // 7[0-7]4u - 8 entries. We can get away with this, because we already // know that each of 704u, 714u, 724u, etc contain the minimum value of // all of the 704[0-8], 714[0-8] and 724[0-8] entries respectively. unsigned UndefIdx; if (i & 0x8000) UndefIdx = 0; else if (i & 0x0800) UndefIdx = 1; else if (i & 0x0080) UndefIdx = 2; else if (i & 0x0008) UndefIdx = 3; else abort(); unsigned MinVal = i; unsigned MinCost = ShufTab[i].Cost; // Scan the 8 entries. for (unsigned j = 0; j != 8; ++j) { unsigned NewElt = setMaskElt(i, UndefIdx, j); if (ShufTab[NewElt].Cost < MinCost) { MinCost = ShufTab[NewElt].Cost; MinVal = NewElt; } } // If we found something cheaper than what was here before, use it. if (i != MinVal) { MadeChange = true; ShufTab[i] = ShufTab[MinVal]; } } } for (unsigned LHS = 0; LHS != 0x8889; ++LHS) { if (!isValidMask(LHS)) continue; if (ShufTab[LHS].Cost > 1000) continue; // If nothing involving this operand could possibly be cheaper than what // we already have, don't consider it. if (ShufTab[LHS].Cost + 1 >= MaxCost) continue; for (unsigned opnum = 0, e = TheOperators.size(); opnum != e; ++opnum) { Operator *Op = TheOperators[opnum]; // Evaluate op(LHS,LHS) unsigned ResultMask = Op->getTransformedMask(LHS, LHS); unsigned Cost = ShufTab[LHS].Cost + Op->getCost(); if (Cost < ShufTab[ResultMask].Cost) { ShufTab[ResultMask].Cost = Cost; ShufTab[ResultMask].Op = Op; ShufTab[ResultMask].Arg0 = LHS; ShufTab[ResultMask].Arg1 = LHS; MadeChange = true; } // If this is a two input instruction, include the op(x,y) cases. If // this is a one input instruction, skip this. if (Op->isOnlyLHSOperator()) continue; for (unsigned RHS = 0; RHS != 0x8889; ++RHS) { if (!isValidMask(RHS)) continue; if (ShufTab[RHS].Cost > 1000) continue; // If nothing involving this operand could possibly be cheaper than // what we already have, don't consider it. if (ShufTab[RHS].Cost + 1 >= MaxCost) continue; // Evaluate op(LHS,RHS) unsigned ResultMask = Op->getTransformedMask(LHS, RHS); if (ShufTab[ResultMask].Cost <= OpCount || ShufTab[ResultMask].Cost <= ShufTab[LHS].Cost || ShufTab[ResultMask].Cost <= ShufTab[RHS].Cost) continue; // Figure out the cost to evaluate this, knowing that CSE's only need // to be evaluated once. unsigned short Vals[30]; unsigned NumVals = 0; EvaluateOps(LHS, Vals, NumVals); EvaluateOps(RHS, Vals, NumVals); unsigned Cost = NumVals + Op->getCost(); if (Cost < ShufTab[ResultMask].Cost) { ShufTab[ResultMask].Cost = Cost; ShufTab[ResultMask].Op = Op; ShufTab[ResultMask].Arg0 = LHS; ShufTab[ResultMask].Arg1 = RHS; MadeChange = true; } } } } } std::cerr << "Finished Table has " << getNumEntered() << " entries established.\n"; unsigned CostArray[10] = { 0 }; // Compute a cost histogram. for (unsigned i = 0; i != 65536; ++i) { if (!isValidMask(i)) continue; if (ShufTab[i].Cost > 9) ++CostArray[9]; else ++CostArray[ShufTab[i].Cost]; } for (unsigned i = 0; i != 9; ++i) if (CostArray[i]) std::cout << "// " << CostArray[i] << " entries have cost " << i << "\n"; if (CostArray[9]) std::cout << "// " << CostArray[9] << " entries have higher cost!\n"; // Build up the table to emit. std::cout << "\n// This table is 6561*4 = 26244 bytes in size.\n"; std::cout << "static const unsigned PerfectShuffleTable[6561+1] = {\n"; for (unsigned i = 0; i != 0x8889; ++i) { if (!isValidMask(i)) continue; // CostSat - The cost of this operation saturated to two bits. unsigned CostSat = ShufTab[i].Cost; if (CostSat > 4) CostSat = 4; if (CostSat == 0) CostSat = 1; --CostSat; // Cost is now between 0-3. unsigned OpNum = ShufTab[i].Op ? ShufTab[i].Op->OpNum : 0; assert(OpNum < 16 && "Too few bits to encode operation!"); unsigned LHS = getCompressedMask(ShufTab[i].Arg0); unsigned RHS = getCompressedMask(ShufTab[i].Arg1); // Encode this as 2 bits of saturated cost, 4 bits of opcodes, 13 bits of // LHS, and 13 bits of RHS = 32 bits. unsigned Val = (CostSat << 30) | (OpNum << 26) | (LHS << 13) | RHS; std::cout << " " << std::setw(10) << Val << "U, // "; PrintMask(i, std::cout); std::cout << ": Cost " << ShufTab[i].Cost; std::cout << " " << (ShufTab[i].Op ? ShufTab[i].Op->getName() : "copy"); std::cout << " "; if (ShufTab[ShufTab[i].Arg0].Cost == 0) { std::cout << getZeroCostOpName(ShufTab[i].Arg0); } else { PrintMask(ShufTab[i].Arg0, std::cout); } if (ShufTab[i].Op && !ShufTab[i].Op->isOnlyLHSOperator()) { std::cout << ", "; if (ShufTab[ShufTab[i].Arg1].Cost == 0) { std::cout << getZeroCostOpName(ShufTab[i].Arg1); } else { PrintMask(ShufTab[i].Arg1, std::cout); } } std::cout << "\n"; } std::cout << " 0\n};\n"; if (0) { // Print out the table. for (unsigned i = 0; i != 0x8889; ++i) { if (!isValidMask(i)) continue; if (ShufTab[i].Cost < 1000) { PrintMask(i, std::cerr); std::cerr << " - Cost " << ShufTab[i].Cost << " - "; unsigned short Vals[30]; unsigned NumVals = 0; EvaluateOps(i, Vals, NumVals); for (unsigned j = 0, e = NumVals; j != e; ++j) PrintOperation(j, Vals); std::cerr << "\n"; } } } } #ifdef GENERATE_ALTIVEC ///===---------------------------------------------------------------------===// /// The altivec instruction definitions. This is the altivec-specific part of /// this file. ///===---------------------------------------------------------------------===// // Note that the opcode numbers here must match those in the PPC backend. enum { OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> OP_VMRGHW, OP_VMRGLW, OP_VSPLTISW0, OP_VSPLTISW1, OP_VSPLTISW2, OP_VSPLTISW3, OP_VSLDOI4, OP_VSLDOI8, OP_VSLDOI12 }; struct vmrghw : public Operator { vmrghw() : Operator(0x0415, "vmrghw", OP_VMRGHW) {} } the_vmrghw; struct vmrglw : public Operator { vmrglw() : Operator(0x2637, "vmrglw", OP_VMRGLW) {} } the_vmrglw; template<unsigned Elt> struct vspltisw : public Operator { vspltisw(const char *N, unsigned Opc) : Operator(MakeMask(Elt, Elt, Elt, Elt), N, Opc) {} }; vspltisw<0> the_vspltisw0("vspltisw0", OP_VSPLTISW0); vspltisw<1> the_vspltisw1("vspltisw1", OP_VSPLTISW1); vspltisw<2> the_vspltisw2("vspltisw2", OP_VSPLTISW2); vspltisw<3> the_vspltisw3("vspltisw3", OP_VSPLTISW3); template<unsigned N> struct vsldoi : public Operator { vsldoi(const char *Name, unsigned Opc) : Operator(MakeMask(N&7, (N+1)&7, (N+2)&7, (N+3)&7), Name, Opc) { } }; vsldoi<1> the_vsldoi1("vsldoi4" , OP_VSLDOI4); vsldoi<2> the_vsldoi2("vsldoi8" , OP_VSLDOI8); vsldoi<3> the_vsldoi3("vsldoi12", OP_VSLDOI12); #endif #define GENERATE_NEON #ifdef GENERATE_NEON enum { OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> OP_VREV, OP_VDUP0, OP_VDUP1, OP_VDUP2, OP_VDUP3, OP_VEXT1, OP_VEXT2, OP_VEXT3, OP_VUZPL, // VUZP, left result OP_VUZPR, // VUZP, right result OP_VZIPL, // VZIP, left result OP_VZIPR, // VZIP, right result OP_VTRNL, // VTRN, left result OP_VTRNR // VTRN, right result }; struct vrev : public Operator { vrev() : Operator(0x1032, "vrev", OP_VREV) {} } the_vrev; template<unsigned Elt> struct vdup : public Operator { vdup(const char *N, unsigned Opc) : Operator(MakeMask(Elt, Elt, Elt, Elt), N, Opc) {} }; vdup<0> the_vdup0("vdup0", OP_VDUP0); vdup<1> the_vdup1("vdup1", OP_VDUP1); vdup<2> the_vdup2("vdup2", OP_VDUP2); vdup<3> the_vdup3("vdup3", OP_VDUP3); template<unsigned N> struct vext : public Operator { vext(const char *Name, unsigned Opc) : Operator(MakeMask(N&7, (N+1)&7, (N+2)&7, (N+3)&7), Name, Opc) { } }; vext<1> the_vext1("vext1", OP_VEXT1); vext<2> the_vext2("vext2", OP_VEXT2); vext<3> the_vext3("vext3", OP_VEXT3); struct vuzpl : public Operator { vuzpl() : Operator(0x0246, "vuzpl", OP_VUZPL, 2) {} } the_vuzpl; struct vuzpr : public Operator { vuzpr() : Operator(0x1357, "vuzpr", OP_VUZPR, 2) {} } the_vuzpr; struct vzipl : public Operator { vzipl() : Operator(0x0415, "vzipl", OP_VZIPL, 2) {} } the_vzipl; struct vzipr : public Operator { vzipr() : Operator(0x2637, "vzipr", OP_VZIPR, 2) {} } the_vzipr; struct vtrnl : public Operator { vtrnl() : Operator(0x0426, "vtrnl", OP_VTRNL, 2) {} } the_vtrnl; struct vtrnr : public Operator { vtrnr() : Operator(0x1537, "vtrnr", OP_VTRNR, 2) {} } the_vtrnr; #endif
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/PerfectShuffle/CMakeLists.txt
add_llvm_utility(llvm-PerfectShuffle PerfectShuffle.cpp )
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/llvm-lit/CMakeLists.txt
if (WIN32 AND NOT CYGWIN) # llvm-lit needs suffix.py for multiprocess to find a main module. set(suffix .py) endif () set(llvm_lit_path ${LLVM_RUNTIME_OUTPUT_INTDIR}/llvm-lit${suffix}) if(NOT "${CMAKE_CFG_INTDIR}" STREQUAL ".") foreach(BUILD_MODE ${CMAKE_CONFIGURATION_TYPES}) string(REPLACE ${CMAKE_CFG_INTDIR} ${BUILD_MODE} bi ${llvm_lit_path}) configure_file( llvm-lit.in ${bi} ) endforeach() else() set(BUILD_MODE .) configure_file( llvm-lit.in ${llvm_lit_path} ) endif()
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/llvm-lit/llvm-lit.in
#!/usr/bin/env python import os import sys # Variables configured at build time. llvm_source_root = "@LLVM_SOURCE_DIR@" llvm_obj_root = "@LLVM_BINARY_DIR@" # Make sure we can find the lit package. sys.path.insert(0, os.path.join(llvm_source_root, 'utils', 'lit')) # Set up some builtin parameters, so that by default the LLVM test suite # configuration file knows how to find the object tree. builtin_parameters = { 'build_mode' : "@BUILD_MODE@", 'llvm_site_config' : os.path.join(llvm_obj_root, 'test', 'lit.site.cfg'), 'llvm_unit_site_config' : os.path.join(llvm_obj_root, 'test', 'Unit', 'lit.site.cfg') } clang_obj_root = os.path.join(llvm_obj_root, 'tools', 'clang') if os.path.exists(clang_obj_root): builtin_parameters['clang_site_config'] = \ os.path.join(clang_obj_root, 'test', 'lit.site.cfg') clang_tools_extra_obj_root = os.path.join(clang_obj_root, 'tools', 'extra') if os.path.exists(clang_tools_extra_obj_root): builtin_parameters['clang_tools_extra_site_config'] = \ os.path.join(clang_tools_extra_obj_root, 'test', 'lit.site.cfg') clang_taef_root = os.path.join(clang_obj_root, 'test', 'taef') if os.path.exists(clang_taef_root): builtin_parameters['clang_taef_site_config'] = \ os.path.join(clang_taef_root, 'lit.site.cfg') clang_taef_exec_root = os.path.join(clang_obj_root, 'test', 'taef_exec') if os.path.exists(clang_taef_root): builtin_parameters['clang_taef_exec_site_config'] = \ os.path.join(clang_taef_exec_root, 'lit.site.cfg') lld_obj_root = os.path.join(llvm_obj_root, 'tools', 'lld') if os.path.exists(lld_obj_root): builtin_parameters['lld_site_config'] = \ os.path.join(lld_obj_root, 'test', 'lit.site.cfg') compilerrt_obj_root = os.path.join(llvm_obj_root, 'projects', 'compiler-rt') if os.path.exists(compilerrt_obj_root): builtin_parameters['compilerrt_site_basedir'] = \ os.path.join(compilerrt_obj_root, 'test') if __name__=='__main__': import lit lit.main(builtin_parameters)
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/unittest/CMakeLists.txt
######################################################################## # Experimental CMake build script for Google Test. # # Consider this a prototype. It will change drastically. For now, # this is only for people on the cutting edge. # # To run the tests for Google Test 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'. ######################################################################## # # Project-wide settings # Where gtest's .h files can be found. include_directories( googletest/include googletest googlemock/include googlemock ) if(WIN32) add_definitions(-DGTEST_OS_WINDOWS=1) endif() if(SUPPORTS_VARIADIC_MACROS_FLAG) add_definitions("-Wno-variadic-macros") endif() if(SUPPORTS_GNU_ZERO_VARIADIC_MACRO_ARGUMENTS_FLAG) add_definitions("-Wno-gnu-zero-variadic-macro-arguments") endif() if(CXX_SUPPORTS_COVERED_SWITCH_DEFAULT_FLAG) add_definitions("-Wno-covered-switch-default") endif() set(LLVM_REQUIRES_RTTI 1) add_definitions( -DGTEST_HAS_RTTI=0 ) if (NOT LLVM_ENABLE_THREADS) add_definitions( -DGTEST_HAS_PTHREAD=0 ) endif() find_library(PTHREAD_LIBRARY_PATH pthread) if (PTHREAD_LIBRARY_PATH) list(APPEND LIBS pthread) endif() add_llvm_library(gtest googletest/src/gtest-all.cc googlemock/src/gmock-all.cc LINK_LIBS ${LIBS} LINK_COMPONENTS Support # Depends on llvm::raw_ostream ) add_subdirectory(UnitTestMain)
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/unittest/LLVMBuild.txt
;===- ./utils/unittest/LLVMBuild.txt ---------------------------*- Conf -*--===; ; ; The LLVM Compiler Infrastructure ; ; This file is distributed under the University of Illinois Open Source ; License. See LICENSE.TXT for details. ; ;===------------------------------------------------------------------------===; ; ; This is an LLVMBuild description file for the components in this subdirectory. ; ; For more information on the LLVMBuild system, please see: ; ; http://llvm.org/docs/LLVMBuild.html ; ;===------------------------------------------------------------------------===; [component_0] type = Library name = gtest parent = Libraries required_libraries = Support installed = 0 [component_1] type = Library name = gtest_main parent = Libraries required_libraries = gtest installed = 0
0
repos/DirectXShaderCompiler/utils/unittest
repos/DirectXShaderCompiler/utils/unittest/UnitTestMain/TestMain.cpp
//===--- utils/unittest/UnitTestMain/TestMain.cpp - unittest driver -------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Support/CommandLine.h" #include "llvm/Support/Signals.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #if defined(_WIN32) # include <windows.h> # if defined(_MSC_VER) # include <crtdbg.h> # endif #endif const char *TestMainArgv0; int main(int argc, char **argv) { llvm::sys::PrintStackTraceOnErrorSignal(true /* Disable crash reporting */); // Initialize both gmock and gtest. testing::InitGoogleMock(&argc, argv); llvm::cl::ParseCommandLineOptions(argc, argv); // Make it easy for a test to re-execute itself by saving argv[0]. TestMainArgv0 = argv[0]; # if defined(_WIN32) // Disable all of the possible ways Windows conspires to make automated // testing impossible. ::SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX); # if defined(_MSC_VER) ::_set_error_mode(_OUT_TO_STDERR); _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG); _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG); _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR); _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG); _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR); # endif # endif return RUN_ALL_TESTS(); }
0
repos/DirectXShaderCompiler/utils/unittest
repos/DirectXShaderCompiler/utils/unittest/UnitTestMain/CMakeLists.txt
add_llvm_library(gtest_main TestMain.cpp LINK_LIBS gtest LINK_COMPONENTS Support # Depends on llvm::cl )
0
repos/DirectXShaderCompiler/utils/unittest
repos/DirectXShaderCompiler/utils/unittest/googletest/LICENSE.TXT
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
repos/DirectXShaderCompiler/utils/unittest/googletest/include
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest/gtest-typed-test.h
// 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. // // Author: [email protected] (Zhanyong Wan) #ifndef GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ #define GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ // This header implements typed tests and type-parameterized tests. // Typed (aka type-driven) tests repeat the same test for types in a // list. You must know which types you want to test with when writing // typed tests. Here's how you do it: #if 0 // First, define a fixture class template. It should be parameterized // by a type. Remember to derive it from testing::Test. template <typename T> class FooTest : public testing::Test { public: ... typedef std::list<T> List; static T shared_; T value_; }; // Next, associate a list of types with the test case, which will be // repeated for each type in the list. The typedef is necessary for // the macro to parse correctly. typedef testing::Types<char, int, unsigned int> MyTypes; TYPED_TEST_CASE(FooTest, MyTypes); // If the type list contains only one type, you can write that type // directly without Types<...>: // TYPED_TEST_CASE(FooTest, int); // Then, use TYPED_TEST() instead of TEST_F() to define as many typed // tests for this test case as you want. TYPED_TEST(FooTest, DoesBlah) { // Inside a test, refer to TypeParam to get the type parameter. // Since we are inside a derived class template, C++ requires use to // visit the members of FooTest via 'this'. TypeParam n = this->value_; // To visit static members of the fixture, add the TestFixture:: // prefix. n += TestFixture::shared_; // To refer to typedefs in the fixture, add the "typename // TestFixture::" prefix. typename TestFixture::List values; values.push_back(n); ... } TYPED_TEST(FooTest, HasPropertyA) { ... } #endif // 0 // Type-parameterized tests are abstract test patterns parameterized // by a type. Compared with typed tests, type-parameterized tests // allow you to define the test pattern without knowing what the type // parameters are. The defined pattern can be instantiated with // different types any number of times, in any number of translation // units. // // If you are designing an interface or concept, you can define a // suite of type-parameterized tests to verify properties that any // valid implementation of the interface/concept should have. Then, // each implementation can easily instantiate the test suite to verify // that it conforms to the requirements, without having to write // similar tests repeatedly. Here's an example: #if 0 // First, define a fixture class template. It should be parameterized // by a type. Remember to derive it from testing::Test. template <typename T> class FooTest : public testing::Test { ... }; // Next, declare that you will define a type-parameterized test case // (the _P suffix is for "parameterized" or "pattern", whichever you // prefer): TYPED_TEST_CASE_P(FooTest); // Then, use TYPED_TEST_P() to define as many type-parameterized tests // for this type-parameterized test case as you want. TYPED_TEST_P(FooTest, DoesBlah) { // Inside a test, refer to TypeParam to get the type parameter. TypeParam n = 0; ... } TYPED_TEST_P(FooTest, HasPropertyA) { ... } // Now the tricky part: you need to register all test patterns before // you can instantiate them. The first argument of the macro is the // test case name; the rest are the names of the tests in this test // case. REGISTER_TYPED_TEST_CASE_P(FooTest, DoesBlah, HasPropertyA); // Finally, you are free to instantiate the pattern with the types you // want. If you put the above code in a header file, you can #include // it in multiple C++ source files and instantiate it multiple times. // // To distinguish different instances of the pattern, the first // argument to the INSTANTIATE_* macro is a prefix that will be added // to the actual test case name. Remember to pick unique prefixes for // different instances. typedef testing::Types<char, int, unsigned int> MyTypes; INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, MyTypes); // If the type list contains only one type, you can write that type // directly without Types<...>: // INSTANTIATE_TYPED_TEST_CASE_P(My, FooTest, int); #endif // 0 #include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-type-util.h" // Implements typed tests. #if GTEST_HAS_TYPED_TEST // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Expands to the name of the typedef for the type parameters of the // given test case. # define GTEST_TYPE_PARAMS_(TestCaseName) gtest_type_params_##TestCaseName##_ // The 'Types' template argument below must have spaces around it // since some compilers may choke on '>>' when passing a template // instance (e.g. Types<int>) # define TYPED_TEST_CASE(CaseName, Types) \ typedef ::testing::internal::TypeList< Types >::type \ GTEST_TYPE_PARAMS_(CaseName) # define TYPED_TEST(CaseName, TestName) \ template <typename gtest_TypeParam_> \ class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \ : public CaseName<gtest_TypeParam_> { \ private: \ typedef CaseName<gtest_TypeParam_> TestFixture; \ typedef gtest_TypeParam_ TypeParam; \ virtual void TestBody(); \ }; \ bool gtest_##CaseName##_##TestName##_registered_ GTEST_ATTRIBUTE_UNUSED_ = \ ::testing::internal::TypeParameterizedTest< \ CaseName, \ ::testing::internal::TemplateSel< \ GTEST_TEST_CLASS_NAME_(CaseName, TestName)>, \ GTEST_TYPE_PARAMS_(CaseName)>::Register(\ "", ::testing::internal::CodeLocation(__FILE__, __LINE__), \ #CaseName, #TestName, 0); \ template <typename gtest_TypeParam_> \ void GTEST_TEST_CLASS_NAME_(CaseName, TestName)<gtest_TypeParam_>::TestBody() #endif // GTEST_HAS_TYPED_TEST // Implements type-parameterized tests. #if GTEST_HAS_TYPED_TEST_P // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Expands to the namespace name that the type-parameterized tests for // the given type-parameterized test case are defined in. The exact // name of the namespace is subject to change without notice. # define GTEST_CASE_NAMESPACE_(TestCaseName) \ gtest_case_##TestCaseName##_ // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Expands to the name of the variable used to remember the names of // the defined tests in the given test case. # define GTEST_TYPED_TEST_CASE_P_STATE_(TestCaseName) \ gtest_typed_test_case_p_state_##TestCaseName##_ // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE DIRECTLY. // // Expands to the name of the variable used to remember the names of // the registered tests in the given test case. # define GTEST_REGISTERED_TEST_NAMES_(TestCaseName) \ gtest_registered_test_names_##TestCaseName##_ // The variables defined in the type-parameterized test macros are // static as typically these macros are used in a .h file that can be // #included in multiple translation units linked together. # define TYPED_TEST_CASE_P(CaseName) \ static ::testing::internal::TypedTestCasePState \ GTEST_TYPED_TEST_CASE_P_STATE_(CaseName) # define TYPED_TEST_P(CaseName, TestName) \ namespace GTEST_CASE_NAMESPACE_(CaseName) { \ template <typename gtest_TypeParam_> \ class TestName : public CaseName<gtest_TypeParam_> { \ private: \ typedef CaseName<gtest_TypeParam_> TestFixture; \ typedef gtest_TypeParam_ TypeParam; \ virtual void TestBody(); \ }; \ static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \ GTEST_TYPED_TEST_CASE_P_STATE_(CaseName).AddTestName(\ __FILE__, __LINE__, #CaseName, #TestName); \ } \ template <typename gtest_TypeParam_> \ void GTEST_CASE_NAMESPACE_(CaseName)::TestName<gtest_TypeParam_>::TestBody() # define REGISTER_TYPED_TEST_CASE_P(CaseName, ...) \ namespace GTEST_CASE_NAMESPACE_(CaseName) { \ typedef ::testing::internal::Templates<__VA_ARGS__>::type gtest_AllTests_; \ } \ static const char* const GTEST_REGISTERED_TEST_NAMES_(CaseName) = \ GTEST_TYPED_TEST_CASE_P_STATE_(CaseName).VerifyRegisteredTestNames(\ __FILE__, __LINE__, #__VA_ARGS__) // The 'Types' template argument below must have spaces around it // since some compilers may choke on '>>' when passing a template // instance (e.g. Types<int>) # define INSTANTIATE_TYPED_TEST_CASE_P(Prefix, CaseName, Types) \ bool gtest_##Prefix##_##CaseName GTEST_ATTRIBUTE_UNUSED_ = \ ::testing::internal::TypeParameterizedTestCase<CaseName, \ GTEST_CASE_NAMESPACE_(CaseName)::gtest_AllTests_, \ ::testing::internal::TypeList< Types >::type>::Register(\ #Prefix, \ ::testing::internal::CodeLocation(__FILE__, __LINE__), \ &GTEST_TYPED_TEST_CASE_P_STATE_(CaseName), \ #CaseName, GTEST_REGISTERED_TEST_NAMES_(CaseName)) #endif // GTEST_HAS_TYPED_TEST_P #endif // GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
0
repos/DirectXShaderCompiler/utils/unittest/googletest/include
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest/gtest-test-part.h
// 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. // // Author: [email protected] (Markus Heule) // #ifndef GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ #define GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_ #include <iosfwd> #include <vector> #include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-string.h" namespace testing { // A copyable object representing the result of a test part (i.e. an // assertion or an explicit FAIL(), ADD_FAILURE(), or SUCCESS()). // // Don't inherit from TestPartResult as its destructor is not virtual. class GTEST_API_ TestPartResult { public: // The possible outcomes of a test part (i.e. an assertion or an // explicit SUCCEED(), FAIL(), or ADD_FAILURE()). enum Type { kSuccess, // Succeeded. kNonFatalFailure, // Failed but the test can continue. kFatalFailure // Failed and the test should be terminated. }; // C'tor. TestPartResult does NOT have a default constructor. // Always use this constructor (with parameters) to create a // TestPartResult object. TestPartResult(Type a_type, const char* a_file_name, int a_line_number, const char* a_message) : type_(a_type), file_name_(a_file_name == NULL ? "" : a_file_name), line_number_(a_line_number), summary_(ExtractSummary(a_message)), message_(a_message) { } // Gets the outcome of the test part. Type type() const { return type_; } // Gets the name of the source file where the test part took place, or // NULL if it's unknown. const char* file_name() const { return file_name_.empty() ? NULL : file_name_.c_str(); } // Gets the line in the source file where the test part took place, // or -1 if it's unknown. int line_number() const { return line_number_; } // Gets the summary of the failure message. const char* summary() const { return summary_.c_str(); } // Gets the message associated with the test part. const char* message() const { return message_.c_str(); } // Returns true iff the test part passed. bool passed() const { return type_ == kSuccess; } // Returns true iff the test part failed. bool failed() const { return type_ != kSuccess; } // Returns true iff the test part non-fatally failed. bool nonfatally_failed() const { return type_ == kNonFatalFailure; } // Returns true iff the test part fatally failed. bool fatally_failed() const { return type_ == kFatalFailure; } private: Type type_; // Gets the summary of the failure message by omitting the stack // trace in it. static std::string ExtractSummary(const char* message); // The name of the source file where the test part took place, or // "" if the source file is unknown. std::string file_name_; // The line in the source file where the test part took place, or -1 // if the line number is unknown. int line_number_; std::string summary_; // The test failure summary. std::string message_; // The test failure message. }; // Prints a TestPartResult object. std::ostream& operator<<(std::ostream& os, const TestPartResult& result); // An array of TestPartResult objects. // // Don't inherit from TestPartResultArray as its destructor is not // virtual. class GTEST_API_ TestPartResultArray { public: TestPartResultArray() {} // Appends the given TestPartResult to the array. void Append(const TestPartResult& result); // Returns the TestPartResult at the given index (0-based). const TestPartResult& GetTestPartResult(int index) const; // Returns the number of TestPartResult objects in the array. int size() const; private: std::vector<TestPartResult> array_; GTEST_DISALLOW_COPY_AND_ASSIGN_(TestPartResultArray); }; // This interface knows how to report a test part result. class TestPartResultReporterInterface { public: virtual ~TestPartResultReporterInterface() {} virtual void ReportTestPartResult(const TestPartResult& result) = 0; }; namespace internal { // This helper class is used by {ASSERT|EXPECT}_NO_FATAL_FAILURE to check if a // statement generates new fatal failures. To do so it registers itself as the // current test part result reporter. Besides checking if fatal failures were // reported, it only delegates the reporting to the former result reporter. // The original result reporter is restored in the destructor. // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. class GTEST_API_ HasNewFatalFailureHelper : public TestPartResultReporterInterface { public: HasNewFatalFailureHelper(); virtual ~HasNewFatalFailureHelper(); virtual void ReportTestPartResult(const TestPartResult& result); bool has_new_fatal_failure() const { return has_new_fatal_failure_; } private: bool has_new_fatal_failure_; TestPartResultReporterInterface* original_reporter_; GTEST_DISALLOW_COPY_AND_ASSIGN_(HasNewFatalFailureHelper); }; } // namespace internal } // namespace testing #endif // GTEST_INCLUDE_GTEST_GTEST_TEST_PART_H_
0
repos/DirectXShaderCompiler/utils/unittest/googletest/include
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest/gtest.h
// Copyright 2005, 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. // // Author: [email protected] (Zhanyong Wan) // // The Google C++ Testing Framework (Google Test) // // This header file defines the public API for Google Test. It should be // included by any test program that uses Google Test. // // IMPORTANT NOTE: Due to limitation of the C++ language, we have to // leave some internal implementation details in this header file. // They are clearly marked by comments like this: // // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. // // Such code is NOT meant to be used by a user directly, and is subject // to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user // program! // // Acknowledgment: Google Test borrowed the idea of automatic test // registration from Barthelemy Dagenais' ([email protected]) // easyUnit framework. #ifndef GTEST_INCLUDE_GTEST_GTEST_H_ #define GTEST_INCLUDE_GTEST_GTEST_H_ #include <limits> #include <ostream> #include <vector> #include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-string.h" #include "gtest/gtest-death-test.h" #include "gtest/gtest-message.h" #include "gtest/gtest-param-test.h" #include "gtest/gtest-printers.h" #include "gtest/gtest_prod.h" #include "gtest/gtest-test-part.h" #include "gtest/gtest-typed-test.h" // Depending on the platform, different string classes are available. // On Linux, in addition to ::std::string, Google also makes use of // class ::string, which has the same interface as ::std::string, but // has a different implementation. // // You can define GTEST_HAS_GLOBAL_STRING to 1 to indicate that // ::string is available AND is a distinct type to ::std::string, or // define it to 0 to indicate otherwise. // // If ::std::string and ::string are the same class on your platform // due to aliasing, you should define GTEST_HAS_GLOBAL_STRING to 0. // // If you do not define GTEST_HAS_GLOBAL_STRING, it is defined // heuristically. namespace testing { // Declares the flags. // This flag temporary enables the disabled tests. GTEST_DECLARE_bool_(also_run_disabled_tests); // This flag brings the debugger on an assertion failure. GTEST_DECLARE_bool_(break_on_failure); // This flag controls whether Google Test catches all test-thrown exceptions // and logs them as failures. GTEST_DECLARE_bool_(catch_exceptions); // This flag enables using colors in terminal output. Available values are // "yes" to enable colors, "no" (disable colors), or "auto" (the default) // to let Google Test decide. GTEST_DECLARE_string_(color); // This flag sets up the filter to select by name using a glob pattern // the tests to run. If the filter is not given all tests are executed. GTEST_DECLARE_string_(filter); // This flag causes the Google Test to list tests. None of the tests listed // are actually run if the flag is provided. GTEST_DECLARE_bool_(list_tests); // This flag controls whether Google Test emits a detailed XML report to a file // in addition to its normal textual output. GTEST_DECLARE_string_(output); // This flags control whether Google Test prints the elapsed time for each // test. GTEST_DECLARE_bool_(print_time); // This flag specifies the random number seed. GTEST_DECLARE_int32_(random_seed); // This flag sets how many times the tests are repeated. The default value // is 1. If the value is -1 the tests are repeating forever. GTEST_DECLARE_int32_(repeat); // This flag controls whether Google Test includes Google Test internal // stack frames in failure stack traces. GTEST_DECLARE_bool_(show_internal_stack_frames); // When this flag is specified, tests' order is randomized on every iteration. GTEST_DECLARE_bool_(shuffle); // This flag specifies the maximum number of stack frames to be // printed in a failure message. GTEST_DECLARE_int32_(stack_trace_depth); // When this flag is specified, a failed assertion will throw an // exception if exceptions are enabled, or exit the program with a // non-zero code otherwise. GTEST_DECLARE_bool_(throw_on_failure); // When this flag is set with a "host:port" string, on supported // platforms test results are streamed to the specified port on // the specified host machine. GTEST_DECLARE_string_(stream_result_to); // The upper limit for valid stack trace depths. const int kMaxStackTraceDepth = 100; namespace internal { class AssertHelper; class DefaultGlobalTestPartResultReporter; class ExecDeathTest; class NoExecDeathTest; class FinalSuccessChecker; class GTestFlagSaver; class StreamingListenerTest; class TestResultAccessor; class TestEventListenersAccessor; class TestEventRepeater; class UnitTestRecordPropertyTestHelper; class WindowsDeathTest; class UnitTestImpl* GetUnitTestImpl(); void ReportFailureInUnknownLocation(TestPartResult::Type result_type, const std::string& message); } // namespace internal // The friend relationship of some of these classes is cyclic. // If we don't forward declare them the compiler might confuse the classes // in friendship clauses with same named classes on the scope. class Test; class TestCase; class TestInfo; class UnitTest; // A class for indicating whether an assertion was successful. When // the assertion wasn't successful, the AssertionResult object // remembers a non-empty message that describes how it failed. // // To create an instance of this class, use one of the factory functions // (AssertionSuccess() and AssertionFailure()). // // This class is useful for two purposes: // 1. Defining predicate functions to be used with Boolean test assertions // EXPECT_TRUE/EXPECT_FALSE and their ASSERT_ counterparts // 2. Defining predicate-format functions to be // used with predicate assertions (ASSERT_PRED_FORMAT*, etc). // // For example, if you define IsEven predicate: // // testing::AssertionResult IsEven(int n) { // if ((n % 2) == 0) // return testing::AssertionSuccess(); // else // return testing::AssertionFailure() << n << " is odd"; // } // // Then the failed expectation EXPECT_TRUE(IsEven(Fib(5))) // will print the message // // Value of: IsEven(Fib(5)) // Actual: false (5 is odd) // Expected: true // // instead of a more opaque // // Value of: IsEven(Fib(5)) // Actual: false // Expected: true // // in case IsEven is a simple Boolean predicate. // // If you expect your predicate to be reused and want to support informative // messages in EXPECT_FALSE and ASSERT_FALSE (negative assertions show up // about half as often as positive ones in our tests), supply messages for // both success and failure cases: // // testing::AssertionResult IsEven(int n) { // if ((n % 2) == 0) // return testing::AssertionSuccess() << n << " is even"; // else // return testing::AssertionFailure() << n << " is odd"; // } // // Then a statement EXPECT_FALSE(IsEven(Fib(6))) will print // // Value of: IsEven(Fib(6)) // Actual: true (8 is even) // Expected: false // // NB: Predicates that support negative Boolean assertions have reduced // performance in positive ones so be careful not to use them in tests // that have lots (tens of thousands) of positive Boolean assertions. // // To use this class with EXPECT_PRED_FORMAT assertions such as: // // // Verifies that Foo() returns an even number. // EXPECT_PRED_FORMAT1(IsEven, Foo()); // // you need to define: // // testing::AssertionResult IsEven(const char* expr, int n) { // if ((n % 2) == 0) // return testing::AssertionSuccess(); // else // return testing::AssertionFailure() // << "Expected: " << expr << " is even\n Actual: it's " << n; // } // // If Foo() returns 5, you will see the following message: // // Expected: Foo() is even // Actual: it's 5 // class GTEST_API_ AssertionResult { public: // Copy constructor. // Used in EXPECT_TRUE/FALSE(assertion_result). AssertionResult(const AssertionResult& other); GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 /* forcing value to bool */) // Used in the EXPECT_TRUE/FALSE(bool_expression). // // T must be contextually convertible to bool. // // The second parameter prevents this overload from being considered if // the argument is implicitly convertible to AssertionResult. In that case // we want AssertionResult's copy constructor to be used. template <typename T> explicit AssertionResult( const T& success, typename internal::EnableIf< !internal::ImplicitlyConvertible<T, AssertionResult>::value>::type* /*enabler*/ = NULL) : success_(success) {} GTEST_DISABLE_MSC_WARNINGS_POP_() // Assignment operator. AssertionResult& operator=(AssertionResult other) { swap(other); return *this; } // Returns true iff the assertion succeeded. operator bool() const { return success_; } // NOLINT // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE. AssertionResult operator!() const; // Returns the text streamed into this AssertionResult. Test assertions // use it when they fail (i.e., the predicate's outcome doesn't match the // assertion's expectation). When nothing has been streamed into the // object, returns an empty string. const char* message() const { return message_.get() != NULL ? message_->c_str() : ""; } // TODO([email protected]): Remove this after making sure no clients use it. // Deprecated; please use message() instead. const char* failure_message() const { return message(); } // Streams a custom failure message into this object. template <typename T> AssertionResult& operator<<(const T& value) { AppendMessage(Message() << value); return *this; } // Allows streaming basic output manipulators such as endl or flush into // this object. AssertionResult& operator<<( ::std::ostream& (*basic_manipulator)(::std::ostream& stream)) { AppendMessage(Message() << basic_manipulator); return *this; } private: // Appends the contents of message to message_. void AppendMessage(const Message& a_message) { if (message_.get() == NULL) message_.reset(new ::std::string); message_->append(a_message.GetString().c_str()); } // Swap the contents of this AssertionResult with other. void swap(AssertionResult& other); // Stores result of the assertion predicate. bool success_; // Stores the message describing the condition in case the expectation // construct is not satisfied with the predicate's outcome. // Referenced via a pointer to avoid taking too much stack frame space // with test assertions. internal::scoped_ptr< ::std::string> message_; }; // Makes a successful assertion result. GTEST_API_ AssertionResult AssertionSuccess(); // Makes a failed assertion result. GTEST_API_ AssertionResult AssertionFailure(); // Makes a failed assertion result with the given failure message. // Deprecated; use AssertionFailure() << msg. GTEST_API_ AssertionResult AssertionFailure(const Message& msg); // The abstract class that all tests inherit from. // // In Google Test, a unit test program contains one or many TestCases, and // each TestCase contains one or many Tests. // // When you define a test using the TEST macro, you don't need to // explicitly derive from Test - the TEST macro automatically does // this for you. // // The only time you derive from Test is when defining a test fixture // to be used a TEST_F. For example: // // class FooTest : public testing::Test { // protected: // void SetUp() override { ... } // void TearDown() override { ... } // ... // }; // // TEST_F(FooTest, Bar) { ... } // TEST_F(FooTest, Baz) { ... } // // Test is not copyable. class GTEST_API_ Test { public: friend class TestInfo; // Defines types for pointers to functions that set up and tear down // a test case. typedef internal::SetUpTestCaseFunc SetUpTestCaseFunc; typedef internal::TearDownTestCaseFunc TearDownTestCaseFunc; // The d'tor is virtual as we intend to inherit from Test. virtual ~Test(); // Sets up the stuff shared by all tests in this test case. // // Google Test will call Foo::SetUpTestCase() before running the first // test in test case Foo. Hence a sub-class can define its own // SetUpTestCase() method to shadow the one defined in the super // class. static void SetUpTestCase() {} // Tears down the stuff shared by all tests in this test case. // // Google Test will call Foo::TearDownTestCase() after running the last // test in test case Foo. Hence a sub-class can define its own // TearDownTestCase() method to shadow the one defined in the super // class. static void TearDownTestCase() {} // Returns true iff the current test has a fatal failure. static bool HasFatalFailure(); // Returns true iff the current test has a non-fatal failure. static bool HasNonfatalFailure(); // Returns true iff the current test has a (either fatal or // non-fatal) failure. static bool HasFailure() { return HasFatalFailure() || HasNonfatalFailure(); } // Logs a property for the current test, test case, or for the entire // invocation of the test program when used outside of the context of a // test case. Only the last value for a given key is remembered. These // are public static so they can be called from utility functions that are // not members of the test fixture. Calls to RecordProperty made during // lifespan of the test (from the moment its constructor starts to the // moment its destructor finishes) will be output in XML as attributes of // the <testcase> element. Properties recorded from fixture's // SetUpTestCase or TearDownTestCase are logged as attributes of the // corresponding <testsuite> element. Calls to RecordProperty made in the // global context (before or after invocation of RUN_ALL_TESTS and from // SetUp/TearDown method of Environment objects registered with Google // Test) will be output as attributes of the <testsuites> element. static void RecordProperty(const std::string& key, const std::string& value); static void RecordProperty(const std::string& key, int value); protected: // Creates a Test object. Test(); // Sets up the test fixture. virtual void SetUp(); // Tears down the test fixture. virtual void TearDown(); private: // Returns true iff the current test has the same fixture class as // the first test in the current test case. static bool HasSameFixtureClass(); // Runs the test after the test fixture has been set up. // // A sub-class must implement this to define the test logic. // // DO NOT OVERRIDE THIS FUNCTION DIRECTLY IN A USER PROGRAM. // Instead, use the TEST or TEST_F macro. virtual void TestBody() = 0; // Sets up, executes, and tears down the test. void Run(); // Deletes self. We deliberately pick an unusual name for this // internal method to avoid clashing with names used in user TESTs. void DeleteSelf_() { delete this; } const internal::scoped_ptr< GTEST_FLAG_SAVER_ > gtest_flag_saver_; // Often a user misspells SetUp() as Setup() and spends a long time // wondering why it is never called by Google Test. The declaration of // the following method is solely for catching such an error at // compile time: // // - The return type is deliberately chosen to be not void, so it // will be a conflict if void Setup() is declared in the user's // test fixture. // // - This method is private, so it will be another compiler error // if the method is called from the user's test fixture. // // DO NOT OVERRIDE THIS FUNCTION. // // If you see an error about overriding the following function or // about it being private, you have mis-spelled SetUp() as Setup(). struct Setup_should_be_spelled_SetUp {}; virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; } // We disallow copying Tests. GTEST_DISALLOW_COPY_AND_ASSIGN_(Test); }; typedef internal::TimeInMillis TimeInMillis; // A copyable object representing a user specified test property which can be // output as a key/value string pair. // // Don't inherit from TestProperty as its destructor is not virtual. class TestProperty { public: // C'tor. TestProperty does NOT have a default constructor. // Always use this constructor (with parameters) to create a // TestProperty object. TestProperty(const std::string& a_key, const std::string& a_value) : key_(a_key), value_(a_value) { } // Gets the user supplied key. const char* key() const { return key_.c_str(); } // Gets the user supplied value. const char* value() const { return value_.c_str(); } // Sets a new value, overriding the one supplied in the constructor. void SetValue(const std::string& new_value) { value_ = new_value; } private: // The key supplied by the user. std::string key_; // The value supplied by the user. std::string value_; }; // The result of a single Test. This includes a list of // TestPartResults, a list of TestProperties, a count of how many // death tests there are in the Test, and how much time it took to run // the Test. // // TestResult is not copyable. class GTEST_API_ TestResult { public: // Creates an empty TestResult. TestResult(); // D'tor. Do not inherit from TestResult. ~TestResult(); // Gets the number of all test parts. This is the sum of the number // of successful test parts and the number of failed test parts. int total_part_count() const; // Returns the number of the test properties. int test_property_count() const; // Returns true iff the test passed (i.e. no test part failed). bool Passed() const { return !Failed(); } // Returns true iff the test failed. bool Failed() const; // Returns true iff the test fatally failed. bool HasFatalFailure() const; // Returns true iff the test has a non-fatal failure. bool HasNonfatalFailure() const; // Returns the elapsed time, in milliseconds. TimeInMillis elapsed_time() const { return elapsed_time_; } // Returns the i-th test part result among all the results. i can range // from 0 to test_property_count() - 1. If i is not in that range, aborts // the program. const TestPartResult& GetTestPartResult(int i) const; // Returns the i-th test property. i can range from 0 to // test_property_count() - 1. If i is not in that range, aborts the // program. const TestProperty& GetTestProperty(int i) const; private: friend class TestInfo; friend class TestCase; friend class UnitTest; friend class internal::DefaultGlobalTestPartResultReporter; friend class internal::ExecDeathTest; friend class internal::TestResultAccessor; friend class internal::UnitTestImpl; friend class internal::WindowsDeathTest; // Gets the vector of TestPartResults. const std::vector<TestPartResult>& test_part_results() const { return test_part_results_; } // Gets the vector of TestProperties. const std::vector<TestProperty>& test_properties() const { return test_properties_; } // Sets the elapsed time. void set_elapsed_time(TimeInMillis elapsed) { elapsed_time_ = elapsed; } // Adds a test property to the list. The property is validated and may add // a non-fatal failure if invalid (e.g., if it conflicts with reserved // key names). If a property is already recorded for the same key, the // value will be updated, rather than storing multiple values for the same // key. xml_element specifies the element for which the property is being // recorded and is used for validation. void RecordProperty(const std::string& xml_element, const TestProperty& test_property); // Adds a failure if the key is a reserved attribute of Google Test // testcase tags. Returns true if the property is valid. // TODO(russr): Validate attribute names are legal and human readable. static bool ValidateTestProperty(const std::string& xml_element, const TestProperty& test_property); // Adds a test part result to the list. void AddTestPartResult(const TestPartResult& test_part_result); // Returns the death test count. int death_test_count() const { return death_test_count_; } // Increments the death test count, returning the new count. int increment_death_test_count() { return ++death_test_count_; } // Clears the test part results. void ClearTestPartResults(); // Clears the object. void Clear(); // Protects mutable state of the property vector and of owned // properties, whose values may be updated. internal::Mutex test_properites_mutex_; // The vector of TestPartResults std::vector<TestPartResult> test_part_results_; // The vector of TestProperties std::vector<TestProperty> test_properties_; // Running count of death tests. int death_test_count_; // The elapsed time, in milliseconds. TimeInMillis elapsed_time_; // We disallow copying TestResult. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestResult); }; // class TestResult // A TestInfo object stores the following information about a test: // // Test case name // Test name // Whether the test should be run // A function pointer that creates the test object when invoked // Test result // // The constructor of TestInfo registers itself with the UnitTest // singleton such that the RUN_ALL_TESTS() macro knows which tests to // run. class GTEST_API_ TestInfo { public: // Destructs a TestInfo object. This function is not virtual, so // don't inherit from TestInfo. ~TestInfo(); // Returns the test case name. const char* test_case_name() const { return test_case_name_.c_str(); } // Returns the test name. const char* name() const { return name_.c_str(); } // Returns the name of the parameter type, or NULL if this is not a typed // or a type-parameterized test. const char* type_param() const { if (type_param_.get() != NULL) return type_param_->c_str(); return NULL; } // Returns the text representation of the value parameter, or NULL if this // is not a value-parameterized test. const char* value_param() const { if (value_param_.get() != NULL) return value_param_->c_str(); return NULL; } // Returns the file name where this test is defined. const char* file() const { return location_.file.c_str(); } // Returns the line where this test is defined. int line() const { return location_.line; } // Returns true if this test should run, that is if the test is not // disabled (or it is disabled but the also_run_disabled_tests flag has // been specified) and its full name matches the user-specified filter. // // Google Test allows the user to filter the tests by their full names. // The full name of a test Bar in test case Foo is defined as // "Foo.Bar". Only the tests that match the filter will run. // // A filter is a colon-separated list of glob (not regex) patterns, // optionally followed by a '-' and a colon-separated list of // negative patterns (tests to exclude). A test is run if it // matches one of the positive patterns and does not match any of // the negative patterns. // // For example, *A*:Foo.* is a filter that matches any string that // contains the character 'A' or starts with "Foo.". bool should_run() const { return should_run_; } // Returns true iff this test will appear in the XML report. bool is_reportable() const { // For now, the XML report includes all tests matching the filter. // In the future, we may trim tests that are excluded because of // sharding. return matches_filter_; } // Returns the result of the test. const TestResult* result() const { return &result_; } private: #if GTEST_HAS_DEATH_TEST friend class internal::DefaultDeathTestFactory; #endif // GTEST_HAS_DEATH_TEST friend class Test; friend class TestCase; friend class internal::UnitTestImpl; friend class internal::StreamingListenerTest; friend TestInfo* internal::MakeAndRegisterTestInfo( const char* test_case_name, const char* name, const char* type_param, const char* value_param, internal::CodeLocation code_location, internal::TypeId fixture_class_id, Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc, internal::TestFactoryBase* factory); // Constructs a TestInfo object. The newly constructed instance assumes // ownership of the factory object. TestInfo(const std::string& test_case_name, const std::string& name, const char* a_type_param, // NULL if not a type-parameterized test const char* a_value_param, // NULL if not a value-parameterized test internal::CodeLocation a_code_location, internal::TypeId fixture_class_id, internal::TestFactoryBase* factory); // Increments the number of death tests encountered in this test so // far. int increment_death_test_count() { return result_.increment_death_test_count(); } // Creates the test object, runs it, records its result, and then // deletes it. void Run(); static void ClearTestResult(TestInfo* test_info) { test_info->result_.Clear(); } // These fields are immutable properties of the test. const std::string test_case_name_; // Test case name const std::string name_; // Test name // Name of the parameter type, or NULL if this is not a typed or a // type-parameterized test. const internal::scoped_ptr<const ::std::string> type_param_; // Text representation of the value parameter, or NULL if this is not a // value-parameterized test. const internal::scoped_ptr<const ::std::string> value_param_; internal::CodeLocation location_; const internal::TypeId fixture_class_id_; // ID of the test fixture class bool should_run_; // True iff this test should run bool is_disabled_; // True iff this test is disabled bool matches_filter_; // True if this test matches the // user-specified filter. internal::TestFactoryBase* const factory_; // The factory that creates // the test object // This field is mutable and needs to be reset before running the // test for the second time. TestResult result_; GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfo); }; // A test case, which consists of a vector of TestInfos. // // TestCase is not copyable. class GTEST_API_ TestCase { public: // Creates a TestCase with the given name. // // TestCase does NOT have a default constructor. Always use this // constructor to create a TestCase object. // // Arguments: // // name: name of the test case // a_type_param: the name of the test's type parameter, or NULL if // this is not a type-parameterized test. // set_up_tc: pointer to the function that sets up the test case // tear_down_tc: pointer to the function that tears down the test case TestCase(const char* name, const char* a_type_param, Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc); // Destructor of TestCase. virtual ~TestCase(); // Gets the name of the TestCase. const char* name() const { return name_.c_str(); } // Returns the name of the parameter type, or NULL if this is not a // type-parameterized test case. const char* type_param() const { if (type_param_.get() != NULL) return type_param_->c_str(); return NULL; } // Returns true if any test in this test case should run. bool should_run() const { return should_run_; } // Gets the number of successful tests in this test case. int successful_test_count() const; // Gets the number of failed tests in this test case. int failed_test_count() const; // Gets the number of disabled tests that will be reported in the XML report. int reportable_disabled_test_count() const; // Gets the number of disabled tests in this test case. int disabled_test_count() const; // Gets the number of tests to be printed in the XML report. int reportable_test_count() const; // Get the number of tests in this test case that should run. int test_to_run_count() const; // Gets the number of all tests in this test case. int total_test_count() const; // Returns true iff the test case passed. bool Passed() const { return !Failed(); } // Returns true iff the test case failed. bool Failed() const { return failed_test_count() > 0; } // Returns the elapsed time, in milliseconds. TimeInMillis elapsed_time() const { return elapsed_time_; } // Returns the i-th test among all the tests. i can range from 0 to // total_test_count() - 1. If i is not in that range, returns NULL. const TestInfo* GetTestInfo(int i) const; // Returns the TestResult that holds test properties recorded during // execution of SetUpTestCase and TearDownTestCase. const TestResult& ad_hoc_test_result() const { return ad_hoc_test_result_; } private: friend class Test; friend class internal::UnitTestImpl; // Gets the (mutable) vector of TestInfos in this TestCase. std::vector<TestInfo*>& test_info_list() { return test_info_list_; } // Gets the (immutable) vector of TestInfos in this TestCase. const std::vector<TestInfo*>& test_info_list() const { return test_info_list_; } // Returns the i-th test among all the tests. i can range from 0 to // total_test_count() - 1. If i is not in that range, returns NULL. TestInfo* GetMutableTestInfo(int i); // Sets the should_run member. void set_should_run(bool should) { should_run_ = should; } // Adds a TestInfo to this test case. Will delete the TestInfo upon // destruction of the TestCase object. void AddTestInfo(TestInfo * test_info); // Clears the results of all tests in this test case. void ClearResult(); // Clears the results of all tests in the given test case. static void ClearTestCaseResult(TestCase* test_case) { test_case->ClearResult(); } // Runs every test in this TestCase. void Run(); // Runs SetUpTestCase() for this TestCase. This wrapper is needed // for catching exceptions thrown from SetUpTestCase(). void RunSetUpTestCase() { (*set_up_tc_)(); } // Runs TearDownTestCase() for this TestCase. This wrapper is // needed for catching exceptions thrown from TearDownTestCase(). void RunTearDownTestCase() { (*tear_down_tc_)(); } // Returns true iff test passed. static bool TestPassed(const TestInfo* test_info) { return test_info->should_run() && test_info->result()->Passed(); } // Returns true iff test failed. static bool TestFailed(const TestInfo* test_info) { return test_info->should_run() && test_info->result()->Failed(); } // Returns true iff the test is disabled and will be reported in the XML // report. static bool TestReportableDisabled(const TestInfo* test_info) { return test_info->is_reportable() && test_info->is_disabled_; } // Returns true iff test is disabled. static bool TestDisabled(const TestInfo* test_info) { return test_info->is_disabled_; } // Returns true iff this test will appear in the XML report. static bool TestReportable(const TestInfo* test_info) { return test_info->is_reportable(); } // Returns true if the given test should run. static bool ShouldRunTest(const TestInfo* test_info) { return test_info->should_run(); } // Shuffles the tests in this test case. void ShuffleTests(internal::Random* random); // Restores the test order to before the first shuffle. void UnshuffleTests(); // Name of the test case. std::string name_; // Name of the parameter type, or NULL if this is not a typed or a // type-parameterized test. const internal::scoped_ptr<const ::std::string> type_param_; // The vector of TestInfos in their original order. It owns the // elements in the vector. std::vector<TestInfo*> test_info_list_; // Provides a level of indirection for the test list to allow easy // shuffling and restoring the test order. The i-th element in this // vector is the index of the i-th test in the shuffled test list. std::vector<int> test_indices_; // Pointer to the function that sets up the test case. Test::SetUpTestCaseFunc set_up_tc_; // Pointer to the function that tears down the test case. Test::TearDownTestCaseFunc tear_down_tc_; // True iff any test in this test case should run. bool should_run_; // Elapsed time, in milliseconds. TimeInMillis elapsed_time_; // Holds test properties recorded during execution of SetUpTestCase and // TearDownTestCase. TestResult ad_hoc_test_result_; // We disallow copying TestCases. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestCase); }; // An Environment object is capable of setting up and tearing down an // environment. You should subclass this to define your own // environment(s). // // An Environment object does the set-up and tear-down in virtual // methods SetUp() and TearDown() instead of the constructor and the // destructor, as: // // 1. You cannot safely throw from a destructor. This is a problem // as in some cases Google Test is used where exceptions are enabled, and // we may want to implement ASSERT_* using exceptions where they are // available. // 2. You cannot use ASSERT_* directly in a constructor or // destructor. class Environment { public: // The d'tor is virtual as we need to subclass Environment. virtual ~Environment() {} // Override this to define how to set up the environment. virtual void SetUp() {} // Override this to define how to tear down the environment. virtual void TearDown() {} private: // If you see an error about overriding the following function or // about it being private, you have mis-spelled SetUp() as Setup(). struct Setup_should_be_spelled_SetUp {}; virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; } }; // The interface for tracing execution of tests. The methods are organized in // the order the corresponding events are fired. class TestEventListener { public: virtual ~TestEventListener() {} // Fired before any test activity starts. virtual void OnTestProgramStart(const UnitTest& unit_test) = 0; // Fired before each iteration of tests starts. There may be more than // one iteration if GTEST_FLAG(repeat) is set. iteration is the iteration // index, starting from 0. virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration) = 0; // Fired before environment set-up for each iteration of tests starts. virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test) = 0; // Fired after environment set-up for each iteration of tests ends. virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) = 0; // Fired before the test case starts. virtual void OnTestCaseStart(const TestCase& test_case) = 0; // Fired before the test starts. virtual void OnTestStart(const TestInfo& test_info) = 0; // Fired after a failed assertion or a SUCCEED() invocation. virtual void OnTestPartResult(const TestPartResult& test_part_result) = 0; // Fired after the test ends. virtual void OnTestEnd(const TestInfo& test_info) = 0; // Fired after the test case ends. virtual void OnTestCaseEnd(const TestCase& test_case) = 0; // Fired before environment tear-down for each iteration of tests starts. virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test) = 0; // Fired after environment tear-down for each iteration of tests ends. virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) = 0; // Fired after each iteration of tests finishes. virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration) = 0; // Fired after all test activities have ended. virtual void OnTestProgramEnd(const UnitTest& unit_test) = 0; }; // The convenience class for users who need to override just one or two // methods and are not concerned that a possible change to a signature of // the methods they override will not be caught during the build. For // comments about each method please see the definition of TestEventListener // above. class EmptyTestEventListener : public TestEventListener { public: virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {} virtual void OnTestIterationStart(const UnitTest& /*unit_test*/, int /*iteration*/) {} virtual void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) {} virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {} virtual void OnTestCaseStart(const TestCase& /*test_case*/) {} virtual void OnTestStart(const TestInfo& /*test_info*/) {} virtual void OnTestPartResult(const TestPartResult& /*test_part_result*/) {} virtual void OnTestEnd(const TestInfo& /*test_info*/) {} virtual void OnTestCaseEnd(const TestCase& /*test_case*/) {} virtual void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) {} virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {} virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/, int /*iteration*/) {} virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {} }; // TestEventListeners lets users add listeners to track events in Google Test. class GTEST_API_ TestEventListeners { public: TestEventListeners(); ~TestEventListeners(); // Appends an event listener to the end of the list. Google Test assumes // the ownership of the listener (i.e. it will delete the listener when // the test program finishes). void Append(TestEventListener* listener); // Removes the given event listener from the list and returns it. It then // becomes the caller's responsibility to delete the listener. Returns // NULL if the listener is not found in the list. TestEventListener* Release(TestEventListener* listener); // Returns the standard listener responsible for the default console // output. Can be removed from the listeners list to shut down default // console output. Note that removing this object from the listener list // with Release transfers its ownership to the caller and makes this // function return NULL the next time. TestEventListener* default_result_printer() const { return default_result_printer_; } // Returns the standard listener responsible for the default XML output // controlled by the --gtest_output=xml flag. Can be removed from the // listeners list by users who want to shut down the default XML output // controlled by this flag and substitute it with custom one. Note that // removing this object from the listener list with Release transfers its // ownership to the caller and makes this function return NULL the next // time. TestEventListener* default_xml_generator() const { return default_xml_generator_; } private: friend class TestCase; friend class TestInfo; friend class internal::DefaultGlobalTestPartResultReporter; friend class internal::NoExecDeathTest; friend class internal::TestEventListenersAccessor; friend class internal::UnitTestImpl; // Returns repeater that broadcasts the TestEventListener events to all // subscribers. TestEventListener* repeater(); // Sets the default_result_printer attribute to the provided listener. // The listener is also added to the listener list and previous // default_result_printer is removed from it and deleted. The listener can // also be NULL in which case it will not be added to the list. Does // nothing if the previous and the current listener objects are the same. void SetDefaultResultPrinter(TestEventListener* listener); // Sets the default_xml_generator attribute to the provided listener. The // listener is also added to the listener list and previous // default_xml_generator is removed from it and deleted. The listener can // also be NULL in which case it will not be added to the list. Does // nothing if the previous and the current listener objects are the same. void SetDefaultXmlGenerator(TestEventListener* listener); // Controls whether events will be forwarded by the repeater to the // listeners in the list. bool EventForwardingEnabled() const; void SuppressEventForwarding(); // The actual list of listeners. internal::TestEventRepeater* repeater_; // Listener responsible for the standard result output. TestEventListener* default_result_printer_; // Listener responsible for the creation of the XML output file. TestEventListener* default_xml_generator_; // We disallow copying TestEventListeners. GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventListeners); }; // A UnitTest consists of a vector of TestCases. // // This is a singleton class. The only instance of UnitTest is // created when UnitTest::GetInstance() is first called. This // instance is never deleted. // // UnitTest is not copyable. // // This class is thread-safe as long as the methods are called // according to their specification. class GTEST_API_ UnitTest { public: // Gets the singleton UnitTest object. The first time this method // is called, a UnitTest object is constructed and returned. // Consecutive calls will return the same object. static UnitTest* GetInstance(); // Runs all tests in this UnitTest object and prints the result. // Returns 0 if successful, or 1 otherwise. // // This method can only be called from the main thread. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. int Run() GTEST_MUST_USE_RESULT_; // Returns the working directory when the first TEST() or TEST_F() // was executed. The UnitTest object owns the string. const char* original_working_dir() const; // Returns the TestCase object for the test that's currently running, // or NULL if no test is running. const TestCase* current_test_case() const GTEST_LOCK_EXCLUDED_(mutex_); // Returns the TestInfo object for the test that's currently running, // or NULL if no test is running. const TestInfo* current_test_info() const GTEST_LOCK_EXCLUDED_(mutex_); // Returns the random seed used at the start of the current test run. int random_seed() const; #if GTEST_HAS_PARAM_TEST // Returns the ParameterizedTestCaseRegistry object used to keep track of // value-parameterized tests and instantiate and register them. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. internal::ParameterizedTestCaseRegistry& parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_); #endif // GTEST_HAS_PARAM_TEST // Gets the number of successful test cases. int successful_test_case_count() const; // Gets the number of failed test cases. int failed_test_case_count() const; // Gets the number of all test cases. int total_test_case_count() const; // Gets the number of all test cases that contain at least one test // that should run. int test_case_to_run_count() const; // Gets the number of successful tests. int successful_test_count() const; // Gets the number of failed tests. int failed_test_count() const; // Gets the number of disabled tests that will be reported in the XML report. int reportable_disabled_test_count() const; // Gets the number of disabled tests. int disabled_test_count() const; // Gets the number of tests to be printed in the XML report. int reportable_test_count() const; // Gets the number of all tests. int total_test_count() const; // Gets the number of tests that should run. int test_to_run_count() const; // Gets the time of the test program start, in ms from the start of the // UNIX epoch. TimeInMillis start_timestamp() const; // Gets the elapsed time, in milliseconds. TimeInMillis elapsed_time() const; // Returns true iff the unit test passed (i.e. all test cases passed). bool Passed() const; // Returns true iff the unit test failed (i.e. some test case failed // or something outside of all tests failed). bool Failed() const; // Gets the i-th test case among all the test cases. i can range from 0 to // total_test_case_count() - 1. If i is not in that range, returns NULL. const TestCase* GetTestCase(int i) const; // Returns the TestResult containing information on test failures and // properties logged outside of individual test cases. const TestResult& ad_hoc_test_result() const; // Returns the list of event listeners that can be used to track events // inside Google Test. TestEventListeners& listeners(); private: // Registers and returns a global test environment. When a test // program is run, all global test environments will be set-up in // the order they were registered. After all tests in the program // have finished, all global test environments will be torn-down in // the *reverse* order they were registered. // // The UnitTest object takes ownership of the given environment. // // This method can only be called from the main thread. Environment* AddEnvironment(Environment* env); // Adds a TestPartResult to the current TestResult object. All // Google Test assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) // eventually call this to report their results. The user code // should use the assertion macros instead of calling this directly. void AddTestPartResult(TestPartResult::Type result_type, const char* file_name, int line_number, const std::string& message, const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_); // Adds a TestProperty to the current TestResult object when invoked from // inside a test, to current TestCase's ad_hoc_test_result_ when invoked // from SetUpTestCase or TearDownTestCase, or to the global property set // when invoked elsewhere. If the result already contains a property with // the same key, the value will be updated. void RecordProperty(const std::string& key, const std::string& value); // Gets the i-th test case among all the test cases. i can range from 0 to // total_test_case_count() - 1. If i is not in that range, returns NULL. TestCase* GetMutableTestCase(int i); // Accessors for the implementation object. internal::UnitTestImpl* impl() { return impl_; } const internal::UnitTestImpl* impl() const { return impl_; } // These classes and funcions are friends as they need to access private // members of UnitTest. friend class Test; friend class internal::AssertHelper; friend class internal::ScopedTrace; friend class internal::StreamingListenerTest; friend class internal::UnitTestRecordPropertyTestHelper; friend Environment* AddGlobalTestEnvironment(Environment* env); friend internal::UnitTestImpl* internal::GetUnitTestImpl(); friend void internal::ReportFailureInUnknownLocation( TestPartResult::Type result_type, const std::string& message); // Creates an empty UnitTest. UnitTest(); // D'tor virtual ~UnitTest(); // Pushes a trace defined by SCOPED_TRACE() on to the per-thread // Google Test trace stack. void PushGTestTrace(const internal::TraceInfo& trace) GTEST_LOCK_EXCLUDED_(mutex_); // Pops a trace from the per-thread Google Test trace stack. void PopGTestTrace() GTEST_LOCK_EXCLUDED_(mutex_); // Protects mutable state in *impl_. This is mutable as some const // methods need to lock it too. mutable internal::Mutex mutex_; // Opaque implementation object. This field is never changed once // the object is constructed. We don't mark it as const here, as // doing so will cause a warning in the constructor of UnitTest. // Mutable state in *impl_ is protected by mutex_. internal::UnitTestImpl* impl_; // We disallow copying UnitTest. GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTest); }; // A convenient wrapper for adding an environment for the test // program. // // You should call this before RUN_ALL_TESTS() is called, probably in // main(). If you use gtest_main, you need to call this before main() // starts for it to take effect. For example, you can define a global // variable like this: // // testing::Environment* const foo_env = // testing::AddGlobalTestEnvironment(new FooEnvironment); // // However, we strongly recommend you to write your own main() and // call AddGlobalTestEnvironment() there, as relying on initialization // of global variables makes the code harder to read and may cause // problems when you register multiple environments from different // translation units and the environments have dependencies among them // (remember that the compiler doesn't guarantee the order in which // global variables from different translation units are initialized). inline Environment* AddGlobalTestEnvironment(Environment* env) { return UnitTest::GetInstance()->AddEnvironment(env); } // Initializes Google Test. This must be called before calling // RUN_ALL_TESTS(). In particular, it parses a command line for the // flags that Google Test recognizes. Whenever a Google Test flag is // seen, it is removed from argv, and *argc is decremented. // // No value is returned. Instead, the Google Test flag variables are // updated. // // Calling the function for the second time has no user-visible effect. GTEST_API_ void InitGoogleTest(int* argc, char** argv); // This overloaded version can be used in Windows programs compiled in // UNICODE mode. GTEST_API_ void InitGoogleTest(int* argc, wchar_t** argv); namespace internal { // Separate the error generating code from the code path to reduce the stack // frame size of CmpHelperEQ. This helps reduce the overhead of some sanitizers // when calling EXPECT_* in a tight loop. template <typename T1, typename T2> AssertionResult CmpHelperEQFailure(const char* lhs_expression, const char* rhs_expression, const T1& lhs, const T2& rhs) { return EqFailure(lhs_expression, rhs_expression, FormatForComparisonFailureMessage(lhs, rhs), FormatForComparisonFailureMessage(rhs, lhs), false); } // The helper function for {ASSERT|EXPECT}_EQ. template <typename T1, typename T2> AssertionResult CmpHelperEQ(const char* lhs_expression, const char* rhs_expression, const T1& lhs, const T2& rhs) { GTEST_DISABLE_MSC_WARNINGS_PUSH_(4389 /* signed/unsigned mismatch */) if (lhs == rhs) { return AssertionSuccess(); } GTEST_DISABLE_MSC_WARNINGS_POP_() return CmpHelperEQFailure(lhs_expression, rhs_expression, lhs, rhs); } // With this overloaded version, we allow anonymous enums to be used // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous enums // can be implicitly cast to BiggestInt. GTEST_API_ AssertionResult CmpHelperEQ(const char* lhs_expression, const char* rhs_expression, BiggestInt lhs, BiggestInt rhs); // The helper class for {ASSERT|EXPECT}_EQ. The template argument // lhs_is_null_literal is true iff the first argument to ASSERT_EQ() // is a null pointer literal. The following default implementation is // for lhs_is_null_literal being false. template <bool lhs_is_null_literal> class EqHelper { public: // This templatized version is for the general case. template <typename T1, typename T2> static AssertionResult Compare(const char* lhs_expression, const char* rhs_expression, const T1& lhs, const T2& rhs) { return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs); } // With this overloaded version, we allow anonymous enums to be used // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous // enums can be implicitly cast to BiggestInt. // // Even though its body looks the same as the above version, we // cannot merge the two, as it will make anonymous enums unhappy. static AssertionResult Compare(const char* lhs_expression, const char* rhs_expression, BiggestInt lhs, BiggestInt rhs) { return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs); } }; // This specialization is used when the first argument to ASSERT_EQ() // is a null pointer literal, like NULL, false, or 0. template <> class EqHelper<true> { public: // We define two overloaded versions of Compare(). The first // version will be picked when the second argument to ASSERT_EQ() is // NOT a pointer, e.g. ASSERT_EQ(0, AnIntFunction()) or // EXPECT_EQ(false, a_bool). template <typename T1, typename T2> static AssertionResult Compare( const char* lhs_expression, const char* rhs_expression, const T1& lhs, const T2& rhs, // The following line prevents this overload from being considered if T2 // is not a pointer type. We need this because ASSERT_EQ(NULL, my_ptr) // expands to Compare("", "", NULL, my_ptr), which requires a conversion // to match the Secret* in the other overload, which would otherwise make // this template match better. typename EnableIf<!is_pointer<T2>::value>::type* = 0) { return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs); } // This version will be picked when the second argument to ASSERT_EQ() is a // pointer, e.g. ASSERT_EQ(NULL, a_pointer). template <typename T> static AssertionResult Compare( const char* lhs_expression, const char* rhs_expression, // We used to have a second template parameter instead of Secret*. That // template parameter would deduce to 'long', making this a better match // than the first overload even without the first overload's EnableIf. // Unfortunately, gcc with -Wconversion-null warns when "passing NULL to // non-pointer argument" (even a deduced integral argument), so the old // implementation caused warnings in user code. Secret* /* lhs (NULL) */, T* rhs) { // We already know that 'lhs' is a null pointer. return CmpHelperEQ(lhs_expression, rhs_expression, static_cast<T*>(NULL), rhs); } }; // Separate the error generating code from the code path to reduce the stack // frame size of CmpHelperOP. This helps reduce the overhead of some sanitizers // when calling EXPECT_OP in a tight loop. template <typename T1, typename T2> AssertionResult CmpHelperOpFailure(const char* expr1, const char* expr2, const T1& val1, const T2& val2, const char* op) { return AssertionFailure() << "Expected: (" << expr1 << ") " << op << " (" << expr2 << "), actual: " << FormatForComparisonFailureMessage(val1, val2) << " vs " << FormatForComparisonFailureMessage(val2, val1); } // A macro for implementing the helper functions needed to implement // ASSERT_?? and EXPECT_??. It is here just to avoid copy-and-paste // of similar code. // // For each templatized helper function, we also define an overloaded // version for BiggestInt in order to reduce code bloat and allow // anonymous enums to be used with {ASSERT|EXPECT}_?? when compiled // with gcc 4. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. #define GTEST_IMPL_CMP_HELPER_(op_name, op)\ template <typename T1, typename T2>\ AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ const T1& val1, const T2& val2) {\ if (val1 op val2) {\ return AssertionSuccess();\ } else {\ return CmpHelperOpFailure(expr1, expr2, val1, val2, #op);\ }\ }\ GTEST_API_ AssertionResult CmpHelper##op_name(\ const char* expr1, const char* expr2, BiggestInt val1, BiggestInt val2) // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. // Implements the helper function for {ASSERT|EXPECT}_NE GTEST_IMPL_CMP_HELPER_(NE, !=); // Implements the helper function for {ASSERT|EXPECT}_LE GTEST_IMPL_CMP_HELPER_(LE, <=); // Implements the helper function for {ASSERT|EXPECT}_LT GTEST_IMPL_CMP_HELPER_(LT, <); // Implements the helper function for {ASSERT|EXPECT}_GE GTEST_IMPL_CMP_HELPER_(GE, >=); // Implements the helper function for {ASSERT|EXPECT}_GT GTEST_IMPL_CMP_HELPER_(GT, >); #undef GTEST_IMPL_CMP_HELPER_ // The helper function for {ASSERT|EXPECT}_STREQ. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression, const char* s2_expression, const char* s1, const char* s2); // The helper function for {ASSERT|EXPECT}_STRCASEEQ. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* s1_expression, const char* s2_expression, const char* s1, const char* s2); // The helper function for {ASSERT|EXPECT}_STRNE. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression, const char* s2_expression, const char* s1, const char* s2); // The helper function for {ASSERT|EXPECT}_STRCASENE. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression, const char* s2_expression, const char* s1, const char* s2); // Helper function for *_STREQ on wide strings. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. GTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression, const char* s2_expression, const wchar_t* s1, const wchar_t* s2); // Helper function for *_STRNE on wide strings. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression, const char* s2_expression, const wchar_t* s1, const wchar_t* s2); } // namespace internal // IsSubstring() and IsNotSubstring() are intended to be used as the // first argument to {EXPECT,ASSERT}_PRED_FORMAT2(), not by // themselves. They check whether needle is a substring of haystack // (NULL is considered a substring of itself only), and return an // appropriate error message when they fail. // // The {needle,haystack}_expr arguments are the stringified // expressions that generated the two real arguments. GTEST_API_ AssertionResult IsSubstring( const char* needle_expr, const char* haystack_expr, const char* needle, const char* haystack); GTEST_API_ AssertionResult IsSubstring( const char* needle_expr, const char* haystack_expr, const wchar_t* needle, const wchar_t* haystack); GTEST_API_ AssertionResult IsNotSubstring( const char* needle_expr, const char* haystack_expr, const char* needle, const char* haystack); GTEST_API_ AssertionResult IsNotSubstring( const char* needle_expr, const char* haystack_expr, const wchar_t* needle, const wchar_t* haystack); GTEST_API_ AssertionResult IsSubstring( const char* needle_expr, const char* haystack_expr, const ::std::string& needle, const ::std::string& haystack); GTEST_API_ AssertionResult IsNotSubstring( const char* needle_expr, const char* haystack_expr, const ::std::string& needle, const ::std::string& haystack); #if GTEST_HAS_STD_WSTRING GTEST_API_ AssertionResult IsSubstring( const char* needle_expr, const char* haystack_expr, const ::std::wstring& needle, const ::std::wstring& haystack); GTEST_API_ AssertionResult IsNotSubstring( const char* needle_expr, const char* haystack_expr, const ::std::wstring& needle, const ::std::wstring& haystack); #endif // GTEST_HAS_STD_WSTRING namespace internal { // Helper template function for comparing floating-points. // // Template parameter: // // RawType: the raw floating-point type (either float or double) // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. template <typename RawType> AssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression, const char* rhs_expression, RawType lhs_value, RawType rhs_value) { const FloatingPoint<RawType> lhs(lhs_value), rhs(rhs_value); if (lhs.AlmostEquals(rhs)) { return AssertionSuccess(); } ::std::stringstream lhs_ss; lhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2) << lhs_value; ::std::stringstream rhs_ss; rhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2) << rhs_value; return EqFailure(lhs_expression, rhs_expression, StringStreamToString(&lhs_ss), StringStreamToString(&rhs_ss), false); } // Helper function for implementing ASSERT_NEAR. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1, const char* expr2, const char* abs_error_expr, double val1, double val2, double abs_error); // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // A class that enables one to stream messages to assertion macros class GTEST_API_ AssertHelper { public: // Constructor. AssertHelper(TestPartResult::Type type, const char* file, int line, const char* message); ~AssertHelper(); // Message assignment is a semantic trick to enable assertion // streaming; see the GTEST_MESSAGE_ macro below. void operator=(const Message& message) const; private: // We put our data in a struct so that the size of the AssertHelper class can // be as small as possible. This is important because gcc is incapable of // re-using stack space even for temporary variables, so every EXPECT_EQ // reserves stack space for another AssertHelper. struct AssertHelperData { AssertHelperData(TestPartResult::Type t, const char* srcfile, int line_num, const char* msg) : type(t), file(srcfile), line(line_num), message(msg) { } TestPartResult::Type const type; const char* const file; int const line; std::string const message; private: GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelperData); }; AssertHelperData* const data_; GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelper); }; } // namespace internal #if GTEST_HAS_PARAM_TEST // The pure interface class that all value-parameterized tests inherit from. // A value-parameterized class must inherit from both ::testing::Test and // ::testing::WithParamInterface. In most cases that just means inheriting // from ::testing::TestWithParam, but more complicated test hierarchies // may need to inherit from Test and WithParamInterface at different levels. // // This interface has support for accessing the test parameter value via // the GetParam() method. // // Use it with one of the parameter generator defining functions, like Range(), // Values(), ValuesIn(), Bool(), and Combine(). // // class FooTest : public ::testing::TestWithParam<int> { // protected: // FooTest() { // // Can use GetParam() here. // } // virtual ~FooTest() { // // Can use GetParam() here. // } // virtual void SetUp() { // // Can use GetParam() here. // } // virtual void TearDown { // // Can use GetParam() here. // } // }; // TEST_P(FooTest, DoesBar) { // // Can use GetParam() method here. // Foo foo; // ASSERT_TRUE(foo.DoesBar(GetParam())); // } // INSTANTIATE_TEST_CASE_P(OneToTenRange, FooTest, ::testing::Range(1, 10)); template <typename T> class WithParamInterface { public: typedef T ParamType; virtual ~WithParamInterface() {} // The current parameter value. Is also available in the test fixture's // constructor. This member function is non-static, even though it only // references static data, to reduce the opportunity for incorrect uses // like writing 'WithParamInterface<bool>::GetParam()' for a test that // uses a fixture whose parameter type is int. const ParamType& GetParam() const { GTEST_CHECK_(parameter_ != NULL) << "GetParam() can only be called inside a value-parameterized test " << "-- did you intend to write TEST_P instead of TEST_F?"; return *parameter_; } private: // Sets parameter value. The caller is responsible for making sure the value // remains alive and unchanged throughout the current test. static void SetParam(const ParamType* parameter) { parameter_ = parameter; } // Static value used for accessing parameter during a test lifetime. static const ParamType* parameter_; // TestClass must be a subclass of WithParamInterface<T> and Test. template <class TestClass> friend class internal::ParameterizedTestFactory; }; template <typename T> const T* WithParamInterface<T>::parameter_ = NULL; // Most value-parameterized classes can ignore the existence of // WithParamInterface, and can just inherit from ::testing::TestWithParam. template <typename T> class TestWithParam : public Test, public WithParamInterface<T> { }; #endif // GTEST_HAS_PARAM_TEST // Macros for indicating success/failure in test code. // ADD_FAILURE unconditionally adds a failure to the current test. // SUCCEED generates a success - it doesn't automatically make the // current test successful, as a test is only successful when it has // no failure. // // EXPECT_* verifies that a certain condition is satisfied. If not, // it behaves like ADD_FAILURE. In particular: // // EXPECT_TRUE verifies that a Boolean condition is true. // EXPECT_FALSE verifies that a Boolean condition is false. // // FAIL and ASSERT_* are similar to ADD_FAILURE and EXPECT_*, except // that they will also abort the current function on failure. People // usually want the fail-fast behavior of FAIL and ASSERT_*, but those // writing data-driven tests often find themselves using ADD_FAILURE // and EXPECT_* more. // Generates a nonfatal failure with a generic message. #define ADD_FAILURE() GTEST_NONFATAL_FAILURE_("Failed") // Generates a nonfatal failure at the given source file location with // a generic message. #define ADD_FAILURE_AT(file, line) \ GTEST_MESSAGE_AT_(file, line, "Failed", \ ::testing::TestPartResult::kNonFatalFailure) // Generates a fatal failure with a generic message. #define GTEST_FAIL() GTEST_FATAL_FAILURE_("Failed") // Define this macro to 1 to omit the definition of FAIL(), which is a // generic name and clashes with some other libraries. #if !GTEST_DONT_DEFINE_FAIL # define FAIL() GTEST_FAIL() #endif // Generates a success with a generic message. #define GTEST_SUCCEED() GTEST_SUCCESS_("Succeeded") // Define this macro to 1 to omit the definition of SUCCEED(), which // is a generic name and clashes with some other libraries. #if !GTEST_DONT_DEFINE_SUCCEED # define SUCCEED() GTEST_SUCCEED() #endif // Macros for testing exceptions. // // * {ASSERT|EXPECT}_THROW(statement, expected_exception): // Tests that the statement throws the expected exception. // * {ASSERT|EXPECT}_NO_THROW(statement): // Tests that the statement doesn't throw any exception. // * {ASSERT|EXPECT}_ANY_THROW(statement): // Tests that the statement throws an exception. #define EXPECT_THROW(statement, expected_exception) \ GTEST_TEST_THROW_(statement, expected_exception, GTEST_NONFATAL_FAILURE_) #define EXPECT_NO_THROW(statement) \ GTEST_TEST_NO_THROW_(statement, GTEST_NONFATAL_FAILURE_) #define EXPECT_ANY_THROW(statement) \ GTEST_TEST_ANY_THROW_(statement, GTEST_NONFATAL_FAILURE_) #define ASSERT_THROW(statement, expected_exception) \ GTEST_TEST_THROW_(statement, expected_exception, GTEST_FATAL_FAILURE_) #define ASSERT_NO_THROW(statement) \ GTEST_TEST_NO_THROW_(statement, GTEST_FATAL_FAILURE_) #define ASSERT_ANY_THROW(statement) \ GTEST_TEST_ANY_THROW_(statement, GTEST_FATAL_FAILURE_) // Boolean assertions. Condition can be either a Boolean expression or an // AssertionResult. For more information on how to use AssertionResult with // these macros see comments on that class. #define EXPECT_TRUE(condition) \ GTEST_TEST_BOOLEAN_((condition), #condition, false, true, \ GTEST_NONFATAL_FAILURE_) #define EXPECT_FALSE(condition) \ GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \ GTEST_NONFATAL_FAILURE_) #define ASSERT_TRUE(condition) \ GTEST_TEST_BOOLEAN_((condition), #condition, false, true, \ GTEST_FATAL_FAILURE_) #define ASSERT_FALSE(condition) \ GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \ GTEST_FATAL_FAILURE_) // Includes the auto-generated header that implements a family of // generic predicate assertion macros. #include "gtest/gtest_pred_impl.h" // Macros for testing equalities and inequalities. // // * {ASSERT|EXPECT}_EQ(v1, v2): Tests that v1 == v2 // * {ASSERT|EXPECT}_NE(v1, v2): Tests that v1 != v2 // * {ASSERT|EXPECT}_LT(v1, v2): Tests that v1 < v2 // * {ASSERT|EXPECT}_LE(v1, v2): Tests that v1 <= v2 // * {ASSERT|EXPECT}_GT(v1, v2): Tests that v1 > v2 // * {ASSERT|EXPECT}_GE(v1, v2): Tests that v1 >= v2 // // When they are not, Google Test prints both the tested expressions and // their actual values. The values must be compatible built-in types, // or you will get a compiler error. By "compatible" we mean that the // values can be compared by the respective operator. // // Note: // // 1. It is possible to make a user-defined type work with // {ASSERT|EXPECT}_??(), but that requires overloading the // comparison operators and is thus discouraged by the Google C++ // Usage Guide. Therefore, you are advised to use the // {ASSERT|EXPECT}_TRUE() macro to assert that two objects are // equal. // // 2. The {ASSERT|EXPECT}_??() macros do pointer comparisons on // pointers (in particular, C strings). Therefore, if you use it // with two C strings, you are testing how their locations in memory // are related, not how their content is related. To compare two C // strings by content, use {ASSERT|EXPECT}_STR*(). // // 3. {ASSERT|EXPECT}_EQ(v1, v2) is preferred to // {ASSERT|EXPECT}_TRUE(v1 == v2), as the former tells you // what the actual value is when it fails, and similarly for the // other comparisons. // // 4. Do not depend on the order in which {ASSERT|EXPECT}_??() // evaluate their arguments, which is undefined. // // 5. These macros evaluate their arguments exactly once. // // Examples: // // EXPECT_NE(5, Foo()); // EXPECT_EQ(NULL, a_pointer); // ASSERT_LT(i, array_size); // ASSERT_GT(records.size(), 0) << "There is no record left."; #define EXPECT_EQ(val1, val2) \ EXPECT_PRED_FORMAT2(::testing::internal:: \ EqHelper<GTEST_IS_NULL_LITERAL_(val1)>::Compare, \ val1, val2) #define EXPECT_NE(val1, val2) \ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2) #define EXPECT_LE(val1, val2) \ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2) #define EXPECT_LT(val1, val2) \ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2) #define EXPECT_GE(val1, val2) \ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2) #define EXPECT_GT(val1, val2) \ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2) #define GTEST_ASSERT_EQ(val1, val2) \ ASSERT_PRED_FORMAT2(::testing::internal:: \ EqHelper<GTEST_IS_NULL_LITERAL_(val1)>::Compare, \ val1, val2) #define GTEST_ASSERT_NE(val1, val2) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2) #define GTEST_ASSERT_LE(val1, val2) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2) #define GTEST_ASSERT_LT(val1, val2) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2) #define GTEST_ASSERT_GE(val1, val2) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2) #define GTEST_ASSERT_GT(val1, val2) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2) // Define macro GTEST_DONT_DEFINE_ASSERT_XY to 1 to omit the definition of // ASSERT_XY(), which clashes with some users' own code. #if !GTEST_DONT_DEFINE_ASSERT_EQ # define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2) #endif #if !GTEST_DONT_DEFINE_ASSERT_NE # define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2) #endif #if !GTEST_DONT_DEFINE_ASSERT_LE # define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2) #endif #if !GTEST_DONT_DEFINE_ASSERT_LT # define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2) #endif #if !GTEST_DONT_DEFINE_ASSERT_GE # define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2) #endif #if !GTEST_DONT_DEFINE_ASSERT_GT # define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2) #endif // C-string Comparisons. All tests treat NULL and any non-NULL string // as different. Two NULLs are equal. // // * {ASSERT|EXPECT}_STREQ(s1, s2): Tests that s1 == s2 // * {ASSERT|EXPECT}_STRNE(s1, s2): Tests that s1 != s2 // * {ASSERT|EXPECT}_STRCASEEQ(s1, s2): Tests that s1 == s2, ignoring case // * {ASSERT|EXPECT}_STRCASENE(s1, s2): Tests that s1 != s2, ignoring case // // For wide or narrow string objects, you can use the // {ASSERT|EXPECT}_??() macros. // // Don't depend on the order in which the arguments are evaluated, // which is undefined. // // These macros evaluate their arguments exactly once. #define EXPECT_STREQ(s1, s2) \ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2) #define EXPECT_STRNE(s1, s2) \ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2) #define EXPECT_STRCASEEQ(s1, s2) \ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2) #define EXPECT_STRCASENE(s1, s2)\ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2) #define ASSERT_STREQ(s1, s2) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2) #define ASSERT_STRNE(s1, s2) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2) #define ASSERT_STRCASEEQ(s1, s2) \ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2) #define ASSERT_STRCASENE(s1, s2)\ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2) // Macros for comparing floating-point numbers. // // * {ASSERT|EXPECT}_FLOAT_EQ(val1, val2): // Tests that two float values are almost equal. // * {ASSERT|EXPECT}_DOUBLE_EQ(val1, val2): // Tests that two double values are almost equal. // * {ASSERT|EXPECT}_NEAR(v1, v2, abs_error): // Tests that v1 and v2 are within the given distance to each other. // // Google Test uses ULP-based comparison to automatically pick a default // error bound that is appropriate for the operands. See the // FloatingPoint template class in gtest-internal.h if you are // interested in the implementation details. #define EXPECT_FLOAT_EQ(val1, val2)\ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \ val1, val2) #define EXPECT_DOUBLE_EQ(val1, val2)\ EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \ val1, val2) #define ASSERT_FLOAT_EQ(val1, val2)\ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \ val1, val2) #define ASSERT_DOUBLE_EQ(val1, val2)\ ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \ val1, val2) #define EXPECT_NEAR(val1, val2, abs_error)\ EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \ val1, val2, abs_error) #define ASSERT_NEAR(val1, val2, abs_error)\ ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \ val1, val2, abs_error) // These predicate format functions work on floating-point values, and // can be used in {ASSERT|EXPECT}_PRED_FORMAT2*(), e.g. // // EXPECT_PRED_FORMAT2(testing::DoubleLE, Foo(), 5.0); // Asserts that val1 is less than, or almost equal to, val2. Fails // otherwise. In particular, it fails if either val1 or val2 is NaN. GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2, float val1, float val2); GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2, double val1, double val2); #if GTEST_OS_WINDOWS // Macros that test for HRESULT failure and success, these are only useful // on Windows, and rely on Windows SDK macros and APIs to compile. // // * {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}(expr) // // When expr unexpectedly fails or succeeds, Google Test prints the // expected result and the actual result with both a human-readable // string representation of the error, if available, as well as the // hex result code. # define EXPECT_HRESULT_SUCCEEDED(expr) \ EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr)) # define ASSERT_HRESULT_SUCCEEDED(expr) \ ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr)) # define EXPECT_HRESULT_FAILED(expr) \ EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr)) # define ASSERT_HRESULT_FAILED(expr) \ ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr)) #endif // GTEST_OS_WINDOWS // Macros that execute statement and check that it doesn't generate new fatal // failures in the current thread. // // * {ASSERT|EXPECT}_NO_FATAL_FAILURE(statement); // // Examples: // // EXPECT_NO_FATAL_FAILURE(Process()); // ASSERT_NO_FATAL_FAILURE(Process()) << "Process() failed"; // #define ASSERT_NO_FATAL_FAILURE(statement) \ GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_) #define EXPECT_NO_FATAL_FAILURE(statement) \ GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_) // Causes a trace (including the source file path, the current line // number, and the given message) to be included in every test failure // message generated by code in the current scope. The effect is // undone when the control leaves the current scope. // // The message argument can be anything streamable to std::ostream. // // In the implementation, we include the current line number as part // of the dummy variable name, thus allowing multiple SCOPED_TRACE()s // to appear in the same block - as long as they are on different // lines. #define SCOPED_TRACE(message) \ ::testing::internal::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\ __FILE__, __LINE__, ::testing::Message() << (message)) // Compile-time assertion for type equality. // StaticAssertTypeEq<type1, type2>() compiles iff type1 and type2 are // the same type. The value it returns is not interesting. // // Instead of making StaticAssertTypeEq a class template, we make it a // function template that invokes a helper class template. This // prevents a user from misusing StaticAssertTypeEq<T1, T2> by // defining objects of that type. // // CAVEAT: // // When used inside a method of a class template, // StaticAssertTypeEq<T1, T2>() is effective ONLY IF the method is // instantiated. For example, given: // // template <typename T> class Foo { // public: // void Bar() { testing::StaticAssertTypeEq<int, T>(); } // }; // // the code: // // void Test1() { Foo<bool> foo; } // // will NOT generate a compiler error, as Foo<bool>::Bar() is never // actually instantiated. Instead, you need: // // void Test2() { Foo<bool> foo; foo.Bar(); } // // to cause a compiler error. template <typename T1, typename T2> bool StaticAssertTypeEq() { (void)internal::StaticAssertTypeEqHelper<T1, T2>(); return true; } // Defines a test. // // The first parameter is the name of the test case, and the second // parameter is the name of the test within the test case. // // The convention is to end the test case name with "Test". For // example, a test case for the Foo class can be named FooTest. // // Test code should appear between braces after an invocation of // this macro. Example: // // TEST(FooTest, InitializesCorrectly) { // Foo foo; // EXPECT_TRUE(foo.StatusIsOK()); // } // Note that we call GetTestTypeId() instead of GetTypeId< // ::testing::Test>() here to get the type ID of testing::Test. This // is to work around a suspected linker bug when using Google Test as // a framework on Mac OS X. The bug causes GetTypeId< // ::testing::Test>() to return different values depending on whether // the call is from the Google Test framework itself or from user test // code. GetTestTypeId() is guaranteed to always return the same // value, as it always calls GetTypeId<>() from the Google Test // framework. #define GTEST_TEST(test_case_name, test_name)\ GTEST_TEST_(test_case_name, test_name, \ ::testing::Test, ::testing::internal::GetTestTypeId()) // Define this macro to 1 to omit the definition of TEST(), which // is a generic name and clashes with some other libraries. #if !GTEST_DONT_DEFINE_TEST # define TEST(test_case_name, test_name) GTEST_TEST(test_case_name, test_name) #endif // Defines a test that uses a test fixture. // // The first parameter is the name of the test fixture class, which // also doubles as the test case name. The second parameter is the // name of the test within the test case. // // A test fixture class must be declared earlier. The user should put // his test code between braces after using this macro. Example: // // class FooTest : public testing::Test { // protected: // virtual void SetUp() { b_.AddElement(3); } // // Foo a_; // Foo b_; // }; // // TEST_F(FooTest, InitializesCorrectly) { // EXPECT_TRUE(a_.StatusIsOK()); // } // // TEST_F(FooTest, ReturnsElementCountCorrectly) { // EXPECT_EQ(0, a_.size()); // EXPECT_EQ(1, b_.size()); // } #define TEST_F(test_fixture, test_name)\ GTEST_TEST_(test_fixture, test_name, test_fixture, \ ::testing::internal::GetTypeId<test_fixture>()) } // namespace testing // Use this function in main() to run all tests. It returns 0 if all // tests are successful, or 1 otherwise. // // RUN_ALL_TESTS() should be invoked after the command line has been // parsed by InitGoogleTest(). // // This function was formerly a macro; thus, it is in the global // namespace and has an all-caps name. int RUN_ALL_TESTS() GTEST_MUST_USE_RESULT_; inline int RUN_ALL_TESTS() { return ::testing::UnitTest::GetInstance()->Run(); } #endif // GTEST_INCLUDE_GTEST_GTEST_H_
0
repos/DirectXShaderCompiler/utils/unittest/googletest/include
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest/gtest-spi.h
// 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. // // Author: [email protected] (Zhanyong Wan) // // Utilities for testing Google Test itself and code that uses Google Test // (e.g. frameworks built on top of Google Test). #ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_ #define GTEST_INCLUDE_GTEST_GTEST_SPI_H_ #include "gtest/gtest.h" namespace testing { // This helper class can be used to mock out Google Test failure reporting // so that we can test Google Test or code that builds on Google Test. // // An object of this class appends a TestPartResult object to the // TestPartResultArray object given in the constructor whenever a Google Test // failure is reported. It can either intercept only failures that are // generated in the same thread that created this object or it can intercept // all generated failures. The scope of this mock object can be controlled with // the second argument to the two arguments constructor. class GTEST_API_ ScopedFakeTestPartResultReporter : public TestPartResultReporterInterface { public: // The two possible mocking modes of this object. enum InterceptMode { INTERCEPT_ONLY_CURRENT_THREAD, // Intercepts only thread local failures. INTERCEPT_ALL_THREADS // Intercepts all failures. }; // The c'tor sets this object as the test part result reporter used // by Google Test. The 'result' parameter specifies where to report the // results. This reporter will only catch failures generated in the current // thread. DEPRECATED explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result); // Same as above, but you can choose the interception scope of this object. ScopedFakeTestPartResultReporter(InterceptMode intercept_mode, TestPartResultArray* result); // The d'tor restores the previous test part result reporter. virtual ~ScopedFakeTestPartResultReporter(); // Appends the TestPartResult object to the TestPartResultArray // received in the constructor. // // This method is from the TestPartResultReporterInterface // interface. virtual void ReportTestPartResult(const TestPartResult& result); private: void Init(); const InterceptMode intercept_mode_; TestPartResultReporterInterface* old_reporter_; TestPartResultArray* const result_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter); }; namespace internal { // A helper class for implementing EXPECT_FATAL_FAILURE() and // EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given // TestPartResultArray contains exactly one failure that has the given // type and contains the given substring. If that's not the case, a // non-fatal failure will be generated. class GTEST_API_ SingleFailureChecker { public: // The constructor remembers the arguments. SingleFailureChecker(const TestPartResultArray* results, TestPartResult::Type type, const string& substr); ~SingleFailureChecker(); private: const TestPartResultArray* const results_; const TestPartResult::Type type_; const string substr_; GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker); }; } // namespace internal } // namespace testing // A set of macros for testing Google Test assertions or code that's expected // to generate Google Test fatal failures. It verifies that the given // statement will cause exactly one fatal Google Test failure with 'substr' // being part of the failure message. // // There are two different versions of this macro. EXPECT_FATAL_FAILURE only // affects and considers failures generated in the current thread and // EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads. // // The verification of the assertion is done correctly even when the statement // throws an exception or aborts the current function. // // Known restrictions: // - 'statement' cannot reference local non-static variables or // non-static members of the current object. // - 'statement' cannot return a value. // - You cannot stream a failure message to this macro. // // Note that even though the implementations of the following two // macros are much alike, we cannot refactor them to use a common // helper macro, due to some peculiarity in how the preprocessor // works. The AcceptsMacroThatExpandsToUnprotectedComma test in // gtest_unittest.cc will fail to compile if we do that. #define EXPECT_FATAL_FAILURE(statement, substr) \ do { \ class GTestExpectFatalFailureHelper {\ public:\ static void Execute() { statement; }\ };\ ::testing::TestPartResultArray gtest_failures;\ ::testing::internal::SingleFailureChecker gtest_checker(\ &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\ {\ ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ ::testing::ScopedFakeTestPartResultReporter:: \ INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\ GTestExpectFatalFailureHelper::Execute();\ }\ } while (::testing::internal::AlwaysFalse()) #define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ do { \ class GTestExpectFatalFailureHelper {\ public:\ static void Execute() { statement; }\ };\ ::testing::TestPartResultArray gtest_failures;\ ::testing::internal::SingleFailureChecker gtest_checker(\ &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\ {\ ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ ::testing::ScopedFakeTestPartResultReporter:: \ INTERCEPT_ALL_THREADS, &gtest_failures);\ GTestExpectFatalFailureHelper::Execute();\ }\ } while (::testing::internal::AlwaysFalse()) // A macro for testing Google Test assertions or code that's expected to // generate Google Test non-fatal failures. It asserts that the given // statement will cause exactly one non-fatal Google Test failure with 'substr' // being part of the failure message. // // There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only // affects and considers failures generated in the current thread and // EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads. // // 'statement' is allowed to reference local variables and members of // the current object. // // The verification of the assertion is done correctly even when the statement // throws an exception or aborts the current function. // // Known restrictions: // - You cannot stream a failure message to this macro. // // Note that even though the implementations of the following two // macros are much alike, we cannot refactor them to use a common // helper macro, due to some peculiarity in how the preprocessor // works. If we do that, the code won't compile when the user gives // EXPECT_NONFATAL_FAILURE() a statement that contains a macro that // expands to code containing an unprotected comma. The // AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc // catches that. // // For the same reason, we have to write // if (::testing::internal::AlwaysTrue()) { statement; } // instead of // GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) // to avoid an MSVC warning on unreachable code. #define EXPECT_NONFATAL_FAILURE(statement, substr) \ do {\ ::testing::TestPartResultArray gtest_failures;\ ::testing::internal::SingleFailureChecker gtest_checker(\ &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \ (substr));\ {\ ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ ::testing::ScopedFakeTestPartResultReporter:: \ INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\ if (::testing::internal::AlwaysTrue()) { statement; }\ }\ } while (::testing::internal::AlwaysFalse()) #define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ do {\ ::testing::TestPartResultArray gtest_failures;\ ::testing::internal::SingleFailureChecker gtest_checker(\ &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \ (substr));\ {\ ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \ &gtest_failures);\ if (::testing::internal::AlwaysTrue()) { statement; }\ }\ } while (::testing::internal::AlwaysFalse()) #endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_
0
repos/DirectXShaderCompiler/utils/unittest/googletest/include
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest/gtest-param-test.h
// This file was GENERATED by command: // pump.py gtest-param-test.h.pump // DO NOT EDIT BY HAND!!! // 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. // // Authors: [email protected] (Vlad Losev) // // Macros and functions for implementing parameterized tests // in Google C++ Testing Framework (Google Test) // // This file is generated by a SCRIPT. DO NOT EDIT BY HAND! // #ifndef GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ #define GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_ // Value-parameterized tests allow you to test your code with different // parameters without writing multiple copies of the same test. // // Here is how you use value-parameterized tests: #if 0 // To write value-parameterized tests, first you should define a fixture // class. It is usually derived from testing::TestWithParam<T> (see below for // another inheritance scheme that's sometimes useful in more complicated // class hierarchies), where the type of your parameter values. // TestWithParam<T> is itself derived from testing::Test. T can be any // copyable type. If it's a raw pointer, you are responsible for managing the // lifespan of the pointed values. class FooTest : public ::testing::TestWithParam<const char*> { // You can implement all the usual class fixture members here. }; // Then, use the TEST_P macro to define as many parameterized tests // for this fixture as you want. The _P suffix is for "parameterized" // or "pattern", whichever you prefer to think. TEST_P(FooTest, DoesBlah) { // Inside a test, access the test parameter with the GetParam() method // of the TestWithParam<T> class: EXPECT_TRUE(foo.Blah(GetParam())); ... } TEST_P(FooTest, HasBlahBlah) { ... } // Finally, you can use INSTANTIATE_TEST_CASE_P to instantiate the test // case with any set of parameters you want. Google Test defines a number // of functions for generating test parameters. They return what we call // (surprise!) parameter generators. Here is a summary of them, which // are all in the testing namespace: // // // Range(begin, end [, step]) - Yields values {begin, begin+step, // begin+step+step, ...}. The values do not // include end. step defaults to 1. // Values(v1, v2, ..., vN) - Yields values {v1, v2, ..., vN}. // ValuesIn(container) - Yields values from a C-style array, an STL // ValuesIn(begin,end) container, or an iterator range [begin, end). // Bool() - Yields sequence {false, true}. // Combine(g1, g2, ..., gN) - Yields all combinations (the Cartesian product // for the math savvy) of the values generated // by the N generators. // // For more details, see comments at the definitions of these functions below // in this file. // // The following statement will instantiate tests from the FooTest test case // each with parameter values "meeny", "miny", and "moe". INSTANTIATE_TEST_CASE_P(InstantiationName, FooTest, Values("meeny", "miny", "moe")); // To distinguish different instances of the pattern, (yes, you // can instantiate it more then once) the first argument to the // INSTANTIATE_TEST_CASE_P macro is a prefix that will be added to the // actual test case name. Remember to pick unique prefixes for different // instantiations. The tests from the instantiation above will have // these names: // // * InstantiationName/FooTest.DoesBlah/0 for "meeny" // * InstantiationName/FooTest.DoesBlah/1 for "miny" // * InstantiationName/FooTest.DoesBlah/2 for "moe" // * InstantiationName/FooTest.HasBlahBlah/0 for "meeny" // * InstantiationName/FooTest.HasBlahBlah/1 for "miny" // * InstantiationName/FooTest.HasBlahBlah/2 for "moe" // // You can use these names in --gtest_filter. // // This statement will instantiate all tests from FooTest again, each // with parameter values "cat" and "dog": const char* pets[] = {"cat", "dog"}; INSTANTIATE_TEST_CASE_P(AnotherInstantiationName, FooTest, ValuesIn(pets)); // The tests from the instantiation above will have these names: // // * AnotherInstantiationName/FooTest.DoesBlah/0 for "cat" // * AnotherInstantiationName/FooTest.DoesBlah/1 for "dog" // * AnotherInstantiationName/FooTest.HasBlahBlah/0 for "cat" // * AnotherInstantiationName/FooTest.HasBlahBlah/1 for "dog" // // Please note that INSTANTIATE_TEST_CASE_P will instantiate all tests // in the given test case, whether their definitions come before or // AFTER the INSTANTIATE_TEST_CASE_P statement. // // Please also note that generator expressions (including parameters to the // generators) are evaluated in InitGoogleTest(), after main() has started. // This allows the user on one hand, to adjust generator parameters in order // to dynamically determine a set of tests to run and on the other hand, // give the user a chance to inspect the generated tests with Google Test // reflection API before RUN_ALL_TESTS() is executed. // // You can see samples/sample7_unittest.cc and samples/sample8_unittest.cc // for more examples. // // In the future, we plan to publish the API for defining new parameter // generators. But for now this interface remains part of the internal // implementation and is subject to change. // // // A parameterized test fixture must be derived from testing::Test and from // testing::WithParamInterface<T>, where T is the type of the parameter // values. Inheriting from TestWithParam<T> satisfies that requirement because // TestWithParam<T> inherits from both Test and WithParamInterface. In more // complicated hierarchies, however, it is occasionally useful to inherit // separately from Test and WithParamInterface. For example: class BaseTest : public ::testing::Test { // You can inherit all the usual members for a non-parameterized test // fixture here. }; class DerivedTest : public BaseTest, public ::testing::WithParamInterface<int> { // The usual test fixture members go here too. }; TEST_F(BaseTest, HasFoo) { // This is an ordinary non-parameterized test. } TEST_P(DerivedTest, DoesBlah) { // GetParam works just the same here as if you inherit from TestWithParam. EXPECT_TRUE(foo.Blah(GetParam())); } #endif // 0 #include "gtest/internal/gtest-port.h" #if !GTEST_OS_SYMBIAN # include <utility> #endif // scripts/fuse_gtest.py depends on gtest's own header being #included // *unconditionally*. Therefore these #includes cannot be moved // inside #if GTEST_HAS_PARAM_TEST. #include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-param-util.h" #include "gtest/internal/gtest-param-util-generated.h" #if GTEST_HAS_PARAM_TEST namespace testing { // Functions producing parameter generators. // // Google Test uses these generators to produce parameters for value- // parameterized tests. When a parameterized test case is instantiated // with a particular generator, Google Test creates and runs tests // for each element in the sequence produced by the generator. // // In the following sample, tests from test case FooTest are instantiated // each three times with parameter values 3, 5, and 8: // // class FooTest : public TestWithParam<int> { ... }; // // TEST_P(FooTest, TestThis) { // } // TEST_P(FooTest, TestThat) { // } // INSTANTIATE_TEST_CASE_P(TestSequence, FooTest, Values(3, 5, 8)); // // Range() returns generators providing sequences of values in a range. // // Synopsis: // Range(start, end) // - returns a generator producing a sequence of values {start, start+1, // start+2, ..., }. // Range(start, end, step) // - returns a generator producing a sequence of values {start, start+step, // start+step+step, ..., }. // Notes: // * The generated sequences never include end. For example, Range(1, 5) // returns a generator producing a sequence {1, 2, 3, 4}. Range(1, 9, 2) // returns a generator producing {1, 3, 5, 7}. // * start and end must have the same type. That type may be any integral or // floating-point type or a user defined type satisfying these conditions: // * It must be assignable (have operator=() defined). // * It must have operator+() (operator+(int-compatible type) for // two-operand version). // * It must have operator<() defined. // Elements in the resulting sequences will also have that type. // * Condition start < end must be satisfied in order for resulting sequences // to contain any elements. // template <typename T, typename IncrementT> internal::ParamGenerator<T> Range(T start, T end, IncrementT step) { return internal::ParamGenerator<T>( new internal::RangeGenerator<T, IncrementT>(start, end, step)); } template <typename T> internal::ParamGenerator<T> Range(T start, T end) { return Range(start, end, 1); } // ValuesIn() function allows generation of tests with parameters coming from // a container. // // Synopsis: // ValuesIn(const T (&array)[N]) // - returns a generator producing sequences with elements from // a C-style array. // ValuesIn(const Container& container) // - returns a generator producing sequences with elements from // an STL-style container. // ValuesIn(Iterator begin, Iterator end) // - returns a generator producing sequences with elements from // a range [begin, end) defined by a pair of STL-style iterators. These // iterators can also be plain C pointers. // // Please note that ValuesIn copies the values from the containers // passed in and keeps them to generate tests in RUN_ALL_TESTS(). // // Examples: // // This instantiates tests from test case StringTest // each with C-string values of "foo", "bar", and "baz": // // const char* strings[] = {"foo", "bar", "baz"}; // INSTANTIATE_TEST_CASE_P(StringSequence, SrtingTest, ValuesIn(strings)); // // This instantiates tests from test case StlStringTest // each with STL strings with values "a" and "b": // // ::std::vector< ::std::string> GetParameterStrings() { // ::std::vector< ::std::string> v; // v.push_back("a"); // v.push_back("b"); // return v; // } // // INSTANTIATE_TEST_CASE_P(CharSequence, // StlStringTest, // ValuesIn(GetParameterStrings())); // // // This will also instantiate tests from CharTest // each with parameter values 'a' and 'b': // // ::std::list<char> GetParameterChars() { // ::std::list<char> list; // list.push_back('a'); // list.push_back('b'); // return list; // } // ::std::list<char> l = GetParameterChars(); // INSTANTIATE_TEST_CASE_P(CharSequence2, // CharTest, // ValuesIn(l.begin(), l.end())); // template <typename ForwardIterator> internal::ParamGenerator< typename ::testing::internal::IteratorTraits<ForwardIterator>::value_type> ValuesIn(ForwardIterator begin, ForwardIterator end) { typedef typename ::testing::internal::IteratorTraits<ForwardIterator> ::value_type ParamType; return internal::ParamGenerator<ParamType>( new internal::ValuesInIteratorRangeGenerator<ParamType>(begin, end)); } template <typename T, size_t N> internal::ParamGenerator<T> ValuesIn(const T (&array)[N]) { return ValuesIn(array, array + N); } template <class Container> internal::ParamGenerator<typename Container::value_type> ValuesIn( const Container& container) { return ValuesIn(container.begin(), container.end()); } // Values() allows generating tests from explicitly specified list of // parameters. // // Synopsis: // Values(T v1, T v2, ..., T vN) // - returns a generator producing sequences with elements v1, v2, ..., vN. // // For example, this instantiates tests from test case BarTest each // with values "one", "two", and "three": // // INSTANTIATE_TEST_CASE_P(NumSequence, BarTest, Values("one", "two", "three")); // // This instantiates tests from test case BazTest each with values 1, 2, 3.5. // The exact type of values will depend on the type of parameter in BazTest. // // INSTANTIATE_TEST_CASE_P(FloatingNumbers, BazTest, Values(1, 2, 3.5)); // // Currently, Values() supports from 1 to 50 parameters. // template <typename T1> internal::ValueArray1<T1> Values(T1 v1) { return internal::ValueArray1<T1>(v1); } template <typename T1, typename T2> internal::ValueArray2<T1, T2> Values(T1 v1, T2 v2) { return internal::ValueArray2<T1, T2>(v1, v2); } template <typename T1, typename T2, typename T3> internal::ValueArray3<T1, T2, T3> Values(T1 v1, T2 v2, T3 v3) { return internal::ValueArray3<T1, T2, T3>(v1, v2, v3); } template <typename T1, typename T2, typename T3, typename T4> internal::ValueArray4<T1, T2, T3, T4> Values(T1 v1, T2 v2, T3 v3, T4 v4) { return internal::ValueArray4<T1, T2, T3, T4>(v1, v2, v3, v4); } template <typename T1, typename T2, typename T3, typename T4, typename T5> internal::ValueArray5<T1, T2, T3, T4, T5> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5) { return internal::ValueArray5<T1, T2, T3, T4, T5>(v1, v2, v3, v4, v5); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6> internal::ValueArray6<T1, T2, T3, T4, T5, T6> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6) { return internal::ValueArray6<T1, T2, T3, T4, T5, T6>(v1, v2, v3, v4, v5, v6); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7> internal::ValueArray7<T1, T2, T3, T4, T5, T6, T7> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7) { return internal::ValueArray7<T1, T2, T3, T4, T5, T6, T7>(v1, v2, v3, v4, v5, v6, v7); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8> internal::ValueArray8<T1, T2, T3, T4, T5, T6, T7, T8> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8) { return internal::ValueArray8<T1, T2, T3, T4, T5, T6, T7, T8>(v1, v2, v3, v4, v5, v6, v7, v8); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9> internal::ValueArray9<T1, T2, T3, T4, T5, T6, T7, T8, T9> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9) { return internal::ValueArray9<T1, T2, T3, T4, T5, T6, T7, T8, T9>(v1, v2, v3, v4, v5, v6, v7, v8, v9); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10> internal::ValueArray10<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10) { return internal::ValueArray10<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11> internal::ValueArray11<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11) { return internal::ValueArray11<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12> internal::ValueArray12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12) { return internal::ValueArray12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13> internal::ValueArray13<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13) { return internal::ValueArray13<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14> internal::ValueArray14<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14) { return internal::ValueArray14<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15> internal::ValueArray15<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15) { return internal::ValueArray15<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16> internal::ValueArray16<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16) { return internal::ValueArray16<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17> internal::ValueArray17<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17) { return internal::ValueArray17<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18> internal::ValueArray18<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18) { return internal::ValueArray18<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19> internal::ValueArray19<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19) { return internal::ValueArray19<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20> internal::ValueArray20<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20) { return internal::ValueArray20<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21> internal::ValueArray21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21) { return internal::ValueArray21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22> internal::ValueArray22<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22) { return internal::ValueArray22<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23> internal::ValueArray23<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23) { return internal::ValueArray23<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24> internal::ValueArray24<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24) { return internal::ValueArray24<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25> internal::ValueArray25<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25) { return internal::ValueArray25<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26> internal::ValueArray26<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26) { return internal::ValueArray26<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27> internal::ValueArray27<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27) { return internal::ValueArray27<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28> internal::ValueArray28<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28) { return internal::ValueArray28<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29> internal::ValueArray29<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29) { return internal::ValueArray29<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30> internal::ValueArray30<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30) { return internal::ValueArray30<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31> internal::ValueArray31<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31) { return internal::ValueArray31<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32> internal::ValueArray32<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32) { return internal::ValueArray32<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33> internal::ValueArray33<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33) { return internal::ValueArray33<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34> internal::ValueArray34<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34) { return internal::ValueArray34<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35> internal::ValueArray35<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35) { return internal::ValueArray35<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36> internal::ValueArray36<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36) { return internal::ValueArray36<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37> internal::ValueArray37<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37) { return internal::ValueArray37<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38> internal::ValueArray38<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38) { return internal::ValueArray38<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39> internal::ValueArray39<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39) { return internal::ValueArray39<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40> internal::ValueArray40<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40) { return internal::ValueArray40<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41> internal::ValueArray41<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41) { return internal::ValueArray41<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42> internal::ValueArray42<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42) { return internal::ValueArray42<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43> internal::ValueArray43<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43) { return internal::ValueArray43<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43, typename T44> internal::ValueArray44<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44) { return internal::ValueArray44<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43, typename T44, typename T45> internal::ValueArray45<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45) { return internal::ValueArray45<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43, typename T44, typename T45, typename T46> internal::ValueArray46<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46) { return internal::ValueArray46<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43, typename T44, typename T45, typename T46, typename T47> internal::ValueArray47<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, T47> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47) { return internal::ValueArray47<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, T47>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43, typename T44, typename T45, typename T46, typename T47, typename T48> internal::ValueArray48<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, T47, T48> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, T48 v48) { return internal::ValueArray48<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, T47, T48>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43, typename T44, typename T45, typename T46, typename T47, typename T48, typename T49> internal::ValueArray49<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, T47, T48, T49> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, T48 v48, T49 v49) { return internal::ValueArray49<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, T47, T48, T49>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43, typename T44, typename T45, typename T46, typename T47, typename T48, typename T49, typename T50> internal::ValueArray50<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, T47, T48, T49, T50> Values(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, T48 v48, T49 v49, T50 v50) { return internal::ValueArray50<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, T47, T48, T49, T50>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50); } // Bool() allows generating tests with parameters in a set of (false, true). // // Synopsis: // Bool() // - returns a generator producing sequences with elements {false, true}. // // It is useful when testing code that depends on Boolean flags. Combinations // of multiple flags can be tested when several Bool()'s are combined using // Combine() function. // // In the following example all tests in the test case FlagDependentTest // will be instantiated twice with parameters false and true. // // class FlagDependentTest : public testing::TestWithParam<bool> { // virtual void SetUp() { // external_flag = GetParam(); // } // } // INSTANTIATE_TEST_CASE_P(BoolSequence, FlagDependentTest, Bool()); // inline internal::ParamGenerator<bool> Bool() { return Values(false, true); } # if GTEST_HAS_COMBINE // Combine() allows the user to combine two or more sequences to produce // values of a Cartesian product of those sequences' elements. // // Synopsis: // Combine(gen1, gen2, ..., genN) // - returns a generator producing sequences with elements coming from // the Cartesian product of elements from the sequences generated by // gen1, gen2, ..., genN. The sequence elements will have a type of // tuple<T1, T2, ..., TN> where T1, T2, ..., TN are the types // of elements from sequences produces by gen1, gen2, ..., genN. // // Combine can have up to 10 arguments. This number is currently limited // by the maximum number of elements in the tuple implementation used by Google // Test. // // Example: // // This will instantiate tests in test case AnimalTest each one with // the parameter values tuple("cat", BLACK), tuple("cat", WHITE), // tuple("dog", BLACK), and tuple("dog", WHITE): // // enum Color { BLACK, GRAY, WHITE }; // class AnimalTest // : public testing::TestWithParam<tuple<const char*, Color> > {...}; // // TEST_P(AnimalTest, AnimalLooksNice) {...} // // INSTANTIATE_TEST_CASE_P(AnimalVariations, AnimalTest, // Combine(Values("cat", "dog"), // Values(BLACK, WHITE))); // // This will instantiate tests in FlagDependentTest with all variations of two // Boolean flags: // // class FlagDependentTest // : public testing::TestWithParam<tuple<bool, bool> > { // virtual void SetUp() { // // Assigns external_flag_1 and external_flag_2 values from the tuple. // tie(external_flag_1, external_flag_2) = GetParam(); // } // }; // // TEST_P(FlagDependentTest, TestFeature1) { // // Test your code using external_flag_1 and external_flag_2 here. // } // INSTANTIATE_TEST_CASE_P(TwoBoolSequence, FlagDependentTest, // Combine(Bool(), Bool())); // template <typename Generator1, typename Generator2> internal::CartesianProductHolder2<Generator1, Generator2> Combine( const Generator1& g1, const Generator2& g2) { return internal::CartesianProductHolder2<Generator1, Generator2>( g1, g2); } template <typename Generator1, typename Generator2, typename Generator3> internal::CartesianProductHolder3<Generator1, Generator2, Generator3> Combine( const Generator1& g1, const Generator2& g2, const Generator3& g3) { return internal::CartesianProductHolder3<Generator1, Generator2, Generator3>( g1, g2, g3); } template <typename Generator1, typename Generator2, typename Generator3, typename Generator4> internal::CartesianProductHolder4<Generator1, Generator2, Generator3, Generator4> Combine( const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4) { return internal::CartesianProductHolder4<Generator1, Generator2, Generator3, Generator4>( g1, g2, g3, g4); } template <typename Generator1, typename Generator2, typename Generator3, typename Generator4, typename Generator5> internal::CartesianProductHolder5<Generator1, Generator2, Generator3, Generator4, Generator5> Combine( const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, const Generator5& g5) { return internal::CartesianProductHolder5<Generator1, Generator2, Generator3, Generator4, Generator5>( g1, g2, g3, g4, g5); } template <typename Generator1, typename Generator2, typename Generator3, typename Generator4, typename Generator5, typename Generator6> internal::CartesianProductHolder6<Generator1, Generator2, Generator3, Generator4, Generator5, Generator6> Combine( const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, const Generator5& g5, const Generator6& g6) { return internal::CartesianProductHolder6<Generator1, Generator2, Generator3, Generator4, Generator5, Generator6>( g1, g2, g3, g4, g5, g6); } template <typename Generator1, typename Generator2, typename Generator3, typename Generator4, typename Generator5, typename Generator6, typename Generator7> internal::CartesianProductHolder7<Generator1, Generator2, Generator3, Generator4, Generator5, Generator6, Generator7> Combine( const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, const Generator5& g5, const Generator6& g6, const Generator7& g7) { return internal::CartesianProductHolder7<Generator1, Generator2, Generator3, Generator4, Generator5, Generator6, Generator7>( g1, g2, g3, g4, g5, g6, g7); } template <typename Generator1, typename Generator2, typename Generator3, typename Generator4, typename Generator5, typename Generator6, typename Generator7, typename Generator8> internal::CartesianProductHolder8<Generator1, Generator2, Generator3, Generator4, Generator5, Generator6, Generator7, Generator8> Combine( const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, const Generator5& g5, const Generator6& g6, const Generator7& g7, const Generator8& g8) { return internal::CartesianProductHolder8<Generator1, Generator2, Generator3, Generator4, Generator5, Generator6, Generator7, Generator8>( g1, g2, g3, g4, g5, g6, g7, g8); } template <typename Generator1, typename Generator2, typename Generator3, typename Generator4, typename Generator5, typename Generator6, typename Generator7, typename Generator8, typename Generator9> internal::CartesianProductHolder9<Generator1, Generator2, Generator3, Generator4, Generator5, Generator6, Generator7, Generator8, Generator9> Combine( const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, const Generator5& g5, const Generator6& g6, const Generator7& g7, const Generator8& g8, const Generator9& g9) { return internal::CartesianProductHolder9<Generator1, Generator2, Generator3, Generator4, Generator5, Generator6, Generator7, Generator8, Generator9>( g1, g2, g3, g4, g5, g6, g7, g8, g9); } template <typename Generator1, typename Generator2, typename Generator3, typename Generator4, typename Generator5, typename Generator6, typename Generator7, typename Generator8, typename Generator9, typename Generator10> internal::CartesianProductHolder10<Generator1, Generator2, Generator3, Generator4, Generator5, Generator6, Generator7, Generator8, Generator9, Generator10> Combine( const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, const Generator5& g5, const Generator6& g6, const Generator7& g7, const Generator8& g8, const Generator9& g9, const Generator10& g10) { return internal::CartesianProductHolder10<Generator1, Generator2, Generator3, Generator4, Generator5, Generator6, Generator7, Generator8, Generator9, Generator10>( g1, g2, g3, g4, g5, g6, g7, g8, g9, g10); } # endif // GTEST_HAS_COMBINE # define TEST_P(test_case_name, test_name) \ class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \ : public test_case_name { \ public: \ GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {} \ virtual void TestBody(); \ private: \ static int AddToRegistry() { \ ::testing::UnitTest::GetInstance()->parameterized_test_registry(). \ GetTestCasePatternHolder<test_case_name>(\ #test_case_name, \ ::testing::internal::CodeLocation(\ __FILE__, __LINE__))->AddTestPattern(\ #test_case_name, \ #test_name, \ new ::testing::internal::TestMetaFactory< \ GTEST_TEST_CLASS_NAME_(\ test_case_name, test_name)>()); \ return 0; \ } \ static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_; \ GTEST_DISALLOW_COPY_AND_ASSIGN_(\ GTEST_TEST_CLASS_NAME_(test_case_name, test_name)); \ }; \ int GTEST_TEST_CLASS_NAME_(test_case_name, \ test_name)::gtest_registering_dummy_ = \ GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::AddToRegistry(); \ void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody() // The optional last argument to INSTANTIATE_TEST_CASE_P allows the user // to specify a function or functor that generates custom test name suffixes // based on the test parameters. The function should accept one argument of // type testing::TestParamInfo<class ParamType>, and return std::string. // // testing::PrintToStringParamName is a builtin test suffix generator that // returns the value of testing::PrintToString(GetParam()). It does not work // for std::string or C strings. // // Note: test names must be non-empty, unique, and may only contain ASCII // alphanumeric characters or underscore. # define INSTANTIATE_TEST_CASE_P(prefix, test_case_name, generator, ...) \ ::testing::internal::ParamGenerator<test_case_name::ParamType> \ gtest_##prefix##test_case_name##_EvalGenerator_() { return generator; } \ ::std::string gtest_##prefix##test_case_name##_EvalGenerateName_( \ const ::testing::TestParamInfo<test_case_name::ParamType>& info) { \ return ::testing::internal::GetParamNameGen<test_case_name::ParamType> \ (__VA_ARGS__)(info); \ } \ int gtest_##prefix##test_case_name##_dummy_ GTEST_ATTRIBUTE_UNUSED_ = \ ::testing::UnitTest::GetInstance()->parameterized_test_registry(). \ GetTestCasePatternHolder<test_case_name>(\ #test_case_name, \ ::testing::internal::CodeLocation(\ __FILE__, __LINE__))->AddTestCaseInstantiation(\ #prefix, \ &gtest_##prefix##test_case_name##_EvalGenerator_, \ &gtest_##prefix##test_case_name##_EvalGenerateName_, \ __FILE__, __LINE__) } // namespace testing #endif // GTEST_HAS_PARAM_TEST #endif // GTEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_
0
repos/DirectXShaderCompiler/utils/unittest/googletest/include
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest/gtest_pred_impl.h
// Copyright 2006, 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. // This file is AUTOMATICALLY GENERATED on 10/31/2011 by command // 'gen_gtest_pred_impl.py 5'. DO NOT EDIT BY HAND! // // Implements a family of generic predicate assertion macros. #ifndef GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ #define GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_ // Makes sure this header is not included before gtest.h. #ifndef GTEST_INCLUDE_GTEST_GTEST_H_ # error Do not include gtest_pred_impl.h directly. Include gtest.h instead. #endif // GTEST_INCLUDE_GTEST_GTEST_H_ // This header implements a family of generic predicate assertion // macros: // // ASSERT_PRED_FORMAT1(pred_format, v1) // ASSERT_PRED_FORMAT2(pred_format, v1, v2) // ... // // where pred_format is a function or functor that takes n (in the // case of ASSERT_PRED_FORMATn) values and their source expression // text, and returns a testing::AssertionResult. See the definition // of ASSERT_EQ in gtest.h for an example. // // If you don't care about formatting, you can use the more // restrictive version: // // ASSERT_PRED1(pred, v1) // ASSERT_PRED2(pred, v1, v2) // ... // // where pred is an n-ary function or functor that returns bool, // and the values v1, v2, ..., must support the << operator for // streaming to std::ostream. // // We also define the EXPECT_* variations. // // For now we only support predicates whose arity is at most 5. // Please email [email protected] if you need // support for higher arities. // GTEST_ASSERT_ is the basic statement to which all of the assertions // in this file reduce. Don't use this in your code. #define GTEST_ASSERT_(expression, on_failure) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (const ::testing::AssertionResult gtest_ar = (expression)) \ ; \ else \ on_failure(gtest_ar.failure_message()) // Helper function for implementing {EXPECT|ASSERT}_PRED1. Don't use // this in your code. template <typename Pred, typename T1> AssertionResult AssertPred1Helper(const char* pred_text, const char* e1, Pred pred, const T1& v1) { if (pred(v1)) return AssertionSuccess(); return AssertionFailure() << pred_text << "(" << e1 << ") evaluates to false, where" << "\n" << e1 << " evaluates to " << v1; } // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT1. // Don't use this in your code. #define GTEST_PRED_FORMAT1_(pred_format, v1, on_failure)\ GTEST_ASSERT_(pred_format(#v1, v1), \ on_failure) // Internal macro for implementing {EXPECT|ASSERT}_PRED1. Don't use // this in your code. #define GTEST_PRED1_(pred, v1, on_failure)\ GTEST_ASSERT_(::testing::AssertPred1Helper(#pred, \ #v1, \ pred, \ v1), on_failure) // Unary predicate assertion macros. #define EXPECT_PRED_FORMAT1(pred_format, v1) \ GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_NONFATAL_FAILURE_) #define EXPECT_PRED1(pred, v1) \ GTEST_PRED1_(pred, v1, GTEST_NONFATAL_FAILURE_) #define ASSERT_PRED_FORMAT1(pred_format, v1) \ GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_FATAL_FAILURE_) #define ASSERT_PRED1(pred, v1) \ GTEST_PRED1_(pred, v1, GTEST_FATAL_FAILURE_) // Helper function for implementing {EXPECT|ASSERT}_PRED2. Don't use // this in your code. template <typename Pred, typename T1, typename T2> AssertionResult AssertPred2Helper(const char* pred_text, const char* e1, const char* e2, Pred pred, const T1& v1, const T2& v2) { if (pred(v1, v2)) return AssertionSuccess(); return AssertionFailure() << pred_text << "(" << e1 << ", " << e2 << ") evaluates to false, where" << "\n" << e1 << " evaluates to " << v1 << "\n" << e2 << " evaluates to " << v2; } // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT2. // Don't use this in your code. #define GTEST_PRED_FORMAT2_(pred_format, v1, v2, on_failure)\ GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2), \ on_failure) // Internal macro for implementing {EXPECT|ASSERT}_PRED2. Don't use // this in your code. #define GTEST_PRED2_(pred, v1, v2, on_failure)\ GTEST_ASSERT_(::testing::AssertPred2Helper(#pred, \ #v1, \ #v2, \ pred, \ v1, \ v2), on_failure) // Binary predicate assertion macros. #define EXPECT_PRED_FORMAT2(pred_format, v1, v2) \ GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_NONFATAL_FAILURE_) #define EXPECT_PRED2(pred, v1, v2) \ GTEST_PRED2_(pred, v1, v2, GTEST_NONFATAL_FAILURE_) #define ASSERT_PRED_FORMAT2(pred_format, v1, v2) \ GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_FATAL_FAILURE_) #define ASSERT_PRED2(pred, v1, v2) \ GTEST_PRED2_(pred, v1, v2, GTEST_FATAL_FAILURE_) // Helper function for implementing {EXPECT|ASSERT}_PRED3. Don't use // this in your code. template <typename Pred, typename T1, typename T2, typename T3> AssertionResult AssertPred3Helper(const char* pred_text, const char* e1, const char* e2, const char* e3, Pred pred, const T1& v1, const T2& v2, const T3& v3) { if (pred(v1, v2, v3)) return AssertionSuccess(); return AssertionFailure() << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ") evaluates to false, where" << "\n" << e1 << " evaluates to " << v1 << "\n" << e2 << " evaluates to " << v2 << "\n" << e3 << " evaluates to " << v3; } // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT3. // Don't use this in your code. #define GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, on_failure)\ GTEST_ASSERT_(pred_format(#v1, #v2, #v3, v1, v2, v3), \ on_failure) // Internal macro for implementing {EXPECT|ASSERT}_PRED3. Don't use // this in your code. #define GTEST_PRED3_(pred, v1, v2, v3, on_failure)\ GTEST_ASSERT_(::testing::AssertPred3Helper(#pred, \ #v1, \ #v2, \ #v3, \ pred, \ v1, \ v2, \ v3), on_failure) // Ternary predicate assertion macros. #define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3) \ GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_NONFATAL_FAILURE_) #define EXPECT_PRED3(pred, v1, v2, v3) \ GTEST_PRED3_(pred, v1, v2, v3, GTEST_NONFATAL_FAILURE_) #define ASSERT_PRED_FORMAT3(pred_format, v1, v2, v3) \ GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_FATAL_FAILURE_) #define ASSERT_PRED3(pred, v1, v2, v3) \ GTEST_PRED3_(pred, v1, v2, v3, GTEST_FATAL_FAILURE_) // Helper function for implementing {EXPECT|ASSERT}_PRED4. Don't use // this in your code. template <typename Pred, typename T1, typename T2, typename T3, typename T4> AssertionResult AssertPred4Helper(const char* pred_text, const char* e1, const char* e2, const char* e3, const char* e4, Pred pred, const T1& v1, const T2& v2, const T3& v3, const T4& v4) { if (pred(v1, v2, v3, v4)) return AssertionSuccess(); return AssertionFailure() << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ", " << e4 << ") evaluates to false, where" << "\n" << e1 << " evaluates to " << v1 << "\n" << e2 << " evaluates to " << v2 << "\n" << e3 << " evaluates to " << v3 << "\n" << e4 << " evaluates to " << v4; } // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT4. // Don't use this in your code. #define GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, on_failure)\ GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4), \ on_failure) // Internal macro for implementing {EXPECT|ASSERT}_PRED4. Don't use // this in your code. #define GTEST_PRED4_(pred, v1, v2, v3, v4, on_failure)\ GTEST_ASSERT_(::testing::AssertPred4Helper(#pred, \ #v1, \ #v2, \ #v3, \ #v4, \ pred, \ v1, \ v2, \ v3, \ v4), on_failure) // 4-ary predicate assertion macros. #define EXPECT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \ GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_) #define EXPECT_PRED4(pred, v1, v2, v3, v4) \ GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_) #define ASSERT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \ GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_FATAL_FAILURE_) #define ASSERT_PRED4(pred, v1, v2, v3, v4) \ GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_FATAL_FAILURE_) // Helper function for implementing {EXPECT|ASSERT}_PRED5. Don't use // this in your code. template <typename Pred, typename T1, typename T2, typename T3, typename T4, typename T5> AssertionResult AssertPred5Helper(const char* pred_text, const char* e1, const char* e2, const char* e3, const char* e4, const char* e5, Pred pred, const T1& v1, const T2& v2, const T3& v3, const T4& v4, const T5& v5) { if (pred(v1, v2, v3, v4, v5)) return AssertionSuccess(); return AssertionFailure() << pred_text << "(" << e1 << ", " << e2 << ", " << e3 << ", " << e4 << ", " << e5 << ") evaluates to false, where" << "\n" << e1 << " evaluates to " << v1 << "\n" << e2 << " evaluates to " << v2 << "\n" << e3 << " evaluates to " << v3 << "\n" << e4 << " evaluates to " << v4 << "\n" << e5 << " evaluates to " << v5; } // Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT5. // Don't use this in your code. #define GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, on_failure)\ GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, #v5, v1, v2, v3, v4, v5), \ on_failure) // Internal macro for implementing {EXPECT|ASSERT}_PRED5. Don't use // this in your code. #define GTEST_PRED5_(pred, v1, v2, v3, v4, v5, on_failure)\ GTEST_ASSERT_(::testing::AssertPred5Helper(#pred, \ #v1, \ #v2, \ #v3, \ #v4, \ #v5, \ pred, \ v1, \ v2, \ v3, \ v4, \ v5), on_failure) // 5-ary predicate assertion macros. #define EXPECT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \ GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_) #define EXPECT_PRED5(pred, v1, v2, v3, v4, v5) \ GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_) #define ASSERT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \ GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_) #define ASSERT_PRED5(pred, v1, v2, v3, v4, v5) \ GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_) #endif // GTEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_
0
repos/DirectXShaderCompiler/utils/unittest/googletest/include
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest/gtest-printers.h
// 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. // // Author: [email protected] (Zhanyong Wan) // Google Test - The Google C++ Testing Framework // // This file implements a universal value printer that can print a // value of any type T: // // void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr); // // A user can teach this function how to print a class type T by // defining either operator<<() or PrintTo() in the namespace that // defines T. More specifically, the FIRST defined function in the // following list will be used (assuming T is defined in namespace // foo): // // 1. foo::PrintTo(const T&, ostream*) // 2. operator<<(ostream&, const T&) defined in either foo or the // global namespace. // // If none of the above is defined, it will print the debug string of // the value if it is a protocol buffer, or print the raw bytes in the // value otherwise. // // To aid debugging: when T is a reference type, the address of the // value is also printed; when T is a (const) char pointer, both the // pointer value and the NUL-terminated string it points to are // printed. // // We also provide some convenient wrappers: // // // Prints a value to a string. For a (const or not) char // // pointer, the NUL-terminated string (but not the pointer) is // // printed. // std::string ::testing::PrintToString(const T& value); // // // Prints a value tersely: for a reference type, the referenced // // value (but not the address) is printed; for a (const or not) char // // pointer, the NUL-terminated string (but not the pointer) is // // printed. // void ::testing::internal::UniversalTersePrint(const T& value, ostream*); // // // Prints value using the type inferred by the compiler. The difference // // from UniversalTersePrint() is that this function prints both the // // pointer and the NUL-terminated string for a (const or not) char pointer. // void ::testing::internal::UniversalPrint(const T& value, ostream*); // // // Prints the fields of a tuple tersely to a string vector, one // // element for each field. Tuple support must be enabled in // // gtest-port.h. // std::vector<string> UniversalTersePrintTupleFieldsToStrings( // const Tuple& value); // // Known limitation: // // The print primitives print the elements of an STL-style container // using the compiler-inferred type of *iter where iter is a // const_iterator of the container. When const_iterator is an input // iterator but not a forward iterator, this inferred type may not // match value_type, and the print output may be incorrect. In // practice, this is rarely a problem as for most containers // const_iterator is a forward iterator. We'll fix this if there's an // actual need for it. Note that this fix cannot rely on value_type // being defined as many user-defined container types don't have // value_type. #ifndef GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_ #define GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_ #include <ostream> // NOLINT #include <sstream> #include <string> #include <utility> #include <vector> #include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-internal.h" #if GTEST_HAS_STD_TUPLE_ # include <tuple> #endif namespace testing { // Definitions in the 'internal' and 'internal2' name spaces are // subject to change without notice. DO NOT USE THEM IN USER CODE! namespace internal2 { // Prints the given number of bytes in the given object to the given // ostream. GTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count, ::std::ostream* os); // For selecting which printer to use when a given type has neither << // nor PrintTo(). enum TypeKind { kProtobuf, // a protobuf type kConvertibleToInteger, // a type implicitly convertible to BiggestInt // (e.g. a named or unnamed enum type) kOtherType // anything else }; // TypeWithoutFormatter<T, kTypeKind>::PrintValue(value, os) is called // by the universal printer to print a value of type T when neither // operator<< nor PrintTo() is defined for T, where kTypeKind is the // "kind" of T as defined by enum TypeKind. template <typename T, TypeKind kTypeKind> class TypeWithoutFormatter { public: // This default version is called when kTypeKind is kOtherType. static void PrintValue(const T& value, ::std::ostream* os) { PrintBytesInObjectTo(reinterpret_cast<const unsigned char*>(&value), sizeof(value), os); } }; // We print a protobuf using its ShortDebugString() when the string // doesn't exceed this many characters; otherwise we print it using // DebugString() for better readability. const size_t kProtobufOneLinerMaxLength = 50; template <typename T> class TypeWithoutFormatter<T, kProtobuf> { public: static void PrintValue(const T& value, ::std::ostream* os) { const ::testing::internal::string short_str = value.ShortDebugString(); const ::testing::internal::string pretty_str = short_str.length() <= kProtobufOneLinerMaxLength ? short_str : ("\n" + value.DebugString()); *os << ("<" + pretty_str + ">"); } }; template <typename T> class TypeWithoutFormatter<T, kConvertibleToInteger> { public: // Since T has no << operator or PrintTo() but can be implicitly // converted to BiggestInt, we print it as a BiggestInt. // // Most likely T is an enum type (either named or unnamed), in which // case printing it as an integer is the desired behavior. In case // T is not an enum, printing it as an integer is the best we can do // given that it has no user-defined printer. static void PrintValue(const T& value, ::std::ostream* os) { const internal::BiggestInt kBigInt = value; *os << kBigInt; } }; // Prints the given value to the given ostream. If the value is a // protocol message, its debug string is printed; if it's an enum or // of a type implicitly convertible to BiggestInt, it's printed as an // integer; otherwise the bytes in the value are printed. This is // what UniversalPrinter<T>::Print() does when it knows nothing about // type T and T has neither << operator nor PrintTo(). // // A user can override this behavior for a class type Foo by defining // a << operator in the namespace where Foo is defined. // // We put this operator in namespace 'internal2' instead of 'internal' // to simplify the implementation, as much code in 'internal' needs to // use << in STL, which would conflict with our own << were it defined // in 'internal'. // // Note that this operator<< takes a generic std::basic_ostream<Char, // CharTraits> type instead of the more restricted std::ostream. If // we define it to take an std::ostream instead, we'll get an // "ambiguous overloads" compiler error when trying to print a type // Foo that supports streaming to std::basic_ostream<Char, // CharTraits>, as the compiler cannot tell whether // operator<<(std::ostream&, const T&) or // operator<<(std::basic_stream<Char, CharTraits>, const Foo&) is more // specific. template <typename Char, typename CharTraits, typename T> ::std::basic_ostream<Char, CharTraits>& operator<<( ::std::basic_ostream<Char, CharTraits>& os, const T& x) { TypeWithoutFormatter<T, (internal::IsAProtocolMessage<T>::value ? kProtobuf : internal::ImplicitlyConvertible<const T&, internal::BiggestInt>::value ? kConvertibleToInteger : kOtherType)>::PrintValue(x, &os); return os; } } // namespace internal2 } // namespace testing // This namespace MUST NOT BE NESTED IN ::testing, or the name look-up // magic needed for implementing UniversalPrinter won't work. namespace testing_internal { // Used to print a value that is not an STL-style container when the // user doesn't define PrintTo() for it. template <typename T> void DefaultPrintNonContainerTo(const T& value, ::std::ostream* os) { // With the following statement, during unqualified name lookup, // testing::internal2::operator<< appears as if it was declared in // the nearest enclosing namespace that contains both // ::testing_internal and ::testing::internal2, i.e. the global // namespace. For more details, refer to the C++ Standard section // 7.3.4-1 [namespace.udir]. This allows us to fall back onto // testing::internal2::operator<< in case T doesn't come with a << // operator. // // We cannot write 'using ::testing::internal2::operator<<;', which // gcc 3.3 fails to compile due to a compiler bug. using namespace ::testing::internal2; // NOLINT // Assuming T is defined in namespace foo, in the next statement, // the compiler will consider all of: // // 1. foo::operator<< (thanks to Koenig look-up), // 2. ::operator<< (as the current namespace is enclosed in ::), // 3. testing::internal2::operator<< (thanks to the using statement above). // // The operator<< whose type matches T best will be picked. // // We deliberately allow #2 to be a candidate, as sometimes it's // impossible to define #1 (e.g. when foo is ::std, defining // anything in it is undefined behavior unless you are a compiler // vendor.). *os << value; } } // namespace testing_internal namespace testing { namespace internal { // FormatForComparison<ToPrint, OtherOperand>::Format(value) formats a // value of type ToPrint that is an operand of a comparison assertion // (e.g. ASSERT_EQ). OtherOperand is the type of the other operand in // the comparison, and is used to help determine the best way to // format the value. In particular, when the value is a C string // (char pointer) and the other operand is an STL string object, we // want to format the C string as a string, since we know it is // compared by value with the string object. If the value is a char // pointer but the other operand is not an STL string object, we don't // know whether the pointer is supposed to point to a NUL-terminated // string, and thus want to print it as a pointer to be safe. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. // The default case. template <typename ToPrint, typename OtherOperand> class FormatForComparison { public: static ::std::string Format(const ToPrint& value) { return ::testing::PrintToString(value); } }; // Array. template <typename ToPrint, size_t N, typename OtherOperand> class FormatForComparison<ToPrint[N], OtherOperand> { public: static ::std::string Format(const ToPrint* value) { return FormatForComparison<const ToPrint*, OtherOperand>::Format(value); } }; // By default, print C string as pointers to be safe, as we don't know // whether they actually point to a NUL-terminated string. #define GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(CharType) \ template <typename OtherOperand> \ class FormatForComparison<CharType*, OtherOperand> { \ public: \ static ::std::string Format(CharType* value) { \ return ::testing::PrintToString(static_cast<const void*>(value)); \ } \ } GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char); GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char); GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(wchar_t); GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t); #undef GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_ // If a C string is compared with an STL string object, we know it's meant // to point to a NUL-terminated string, and thus can print it as a string. #define GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(CharType, OtherStringType) \ template <> \ class FormatForComparison<CharType*, OtherStringType> { \ public: \ static ::std::string Format(CharType* value) { \ return ::testing::PrintToString(value); \ } \ } GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string); GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string); #if GTEST_HAS_GLOBAL_STRING GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::string); GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::string); #endif #if GTEST_HAS_GLOBAL_WSTRING GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::wstring); GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::wstring); #endif #if GTEST_HAS_STD_WSTRING GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::std::wstring); GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::std::wstring); #endif #undef GTEST_IMPL_FORMAT_C_STRING_AS_STRING_ // Formats a comparison assertion (e.g. ASSERT_EQ, EXPECT_LT, and etc) // operand to be used in a failure message. The type (but not value) // of the other operand may affect the format. This allows us to // print a char* as a raw pointer when it is compared against another // char* or void*, and print it as a C string when it is compared // against an std::string object, for example. // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. template <typename T1, typename T2> std::string FormatForComparisonFailureMessage( const T1& value, const T2& /* other_operand */) { return FormatForComparison<T1, T2>::Format(value); } // UniversalPrinter<T>::Print(value, ostream_ptr) prints the given // value to the given ostream. The caller must ensure that // 'ostream_ptr' is not NULL, or the behavior is undefined. // // We define UniversalPrinter as a class template (as opposed to a // function template), as we need to partially specialize it for // reference types, which cannot be done with function templates. template <typename T> class UniversalPrinter; template <typename T> void UniversalPrint(const T& value, ::std::ostream* os); // Used to print an STL-style container when the user doesn't define // a PrintTo() for it. template <typename C> void DefaultPrintTo(IsContainer /* dummy */, false_type /* is not a pointer */, const C& container, ::std::ostream* os) { const size_t kMaxCount = 32; // The maximum number of elements to print. *os << '{'; size_t count = 0; for (typename C::const_iterator it = container.begin(); it != container.end(); ++it, ++count) { if (count > 0) { *os << ','; if (count == kMaxCount) { // Enough has been printed. *os << " ..."; break; } } *os << ' '; // We cannot call PrintTo(*it, os) here as PrintTo() doesn't // handle *it being a native array. internal::UniversalPrint(*it, os); } if (count > 0) { *os << ' '; } *os << '}'; } // Used to print a pointer that is neither a char pointer nor a member // pointer, when the user doesn't define PrintTo() for it. (A member // variable pointer or member function pointer doesn't really point to // a location in the address space. Their representation is // implementation-defined. Therefore they will be printed as raw // bytes.) template <typename T> void DefaultPrintTo(IsNotContainer /* dummy */, true_type /* is a pointer */, T* p, ::std::ostream* os) { if (p == NULL) { *os << "NULL"; } else { // C++ doesn't allow casting from a function pointer to any object // pointer. // // IsTrue() silences warnings: "Condition is always true", // "unreachable code". if (IsTrue(ImplicitlyConvertible<T*, const void*>::value)) { // T is not a function type. We just call << to print p, // relying on ADL to pick up user-defined << for their pointer // types, if any. *os << p; } else { // T is a function type, so '*os << p' doesn't do what we want // (it just prints p as bool). We want to print p as a const // void*. However, we cannot cast it to const void* directly, // even using reinterpret_cast, as earlier versions of gcc // (e.g. 3.4.5) cannot compile the cast when p is a function // pointer. Casting to UInt64 first solves the problem. *os << reinterpret_cast<const void*>( reinterpret_cast<internal::UInt64>(p)); } } } // Used to print a non-container, non-pointer value when the user // doesn't define PrintTo() for it. template <typename T> void DefaultPrintTo(IsNotContainer /* dummy */, false_type /* is not a pointer */, const T& value, ::std::ostream* os) { ::testing_internal::DefaultPrintNonContainerTo(value, os); } // Prints the given value using the << operator if it has one; // otherwise prints the bytes in it. This is what // UniversalPrinter<T>::Print() does when PrintTo() is not specialized // or overloaded for type T. // // A user can override this behavior for a class type Foo by defining // an overload of PrintTo() in the namespace where Foo is defined. We // give the user this option as sometimes defining a << operator for // Foo is not desirable (e.g. the coding style may prevent doing it, // or there is already a << operator but it doesn't do what the user // wants). template <typename T> void PrintTo(const T& value, ::std::ostream* os) { // DefaultPrintTo() is overloaded. The type of its first two // arguments determine which version will be picked. If T is an // STL-style container, the version for container will be called; if // T is a pointer, the pointer version will be called; otherwise the // generic version will be called. // // Note that we check for container types here, prior to we check // for protocol message types in our operator<<. The rationale is: // // For protocol messages, we want to give people a chance to // override Google Mock's format by defining a PrintTo() or // operator<<. For STL containers, other formats can be // incompatible with Google Mock's format for the container // elements; therefore we check for container types here to ensure // that our format is used. // // The second argument of DefaultPrintTo() is needed to bypass a bug // in Symbian's C++ compiler that prevents it from picking the right // overload between: // // PrintTo(const T& x, ...); // PrintTo(T* x, ...); DefaultPrintTo(IsContainerTest<T>(0), is_pointer<T>(), value, os); } // The following list of PrintTo() overloads tells // UniversalPrinter<T>::Print() how to print standard types (built-in // types, strings, plain arrays, and pointers). // Overloads for various char types. GTEST_API_ void PrintTo(unsigned char c, ::std::ostream* os); GTEST_API_ void PrintTo(signed char c, ::std::ostream* os); inline void PrintTo(char c, ::std::ostream* os) { // When printing a plain char, we always treat it as unsigned. This // way, the output won't be affected by whether the compiler thinks // char is signed or not. PrintTo(static_cast<unsigned char>(c), os); } // Overloads for other simple built-in types. inline void PrintTo(bool x, ::std::ostream* os) { *os << (x ? "true" : "false"); } // Overload for wchar_t type. // Prints a wchar_t as a symbol if it is printable or as its internal // code otherwise and also as its decimal code (except for L'\0'). // The L'\0' char is printed as "L'\\0'". The decimal code is printed // as signed integer when wchar_t is implemented by the compiler // as a signed type and is printed as an unsigned integer when wchar_t // is implemented as an unsigned type. GTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os); // Overloads for C strings. GTEST_API_ void PrintTo(const char* s, ::std::ostream* os); inline void PrintTo(char* s, ::std::ostream* os) { PrintTo(ImplicitCast_<const char*>(s), os); } // signed/unsigned char is often used for representing binary data, so // we print pointers to it as void* to be safe. inline void PrintTo(const signed char* s, ::std::ostream* os) { PrintTo(ImplicitCast_<const void*>(s), os); } inline void PrintTo(signed char* s, ::std::ostream* os) { PrintTo(ImplicitCast_<const void*>(s), os); } inline void PrintTo(const unsigned char* s, ::std::ostream* os) { PrintTo(ImplicitCast_<const void*>(s), os); } inline void PrintTo(unsigned char* s, ::std::ostream* os) { PrintTo(ImplicitCast_<const void*>(s), os); } // MSVC can be configured to define wchar_t as a typedef of unsigned // short. It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native // type. When wchar_t is a typedef, defining an overload for const // wchar_t* would cause unsigned short* be printed as a wide string, // possibly causing invalid memory accesses. #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) // Overloads for wide C strings GTEST_API_ void PrintTo(const wchar_t* s, ::std::ostream* os); inline void PrintTo(wchar_t* s, ::std::ostream* os) { PrintTo(ImplicitCast_<const wchar_t*>(s), os); } #endif // Overload for C arrays. Multi-dimensional arrays are printed // properly. // Prints the given number of elements in an array, without printing // the curly braces. template <typename T> void PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) { UniversalPrint(a[0], os); for (size_t i = 1; i != count; i++) { *os << ", "; UniversalPrint(a[i], os); } } // Overloads for ::string and ::std::string. #if GTEST_HAS_GLOBAL_STRING GTEST_API_ void PrintStringTo(const ::string&s, ::std::ostream* os); inline void PrintTo(const ::string& s, ::std::ostream* os) { PrintStringTo(s, os); } #endif // GTEST_HAS_GLOBAL_STRING GTEST_API_ void PrintStringTo(const ::std::string&s, ::std::ostream* os); inline void PrintTo(const ::std::string& s, ::std::ostream* os) { PrintStringTo(s, os); } // Overloads for ::wstring and ::std::wstring. #if GTEST_HAS_GLOBAL_WSTRING GTEST_API_ void PrintWideStringTo(const ::wstring&s, ::std::ostream* os); inline void PrintTo(const ::wstring& s, ::std::ostream* os) { PrintWideStringTo(s, os); } #endif // GTEST_HAS_GLOBAL_WSTRING #if GTEST_HAS_STD_WSTRING GTEST_API_ void PrintWideStringTo(const ::std::wstring&s, ::std::ostream* os); inline void PrintTo(const ::std::wstring& s, ::std::ostream* os) { PrintWideStringTo(s, os); } #endif // GTEST_HAS_STD_WSTRING #if GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_ // Helper function for printing a tuple. T must be instantiated with // a tuple type. template <typename T> void PrintTupleTo(const T& t, ::std::ostream* os); #endif // GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_ #if GTEST_HAS_TR1_TUPLE // Overload for ::std::tr1::tuple. Needed for printing function arguments, // which are packed as tuples. // Overloaded PrintTo() for tuples of various arities. We support // tuples of up-to 10 fields. The following implementation works // regardless of whether tr1::tuple is implemented using the // non-standard variadic template feature or not. inline void PrintTo(const ::std::tr1::tuple<>& t, ::std::ostream* os) { PrintTupleTo(t, os); } template <typename T1> void PrintTo(const ::std::tr1::tuple<T1>& t, ::std::ostream* os) { PrintTupleTo(t, os); } template <typename T1, typename T2> void PrintTo(const ::std::tr1::tuple<T1, T2>& t, ::std::ostream* os) { PrintTupleTo(t, os); } template <typename T1, typename T2, typename T3> void PrintTo(const ::std::tr1::tuple<T1, T2, T3>& t, ::std::ostream* os) { PrintTupleTo(t, os); } template <typename T1, typename T2, typename T3, typename T4> void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4>& t, ::std::ostream* os) { PrintTupleTo(t, os); } template <typename T1, typename T2, typename T3, typename T4, typename T5> void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5>& t, ::std::ostream* os) { PrintTupleTo(t, os); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6> void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6>& t, ::std::ostream* os) { PrintTupleTo(t, os); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7> void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7>& t, ::std::ostream* os) { PrintTupleTo(t, os); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8> void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7, T8>& t, ::std::ostream* os) { PrintTupleTo(t, os); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9> void PrintTo(const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9>& t, ::std::ostream* os) { PrintTupleTo(t, os); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10> void PrintTo( const ::std::tr1::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>& t, ::std::ostream* os) { PrintTupleTo(t, os); } #endif // GTEST_HAS_TR1_TUPLE #if GTEST_HAS_STD_TUPLE_ template <typename... Types> void PrintTo(const ::std::tuple<Types...>& t, ::std::ostream* os) { PrintTupleTo(t, os); } #endif // GTEST_HAS_STD_TUPLE_ // Overload for std::pair. template <typename T1, typename T2> void PrintTo(const ::std::pair<T1, T2>& value, ::std::ostream* os) { *os << '('; // We cannot use UniversalPrint(value.first, os) here, as T1 may be // a reference type. The same for printing value.second. UniversalPrinter<T1>::Print(value.first, os); *os << ", "; UniversalPrinter<T2>::Print(value.second, os); *os << ')'; } #if GTEST_LANG_CXX11 inline void PrintTo(std::nullptr_t, ::std::ostream* os) { *os << "(nullptr)"; } #endif // GTEST_LANG_CXX11 // Implements printing a non-reference type T by letting the compiler // pick the right overload of PrintTo() for T. template <typename T> class UniversalPrinter { public: // MSVC warns about adding const to a function type, so we want to // disable the warning. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180) // Note: we deliberately don't call this PrintTo(), as that name // conflicts with ::testing::internal::PrintTo in the body of the // function. static void Print(const T& value, ::std::ostream* os) { // By default, ::testing::internal::PrintTo() is used for printing // the value. // // Thanks to Koenig look-up, if T is a class and has its own // PrintTo() function defined in its namespace, that function will // be visible here. Since it is more specific than the generic ones // in ::testing::internal, it will be picked by the compiler in the // following statement - exactly what we want. PrintTo(value, os); } GTEST_DISABLE_MSC_WARNINGS_POP_() }; // UniversalPrintArray(begin, len, os) prints an array of 'len' // elements, starting at address 'begin'. template <typename T> void UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) { if (len == 0) { *os << "{}"; } else { *os << "{ "; const size_t kThreshold = 18; const size_t kChunkSize = 8; // If the array has more than kThreshold elements, we'll have to // omit some details by printing only the first and the last // kChunkSize elements. // TODO([email protected]): let the user control the threshold using a flag. if (len <= kThreshold) { PrintRawArrayTo(begin, len, os); } else { PrintRawArrayTo(begin, kChunkSize, os); *os << ", ..., "; PrintRawArrayTo(begin + len - kChunkSize, kChunkSize, os); } *os << " }"; } } // This overload prints a (const) char array compactly. GTEST_API_ void UniversalPrintArray( const char* begin, size_t len, ::std::ostream* os); // This overload prints a (const) wchar_t array compactly. GTEST_API_ void UniversalPrintArray( const wchar_t* begin, size_t len, ::std::ostream* os); // Implements printing an array type T[N]. template <typename T, size_t N> class UniversalPrinter<T[N]> { public: // Prints the given array, omitting some elements when there are too // many. static void Print(const T (&a)[N], ::std::ostream* os) { UniversalPrintArray(a, N, os); } }; // Implements printing a reference type T&. template <typename T> class UniversalPrinter<T&> { public: // MSVC warns about adding const to a function type, so we want to // disable the warning. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180) static void Print(const T& value, ::std::ostream* os) { // Prints the address of the value. We use reinterpret_cast here // as static_cast doesn't compile when T is a function type. *os << "@" << reinterpret_cast<const void*>(&value) << " "; // Then prints the value itself. UniversalPrint(value, os); } GTEST_DISABLE_MSC_WARNINGS_POP_() }; // Prints a value tersely: for a reference type, the referenced value // (but not the address) is printed; for a (const) char pointer, the // NUL-terminated string (but not the pointer) is printed. template <typename T> class UniversalTersePrinter { public: static void Print(const T& value, ::std::ostream* os) { UniversalPrint(value, os); } }; template <typename T> class UniversalTersePrinter<T&> { public: static void Print(const T& value, ::std::ostream* os) { UniversalPrint(value, os); } }; template <typename T, size_t N> class UniversalTersePrinter<T[N]> { public: static void Print(const T (&value)[N], ::std::ostream* os) { UniversalPrinter<T[N]>::Print(value, os); } }; template <> class UniversalTersePrinter<const char*> { public: static void Print(const char* str, ::std::ostream* os) { if (str == NULL) { *os << "NULL"; } else { UniversalPrint(string(str), os); } } }; template <> class UniversalTersePrinter<char*> { public: static void Print(char* str, ::std::ostream* os) { UniversalTersePrinter<const char*>::Print(str, os); } }; #if GTEST_HAS_STD_WSTRING template <> class UniversalTersePrinter<const wchar_t*> { public: static void Print(const wchar_t* str, ::std::ostream* os) { if (str == NULL) { *os << "NULL"; } else { UniversalPrint(::std::wstring(str), os); } } }; #endif template <> class UniversalTersePrinter<wchar_t*> { public: static void Print(wchar_t* str, ::std::ostream* os) { UniversalTersePrinter<const wchar_t*>::Print(str, os); } }; template <typename T> void UniversalTersePrint(const T& value, ::std::ostream* os) { UniversalTersePrinter<T>::Print(value, os); } // Prints a value using the type inferred by the compiler. The // difference between this and UniversalTersePrint() is that for a // (const) char pointer, this prints both the pointer and the // NUL-terminated string. template <typename T> void UniversalPrint(const T& value, ::std::ostream* os) { // A workarond for the bug in VC++ 7.1 that prevents us from instantiating // UniversalPrinter with T directly. typedef T T1; UniversalPrinter<T1>::Print(value, os); } typedef ::std::vector<string> Strings; // TuplePolicy<TupleT> must provide: // - tuple_size // size of tuple TupleT. // - get<size_t I>(const TupleT& t) // static function extracting element I of tuple TupleT. // - tuple_element<size_t I>::type // type of element I of tuple TupleT. template <typename TupleT> struct TuplePolicy; #if GTEST_HAS_TR1_TUPLE template <typename TupleT> struct TuplePolicy { typedef TupleT Tuple; static const size_t tuple_size = ::std::tr1::tuple_size<Tuple>::value; template <size_t I> struct tuple_element : ::std::tr1::tuple_element<I, Tuple> {}; template <size_t I> static typename AddReference< const typename ::std::tr1::tuple_element<I, Tuple>::type>::type get( const Tuple& tuple) { return ::std::tr1::get<I>(tuple); } }; template <typename TupleT> const size_t TuplePolicy<TupleT>::tuple_size; #endif // GTEST_HAS_TR1_TUPLE #if GTEST_HAS_STD_TUPLE_ template <typename... Types> struct TuplePolicy< ::std::tuple<Types...> > { typedef ::std::tuple<Types...> Tuple; static const size_t tuple_size = ::std::tuple_size<Tuple>::value; template <size_t I> struct tuple_element : ::std::tuple_element<I, Tuple> {}; template <size_t I> static const typename ::std::tuple_element<I, Tuple>::type& get( const Tuple& tuple) { return ::std::get<I>(tuple); } }; template <typename... Types> const size_t TuplePolicy< ::std::tuple<Types...> >::tuple_size; #endif // GTEST_HAS_STD_TUPLE_ #if GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_ // This helper template allows PrintTo() for tuples and // UniversalTersePrintTupleFieldsToStrings() to be defined by // induction on the number of tuple fields. The idea is that // TuplePrefixPrinter<N>::PrintPrefixTo(t, os) prints the first N // fields in tuple t, and can be defined in terms of // TuplePrefixPrinter<N - 1>. // // The inductive case. template <size_t N> struct TuplePrefixPrinter { // Prints the first N fields of a tuple. template <typename Tuple> static void PrintPrefixTo(const Tuple& t, ::std::ostream* os) { TuplePrefixPrinter<N - 1>::PrintPrefixTo(t, os); GTEST_INTENTIONAL_CONST_COND_PUSH_() if (N > 1) { GTEST_INTENTIONAL_CONST_COND_POP_() *os << ", "; } UniversalPrinter< typename TuplePolicy<Tuple>::template tuple_element<N - 1>::type> ::Print(TuplePolicy<Tuple>::template get<N - 1>(t), os); } // Tersely prints the first N fields of a tuple to a string vector, // one element for each field. template <typename Tuple> static void TersePrintPrefixToStrings(const Tuple& t, Strings* strings) { TuplePrefixPrinter<N - 1>::TersePrintPrefixToStrings(t, strings); ::std::stringstream ss; UniversalTersePrint(TuplePolicy<Tuple>::template get<N - 1>(t), &ss); strings->push_back(ss.str()); } }; // Base case. template <> struct TuplePrefixPrinter<0> { template <typename Tuple> static void PrintPrefixTo(const Tuple&, ::std::ostream*) {} template <typename Tuple> static void TersePrintPrefixToStrings(const Tuple&, Strings*) {} }; // Helper function for printing a tuple. // Tuple must be either std::tr1::tuple or std::tuple type. template <typename Tuple> void PrintTupleTo(const Tuple& t, ::std::ostream* os) { *os << "("; TuplePrefixPrinter<TuplePolicy<Tuple>::tuple_size>::PrintPrefixTo(t, os); *os << ")"; } // Prints the fields of a tuple tersely to a string vector, one // element for each field. See the comment before // UniversalTersePrint() for how we define "tersely". template <typename Tuple> Strings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) { Strings result; TuplePrefixPrinter<TuplePolicy<Tuple>::tuple_size>:: TersePrintPrefixToStrings(value, &result); return result; } #endif // GTEST_HAS_TR1_TUPLE || GTEST_HAS_STD_TUPLE_ } // namespace internal template <typename T> ::std::string PrintToString(const T& value) { ::std::stringstream ss; internal::UniversalTersePrinter<T>::Print(value, &ss); return ss.str(); } } // namespace testing // Include any custom printer added by the local installation. // We must include this header at the end to make sure it can use the // declarations from this file. #include "gtest/internal/custom/gtest-printers.h" #endif // GTEST_INCLUDE_GTEST_GTEST_PRINTERS_H_
0
repos/DirectXShaderCompiler/utils/unittest/googletest/include
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest/gtest-death-test.h
// Copyright 2005, 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. // // Author: [email protected] (Zhanyong Wan) // // The Google C++ Testing Framework (Google Test) // // This header file defines the public API for death tests. It is // #included by gtest.h so a user doesn't need to include this // directly. #ifndef GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ #define GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_ #include "gtest/internal/gtest-death-test-internal.h" namespace testing { // This flag controls the style of death tests. Valid values are "threadsafe", // meaning that the death test child process will re-execute the test binary // from the start, running only a single death test, or "fast", // meaning that the child process will execute the test logic immediately // after forking. GTEST_DECLARE_string_(death_test_style); #if GTEST_HAS_DEATH_TEST namespace internal { // Returns a Boolean value indicating whether the caller is currently // executing in the context of the death test child process. Tools such as // Valgrind heap checkers may need this to modify their behavior in death // tests. IMPORTANT: This is an internal utility. Using it may break the // implementation of death tests. User code MUST NOT use it. GTEST_API_ bool InDeathTestChild(); } // namespace internal // The following macros are useful for writing death tests. // Here's what happens when an ASSERT_DEATH* or EXPECT_DEATH* is // executed: // // 1. It generates a warning if there is more than one active // thread. This is because it's safe to fork() or clone() only // when there is a single thread. // // 2. The parent process clone()s a sub-process and runs the death // test in it; the sub-process exits with code 0 at the end of the // death test, if it hasn't exited already. // // 3. The parent process waits for the sub-process to terminate. // // 4. The parent process checks the exit code and error message of // the sub-process. // // Examples: // // ASSERT_DEATH(server.SendMessage(56, "Hello"), "Invalid port number"); // for (int i = 0; i < 5; i++) { // EXPECT_DEATH(server.ProcessRequest(i), // "Invalid request .* in ProcessRequest()") // << "Failed to die on request " << i; // } // // ASSERT_EXIT(server.ExitNow(), ::testing::ExitedWithCode(0), "Exiting"); // // bool KilledBySIGHUP(int exit_code) { // return WIFSIGNALED(exit_code) && WTERMSIG(exit_code) == SIGHUP; // } // // ASSERT_EXIT(client.HangUpServer(), KilledBySIGHUP, "Hanging up!"); // // On the regular expressions used in death tests: // // On POSIX-compliant systems (*nix), we use the <regex.h> library, // which uses the POSIX extended regex syntax. // // On other platforms (e.g. Windows), we only support a simple regex // syntax implemented as part of Google Test. This limited // implementation should be enough most of the time when writing // death tests; though it lacks many features you can find in PCRE // or POSIX extended regex syntax. For example, we don't support // union ("x|y"), grouping ("(xy)"), brackets ("[xy]"), and // repetition count ("x{5,7}"), among others. // // Below is the syntax that we do support. We chose it to be a // subset of both PCRE and POSIX extended regex, so it's easy to // learn wherever you come from. In the following: 'A' denotes a // literal character, period (.), or a single \\ escape sequence; // 'x' and 'y' denote regular expressions; 'm' and 'n' are for // natural numbers. // // c matches any literal character c // \\d matches any decimal digit // \\D matches any character that's not a decimal digit // \\f matches \f // \\n matches \n // \\r matches \r // \\s matches any ASCII whitespace, including \n // \\S matches any character that's not a whitespace // \\t matches \t // \\v matches \v // \\w matches any letter, _, or decimal digit // \\W matches any character that \\w doesn't match // \\c matches any literal character c, which must be a punctuation // . matches any single character except \n // A? matches 0 or 1 occurrences of A // A* matches 0 or many occurrences of A // A+ matches 1 or many occurrences of A // ^ matches the beginning of a string (not that of each line) // $ matches the end of a string (not that of each line) // xy matches x followed by y // // If you accidentally use PCRE or POSIX extended regex features // not implemented by us, you will get a run-time failure. In that // case, please try to rewrite your regular expression within the // above syntax. // // This implementation is *not* meant to be as highly tuned or robust // as a compiled regex library, but should perform well enough for a // death test, which already incurs significant overhead by launching // a child process. // // Known caveats: // // A "threadsafe" style death test obtains the path to the test // program from argv[0] and re-executes it in the sub-process. For // simplicity, the current implementation doesn't search the PATH // when launching the sub-process. This means that the user must // invoke the test program via a path that contains at least one // path separator (e.g. path/to/foo_test and // /absolute/path/to/bar_test are fine, but foo_test is not). This // is rarely a problem as people usually don't put the test binary // directory in PATH. // // TODO([email protected]): make thread-safe death tests search the PATH. // Asserts that a given statement causes the program to exit, with an // integer exit status that satisfies predicate, and emitting error output // that matches regex. # define ASSERT_EXIT(statement, predicate, regex) \ GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_FATAL_FAILURE_) // Like ASSERT_EXIT, but continues on to successive tests in the // test case, if any: # define EXPECT_EXIT(statement, predicate, regex) \ GTEST_DEATH_TEST_(statement, predicate, regex, GTEST_NONFATAL_FAILURE_) // Asserts that a given statement causes the program to exit, either by // explicitly exiting with a nonzero exit code or being killed by a // signal, and emitting error output that matches regex. # define ASSERT_DEATH(statement, regex) \ ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex) // Like ASSERT_DEATH, but continues on to successive tests in the // test case, if any: # define EXPECT_DEATH(statement, regex) \ EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, regex) // Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*: // Tests that an exit code describes a normal exit with a given exit code. class GTEST_API_ ExitedWithCode { public: explicit ExitedWithCode(int exit_code); bool operator()(int exit_status) const; private: // No implementation - assignment is unsupported. void operator=(const ExitedWithCode& other); const int exit_code_; }; # if !GTEST_OS_WINDOWS // Tests that an exit code describes an exit due to termination by a // given signal. class GTEST_API_ KilledBySignal { public: explicit KilledBySignal(int signum); bool operator()(int exit_status) const; private: const int signum_; }; # endif // !GTEST_OS_WINDOWS // EXPECT_DEBUG_DEATH asserts that the given statements die in debug mode. // The death testing framework causes this to have interesting semantics, // since the sideeffects of the call are only visible in opt mode, and not // in debug mode. // // In practice, this can be used to test functions that utilize the // LOG(DFATAL) macro using the following style: // // int DieInDebugOr12(int* sideeffect) { // if (sideeffect) { // *sideeffect = 12; // } // LOG(DFATAL) << "death"; // return 12; // } // // TEST(TestCase, TestDieOr12WorksInDgbAndOpt) { // int sideeffect = 0; // // Only asserts in dbg. // EXPECT_DEBUG_DEATH(DieInDebugOr12(&sideeffect), "death"); // // #ifdef NDEBUG // // opt-mode has sideeffect visible. // EXPECT_EQ(12, sideeffect); // #else // // dbg-mode no visible sideeffect. // EXPECT_EQ(0, sideeffect); // #endif // } // // This will assert that DieInDebugReturn12InOpt() crashes in debug // mode, usually due to a DCHECK or LOG(DFATAL), but returns the // appropriate fallback value (12 in this case) in opt mode. If you // need to test that a function has appropriate side-effects in opt // mode, include assertions against the side-effects. A general // pattern for this is: // // EXPECT_DEBUG_DEATH({ // // Side-effects here will have an effect after this statement in // // opt mode, but none in debug mode. // EXPECT_EQ(12, DieInDebugOr12(&sideeffect)); // }, "death"); // # ifdef NDEBUG # define EXPECT_DEBUG_DEATH(statement, regex) \ GTEST_EXECUTE_STATEMENT_(statement, regex) # define ASSERT_DEBUG_DEATH(statement, regex) \ GTEST_EXECUTE_STATEMENT_(statement, regex) # else # define EXPECT_DEBUG_DEATH(statement, regex) \ EXPECT_DEATH(statement, regex) # define ASSERT_DEBUG_DEATH(statement, regex) \ ASSERT_DEATH(statement, regex) # endif // NDEBUG for EXPECT_DEBUG_DEATH #endif // GTEST_HAS_DEATH_TEST // EXPECT_DEATH_IF_SUPPORTED(statement, regex) and // ASSERT_DEATH_IF_SUPPORTED(statement, regex) expand to real death tests if // death tests are supported; otherwise they just issue a warning. This is // useful when you are combining death test assertions with normal test // assertions in one test. #if GTEST_HAS_DEATH_TEST # define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \ EXPECT_DEATH(statement, regex) # define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \ ASSERT_DEATH(statement, regex) #else # define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \ GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, ) # define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \ GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, return) #endif } // namespace testing #endif // GTEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_
0
repos/DirectXShaderCompiler/utils/unittest/googletest/include
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest/gtest_prod.h
// Copyright 2006, 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. // // Author: [email protected] (Zhanyong Wan) // // Google C++ Testing Framework definitions useful in production code. #ifndef GTEST_INCLUDE_GTEST_GTEST_PROD_H_ #define GTEST_INCLUDE_GTEST_GTEST_PROD_H_ // When you need to test the private or protected members of a class, // use the FRIEND_TEST macro to declare your tests as friends of the // class. For example: // // class MyClass { // private: // void MyMethod(); // FRIEND_TEST(MyClassTest, MyMethod); // }; // // class MyClassTest : public testing::Test { // // ... // }; // // TEST_F(MyClassTest, MyMethod) { // // Can call MyClass::MyMethod() here. // } #define FRIEND_TEST(test_case_name, test_name)\ friend class test_case_name##_##test_name##_Test #endif // GTEST_INCLUDE_GTEST_GTEST_PROD_H_
0
repos/DirectXShaderCompiler/utils/unittest/googletest/include
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest/gtest-message.h
// Copyright 2005, 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. // // Author: [email protected] (Zhanyong Wan) // // The Google C++ Testing Framework (Google Test) // // This header file defines the Message class. // // IMPORTANT NOTE: Due to limitation of the C++ language, we have to // leave some internal implementation details in this header file. // They are clearly marked by comments like this: // // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. // // Such code is NOT meant to be used by a user directly, and is subject // to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user // program! #ifndef GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ #define GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_ #include <limits> #include "gtest/internal/gtest-port.h" #if !GTEST_NO_LLVM_RAW_OSTREAM #include "llvm/Support/raw_os_ostream.h" // LLVM INTERNAL CHANGE: To allow operator<< to work with both // std::ostreams and LLVM's raw_ostreams, we define a special // std::ostream with an implicit conversion to raw_ostream& and stream // to that. This causes the compiler to prefer std::ostream overloads // but still find raw_ostream& overloads. namespace llvm { class convertible_fwd_ostream : public std::ostream { raw_os_ostream ros_; public: convertible_fwd_ostream(std::ostream& os) : std::ostream(os.rdbuf()), ros_(*this) {} operator raw_ostream&() { return ros_; } }; } template <typename T> inline void GTestStreamToHelper(std::ostream& os, const T& val) { llvm::convertible_fwd_ostream cos(os); cos << val; } #else template <typename T> inline void GTestStreamToHelper(std::ostream& os, const T& val) { os << val; } #endif // Ensures that there is at least one operator<< in the global namespace. // See Message& operator<<(...) below for why. void operator<<(const testing::internal::Secret&, int); namespace testing { // The Message class works like an ostream repeater. // // Typical usage: // // 1. You stream a bunch of values to a Message object. // It will remember the text in a stringstream. // 2. Then you stream the Message object to an ostream. // This causes the text in the Message to be streamed // to the ostream. // // For example; // // testing::Message foo; // foo << 1 << " != " << 2; // std::cout << foo; // // will print "1 != 2". // // Message is not intended to be inherited from. In particular, its // destructor is not virtual. // // Note that stringstream behaves differently in gcc and in MSVC. You // can stream a NULL char pointer to it in the former, but not in the // latter (it causes an access violation if you do). The Message // class hides this difference by treating a NULL char pointer as // "(null)". class GTEST_API_ Message { private: // The type of basic IO manipulators (endl, ends, and flush) for // narrow streams. typedef std::ostream& (*BasicNarrowIoManip)(std::ostream&); public: // Constructs an empty Message. Message(); // Copy constructor. Message(const Message& msg) : ss_(new ::std::stringstream) { // NOLINT *ss_ << msg.GetString(); } // Constructs a Message from a C-string. explicit Message(const char* str) : ss_(new ::std::stringstream) { *ss_ << str; } #if GTEST_OS_SYMBIAN // Streams a value (either a pointer or not) to this object. template <typename T> inline Message& operator <<(const T& value) { StreamHelper(typename internal::is_pointer<T>::type(), value); return *this; } #else // Streams a non-pointer value to this object. template <typename T> inline Message& operator <<(const T& val) { // Some libraries overload << for STL containers. These // overloads are defined in the global namespace instead of ::std. // // C++'s symbol lookup rule (i.e. Koenig lookup) says that these // overloads are visible in either the std namespace or the global // namespace, but not other namespaces, including the testing // namespace which Google Test's Message class is in. // // To allow STL containers (and other types that has a << operator // defined in the global namespace) to be used in Google Test // assertions, testing::Message must access the custom << operator // from the global namespace. With this using declaration, // overloads of << defined in the global namespace and those // visible via Koenig lookup are both exposed in this function. #if GTEST_NO_LLVM_RAW_OSTREAM using ::operator <<; *ss_ << val; #else ::GTestStreamToHelper(*ss_, val); #endif return *this; } // Streams a pointer value to this object. // // This function is an overload of the previous one. When you // stream a pointer to a Message, this definition will be used as it // is more specialized. (The C++ Standard, section // [temp.func.order].) If you stream a non-pointer, then the // previous definition will be used. // // The reason for this overload is that streaming a NULL pointer to // ostream is undefined behavior. Depending on the compiler, you // may get "0", "(nil)", "(null)", or an access violation. To // ensure consistent result across compilers, we always treat NULL // as "(null)". template <typename T> inline Message& operator <<(T* const& pointer) { // NOLINT if (pointer == NULL) { *ss_ << "(null)"; } else { #if GTEST_NO_LLVM_RAW_OSTREAM *ss_ << pointer; #else ::GTestStreamToHelper(*ss_, pointer); #endif } return *this; } #endif // GTEST_OS_SYMBIAN // Since the basic IO manipulators are overloaded for both narrow // and wide streams, we have to provide this specialized definition // of operator <<, even though its body is the same as the // templatized version above. Without this definition, streaming // endl or other basic IO manipulators to Message will confuse the // compiler. Message& operator <<(BasicNarrowIoManip val) { *ss_ << val; return *this; } // Instead of 1/0, we want to see true/false for bool values. Message& operator <<(bool b) { return *this << (b ? "true" : "false"); } // These two overloads allow streaming a wide C string to a Message // using the UTF-8 encoding. Message& operator <<(const wchar_t* wide_c_str); Message& operator <<(wchar_t* wide_c_str); #if GTEST_HAS_STD_WSTRING // Converts the given wide string to a narrow string using the UTF-8 // encoding, and streams the result to this Message object. Message& operator <<(const ::std::wstring& wstr); #endif // GTEST_HAS_STD_WSTRING #if GTEST_HAS_GLOBAL_WSTRING // Converts the given wide string to a narrow string using the UTF-8 // encoding, and streams the result to this Message object. Message& operator <<(const ::wstring& wstr); #endif // GTEST_HAS_GLOBAL_WSTRING // Gets the text streamed to this object so far as an std::string. // Each '\0' character in the buffer is replaced with "\\0". // // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM. std::string GetString() const; private: #if GTEST_OS_SYMBIAN // These are needed as the Nokia Symbian Compiler cannot decide between // const T& and const T* in a function template. The Nokia compiler _can_ // decide between class template specializations for T and T*, so a // tr1::type_traits-like is_pointer works, and we can overload on that. template <typename T> inline void StreamHelper(internal::true_type /*is_pointer*/, T* pointer) { if (pointer == NULL) { *ss_ << "(null)"; } else { *ss_ << pointer; } } template <typename T> inline void StreamHelper(internal::false_type /*is_pointer*/, const T& value) { // See the comments in Message& operator <<(const T&) above for why // we need this using statement. using ::operator <<; *ss_ << value; } #endif // GTEST_OS_SYMBIAN // We'll hold the text streamed to this object here. const internal::scoped_ptr< ::std::stringstream> ss_; // We declare (but don't implement) this to prevent the compiler // from implementing the assignment operator. void operator=(const Message&); }; // Streams a Message to an ostream. inline std::ostream& operator <<(std::ostream& os, const Message& sb) { return os << sb.GetString(); } namespace internal { // Converts a streamable value to an std::string. A NULL pointer is // converted to "(null)". When the input value is a ::string, // ::std::string, ::wstring, or ::std::wstring object, each NUL // character in it is replaced with "\\0". template <typename T> std::string StreamableToString(const T& streamable) { return (Message() << streamable).GetString(); } } // namespace internal } // namespace testing #endif // GTEST_INCLUDE_GTEST_GTEST_MESSAGE_H_
0
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest/internal/gtest-internal.h
// Copyright 2005, 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. // // Authors: [email protected] (Zhanyong Wan), [email protected] (Sean Mcafee) // // The Google C++ Testing Framework (Google Test) // // This header file declares functions and macros used internally by // Google Test. They are subject to change without notice. #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_ #include "gtest/internal/gtest-port.h" #if GTEST_OS_LINUX # include <stdlib.h> # include <sys/types.h> # include <sys/wait.h> # include <unistd.h> #endif // GTEST_OS_LINUX #if GTEST_HAS_EXCEPTIONS # include <stdexcept> #endif #include <ctype.h> #include <float.h> #include <string.h> #include <iomanip> #include <limits> #include <map> #include <set> #include <string> #include <vector> #include "gtest/gtest-message.h" #include "gtest/internal/gtest-string.h" #include "gtest/internal/gtest-filepath.h" #include "gtest/internal/gtest-type-util.h" // Due to C++ preprocessor weirdness, we need double indirection to // concatenate two tokens when one of them is __LINE__. Writing // // foo ## __LINE__ // // will result in the token foo__LINE__, instead of foo followed by // the current line number. For more details, see // http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6 #define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar) #define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo ## bar class ProtocolMessage; namespace proto2 { class Message; } namespace testing { // Forward declarations. class AssertionResult; // Result of an assertion. class Message; // Represents a failure message. class Test; // Represents a test. class TestInfo; // Information about a test. class TestPartResult; // Result of a test part. class UnitTest; // A collection of test cases. template <typename T> ::std::string PrintToString(const T& value); namespace internal { struct TraceInfo; // Information about a trace point. class ScopedTrace; // Implements scoped trace. class TestInfoImpl; // Opaque implementation of TestInfo class UnitTestImpl; // Opaque implementation of UnitTest // The text used in failure messages to indicate the start of the // stack trace. GTEST_API_ extern const char kStackTraceMarker[]; // Two overloaded helpers for checking at compile time whether an // expression is a null pointer literal (i.e. NULL or any 0-valued // compile-time integral constant). Their return values have // different sizes, so we can use sizeof() to test which version is // picked by the compiler. These helpers have no implementations, as // we only need their signatures. // // Given IsNullLiteralHelper(x), the compiler will pick the first // version if x can be implicitly converted to Secret*, and pick the // second version otherwise. Since Secret is a secret and incomplete // type, the only expression a user can write that has type Secret* is // a null pointer literal. Therefore, we know that x is a null // pointer literal if and only if the first version is picked by the // compiler. char IsNullLiteralHelper(Secret* p); char (&IsNullLiteralHelper(...))[2]; // NOLINT // A compile-time bool constant that is true if and only if x is a // null pointer literal (i.e. NULL or any 0-valued compile-time // integral constant). #ifdef GTEST_ELLIPSIS_NEEDS_POD_ // We lose support for NULL detection where the compiler doesn't like // passing non-POD classes through ellipsis (...). # define GTEST_IS_NULL_LITERAL_(x) false #else # define GTEST_IS_NULL_LITERAL_(x) \ (sizeof(::testing::internal::IsNullLiteralHelper(x)) == 1) #endif // GTEST_ELLIPSIS_NEEDS_POD_ // Appends the user-supplied message to the Google-Test-generated message. GTEST_API_ std::string AppendUserMessage( const std::string& gtest_msg, const Message& user_msg); #if GTEST_HAS_EXCEPTIONS // This exception is thrown by (and only by) a failed Google Test // assertion when GTEST_FLAG(throw_on_failure) is true (if exceptions // are enabled). We derive it from std::runtime_error, which is for // errors presumably detectable only at run time. Since // std::runtime_error inherits from std::exception, many testing // frameworks know how to extract and print the message inside it. class GTEST_API_ GoogleTestFailureException : public ::std::runtime_error { public: explicit GoogleTestFailureException(const TestPartResult& failure); }; #endif // GTEST_HAS_EXCEPTIONS // A helper class for creating scoped traces in user programs. class GTEST_API_ ScopedTrace { public: // The c'tor pushes the given source file location and message onto // a trace stack maintained by Google Test. ScopedTrace(const char* file, int line, const Message& message); // The d'tor pops the info pushed by the c'tor. // // Note that the d'tor is not virtual in order to be efficient. // Don't inherit from ScopedTrace! ~ScopedTrace(); private: GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedTrace); } GTEST_ATTRIBUTE_UNUSED_; // A ScopedTrace object does its job in its // c'tor and d'tor. Therefore it doesn't // need to be used otherwise. namespace edit_distance { // Returns the optimal edits to go from 'left' to 'right'. // All edits cost the same, with replace having lower priority than // add/remove. // Simple implementation of the Wagner–Fischer algorithm. // See http://en.wikipedia.org/wiki/Wagner-Fischer_algorithm enum EditType { kMatch, kAdd, kRemove, kReplace }; GTEST_API_ std::vector<EditType> CalculateOptimalEdits( const std::vector<size_t>& left, const std::vector<size_t>& right); // Same as above, but the input is represented as strings. GTEST_API_ std::vector<EditType> CalculateOptimalEdits( const std::vector<std::string>& left, const std::vector<std::string>& right); // Create a diff of the input strings in Unified diff format. GTEST_API_ std::string CreateUnifiedDiff(const std::vector<std::string>& left, const std::vector<std::string>& right, size_t context = 2); } // namespace edit_distance // Calculate the diff between 'left' and 'right' and return it in unified diff // format. // If not null, stores in 'total_line_count' the total number of lines found // in left + right. GTEST_API_ std::string DiffStrings(const std::string& left, const std::string& right, size_t* total_line_count); // Constructs and returns the message for an equality assertion // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure. // // The first four parameters are the expressions used in the assertion // and their values, as strings. For example, for ASSERT_EQ(foo, bar) // where foo is 5 and bar is 6, we have: // // expected_expression: "foo" // actual_expression: "bar" // expected_value: "5" // actual_value: "6" // // The ignoring_case parameter is true iff the assertion is a // *_STRCASEEQ*. When it's true, the string " (ignoring case)" will // be inserted into the message. GTEST_API_ AssertionResult EqFailure(const char* expected_expression, const char* actual_expression, const std::string& expected_value, const std::string& actual_value, bool ignoring_case); // Constructs a failure message for Boolean assertions such as EXPECT_TRUE. GTEST_API_ std::string GetBoolAssertionFailureMessage( const AssertionResult& assertion_result, const char* expression_text, const char* actual_predicate_value, const char* expected_predicate_value); // This template class represents an IEEE floating-point number // (either single-precision or double-precision, depending on the // template parameters). // // The purpose of this class is to do more sophisticated number // comparison. (Due to round-off error, etc, it's very unlikely that // two floating-points will be equal exactly. Hence a naive // comparison by the == operation often doesn't work.) // // Format of IEEE floating-point: // // The most-significant bit being the leftmost, an IEEE // floating-point looks like // // sign_bit exponent_bits fraction_bits // // Here, sign_bit is a single bit that designates the sign of the // number. // // For float, there are 8 exponent bits and 23 fraction bits. // // For double, there are 11 exponent bits and 52 fraction bits. // // More details can be found at // http://en.wikipedia.org/wiki/IEEE_floating-point_standard. // // Template parameter: // // RawType: the raw floating-point type (either float or double) template <typename RawType> class FloatingPoint { public: // Defines the unsigned integer type that has the same size as the // floating point number. typedef typename TypeWithSize<sizeof(RawType)>::UInt Bits; // Constants. // # of bits in a number. static const size_t kBitCount = 8*sizeof(RawType); // # of fraction bits in a number. static const size_t kFractionBitCount = std::numeric_limits<RawType>::digits - 1; // # of exponent bits in a number. static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount; // The mask for the sign bit. static const Bits kSignBitMask = static_cast<Bits>(1) << (kBitCount - 1); // The mask for the fraction bits. static const Bits kFractionBitMask = ~static_cast<Bits>(0) >> (kExponentBitCount + 1); // The mask for the exponent bits. static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask); // How many ULP's (Units in the Last Place) we want to tolerate when // comparing two numbers. The larger the value, the more error we // allow. A 0 value means that two numbers must be exactly the same // to be considered equal. // // The maximum error of a single floating-point operation is 0.5 // units in the last place. On Intel CPU's, all floating-point // calculations are done with 80-bit precision, while double has 64 // bits. Therefore, 4 should be enough for ordinary use. // // See the following article for more details on ULP: // http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ static const size_t kMaxUlps = 4; // Constructs a FloatingPoint from a raw floating-point number. // // On an Intel CPU, passing a non-normalized NAN (Not a Number) // around may change its bits, although the new value is guaranteed // to be also a NAN. Therefore, don't expect this constructor to // preserve the bits in x when x is a NAN. explicit FloatingPoint(const RawType& x) { u_.value_ = x; } // Static methods // Reinterprets a bit pattern as a floating-point number. // // This function is needed to test the AlmostEquals() method. static RawType ReinterpretBits(const Bits bits) { FloatingPoint fp(0); fp.u_.bits_ = bits; return fp.u_.value_; } // Returns the floating-point number that represent positive infinity. static RawType Infinity() { return ReinterpretBits(kExponentBitMask); } // Returns the maximum representable finite floating-point number. static RawType Max(); // Non-static methods // Returns the bits that represents this number. const Bits &bits() const { return u_.bits_; } // Returns the exponent bits of this number. Bits exponent_bits() const { return kExponentBitMask & u_.bits_; } // Returns the fraction bits of this number. Bits fraction_bits() const { return kFractionBitMask & u_.bits_; } // Returns the sign bit of this number. Bits sign_bit() const { return kSignBitMask & u_.bits_; } // Returns true iff this is NAN (not a number). bool is_nan() const { // It's a NAN if the exponent bits are all ones and the fraction // bits are not entirely zeros. return (exponent_bits() == kExponentBitMask) && (fraction_bits() != 0); } // Returns true iff this number is at most kMaxUlps ULP's away from // rhs. In particular, this function: // // - returns false if either number is (or both are) NAN. // - treats really large numbers as almost equal to infinity. // - thinks +0.0 and -0.0 are 0 DLP's apart. bool AlmostEquals(const FloatingPoint& rhs) const { // The IEEE standard says that any comparison operation involving // a NAN must return false. if (is_nan() || rhs.is_nan()) return false; return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_) <= kMaxUlps; } private: // The data type used to store the actual floating-point number. union FloatingPointUnion { RawType value_; // The raw floating-point number. Bits bits_; // The bits that represent the number. }; // Converts an integer from the sign-and-magnitude representation to // the biased representation. More precisely, let N be 2 to the // power of (kBitCount - 1), an integer x is represented by the // unsigned number x + N. // // For instance, // // -N + 1 (the most negative number representable using // sign-and-magnitude) is represented by 1; // 0 is represented by N; and // N - 1 (the biggest number representable using // sign-and-magnitude) is represented by 2N - 1. // // Read http://en.wikipedia.org/wiki/Signed_number_representations // for more details on signed number representations. static Bits SignAndMagnitudeToBiased(const Bits &sam) { if (kSignBitMask & sam) { // sam represents a negative number. return ~sam + 1; } else { // sam represents a positive number. return kSignBitMask | sam; } } // Given two numbers in the sign-and-magnitude representation, // returns the distance between them as an unsigned number. static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits &sam1, const Bits &sam2) { const Bits biased1 = SignAndMagnitudeToBiased(sam1); const Bits biased2 = SignAndMagnitudeToBiased(sam2); return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1); } FloatingPointUnion u_; }; // We cannot use std::numeric_limits<T>::max() as it clashes with the max() // macro defined by <windows.h>. template <> inline float FloatingPoint<float>::Max() { return FLT_MAX; } template <> inline double FloatingPoint<double>::Max() { return DBL_MAX; } // Typedefs the instances of the FloatingPoint template class that we // care to use. typedef FloatingPoint<float> Float; typedef FloatingPoint<double> Double; // In order to catch the mistake of putting tests that use different // test fixture classes in the same test case, we need to assign // unique IDs to fixture classes and compare them. The TypeId type is // used to hold such IDs. The user should treat TypeId as an opaque // type: the only operation allowed on TypeId values is to compare // them for equality using the == operator. typedef const void* TypeId; template <typename T> class TypeIdHelper { public: // dummy_ must not have a const type. Otherwise an overly eager // compiler (e.g. MSVC 7.1 & 8.0) may try to merge // TypeIdHelper<T>::dummy_ for different Ts as an "optimization". static bool dummy_; }; template <typename T> bool TypeIdHelper<T>::dummy_ = false; // GetTypeId<T>() returns the ID of type T. Different values will be // returned for different types. Calling the function twice with the // same type argument is guaranteed to return the same ID. template <typename T> TypeId GetTypeId() { // The compiler is required to allocate a different // TypeIdHelper<T>::dummy_ variable for each T used to instantiate // the template. Therefore, the address of dummy_ is guaranteed to // be unique. return &(TypeIdHelper<T>::dummy_); } // Returns the type ID of ::testing::Test. Always call this instead // of GetTypeId< ::testing::Test>() to get the type ID of // ::testing::Test, as the latter may give the wrong result due to a // suspected linker bug when compiling Google Test as a Mac OS X // framework. GTEST_API_ TypeId GetTestTypeId(); // Defines the abstract factory interface that creates instances // of a Test object. class TestFactoryBase { public: virtual ~TestFactoryBase() {} // Creates a test instance to run. The instance is both created and destroyed // within TestInfoImpl::Run() virtual Test* CreateTest() = 0; protected: TestFactoryBase() {} private: GTEST_DISALLOW_COPY_AND_ASSIGN_(TestFactoryBase); }; // This class provides implementation of TeastFactoryBase interface. // It is used in TEST and TEST_F macros. template <class TestClass> class TestFactoryImpl : public TestFactoryBase { public: virtual Test* CreateTest() { return new TestClass; } }; #if GTEST_OS_WINDOWS // Predicate-formatters for implementing the HRESULT checking macros // {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED} // We pass a long instead of HRESULT to avoid causing an // include dependency for the HRESULT type. GTEST_API_ AssertionResult IsHRESULTSuccess(const char* expr, long hr); // NOLINT GTEST_API_ AssertionResult IsHRESULTFailure(const char* expr, long hr); // NOLINT #endif // GTEST_OS_WINDOWS // Types of SetUpTestCase() and TearDownTestCase() functions. typedef void (*SetUpTestCaseFunc)(); typedef void (*TearDownTestCaseFunc)(); struct CodeLocation { CodeLocation(const string& a_file, int a_line) : file(a_file), line(a_line) {} string file; int line; }; // Creates a new TestInfo object and registers it with Google Test; // returns the created object. // // Arguments: // // test_case_name: name of the test case // name: name of the test // type_param the name of the test's type parameter, or NULL if // this is not a typed or a type-parameterized test. // value_param text representation of the test's value parameter, // or NULL if this is not a type-parameterized test. // code_location: code location where the test is defined // fixture_class_id: ID of the test fixture class // set_up_tc: pointer to the function that sets up the test case // tear_down_tc: pointer to the function that tears down the test case // factory: pointer to the factory that creates a test object. // The newly created TestInfo instance will assume // ownership of the factory object. GTEST_API_ TestInfo* MakeAndRegisterTestInfo( const char* test_case_name, const char* name, const char* type_param, const char* value_param, CodeLocation code_location, TypeId fixture_class_id, SetUpTestCaseFunc set_up_tc, TearDownTestCaseFunc tear_down_tc, TestFactoryBase* factory); // If *pstr starts with the given prefix, modifies *pstr to be right // past the prefix and returns true; otherwise leaves *pstr unchanged // and returns false. None of pstr, *pstr, and prefix can be NULL. GTEST_API_ bool SkipPrefix(const char* prefix, const char** pstr); #if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P // State of the definition of a type-parameterized test case. class GTEST_API_ TypedTestCasePState { public: TypedTestCasePState() : registered_(false) {} // Adds the given test name to defined_test_names_ and return true // if the test case hasn't been registered; otherwise aborts the // program. bool AddTestName(const char* file, int line, const char* case_name, const char* test_name) { if (registered_) { fprintf(stderr, "%s Test %s must be defined before " "REGISTER_TYPED_TEST_CASE_P(%s, ...).\n", FormatFileLocation(file, line).c_str(), test_name, case_name); fflush(stderr); posix::Abort(); } registered_tests_.insert( ::std::make_pair(test_name, CodeLocation(file, line))); return true; } bool TestExists(const std::string& test_name) const { return registered_tests_.count(test_name) > 0; } const CodeLocation& GetCodeLocation(const std::string& test_name) const { RegisteredTestsMap::const_iterator it = registered_tests_.find(test_name); GTEST_CHECK_(it != registered_tests_.end()); return it->second; } // Verifies that registered_tests match the test names in // defined_test_names_; returns registered_tests if successful, or // aborts the program otherwise. const char* VerifyRegisteredTestNames( const char* file, int line, const char* registered_tests); private: typedef ::std::map<std::string, CodeLocation> RegisteredTestsMap; bool registered_; RegisteredTestsMap registered_tests_; }; // Skips to the first non-space char after the first comma in 'str'; // returns NULL if no comma is found in 'str'. inline const char* SkipComma(const char* str) { const char* comma = strchr(str, ','); if (comma == NULL) { return NULL; } while (IsSpace(*(++comma))) {} return comma; } // Returns the prefix of 'str' before the first comma in it; returns // the entire string if it contains no comma. inline std::string GetPrefixUntilComma(const char* str) { const char* comma = strchr(str, ','); return comma == NULL ? str : std::string(str, comma); } // Splits a given string on a given delimiter, populating a given // vector with the fields. void SplitString(const ::std::string& str, char delimiter, ::std::vector< ::std::string>* dest); // TypeParameterizedTest<Fixture, TestSel, Types>::Register() // registers a list of type-parameterized tests with Google Test. The // return value is insignificant - we just need to return something // such that we can call this function in a namespace scope. // // Implementation note: The GTEST_TEMPLATE_ macro declares a template // template parameter. It's defined in gtest-type-util.h. template <GTEST_TEMPLATE_ Fixture, class TestSel, typename Types> class TypeParameterizedTest { public: // 'index' is the index of the test in the type list 'Types' // specified in INSTANTIATE_TYPED_TEST_CASE_P(Prefix, TestCase, // Types). Valid values for 'index' are [0, N - 1] where N is the // length of Types. static bool Register(const char* prefix, CodeLocation code_location, const char* case_name, const char* test_names, int index) { typedef typename Types::Head Type; typedef Fixture<Type> FixtureClass; typedef typename GTEST_BIND_(TestSel, Type) TestClass; // First, registers the first type-parameterized test in the type // list. MakeAndRegisterTestInfo( (std::string(prefix) + (prefix[0] == '\0' ? "" : "/") + case_name + "/" + StreamableToString(index)).c_str(), StripTrailingSpaces(GetPrefixUntilComma(test_names)).c_str(), GetTypeName<Type>().c_str(), NULL, // No value parameter. code_location, GetTypeId<FixtureClass>(), TestClass::SetUpTestCase, TestClass::TearDownTestCase, new TestFactoryImpl<TestClass>); // Next, recurses (at compile time) with the tail of the type list. return TypeParameterizedTest<Fixture, TestSel, typename Types::Tail> ::Register(prefix, code_location, case_name, test_names, index + 1); } }; // The base case for the compile time recursion. template <GTEST_TEMPLATE_ Fixture, class TestSel> class TypeParameterizedTest<Fixture, TestSel, Types0> { public: static bool Register(const char* /*prefix*/, CodeLocation, const char* /*case_name*/, const char* /*test_names*/, int /*index*/) { return true; } }; // TypeParameterizedTestCase<Fixture, Tests, Types>::Register() // registers *all combinations* of 'Tests' and 'Types' with Google // Test. The return value is insignificant - we just need to return // something such that we can call this function in a namespace scope. template <GTEST_TEMPLATE_ Fixture, typename Tests, typename Types> class TypeParameterizedTestCase { public: static bool Register(const char* prefix, CodeLocation code_location, const TypedTestCasePState* state, const char* case_name, const char* test_names) { std::string test_name = StripTrailingSpaces( GetPrefixUntilComma(test_names)); if (!state->TestExists(test_name)) { fprintf(stderr, "Failed to get code location for test %s.%s at %s.", case_name, test_name.c_str(), FormatFileLocation(code_location.file.c_str(), code_location.line).c_str()); fflush(stderr); posix::Abort(); } const CodeLocation& test_location = state->GetCodeLocation(test_name); typedef typename Tests::Head Head; // First, register the first test in 'Test' for each type in 'Types'. TypeParameterizedTest<Fixture, Head, Types>::Register( prefix, test_location, case_name, test_names, 0); // Next, recurses (at compile time) with the tail of the test list. return TypeParameterizedTestCase<Fixture, typename Tests::Tail, Types> ::Register(prefix, code_location, state, case_name, SkipComma(test_names)); } }; // The base case for the compile time recursion. template <GTEST_TEMPLATE_ Fixture, typename Types> class TypeParameterizedTestCase<Fixture, Templates0, Types> { public: static bool Register(const char* /*prefix*/, CodeLocation, const TypedTestCasePState* /*state*/, const char* /*case_name*/, const char* /*test_names*/) { return true; } }; #endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P // Returns the current OS stack trace as an std::string. // // The maximum number of stack frames to be included is specified by // the gtest_stack_trace_depth flag. The skip_count parameter // specifies the number of top frames to be skipped, which doesn't // count against the number of frames to be included. // // For example, if Foo() calls Bar(), which in turn calls // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't. GTEST_API_ std::string GetCurrentOsStackTraceExceptTop( UnitTest* unit_test, int skip_count); // Helpers for suppressing warnings on unreachable code or constant // condition. // Always returns true. GTEST_API_ bool AlwaysTrue(); // Always returns false. inline bool AlwaysFalse() { return !AlwaysTrue(); } // Helper for suppressing false warning from Clang on a const char* // variable declared in a conditional expression always being NULL in // the else branch. struct GTEST_API_ ConstCharPtr { ConstCharPtr(const char* str) : value(str) {} operator bool() const { return true; } const char* value; }; // A simple Linear Congruential Generator for generating random // numbers with a uniform distribution. Unlike rand() and srand(), it // doesn't use global state (and therefore can't interfere with user // code). Unlike rand_r(), it's portable. An LCG isn't very random, // but it's good enough for our purposes. class GTEST_API_ Random { public: static const UInt32 kMaxRange = 1u << 31; explicit Random(UInt32 seed) : state_(seed) {} void Reseed(UInt32 seed) { state_ = seed; } // Generates a random number from [0, range). Crashes if 'range' is // 0 or greater than kMaxRange. UInt32 Generate(UInt32 range); private: UInt32 state_; GTEST_DISALLOW_COPY_AND_ASSIGN_(Random); }; // Defining a variable of type CompileAssertTypesEqual<T1, T2> will cause a // compiler error iff T1 and T2 are different types. template <typename T1, typename T2> struct CompileAssertTypesEqual; template <typename T> struct CompileAssertTypesEqual<T, T> { }; // Removes the reference from a type if it is a reference type, // otherwise leaves it unchanged. This is the same as // tr1::remove_reference, which is not widely available yet. template <typename T> struct RemoveReference { typedef T type; }; // NOLINT template <typename T> struct RemoveReference<T&> { typedef T type; }; // NOLINT // A handy wrapper around RemoveReference that works when the argument // T depends on template parameters. #define GTEST_REMOVE_REFERENCE_(T) \ typename ::testing::internal::RemoveReference<T>::type // Removes const from a type if it is a const type, otherwise leaves // it unchanged. This is the same as tr1::remove_const, which is not // widely available yet. template <typename T> struct RemoveConst { typedef T type; }; // NOLINT template <typename T> struct RemoveConst<const T> { typedef T type; }; // NOLINT // MSVC 8.0, Sun C++, and IBM XL C++ have a bug which causes the above // definition to fail to remove the const in 'const int[3]' and 'const // char[3][4]'. The following specialization works around the bug. template <typename T, size_t N> struct RemoveConst<const T[N]> { typedef typename RemoveConst<T>::type type[N]; }; #if defined(_MSC_VER) && _MSC_VER < 1400 // This is the only specialization that allows VC++ 7.1 to remove const in // 'const int[3] and 'const int[3][4]'. However, it causes trouble with GCC // and thus needs to be conditionally compiled. template <typename T, size_t N> struct RemoveConst<T[N]> { typedef typename RemoveConst<T>::type type[N]; }; #endif // A handy wrapper around RemoveConst that works when the argument // T depends on template parameters. #define GTEST_REMOVE_CONST_(T) \ typename ::testing::internal::RemoveConst<T>::type // Turns const U&, U&, const U, and U all into U. #define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \ GTEST_REMOVE_CONST_(GTEST_REMOVE_REFERENCE_(T)) // Adds reference to a type if it is not a reference type, // otherwise leaves it unchanged. This is the same as // tr1::add_reference, which is not widely available yet. template <typename T> struct AddReference { typedef T& type; }; // NOLINT template <typename T> struct AddReference<T&> { typedef T& type; }; // NOLINT // A handy wrapper around AddReference that works when the argument T // depends on template parameters. #define GTEST_ADD_REFERENCE_(T) \ typename ::testing::internal::AddReference<T>::type // Adds a reference to const on top of T as necessary. For example, // it transforms // // char ==> const char& // const char ==> const char& // char& ==> const char& // const char& ==> const char& // // The argument T must depend on some template parameters. #define GTEST_REFERENCE_TO_CONST_(T) \ GTEST_ADD_REFERENCE_(const GTEST_REMOVE_REFERENCE_(T)) // ImplicitlyConvertible<From, To>::value is a compile-time bool // constant that's true iff type From can be implicitly converted to // type To. template <typename From, typename To> class ImplicitlyConvertible { private: // We need the following helper functions only for their types. // They have no implementations. // MakeFrom() is an expression whose type is From. We cannot simply // use From(), as the type From may not have a public default // constructor. static typename AddReference<From>::type MakeFrom(); // These two functions are overloaded. Given an expression // Helper(x), the compiler will pick the first version if x can be // implicitly converted to type To; otherwise it will pick the // second version. // // The first version returns a value of size 1, and the second // version returns a value of size 2. Therefore, by checking the // size of Helper(x), which can be done at compile time, we can tell // which version of Helper() is used, and hence whether x can be // implicitly converted to type To. static char Helper(To); static char (&Helper(...))[2]; // NOLINT // We have to put the 'public' section after the 'private' section, // or MSVC refuses to compile the code. public: #if defined(__BORLANDC__) // C++Builder cannot use member overload resolution during template // instantiation. The simplest workaround is to use its C++0x type traits // functions (C++Builder 2009 and above only). static const bool value = __is_convertible(From, To); #else // MSVC warns about implicitly converting from double to int for // possible loss of data, so we need to temporarily disable the // warning. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4244) static const bool value = sizeof(Helper(ImplicitlyConvertible::MakeFrom())) == 1; GTEST_DISABLE_MSC_WARNINGS_POP_() #endif // __BORLANDC__ }; template <typename From, typename To> const bool ImplicitlyConvertible<From, To>::value; // IsAProtocolMessage<T>::value is a compile-time bool constant that's // true iff T is type ProtocolMessage, proto2::Message, or a subclass // of those. template <typename T> struct IsAProtocolMessage : public bool_constant< ImplicitlyConvertible<const T*, const ::ProtocolMessage*>::value || ImplicitlyConvertible<const T*, const ::proto2::Message*>::value> { }; // When the compiler sees expression IsContainerTest<C>(0), if C is an // STL-style container class, the first overload of IsContainerTest // will be viable (since both C::iterator* and C::const_iterator* are // valid types and NULL can be implicitly converted to them). It will // be picked over the second overload as 'int' is a perfect match for // the type of argument 0. If C::iterator or C::const_iterator is not // a valid type, the first overload is not viable, and the second // overload will be picked. Therefore, we can determine whether C is // a container class by checking the type of IsContainerTest<C>(0). // The value of the expression is insignificant. // // Note that we look for both C::iterator and C::const_iterator. The // reason is that C++ injects the name of a class as a member of the // class itself (e.g. you can refer to class iterator as either // 'iterator' or 'iterator::iterator'). If we look for C::iterator // only, for example, we would mistakenly think that a class named // iterator is an STL container. // // Also note that the simpler approach of overloading // IsContainerTest(typename C::const_iterator*) and // IsContainerTest(...) doesn't work with Visual Age C++ and Sun C++. typedef int IsContainer; template <class C> IsContainer IsContainerTest(int /* dummy */, typename C::iterator* /* it */ = NULL, typename C::const_iterator* /* const_it */ = NULL) { return 0; } typedef char IsNotContainer; template <class C> IsNotContainer IsContainerTest(long /* dummy */) { return '\0'; } // EnableIf<condition>::type is void when 'Cond' is true, and // undefined when 'Cond' is false. To use SFINAE to make a function // overload only apply when a particular expression is true, add // "typename EnableIf<expression>::type* = 0" as the last parameter. template<bool> struct EnableIf; template<> struct EnableIf<true> { typedef void type; }; // NOLINT // Utilities for native arrays. // ArrayEq() compares two k-dimensional native arrays using the // elements' operator==, where k can be any integer >= 0. When k is // 0, ArrayEq() degenerates into comparing a single pair of values. template <typename T, typename U> bool ArrayEq(const T* lhs, size_t size, const U* rhs); // This generic version is used when k is 0. template <typename T, typename U> inline bool ArrayEq(const T& lhs, const U& rhs) { return lhs == rhs; } // This overload is used when k >= 1. template <typename T, typename U, size_t N> inline bool ArrayEq(const T(&lhs)[N], const U(&rhs)[N]) { return internal::ArrayEq(lhs, N, rhs); } // This helper reduces code bloat. If we instead put its logic inside // the previous ArrayEq() function, arrays with different sizes would // lead to different copies of the template code. template <typename T, typename U> bool ArrayEq(const T* lhs, size_t size, const U* rhs) { for (size_t i = 0; i != size; i++) { if (!internal::ArrayEq(lhs[i], rhs[i])) return false; } return true; } // Finds the first element in the iterator range [begin, end) that // equals elem. Element may be a native array type itself. template <typename Iter, typename Element> Iter ArrayAwareFind(Iter begin, Iter end, const Element& elem) { for (Iter it = begin; it != end; ++it) { if (internal::ArrayEq(*it, elem)) return it; } return end; } // CopyArray() copies a k-dimensional native array using the elements' // operator=, where k can be any integer >= 0. When k is 0, // CopyArray() degenerates into copying a single value. template <typename T, typename U> void CopyArray(const T* from, size_t size, U* to); // This generic version is used when k is 0. template <typename T, typename U> inline void CopyArray(const T& from, U* to) { *to = from; } // This overload is used when k >= 1. template <typename T, typename U, size_t N> inline void CopyArray(const T(&from)[N], U(*to)[N]) { internal::CopyArray(from, N, *to); } // This helper reduces code bloat. If we instead put its logic inside // the previous CopyArray() function, arrays with different sizes // would lead to different copies of the template code. template <typename T, typename U> void CopyArray(const T* from, size_t size, U* to) { for (size_t i = 0; i != size; i++) { internal::CopyArray(from[i], to + i); } } // The relation between an NativeArray object (see below) and the // native array it represents. // We use 2 different structs to allow non-copyable types to be used, as long // as RelationToSourceReference() is passed. struct RelationToSourceReference {}; struct RelationToSourceCopy {}; // Adapts a native array to a read-only STL-style container. Instead // of the complete STL container concept, this adaptor only implements // members useful for Google Mock's container matchers. New members // should be added as needed. To simplify the implementation, we only // support Element being a raw type (i.e. having no top-level const or // reference modifier). It's the client's responsibility to satisfy // this requirement. Element can be an array type itself (hence // multi-dimensional arrays are supported). template <typename Element> class NativeArray { public: // STL-style container typedefs. typedef Element value_type; typedef Element* iterator; typedef const Element* const_iterator; // Constructs from a native array. References the source. NativeArray(const Element* array, size_t count, RelationToSourceReference) { InitRef(array, count); } // Constructs from a native array. Copies the source. NativeArray(const Element* array, size_t count, RelationToSourceCopy) { InitCopy(array, count); } // Copy constructor. NativeArray(const NativeArray& rhs) { (this->*rhs.clone_)(rhs.array_, rhs.size_); } ~NativeArray() { if (clone_ != &NativeArray::InitRef) delete[] array_; } // STL-style container methods. size_t size() const { return size_; } const_iterator begin() const { return array_; } const_iterator end() const { return array_ + size_; } bool operator==(const NativeArray& rhs) const { return size() == rhs.size() && ArrayEq(begin(), size(), rhs.begin()); } private: enum { kCheckTypeIsNotConstOrAReference = StaticAssertTypeEqHelper< Element, GTEST_REMOVE_REFERENCE_AND_CONST_(Element)>::value, }; // Initializes this object with a copy of the input. void InitCopy(const Element* array, size_t a_size) { Element* const copy = new Element[a_size]; CopyArray(array, a_size, copy); array_ = copy; size_ = a_size; clone_ = &NativeArray::InitCopy; } // Initializes this object with a reference of the input. void InitRef(const Element* array, size_t a_size) { array_ = array; size_ = a_size; clone_ = &NativeArray::InitRef; } const Element* array_; size_t size_; void (NativeArray::*clone_)(const Element*, size_t); GTEST_DISALLOW_ASSIGN_(NativeArray); }; } // namespace internal } // namespace testing #define GTEST_MESSAGE_AT_(file, line, message, result_type) \ ::testing::internal::AssertHelper(result_type, file, line, message) \ = ::testing::Message() #define GTEST_MESSAGE_(message, result_type) \ GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type) #define GTEST_FATAL_FAILURE_(message) \ return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure) #define GTEST_NONFATAL_FAILURE_(message) \ GTEST_MESSAGE_(message, ::testing::TestPartResult::kNonFatalFailure) #define GTEST_SUCCESS_(message) \ GTEST_MESSAGE_(message, ::testing::TestPartResult::kSuccess) // Suppresses MSVC warnings 4072 (unreachable code) for the code following // statement if it returns or throws (or doesn't return or throw in some // situations). #define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \ if (::testing::internal::AlwaysTrue()) { statement; } #define GTEST_TEST_THROW_(statement, expected_exception, fail) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (::testing::internal::ConstCharPtr gtest_msg = "") { \ bool gtest_caught_expected = false; \ try { \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ } \ catch (expected_exception const&) { \ gtest_caught_expected = true; \ } \ catch (...) { \ gtest_msg.value = \ "Expected: " #statement " throws an exception of type " \ #expected_exception ".\n Actual: it throws a different type."; \ goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ } \ if (!gtest_caught_expected) { \ gtest_msg.value = \ "Expected: " #statement " throws an exception of type " \ #expected_exception ".\n Actual: it throws nothing."; \ goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__); \ } \ } else \ GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__): \ fail(gtest_msg.value) #define GTEST_TEST_NO_THROW_(statement, fail) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (::testing::internal::AlwaysTrue()) { \ try { \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ } \ catch (...) { \ goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \ } \ } else \ GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__): \ fail("Expected: " #statement " doesn't throw an exception.\n" \ " Actual: it throws.") #define GTEST_TEST_ANY_THROW_(statement, fail) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (::testing::internal::AlwaysTrue()) { \ bool gtest_caught_any = false; \ try { \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ } \ catch (...) { \ gtest_caught_any = true; \ } \ if (!gtest_caught_any) { \ goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \ } \ } else \ GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__): \ fail("Expected: " #statement " throws an exception.\n" \ " Actual: it doesn't.") // Implements Boolean test assertions such as EXPECT_TRUE. expression can be // either a boolean expression or an AssertionResult. text is a textual // represenation of expression as it was passed into the EXPECT_TRUE. #define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (const ::testing::AssertionResult gtest_ar_ = \ ::testing::AssertionResult(expression)) \ ; \ else \ fail(::testing::internal::GetBoolAssertionFailureMessage(\ gtest_ar_, text, #actual, #expected).c_str()) #define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (::testing::internal::AlwaysTrue()) { \ ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ if (gtest_fatal_failure_checker.has_new_fatal_failure()) { \ goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__); \ } \ } else \ GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__): \ fail("Expected: " #statement " doesn't generate new fatal " \ "failures in the current thread.\n" \ " Actual: it does.") // Expands to the name of the class that implements the given test. #define GTEST_TEST_CLASS_NAME_(test_case_name, test_name) \ test_case_name##_##test_name##_Test // Helper macro for defining tests. #define GTEST_TEST_(test_case_name, test_name, parent_class, parent_id)\ class GTEST_TEST_CLASS_NAME_(test_case_name, test_name) : public parent_class {\ public:\ GTEST_TEST_CLASS_NAME_(test_case_name, test_name)() {}\ private:\ virtual void TestBody();\ static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_;\ GTEST_DISALLOW_COPY_AND_ASSIGN_(\ GTEST_TEST_CLASS_NAME_(test_case_name, test_name));\ };\ \ ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_case_name, test_name)\ ::test_info_ =\ ::testing::internal::MakeAndRegisterTestInfo(\ #test_case_name, #test_name, NULL, NULL, \ ::testing::internal::CodeLocation(__FILE__, __LINE__), \ (parent_id), \ parent_class::SetUpTestCase, \ parent_class::TearDownTestCase, \ new ::testing::internal::TestFactoryImpl<\ GTEST_TEST_CLASS_NAME_(test_case_name, test_name)>);\ void GTEST_TEST_CLASS_NAME_(test_case_name, test_name)::TestBody() #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_
0
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest/internal/gtest-param-util.h
// 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. // // Author: [email protected] (Vlad Losev) // Type and function utilities for implementing parameterized tests. #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_ #include <ctype.h> #include <iterator> #include <set> #include <utility> #include <vector> // scripts/fuse_gtest.py depends on gtest's own header being #included // *unconditionally*. Therefore these #includes cannot be moved // inside #if GTEST_HAS_PARAM_TEST. #include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-linked_ptr.h" #include "gtest/internal/gtest-port.h" #include "gtest/gtest-printers.h" #if GTEST_HAS_PARAM_TEST namespace testing { // Input to a parameterized test name generator, describing a test parameter. // Consists of the parameter value and the integer parameter index. template <class ParamType> struct TestParamInfo { TestParamInfo(const ParamType& a_param, size_t an_index) : param(a_param), index(an_index) {} ParamType param; size_t index; }; // A builtin parameterized test name generator which returns the result of // testing::PrintToString. struct PrintToStringParamName { template <class ParamType> std::string operator()(const TestParamInfo<ParamType>& info) const { return PrintToString(info.param); } }; namespace internal { // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Outputs a message explaining invalid registration of different // fixture class for the same test case. This may happen when // TEST_P macro is used to define two tests with the same name // but in different namespaces. GTEST_API_ void ReportInvalidTestCaseType(const char* test_case_name, CodeLocation code_location); template <typename> class ParamGeneratorInterface; template <typename> class ParamGenerator; // Interface for iterating over elements provided by an implementation // of ParamGeneratorInterface<T>. template <typename T> class ParamIteratorInterface { public: virtual ~ParamIteratorInterface() {} // A pointer to the base generator instance. // Used only for the purposes of iterator comparison // to make sure that two iterators belong to the same generator. virtual const ParamGeneratorInterface<T>* BaseGenerator() const = 0; // Advances iterator to point to the next element // provided by the generator. The caller is responsible // for not calling Advance() on an iterator equal to // BaseGenerator()->End(). virtual void Advance() = 0; // Clones the iterator object. Used for implementing copy semantics // of ParamIterator<T>. virtual ParamIteratorInterface* Clone() const = 0; // Dereferences the current iterator and provides (read-only) access // to the pointed value. It is the caller's responsibility not to call // Current() on an iterator equal to BaseGenerator()->End(). // Used for implementing ParamGenerator<T>::operator*(). virtual const T* Current() const = 0; // Determines whether the given iterator and other point to the same // element in the sequence generated by the generator. // Used for implementing ParamGenerator<T>::operator==(). virtual bool Equals(const ParamIteratorInterface& other) const = 0; }; // Class iterating over elements provided by an implementation of // ParamGeneratorInterface<T>. It wraps ParamIteratorInterface<T> // and implements the const forward iterator concept. template <typename T> class ParamIterator { public: typedef T value_type; typedef const T& reference; typedef ptrdiff_t difference_type; // ParamIterator assumes ownership of the impl_ pointer. ParamIterator(const ParamIterator& other) : impl_(other.impl_->Clone()) {} ParamIterator& operator=(const ParamIterator& other) { if (this != &other) impl_.reset(other.impl_->Clone()); return *this; } const T& operator*() const { return *impl_->Current(); } const T* operator->() const { return impl_->Current(); } // Prefix version of operator++. ParamIterator& operator++() { impl_->Advance(); return *this; } // Postfix version of operator++. ParamIterator operator++(int /*unused*/) { ParamIteratorInterface<T>* clone = impl_->Clone(); impl_->Advance(); return ParamIterator(clone); } bool operator==(const ParamIterator& other) const { return impl_.get() == other.impl_.get() || impl_->Equals(*other.impl_); } bool operator!=(const ParamIterator& other) const { return !(*this == other); } private: friend class ParamGenerator<T>; explicit ParamIterator(ParamIteratorInterface<T>* impl) : impl_(impl) {} scoped_ptr<ParamIteratorInterface<T> > impl_; }; // ParamGeneratorInterface<T> is the binary interface to access generators // defined in other translation units. template <typename T> class ParamGeneratorInterface { public: typedef T ParamType; virtual ~ParamGeneratorInterface() {} // Generator interface definition virtual ParamIteratorInterface<T>* Begin() const = 0; virtual ParamIteratorInterface<T>* End() const = 0; }; // Wraps ParamGeneratorInterface<T> and provides general generator syntax // compatible with the STL Container concept. // This class implements copy initialization semantics and the contained // ParamGeneratorInterface<T> instance is shared among all copies // of the original object. This is possible because that instance is immutable. template<typename T> class ParamGenerator { public: typedef ParamIterator<T> iterator; explicit ParamGenerator(ParamGeneratorInterface<T>* impl) : impl_(impl) {} ParamGenerator(const ParamGenerator& other) : impl_(other.impl_) {} ParamGenerator& operator=(const ParamGenerator& other) { impl_ = other.impl_; return *this; } iterator begin() const { return iterator(impl_->Begin()); } iterator end() const { return iterator(impl_->End()); } private: linked_ptr<const ParamGeneratorInterface<T> > impl_; }; // Generates values from a range of two comparable values. Can be used to // generate sequences of user-defined types that implement operator+() and // operator<(). // This class is used in the Range() function. template <typename T, typename IncrementT> class RangeGenerator : public ParamGeneratorInterface<T> { public: RangeGenerator(T begin, T end, IncrementT step) : begin_(begin), end_(end), step_(step), end_index_(CalculateEndIndex(begin, end, step)) {} virtual ~RangeGenerator() {} virtual ParamIteratorInterface<T>* Begin() const { return new Iterator(this, begin_, 0, step_); } virtual ParamIteratorInterface<T>* End() const { return new Iterator(this, end_, end_index_, step_); } private: class Iterator : public ParamIteratorInterface<T> { public: Iterator(const ParamGeneratorInterface<T>* base, T value, int index, IncrementT step) : base_(base), value_(value), index_(index), step_(step) {} virtual ~Iterator() {} virtual const ParamGeneratorInterface<T>* BaseGenerator() const { return base_; } virtual void Advance() { value_ = static_cast<T>(value_ + step_); index_++; } virtual ParamIteratorInterface<T>* Clone() const { return new Iterator(*this); } virtual const T* Current() const { return &value_; } virtual bool Equals(const ParamIteratorInterface<T>& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " << "from different generators." << std::endl; const int other_index = CheckedDowncastToActualType<const Iterator>(&other)->index_; return index_ == other_index; } private: Iterator(const Iterator& other) : ParamIteratorInterface<T>(), base_(other.base_), value_(other.value_), index_(other.index_), step_(other.step_) {} // No implementation - assignment is unsupported. void operator=(const Iterator& other); const ParamGeneratorInterface<T>* const base_; T value_; int index_; const IncrementT step_; }; // class RangeGenerator::Iterator static int CalculateEndIndex(const T& begin, const T& end, const IncrementT& step) { int end_index = 0; for (T i = begin; i < end; i = static_cast<T>(i + step)) end_index++; return end_index; } // No implementation - assignment is unsupported. void operator=(const RangeGenerator& other); const T begin_; const T end_; const IncrementT step_; // The index for the end() iterator. All the elements in the generated // sequence are indexed (0-based) to aid iterator comparison. const int end_index_; }; // class RangeGenerator // Generates values from a pair of STL-style iterators. Used in the // ValuesIn() function. The elements are copied from the source range // since the source can be located on the stack, and the generator // is likely to persist beyond that stack frame. template <typename T> class ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> { public: template <typename ForwardIterator> ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end) : container_(begin, end) {} virtual ~ValuesInIteratorRangeGenerator() {} virtual ParamIteratorInterface<T>* Begin() const { return new Iterator(this, container_.begin()); } virtual ParamIteratorInterface<T>* End() const { return new Iterator(this, container_.end()); } private: typedef typename ::std::vector<T> ContainerType; class Iterator : public ParamIteratorInterface<T> { public: Iterator(const ParamGeneratorInterface<T>* base, typename ContainerType::const_iterator iterator) : base_(base), iterator_(iterator) {} virtual ~Iterator() {} virtual const ParamGeneratorInterface<T>* BaseGenerator() const { return base_; } virtual void Advance() { ++iterator_; value_.reset(); } virtual ParamIteratorInterface<T>* Clone() const { return new Iterator(*this); } // We need to use cached value referenced by iterator_ because *iterator_ // can return a temporary object (and of type other then T), so just // having "return &*iterator_;" doesn't work. // value_ is updated here and not in Advance() because Advance() // can advance iterator_ beyond the end of the range, and we cannot // detect that fact. The client code, on the other hand, is // responsible for not calling Current() on an out-of-range iterator. virtual const T* Current() const { if (value_.get() == NULL) value_.reset(new T(*iterator_)); return value_.get(); } virtual bool Equals(const ParamIteratorInterface<T>& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " << "from different generators." << std::endl; return iterator_ == CheckedDowncastToActualType<const Iterator>(&other)->iterator_; } private: Iterator(const Iterator& other) // The explicit constructor call suppresses a false warning // emitted by gcc when supplied with the -Wextra option. : ParamIteratorInterface<T>(), base_(other.base_), iterator_(other.iterator_) {} const ParamGeneratorInterface<T>* const base_; typename ContainerType::const_iterator iterator_; // A cached value of *iterator_. We keep it here to allow access by // pointer in the wrapping iterator's operator->(). // value_ needs to be mutable to be accessed in Current(). // Use of scoped_ptr helps manage cached value's lifetime, // which is bound by the lifespan of the iterator itself. mutable scoped_ptr<const T> value_; }; // class ValuesInIteratorRangeGenerator::Iterator // No implementation - assignment is unsupported. void operator=(const ValuesInIteratorRangeGenerator& other); const ContainerType container_; }; // class ValuesInIteratorRangeGenerator // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Default parameterized test name generator, returns a string containing the // integer test parameter index. template <class ParamType> std::string DefaultParamName(const TestParamInfo<ParamType>& info) { Message name_stream; name_stream << info.index; return name_stream.GetString(); } // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Parameterized test name overload helpers, which help the // INSTANTIATE_TEST_CASE_P macro choose between the default parameterized // test name generator and user param name generator. template <class ParamType, class ParamNameGenFunctor> ParamNameGenFunctor GetParamNameGen(ParamNameGenFunctor func) { return func; } template <class ParamType> struct ParamNameGenFunc { typedef std::string Type(const TestParamInfo<ParamType>&); }; template <class ParamType> typename ParamNameGenFunc<ParamType>::Type *GetParamNameGen() { return DefaultParamName; } // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Stores a parameter value and later creates tests parameterized with that // value. template <class TestClass> class ParameterizedTestFactory : public TestFactoryBase { public: typedef typename TestClass::ParamType ParamType; explicit ParameterizedTestFactory(ParamType parameter) : parameter_(parameter) {} virtual Test* CreateTest() { TestClass::SetParam(&parameter_); return new TestClass(); } private: const ParamType parameter_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestFactory); }; // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // TestMetaFactoryBase is a base class for meta-factories that create // test factories for passing into MakeAndRegisterTestInfo function. template <class ParamType> class TestMetaFactoryBase { public: virtual ~TestMetaFactoryBase() {} virtual TestFactoryBase* CreateTestFactory(ParamType parameter) = 0; }; // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // TestMetaFactory creates test factories for passing into // MakeAndRegisterTestInfo function. Since MakeAndRegisterTestInfo receives // ownership of test factory pointer, same factory object cannot be passed // into that method twice. But ParameterizedTestCaseInfo is going to call // it for each Test/Parameter value combination. Thus it needs meta factory // creator class. template <class TestCase> class TestMetaFactory : public TestMetaFactoryBase<typename TestCase::ParamType> { public: typedef typename TestCase::ParamType ParamType; TestMetaFactory() {} virtual TestFactoryBase* CreateTestFactory(ParamType parameter) { return new ParameterizedTestFactory<TestCase>(parameter); } private: GTEST_DISALLOW_COPY_AND_ASSIGN_(TestMetaFactory); }; // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // ParameterizedTestCaseInfoBase is a generic interface // to ParameterizedTestCaseInfo classes. ParameterizedTestCaseInfoBase // accumulates test information provided by TEST_P macro invocations // and generators provided by INSTANTIATE_TEST_CASE_P macro invocations // and uses that information to register all resulting test instances // in RegisterTests method. The ParameterizeTestCaseRegistry class holds // a collection of pointers to the ParameterizedTestCaseInfo objects // and calls RegisterTests() on each of them when asked. class ParameterizedTestCaseInfoBase { public: virtual ~ParameterizedTestCaseInfoBase() {} // Base part of test case name for display purposes. virtual const string& GetTestCaseName() const = 0; // Test case id to verify identity. virtual TypeId GetTestCaseTypeId() const = 0; // UnitTest class invokes this method to register tests in this // test case right before running them in RUN_ALL_TESTS macro. // This method should not be called more then once on any single // instance of a ParameterizedTestCaseInfoBase derived class. virtual void RegisterTests() = 0; protected: ParameterizedTestCaseInfoBase() {} private: GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseInfoBase); }; // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // ParameterizedTestCaseInfo accumulates tests obtained from TEST_P // macro invocations for a particular test case and generators // obtained from INSTANTIATE_TEST_CASE_P macro invocations for that // test case. It registers tests with all values generated by all // generators when asked. template <class TestCase> class ParameterizedTestCaseInfo : public ParameterizedTestCaseInfoBase { public: // ParamType and GeneratorCreationFunc are private types but are required // for declarations of public methods AddTestPattern() and // AddTestCaseInstantiation(). typedef typename TestCase::ParamType ParamType; // A function that returns an instance of appropriate generator type. typedef ParamGenerator<ParamType>(GeneratorCreationFunc)(); typedef typename ParamNameGenFunc<ParamType>::Type ParamNameGeneratorFunc; explicit ParameterizedTestCaseInfo( const char* name, CodeLocation code_location) : test_case_name_(name), code_location_(code_location) {} // Test case base name for display purposes. virtual const string& GetTestCaseName() const { return test_case_name_; } // Test case id to verify identity. virtual TypeId GetTestCaseTypeId() const { return GetTypeId<TestCase>(); } // TEST_P macro uses AddTestPattern() to record information // about a single test in a LocalTestInfo structure. // test_case_name is the base name of the test case (without invocation // prefix). test_base_name is the name of an individual test without // parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is // test case base name and DoBar is test base name. void AddTestPattern(const char* test_case_name, const char* test_base_name, TestMetaFactoryBase<ParamType>* meta_factory) { tests_.push_back(linked_ptr<TestInfo>(new TestInfo(test_case_name, test_base_name, meta_factory))); } // INSTANTIATE_TEST_CASE_P macro uses AddGenerator() to record information // about a generator. int AddTestCaseInstantiation(const string& instantiation_name, GeneratorCreationFunc* func, ParamNameGeneratorFunc* name_func, const char* file, int line) { instantiations_.push_back( InstantiationInfo(instantiation_name, func, name_func, file, line)); return 0; // Return value used only to run this method in namespace scope. } // UnitTest class invokes this method to register tests in this test case // test cases right before running tests in RUN_ALL_TESTS macro. // This method should not be called more then once on any single // instance of a ParameterizedTestCaseInfoBase derived class. // UnitTest has a guard to prevent from calling this method more then once. virtual void RegisterTests() { for (typename TestInfoContainer::iterator test_it = tests_.begin(); test_it != tests_.end(); ++test_it) { linked_ptr<TestInfo> test_info = *test_it; for (typename InstantiationContainer::iterator gen_it = instantiations_.begin(); gen_it != instantiations_.end(); ++gen_it) { const string& instantiation_name = gen_it->name; ParamGenerator<ParamType> generator((*gen_it->generator)()); ParamNameGeneratorFunc* name_func = gen_it->name_func; const char* file = gen_it->file; int line = gen_it->line; string test_case_name; if ( !instantiation_name.empty() ) test_case_name = instantiation_name + "/"; test_case_name += test_info->test_case_base_name; size_t i = 0; std::set<std::string> test_param_names; for (typename ParamGenerator<ParamType>::iterator param_it = generator.begin(); param_it != generator.end(); ++param_it, ++i) { Message test_name_stream; std::string param_name = name_func( TestParamInfo<ParamType>(*param_it, i)); GTEST_CHECK_(IsValidParamName(param_name)) << "Parameterized test name '" << param_name << "' is invalid, in " << file << " line " << line << std::endl; GTEST_CHECK_(test_param_names.count(param_name) == 0) << "Duplicate parameterized test name '" << param_name << "', in " << file << " line " << line << std::endl; test_param_names.insert(param_name); test_name_stream << test_info->test_base_name << "/" << param_name; MakeAndRegisterTestInfo( test_case_name.c_str(), test_name_stream.GetString().c_str(), NULL, // No type parameter. PrintToString(*param_it).c_str(), code_location_, GetTestCaseTypeId(), TestCase::SetUpTestCase, TestCase::TearDownTestCase, test_info->test_meta_factory->CreateTestFactory(*param_it)); } // for param_it } // for gen_it } // for test_it } // RegisterTests private: // LocalTestInfo structure keeps information about a single test registered // with TEST_P macro. struct TestInfo { TestInfo(const char* a_test_case_base_name, const char* a_test_base_name, TestMetaFactoryBase<ParamType>* a_test_meta_factory) : test_case_base_name(a_test_case_base_name), test_base_name(a_test_base_name), test_meta_factory(a_test_meta_factory) {} const string test_case_base_name; const string test_base_name; const scoped_ptr<TestMetaFactoryBase<ParamType> > test_meta_factory; }; typedef ::std::vector<linked_ptr<TestInfo> > TestInfoContainer; // Records data received from INSTANTIATE_TEST_CASE_P macros: // <Instantiation name, Sequence generator creation function, // Name generator function, Source file, Source line> struct InstantiationInfo { InstantiationInfo(const std::string &name_in, GeneratorCreationFunc* generator_in, ParamNameGeneratorFunc* name_func_in, const char* file_in, int line_in) : name(name_in), generator(generator_in), name_func(name_func_in), file(file_in), line(line_in) {} std::string name; GeneratorCreationFunc* generator; ParamNameGeneratorFunc* name_func; const char* file; int line; }; typedef ::std::vector<InstantiationInfo> InstantiationContainer; static bool IsValidParamName(const std::string& name) { // Check for empty string if (name.empty()) return false; // Check for invalid characters for (std::string::size_type index = 0; index < name.size(); ++index) { if (!isalnum(name[index]) && name[index] != '_') return false; } return true; } const string test_case_name_; CodeLocation code_location_; TestInfoContainer tests_; InstantiationContainer instantiations_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseInfo); }; // class ParameterizedTestCaseInfo // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // ParameterizedTestCaseRegistry contains a map of ParameterizedTestCaseInfoBase // classes accessed by test case names. TEST_P and INSTANTIATE_TEST_CASE_P // macros use it to locate their corresponding ParameterizedTestCaseInfo // descriptors. class ParameterizedTestCaseRegistry { public: ParameterizedTestCaseRegistry() {} ~ParameterizedTestCaseRegistry() { for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); it != test_case_infos_.end(); ++it) { delete *it; } } // Looks up or creates and returns a structure containing information about // tests and instantiations of a particular test case. template <class TestCase> ParameterizedTestCaseInfo<TestCase>* GetTestCasePatternHolder( const char* test_case_name, CodeLocation code_location) { ParameterizedTestCaseInfo<TestCase>* typed_test_info = NULL; for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); it != test_case_infos_.end(); ++it) { if ((*it)->GetTestCaseName() == test_case_name) { if ((*it)->GetTestCaseTypeId() != GetTypeId<TestCase>()) { // Complain about incorrect usage of Google Test facilities // and terminate the program since we cannot guaranty correct // test case setup and tear-down in this case. ReportInvalidTestCaseType(test_case_name, code_location); posix::Abort(); } else { // At this point we are sure that the object we found is of the same // type we are looking for, so we downcast it to that type // without further checks. typed_test_info = CheckedDowncastToActualType< ParameterizedTestCaseInfo<TestCase> >(*it); } break; } } if (typed_test_info == NULL) { typed_test_info = new ParameterizedTestCaseInfo<TestCase>( test_case_name, code_location); test_case_infos_.push_back(typed_test_info); } return typed_test_info; } void RegisterTests() { for (TestCaseInfoContainer::iterator it = test_case_infos_.begin(); it != test_case_infos_.end(); ++it) { (*it)->RegisterTests(); } } private: typedef ::std::vector<ParameterizedTestCaseInfoBase*> TestCaseInfoContainer; TestCaseInfoContainer test_case_infos_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ParameterizedTestCaseRegistry); }; } // namespace internal } // namespace testing #endif // GTEST_HAS_PARAM_TEST #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_
0
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest/internal/gtest-filepath.h
// 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. // // Author: [email protected] (Keith Ray) // // Google Test filepath utilities // // This header file declares classes and functions used internally by // Google Test. They are subject to change without notice. // // This file is #included in <gtest/internal/gtest-internal.h>. // Do not include this header file separately! #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_ #include "gtest/internal/gtest-string.h" namespace testing { namespace internal { // FilePath - a class for file and directory pathname manipulation which // handles platform-specific conventions (like the pathname separator). // Used for helper functions for naming files in a directory for xml output. // Except for Set methods, all methods are const or static, which provides an // "immutable value object" -- useful for peace of mind. // A FilePath with a value ending in a path separator ("like/this/") represents // a directory, otherwise it is assumed to represent a file. In either case, // it may or may not represent an actual file or directory in the file system. // Names are NOT checked for syntax correctness -- no checking for illegal // characters, malformed paths, etc. class GTEST_API_ FilePath { public: FilePath() : pathname_("") { } FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) { } explicit FilePath(const std::string& pathname) : pathname_(pathname) { Normalize(); } FilePath& operator=(const FilePath& rhs) { Set(rhs); return *this; } void Set(const FilePath& rhs) { pathname_ = rhs.pathname_; } const std::string& string() const { return pathname_; } const char* c_str() const { return pathname_.c_str(); } // Returns the current working directory, or "" if unsuccessful. static FilePath GetCurrentDir(); // Given directory = "dir", base_name = "test", number = 0, // extension = "xml", returns "dir/test.xml". If number is greater // than zero (e.g., 12), returns "dir/test_12.xml". // On Windows platform, uses \ as the separator rather than /. static FilePath MakeFileName(const FilePath& directory, const FilePath& base_name, int number, const char* extension); // Given directory = "dir", relative_path = "test.xml", // returns "dir/test.xml". // On Windows, uses \ as the separator rather than /. static FilePath ConcatPaths(const FilePath& directory, const FilePath& relative_path); // Returns a pathname for a file that does not currently exist. The pathname // will be directory/base_name.extension or // directory/base_name_<number>.extension if directory/base_name.extension // already exists. The number will be incremented until a pathname is found // that does not already exist. // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'. // There could be a race condition if two or more processes are calling this // function at the same time -- they could both pick the same filename. static FilePath GenerateUniqueFileName(const FilePath& directory, const FilePath& base_name, const char* extension); // Returns true iff the path is "". bool IsEmpty() const { return pathname_.empty(); } // If input name has a trailing separator character, removes it and returns // the name, otherwise return the name string unmodified. // On Windows platform, uses \ as the separator, other platforms use /. FilePath RemoveTrailingPathSeparator() const; // Returns a copy of the FilePath with the directory part removed. // Example: FilePath("path/to/file").RemoveDirectoryName() returns // FilePath("file"). If there is no directory part ("just_a_file"), it returns // the FilePath unmodified. If there is no file part ("just_a_dir/") it // returns an empty FilePath (""). // On Windows platform, '\' is the path separator, otherwise it is '/'. FilePath RemoveDirectoryName() const; // RemoveFileName returns the directory path with the filename removed. // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/". // If the FilePath is "a_file" or "/a_file", RemoveFileName returns // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does // not have a file, like "just/a/dir/", it returns the FilePath unmodified. // On Windows platform, '\' is the path separator, otherwise it is '/'. FilePath RemoveFileName() const; // Returns a copy of the FilePath with the case-insensitive extension removed. // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns // FilePath("dir/file"). If a case-insensitive extension is not // found, returns a copy of the original FilePath. FilePath RemoveExtension(const char* extension) const; // Creates directories so that path exists. Returns true if successful or if // the directories already exist; returns false if unable to create // directories for any reason. Will also return false if the FilePath does // not represent a directory (that is, it doesn't end with a path separator). bool CreateDirectoriesRecursively() const; // Create the directory so that path exists. Returns true if successful or // if the directory already exists; returns false if unable to create the // directory for any reason, including if the parent directory does not // exist. Not named "CreateDirectory" because that's a macro on Windows. bool CreateFolder() const; // Returns true if FilePath describes something in the file-system, // either a file, directory, or whatever, and that something exists. bool FileOrDirectoryExists() const; // Returns true if pathname describes a directory in the file-system // that exists. bool DirectoryExists() const; // Returns true if FilePath ends with a path separator, which indicates that // it is intended to represent a directory. Returns false otherwise. // This does NOT check that a directory (or file) actually exists. bool IsDirectory() const; // Returns true if pathname describes a root directory. (Windows has one // root directory per disk drive.) bool IsRootDirectory() const; // Returns true if pathname describes an absolute path. bool IsAbsolutePath() const; private: // Replaces multiple consecutive separators with a single separator. // For example, "bar///foo" becomes "bar/foo". Does not eliminate other // redundancies that might be in a pathname involving "." or "..". // // A pathname with multiple consecutive separators may occur either through // user error or as a result of some scripts or APIs that generate a pathname // with a trailing separator. On other platforms the same API or script // may NOT generate a pathname with a trailing "/". Then elsewhere that // pathname may have another "/" and pathname components added to it, // without checking for the separator already being there. // The script language and operating system may allow paths like "foo//bar" // but some of the functions in FilePath will not handle that correctly. In // particular, RemoveTrailingPathSeparator() only removes one separator, and // it is called in CreateDirectoriesRecursively() assuming that it will change // a pathname from directory syntax (trailing separator) to filename syntax. // // On Windows this method also replaces the alternate path separator '/' with // the primary path separator '\\', so that for example "bar\\/\\foo" becomes // "bar\\foo". void Normalize(); // Returns a pointer to the last occurence of a valid path separator in // the FilePath. On Windows, for example, both '/' and '\' are valid path // separators. Returns NULL if no path separator was found. const char* FindLastPathSeparator() const; std::string pathname_; }; // class FilePath } // namespace internal } // namespace testing #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_
0
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest/internal/gtest-param-util-generated.h
// This file was GENERATED by command: // pump.py gtest-param-util-generated.h.pump // DO NOT EDIT BY HAND!!! // 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. // // Author: [email protected] (Vlad Losev) // Type and function utilities for implementing parameterized tests. // This file is generated by a SCRIPT. DO NOT EDIT BY HAND! // // Currently Google Test supports at most 50 arguments in Values, // and at most 10 arguments in Combine. Please contact // [email protected] if you need more. // Please note that the number of arguments to Combine is limited // by the maximum arity of the implementation of tuple which is // currently set at 10. #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_ // scripts/fuse_gtest.py depends on gtest's own header being #included // *unconditionally*. Therefore these #includes cannot be moved // inside #if GTEST_HAS_PARAM_TEST. #include "gtest/internal/gtest-param-util.h" #include "gtest/internal/gtest-port.h" #if GTEST_HAS_PARAM_TEST namespace testing { // Forward declarations of ValuesIn(), which is implemented in // include/gtest/gtest-param-test.h. template <typename ForwardIterator> internal::ParamGenerator< typename ::testing::internal::IteratorTraits<ForwardIterator>::value_type> ValuesIn(ForwardIterator begin, ForwardIterator end); template <typename T, size_t N> internal::ParamGenerator<T> ValuesIn(const T (&array)[N]); template <class Container> internal::ParamGenerator<typename Container::value_type> ValuesIn( const Container& container); namespace internal { // Used in the Values() function to provide polymorphic capabilities. template <typename T1> class ValueArray1 { public: explicit ValueArray1(T1 v1) : v1_(v1) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray1& other) = delete; const T1 v1_; }; template <typename T1, typename T2> class ValueArray2 { public: ValueArray2(T1 v1, T2 v2) : v1_(v1), v2_(v2) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray2& other) = delete; const T1 v1_; const T2 v2_; }; template <typename T1, typename T2, typename T3> class ValueArray3 { public: ValueArray3(T1 v1, T2 v2, T3 v3) : v1_(v1), v2_(v2), v3_(v3) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray3& other); const T1 v1_; const T2 v2_; const T3 v3_; }; template <typename T1, typename T2, typename T3, typename T4> class ValueArray4 { public: ValueArray4(T1 v1, T2 v2, T3 v3, T4 v4) : v1_(v1), v2_(v2), v3_(v3), v4_(v4) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray4& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5> class ValueArray5 { public: ValueArray5(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray5& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6> class ValueArray6 { public: ValueArray6(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray6& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7> class ValueArray7 { public: ValueArray7(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray7& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8> class ValueArray8 { public: ValueArray8(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray8& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9> class ValueArray9 { public: ValueArray9(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray9& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10> class ValueArray10 { public: ValueArray10(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray10& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11> class ValueArray11 { public: ValueArray11(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray11& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12> class ValueArray12 { public: ValueArray12(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray12& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13> class ValueArray13 { public: ValueArray13(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray13& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14> class ValueArray14 { public: ValueArray14(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray14& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15> class ValueArray15 { public: ValueArray15(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), static_cast<T>(v15_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray15& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16> class ValueArray16 { public: ValueArray16(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), static_cast<T>(v15_), static_cast<T>(v16_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray16& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17> class ValueArray17 { public: ValueArray17(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray17& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18> class ValueArray18 { public: ValueArray18(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), static_cast<T>(v18_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray18& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19> class ValueArray19 { public: ValueArray19(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), static_cast<T>(v18_), static_cast<T>(v19_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray19& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20> class ValueArray20 { public: ValueArray20(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray20& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21> class ValueArray21 { public: ValueArray21(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), static_cast<T>(v21_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray21& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22> class ValueArray22 { public: ValueArray22(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), static_cast<T>(v21_), static_cast<T>(v22_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray22& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23> class ValueArray23 { public: ValueArray23(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray23& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24> class ValueArray24 { public: ValueArray24(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), static_cast<T>(v24_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray24& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25> class ValueArray25 { public: ValueArray25(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), static_cast<T>(v24_), static_cast<T>(v25_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray25& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26> class ValueArray26 { public: ValueArray26(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray26& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27> class ValueArray27 { public: ValueArray27(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), static_cast<T>(v27_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray27& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28> class ValueArray28 { public: ValueArray28(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), static_cast<T>(v27_), static_cast<T>(v28_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray28& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29> class ValueArray29 { public: ValueArray29(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray29& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30> class ValueArray30 { public: ValueArray30(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), static_cast<T>(v30_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray30& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31> class ValueArray31 { public: ValueArray31(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), static_cast<T>(v30_), static_cast<T>(v31_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray31& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32> class ValueArray32 { public: ValueArray32(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray32& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33> class ValueArray33 { public: ValueArray33(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_), static_cast<T>(v33_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray33& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; const T33 v33_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34> class ValueArray34 { public: ValueArray34(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_), static_cast<T>(v33_), static_cast<T>(v34_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray34& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; const T33 v33_; const T34 v34_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35> class ValueArray35 { public: ValueArray35(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_), static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray35& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; const T33 v33_; const T34 v34_; const T35 v35_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36> class ValueArray36 { public: ValueArray36(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_), static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_), static_cast<T>(v36_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray36& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; const T33 v33_; const T34 v34_; const T35 v35_; const T36 v36_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37> class ValueArray37 { public: ValueArray37(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_), static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_), static_cast<T>(v36_), static_cast<T>(v37_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray37& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; const T33 v33_; const T34 v34_; const T35 v35_; const T36 v36_; const T37 v37_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38> class ValueArray38 { public: ValueArray38(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_), static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_), static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray38& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; const T33 v33_; const T34 v34_; const T35 v35_; const T36 v36_; const T37 v37_; const T38 v38_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39> class ValueArray39 { public: ValueArray39(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_), static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_), static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_), static_cast<T>(v39_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray39& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; const T33 v33_; const T34 v34_; const T35 v35_; const T36 v36_; const T37 v37_; const T38 v38_; const T39 v39_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40> class ValueArray40 { public: ValueArray40(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_), static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_), static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_), static_cast<T>(v39_), static_cast<T>(v40_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray40& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; const T33 v33_; const T34 v34_; const T35 v35_; const T36 v36_; const T37 v37_; const T38 v38_; const T39 v39_; const T40 v40_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41> class ValueArray41 { public: ValueArray41(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), v41_(v41) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_), static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_), static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_), static_cast<T>(v39_), static_cast<T>(v40_), static_cast<T>(v41_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray41& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; const T33 v33_; const T34 v34_; const T35 v35_; const T36 v36_; const T37 v37_; const T38 v38_; const T39 v39_; const T40 v40_; const T41 v41_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42> class ValueArray42 { public: ValueArray42(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), v41_(v41), v42_(v42) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_), static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_), static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_), static_cast<T>(v39_), static_cast<T>(v40_), static_cast<T>(v41_), static_cast<T>(v42_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray42& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; const T33 v33_; const T34 v34_; const T35 v35_; const T36 v36_; const T37 v37_; const T38 v38_; const T39 v39_; const T40 v40_; const T41 v41_; const T42 v42_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43> class ValueArray43 { public: ValueArray43(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_), static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_), static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_), static_cast<T>(v39_), static_cast<T>(v40_), static_cast<T>(v41_), static_cast<T>(v42_), static_cast<T>(v43_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray43& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; const T33 v33_; const T34 v34_; const T35 v35_; const T36 v36_; const T37 v37_; const T38 v38_; const T39 v39_; const T40 v40_; const T41 v41_; const T42 v42_; const T43 v43_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43, typename T44> class ValueArray44 { public: ValueArray44(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43), v44_(v44) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_), static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_), static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_), static_cast<T>(v39_), static_cast<T>(v40_), static_cast<T>(v41_), static_cast<T>(v42_), static_cast<T>(v43_), static_cast<T>(v44_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray44& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; const T33 v33_; const T34 v34_; const T35 v35_; const T36 v36_; const T37 v37_; const T38 v38_; const T39 v39_; const T40 v40_; const T41 v41_; const T42 v42_; const T43 v43_; const T44 v44_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43, typename T44, typename T45> class ValueArray45 { public: ValueArray45(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43), v44_(v44), v45_(v45) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_), static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_), static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_), static_cast<T>(v39_), static_cast<T>(v40_), static_cast<T>(v41_), static_cast<T>(v42_), static_cast<T>(v43_), static_cast<T>(v44_), static_cast<T>(v45_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray45& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; const T33 v33_; const T34 v34_; const T35 v35_; const T36 v36_; const T37 v37_; const T38 v38_; const T39 v39_; const T40 v40_; const T41 v41_; const T42 v42_; const T43 v43_; const T44 v44_; const T45 v45_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43, typename T44, typename T45, typename T46> class ValueArray46 { public: ValueArray46(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43), v44_(v44), v45_(v45), v46_(v46) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_), static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_), static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_), static_cast<T>(v39_), static_cast<T>(v40_), static_cast<T>(v41_), static_cast<T>(v42_), static_cast<T>(v43_), static_cast<T>(v44_), static_cast<T>(v45_), static_cast<T>(v46_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray46& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; const T33 v33_; const T34 v34_; const T35 v35_; const T36 v36_; const T37 v37_; const T38 v38_; const T39 v39_; const T40 v40_; const T41 v41_; const T42 v42_; const T43 v43_; const T44 v44_; const T45 v45_; const T46 v46_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43, typename T44, typename T45, typename T46, typename T47> class ValueArray47 { public: ValueArray47(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43), v44_(v44), v45_(v45), v46_(v46), v47_(v47) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_), static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_), static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_), static_cast<T>(v39_), static_cast<T>(v40_), static_cast<T>(v41_), static_cast<T>(v42_), static_cast<T>(v43_), static_cast<T>(v44_), static_cast<T>(v45_), static_cast<T>(v46_), static_cast<T>(v47_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray47& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; const T33 v33_; const T34 v34_; const T35 v35_; const T36 v36_; const T37 v37_; const T38 v38_; const T39 v39_; const T40 v40_; const T41 v41_; const T42 v42_; const T43 v43_; const T44 v44_; const T45 v45_; const T46 v46_; const T47 v47_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43, typename T44, typename T45, typename T46, typename T47, typename T48> class ValueArray48 { public: ValueArray48(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, T48 v48) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43), v44_(v44), v45_(v45), v46_(v46), v47_(v47), v48_(v48) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_), static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_), static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_), static_cast<T>(v39_), static_cast<T>(v40_), static_cast<T>(v41_), static_cast<T>(v42_), static_cast<T>(v43_), static_cast<T>(v44_), static_cast<T>(v45_), static_cast<T>(v46_), static_cast<T>(v47_), static_cast<T>(v48_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray48& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; const T33 v33_; const T34 v34_; const T35 v35_; const T36 v36_; const T37 v37_; const T38 v38_; const T39 v39_; const T40 v40_; const T41 v41_; const T42 v42_; const T43 v43_; const T44 v44_; const T45 v45_; const T46 v46_; const T47 v47_; const T48 v48_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43, typename T44, typename T45, typename T46, typename T47, typename T48, typename T49> class ValueArray49 { public: ValueArray49(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, T48 v48, T49 v49) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43), v44_(v44), v45_(v45), v46_(v46), v47_(v47), v48_(v48), v49_(v49) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_), static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_), static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_), static_cast<T>(v39_), static_cast<T>(v40_), static_cast<T>(v41_), static_cast<T>(v42_), static_cast<T>(v43_), static_cast<T>(v44_), static_cast<T>(v45_), static_cast<T>(v46_), static_cast<T>(v47_), static_cast<T>(v48_), static_cast<T>(v49_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray49& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; const T33 v33_; const T34 v34_; const T35 v35_; const T36 v36_; const T37 v37_; const T38 v38_; const T39 v39_; const T40 v40_; const T41 v41_; const T42 v42_; const T43 v43_; const T44 v44_; const T45 v45_; const T46 v46_; const T47 v47_; const T48 v48_; const T49 v49_; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43, typename T44, typename T45, typename T46, typename T47, typename T48, typename T49, typename T50> class ValueArray50 { public: ValueArray50(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10, T11 v11, T12 v12, T13 v13, T14 v14, T15 v15, T16 v16, T17 v17, T18 v18, T19 v19, T20 v20, T21 v21, T22 v22, T23 v23, T24 v24, T25 v25, T26 v26, T27 v27, T28 v28, T29 v29, T30 v30, T31 v31, T32 v32, T33 v33, T34 v34, T35 v35, T36 v36, T37 v37, T38 v38, T39 v39, T40 v40, T41 v41, T42 v42, T43 v43, T44 v44, T45 v45, T46 v46, T47 v47, T48 v48, T49 v49, T50 v50) : v1_(v1), v2_(v2), v3_(v3), v4_(v4), v5_(v5), v6_(v6), v7_(v7), v8_(v8), v9_(v9), v10_(v10), v11_(v11), v12_(v12), v13_(v13), v14_(v14), v15_(v15), v16_(v16), v17_(v17), v18_(v18), v19_(v19), v20_(v20), v21_(v21), v22_(v22), v23_(v23), v24_(v24), v25_(v25), v26_(v26), v27_(v27), v28_(v28), v29_(v29), v30_(v30), v31_(v31), v32_(v32), v33_(v33), v34_(v34), v35_(v35), v36_(v36), v37_(v37), v38_(v38), v39_(v39), v40_(v40), v41_(v41), v42_(v42), v43_(v43), v44_(v44), v45_(v45), v46_(v46), v47_(v47), v48_(v48), v49_(v49), v50_(v50) {} template <typename T> operator ParamGenerator<T>() const { const T array[] = {static_cast<T>(v1_), static_cast<T>(v2_), static_cast<T>(v3_), static_cast<T>(v4_), static_cast<T>(v5_), static_cast<T>(v6_), static_cast<T>(v7_), static_cast<T>(v8_), static_cast<T>(v9_), static_cast<T>(v10_), static_cast<T>(v11_), static_cast<T>(v12_), static_cast<T>(v13_), static_cast<T>(v14_), static_cast<T>(v15_), static_cast<T>(v16_), static_cast<T>(v17_), static_cast<T>(v18_), static_cast<T>(v19_), static_cast<T>(v20_), static_cast<T>(v21_), static_cast<T>(v22_), static_cast<T>(v23_), static_cast<T>(v24_), static_cast<T>(v25_), static_cast<T>(v26_), static_cast<T>(v27_), static_cast<T>(v28_), static_cast<T>(v29_), static_cast<T>(v30_), static_cast<T>(v31_), static_cast<T>(v32_), static_cast<T>(v33_), static_cast<T>(v34_), static_cast<T>(v35_), static_cast<T>(v36_), static_cast<T>(v37_), static_cast<T>(v38_), static_cast<T>(v39_), static_cast<T>(v40_), static_cast<T>(v41_), static_cast<T>(v42_), static_cast<T>(v43_), static_cast<T>(v44_), static_cast<T>(v45_), static_cast<T>(v46_), static_cast<T>(v47_), static_cast<T>(v48_), static_cast<T>(v49_), static_cast<T>(v50_)}; return ValuesIn(array); } private: // No implementation - assignment is unsupported. void operator=(const ValueArray50& other); const T1 v1_; const T2 v2_; const T3 v3_; const T4 v4_; const T5 v5_; const T6 v6_; const T7 v7_; const T8 v8_; const T9 v9_; const T10 v10_; const T11 v11_; const T12 v12_; const T13 v13_; const T14 v14_; const T15 v15_; const T16 v16_; const T17 v17_; const T18 v18_; const T19 v19_; const T20 v20_; const T21 v21_; const T22 v22_; const T23 v23_; const T24 v24_; const T25 v25_; const T26 v26_; const T27 v27_; const T28 v28_; const T29 v29_; const T30 v30_; const T31 v31_; const T32 v32_; const T33 v33_; const T34 v34_; const T35 v35_; const T36 v36_; const T37 v37_; const T38 v38_; const T39 v39_; const T40 v40_; const T41 v41_; const T42 v42_; const T43 v43_; const T44 v44_; const T45 v45_; const T46 v46_; const T47 v47_; const T48 v48_; const T49 v49_; const T50 v50_; }; # if GTEST_HAS_COMBINE // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Generates values from the Cartesian product of values produced // by the argument generators. // template <typename T1, typename T2> class CartesianProductGenerator2 : public ParamGeneratorInterface< ::testing::tuple<T1, T2> > { public: typedef ::testing::tuple<T1, T2> ParamType; CartesianProductGenerator2(const ParamGenerator<T1>& g1, const ParamGenerator<T2>& g2) : g1_(g1), g2_(g2) {} virtual ~CartesianProductGenerator2() {} virtual ParamIteratorInterface<ParamType>* Begin() const { return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin()); } virtual ParamIteratorInterface<ParamType>* End() const { return new Iterator(this, g1_, g1_.end(), g2_, g2_.end()); } private: class Iterator : public ParamIteratorInterface<ParamType> { public: Iterator(const ParamGeneratorInterface<ParamType>* base, const ParamGenerator<T1>& g1, const typename ParamGenerator<T1>::iterator& current1, const ParamGenerator<T2>& g2, const typename ParamGenerator<T2>::iterator& current2) : base_(base), begin1_(g1.begin()), end1_(g1.end()), current1_(current1), begin2_(g2.begin()), end2_(g2.end()), current2_(current2) { ComputeCurrentValue(); } virtual ~Iterator() {} virtual const ParamGeneratorInterface<ParamType>* BaseGenerator() const { return base_; } // Advance should not be called on beyond-of-range iterators // so no component iterators must be beyond end of range, either. virtual void Advance() { assert(!AtEnd()); ++current2_; if (current2_ == end2_) { current2_ = begin2_; ++current1_; } ComputeCurrentValue(); } virtual ParamIteratorInterface<ParamType>* Clone() const { return new Iterator(*this); } virtual const ParamType* Current() const { return &current_value_; } virtual bool Equals(const ParamIteratorInterface<ParamType>& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " << "from different generators." << std::endl; const Iterator* typed_other = CheckedDowncastToActualType<const Iterator>(&other); // We must report iterators equal if they both point beyond their // respective ranges. That can happen in a variety of fashions, // so we have to consult AtEnd(). return (AtEnd() && typed_other->AtEnd()) || ( current1_ == typed_other->current1_ && current2_ == typed_other->current2_); } private: Iterator(const Iterator& other) : base_(other.base_), begin1_(other.begin1_), end1_(other.end1_), current1_(other.current1_), begin2_(other.begin2_), end2_(other.end2_), current2_(other.current2_) { ComputeCurrentValue(); } void ComputeCurrentValue() { if (!AtEnd()) current_value_ = ParamType(*current1_, *current2_); } bool AtEnd() const { // We must report iterator past the end of the range when either of the // component iterators has reached the end of its range. return current1_ == end1_ || current2_ == end2_; } // No implementation - assignment is unsupported. void operator=(const Iterator& other); const ParamGeneratorInterface<ParamType>* const base_; // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. // current[i]_ is the actual traversing iterator. const typename ParamGenerator<T1>::iterator begin1_; const typename ParamGenerator<T1>::iterator end1_; typename ParamGenerator<T1>::iterator current1_; const typename ParamGenerator<T2>::iterator begin2_; const typename ParamGenerator<T2>::iterator end2_; typename ParamGenerator<T2>::iterator current2_; ParamType current_value_; }; // class CartesianProductGenerator2::Iterator // No implementation - assignment is unsupported. void operator=(const CartesianProductGenerator2& other); const ParamGenerator<T1> g1_; const ParamGenerator<T2> g2_; }; // class CartesianProductGenerator2 template <typename T1, typename T2, typename T3> class CartesianProductGenerator3 : public ParamGeneratorInterface< ::testing::tuple<T1, T2, T3> > { public: typedef ::testing::tuple<T1, T2, T3> ParamType; CartesianProductGenerator3(const ParamGenerator<T1>& g1, const ParamGenerator<T2>& g2, const ParamGenerator<T3>& g3) : g1_(g1), g2_(g2), g3_(g3) {} virtual ~CartesianProductGenerator3() {} virtual ParamIteratorInterface<ParamType>* Begin() const { return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, g3_.begin()); } virtual ParamIteratorInterface<ParamType>* End() const { return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end()); } private: class Iterator : public ParamIteratorInterface<ParamType> { public: Iterator(const ParamGeneratorInterface<ParamType>* base, const ParamGenerator<T1>& g1, const typename ParamGenerator<T1>::iterator& current1, const ParamGenerator<T2>& g2, const typename ParamGenerator<T2>::iterator& current2, const ParamGenerator<T3>& g3, const typename ParamGenerator<T3>::iterator& current3) : base_(base), begin1_(g1.begin()), end1_(g1.end()), current1_(current1), begin2_(g2.begin()), end2_(g2.end()), current2_(current2), begin3_(g3.begin()), end3_(g3.end()), current3_(current3) { ComputeCurrentValue(); } virtual ~Iterator() {} virtual const ParamGeneratorInterface<ParamType>* BaseGenerator() const { return base_; } // Advance should not be called on beyond-of-range iterators // so no component iterators must be beyond end of range, either. virtual void Advance() { assert(!AtEnd()); ++current3_; if (current3_ == end3_) { current3_ = begin3_; ++current2_; } if (current2_ == end2_) { current2_ = begin2_; ++current1_; } ComputeCurrentValue(); } virtual ParamIteratorInterface<ParamType>* Clone() const { return new Iterator(*this); } virtual const ParamType* Current() const { return &current_value_; } virtual bool Equals(const ParamIteratorInterface<ParamType>& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " << "from different generators." << std::endl; const Iterator* typed_other = CheckedDowncastToActualType<const Iterator>(&other); // We must report iterators equal if they both point beyond their // respective ranges. That can happen in a variety of fashions, // so we have to consult AtEnd(). return (AtEnd() && typed_other->AtEnd()) || ( current1_ == typed_other->current1_ && current2_ == typed_other->current2_ && current3_ == typed_other->current3_); } private: Iterator(const Iterator& other) : base_(other.base_), begin1_(other.begin1_), end1_(other.end1_), current1_(other.current1_), begin2_(other.begin2_), end2_(other.end2_), current2_(other.current2_), begin3_(other.begin3_), end3_(other.end3_), current3_(other.current3_) { ComputeCurrentValue(); } void ComputeCurrentValue() { if (!AtEnd()) current_value_ = ParamType(*current1_, *current2_, *current3_); } bool AtEnd() const { // We must report iterator past the end of the range when either of the // component iterators has reached the end of its range. return current1_ == end1_ || current2_ == end2_ || current3_ == end3_; } // No implementation - assignment is unsupported. void operator=(const Iterator& other); const ParamGeneratorInterface<ParamType>* const base_; // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. // current[i]_ is the actual traversing iterator. const typename ParamGenerator<T1>::iterator begin1_; const typename ParamGenerator<T1>::iterator end1_; typename ParamGenerator<T1>::iterator current1_; const typename ParamGenerator<T2>::iterator begin2_; const typename ParamGenerator<T2>::iterator end2_; typename ParamGenerator<T2>::iterator current2_; const typename ParamGenerator<T3>::iterator begin3_; const typename ParamGenerator<T3>::iterator end3_; typename ParamGenerator<T3>::iterator current3_; ParamType current_value_; }; // class CartesianProductGenerator3::Iterator // No implementation - assignment is unsupported. void operator=(const CartesianProductGenerator3& other); const ParamGenerator<T1> g1_; const ParamGenerator<T2> g2_; const ParamGenerator<T3> g3_; }; // class CartesianProductGenerator3 template <typename T1, typename T2, typename T3, typename T4> class CartesianProductGenerator4 : public ParamGeneratorInterface< ::testing::tuple<T1, T2, T3, T4> > { public: typedef ::testing::tuple<T1, T2, T3, T4> ParamType; CartesianProductGenerator4(const ParamGenerator<T1>& g1, const ParamGenerator<T2>& g2, const ParamGenerator<T3>& g3, const ParamGenerator<T4>& g4) : g1_(g1), g2_(g2), g3_(g3), g4_(g4) {} virtual ~CartesianProductGenerator4() {} virtual ParamIteratorInterface<ParamType>* Begin() const { return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, g3_.begin(), g4_, g4_.begin()); } virtual ParamIteratorInterface<ParamType>* End() const { return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), g4_, g4_.end()); } private: class Iterator : public ParamIteratorInterface<ParamType> { public: Iterator(const ParamGeneratorInterface<ParamType>* base, const ParamGenerator<T1>& g1, const typename ParamGenerator<T1>::iterator& current1, const ParamGenerator<T2>& g2, const typename ParamGenerator<T2>::iterator& current2, const ParamGenerator<T3>& g3, const typename ParamGenerator<T3>::iterator& current3, const ParamGenerator<T4>& g4, const typename ParamGenerator<T4>::iterator& current4) : base_(base), begin1_(g1.begin()), end1_(g1.end()), current1_(current1), begin2_(g2.begin()), end2_(g2.end()), current2_(current2), begin3_(g3.begin()), end3_(g3.end()), current3_(current3), begin4_(g4.begin()), end4_(g4.end()), current4_(current4) { ComputeCurrentValue(); } virtual ~Iterator() {} virtual const ParamGeneratorInterface<ParamType>* BaseGenerator() const { return base_; } // Advance should not be called on beyond-of-range iterators // so no component iterators must be beyond end of range, either. virtual void Advance() { assert(!AtEnd()); ++current4_; if (current4_ == end4_) { current4_ = begin4_; ++current3_; } if (current3_ == end3_) { current3_ = begin3_; ++current2_; } if (current2_ == end2_) { current2_ = begin2_; ++current1_; } ComputeCurrentValue(); } virtual ParamIteratorInterface<ParamType>* Clone() const { return new Iterator(*this); } virtual const ParamType* Current() const { return &current_value_; } virtual bool Equals(const ParamIteratorInterface<ParamType>& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " << "from different generators." << std::endl; const Iterator* typed_other = CheckedDowncastToActualType<const Iterator>(&other); // We must report iterators equal if they both point beyond their // respective ranges. That can happen in a variety of fashions, // so we have to consult AtEnd(). return (AtEnd() && typed_other->AtEnd()) || ( current1_ == typed_other->current1_ && current2_ == typed_other->current2_ && current3_ == typed_other->current3_ && current4_ == typed_other->current4_); } private: Iterator(const Iterator& other) : base_(other.base_), begin1_(other.begin1_), end1_(other.end1_), current1_(other.current1_), begin2_(other.begin2_), end2_(other.end2_), current2_(other.current2_), begin3_(other.begin3_), end3_(other.end3_), current3_(other.current3_), begin4_(other.begin4_), end4_(other.end4_), current4_(other.current4_) { ComputeCurrentValue(); } void ComputeCurrentValue() { if (!AtEnd()) current_value_ = ParamType(*current1_, *current2_, *current3_, *current4_); } bool AtEnd() const { // We must report iterator past the end of the range when either of the // component iterators has reached the end of its range. return current1_ == end1_ || current2_ == end2_ || current3_ == end3_ || current4_ == end4_; } // No implementation - assignment is unsupported. void operator=(const Iterator& other); const ParamGeneratorInterface<ParamType>* const base_; // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. // current[i]_ is the actual traversing iterator. const typename ParamGenerator<T1>::iterator begin1_; const typename ParamGenerator<T1>::iterator end1_; typename ParamGenerator<T1>::iterator current1_; const typename ParamGenerator<T2>::iterator begin2_; const typename ParamGenerator<T2>::iterator end2_; typename ParamGenerator<T2>::iterator current2_; const typename ParamGenerator<T3>::iterator begin3_; const typename ParamGenerator<T3>::iterator end3_; typename ParamGenerator<T3>::iterator current3_; const typename ParamGenerator<T4>::iterator begin4_; const typename ParamGenerator<T4>::iterator end4_; typename ParamGenerator<T4>::iterator current4_; ParamType current_value_; }; // class CartesianProductGenerator4::Iterator // No implementation - assignment is unsupported. void operator=(const CartesianProductGenerator4& other); const ParamGenerator<T1> g1_; const ParamGenerator<T2> g2_; const ParamGenerator<T3> g3_; const ParamGenerator<T4> g4_; }; // class CartesianProductGenerator4 template <typename T1, typename T2, typename T3, typename T4, typename T5> class CartesianProductGenerator5 : public ParamGeneratorInterface< ::testing::tuple<T1, T2, T3, T4, T5> > { public: typedef ::testing::tuple<T1, T2, T3, T4, T5> ParamType; CartesianProductGenerator5(const ParamGenerator<T1>& g1, const ParamGenerator<T2>& g2, const ParamGenerator<T3>& g3, const ParamGenerator<T4>& g4, const ParamGenerator<T5>& g5) : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5) {} virtual ~CartesianProductGenerator5() {} virtual ParamIteratorInterface<ParamType>* Begin() const { return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin()); } virtual ParamIteratorInterface<ParamType>* End() const { return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), g4_, g4_.end(), g5_, g5_.end()); } private: class Iterator : public ParamIteratorInterface<ParamType> { public: Iterator(const ParamGeneratorInterface<ParamType>* base, const ParamGenerator<T1>& g1, const typename ParamGenerator<T1>::iterator& current1, const ParamGenerator<T2>& g2, const typename ParamGenerator<T2>::iterator& current2, const ParamGenerator<T3>& g3, const typename ParamGenerator<T3>::iterator& current3, const ParamGenerator<T4>& g4, const typename ParamGenerator<T4>::iterator& current4, const ParamGenerator<T5>& g5, const typename ParamGenerator<T5>::iterator& current5) : base_(base), begin1_(g1.begin()), end1_(g1.end()), current1_(current1), begin2_(g2.begin()), end2_(g2.end()), current2_(current2), begin3_(g3.begin()), end3_(g3.end()), current3_(current3), begin4_(g4.begin()), end4_(g4.end()), current4_(current4), begin5_(g5.begin()), end5_(g5.end()), current5_(current5) { ComputeCurrentValue(); } virtual ~Iterator() {} virtual const ParamGeneratorInterface<ParamType>* BaseGenerator() const { return base_; } // Advance should not be called on beyond-of-range iterators // so no component iterators must be beyond end of range, either. virtual void Advance() { assert(!AtEnd()); ++current5_; if (current5_ == end5_) { current5_ = begin5_; ++current4_; } if (current4_ == end4_) { current4_ = begin4_; ++current3_; } if (current3_ == end3_) { current3_ = begin3_; ++current2_; } if (current2_ == end2_) { current2_ = begin2_; ++current1_; } ComputeCurrentValue(); } virtual ParamIteratorInterface<ParamType>* Clone() const { return new Iterator(*this); } virtual const ParamType* Current() const { return &current_value_; } virtual bool Equals(const ParamIteratorInterface<ParamType>& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " << "from different generators." << std::endl; const Iterator* typed_other = CheckedDowncastToActualType<const Iterator>(&other); // We must report iterators equal if they both point beyond their // respective ranges. That can happen in a variety of fashions, // so we have to consult AtEnd(). return (AtEnd() && typed_other->AtEnd()) || ( current1_ == typed_other->current1_ && current2_ == typed_other->current2_ && current3_ == typed_other->current3_ && current4_ == typed_other->current4_ && current5_ == typed_other->current5_); } private: Iterator(const Iterator& other) : base_(other.base_), begin1_(other.begin1_), end1_(other.end1_), current1_(other.current1_), begin2_(other.begin2_), end2_(other.end2_), current2_(other.current2_), begin3_(other.begin3_), end3_(other.end3_), current3_(other.current3_), begin4_(other.begin4_), end4_(other.end4_), current4_(other.current4_), begin5_(other.begin5_), end5_(other.end5_), current5_(other.current5_) { ComputeCurrentValue(); } void ComputeCurrentValue() { if (!AtEnd()) current_value_ = ParamType(*current1_, *current2_, *current3_, *current4_, *current5_); } bool AtEnd() const { // We must report iterator past the end of the range when either of the // component iterators has reached the end of its range. return current1_ == end1_ || current2_ == end2_ || current3_ == end3_ || current4_ == end4_ || current5_ == end5_; } // No implementation - assignment is unsupported. void operator=(const Iterator& other); const ParamGeneratorInterface<ParamType>* const base_; // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. // current[i]_ is the actual traversing iterator. const typename ParamGenerator<T1>::iterator begin1_; const typename ParamGenerator<T1>::iterator end1_; typename ParamGenerator<T1>::iterator current1_; const typename ParamGenerator<T2>::iterator begin2_; const typename ParamGenerator<T2>::iterator end2_; typename ParamGenerator<T2>::iterator current2_; const typename ParamGenerator<T3>::iterator begin3_; const typename ParamGenerator<T3>::iterator end3_; typename ParamGenerator<T3>::iterator current3_; const typename ParamGenerator<T4>::iterator begin4_; const typename ParamGenerator<T4>::iterator end4_; typename ParamGenerator<T4>::iterator current4_; const typename ParamGenerator<T5>::iterator begin5_; const typename ParamGenerator<T5>::iterator end5_; typename ParamGenerator<T5>::iterator current5_; ParamType current_value_; }; // class CartesianProductGenerator5::Iterator // No implementation - assignment is unsupported. void operator=(const CartesianProductGenerator5& other); const ParamGenerator<T1> g1_; const ParamGenerator<T2> g2_; const ParamGenerator<T3> g3_; const ParamGenerator<T4> g4_; const ParamGenerator<T5> g5_; }; // class CartesianProductGenerator5 template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6> class CartesianProductGenerator6 : public ParamGeneratorInterface< ::testing::tuple<T1, T2, T3, T4, T5, T6> > { public: typedef ::testing::tuple<T1, T2, T3, T4, T5, T6> ParamType; CartesianProductGenerator6(const ParamGenerator<T1>& g1, const ParamGenerator<T2>& g2, const ParamGenerator<T3>& g3, const ParamGenerator<T4>& g4, const ParamGenerator<T5>& g5, const ParamGenerator<T6>& g6) : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6) {} virtual ~CartesianProductGenerator6() {} virtual ParamIteratorInterface<ParamType>* Begin() const { return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin()); } virtual ParamIteratorInterface<ParamType>* End() const { return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end()); } private: class Iterator : public ParamIteratorInterface<ParamType> { public: Iterator(const ParamGeneratorInterface<ParamType>* base, const ParamGenerator<T1>& g1, const typename ParamGenerator<T1>::iterator& current1, const ParamGenerator<T2>& g2, const typename ParamGenerator<T2>::iterator& current2, const ParamGenerator<T3>& g3, const typename ParamGenerator<T3>::iterator& current3, const ParamGenerator<T4>& g4, const typename ParamGenerator<T4>::iterator& current4, const ParamGenerator<T5>& g5, const typename ParamGenerator<T5>::iterator& current5, const ParamGenerator<T6>& g6, const typename ParamGenerator<T6>::iterator& current6) : base_(base), begin1_(g1.begin()), end1_(g1.end()), current1_(current1), begin2_(g2.begin()), end2_(g2.end()), current2_(current2), begin3_(g3.begin()), end3_(g3.end()), current3_(current3), begin4_(g4.begin()), end4_(g4.end()), current4_(current4), begin5_(g5.begin()), end5_(g5.end()), current5_(current5), begin6_(g6.begin()), end6_(g6.end()), current6_(current6) { ComputeCurrentValue(); } virtual ~Iterator() {} virtual const ParamGeneratorInterface<ParamType>* BaseGenerator() const { return base_; } // Advance should not be called on beyond-of-range iterators // so no component iterators must be beyond end of range, either. virtual void Advance() { assert(!AtEnd()); ++current6_; if (current6_ == end6_) { current6_ = begin6_; ++current5_; } if (current5_ == end5_) { current5_ = begin5_; ++current4_; } if (current4_ == end4_) { current4_ = begin4_; ++current3_; } if (current3_ == end3_) { current3_ = begin3_; ++current2_; } if (current2_ == end2_) { current2_ = begin2_; ++current1_; } ComputeCurrentValue(); } virtual ParamIteratorInterface<ParamType>* Clone() const { return new Iterator(*this); } virtual const ParamType* Current() const { return &current_value_; } virtual bool Equals(const ParamIteratorInterface<ParamType>& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " << "from different generators." << std::endl; const Iterator* typed_other = CheckedDowncastToActualType<const Iterator>(&other); // We must report iterators equal if they both point beyond their // respective ranges. That can happen in a variety of fashions, // so we have to consult AtEnd(). return (AtEnd() && typed_other->AtEnd()) || ( current1_ == typed_other->current1_ && current2_ == typed_other->current2_ && current3_ == typed_other->current3_ && current4_ == typed_other->current4_ && current5_ == typed_other->current5_ && current6_ == typed_other->current6_); } private: Iterator(const Iterator& other) : base_(other.base_), begin1_(other.begin1_), end1_(other.end1_), current1_(other.current1_), begin2_(other.begin2_), end2_(other.end2_), current2_(other.current2_), begin3_(other.begin3_), end3_(other.end3_), current3_(other.current3_), begin4_(other.begin4_), end4_(other.end4_), current4_(other.current4_), begin5_(other.begin5_), end5_(other.end5_), current5_(other.current5_), begin6_(other.begin6_), end6_(other.end6_), current6_(other.current6_) { ComputeCurrentValue(); } void ComputeCurrentValue() { if (!AtEnd()) current_value_ = ParamType(*current1_, *current2_, *current3_, *current4_, *current5_, *current6_); } bool AtEnd() const { // We must report iterator past the end of the range when either of the // component iterators has reached the end of its range. return current1_ == end1_ || current2_ == end2_ || current3_ == end3_ || current4_ == end4_ || current5_ == end5_ || current6_ == end6_; } // No implementation - assignment is unsupported. void operator=(const Iterator& other); const ParamGeneratorInterface<ParamType>* const base_; // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. // current[i]_ is the actual traversing iterator. const typename ParamGenerator<T1>::iterator begin1_; const typename ParamGenerator<T1>::iterator end1_; typename ParamGenerator<T1>::iterator current1_; const typename ParamGenerator<T2>::iterator begin2_; const typename ParamGenerator<T2>::iterator end2_; typename ParamGenerator<T2>::iterator current2_; const typename ParamGenerator<T3>::iterator begin3_; const typename ParamGenerator<T3>::iterator end3_; typename ParamGenerator<T3>::iterator current3_; const typename ParamGenerator<T4>::iterator begin4_; const typename ParamGenerator<T4>::iterator end4_; typename ParamGenerator<T4>::iterator current4_; const typename ParamGenerator<T5>::iterator begin5_; const typename ParamGenerator<T5>::iterator end5_; typename ParamGenerator<T5>::iterator current5_; const typename ParamGenerator<T6>::iterator begin6_; const typename ParamGenerator<T6>::iterator end6_; typename ParamGenerator<T6>::iterator current6_; ParamType current_value_; }; // class CartesianProductGenerator6::Iterator // No implementation - assignment is unsupported. void operator=(const CartesianProductGenerator6& other); const ParamGenerator<T1> g1_; const ParamGenerator<T2> g2_; const ParamGenerator<T3> g3_; const ParamGenerator<T4> g4_; const ParamGenerator<T5> g5_; const ParamGenerator<T6> g6_; }; // class CartesianProductGenerator6 template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7> class CartesianProductGenerator7 : public ParamGeneratorInterface< ::testing::tuple<T1, T2, T3, T4, T5, T6, T7> > { public: typedef ::testing::tuple<T1, T2, T3, T4, T5, T6, T7> ParamType; CartesianProductGenerator7(const ParamGenerator<T1>& g1, const ParamGenerator<T2>& g2, const ParamGenerator<T3>& g3, const ParamGenerator<T4>& g4, const ParamGenerator<T5>& g5, const ParamGenerator<T6>& g6, const ParamGenerator<T7>& g7) : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7) {} virtual ~CartesianProductGenerator7() {} virtual ParamIteratorInterface<ParamType>* Begin() const { return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin(), g7_, g7_.begin()); } virtual ParamIteratorInterface<ParamType>* End() const { return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end(), g7_, g7_.end()); } private: class Iterator : public ParamIteratorInterface<ParamType> { public: Iterator(const ParamGeneratorInterface<ParamType>* base, const ParamGenerator<T1>& g1, const typename ParamGenerator<T1>::iterator& current1, const ParamGenerator<T2>& g2, const typename ParamGenerator<T2>::iterator& current2, const ParamGenerator<T3>& g3, const typename ParamGenerator<T3>::iterator& current3, const ParamGenerator<T4>& g4, const typename ParamGenerator<T4>::iterator& current4, const ParamGenerator<T5>& g5, const typename ParamGenerator<T5>::iterator& current5, const ParamGenerator<T6>& g6, const typename ParamGenerator<T6>::iterator& current6, const ParamGenerator<T7>& g7, const typename ParamGenerator<T7>::iterator& current7) : base_(base), begin1_(g1.begin()), end1_(g1.end()), current1_(current1), begin2_(g2.begin()), end2_(g2.end()), current2_(current2), begin3_(g3.begin()), end3_(g3.end()), current3_(current3), begin4_(g4.begin()), end4_(g4.end()), current4_(current4), begin5_(g5.begin()), end5_(g5.end()), current5_(current5), begin6_(g6.begin()), end6_(g6.end()), current6_(current6), begin7_(g7.begin()), end7_(g7.end()), current7_(current7) { ComputeCurrentValue(); } virtual ~Iterator() {} virtual const ParamGeneratorInterface<ParamType>* BaseGenerator() const { return base_; } // Advance should not be called on beyond-of-range iterators // so no component iterators must be beyond end of range, either. virtual void Advance() { assert(!AtEnd()); ++current7_; if (current7_ == end7_) { current7_ = begin7_; ++current6_; } if (current6_ == end6_) { current6_ = begin6_; ++current5_; } if (current5_ == end5_) { current5_ = begin5_; ++current4_; } if (current4_ == end4_) { current4_ = begin4_; ++current3_; } if (current3_ == end3_) { current3_ = begin3_; ++current2_; } if (current2_ == end2_) { current2_ = begin2_; ++current1_; } ComputeCurrentValue(); } virtual ParamIteratorInterface<ParamType>* Clone() const { return new Iterator(*this); } virtual const ParamType* Current() const { return &current_value_; } virtual bool Equals(const ParamIteratorInterface<ParamType>& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " << "from different generators." << std::endl; const Iterator* typed_other = CheckedDowncastToActualType<const Iterator>(&other); // We must report iterators equal if they both point beyond their // respective ranges. That can happen in a variety of fashions, // so we have to consult AtEnd(). return (AtEnd() && typed_other->AtEnd()) || ( current1_ == typed_other->current1_ && current2_ == typed_other->current2_ && current3_ == typed_other->current3_ && current4_ == typed_other->current4_ && current5_ == typed_other->current5_ && current6_ == typed_other->current6_ && current7_ == typed_other->current7_); } private: Iterator(const Iterator& other) : base_(other.base_), begin1_(other.begin1_), end1_(other.end1_), current1_(other.current1_), begin2_(other.begin2_), end2_(other.end2_), current2_(other.current2_), begin3_(other.begin3_), end3_(other.end3_), current3_(other.current3_), begin4_(other.begin4_), end4_(other.end4_), current4_(other.current4_), begin5_(other.begin5_), end5_(other.end5_), current5_(other.current5_), begin6_(other.begin6_), end6_(other.end6_), current6_(other.current6_), begin7_(other.begin7_), end7_(other.end7_), current7_(other.current7_) { ComputeCurrentValue(); } void ComputeCurrentValue() { if (!AtEnd()) current_value_ = ParamType(*current1_, *current2_, *current3_, *current4_, *current5_, *current6_, *current7_); } bool AtEnd() const { // We must report iterator past the end of the range when either of the // component iterators has reached the end of its range. return current1_ == end1_ || current2_ == end2_ || current3_ == end3_ || current4_ == end4_ || current5_ == end5_ || current6_ == end6_ || current7_ == end7_; } // No implementation - assignment is unsupported. void operator=(const Iterator& other); const ParamGeneratorInterface<ParamType>* const base_; // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. // current[i]_ is the actual traversing iterator. const typename ParamGenerator<T1>::iterator begin1_; const typename ParamGenerator<T1>::iterator end1_; typename ParamGenerator<T1>::iterator current1_; const typename ParamGenerator<T2>::iterator begin2_; const typename ParamGenerator<T2>::iterator end2_; typename ParamGenerator<T2>::iterator current2_; const typename ParamGenerator<T3>::iterator begin3_; const typename ParamGenerator<T3>::iterator end3_; typename ParamGenerator<T3>::iterator current3_; const typename ParamGenerator<T4>::iterator begin4_; const typename ParamGenerator<T4>::iterator end4_; typename ParamGenerator<T4>::iterator current4_; const typename ParamGenerator<T5>::iterator begin5_; const typename ParamGenerator<T5>::iterator end5_; typename ParamGenerator<T5>::iterator current5_; const typename ParamGenerator<T6>::iterator begin6_; const typename ParamGenerator<T6>::iterator end6_; typename ParamGenerator<T6>::iterator current6_; const typename ParamGenerator<T7>::iterator begin7_; const typename ParamGenerator<T7>::iterator end7_; typename ParamGenerator<T7>::iterator current7_; ParamType current_value_; }; // class CartesianProductGenerator7::Iterator // No implementation - assignment is unsupported. void operator=(const CartesianProductGenerator7& other); const ParamGenerator<T1> g1_; const ParamGenerator<T2> g2_; const ParamGenerator<T3> g3_; const ParamGenerator<T4> g4_; const ParamGenerator<T5> g5_; const ParamGenerator<T6> g6_; const ParamGenerator<T7> g7_; }; // class CartesianProductGenerator7 template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8> class CartesianProductGenerator8 : public ParamGeneratorInterface< ::testing::tuple<T1, T2, T3, T4, T5, T6, T7, T8> > { public: typedef ::testing::tuple<T1, T2, T3, T4, T5, T6, T7, T8> ParamType; CartesianProductGenerator8(const ParamGenerator<T1>& g1, const ParamGenerator<T2>& g2, const ParamGenerator<T3>& g3, const ParamGenerator<T4>& g4, const ParamGenerator<T5>& g5, const ParamGenerator<T6>& g6, const ParamGenerator<T7>& g7, const ParamGenerator<T8>& g8) : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8) {} virtual ~CartesianProductGenerator8() {} virtual ParamIteratorInterface<ParamType>* Begin() const { return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin(), g7_, g7_.begin(), g8_, g8_.begin()); } virtual ParamIteratorInterface<ParamType>* End() const { return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end(), g7_, g7_.end(), g8_, g8_.end()); } private: class Iterator : public ParamIteratorInterface<ParamType> { public: Iterator(const ParamGeneratorInterface<ParamType>* base, const ParamGenerator<T1>& g1, const typename ParamGenerator<T1>::iterator& current1, const ParamGenerator<T2>& g2, const typename ParamGenerator<T2>::iterator& current2, const ParamGenerator<T3>& g3, const typename ParamGenerator<T3>::iterator& current3, const ParamGenerator<T4>& g4, const typename ParamGenerator<T4>::iterator& current4, const ParamGenerator<T5>& g5, const typename ParamGenerator<T5>::iterator& current5, const ParamGenerator<T6>& g6, const typename ParamGenerator<T6>::iterator& current6, const ParamGenerator<T7>& g7, const typename ParamGenerator<T7>::iterator& current7, const ParamGenerator<T8>& g8, const typename ParamGenerator<T8>::iterator& current8) : base_(base), begin1_(g1.begin()), end1_(g1.end()), current1_(current1), begin2_(g2.begin()), end2_(g2.end()), current2_(current2), begin3_(g3.begin()), end3_(g3.end()), current3_(current3), begin4_(g4.begin()), end4_(g4.end()), current4_(current4), begin5_(g5.begin()), end5_(g5.end()), current5_(current5), begin6_(g6.begin()), end6_(g6.end()), current6_(current6), begin7_(g7.begin()), end7_(g7.end()), current7_(current7), begin8_(g8.begin()), end8_(g8.end()), current8_(current8) { ComputeCurrentValue(); } virtual ~Iterator() {} virtual const ParamGeneratorInterface<ParamType>* BaseGenerator() const { return base_; } // Advance should not be called on beyond-of-range iterators // so no component iterators must be beyond end of range, either. virtual void Advance() { assert(!AtEnd()); ++current8_; if (current8_ == end8_) { current8_ = begin8_; ++current7_; } if (current7_ == end7_) { current7_ = begin7_; ++current6_; } if (current6_ == end6_) { current6_ = begin6_; ++current5_; } if (current5_ == end5_) { current5_ = begin5_; ++current4_; } if (current4_ == end4_) { current4_ = begin4_; ++current3_; } if (current3_ == end3_) { current3_ = begin3_; ++current2_; } if (current2_ == end2_) { current2_ = begin2_; ++current1_; } ComputeCurrentValue(); } virtual ParamIteratorInterface<ParamType>* Clone() const { return new Iterator(*this); } virtual const ParamType* Current() const { return &current_value_; } virtual bool Equals(const ParamIteratorInterface<ParamType>& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " << "from different generators." << std::endl; const Iterator* typed_other = CheckedDowncastToActualType<const Iterator>(&other); // We must report iterators equal if they both point beyond their // respective ranges. That can happen in a variety of fashions, // so we have to consult AtEnd(). return (AtEnd() && typed_other->AtEnd()) || ( current1_ == typed_other->current1_ && current2_ == typed_other->current2_ && current3_ == typed_other->current3_ && current4_ == typed_other->current4_ && current5_ == typed_other->current5_ && current6_ == typed_other->current6_ && current7_ == typed_other->current7_ && current8_ == typed_other->current8_); } private: Iterator(const Iterator& other) : base_(other.base_), begin1_(other.begin1_), end1_(other.end1_), current1_(other.current1_), begin2_(other.begin2_), end2_(other.end2_), current2_(other.current2_), begin3_(other.begin3_), end3_(other.end3_), current3_(other.current3_), begin4_(other.begin4_), end4_(other.end4_), current4_(other.current4_), begin5_(other.begin5_), end5_(other.end5_), current5_(other.current5_), begin6_(other.begin6_), end6_(other.end6_), current6_(other.current6_), begin7_(other.begin7_), end7_(other.end7_), current7_(other.current7_), begin8_(other.begin8_), end8_(other.end8_), current8_(other.current8_) { ComputeCurrentValue(); } void ComputeCurrentValue() { if (!AtEnd()) current_value_ = ParamType(*current1_, *current2_, *current3_, *current4_, *current5_, *current6_, *current7_, *current8_); } bool AtEnd() const { // We must report iterator past the end of the range when either of the // component iterators has reached the end of its range. return current1_ == end1_ || current2_ == end2_ || current3_ == end3_ || current4_ == end4_ || current5_ == end5_ || current6_ == end6_ || current7_ == end7_ || current8_ == end8_; } // No implementation - assignment is unsupported. void operator=(const Iterator& other); const ParamGeneratorInterface<ParamType>* const base_; // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. // current[i]_ is the actual traversing iterator. const typename ParamGenerator<T1>::iterator begin1_; const typename ParamGenerator<T1>::iterator end1_; typename ParamGenerator<T1>::iterator current1_; const typename ParamGenerator<T2>::iterator begin2_; const typename ParamGenerator<T2>::iterator end2_; typename ParamGenerator<T2>::iterator current2_; const typename ParamGenerator<T3>::iterator begin3_; const typename ParamGenerator<T3>::iterator end3_; typename ParamGenerator<T3>::iterator current3_; const typename ParamGenerator<T4>::iterator begin4_; const typename ParamGenerator<T4>::iterator end4_; typename ParamGenerator<T4>::iterator current4_; const typename ParamGenerator<T5>::iterator begin5_; const typename ParamGenerator<T5>::iterator end5_; typename ParamGenerator<T5>::iterator current5_; const typename ParamGenerator<T6>::iterator begin6_; const typename ParamGenerator<T6>::iterator end6_; typename ParamGenerator<T6>::iterator current6_; const typename ParamGenerator<T7>::iterator begin7_; const typename ParamGenerator<T7>::iterator end7_; typename ParamGenerator<T7>::iterator current7_; const typename ParamGenerator<T8>::iterator begin8_; const typename ParamGenerator<T8>::iterator end8_; typename ParamGenerator<T8>::iterator current8_; ParamType current_value_; }; // class CartesianProductGenerator8::Iterator // No implementation - assignment is unsupported. void operator=(const CartesianProductGenerator8& other); const ParamGenerator<T1> g1_; const ParamGenerator<T2> g2_; const ParamGenerator<T3> g3_; const ParamGenerator<T4> g4_; const ParamGenerator<T5> g5_; const ParamGenerator<T6> g6_; const ParamGenerator<T7> g7_; const ParamGenerator<T8> g8_; }; // class CartesianProductGenerator8 template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9> class CartesianProductGenerator9 : public ParamGeneratorInterface< ::testing::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9> > { public: typedef ::testing::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9> ParamType; CartesianProductGenerator9(const ParamGenerator<T1>& g1, const ParamGenerator<T2>& g2, const ParamGenerator<T3>& g3, const ParamGenerator<T4>& g4, const ParamGenerator<T5>& g5, const ParamGenerator<T6>& g6, const ParamGenerator<T7>& g7, const ParamGenerator<T8>& g8, const ParamGenerator<T9>& g9) : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8), g9_(g9) {} virtual ~CartesianProductGenerator9() {} virtual ParamIteratorInterface<ParamType>* Begin() const { return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin(), g7_, g7_.begin(), g8_, g8_.begin(), g9_, g9_.begin()); } virtual ParamIteratorInterface<ParamType>* End() const { return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end(), g7_, g7_.end(), g8_, g8_.end(), g9_, g9_.end()); } private: class Iterator : public ParamIteratorInterface<ParamType> { public: Iterator(const ParamGeneratorInterface<ParamType>* base, const ParamGenerator<T1>& g1, const typename ParamGenerator<T1>::iterator& current1, const ParamGenerator<T2>& g2, const typename ParamGenerator<T2>::iterator& current2, const ParamGenerator<T3>& g3, const typename ParamGenerator<T3>::iterator& current3, const ParamGenerator<T4>& g4, const typename ParamGenerator<T4>::iterator& current4, const ParamGenerator<T5>& g5, const typename ParamGenerator<T5>::iterator& current5, const ParamGenerator<T6>& g6, const typename ParamGenerator<T6>::iterator& current6, const ParamGenerator<T7>& g7, const typename ParamGenerator<T7>::iterator& current7, const ParamGenerator<T8>& g8, const typename ParamGenerator<T8>::iterator& current8, const ParamGenerator<T9>& g9, const typename ParamGenerator<T9>::iterator& current9) : base_(base), begin1_(g1.begin()), end1_(g1.end()), current1_(current1), begin2_(g2.begin()), end2_(g2.end()), current2_(current2), begin3_(g3.begin()), end3_(g3.end()), current3_(current3), begin4_(g4.begin()), end4_(g4.end()), current4_(current4), begin5_(g5.begin()), end5_(g5.end()), current5_(current5), begin6_(g6.begin()), end6_(g6.end()), current6_(current6), begin7_(g7.begin()), end7_(g7.end()), current7_(current7), begin8_(g8.begin()), end8_(g8.end()), current8_(current8), begin9_(g9.begin()), end9_(g9.end()), current9_(current9) { ComputeCurrentValue(); } virtual ~Iterator() {} virtual const ParamGeneratorInterface<ParamType>* BaseGenerator() const { return base_; } // Advance should not be called on beyond-of-range iterators // so no component iterators must be beyond end of range, either. virtual void Advance() { assert(!AtEnd()); ++current9_; if (current9_ == end9_) { current9_ = begin9_; ++current8_; } if (current8_ == end8_) { current8_ = begin8_; ++current7_; } if (current7_ == end7_) { current7_ = begin7_; ++current6_; } if (current6_ == end6_) { current6_ = begin6_; ++current5_; } if (current5_ == end5_) { current5_ = begin5_; ++current4_; } if (current4_ == end4_) { current4_ = begin4_; ++current3_; } if (current3_ == end3_) { current3_ = begin3_; ++current2_; } if (current2_ == end2_) { current2_ = begin2_; ++current1_; } ComputeCurrentValue(); } virtual ParamIteratorInterface<ParamType>* Clone() const { return new Iterator(*this); } virtual const ParamType* Current() const { return &current_value_; } virtual bool Equals(const ParamIteratorInterface<ParamType>& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " << "from different generators." << std::endl; const Iterator* typed_other = CheckedDowncastToActualType<const Iterator>(&other); // We must report iterators equal if they both point beyond their // respective ranges. That can happen in a variety of fashions, // so we have to consult AtEnd(). return (AtEnd() && typed_other->AtEnd()) || ( current1_ == typed_other->current1_ && current2_ == typed_other->current2_ && current3_ == typed_other->current3_ && current4_ == typed_other->current4_ && current5_ == typed_other->current5_ && current6_ == typed_other->current6_ && current7_ == typed_other->current7_ && current8_ == typed_other->current8_ && current9_ == typed_other->current9_); } private: Iterator(const Iterator& other) : base_(other.base_), begin1_(other.begin1_), end1_(other.end1_), current1_(other.current1_), begin2_(other.begin2_), end2_(other.end2_), current2_(other.current2_), begin3_(other.begin3_), end3_(other.end3_), current3_(other.current3_), begin4_(other.begin4_), end4_(other.end4_), current4_(other.current4_), begin5_(other.begin5_), end5_(other.end5_), current5_(other.current5_), begin6_(other.begin6_), end6_(other.end6_), current6_(other.current6_), begin7_(other.begin7_), end7_(other.end7_), current7_(other.current7_), begin8_(other.begin8_), end8_(other.end8_), current8_(other.current8_), begin9_(other.begin9_), end9_(other.end9_), current9_(other.current9_) { ComputeCurrentValue(); } void ComputeCurrentValue() { if (!AtEnd()) current_value_ = ParamType(*current1_, *current2_, *current3_, *current4_, *current5_, *current6_, *current7_, *current8_, *current9_); } bool AtEnd() const { // We must report iterator past the end of the range when either of the // component iterators has reached the end of its range. return current1_ == end1_ || current2_ == end2_ || current3_ == end3_ || current4_ == end4_ || current5_ == end5_ || current6_ == end6_ || current7_ == end7_ || current8_ == end8_ || current9_ == end9_; } // No implementation - assignment is unsupported. void operator=(const Iterator& other); const ParamGeneratorInterface<ParamType>* const base_; // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. // current[i]_ is the actual traversing iterator. const typename ParamGenerator<T1>::iterator begin1_; const typename ParamGenerator<T1>::iterator end1_; typename ParamGenerator<T1>::iterator current1_; const typename ParamGenerator<T2>::iterator begin2_; const typename ParamGenerator<T2>::iterator end2_; typename ParamGenerator<T2>::iterator current2_; const typename ParamGenerator<T3>::iterator begin3_; const typename ParamGenerator<T3>::iterator end3_; typename ParamGenerator<T3>::iterator current3_; const typename ParamGenerator<T4>::iterator begin4_; const typename ParamGenerator<T4>::iterator end4_; typename ParamGenerator<T4>::iterator current4_; const typename ParamGenerator<T5>::iterator begin5_; const typename ParamGenerator<T5>::iterator end5_; typename ParamGenerator<T5>::iterator current5_; const typename ParamGenerator<T6>::iterator begin6_; const typename ParamGenerator<T6>::iterator end6_; typename ParamGenerator<T6>::iterator current6_; const typename ParamGenerator<T7>::iterator begin7_; const typename ParamGenerator<T7>::iterator end7_; typename ParamGenerator<T7>::iterator current7_; const typename ParamGenerator<T8>::iterator begin8_; const typename ParamGenerator<T8>::iterator end8_; typename ParamGenerator<T8>::iterator current8_; const typename ParamGenerator<T9>::iterator begin9_; const typename ParamGenerator<T9>::iterator end9_; typename ParamGenerator<T9>::iterator current9_; ParamType current_value_; }; // class CartesianProductGenerator9::Iterator // No implementation - assignment is unsupported. void operator=(const CartesianProductGenerator9& other); const ParamGenerator<T1> g1_; const ParamGenerator<T2> g2_; const ParamGenerator<T3> g3_; const ParamGenerator<T4> g4_; const ParamGenerator<T5> g5_; const ParamGenerator<T6> g6_; const ParamGenerator<T7> g7_; const ParamGenerator<T8> g8_; const ParamGenerator<T9> g9_; }; // class CartesianProductGenerator9 template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10> class CartesianProductGenerator10 : public ParamGeneratorInterface< ::testing::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> > { public: typedef ::testing::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> ParamType; CartesianProductGenerator10(const ParamGenerator<T1>& g1, const ParamGenerator<T2>& g2, const ParamGenerator<T3>& g3, const ParamGenerator<T4>& g4, const ParamGenerator<T5>& g5, const ParamGenerator<T6>& g6, const ParamGenerator<T7>& g7, const ParamGenerator<T8>& g8, const ParamGenerator<T9>& g9, const ParamGenerator<T10>& g10) : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8), g9_(g9), g10_(g10) {} virtual ~CartesianProductGenerator10() {} virtual ParamIteratorInterface<ParamType>* Begin() const { return new Iterator(this, g1_, g1_.begin(), g2_, g2_.begin(), g3_, g3_.begin(), g4_, g4_.begin(), g5_, g5_.begin(), g6_, g6_.begin(), g7_, g7_.begin(), g8_, g8_.begin(), g9_, g9_.begin(), g10_, g10_.begin()); } virtual ParamIteratorInterface<ParamType>* End() const { return new Iterator(this, g1_, g1_.end(), g2_, g2_.end(), g3_, g3_.end(), g4_, g4_.end(), g5_, g5_.end(), g6_, g6_.end(), g7_, g7_.end(), g8_, g8_.end(), g9_, g9_.end(), g10_, g10_.end()); } private: class Iterator : public ParamIteratorInterface<ParamType> { public: Iterator(const ParamGeneratorInterface<ParamType>* base, const ParamGenerator<T1>& g1, const typename ParamGenerator<T1>::iterator& current1, const ParamGenerator<T2>& g2, const typename ParamGenerator<T2>::iterator& current2, const ParamGenerator<T3>& g3, const typename ParamGenerator<T3>::iterator& current3, const ParamGenerator<T4>& g4, const typename ParamGenerator<T4>::iterator& current4, const ParamGenerator<T5>& g5, const typename ParamGenerator<T5>::iterator& current5, const ParamGenerator<T6>& g6, const typename ParamGenerator<T6>::iterator& current6, const ParamGenerator<T7>& g7, const typename ParamGenerator<T7>::iterator& current7, const ParamGenerator<T8>& g8, const typename ParamGenerator<T8>::iterator& current8, const ParamGenerator<T9>& g9, const typename ParamGenerator<T9>::iterator& current9, const ParamGenerator<T10>& g10, const typename ParamGenerator<T10>::iterator& current10) : base_(base), begin1_(g1.begin()), end1_(g1.end()), current1_(current1), begin2_(g2.begin()), end2_(g2.end()), current2_(current2), begin3_(g3.begin()), end3_(g3.end()), current3_(current3), begin4_(g4.begin()), end4_(g4.end()), current4_(current4), begin5_(g5.begin()), end5_(g5.end()), current5_(current5), begin6_(g6.begin()), end6_(g6.end()), current6_(current6), begin7_(g7.begin()), end7_(g7.end()), current7_(current7), begin8_(g8.begin()), end8_(g8.end()), current8_(current8), begin9_(g9.begin()), end9_(g9.end()), current9_(current9), begin10_(g10.begin()), end10_(g10.end()), current10_(current10) { ComputeCurrentValue(); } virtual ~Iterator() {} virtual const ParamGeneratorInterface<ParamType>* BaseGenerator() const { return base_; } // Advance should not be called on beyond-of-range iterators // so no component iterators must be beyond end of range, either. virtual void Advance() { assert(!AtEnd()); ++current10_; if (current10_ == end10_) { current10_ = begin10_; ++current9_; } if (current9_ == end9_) { current9_ = begin9_; ++current8_; } if (current8_ == end8_) { current8_ = begin8_; ++current7_; } if (current7_ == end7_) { current7_ = begin7_; ++current6_; } if (current6_ == end6_) { current6_ = begin6_; ++current5_; } if (current5_ == end5_) { current5_ = begin5_; ++current4_; } if (current4_ == end4_) { current4_ = begin4_; ++current3_; } if (current3_ == end3_) { current3_ = begin3_; ++current2_; } if (current2_ == end2_) { current2_ = begin2_; ++current1_; } ComputeCurrentValue(); } virtual ParamIteratorInterface<ParamType>* Clone() const { return new Iterator(*this); } virtual const ParamType* Current() const { return &current_value_; } virtual bool Equals(const ParamIteratorInterface<ParamType>& other) const { // Having the same base generator guarantees that the other // iterator is of the same type and we can downcast. GTEST_CHECK_(BaseGenerator() == other.BaseGenerator()) << "The program attempted to compare iterators " << "from different generators." << std::endl; const Iterator* typed_other = CheckedDowncastToActualType<const Iterator>(&other); // We must report iterators equal if they both point beyond their // respective ranges. That can happen in a variety of fashions, // so we have to consult AtEnd(). return (AtEnd() && typed_other->AtEnd()) || ( current1_ == typed_other->current1_ && current2_ == typed_other->current2_ && current3_ == typed_other->current3_ && current4_ == typed_other->current4_ && current5_ == typed_other->current5_ && current6_ == typed_other->current6_ && current7_ == typed_other->current7_ && current8_ == typed_other->current8_ && current9_ == typed_other->current9_ && current10_ == typed_other->current10_); } private: Iterator(const Iterator& other) : base_(other.base_), begin1_(other.begin1_), end1_(other.end1_), current1_(other.current1_), begin2_(other.begin2_), end2_(other.end2_), current2_(other.current2_), begin3_(other.begin3_), end3_(other.end3_), current3_(other.current3_), begin4_(other.begin4_), end4_(other.end4_), current4_(other.current4_), begin5_(other.begin5_), end5_(other.end5_), current5_(other.current5_), begin6_(other.begin6_), end6_(other.end6_), current6_(other.current6_), begin7_(other.begin7_), end7_(other.end7_), current7_(other.current7_), begin8_(other.begin8_), end8_(other.end8_), current8_(other.current8_), begin9_(other.begin9_), end9_(other.end9_), current9_(other.current9_), begin10_(other.begin10_), end10_(other.end10_), current10_(other.current10_) { ComputeCurrentValue(); } void ComputeCurrentValue() { if (!AtEnd()) current_value_ = ParamType(*current1_, *current2_, *current3_, *current4_, *current5_, *current6_, *current7_, *current8_, *current9_, *current10_); } bool AtEnd() const { // We must report iterator past the end of the range when either of the // component iterators has reached the end of its range. return current1_ == end1_ || current2_ == end2_ || current3_ == end3_ || current4_ == end4_ || current5_ == end5_ || current6_ == end6_ || current7_ == end7_ || current8_ == end8_ || current9_ == end9_ || current10_ == end10_; } // No implementation - assignment is unsupported. void operator=(const Iterator& other); const ParamGeneratorInterface<ParamType>* const base_; // begin[i]_ and end[i]_ define the i-th range that Iterator traverses. // current[i]_ is the actual traversing iterator. const typename ParamGenerator<T1>::iterator begin1_; const typename ParamGenerator<T1>::iterator end1_; typename ParamGenerator<T1>::iterator current1_; const typename ParamGenerator<T2>::iterator begin2_; const typename ParamGenerator<T2>::iterator end2_; typename ParamGenerator<T2>::iterator current2_; const typename ParamGenerator<T3>::iterator begin3_; const typename ParamGenerator<T3>::iterator end3_; typename ParamGenerator<T3>::iterator current3_; const typename ParamGenerator<T4>::iterator begin4_; const typename ParamGenerator<T4>::iterator end4_; typename ParamGenerator<T4>::iterator current4_; const typename ParamGenerator<T5>::iterator begin5_; const typename ParamGenerator<T5>::iterator end5_; typename ParamGenerator<T5>::iterator current5_; const typename ParamGenerator<T6>::iterator begin6_; const typename ParamGenerator<T6>::iterator end6_; typename ParamGenerator<T6>::iterator current6_; const typename ParamGenerator<T7>::iterator begin7_; const typename ParamGenerator<T7>::iterator end7_; typename ParamGenerator<T7>::iterator current7_; const typename ParamGenerator<T8>::iterator begin8_; const typename ParamGenerator<T8>::iterator end8_; typename ParamGenerator<T8>::iterator current8_; const typename ParamGenerator<T9>::iterator begin9_; const typename ParamGenerator<T9>::iterator end9_; typename ParamGenerator<T9>::iterator current9_; const typename ParamGenerator<T10>::iterator begin10_; const typename ParamGenerator<T10>::iterator end10_; typename ParamGenerator<T10>::iterator current10_; ParamType current_value_; }; // class CartesianProductGenerator10::Iterator // No implementation - assignment is unsupported. void operator=(const CartesianProductGenerator10& other); const ParamGenerator<T1> g1_; const ParamGenerator<T2> g2_; const ParamGenerator<T3> g3_; const ParamGenerator<T4> g4_; const ParamGenerator<T5> g5_; const ParamGenerator<T6> g6_; const ParamGenerator<T7> g7_; const ParamGenerator<T8> g8_; const ParamGenerator<T9> g9_; const ParamGenerator<T10> g10_; }; // class CartesianProductGenerator10 // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Helper classes providing Combine() with polymorphic features. They allow // casting CartesianProductGeneratorN<T> to ParamGenerator<U> if T is // convertible to U. // template <class Generator1, class Generator2> class CartesianProductHolder2 { public: CartesianProductHolder2(const Generator1& g1, const Generator2& g2) : g1_(g1), g2_(g2) {} template <typename T1, typename T2> operator ParamGenerator< ::testing::tuple<T1, T2> >() const { return ParamGenerator< ::testing::tuple<T1, T2> >( new CartesianProductGenerator2<T1, T2>( static_cast<ParamGenerator<T1> >(g1_), static_cast<ParamGenerator<T2> >(g2_))); } private: // No implementation - assignment is unsupported. void operator=(const CartesianProductHolder2& other); const Generator1 g1_; const Generator2 g2_; }; // class CartesianProductHolder2 template <class Generator1, class Generator2, class Generator3> class CartesianProductHolder3 { public: CartesianProductHolder3(const Generator1& g1, const Generator2& g2, const Generator3& g3) : g1_(g1), g2_(g2), g3_(g3) {} template <typename T1, typename T2, typename T3> operator ParamGenerator< ::testing::tuple<T1, T2, T3> >() const { return ParamGenerator< ::testing::tuple<T1, T2, T3> >( new CartesianProductGenerator3<T1, T2, T3>( static_cast<ParamGenerator<T1> >(g1_), static_cast<ParamGenerator<T2> >(g2_), static_cast<ParamGenerator<T3> >(g3_))); } private: // No implementation - assignment is unsupported. void operator=(const CartesianProductHolder3& other); const Generator1 g1_; const Generator2 g2_; const Generator3 g3_; }; // class CartesianProductHolder3 template <class Generator1, class Generator2, class Generator3, class Generator4> class CartesianProductHolder4 { public: CartesianProductHolder4(const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4) : g1_(g1), g2_(g2), g3_(g3), g4_(g4) {} template <typename T1, typename T2, typename T3, typename T4> operator ParamGenerator< ::testing::tuple<T1, T2, T3, T4> >() const { return ParamGenerator< ::testing::tuple<T1, T2, T3, T4> >( new CartesianProductGenerator4<T1, T2, T3, T4>( static_cast<ParamGenerator<T1> >(g1_), static_cast<ParamGenerator<T2> >(g2_), static_cast<ParamGenerator<T3> >(g3_), static_cast<ParamGenerator<T4> >(g4_))); } private: // No implementation - assignment is unsupported. void operator=(const CartesianProductHolder4& other); const Generator1 g1_; const Generator2 g2_; const Generator3 g3_; const Generator4 g4_; }; // class CartesianProductHolder4 template <class Generator1, class Generator2, class Generator3, class Generator4, class Generator5> class CartesianProductHolder5 { public: CartesianProductHolder5(const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, const Generator5& g5) : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5) {} template <typename T1, typename T2, typename T3, typename T4, typename T5> operator ParamGenerator< ::testing::tuple<T1, T2, T3, T4, T5> >() const { return ParamGenerator< ::testing::tuple<T1, T2, T3, T4, T5> >( new CartesianProductGenerator5<T1, T2, T3, T4, T5>( static_cast<ParamGenerator<T1> >(g1_), static_cast<ParamGenerator<T2> >(g2_), static_cast<ParamGenerator<T3> >(g3_), static_cast<ParamGenerator<T4> >(g4_), static_cast<ParamGenerator<T5> >(g5_))); } private: // No implementation - assignment is unsupported. void operator=(const CartesianProductHolder5& other); const Generator1 g1_; const Generator2 g2_; const Generator3 g3_; const Generator4 g4_; const Generator5 g5_; }; // class CartesianProductHolder5 template <class Generator1, class Generator2, class Generator3, class Generator4, class Generator5, class Generator6> class CartesianProductHolder6 { public: CartesianProductHolder6(const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, const Generator5& g5, const Generator6& g6) : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6) {} template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6> operator ParamGenerator< ::testing::tuple<T1, T2, T3, T4, T5, T6> >() const { return ParamGenerator< ::testing::tuple<T1, T2, T3, T4, T5, T6> >( new CartesianProductGenerator6<T1, T2, T3, T4, T5, T6>( static_cast<ParamGenerator<T1> >(g1_), static_cast<ParamGenerator<T2> >(g2_), static_cast<ParamGenerator<T3> >(g3_), static_cast<ParamGenerator<T4> >(g4_), static_cast<ParamGenerator<T5> >(g5_), static_cast<ParamGenerator<T6> >(g6_))); } private: // No implementation - assignment is unsupported. void operator=(const CartesianProductHolder6& other); const Generator1 g1_; const Generator2 g2_; const Generator3 g3_; const Generator4 g4_; const Generator5 g5_; const Generator6 g6_; }; // class CartesianProductHolder6 template <class Generator1, class Generator2, class Generator3, class Generator4, class Generator5, class Generator6, class Generator7> class CartesianProductHolder7 { public: CartesianProductHolder7(const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, const Generator5& g5, const Generator6& g6, const Generator7& g7) : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7) {} template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7> operator ParamGenerator< ::testing::tuple<T1, T2, T3, T4, T5, T6, T7> >() const { return ParamGenerator< ::testing::tuple<T1, T2, T3, T4, T5, T6, T7> >( new CartesianProductGenerator7<T1, T2, T3, T4, T5, T6, T7>( static_cast<ParamGenerator<T1> >(g1_), static_cast<ParamGenerator<T2> >(g2_), static_cast<ParamGenerator<T3> >(g3_), static_cast<ParamGenerator<T4> >(g4_), static_cast<ParamGenerator<T5> >(g5_), static_cast<ParamGenerator<T6> >(g6_), static_cast<ParamGenerator<T7> >(g7_))); } private: // No implementation - assignment is unsupported. void operator=(const CartesianProductHolder7& other); const Generator1 g1_; const Generator2 g2_; const Generator3 g3_; const Generator4 g4_; const Generator5 g5_; const Generator6 g6_; const Generator7 g7_; }; // class CartesianProductHolder7 template <class Generator1, class Generator2, class Generator3, class Generator4, class Generator5, class Generator6, class Generator7, class Generator8> class CartesianProductHolder8 { public: CartesianProductHolder8(const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, const Generator5& g5, const Generator6& g6, const Generator7& g7, const Generator8& g8) : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8) {} template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8> operator ParamGenerator< ::testing::tuple<T1, T2, T3, T4, T5, T6, T7, T8> >() const { return ParamGenerator< ::testing::tuple<T1, T2, T3, T4, T5, T6, T7, T8> >( new CartesianProductGenerator8<T1, T2, T3, T4, T5, T6, T7, T8>( static_cast<ParamGenerator<T1> >(g1_), static_cast<ParamGenerator<T2> >(g2_), static_cast<ParamGenerator<T3> >(g3_), static_cast<ParamGenerator<T4> >(g4_), static_cast<ParamGenerator<T5> >(g5_), static_cast<ParamGenerator<T6> >(g6_), static_cast<ParamGenerator<T7> >(g7_), static_cast<ParamGenerator<T8> >(g8_))); } private: // No implementation - assignment is unsupported. void operator=(const CartesianProductHolder8& other); const Generator1 g1_; const Generator2 g2_; const Generator3 g3_; const Generator4 g4_; const Generator5 g5_; const Generator6 g6_; const Generator7 g7_; const Generator8 g8_; }; // class CartesianProductHolder8 template <class Generator1, class Generator2, class Generator3, class Generator4, class Generator5, class Generator6, class Generator7, class Generator8, class Generator9> class CartesianProductHolder9 { public: CartesianProductHolder9(const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, const Generator5& g5, const Generator6& g6, const Generator7& g7, const Generator8& g8, const Generator9& g9) : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8), g9_(g9) {} template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9> operator ParamGenerator< ::testing::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9> >() const { return ParamGenerator< ::testing::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9> >( new CartesianProductGenerator9<T1, T2, T3, T4, T5, T6, T7, T8, T9>( static_cast<ParamGenerator<T1> >(g1_), static_cast<ParamGenerator<T2> >(g2_), static_cast<ParamGenerator<T3> >(g3_), static_cast<ParamGenerator<T4> >(g4_), static_cast<ParamGenerator<T5> >(g5_), static_cast<ParamGenerator<T6> >(g6_), static_cast<ParamGenerator<T7> >(g7_), static_cast<ParamGenerator<T8> >(g8_), static_cast<ParamGenerator<T9> >(g9_))); } private: // No implementation - assignment is unsupported. void operator=(const CartesianProductHolder9& other); const Generator1 g1_; const Generator2 g2_; const Generator3 g3_; const Generator4 g4_; const Generator5 g5_; const Generator6 g6_; const Generator7 g7_; const Generator8 g8_; const Generator9 g9_; }; // class CartesianProductHolder9 template <class Generator1, class Generator2, class Generator3, class Generator4, class Generator5, class Generator6, class Generator7, class Generator8, class Generator9, class Generator10> class CartesianProductHolder10 { public: CartesianProductHolder10(const Generator1& g1, const Generator2& g2, const Generator3& g3, const Generator4& g4, const Generator5& g5, const Generator6& g6, const Generator7& g7, const Generator8& g8, const Generator9& g9, const Generator10& g10) : g1_(g1), g2_(g2), g3_(g3), g4_(g4), g5_(g5), g6_(g6), g7_(g7), g8_(g8), g9_(g9), g10_(g10) {} template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10> operator ParamGenerator< ::testing::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> >() const { return ParamGenerator< ::testing::tuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> >( new CartesianProductGenerator10<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>( static_cast<ParamGenerator<T1> >(g1_), static_cast<ParamGenerator<T2> >(g2_), static_cast<ParamGenerator<T3> >(g3_), static_cast<ParamGenerator<T4> >(g4_), static_cast<ParamGenerator<T5> >(g5_), static_cast<ParamGenerator<T6> >(g6_), static_cast<ParamGenerator<T7> >(g7_), static_cast<ParamGenerator<T8> >(g8_), static_cast<ParamGenerator<T9> >(g9_), static_cast<ParamGenerator<T10> >(g10_))); } private: // No implementation - assignment is unsupported. void operator=(const CartesianProductHolder10& other); const Generator1 g1_; const Generator2 g2_; const Generator3 g3_; const Generator4 g4_; const Generator5 g5_; const Generator6 g6_; const Generator7 g7_; const Generator8 g8_; const Generator9 g9_; const Generator10 g10_; }; // class CartesianProductHolder10 # endif // GTEST_HAS_COMBINE } // namespace internal } // namespace testing #endif // GTEST_HAS_PARAM_TEST #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_GENERATED_H_
0
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest/internal/gtest-port-arch.h
// Copyright 2015, 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. // // The Google C++ Testing Framework (Google Test) // // This header file defines the GTEST_OS_* macro. // It is separate from gtest-port.h so that custom/gtest-port.h can include it. #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_ // Determines the platform on which Google Test is compiled. #ifdef __CYGWIN__ # define GTEST_OS_CYGWIN 1 #elif defined __SYMBIAN32__ # define GTEST_OS_SYMBIAN 1 #elif defined _WIN32 # define GTEST_OS_WINDOWS 1 # ifdef _WIN32_WCE # define GTEST_OS_WINDOWS_MOBILE 1 # elif defined(__MINGW__) || defined(__MINGW32__) # define GTEST_OS_WINDOWS_MINGW 1 # elif defined(WINAPI_FAMILY) # include <winapifamily.h> # if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) # define GTEST_OS_WINDOWS_DESKTOP 1 # elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP) # define GTEST_OS_WINDOWS_PHONE 1 # elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) # define GTEST_OS_WINDOWS_RT 1 # else // WINAPI_FAMILY defined but no known partition matched. // Default to desktop. # define GTEST_OS_WINDOWS_DESKTOP 1 # endif # else # define GTEST_OS_WINDOWS_DESKTOP 1 # endif // _WIN32_WCE #elif defined __APPLE__ # define GTEST_OS_MAC 1 # if TARGET_OS_IPHONE # define GTEST_OS_IOS 1 # endif #elif defined __FreeBSD__ # define GTEST_OS_FREEBSD 1 #elif defined __linux__ # define GTEST_OS_LINUX 1 # if defined __ANDROID__ # define GTEST_OS_LINUX_ANDROID 1 # endif #elif defined __MVS__ # define GTEST_OS_ZOS 1 #elif defined(__sun) && defined(__SVR4) # define GTEST_OS_SOLARIS 1 #elif defined(_AIX) # define GTEST_OS_AIX 1 #elif defined(__hpux) # define GTEST_OS_HPUX 1 #elif defined __native_client__ # define GTEST_OS_NACL 1 #elif defined __OpenBSD__ # define GTEST_OS_OPENBSD 1 #elif defined __QNX__ # define GTEST_OS_QNX 1 #elif defined(__HAIKU__) # define GTEST_OS_HAIKU 1 #elif defined(_MINIX) # define GTEST_OS_MINIX 1 #endif // __CYGWIN__ #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_
0
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest/internal/gtest-death-test-internal.h
// Copyright 2005, 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. // // Authors: [email protected] (Zhanyong Wan), [email protected] (Sean Mcafee) // // The Google C++ Testing Framework (Google Test) // // This header file defines internal utilities needed for implementing // death tests. They are subject to change without notice. #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_ #include "gtest/internal/gtest-internal.h" #include <stdio.h> namespace testing { namespace internal { GTEST_DECLARE_string_(internal_run_death_test); // Names of the flags (needed for parsing Google Test flags). const char kDeathTestStyleFlag[] = "death_test_style"; const char kDeathTestUseFork[] = "death_test_use_fork"; const char kInternalRunDeathTestFlag[] = "internal_run_death_test"; #if GTEST_HAS_DEATH_TEST // DeathTest is a class that hides much of the complexity of the // GTEST_DEATH_TEST_ macro. It is abstract; its static Create method // returns a concrete class that depends on the prevailing death test // style, as defined by the --gtest_death_test_style and/or // --gtest_internal_run_death_test flags. // In describing the results of death tests, these terms are used with // the corresponding definitions: // // exit status: The integer exit information in the format specified // by wait(2) // exit code: The integer code passed to exit(3), _exit(2), or // returned from main() class GTEST_API_ DeathTest { public: // Create returns false if there was an error determining the // appropriate action to take for the current death test; for example, // if the gtest_death_test_style flag is set to an invalid value. // The LastMessage method will return a more detailed message in that // case. Otherwise, the DeathTest pointer pointed to by the "test" // argument is set. If the death test should be skipped, the pointer // is set to NULL; otherwise, it is set to the address of a new concrete // DeathTest object that controls the execution of the current test. static bool Create(const char* statement, const RE* regex, const char* file, int line, DeathTest** test); DeathTest(); virtual ~DeathTest() { } // A helper class that aborts a death test when it's deleted. class ReturnSentinel { public: explicit ReturnSentinel(DeathTest* test) : test_(test) { } ~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); } private: DeathTest* const test_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ReturnSentinel); } GTEST_ATTRIBUTE_UNUSED_; // An enumeration of possible roles that may be taken when a death // test is encountered. EXECUTE means that the death test logic should // be executed immediately. OVERSEE means that the program should prepare // the appropriate environment for a child process to execute the death // test, then wait for it to complete. enum TestRole { OVERSEE_TEST, EXECUTE_TEST }; // An enumeration of the three reasons that a test might be aborted. enum AbortReason { TEST_ENCOUNTERED_RETURN_STATEMENT, TEST_THREW_EXCEPTION, TEST_DID_NOT_DIE }; // Assumes one of the above roles. virtual TestRole AssumeRole() = 0; // Waits for the death test to finish and returns its status. virtual int Wait() = 0; // Returns true if the death test passed; that is, the test process // exited during the test, its exit status matches a user-supplied // predicate, and its stderr output matches a user-supplied regular // expression. // The user-supplied predicate may be a macro expression rather // than a function pointer or functor, or else Wait and Passed could // be combined. virtual bool Passed(bool exit_status_ok) = 0; // Signals that the death test did not die as expected. virtual void Abort(AbortReason reason) = 0; // Returns a human-readable outcome message regarding the outcome of // the last death test. static const char* LastMessage(); static void set_last_death_test_message(const std::string& message); private: // A string containing a description of the outcome of the last death test. static std::string last_death_test_message_; GTEST_DISALLOW_COPY_AND_ASSIGN_(DeathTest); }; // Factory interface for death tests. May be mocked out for testing. class DeathTestFactory { public: virtual ~DeathTestFactory() { } virtual bool Create(const char* statement, const RE* regex, const char* file, int line, DeathTest** test) = 0; }; // A concrete DeathTestFactory implementation for normal use. class DefaultDeathTestFactory : public DeathTestFactory { public: virtual bool Create(const char* statement, const RE* regex, const char* file, int line, DeathTest** test); }; // Returns true if exit_status describes a process that was terminated // by a signal, or exited normally with a nonzero exit code. GTEST_API_ bool ExitedUnsuccessfully(int exit_status); // Traps C++ exceptions escaping statement and reports them as test // failures. Note that trapping SEH exceptions is not implemented here. # if GTEST_HAS_EXCEPTIONS # define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \ try { \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ } catch (const ::std::exception& gtest_exception) { \ fprintf(\ stderr, \ "\n%s: Caught std::exception-derived exception escaping the " \ "death test statement. Exception message: %s\n", \ ::testing::internal::FormatFileLocation(__FILE__, __LINE__).c_str(), \ gtest_exception.what()); \ fflush(stderr); \ death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \ } catch (...) { \ death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \ } # else # define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) # endif // This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*, // ASSERT_EXIT*, and EXPECT_EXIT*. # define GTEST_DEATH_TEST_(statement, predicate, regex, fail) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (::testing::internal::AlwaysTrue()) { \ const ::testing::internal::RE& gtest_regex = (regex); \ ::testing::internal::DeathTest* gtest_dt; \ if (!::testing::internal::DeathTest::Create(#statement, &gtest_regex, \ __FILE__, __LINE__, &gtest_dt)) { \ goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \ } \ if (gtest_dt != NULL) { \ ::testing::internal::scoped_ptr< ::testing::internal::DeathTest> \ gtest_dt_ptr(gtest_dt); \ switch (gtest_dt->AssumeRole()) { \ case ::testing::internal::DeathTest::OVERSEE_TEST: \ if (!gtest_dt->Passed(predicate(gtest_dt->Wait()))) { \ goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__); \ } \ break; \ case ::testing::internal::DeathTest::EXECUTE_TEST: { \ ::testing::internal::DeathTest::ReturnSentinel \ gtest_sentinel(gtest_dt); \ GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt); \ gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE); \ break; \ } \ } \ } \ } else \ GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__): \ fail(::testing::internal::DeathTest::LastMessage()) // The symbol "fail" here expands to something into which a message // can be streamed. // This macro is for implementing ASSERT/EXPECT_DEBUG_DEATH when compiled in // NDEBUG mode. In this case we need the statements to be executed, the regex is // ignored, and the macro must accept a streamed message even though the message // is never printed. # define GTEST_EXECUTE_STATEMENT_(statement, regex) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (::testing::internal::AlwaysTrue()) { \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ } else \ ::testing::Message() // A class representing the parsed contents of the // --gtest_internal_run_death_test flag, as it existed when // RUN_ALL_TESTS was called. class InternalRunDeathTestFlag { public: InternalRunDeathTestFlag(const std::string& a_file, int a_line, int an_index, int a_write_fd) : file_(a_file), line_(a_line), index_(an_index), write_fd_(a_write_fd) {} ~InternalRunDeathTestFlag() { if (write_fd_ >= 0) posix::Close(write_fd_); } const std::string& file() const { return file_; } int line() const { return line_; } int index() const { return index_; } int write_fd() const { return write_fd_; } private: std::string file_; int line_; int index_; int write_fd_; GTEST_DISALLOW_COPY_AND_ASSIGN_(InternalRunDeathTestFlag); }; // Returns a newly created InternalRunDeathTestFlag object with fields // initialized from the GTEST_FLAG(internal_run_death_test) flag if // the flag is specified; otherwise returns NULL. InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag(); #else // GTEST_HAS_DEATH_TEST // This macro is used for implementing macros such as // EXPECT_DEATH_IF_SUPPORTED and ASSERT_DEATH_IF_SUPPORTED on systems where // death tests are not supported. Those macros must compile on such systems // iff EXPECT_DEATH and ASSERT_DEATH compile with the same parameters on // systems that support death tests. This allows one to write such a macro // on a system that does not support death tests and be sure that it will // compile on a death-test supporting system. // // Parameters: // statement - A statement that a macro such as EXPECT_DEATH would test // for program termination. This macro has to make sure this // statement is compiled but not executed, to ensure that // EXPECT_DEATH_IF_SUPPORTED compiles with a certain // parameter iff EXPECT_DEATH compiles with it. // regex - A regex that a macro such as EXPECT_DEATH would use to test // the output of statement. This parameter has to be // compiled but not evaluated by this macro, to ensure that // this macro only accepts expressions that a macro such as // EXPECT_DEATH would accept. // terminator - Must be an empty statement for EXPECT_DEATH_IF_SUPPORTED // and a return statement for ASSERT_DEATH_IF_SUPPORTED. // This ensures that ASSERT_DEATH_IF_SUPPORTED will not // compile inside functions where ASSERT_DEATH doesn't // compile. // // The branch that has an always false condition is used to ensure that // statement and regex are compiled (and thus syntactically correct) but // never executed. The unreachable code macro protects the terminator // statement from generating an 'unreachable code' warning in case // statement unconditionally returns or throws. The Message constructor at // the end allows the syntax of streaming additional messages into the // macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH. # define GTEST_UNSUPPORTED_DEATH_TEST_(statement, regex, terminator) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (::testing::internal::AlwaysTrue()) { \ GTEST_LOG_(WARNING) \ << "Death tests are not supported on this platform.\n" \ << "Statement '" #statement "' cannot be verified."; \ } else if (::testing::internal::AlwaysFalse()) { \ ::testing::internal::RE::PartialMatch(".*", (regex)); \ GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement); \ terminator; \ } else \ ::testing::Message() #endif // GTEST_HAS_DEATH_TEST } // namespace internal } // namespace testing #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_
0
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest/internal/gtest-string.h
// Copyright 2005, 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. // // Authors: [email protected] (Zhanyong Wan), [email protected] (Sean Mcafee) // // The Google C++ Testing Framework (Google Test) // // This header file declares the String class and functions used internally by // Google Test. They are subject to change without notice. They should not used // by code external to Google Test. // // This header file is #included by <gtest/internal/gtest-internal.h>. // It should not be #included by other files. #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ #ifdef __BORLANDC__ // string.h is not guaranteed to provide strcpy on C++ Builder. # include <mem.h> #endif #include <string.h> #include <string> #include "gtest/internal/gtest-port.h" namespace testing { namespace internal { // String - an abstract class holding static string utilities. class GTEST_API_ String { public: // Static utility methods // Clones a 0-terminated C string, allocating memory using new. The // caller is responsible for deleting the return value using // delete[]. Returns the cloned string, or NULL if the input is // NULL. // // This is different from strdup() in string.h, which allocates // memory using malloc(). static const char* CloneCString(const char* c_str); #if GTEST_OS_WINDOWS_MOBILE // Windows CE does not have the 'ANSI' versions of Win32 APIs. To be // able to pass strings to Win32 APIs on CE we need to convert them // to 'Unicode', UTF-16. // Creates a UTF-16 wide string from the given ANSI string, allocating // memory using new. The caller is responsible for deleting the return // value using delete[]. Returns the wide string, or NULL if the // input is NULL. // // The wide string is created using the ANSI codepage (CP_ACP) to // match the behaviour of the ANSI versions of Win32 calls and the // C runtime. static LPCWSTR AnsiToUtf16(const char* c_str); // Creates an ANSI string from the given wide string, allocating // memory using new. The caller is responsible for deleting the return // value using delete[]. Returns the ANSI string, or NULL if the // input is NULL. // // The returned string is created using the ANSI codepage (CP_ACP) to // match the behaviour of the ANSI versions of Win32 calls and the // C runtime. static const char* Utf16ToAnsi(LPCWSTR utf16_str); #endif // Compares two C strings. Returns true iff they have the same content. // // Unlike strcmp(), this function can handle NULL argument(s). A // NULL C string is considered different to any non-NULL C string, // including the empty string. static bool CStringEquals(const char* lhs, const char* rhs); // Converts a wide C string to a String using the UTF-8 encoding. // NULL will be converted to "(null)". If an error occurred during // the conversion, "(failed to convert from wide string)" is // returned. static std::string ShowWideCString(const wchar_t* wide_c_str); // Compares two wide C strings. Returns true iff they have the same // content. // // Unlike wcscmp(), this function can handle NULL argument(s). A // NULL C string is considered different to any non-NULL C string, // including the empty string. static bool WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs); // Compares two C strings, ignoring case. Returns true iff they // have the same content. // // Unlike strcasecmp(), this function can handle NULL argument(s). // A NULL C string is considered different to any non-NULL C string, // including the empty string. static bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs); // Compares two wide C strings, ignoring case. Returns true iff they // have the same content. // // Unlike wcscasecmp(), this function can handle NULL argument(s). // A NULL C string is considered different to any non-NULL wide C string, // including the empty string. // NB: The implementations on different platforms slightly differ. // On windows, this method uses _wcsicmp which compares according to LC_CTYPE // environment variable. On GNU platform this method uses wcscasecmp // which compares according to LC_CTYPE category of the current locale. // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the // current locale. static bool CaseInsensitiveWideCStringEquals(const wchar_t* lhs, const wchar_t* rhs); // Returns true iff the given string ends with the given suffix, ignoring // case. Any string is considered to end with an empty suffix. static bool EndsWithCaseInsensitive( const std::string& str, const std::string& suffix); // Formats an int value as "%02d". static std::string FormatIntWidth2(int value); // "%02d" for width == 2 // Formats an int value as "%X". static std::string FormatHexInt(int value); // Formats a byte as "%02X". static std::string FormatByte(unsigned char value); private: String(); // Not meant to be instantiated. }; // class String // Gets the content of the stringstream's buffer as an std::string. Each '\0' // character in the buffer is replaced with "\\0". GTEST_API_ std::string StringStreamToString(::std::stringstream* stream); } // namespace internal } // namespace testing #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
0
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest/internal/gtest-port.h
// Copyright 2005, 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. // // Authors: [email protected] (Zhanyong Wan) // // Low-level types and utilities for porting Google Test to various // platforms. All macros ending with _ and symbols defined in an // internal namespace are subject to change without notice. Code // outside Google Test MUST NOT USE THEM DIRECTLY. Macros that don't // end with _ are part of Google Test's public API and can be used by // code outside Google Test. // // This file is fundamental to Google Test. All other Google Test source // files are expected to #include this. Therefore, it cannot #include // any other Google Test header. #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_ // Environment-describing macros // ----------------------------- // // Google Test can be used in many different environments. Macros in // this section tell Google Test what kind of environment it is being // used in, such that Google Test can provide environment-specific // features and implementations. // // Google Test tries to automatically detect the properties of its // environment, so users usually don't need to worry about these // macros. However, the automatic detection is not perfect. // Sometimes it's necessary for a user to define some of the following // macros in the build script to override Google Test's decisions. // // If the user doesn't define a macro in the list, Google Test will // provide a default definition. After this header is #included, all // macros in this list will be defined to either 1 or 0. // // Notes to maintainers: // - Each macro here is a user-tweakable knob; do not grow the list // lightly. // - Use #if to key off these macros. Don't use #ifdef or "#if // defined(...)", which will not work as these macros are ALWAYS // defined. // // GTEST_HAS_CLONE - Define it to 1/0 to indicate that clone(2) // is/isn't available. // GTEST_HAS_EXCEPTIONS - Define it to 1/0 to indicate that exceptions // are enabled. // GTEST_HAS_GLOBAL_STRING - Define it to 1/0 to indicate that ::string // is/isn't available (some systems define // ::string, which is different to std::string). // GTEST_HAS_GLOBAL_WSTRING - Define it to 1/0 to indicate that ::string // is/isn't available (some systems define // ::wstring, which is different to std::wstring). // GTEST_HAS_POSIX_RE - Define it to 1/0 to indicate that POSIX regular // expressions are/aren't available. // GTEST_HAS_PTHREAD - Define it to 1/0 to indicate that <pthread.h> // is/isn't available. // GTEST_HAS_RTTI - Define it to 1/0 to indicate that RTTI is/isn't // enabled. // GTEST_HAS_STD_WSTRING - Define it to 1/0 to indicate that // std::wstring does/doesn't work (Google Test can // be used where std::wstring is unavailable). // GTEST_HAS_TR1_TUPLE - Define it to 1/0 to indicate tr1::tuple // is/isn't available. // GTEST_HAS_SEH - Define it to 1/0 to indicate whether the // compiler supports Microsoft's "Structured // Exception Handling". // GTEST_HAS_STREAM_REDIRECTION // - Define it to 1/0 to indicate whether the // platform supports I/O stream redirection using // dup() and dup2(). // GTEST_USE_OWN_TR1_TUPLE - Define it to 1/0 to indicate whether Google // Test's own tr1 tuple implementation should be // used. Unused when the user sets // GTEST_HAS_TR1_TUPLE to 0. // GTEST_LANG_CXX11 - Define it to 1/0 to indicate that Google Test // is building in C++11/C++98 mode. // GTEST_LINKED_AS_SHARED_LIBRARY // - Define to 1 when compiling tests that use // Google Test as a shared library (known as // DLL on Windows). // GTEST_CREATE_SHARED_LIBRARY // - Define to 1 when compiling Google Test itself // as a shared library. // Platform-indicating macros // -------------------------- // // Macros indicating the platform on which Google Test is being used // (a macro is defined to 1 if compiled on the given platform; // otherwise UNDEFINED -- it's never defined to 0.). Google Test // defines these macros automatically. Code outside Google Test MUST // NOT define them. // // GTEST_OS_AIX - IBM AIX // GTEST_OS_CYGWIN - Cygwin // GTEST_OS_FREEBSD - FreeBSD // GTEST_OS_HAIKU - Haiku // GTEST_OS_HPUX - HP-UX // GTEST_OS_LINUX - Linux // GTEST_OS_LINUX_ANDROID - Google Android // GTEST_OS_MAC - Mac OS X // GTEST_OS_IOS - iOS // GTEST_OS_MINIX - Minix // GTEST_OS_NACL - Google Native Client (NaCl) // GTEST_OS_OPENBSD - OpenBSD // GTEST_OS_QNX - QNX // GTEST_OS_SOLARIS - Sun Solaris // GTEST_OS_SYMBIAN - Symbian // GTEST_OS_WINDOWS - Windows (Desktop, MinGW, or Mobile) // GTEST_OS_WINDOWS_DESKTOP - Windows Desktop // GTEST_OS_WINDOWS_MINGW - MinGW // GTEST_OS_WINDOWS_MOBILE - Windows Mobile // GTEST_OS_WINDOWS_PHONE - Windows Phone // GTEST_OS_WINDOWS_RT - Windows Store App/WinRT // GTEST_OS_ZOS - z/OS // // Among the platforms, Cygwin, Linux, Max OS X, and Windows have the // most stable support. Since core members of the Google Test project // don't have access to other platforms, support for them may be less // stable. If you notice any problems on your platform, please notify // [email protected] (patches for fixing them are // even more welcome!). // // It is possible that none of the GTEST_OS_* macros are defined. // Feature-indicating macros // ------------------------- // // Macros indicating which Google Test features are available (a macro // is defined to 1 if the corresponding feature is supported; // otherwise UNDEFINED -- it's never defined to 0.). Google Test // defines these macros automatically. Code outside Google Test MUST // NOT define them. // // These macros are public so that portable tests can be written. // Such tests typically surround code using a feature with an #if // which controls that code. For example: // // #if GTEST_HAS_DEATH_TEST // EXPECT_DEATH(DoSomethingDeadly()); // #endif // // GTEST_HAS_COMBINE - the Combine() function (for value-parameterized // tests) // GTEST_HAS_DEATH_TEST - death tests // GTEST_HAS_PARAM_TEST - value-parameterized tests // GTEST_HAS_TYPED_TEST - typed tests // GTEST_HAS_TYPED_TEST_P - type-parameterized tests // GTEST_IS_THREADSAFE - Google Test is thread-safe. // GTEST_USES_POSIX_RE - enhanced POSIX regex is used. Do not confuse with // GTEST_HAS_POSIX_RE (see above) which users can // define themselves. // GTEST_USES_SIMPLE_RE - our own simple regex is used; // the above two are mutually exclusive. // GTEST_CAN_COMPARE_NULL - accepts untyped NULL in EXPECT_EQ(). // Misc public macros // ------------------ // // GTEST_FLAG(flag_name) - references the variable corresponding to // the given Google Test flag. // Internal utilities // ------------------ // // The following macros and utilities are for Google Test's INTERNAL // use only. Code outside Google Test MUST NOT USE THEM DIRECTLY. // // Macros for basic C++ coding: // GTEST_AMBIGUOUS_ELSE_BLOCKER_ - for disabling a gcc warning. // GTEST_ATTRIBUTE_UNUSED_ - declares that a class' instances or a // variable don't have to be used. // GTEST_DISALLOW_ASSIGN_ - disables operator=. // GTEST_DISALLOW_COPY_AND_ASSIGN_ - disables copy ctor and operator=. // GTEST_MUST_USE_RESULT_ - declares that a function's result must be used. // GTEST_INTENTIONAL_CONST_COND_PUSH_ - start code section where MSVC C4127 is // suppressed (constant conditional). // GTEST_INTENTIONAL_CONST_COND_POP_ - finish code section where MSVC C4127 // is suppressed. // // C++11 feature wrappers: // // testing::internal::move - portability wrapper for std::move. // // Synchronization: // Mutex, MutexLock, ThreadLocal, GetThreadCount() // - synchronization primitives. // // Template meta programming: // is_pointer - as in TR1; needed on Symbian and IBM XL C/C++ only. // IteratorTraits - partial implementation of std::iterator_traits, which // is not available in libCstd when compiled with Sun C++. // // Smart pointers: // scoped_ptr - as in TR2. // // Regular expressions: // RE - a simple regular expression class using the POSIX // Extended Regular Expression syntax on UNIX-like // platforms, or a reduced regular exception syntax on // other platforms, including Windows. // // Logging: // GTEST_LOG_() - logs messages at the specified severity level. // LogToStderr() - directs all log messages to stderr. // FlushInfoLog() - flushes informational log messages. // // Stdout and stderr capturing: // CaptureStdout() - starts capturing stdout. // GetCapturedStdout() - stops capturing stdout and returns the captured // string. // CaptureStderr() - starts capturing stderr. // GetCapturedStderr() - stops capturing stderr and returns the captured // string. // // Integer types: // TypeWithSize - maps an integer to a int type. // Int32, UInt32, Int64, UInt64, TimeInMillis // - integers of known sizes. // BiggestInt - the biggest signed integer type. // // Command-line utilities: // GTEST_DECLARE_*() - declares a flag. // GTEST_DEFINE_*() - defines a flag. // GetInjectableArgvs() - returns the command line as a vector of strings. // // Environment variable utilities: // GetEnv() - gets the value of an environment variable. // BoolFromGTestEnv() - parses a bool environment variable. // Int32FromGTestEnv() - parses an Int32 environment variable. // StringFromGTestEnv() - parses a string environment variable. #include <ctype.h> // for isspace, etc #include <stddef.h> // for ptrdiff_t #include <stdlib.h> #include <stdio.h> #include <string.h> #ifndef _WIN32_WCE # include <sys/types.h> # include <sys/stat.h> #endif // !_WIN32_WCE #if defined __APPLE__ # include <AvailabilityMacros.h> # include <TargetConditionals.h> #endif #include <algorithm> // NOLINT #include <iostream> // NOLINT #include <sstream> // NOLINT #include <string> // NOLINT #include <utility> #include <vector> // NOLINT #include "gtest/internal/gtest-port-arch.h" #include "gtest/internal/custom/gtest-port.h" #if !defined(GTEST_DEV_EMAIL_) # define GTEST_DEV_EMAIL_ "googletestframework@@googlegroups.com" # define GTEST_FLAG_PREFIX_ "gtest_" # define GTEST_FLAG_PREFIX_DASH_ "gtest-" # define GTEST_FLAG_PREFIX_UPPER_ "GTEST_" # define GTEST_NAME_ "Google Test" # define GTEST_PROJECT_URL_ "https://github.com/google/googletest/" #endif // !defined(GTEST_DEV_EMAIL_) #if !defined(GTEST_INIT_GOOGLE_TEST_NAME_) # define GTEST_INIT_GOOGLE_TEST_NAME_ "testing::InitGoogleTest" #endif // !defined(GTEST_INIT_GOOGLE_TEST_NAME_) // Determines the version of gcc that is used to compile this. #ifdef __GNUC__ // 40302 means version 4.3.2. # define GTEST_GCC_VER_ \ (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__) #endif // __GNUC__ // Macros for disabling Microsoft Visual C++ warnings. // // GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 4385) // /* code that triggers warnings C4800 and C4385 */ // GTEST_DISABLE_MSC_WARNINGS_POP_() #if _MSC_VER >= 1500 # define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) \ __pragma(warning(push)) \ __pragma(warning(disable: warnings)) # define GTEST_DISABLE_MSC_WARNINGS_POP_() \ __pragma(warning(pop)) #else // Older versions of MSVC don't have __pragma. # define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) # define GTEST_DISABLE_MSC_WARNINGS_POP_() #endif #ifndef GTEST_LANG_CXX11 // gcc and clang define __GXX_EXPERIMENTAL_CXX0X__ when // -std={c,gnu}++{0x,11} is passed. The C++11 standard specifies a // value for __cplusplus, and recent versions of clang, gcc, and // probably other compilers set that too in C++11 mode. // HLSL Change - Add MSC_VER 1900 # if __GXX_EXPERIMENTAL_CXX0X__ || __cplusplus >= 201103L || _MSC_VER >= 1900 // Compiling in at least C++11 mode. # define GTEST_LANG_CXX11 1 # else # define GTEST_LANG_CXX11 0 # endif #endif // Distinct from C++11 language support, some environments don't provide // proper C++11 library support. Notably, it's possible to build in // C++11 mode when targeting Mac OS X 10.6, which has an old libstdc++ // with no C++11 support. // // libstdc++ has sufficient C++11 support as of GCC 4.6.0, __GLIBCXX__ // 20110325, but maintenance releases in the 4.4 and 4.5 series followed // this date, so check for those versions by their date stamps. // https://gcc.gnu.org/onlinedocs/libstdc++/manual/abi.html#abi.versioning #if GTEST_LANG_CXX11 && \ (!defined(__GLIBCXX__) || ( \ __GLIBCXX__ >= 20110325ul && /* GCC >= 4.6.0 */ \ /* Blacklist of patch releases of older branches: */ \ __GLIBCXX__ != 20110416ul && /* GCC 4.4.6 */ \ __GLIBCXX__ != 20120313ul && /* GCC 4.4.7 */ \ __GLIBCXX__ != 20110428ul && /* GCC 4.5.3 */ \ __GLIBCXX__ != 20120702ul)) /* GCC 4.5.4 */ # define GTEST_STDLIB_CXX11 1 #endif // Only use C++11 library features if the library provides them. #if GTEST_STDLIB_CXX11 # define GTEST_HAS_STD_BEGIN_AND_END_ 1 # define GTEST_HAS_STD_FORWARD_LIST_ 1 # define GTEST_HAS_STD_FUNCTION_ 1 # define GTEST_HAS_STD_INITIALIZER_LIST_ 1 # define GTEST_HAS_STD_MOVE_ 1 # define GTEST_HAS_STD_SHARED_PTR_ 1 # define GTEST_HAS_STD_TYPE_TRAITS_ 1 # define GTEST_HAS_STD_UNIQUE_PTR_ 1 #endif // C++11 specifies that <tuple> provides std::tuple. // Some platforms still might not have it, however. #if GTEST_LANG_CXX11 # define GTEST_HAS_STD_TUPLE_ 1 # if defined(__clang__) // Inspired by http://clang.llvm.org/docs/LanguageExtensions.html#__has_include # if defined(__has_include) && !__has_include(<tuple>) # undef GTEST_HAS_STD_TUPLE_ # endif # elif defined(_MSC_VER) // Inspired by boost/config/stdlib/dinkumware.hpp # if defined(_CPPLIB_VER) && _CPPLIB_VER < 520 # undef GTEST_HAS_STD_TUPLE_ # endif # elif defined(__GLIBCXX__) // Inspired by boost/config/stdlib/libstdcpp3.hpp, // http://gcc.gnu.org/gcc-4.2/changes.html and // http://gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt01ch01.html#manual.intro.status.standard.200x # if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 2) # undef GTEST_HAS_STD_TUPLE_ # endif # endif #endif // Brings in definitions for functions used in the testing::internal::posix // namespace (read, write, close, chdir, isatty, stat). We do not currently // use them on Windows Mobile. #if GTEST_OS_WINDOWS # if !GTEST_OS_WINDOWS_MOBILE # include <direct.h> # include <io.h> # endif // In order to avoid having to include <windows.h>, use forward declaration // assuming CRITICAL_SECTION is a typedef of _RTL_CRITICAL_SECTION. // This assumption is verified by // WindowsTypesTest.CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION. struct _RTL_CRITICAL_SECTION; #else // This assumes that non-Windows OSes provide unistd.h. For OSes where this // is not the case, we need to include headers that provide the functions // mentioned above. # include <unistd.h> # include <strings.h> #endif // GTEST_OS_WINDOWS #if GTEST_OS_LINUX_ANDROID // Used to define __ANDROID_API__ matching the target NDK API level. # include <android/api-level.h> // NOLINT #endif // Defines this to true iff Google Test can use POSIX regular expressions. #ifndef GTEST_HAS_POSIX_RE # if GTEST_OS_LINUX_ANDROID // On Android, <regex.h> is only available starting with Gingerbread. # define GTEST_HAS_POSIX_RE (__ANDROID_API__ >= 9) # else # define GTEST_HAS_POSIX_RE (!GTEST_OS_WINDOWS) # endif #endif #if GTEST_USES_PCRE // The appropriate headers have already been included. #elif GTEST_HAS_POSIX_RE // On some platforms, <regex.h> needs someone to define size_t, and // won't compile otherwise. We can #include it here as we already // included <stdlib.h>, which is guaranteed to define size_t through // <stddef.h>. # include <regex.h> // NOLINT # define GTEST_USES_POSIX_RE 1 #elif GTEST_OS_WINDOWS // <regex.h> is not available on Windows. Use our own simple regex // implementation instead. # define GTEST_USES_SIMPLE_RE 1 #else // <regex.h> may not be available on this platform. Use our own // simple regex implementation instead. # define GTEST_USES_SIMPLE_RE 1 #endif // GTEST_USES_PCRE #ifndef GTEST_HAS_EXCEPTIONS // The user didn't tell us whether exceptions are enabled, so we need // to figure it out. # if defined(_MSC_VER) || defined(__BORLANDC__) // MSVC's and C++Builder's implementations of the STL use the _HAS_EXCEPTIONS // macro to enable exceptions, so we'll do the same. // Assumes that exceptions are enabled by default. # ifndef _HAS_EXCEPTIONS # define _HAS_EXCEPTIONS 1 # endif // _HAS_EXCEPTIONS # define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS # elif defined(__clang__) // clang defines __EXCEPTIONS iff exceptions are enabled before clang 220714, // but iff cleanups are enabled after that. In Obj-C++ files, there can be // cleanups for ObjC exceptions which also need cleanups, even if C++ exceptions // are disabled. clang has __has_feature(cxx_exceptions) which checks for C++ // exceptions starting at clang r206352, but which checked for cleanups prior to // that. To reliably check for C++ exception availability with clang, check for // __EXCEPTIONS && __has_feature(cxx_exceptions). # define GTEST_HAS_EXCEPTIONS (__EXCEPTIONS && __has_feature(cxx_exceptions)) # elif defined(__GNUC__) && __EXCEPTIONS // gcc defines __EXCEPTIONS to 1 iff exceptions are enabled. # define GTEST_HAS_EXCEPTIONS 1 # elif defined(__SUNPRO_CC) // Sun Pro CC supports exceptions. However, there is no compile-time way of // detecting whether they are enabled or not. Therefore, we assume that // they are enabled unless the user tells us otherwise. # define GTEST_HAS_EXCEPTIONS 1 # elif defined(__IBMCPP__) && __EXCEPTIONS // xlC defines __EXCEPTIONS to 1 iff exceptions are enabled. # define GTEST_HAS_EXCEPTIONS 1 # elif defined(__HP_aCC) // Exception handling is in effect by default in HP aCC compiler. It has to // be turned of by +noeh compiler option if desired. # define GTEST_HAS_EXCEPTIONS 1 # else // For other compilers, we assume exceptions are disabled to be // conservative. # define GTEST_HAS_EXCEPTIONS 0 # endif // defined(_MSC_VER) || defined(__BORLANDC__) #endif // GTEST_HAS_EXCEPTIONS #if !defined(GTEST_HAS_STD_STRING) // Even though we don't use this macro any longer, we keep it in case // some clients still depend on it. # define GTEST_HAS_STD_STRING 1 #elif !GTEST_HAS_STD_STRING // The user told us that ::std::string isn't available. # error "Google Test cannot be used where ::std::string isn't available." #endif // !defined(GTEST_HAS_STD_STRING) #ifndef GTEST_HAS_GLOBAL_STRING // The user didn't tell us whether ::string is available, so we need // to figure it out. # define GTEST_HAS_GLOBAL_STRING 0 #endif // GTEST_HAS_GLOBAL_STRING #ifndef GTEST_HAS_STD_WSTRING // The user didn't tell us whether ::std::wstring is available, so we need // to figure it out. // TODO([email protected]): uses autoconf to detect whether ::std::wstring // is available. // Cygwin 1.7 and below doesn't support ::std::wstring. // Solaris' libc++ doesn't support it either. Android has // no support for it at least as recent as Froyo (2.2). // Minix currently doesn't support it either. # define GTEST_HAS_STD_WSTRING \ (!(GTEST_OS_LINUX_ANDROID || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || GTEST_OS_HAIKU || GTEST_OS_MINIX)) #endif // GTEST_HAS_STD_WSTRING #ifndef GTEST_HAS_GLOBAL_WSTRING // The user didn't tell us whether ::wstring is available, so we need // to figure it out. # define GTEST_HAS_GLOBAL_WSTRING \ (GTEST_HAS_STD_WSTRING && GTEST_HAS_GLOBAL_STRING) #endif // GTEST_HAS_GLOBAL_WSTRING // Determines whether RTTI is available. #ifndef GTEST_HAS_RTTI // The user didn't tell us whether RTTI is enabled, so we need to // figure it out. # ifdef _MSC_VER # ifdef _CPPRTTI // MSVC defines this macro iff RTTI is enabled. # define GTEST_HAS_RTTI 1 # else # define GTEST_HAS_RTTI 0 # endif // Starting with version 4.3.2, gcc defines __GXX_RTTI iff RTTI is enabled. # elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40302) # ifdef __GXX_RTTI // When building against STLport with the Android NDK and with // -frtti -fno-exceptions, the build fails at link time with undefined // references to __cxa_bad_typeid. Note sure if STL or toolchain bug, // so disable RTTI when detected. # if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) && \ !defined(__EXCEPTIONS) # define GTEST_HAS_RTTI 0 # else # define GTEST_HAS_RTTI 1 # endif // GTEST_OS_LINUX_ANDROID && __STLPORT_MAJOR && !__EXCEPTIONS # else # define GTEST_HAS_RTTI 0 # endif // __GXX_RTTI // Clang defines __GXX_RTTI starting with version 3.0, but its manual recommends // using has_feature instead. has_feature(cxx_rtti) is supported since 2.7, the // first version with C++ support. # elif defined(__clang__) # define GTEST_HAS_RTTI __has_feature(cxx_rtti) // Starting with version 9.0 IBM Visual Age defines __RTTI_ALL__ to 1 if // both the typeid and dynamic_cast features are present. # elif defined(__IBMCPP__) && (__IBMCPP__ >= 900) # ifdef __RTTI_ALL__ # define GTEST_HAS_RTTI 1 # else # define GTEST_HAS_RTTI 0 # endif # else // For all other compilers, we assume RTTI is enabled. # define GTEST_HAS_RTTI 1 # endif // _MSC_VER #endif // GTEST_HAS_RTTI // It's this header's responsibility to #include <typeinfo> when RTTI // is enabled. #if GTEST_HAS_RTTI # include <typeinfo> #endif // Determines whether Google Test can use the pthreads library. #ifndef GTEST_HAS_PTHREAD // The user didn't tell us explicitly, so we make reasonable assumptions about // which platforms have pthreads support. // // To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0 // to your compiler flags. # define GTEST_HAS_PTHREAD (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX \ || GTEST_OS_QNX || GTEST_OS_FREEBSD || GTEST_OS_NACL) #endif // GTEST_HAS_PTHREAD #if GTEST_HAS_PTHREAD // gtest-port.h guarantees to #include <pthread.h> when GTEST_HAS_PTHREAD is // true. # include <pthread.h> // NOLINT // For timespec and nanosleep, used below. # include <time.h> // NOLINT #endif // Determines if hash_map/hash_set are available. // Only used for testing against those containers. #if !defined(GTEST_HAS_HASH_MAP_) # if _MSC_VER # define GTEST_HAS_HASH_MAP_ 1 // Indicates that hash_map is available. # define GTEST_HAS_HASH_SET_ 1 // Indicates that hash_set is available. # endif // _MSC_VER #endif // !defined(GTEST_HAS_HASH_MAP_) // Determines whether Google Test can use tr1/tuple. You can define // this macro to 0 to prevent Google Test from using tuple (any // feature depending on tuple with be disabled in this mode). #ifndef GTEST_HAS_TR1_TUPLE # if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) // STLport, provided with the Android NDK, has neither <tr1/tuple> or <tuple>. # define GTEST_HAS_TR1_TUPLE 0 # else // The user didn't tell us not to do it, so we assume it's OK. # define GTEST_HAS_TR1_TUPLE 1 # endif #endif // GTEST_HAS_TR1_TUPLE // Determines whether Google Test's own tr1 tuple implementation // should be used. #ifndef GTEST_USE_OWN_TR1_TUPLE // The user didn't tell us, so we need to figure it out. // We use our own TR1 tuple if we aren't sure the user has an // implementation of it already. At this time, libstdc++ 4.0.0+ and // MSVC 2010 are the only mainstream standard libraries that come // with a TR1 tuple implementation. NVIDIA's CUDA NVCC compiler // pretends to be GCC by defining __GNUC__ and friends, but cannot // compile GCC's tuple implementation. MSVC 2008 (9.0) provides TR1 // tuple in a 323 MB Feature Pack download, which we cannot assume the // user has. QNX's QCC compiler is a modified GCC but it doesn't // support TR1 tuple. libc++ only provides std::tuple, in C++11 mode, // and it can be used with some compilers that define __GNUC__. # if (defined(__GNUC__) && !defined(__CUDACC__) && (GTEST_GCC_VER_ >= 40000) \ && !GTEST_OS_QNX && !defined(_LIBCPP_VERSION)) || _MSC_VER >= 1600 # define GTEST_ENV_HAS_TR1_TUPLE_ 1 # endif // C++11 specifies that <tuple> provides std::tuple. Use that if gtest is used // in C++11 mode and libstdc++ isn't very old (binaries targeting OS X 10.6 // can build with clang but need to use gcc4.2's libstdc++). # if GTEST_LANG_CXX11 && (!defined(__GLIBCXX__) || __GLIBCXX__ > 20110325) # define GTEST_ENV_HAS_STD_TUPLE_ 1 # endif # if GTEST_ENV_HAS_TR1_TUPLE_ || GTEST_ENV_HAS_STD_TUPLE_ # define GTEST_USE_OWN_TR1_TUPLE 0 # else # define GTEST_USE_OWN_TR1_TUPLE 1 # endif #endif // GTEST_USE_OWN_TR1_TUPLE // To avoid conditional compilation everywhere, we make it // gtest-port.h's responsibility to #include the header implementing // tuple. #if GTEST_HAS_STD_TUPLE_ # include <tuple> // IWYU pragma: export # define GTEST_TUPLE_NAMESPACE_ ::std # undef GTEST_HAS_TR1_TUPLE // HLSL Change - For modern VS compat, don't use tr1 #endif // GTEST_HAS_STD_TUPLE_ // We include tr1::tuple even if std::tuple is available to define printers for // them. #if GTEST_HAS_TR1_TUPLE # ifndef GTEST_TUPLE_NAMESPACE_ # define GTEST_TUPLE_NAMESPACE_ ::std::tr1 # endif // GTEST_TUPLE_NAMESPACE_ # if GTEST_USE_OWN_TR1_TUPLE # include "gtest/internal/gtest-tuple.h" // IWYU pragma: export // NOLINT # elif GTEST_ENV_HAS_STD_TUPLE_ # include <tuple> // C++11 puts its tuple into the ::std namespace rather than // ::std::tr1. gtest expects tuple to live in ::std::tr1, so put it there. // This causes undefined behavior, but supported compilers react in // the way we intend. namespace std { namespace tr1 { using ::std::get; using ::std::make_tuple; using ::std::tuple; using ::std::tuple_element; using ::std::tuple_size; } } # elif GTEST_OS_SYMBIAN // On Symbian, BOOST_HAS_TR1_TUPLE causes Boost's TR1 tuple library to // use STLport's tuple implementation, which unfortunately doesn't // work as the copy of STLport distributed with Symbian is incomplete. // By making sure BOOST_HAS_TR1_TUPLE is undefined, we force Boost to // use its own tuple implementation. # ifdef BOOST_HAS_TR1_TUPLE # undef BOOST_HAS_TR1_TUPLE # endif // BOOST_HAS_TR1_TUPLE // This prevents <boost/tr1/detail/config.hpp>, which defines // BOOST_HAS_TR1_TUPLE, from being #included by Boost's <tuple>. # define BOOST_TR1_DETAIL_CONFIG_HPP_INCLUDED # include <tuple> // IWYU pragma: export // NOLINT # elif defined(__GNUC__) && (GTEST_GCC_VER_ >= 40000) // GCC 4.0+ implements tr1/tuple in the <tr1/tuple> header. This does // not conform to the TR1 spec, which requires the header to be <tuple>. # if !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302 // Until version 4.3.2, gcc has a bug that causes <tr1/functional>, // which is #included by <tr1/tuple>, to not compile when RTTI is // disabled. _TR1_FUNCTIONAL is the header guard for // <tr1/functional>. Hence the following #define is a hack to prevent // <tr1/functional> from being included. # define _TR1_FUNCTIONAL 1 # include <tr1/tuple> # undef _TR1_FUNCTIONAL // Allows the user to #include // <tr1/functional> if he chooses to. # else # include <tr1/tuple> // NOLINT # endif // !GTEST_HAS_RTTI && GTEST_GCC_VER_ < 40302 # else // If the compiler is not GCC 4.0+, we assume the user is using a // spec-conforming TR1 implementation. # include <tuple> // IWYU pragma: export // NOLINT # endif // GTEST_USE_OWN_TR1_TUPLE #endif // GTEST_HAS_TR1_TUPLE // Determines whether clone(2) is supported. // Usually it will only be available on Linux, excluding // Linux on the Itanium architecture. // Also see http://linux.die.net/man/2/clone. #ifndef GTEST_HAS_CLONE // The user didn't tell us, so we need to figure it out. # if GTEST_OS_LINUX && !defined(__ia64__) # if GTEST_OS_LINUX_ANDROID // On Android, clone() is only available on ARM starting with Gingerbread. # if defined(__arm__) && __ANDROID_API__ >= 9 # define GTEST_HAS_CLONE 1 # else # define GTEST_HAS_CLONE 0 # endif # else # define GTEST_HAS_CLONE 1 # endif # else # define GTEST_HAS_CLONE 0 # endif // GTEST_OS_LINUX && !defined(__ia64__) #endif // GTEST_HAS_CLONE // Determines whether to support stream redirection. This is used to test // output correctness and to implement death tests. #ifndef GTEST_HAS_STREAM_REDIRECTION // By default, we assume that stream redirection is supported on all // platforms except known mobile ones. # if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || \ GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT # define GTEST_HAS_STREAM_REDIRECTION 0 # else # define GTEST_HAS_STREAM_REDIRECTION 1 # endif // !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_SYMBIAN #endif // GTEST_HAS_STREAM_REDIRECTION // Determines whether to support death tests. // Google Test does not support death tests for VC 7.1 and earlier as // abort() in a VC 7.1 application compiled as GUI in debug config // pops up a dialog window that cannot be suppressed programmatically. #if (GTEST_OS_LINUX || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \ (GTEST_OS_MAC && !GTEST_OS_IOS) || \ (!GTEST_OS_WINDOWS_DESKTOP /*HLSL Change - Disable death on Windows.*/) || \ GTEST_OS_WINDOWS_MINGW || GTEST_OS_AIX || GTEST_OS_HPUX || \ GTEST_OS_OPENBSD || GTEST_OS_QNX || GTEST_OS_FREEBSD) # define GTEST_HAS_DEATH_TEST 1 #endif // We don't support MSVC 7.1 with exceptions disabled now. Therefore // all the compilers we care about are adequate for supporting // value-parameterized tests. #define GTEST_HAS_PARAM_TEST 1 // Determines whether to support type-driven tests. // Typed tests need <typeinfo> and variadic macros, which GCC, VC++ 8.0, // Sun Pro CC, IBM Visual Age, and HP aCC support. #if defined(__GNUC__) || (_MSC_VER >= 1400) || defined(__SUNPRO_CC) || \ defined(__IBMCPP__) || defined(__HP_aCC) # define GTEST_HAS_TYPED_TEST 1 # define GTEST_HAS_TYPED_TEST_P 1 #endif // Determines whether to support Combine(). This only makes sense when // value-parameterized tests are enabled. The implementation doesn't // work on Sun Studio since it doesn't understand templated conversion // operators. #if GTEST_HAS_PARAM_TEST && GTEST_HAS_TR1_TUPLE && !defined(__SUNPRO_CC) # define GTEST_HAS_COMBINE 1 #endif // Determines whether the system compiler uses UTF-16 for encoding wide strings. #define GTEST_WIDE_STRING_USES_UTF16_ \ (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_SYMBIAN || GTEST_OS_AIX) // Determines whether test results can be streamed to a socket. #if GTEST_OS_LINUX # define GTEST_CAN_STREAM_RESULTS_ 1 #endif // Defines some utility macros. // The GNU compiler emits a warning if nested "if" statements are followed by // an "else" statement and braces are not used to explicitly disambiguate the // "else" binding. This leads to problems with code like: // // if (gate) // ASSERT_*(condition) << "Some message"; // // The "switch (0) case 0:" idiom is used to suppress this. #ifdef __INTEL_COMPILER # define GTEST_AMBIGUOUS_ELSE_BLOCKER_ #else # define GTEST_AMBIGUOUS_ELSE_BLOCKER_ switch (0) case 0: default: // NOLINT #endif // Use this annotation at the end of a struct/class definition to // prevent the compiler from optimizing away instances that are never // used. This is useful when all interesting logic happens inside the // c'tor and / or d'tor. Example: // // struct Foo { // Foo() { ... } // } GTEST_ATTRIBUTE_UNUSED_; // // Also use it after a variable or parameter declaration to tell the // compiler the variable/parameter does not have to be used. #if defined(__GNUC__) && !defined(COMPILER_ICC) # define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused)) #elif defined(__clang__) # if __has_attribute(unused) # define GTEST_ATTRIBUTE_UNUSED_ __attribute__ ((unused)) # endif #endif #ifndef GTEST_ATTRIBUTE_UNUSED_ # define GTEST_ATTRIBUTE_UNUSED_ #endif // A macro to disallow operator= // This should be used in the private: declarations for a class. #define GTEST_DISALLOW_ASSIGN_(type)\ void operator=(type const &) // A macro to disallow copy constructor and operator= // This should be used in the private: declarations for a class. #define GTEST_DISALLOW_COPY_AND_ASSIGN_(type)\ type(type const &);\ GTEST_DISALLOW_ASSIGN_(type) // Tell the compiler to warn about unused return values for functions declared // with this macro. The macro should be used on function declarations // following the argument list: // // Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_; #if defined(__GNUC__) && (GTEST_GCC_VER_ >= 30400) && !defined(COMPILER_ICC) # define GTEST_MUST_USE_RESULT_ __attribute__ ((warn_unused_result)) #else # define GTEST_MUST_USE_RESULT_ #endif // __GNUC__ && (GTEST_GCC_VER_ >= 30400) && !COMPILER_ICC // MS C++ compiler emits warning when a conditional expression is compile time // constant. In some contexts this warning is false positive and needs to be // suppressed. Use the following two macros in such cases: // // GTEST_INTENTIONAL_CONST_COND_PUSH_() // while (true) { // GTEST_INTENTIONAL_CONST_COND_POP_() // } # define GTEST_INTENTIONAL_CONST_COND_PUSH_() \ GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127) # define GTEST_INTENTIONAL_CONST_COND_POP_() \ GTEST_DISABLE_MSC_WARNINGS_POP_() // Determine whether the compiler supports Microsoft's Structured Exception // Handling. This is supported by several Windows compilers but generally // does not exist on any other system. #ifndef GTEST_HAS_SEH // The user didn't tell us, so we need to figure it out. # if defined(_MSC_VER) || defined(__BORLANDC__) // These two compilers are known to support SEH. # define GTEST_HAS_SEH 1 # else // Assume no SEH. # define GTEST_HAS_SEH 0 # endif #endif // GTEST_HAS_SEH #define GTEST_IS_THREADSAFE \ (GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ \ || (GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT) \ || GTEST_HAS_PTHREAD) #ifdef _MSC_VER # if GTEST_LINKED_AS_SHARED_LIBRARY # define GTEST_API_ __declspec(dllimport) # elif GTEST_CREATE_SHARED_LIBRARY # define GTEST_API_ __declspec(dllexport) # endif #elif __GNUC__ >= 4 || defined(__clang__) # define GTEST_API_ __attribute__((visibility ("default"))) #endif // _MSC_VER #ifndef GTEST_API_ # define GTEST_API_ #endif #ifdef __GNUC__ // Ask the compiler to never inline a given function. # define GTEST_NO_INLINE_ __attribute__((noinline)) #else # define GTEST_NO_INLINE_ #endif // _LIBCPP_VERSION is defined by the libc++ library from the LLVM project. #if defined(__has_include) # if __has_include(<cxxabi.h>) # define GTEST_HAS_CXXABI_H_ 1 # else # define GTEST_HAS_CXXABI_H_ 0 # endif #elif defined(__GLIBCXX__) || defined(_LIBCPP_VERSION) # define GTEST_HAS_CXXABI_H_ 1 #else # define GTEST_HAS_CXXABI_H_ 0 #endif // A function level attribute to disable checking for use of uninitialized // memory when built with MemorySanitizer. #if defined(__clang__) # if __has_feature(memory_sanitizer) # define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ \ __attribute__((no_sanitize_memory)) # else # define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ # endif // __has_feature(memory_sanitizer) #else # define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ #endif // __clang__ // A function level attribute to disable AddressSanitizer instrumentation. #if defined(__clang__) # if __has_feature(address_sanitizer) # define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ \ __attribute__((no_sanitize_address)) # else # define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ # endif // __has_feature(address_sanitizer) #else # define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ #endif // __clang__ // A function level attribute to disable ThreadSanitizer instrumentation. #if defined(__clang__) # if __has_feature(thread_sanitizer) # define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ \ __attribute__((no_sanitize_thread)) # else # define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ # endif // __has_feature(thread_sanitizer) #else # define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ #endif // __clang__ namespace testing { class Message; #if defined(GTEST_TUPLE_NAMESPACE_) // Import tuple and friends into the ::testing namespace. // It is part of our interface, having them in ::testing allows us to change // their types as needed. using GTEST_TUPLE_NAMESPACE_::get; using GTEST_TUPLE_NAMESPACE_::make_tuple; using GTEST_TUPLE_NAMESPACE_::tuple; using GTEST_TUPLE_NAMESPACE_::tuple_size; using GTEST_TUPLE_NAMESPACE_::tuple_element; #endif // defined(GTEST_TUPLE_NAMESPACE_) namespace internal { // A secret type that Google Test users don't know about. It has no // definition on purpose. Therefore it's impossible to create a // Secret object, which is what we want. class Secret; // The GTEST_COMPILE_ASSERT_ macro can be used to verify that a compile time // expression is true. For example, you could use it to verify the // size of a static array: // // GTEST_COMPILE_ASSERT_(GTEST_ARRAY_SIZE_(names) == NUM_NAMES, // names_incorrect_size); // // or to make sure a struct is smaller than a certain size: // // GTEST_COMPILE_ASSERT_(sizeof(foo) < 128, foo_too_large); // // The second argument to the macro is the name of the variable. If // the expression is false, most compilers will issue a warning/error // containing the name of the variable. #if GTEST_LANG_CXX11 # define GTEST_COMPILE_ASSERT_(expr, msg) static_assert(expr, #msg) #else // !GTEST_LANG_CXX11 template <bool> struct CompileAssert { }; # define GTEST_COMPILE_ASSERT_(expr, msg) \ typedef ::testing::internal::CompileAssert<(static_cast<bool>(expr))> \ msg[static_cast<bool>(expr) ? 1 : -1] GTEST_ATTRIBUTE_UNUSED_ #endif // !GTEST_LANG_CXX11 // Implementation details of GTEST_COMPILE_ASSERT_: // // (In C++11, we simply use static_assert instead of the following) // // - GTEST_COMPILE_ASSERT_ works by defining an array type that has -1 // elements (and thus is invalid) when the expression is false. // // - The simpler definition // // #define GTEST_COMPILE_ASSERT_(expr, msg) typedef char msg[(expr) ? 1 : -1] // // does not work, as gcc supports variable-length arrays whose sizes // are determined at run-time (this is gcc's extension and not part // of the C++ standard). As a result, gcc fails to reject the // following code with the simple definition: // // int foo; // GTEST_COMPILE_ASSERT_(foo, msg); // not supposed to compile as foo is // // not a compile-time constant. // // - By using the type CompileAssert<(bool(expr))>, we ensures that // expr is a compile-time constant. (Template arguments must be // determined at compile-time.) // // - The outter parentheses in CompileAssert<(bool(expr))> are necessary // to work around a bug in gcc 3.4.4 and 4.0.1. If we had written // // CompileAssert<bool(expr)> // // instead, these compilers will refuse to compile // // GTEST_COMPILE_ASSERT_(5 > 0, some_message); // // (They seem to think the ">" in "5 > 0" marks the end of the // template argument list.) // // - The array size is (bool(expr) ? 1 : -1), instead of simply // // ((expr) ? 1 : -1). // // This is to avoid running into a bug in MS VC 7.1, which // causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1. // StaticAssertTypeEqHelper is used by StaticAssertTypeEq defined in gtest.h. // // This template is declared, but intentionally undefined. template <typename T1, typename T2> struct StaticAssertTypeEqHelper; template <typename T> struct StaticAssertTypeEqHelper<T, T> { enum { value = true }; }; // Evaluates to the number of elements in 'array'. #define GTEST_ARRAY_SIZE_(array) (sizeof(array) / sizeof(array[0])) #if GTEST_HAS_GLOBAL_STRING typedef ::string string; #else typedef ::std::string string; #endif // GTEST_HAS_GLOBAL_STRING #if GTEST_HAS_GLOBAL_WSTRING typedef ::wstring wstring; #elif GTEST_HAS_STD_WSTRING typedef ::std::wstring wstring; #endif // GTEST_HAS_GLOBAL_WSTRING // A helper for suppressing warnings on constant condition. It just // returns 'condition'. GTEST_API_ bool IsTrue(bool condition); // Defines scoped_ptr. // This implementation of scoped_ptr is PARTIAL - it only contains // enough stuff to satisfy Google Test's need. template <typename T> class scoped_ptr { public: typedef T element_type; explicit scoped_ptr(T* p = NULL) : ptr_(p) {} ~scoped_ptr() { reset(); } T& operator*() const { return *ptr_; } T* operator->() const { return ptr_; } T* get() const { return ptr_; } T* release() { T* const ptr = ptr_; ptr_ = NULL; return ptr; } void reset(T* p = NULL) { if (p != ptr_) { if (IsTrue(sizeof(T) > 0)) { // Makes sure T is a complete type. delete ptr_; } ptr_ = p; } } friend void swap(scoped_ptr& a, scoped_ptr& b) { using std::swap; swap(a.ptr_, b.ptr_); } private: T* ptr_; GTEST_DISALLOW_COPY_AND_ASSIGN_(scoped_ptr); }; // Defines RE. // A simple C++ wrapper for <regex.h>. It uses the POSIX Extended // Regular Expression syntax. class GTEST_API_ RE { public: // A copy constructor is required by the Standard to initialize object // references from r-values. RE(const RE& other) { Init(other.pattern()); } // Constructs an RE from a string. RE(const ::std::string& regex) { Init(regex.c_str()); } // NOLINT #if GTEST_HAS_GLOBAL_STRING RE(const ::string& regex) { Init(regex.c_str()); } // NOLINT #endif // GTEST_HAS_GLOBAL_STRING RE(const char* regex) { Init(regex); } // NOLINT ~RE(); // Returns the string representation of the regex. const char* pattern() const { return pattern_; } // FullMatch(str, re) returns true iff regular expression re matches // the entire str. // PartialMatch(str, re) returns true iff regular expression re // matches a substring of str (including str itself). // // TODO([email protected]): make FullMatch() and PartialMatch() work // when str contains NUL characters. static bool FullMatch(const ::std::string& str, const RE& re) { return FullMatch(str.c_str(), re); } static bool PartialMatch(const ::std::string& str, const RE& re) { return PartialMatch(str.c_str(), re); } #if GTEST_HAS_GLOBAL_STRING static bool FullMatch(const ::string& str, const RE& re) { return FullMatch(str.c_str(), re); } static bool PartialMatch(const ::string& str, const RE& re) { return PartialMatch(str.c_str(), re); } #endif // GTEST_HAS_GLOBAL_STRING static bool FullMatch(const char* str, const RE& re); static bool PartialMatch(const char* str, const RE& re); private: void Init(const char* regex); // We use a const char* instead of an std::string, as Google Test used to be // used where std::string is not available. TODO([email protected]): change to // std::string. const char* pattern_; bool is_valid_; #if GTEST_USES_POSIX_RE regex_t full_regex_; // For FullMatch(). regex_t partial_regex_; // For PartialMatch(). #else // GTEST_USES_SIMPLE_RE const char* full_pattern_; // For FullMatch(); #endif GTEST_DISALLOW_ASSIGN_(RE); }; // Formats a source file path and a line number as they would appear // in an error message from the compiler used to compile this code. GTEST_API_ ::std::string FormatFileLocation(const char* file, int line); // Formats a file location for compiler-independent XML output. // Although this function is not platform dependent, we put it next to // FormatFileLocation in order to contrast the two functions. GTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file, int line); // Defines logging utilities: // GTEST_LOG_(severity) - logs messages at the specified severity level. The // message itself is streamed into the macro. // LogToStderr() - directs all log messages to stderr. // FlushInfoLog() - flushes informational log messages. enum GTestLogSeverity { GTEST_INFO, GTEST_WARNING, GTEST_ERROR, GTEST_FATAL }; // Formats log entry severity, provides a stream object for streaming the // log message, and terminates the message with a newline when going out of // scope. class GTEST_API_ GTestLog { public: GTestLog(GTestLogSeverity severity, const char* file, int line); // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program. ~GTestLog(); ::std::ostream& GetStream() { return ::std::cerr; } private: const GTestLogSeverity severity_; GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestLog); }; #if !defined(GTEST_LOG_) # define GTEST_LOG_(severity) \ ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \ __FILE__, __LINE__).GetStream() inline void LogToStderr() {} inline void FlushInfoLog() { fflush(NULL); } #endif // !defined(GTEST_LOG_) #if !defined(GTEST_CHECK_) // INTERNAL IMPLEMENTATION - DO NOT USE. // // GTEST_CHECK_ is an all-mode assert. It aborts the program if the condition // is not satisfied. // Synopsys: // GTEST_CHECK_(boolean_condition); // or // GTEST_CHECK_(boolean_condition) << "Additional message"; // // This checks the condition and if the condition is not satisfied // it prints message about the condition violation, including the // condition itself, plus additional message streamed into it, if any, // and then it aborts the program. It aborts the program irrespective of // whether it is built in the debug mode or not. # define GTEST_CHECK_(condition) \ GTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if (::testing::internal::IsTrue(condition)) \ ; \ else \ GTEST_LOG_(FATAL) << "Condition " #condition " failed. " #endif // !defined(GTEST_CHECK_) // An all-mode assert to verify that the given POSIX-style function // call returns 0 (indicating success). Known limitation: this // doesn't expand to a balanced 'if' statement, so enclose the macro // in {} if you need to use it as the only statement in an 'if' // branch. #define GTEST_CHECK_POSIX_SUCCESS_(posix_call) \ if (const int gtest_error = (posix_call)) \ GTEST_LOG_(FATAL) << #posix_call << "failed with error " \ << gtest_error #if GTEST_HAS_STD_MOVE_ using std::move; #else // GTEST_HAS_STD_MOVE_ template <typename T> const T& move(const T& t) { return t; } #endif // GTEST_HAS_STD_MOVE_ // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Use ImplicitCast_ as a safe version of static_cast for upcasting in // the type hierarchy (e.g. casting a Foo* to a SuperclassOfFoo* or a // const Foo*). When you use ImplicitCast_, the compiler checks that // the cast is safe. Such explicit ImplicitCast_s are necessary in // surprisingly many situations where C++ demands an exact type match // instead of an argument type convertable to a target type. // // The syntax for using ImplicitCast_ is the same as for static_cast: // // ImplicitCast_<ToType>(expr) // // ImplicitCast_ would have been part of the C++ standard library, // but the proposal was submitted too late. It will probably make // its way into the language in the future. // // This relatively ugly name is intentional. It prevents clashes with // similar functions users may have (e.g., implicit_cast). The internal // namespace alone is not enough because the function can be found by ADL. template<typename To> inline To ImplicitCast_(To x) { return x; } // When you upcast (that is, cast a pointer from type Foo to type // SuperclassOfFoo), it's fine to use ImplicitCast_<>, since upcasts // always succeed. When you downcast (that is, cast a pointer from // type Foo to type SubclassOfFoo), static_cast<> isn't safe, because // how do you know the pointer is really of type SubclassOfFoo? It // could be a bare Foo, or of type DifferentSubclassOfFoo. Thus, // when you downcast, you should use this macro. In debug mode, we // use dynamic_cast<> to double-check the downcast is legal (we die // if it's not). In normal mode, we do the efficient static_cast<> // instead. Thus, it's important to test in debug mode to make sure // the cast is legal! // This is the only place in the code we should use dynamic_cast<>. // In particular, you SHOULDN'T be using dynamic_cast<> in order to // do RTTI (eg code like this: // if (dynamic_cast<Subclass1>(foo)) HandleASubclass1Object(foo); // if (dynamic_cast<Subclass2>(foo)) HandleASubclass2Object(foo); // You should design the code some other way not to need this. // // This relatively ugly name is intentional. It prevents clashes with // similar functions users may have (e.g., down_cast). The internal // namespace alone is not enough because the function can be found by ADL. template<typename To, typename From> // use like this: DownCast_<T*>(foo); inline To DownCast_(From* f) { // so we only accept pointers // Ensures that To is a sub-type of From *. This test is here only // for compile-time type checking, and has no overhead in an // optimized build at run-time, as it will be optimized away // completely. GTEST_INTENTIONAL_CONST_COND_PUSH_() if (false) { GTEST_INTENTIONAL_CONST_COND_POP_() const To to = NULL; ::testing::internal::ImplicitCast_<From*>(to); } #if GTEST_HAS_RTTI // RTTI: debug mode only! GTEST_CHECK_(f == NULL || dynamic_cast<To>(f) != NULL); #endif return static_cast<To>(f); } // Downcasts the pointer of type Base to Derived. // Derived must be a subclass of Base. The parameter MUST // point to a class of type Derived, not any subclass of it. // When RTTI is available, the function performs a runtime // check to enforce this. template <class Derived, class Base> Derived* CheckedDowncastToActualType(Base* base) { #if GTEST_HAS_RTTI GTEST_CHECK_(typeid(*base) == typeid(Derived)); #endif #if GTEST_HAS_DOWNCAST_ return ::down_cast<Derived*>(base); #elif GTEST_HAS_RTTI return dynamic_cast<Derived*>(base); // NOLINT #else return static_cast<Derived*>(base); // Poor man's downcast. #endif } #if GTEST_HAS_STREAM_REDIRECTION // Defines the stderr capturer: // CaptureStdout - starts capturing stdout. // GetCapturedStdout - stops capturing stdout and returns the captured string. // CaptureStderr - starts capturing stderr. // GetCapturedStderr - stops capturing stderr and returns the captured string. // GTEST_API_ void CaptureStdout(); GTEST_API_ std::string GetCapturedStdout(); GTEST_API_ void CaptureStderr(); GTEST_API_ std::string GetCapturedStderr(); #endif // GTEST_HAS_STREAM_REDIRECTION // Returns a path to temporary directory. GTEST_API_ std::string TempDir(); // Returns the size (in bytes) of a file. GTEST_API_ size_t GetFileSize(FILE* file); // Reads the entire content of a file as a string. GTEST_API_ std::string ReadEntireFile(FILE* file); // All command line arguments. GTEST_API_ const ::std::vector<testing::internal::string>& GetArgvs(); #if GTEST_HAS_DEATH_TEST const ::std::vector<testing::internal::string>& GetInjectableArgvs(); void SetInjectableArgvs(const ::std::vector<testing::internal::string>* new_argvs); #endif // GTEST_HAS_DEATH_TEST // Defines synchronization primitives. #if GTEST_IS_THREADSAFE # if GTEST_HAS_PTHREAD // Sleeps for (roughly) n milliseconds. This function is only for testing // Google Test's own constructs. Don't use it in user tests, either // directly or indirectly. inline void SleepMilliseconds(int n) { const timespec time = { 0, // 0 seconds. n * 1000L * 1000L, // And n ms. }; nanosleep(&time, NULL); } # endif // GTEST_HAS_PTHREAD # if GTEST_HAS_NOTIFICATION_ // Notification has already been imported into the namespace. // Nothing to do here. # elif GTEST_HAS_PTHREAD // Allows a controller thread to pause execution of newly created // threads until notified. Instances of this class must be created // and destroyed in the controller thread. // // This class is only for testing Google Test's own constructs. Do not // use it in user tests, either directly or indirectly. class Notification { public: Notification() : notified_(false) { GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL)); } ~Notification() { pthread_mutex_destroy(&mutex_); } // Notifies all threads created with this notification to start. Must // be called from the controller thread. void Notify() { pthread_mutex_lock(&mutex_); notified_ = true; pthread_mutex_unlock(&mutex_); } // Blocks until the controller thread notifies. Must be called from a test // thread. void WaitForNotification() { for (;;) { pthread_mutex_lock(&mutex_); const bool notified = notified_; pthread_mutex_unlock(&mutex_); if (notified) break; SleepMilliseconds(10); } } private: pthread_mutex_t mutex_; bool notified_; GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification); }; # elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT GTEST_API_ void SleepMilliseconds(int n); // Provides leak-safe Windows kernel handle ownership. // Used in death tests and in threading support. class GTEST_API_ AutoHandle { public: // Assume that Win32 HANDLE type is equivalent to void*. Doing so allows us to // avoid including <windows.h> in this header file. Including <windows.h> is // undesirable because it defines a lot of symbols and macros that tend to // conflict with client code. This assumption is verified by // WindowsTypesTest.HANDLEIsVoidStar. typedef void* Handle; AutoHandle(); explicit AutoHandle(Handle handle); ~AutoHandle(); Handle Get() const; void Reset(); void Reset(Handle handle); private: // Returns true iff the handle is a valid handle object that can be closed. bool IsCloseable() const; Handle handle_; GTEST_DISALLOW_COPY_AND_ASSIGN_(AutoHandle); }; // Allows a controller thread to pause execution of newly created // threads until notified. Instances of this class must be created // and destroyed in the controller thread. // // This class is only for testing Google Test's own constructs. Do not // use it in user tests, either directly or indirectly. class GTEST_API_ Notification { public: Notification(); void Notify(); void WaitForNotification(); private: AutoHandle event_; GTEST_DISALLOW_COPY_AND_ASSIGN_(Notification); }; # endif // GTEST_HAS_NOTIFICATION_ // On MinGW, we can have both GTEST_OS_WINDOWS and GTEST_HAS_PTHREAD // defined, but we don't want to use MinGW's pthreads implementation, which // has conformance problems with some versions of the POSIX standard. # if GTEST_HAS_PTHREAD && !GTEST_OS_WINDOWS_MINGW // As a C-function, ThreadFuncWithCLinkage cannot be templated itself. // Consequently, it cannot select a correct instantiation of ThreadWithParam // in order to call its Run(). Introducing ThreadWithParamBase as a // non-templated base class for ThreadWithParam allows us to bypass this // problem. class ThreadWithParamBase { public: virtual ~ThreadWithParamBase() {} virtual void Run() = 0; }; // pthread_create() accepts a pointer to a function type with the C linkage. // According to the Standard (7.5/1), function types with different linkages // are different even if they are otherwise identical. Some compilers (for // example, SunStudio) treat them as different types. Since class methods // cannot be defined with C-linkage we need to define a free C-function to // pass into pthread_create(). extern "C" inline void* ThreadFuncWithCLinkage(void* thread) { static_cast<ThreadWithParamBase*>(thread)->Run(); return NULL; } // Helper class for testing Google Test's multi-threading constructs. // To use it, write: // // void ThreadFunc(int param) { /* Do things with param */ } // Notification thread_can_start; // ... // // The thread_can_start parameter is optional; you can supply NULL. // ThreadWithParam<int> thread(&ThreadFunc, 5, &thread_can_start); // thread_can_start.Notify(); // // These classes are only for testing Google Test's own constructs. Do // not use them in user tests, either directly or indirectly. template <typename T> class ThreadWithParam : public ThreadWithParamBase { public: typedef void UserThreadFunc(T); ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start) : func_(func), param_(param), thread_can_start_(thread_can_start), finished_(false) { ThreadWithParamBase* const base = this; // The thread can be created only after all fields except thread_ // have been initialized. GTEST_CHECK_POSIX_SUCCESS_( pthread_create(&thread_, 0, &ThreadFuncWithCLinkage, base)); } ~ThreadWithParam() { Join(); } void Join() { if (!finished_) { GTEST_CHECK_POSIX_SUCCESS_(pthread_join(thread_, 0)); finished_ = true; } } virtual void Run() { if (thread_can_start_ != NULL) thread_can_start_->WaitForNotification(); func_(param_); } private: UserThreadFunc* const func_; // User-supplied thread function. const T param_; // User-supplied parameter to the thread function. // When non-NULL, used to block execution until the controller thread // notifies. Notification* const thread_can_start_; bool finished_; // true iff we know that the thread function has finished. pthread_t thread_; // The native thread object. GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam); }; # endif // !GTEST_OS_WINDOWS && GTEST_HAS_PTHREAD || // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ # if GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ // Mutex and ThreadLocal have already been imported into the namespace. // Nothing to do here. # elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT // Mutex implements mutex on Windows platforms. It is used in conjunction // with class MutexLock: // // Mutex mutex; // ... // MutexLock lock(&mutex); // Acquires the mutex and releases it at the // // end of the current scope. // // A static Mutex *must* be defined or declared using one of the following // macros: // GTEST_DEFINE_STATIC_MUTEX_(g_some_mutex); // GTEST_DECLARE_STATIC_MUTEX_(g_some_mutex); // // (A non-static Mutex is defined/declared in the usual way). class GTEST_API_ Mutex { public: enum MutexType { kStatic = 0, kDynamic = 1 }; // We rely on kStaticMutex being 0 as it is to what the linker initializes // type_ in static mutexes. critical_section_ will be initialized lazily // in ThreadSafeLazyInit(). enum StaticConstructorSelector { kStaticMutex = 0 }; // This constructor intentionally does nothing. It relies on type_ being // statically initialized to 0 (effectively setting it to kStatic) and on // ThreadSafeLazyInit() to lazily initialize the rest of the members. explicit Mutex(StaticConstructorSelector /*dummy*/) {} Mutex(); ~Mutex(); void Lock(); void Unlock(); // Does nothing if the current thread holds the mutex. Otherwise, crashes // with high probability. void AssertHeld(); private: // Initializes owner_thread_id_ and critical_section_ in static mutexes. void ThreadSafeLazyInit(); // Per http://blogs.msdn.com/b/oldnewthing/archive/2004/02/23/78395.aspx, // we assume that 0 is an invalid value for thread IDs. unsigned int owner_thread_id_; // For static mutexes, we rely on these members being initialized to zeros // by the linker. MutexType type_; long critical_section_init_phase_; // NOLINT _RTL_CRITICAL_SECTION* critical_section_; GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex); }; # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ extern ::testing::internal::Mutex mutex # define GTEST_DEFINE_STATIC_MUTEX_(mutex) \ ::testing::internal::Mutex mutex(::testing::internal::Mutex::kStaticMutex) // We cannot name this class MutexLock because the ctor declaration would // conflict with a macro named MutexLock, which is defined on some // platforms. That macro is used as a defensive measure to prevent against // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than // "MutexLock l(&mu)". Hence the typedef trick below. class GTestMutexLock { public: explicit GTestMutexLock(Mutex* mutex) : mutex_(mutex) { mutex_->Lock(); } ~GTestMutexLock() { mutex_->Unlock(); } private: Mutex* const mutex_; GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock); }; typedef GTestMutexLock MutexLock; // Base class for ValueHolder<T>. Allows a caller to hold and delete a value // without knowing its type. class ThreadLocalValueHolderBase { public: virtual ~ThreadLocalValueHolderBase() {} }; // Provides a way for a thread to send notifications to a ThreadLocal // regardless of its parameter type. class ThreadLocalBase { public: // Creates a new ValueHolder<T> object holding a default value passed to // this ThreadLocal<T>'s constructor and returns it. It is the caller's // responsibility not to call this when the ThreadLocal<T> instance already // has a value on the current thread. virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const = 0; protected: ThreadLocalBase() {} virtual ~ThreadLocalBase() {} private: GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocalBase); }; // Maps a thread to a set of ThreadLocals that have values instantiated on that // thread and notifies them when the thread exits. A ThreadLocal instance is // expected to persist until all threads it has values on have terminated. class GTEST_API_ ThreadLocalRegistry { public: // Registers thread_local_instance as having value on the current thread. // Returns a value that can be used to identify the thread from other threads. static ThreadLocalValueHolderBase* GetValueOnCurrentThread( const ThreadLocalBase* thread_local_instance); // Invoked when a ThreadLocal instance is destroyed. static void OnThreadLocalDestroyed( const ThreadLocalBase* thread_local_instance); }; class GTEST_API_ ThreadWithParamBase { public: void Join(); protected: class Runnable { public: virtual ~Runnable() {} virtual void Run() = 0; }; ThreadWithParamBase(Runnable *runnable, Notification* thread_can_start); virtual ~ThreadWithParamBase(); private: AutoHandle thread_; }; // Helper class for testing Google Test's multi-threading constructs. template <typename T> class ThreadWithParam : public ThreadWithParamBase { public: typedef void UserThreadFunc(T); ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start) : ThreadWithParamBase(new RunnableImpl(func, param), thread_can_start) { } virtual ~ThreadWithParam() {} private: class RunnableImpl : public Runnable { public: RunnableImpl(UserThreadFunc* func, T param) : func_(func), param_(param) { } virtual ~RunnableImpl() {} virtual void Run() { func_(param_); } private: UserThreadFunc* const func_; const T param_; GTEST_DISALLOW_COPY_AND_ASSIGN_(RunnableImpl); }; GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParam); }; // Implements thread-local storage on Windows systems. // // // Thread 1 // ThreadLocal<int> tl(100); // 100 is the default value for each thread. // // // Thread 2 // tl.set(150); // Changes the value for thread 2 only. // EXPECT_EQ(150, tl.get()); // // // Thread 1 // EXPECT_EQ(100, tl.get()); // In thread 1, tl has the original value. // tl.set(200); // EXPECT_EQ(200, tl.get()); // // The template type argument T must have a public copy constructor. // In addition, the default ThreadLocal constructor requires T to have // a public default constructor. // // The users of a TheadLocal instance have to make sure that all but one // threads (including the main one) using that instance have exited before // destroying it. Otherwise, the per-thread objects managed for them by the // ThreadLocal instance are not guaranteed to be destroyed on all platforms. // // Google Test only uses global ThreadLocal objects. That means they // will die after main() has returned. Therefore, no per-thread // object managed by Google Test will be leaked as long as all threads // using Google Test have exited when main() returns. template <typename T> class ThreadLocal : public ThreadLocalBase { public: ThreadLocal() : default_factory_(new DefaultValueHolderFactory()) {} explicit ThreadLocal(const T& value) : default_factory_(new InstanceValueHolderFactory(value)) {} ~ThreadLocal() { ThreadLocalRegistry::OnThreadLocalDestroyed(this); } T* pointer() { return GetOrCreateValue(); } const T* pointer() const { return GetOrCreateValue(); } const T& get() const { return *pointer(); } void set(const T& value) { *pointer() = value; } private: // Holds a value of T. Can be deleted via its base class without the caller // knowing the type of T. class ValueHolder : public ThreadLocalValueHolderBase { public: ValueHolder() : value_() {} explicit ValueHolder(const T& value) : value_(value) {} T* pointer() { return &value_; } private: T value_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder); }; T* GetOrCreateValue() const { return static_cast<ValueHolder*>( ThreadLocalRegistry::GetValueOnCurrentThread(this))->pointer(); } virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const { return default_factory_->MakeNewHolder(); } class ValueHolderFactory { public: ValueHolderFactory() {} virtual ~ValueHolderFactory() {} virtual ValueHolder* MakeNewHolder() const = 0; private: GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory); }; class DefaultValueHolderFactory : public ValueHolderFactory { public: DefaultValueHolderFactory() {} virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(); } private: GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory); }; class InstanceValueHolderFactory : public ValueHolderFactory { public: explicit InstanceValueHolderFactory(const T& value) : value_(value) {} virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(value_); } private: const T value_; // The value for each thread. GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory); }; scoped_ptr<ValueHolderFactory> default_factory_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal); }; # elif GTEST_HAS_PTHREAD // MutexBase and Mutex implement mutex on pthreads-based platforms. class MutexBase { public: // Acquires this mutex. void Lock() { GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&mutex_)); owner_ = pthread_self(); has_owner_ = true; } // Releases this mutex. void Unlock() { // Since the lock is being released the owner_ field should no longer be // considered valid. We don't protect writing to has_owner_ here, as it's // the caller's responsibility to ensure that the current thread holds the // mutex when this is called. has_owner_ = false; GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&mutex_)); } // Does nothing if the current thread holds the mutex. Otherwise, crashes // with high probability. void AssertHeld() const { GTEST_CHECK_(has_owner_ && pthread_equal(owner_, pthread_self())) << "The current thread is not holding the mutex @" << this; } // A static mutex may be used before main() is entered. It may even // be used before the dynamic initialization stage. Therefore we // must be able to initialize a static mutex object at link time. // This means MutexBase has to be a POD and its member variables // have to be public. public: pthread_mutex_t mutex_; // The underlying pthread mutex. // has_owner_ indicates whether the owner_ field below contains a valid thread // ID and is therefore safe to inspect (e.g., to use in pthread_equal()). All // accesses to the owner_ field should be protected by a check of this field. // An alternative might be to memset() owner_ to all zeros, but there's no // guarantee that a zero'd pthread_t is necessarily invalid or even different // from pthread_self(). bool has_owner_; pthread_t owner_; // The thread holding the mutex. }; // Forward-declares a static mutex. # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ extern ::testing::internal::MutexBase mutex // Defines and statically (i.e. at link time) initializes a static mutex. # define GTEST_DEFINE_STATIC_MUTEX_(mutex) \ ::testing::internal::MutexBase mutex = { PTHREAD_MUTEX_INITIALIZER, false, pthread_t() } // The Mutex class can only be used for mutexes created at runtime. It // shares its API with MutexBase otherwise. class Mutex : public MutexBase { public: Mutex() { GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, NULL)); has_owner_ = false; } ~Mutex() { GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_)); } private: GTEST_DISALLOW_COPY_AND_ASSIGN_(Mutex); }; // We cannot name this class MutexLock because the ctor declaration would // conflict with a macro named MutexLock, which is defined on some // platforms. That macro is used as a defensive measure to prevent against // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than // "MutexLock l(&mu)". Hence the typedef trick below. class GTestMutexLock { public: explicit GTestMutexLock(MutexBase* mutex) : mutex_(mutex) { mutex_->Lock(); } ~GTestMutexLock() { mutex_->Unlock(); } private: MutexBase* const mutex_; GTEST_DISALLOW_COPY_AND_ASSIGN_(GTestMutexLock); }; typedef GTestMutexLock MutexLock; // Helpers for ThreadLocal. // pthread_key_create() requires DeleteThreadLocalValue() to have // C-linkage. Therefore it cannot be templatized to access // ThreadLocal<T>. Hence the need for class // ThreadLocalValueHolderBase. class ThreadLocalValueHolderBase { public: virtual ~ThreadLocalValueHolderBase() {} }; // Called by pthread to delete thread-local data stored by // pthread_setspecific(). extern "C" inline void DeleteThreadLocalValue(void* value_holder) { delete static_cast<ThreadLocalValueHolderBase*>(value_holder); } // Implements thread-local storage on pthreads-based systems. template <typename T> class ThreadLocal { public: ThreadLocal() : key_(CreateKey()), default_factory_(new DefaultValueHolderFactory()) {} explicit ThreadLocal(const T& value) : key_(CreateKey()), default_factory_(new InstanceValueHolderFactory(value)) {} ~ThreadLocal() { // Destroys the managed object for the current thread, if any. DeleteThreadLocalValue(pthread_getspecific(key_)); // Releases resources associated with the key. This will *not* // delete managed objects for other threads. GTEST_CHECK_POSIX_SUCCESS_(pthread_key_delete(key_)); } T* pointer() { return GetOrCreateValue(); } const T* pointer() const { return GetOrCreateValue(); } const T& get() const { return *pointer(); } void set(const T& value) { *pointer() = value; } private: // Holds a value of type T. class ValueHolder : public ThreadLocalValueHolderBase { public: ValueHolder() : value_() {} explicit ValueHolder(const T& value) : value_(value) {} T* pointer() { return &value_; } private: T value_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolder); }; static pthread_key_t CreateKey() { pthread_key_t key; // When a thread exits, DeleteThreadLocalValue() will be called on // the object managed for that thread. GTEST_CHECK_POSIX_SUCCESS_( pthread_key_create(&key, &DeleteThreadLocalValue)); return key; } T* GetOrCreateValue() const { ThreadLocalValueHolderBase* const holder = static_cast<ThreadLocalValueHolderBase*>(pthread_getspecific(key_)); if (holder != NULL) { return CheckedDowncastToActualType<ValueHolder>(holder)->pointer(); } ValueHolder* const new_holder = default_factory_->MakeNewHolder(); ThreadLocalValueHolderBase* const holder_base = new_holder; GTEST_CHECK_POSIX_SUCCESS_(pthread_setspecific(key_, holder_base)); return new_holder->pointer(); } class ValueHolderFactory { public: ValueHolderFactory() {} virtual ~ValueHolderFactory() {} virtual ValueHolder* MakeNewHolder() const = 0; private: GTEST_DISALLOW_COPY_AND_ASSIGN_(ValueHolderFactory); }; class DefaultValueHolderFactory : public ValueHolderFactory { public: DefaultValueHolderFactory() {} virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(); } private: GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultValueHolderFactory); }; class InstanceValueHolderFactory : public ValueHolderFactory { public: explicit InstanceValueHolderFactory(const T& value) : value_(value) {} virtual ValueHolder* MakeNewHolder() const { return new ValueHolder(value_); } private: const T value_; // The value for each thread. GTEST_DISALLOW_COPY_AND_ASSIGN_(InstanceValueHolderFactory); }; // A key pthreads uses for looking up per-thread values. const pthread_key_t key_; scoped_ptr<ValueHolderFactory> default_factory_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadLocal); }; # endif // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ #else // GTEST_IS_THREADSAFE // A dummy implementation of synchronization primitives (mutex, lock, // and thread-local variable). Necessary for compiling Google Test where // mutex is not supported - using Google Test in multiple threads is not // supported on such platforms. class Mutex { public: Mutex() {} void Lock() {} void Unlock() {} void AssertHeld() const {} }; # define GTEST_DECLARE_STATIC_MUTEX_(mutex) \ extern ::testing::internal::Mutex mutex # define GTEST_DEFINE_STATIC_MUTEX_(mutex) ::testing::internal::Mutex mutex // We cannot name this class MutexLock because the ctor declaration would // conflict with a macro named MutexLock, which is defined on some // platforms. That macro is used as a defensive measure to prevent against // inadvertent misuses of MutexLock like "MutexLock(&mu)" rather than // "MutexLock l(&mu)". Hence the typedef trick below. class GTestMutexLock { public: explicit GTestMutexLock(Mutex*) {} // NOLINT }; typedef GTestMutexLock MutexLock; template <typename T> class ThreadLocal { public: ThreadLocal() : value_() {} explicit ThreadLocal(const T& value) : value_(value) {} T* pointer() { return &value_; } const T* pointer() const { return &value_; } const T& get() const { return value_; } void set(const T& value) { value_ = value; } private: T value_; }; #endif // GTEST_IS_THREADSAFE // Returns the number of threads running in the process, or 0 to indicate that // we cannot detect it. GTEST_API_ size_t GetThreadCount(); // Passing non-POD classes through ellipsis (...) crashes the ARM // compiler and generates a warning in Sun Studio. The Nokia Symbian // and the IBM XL C/C++ compiler try to instantiate a copy constructor // for objects passed through ellipsis (...), failing for uncopyable // objects. We define this to ensure that only POD is passed through // ellipsis on these systems. #if defined(__SYMBIAN32__) || defined(__IBMCPP__) || defined(__SUNPRO_CC) // We lose support for NULL detection where the compiler doesn't like // passing non-POD classes through ellipsis (...). # define GTEST_ELLIPSIS_NEEDS_POD_ 1 #else # define GTEST_CAN_COMPARE_NULL 1 #endif // The Nokia Symbian and IBM XL C/C++ compilers cannot decide between // const T& and const T* in a function template. These compilers // _can_ decide between class template specializations for T and T*, // so a tr1::type_traits-like is_pointer works. #if defined(__SYMBIAN32__) || defined(__IBMCPP__) # define GTEST_NEEDS_IS_POINTER_ 1 #endif template <bool bool_value> struct bool_constant { typedef bool_constant<bool_value> type; static const bool value = bool_value; }; template <bool bool_value> const bool bool_constant<bool_value>::value; typedef bool_constant<false> false_type; typedef bool_constant<true> true_type; template <typename T> struct is_pointer : public false_type {}; template <typename T> struct is_pointer<T*> : public true_type {}; template <typename Iterator> struct IteratorTraits { typedef typename Iterator::value_type value_type; }; template <typename T> struct IteratorTraits<T*> { typedef T value_type; }; template <typename T> struct IteratorTraits<const T*> { typedef T value_type; }; #if GTEST_OS_WINDOWS # define GTEST_PATH_SEP_ "\\" # define GTEST_HAS_ALT_PATH_SEP_ 1 // The biggest signed integer type the compiler supports. typedef __int64 BiggestInt; #else # define GTEST_PATH_SEP_ "/" # define GTEST_HAS_ALT_PATH_SEP_ 0 typedef long long BiggestInt; // NOLINT #endif // GTEST_OS_WINDOWS // Utilities for char. // isspace(int ch) and friends accept an unsigned char or EOF. char // may be signed, depending on the compiler (or compiler flags). // Therefore we need to cast a char to unsigned char before calling // isspace(), etc. inline bool IsAlpha(char ch) { return isalpha(static_cast<unsigned char>(ch)) != 0; } inline bool IsAlNum(char ch) { return isalnum(static_cast<unsigned char>(ch)) != 0; } inline bool IsDigit(char ch) { return isdigit(static_cast<unsigned char>(ch)) != 0; } inline bool IsLower(char ch) { return islower(static_cast<unsigned char>(ch)) != 0; } inline bool IsSpace(char ch) { return isspace(static_cast<unsigned char>(ch)) != 0; } inline bool IsUpper(char ch) { return isupper(static_cast<unsigned char>(ch)) != 0; } inline bool IsXDigit(char ch) { return isxdigit(static_cast<unsigned char>(ch)) != 0; } inline bool IsXDigit(wchar_t ch) { const unsigned char low_byte = static_cast<unsigned char>(ch); return ch == low_byte && isxdigit(low_byte) != 0; } inline char ToLower(char ch) { return static_cast<char>(tolower(static_cast<unsigned char>(ch))); } inline char ToUpper(char ch) { return static_cast<char>(toupper(static_cast<unsigned char>(ch))); } inline std::string StripTrailingSpaces(std::string str) { std::string::iterator it = str.end(); while (it != str.begin() && IsSpace(*--it)) it = str.erase(it); return str; } // The testing::internal::posix namespace holds wrappers for common // POSIX functions. These wrappers hide the differences between // Windows/MSVC and POSIX systems. Since some compilers define these // standard functions as macros, the wrapper cannot have the same name // as the wrapped function. namespace posix { // Functions with a different name on Windows. #if GTEST_OS_WINDOWS typedef struct _stat StatStruct; # ifdef __BORLANDC__ inline int IsATTY(int fd) { return isatty(fd); } inline int StrCaseCmp(const char* s1, const char* s2) { return stricmp(s1, s2); } inline char* StrDup(const char* src) { return strdup(src); } # else // !__BORLANDC__ # if GTEST_OS_WINDOWS_MOBILE inline int IsATTY(int /* fd */) { return 0; } # else inline int IsATTY(int fd) { return _isatty(fd); } # endif // GTEST_OS_WINDOWS_MOBILE inline int StrCaseCmp(const char* s1, const char* s2) { return _stricmp(s1, s2); } inline char* StrDup(const char* src) { return _strdup(src); } # endif // __BORLANDC__ # if GTEST_OS_WINDOWS_MOBILE inline int FileNo(FILE* file) { return reinterpret_cast<int>(_fileno(file)); } // Stat(), RmDir(), and IsDir() are not needed on Windows CE at this // time and thus not defined there. # else inline int FileNo(FILE* file) { return _fileno(file); } inline int Stat(const char* path, StatStruct* buf) { return _stat(path, buf); } inline int RmDir(const char* dir) { return _rmdir(dir); } inline bool IsDir(const StatStruct& st) { return (_S_IFDIR & st.st_mode) != 0; } # endif // GTEST_OS_WINDOWS_MOBILE #else typedef struct stat StatStruct; inline int FileNo(FILE* file) { return fileno(file); } inline int IsATTY(int fd) { return isatty(fd); } inline int Stat(const char* path, StatStruct* buf) { return stat(path, buf); } inline int StrCaseCmp(const char* s1, const char* s2) { return strcasecmp(s1, s2); } inline char* StrDup(const char* src) { return strdup(src); } inline int RmDir(const char* dir) { return rmdir(dir); } inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); } #endif // GTEST_OS_WINDOWS // Functions deprecated by MSVC 8.0. GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* deprecated function */) inline const char* StrNCpy(char* dest, const char* src, size_t n) { return strncpy(dest, src, n); } // ChDir(), FReopen(), FDOpen(), Read(), Write(), Close(), and // StrError() aren't needed on Windows CE at this time and thus not // defined there. #if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT inline int ChDir(const char* dir) { return chdir(dir); } #endif inline FILE* FOpen(const char* path, const char* mode) { return fopen(path, mode); } #if !GTEST_OS_WINDOWS_MOBILE inline FILE *FReopen(const char* path, const char* mode, FILE* stream) { return freopen(path, mode, stream); } inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); } #endif inline int FClose(FILE* fp) { return fclose(fp); } #if !GTEST_OS_WINDOWS_MOBILE inline int Read(int fd, void* buf, unsigned int count) { return static_cast<int>(read(fd, buf, count)); } inline int Write(int fd, const void* buf, unsigned int count) { return static_cast<int>(write(fd, buf, count)); } inline int Close(int fd) { return close(fd); } inline const char* StrError(int errnum) { return strerror(errnum); } #endif inline const char* GetEnv(const char* name) { #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE | GTEST_OS_WINDOWS_RT // We are on Windows CE, which has no environment variables. static_cast<void>(name); // To prevent 'unused argument' warning. return NULL; #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9) // Environment variables which we programmatically clear will be set to the // empty string rather than unset (NULL). Handle that case. const char* const env = getenv(name); return (env != NULL && env[0] != '\0') ? env : NULL; #else return getenv(name); #endif } GTEST_DISABLE_MSC_WARNINGS_POP_() #if GTEST_OS_WINDOWS_MOBILE // Windows CE has no C library. The abort() function is used in // several places in Google Test. This implementation provides a reasonable // imitation of standard behaviour. void Abort(); #else inline void Abort() { abort(); } #endif // GTEST_OS_WINDOWS_MOBILE } // namespace posix // MSVC "deprecates" snprintf and issues warnings wherever it is used. In // order to avoid these warnings, we need to use _snprintf or _snprintf_s on // MSVC-based platforms. We map the GTEST_SNPRINTF_ macro to the appropriate // function in order to achieve that. We use macro definition here because // snprintf is a variadic function. #if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE // MSVC 2005 and above support variadic macros. # define GTEST_SNPRINTF_(buffer, size, format, ...) \ _snprintf_s(buffer, size, size, format, __VA_ARGS__) #elif defined(_MSC_VER) // Windows CE does not define _snprintf_s and MSVC prior to 2005 doesn't // complain about _snprintf. # define GTEST_SNPRINTF_ _snprintf #else # define GTEST_SNPRINTF_ snprintf #endif // The maximum number a BiggestInt can represent. This definition // works no matter BiggestInt is represented in one's complement or // two's complement. // // We cannot rely on numeric_limits in STL, as __int64 and long long // are not part of standard C++ and numeric_limits doesn't need to be // defined for them. const BiggestInt kMaxBiggestInt = ~(static_cast<BiggestInt>(1) << (8*sizeof(BiggestInt) - 1)); // This template class serves as a compile-time function from size to // type. It maps a size in bytes to a primitive type with that // size. e.g. // // TypeWithSize<4>::UInt // // is typedef-ed to be unsigned int (unsigned integer made up of 4 // bytes). // // Such functionality should belong to STL, but I cannot find it // there. // // Google Test uses this class in the implementation of floating-point // comparison. // // For now it only handles UInt (unsigned int) as that's all Google Test // needs. Other types can be easily added in the future if need // arises. template <size_t size> class TypeWithSize { public: // This prevents the user from using TypeWithSize<N> with incorrect // values of N. typedef void UInt; }; // The specialization for size 4. template <> class TypeWithSize<4> { public: // unsigned int has size 4 in both gcc and MSVC. // // As base/basictypes.h doesn't compile on Windows, we cannot use // uint32, uint64, and etc here. typedef int Int; typedef unsigned int UInt; }; // The specialization for size 8. template <> class TypeWithSize<8> { public: #if GTEST_OS_WINDOWS typedef __int64 Int; typedef unsigned __int64 UInt; #else typedef long long Int; // NOLINT typedef unsigned long long UInt; // NOLINT #endif // GTEST_OS_WINDOWS }; // Integer types of known sizes. typedef TypeWithSize<4>::Int Int32; typedef TypeWithSize<4>::UInt UInt32; typedef TypeWithSize<8>::Int Int64; typedef TypeWithSize<8>::UInt UInt64; typedef TypeWithSize<8>::Int TimeInMillis; // Represents time in milliseconds. // Utilities for command line flags and environment variables. // Macro for referencing flags. #if !defined(GTEST_FLAG) # define GTEST_FLAG(name) FLAGS_gtest_##name #endif // !defined(GTEST_FLAG) #if !defined(GTEST_USE_OWN_FLAGFILE_FLAG_) # define GTEST_USE_OWN_FLAGFILE_FLAG_ 1 #endif // !defined(GTEST_USE_OWN_FLAGFILE_FLAG_) #if !defined(GTEST_DECLARE_bool_) # define GTEST_FLAG_SAVER_ ::testing::internal::GTestFlagSaver // Macros for declaring flags. # define GTEST_DECLARE_bool_(name) GTEST_API_ extern bool GTEST_FLAG(name) # define GTEST_DECLARE_int32_(name) \ GTEST_API_ extern ::testing::internal::Int32 GTEST_FLAG(name) #define GTEST_DECLARE_string_(name) \ GTEST_API_ extern ::std::string GTEST_FLAG(name) // Macros for defining flags. #define GTEST_DEFINE_bool_(name, default_val, doc) \ GTEST_API_ bool GTEST_FLAG(name) = (default_val) #define GTEST_DEFINE_int32_(name, default_val, doc) \ GTEST_API_ ::testing::internal::Int32 GTEST_FLAG(name) = (default_val) #define GTEST_DEFINE_string_(name, default_val, doc) \ GTEST_API_ ::std::string GTEST_FLAG(name) = (default_val) #endif // !defined(GTEST_DECLARE_bool_) // Thread annotations #if !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_) # define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks) # define GTEST_LOCK_EXCLUDED_(locks) #endif // !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_) // Parses 'str' for a 32-bit signed integer. If successful, writes the result // to *value and returns true; otherwise leaves *value unchanged and returns // false. // TODO(chandlerc): Find a better way to refactor flag and environment parsing // out of both gtest-port.cc and gtest.cc to avoid exporting this utility // function. bool ParseInt32(const Message& src_text, const char* str, Int32* value); // Parses a bool/Int32/string from the environment variable // corresponding to the given Google Test flag. bool BoolFromGTestEnv(const char* flag, bool default_val); GTEST_API_ Int32 Int32FromGTestEnv(const char* flag, Int32 default_val); std::string StringFromGTestEnv(const char* flag, const char* default_val); } // namespace internal } // namespace testing #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_
0
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest/internal/gtest-type-util.h
// This file was GENERATED by command: // pump.py gtest-type-util.h.pump // DO NOT EDIT BY HAND!!! // 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. // // Author: [email protected] (Zhanyong Wan) // Type utilities needed for implementing typed and type-parameterized // tests. This file is generated by a SCRIPT. DO NOT EDIT BY HAND! // // Currently we support at most 50 types in a list, and at most 50 // type-parameterized tests in one type-parameterized test case. // Please contact [email protected] if you need // more. #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_ #include "gtest/internal/gtest-port.h" // #ifdef __GNUC__ is too general here. It is possible to use gcc without using // libstdc++ (which is where cxxabi.h comes from). # if GTEST_HAS_CXXABI_H_ # include <cxxabi.h> # elif defined(__HP_aCC) # include <acxx_demangle.h> # endif // GTEST_HASH_CXXABI_H_ namespace testing { namespace internal { // GetTypeName<T>() returns a human-readable name of type T. // NB: This function is also used in Google Mock, so don't move it inside of // the typed-test-only section below. template <typename T> std::string GetTypeName() { # if GTEST_HAS_RTTI const char* const name = typeid(T).name(); # if GTEST_HAS_CXXABI_H_ || defined(__HP_aCC) int status = 0; // gcc's implementation of typeid(T).name() mangles the type name, // so we have to demangle it. # if GTEST_HAS_CXXABI_H_ using abi::__cxa_demangle; # endif // GTEST_HAS_CXXABI_H_ char* const readable_name = __cxa_demangle(name, 0, 0, &status); const std::string name_str(status == 0 ? readable_name : name); free(readable_name); return name_str; # else return name; # endif // GTEST_HAS_CXXABI_H_ || __HP_aCC # else return "<type>"; # endif // GTEST_HAS_RTTI } #if GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P // AssertyTypeEq<T1, T2>::type is defined iff T1 and T2 are the same // type. This can be used as a compile-time assertion to ensure that // two types are equal. template <typename T1, typename T2> struct AssertTypeEq; template <typename T> struct AssertTypeEq<T, T> { typedef bool type; }; // A unique type used as the default value for the arguments of class // template Types. This allows us to simulate variadic templates // (e.g. Types<int>, Type<int, double>, and etc), which C++ doesn't // support directly. struct None {}; // The following family of struct and struct templates are used to // represent type lists. In particular, TypesN<T1, T2, ..., TN> // represents a type list with N types (T1, T2, ..., and TN) in it. // Except for Types0, every struct in the family has two member types: // Head for the first type in the list, and Tail for the rest of the // list. // The empty type list. struct Types0 {}; // Type lists of length 1, 2, 3, and so on. template <typename T1> struct Types1 { typedef T1 Head; typedef Types0 Tail; }; template <typename T1, typename T2> struct Types2 { typedef T1 Head; typedef Types1<T2> Tail; }; template <typename T1, typename T2, typename T3> struct Types3 { typedef T1 Head; typedef Types2<T2, T3> Tail; }; template <typename T1, typename T2, typename T3, typename T4> struct Types4 { typedef T1 Head; typedef Types3<T2, T3, T4> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5> struct Types5 { typedef T1 Head; typedef Types4<T2, T3, T4, T5> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6> struct Types6 { typedef T1 Head; typedef Types5<T2, T3, T4, T5, T6> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7> struct Types7 { typedef T1 Head; typedef Types6<T2, T3, T4, T5, T6, T7> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8> struct Types8 { typedef T1 Head; typedef Types7<T2, T3, T4, T5, T6, T7, T8> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9> struct Types9 { typedef T1 Head; typedef Types8<T2, T3, T4, T5, T6, T7, T8, T9> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10> struct Types10 { typedef T1 Head; typedef Types9<T2, T3, T4, T5, T6, T7, T8, T9, T10> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11> struct Types11 { typedef T1 Head; typedef Types10<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12> struct Types12 { typedef T1 Head; typedef Types11<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13> struct Types13 { typedef T1 Head; typedef Types12<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14> struct Types14 { typedef T1 Head; typedef Types13<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15> struct Types15 { typedef T1 Head; typedef Types14<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16> struct Types16 { typedef T1 Head; typedef Types15<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17> struct Types17 { typedef T1 Head; typedef Types16<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18> struct Types18 { typedef T1 Head; typedef Types17<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19> struct Types19 { typedef T1 Head; typedef Types18<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20> struct Types20 { typedef T1 Head; typedef Types19<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21> struct Types21 { typedef T1 Head; typedef Types20<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22> struct Types22 { typedef T1 Head; typedef Types21<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23> struct Types23 { typedef T1 Head; typedef Types22<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24> struct Types24 { typedef T1 Head; typedef Types23<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25> struct Types25 { typedef T1 Head; typedef Types24<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26> struct Types26 { typedef T1 Head; typedef Types25<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27> struct Types27 { typedef T1 Head; typedef Types26<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28> struct Types28 { typedef T1 Head; typedef Types27<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29> struct Types29 { typedef T1 Head; typedef Types28<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30> struct Types30 { typedef T1 Head; typedef Types29<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31> struct Types31 { typedef T1 Head; typedef Types30<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32> struct Types32 { typedef T1 Head; typedef Types31<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33> struct Types33 { typedef T1 Head; typedef Types32<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34> struct Types34 { typedef T1 Head; typedef Types33<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35> struct Types35 { typedef T1 Head; typedef Types34<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36> struct Types36 { typedef T1 Head; typedef Types35<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37> struct Types37 { typedef T1 Head; typedef Types36<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38> struct Types38 { typedef T1 Head; typedef Types37<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39> struct Types39 { typedef T1 Head; typedef Types38<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40> struct Types40 { typedef T1 Head; typedef Types39<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41> struct Types41 { typedef T1 Head; typedef Types40<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42> struct Types42 { typedef T1 Head; typedef Types41<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43> struct Types43 { typedef T1 Head; typedef Types42<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43, typename T44> struct Types44 { typedef T1 Head; typedef Types43<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43, typename T44, typename T45> struct Types45 { typedef T1 Head; typedef Types44<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43, typename T44, typename T45, typename T46> struct Types46 { typedef T1 Head; typedef Types45<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43, typename T44, typename T45, typename T46, typename T47> struct Types47 { typedef T1 Head; typedef Types46<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, T47> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43, typename T44, typename T45, typename T46, typename T47, typename T48> struct Types48 { typedef T1 Head; typedef Types47<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, T47, T48> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43, typename T44, typename T45, typename T46, typename T47, typename T48, typename T49> struct Types49 { typedef T1 Head; typedef Types48<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, T47, T48, T49> Tail; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43, typename T44, typename T45, typename T46, typename T47, typename T48, typename T49, typename T50> struct Types50 { typedef T1 Head; typedef Types49<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, T47, T48, T49, T50> Tail; }; } // namespace internal // We don't want to require the users to write TypesN<...> directly, // as that would require them to count the length. Types<...> is much // easier to write, but generates horrible messages when there is a // compiler error, as gcc insists on printing out each template // argument, even if it has the default value (this means Types<int> // will appear as Types<int, None, None, ..., None> in the compiler // errors). // // Our solution is to combine the best part of the two approaches: a // user would write Types<T1, ..., TN>, and Google Test will translate // that to TypesN<T1, ..., TN> internally to make error messages // readable. The translation is done by the 'type' member of the // Types template. template <typename T1 = internal::None, typename T2 = internal::None, typename T3 = internal::None, typename T4 = internal::None, typename T5 = internal::None, typename T6 = internal::None, typename T7 = internal::None, typename T8 = internal::None, typename T9 = internal::None, typename T10 = internal::None, typename T11 = internal::None, typename T12 = internal::None, typename T13 = internal::None, typename T14 = internal::None, typename T15 = internal::None, typename T16 = internal::None, typename T17 = internal::None, typename T18 = internal::None, typename T19 = internal::None, typename T20 = internal::None, typename T21 = internal::None, typename T22 = internal::None, typename T23 = internal::None, typename T24 = internal::None, typename T25 = internal::None, typename T26 = internal::None, typename T27 = internal::None, typename T28 = internal::None, typename T29 = internal::None, typename T30 = internal::None, typename T31 = internal::None, typename T32 = internal::None, typename T33 = internal::None, typename T34 = internal::None, typename T35 = internal::None, typename T36 = internal::None, typename T37 = internal::None, typename T38 = internal::None, typename T39 = internal::None, typename T40 = internal::None, typename T41 = internal::None, typename T42 = internal::None, typename T43 = internal::None, typename T44 = internal::None, typename T45 = internal::None, typename T46 = internal::None, typename T47 = internal::None, typename T48 = internal::None, typename T49 = internal::None, typename T50 = internal::None> struct Types { typedef internal::Types50<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, T47, T48, T49, T50> type; }; template <> struct Types<internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types0 type; }; template <typename T1> struct Types<T1, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types1<T1> type; }; template <typename T1, typename T2> struct Types<T1, T2, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types2<T1, T2> type; }; template <typename T1, typename T2, typename T3> struct Types<T1, T2, T3, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types3<T1, T2, T3> type; }; template <typename T1, typename T2, typename T3, typename T4> struct Types<T1, T2, T3, T4, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types4<T1, T2, T3, T4> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5> struct Types<T1, T2, T3, T4, T5, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types5<T1, T2, T3, T4, T5> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6> struct Types<T1, T2, T3, T4, T5, T6, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types6<T1, T2, T3, T4, T5, T6> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7> struct Types<T1, T2, T3, T4, T5, T6, T7, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types7<T1, T2, T3, T4, T5, T6, T7> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types8<T1, T2, T3, T4, T5, T6, T7, T8> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types9<T1, T2, T3, T4, T5, T6, T7, T8, T9> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types10<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types11<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types13<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types14<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types15<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types16<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types17<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types18<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types19<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types20<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types22<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types23<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types24<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types25<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types26<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types27<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types28<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types29<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types30<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types31<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types32<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types33<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types34<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types35<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types36<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types37<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types38<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types39<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types40<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types41<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types42<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types43<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43, typename T44> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, internal::None, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types44<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43, typename T44, typename T45> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, internal::None, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types45<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43, typename T44, typename T45, typename T46> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, internal::None, internal::None, internal::None, internal::None> { typedef internal::Types46<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43, typename T44, typename T45, typename T46, typename T47> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, T47, internal::None, internal::None, internal::None> { typedef internal::Types47<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, T47> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43, typename T44, typename T45, typename T46, typename T47, typename T48> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, T47, T48, internal::None, internal::None> { typedef internal::Types48<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, T47, T48> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43, typename T44, typename T45, typename T46, typename T47, typename T48, typename T49> struct Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, T47, T48, T49, internal::None> { typedef internal::Types49<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, T47, T48, T49> type; }; namespace internal { # define GTEST_TEMPLATE_ template <typename T> class // The template "selector" struct TemplateSel<Tmpl> is used to // represent Tmpl, which must be a class template with one type // parameter, as a type. TemplateSel<Tmpl>::Bind<T>::type is defined // as the type Tmpl<T>. This allows us to actually instantiate the // template "selected" by TemplateSel<Tmpl>. // // This trick is necessary for simulating typedef for class templates, // which C++ doesn't support directly. template <GTEST_TEMPLATE_ Tmpl> struct TemplateSel { template <typename T> struct Bind { typedef Tmpl<T> type; }; }; # define GTEST_BIND_(TmplSel, T) \ TmplSel::template Bind<T>::type // A unique struct template used as the default value for the // arguments of class template Templates. This allows us to simulate // variadic templates (e.g. Templates<int>, Templates<int, double>, // and etc), which C++ doesn't support directly. template <typename T> struct NoneT {}; // The following family of struct and struct templates are used to // represent template lists. In particular, TemplatesN<T1, T2, ..., // TN> represents a list of N templates (T1, T2, ..., and TN). Except // for Templates0, every struct in the family has two member types: // Head for the selector of the first template in the list, and Tail // for the rest of the list. // The empty template list. struct Templates0 {}; // Template lists of length 1, 2, 3, and so on. template <GTEST_TEMPLATE_ T1> struct Templates1 { typedef TemplateSel<T1> Head; typedef Templates0 Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2> struct Templates2 { typedef TemplateSel<T1> Head; typedef Templates1<T2> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3> struct Templates3 { typedef TemplateSel<T1> Head; typedef Templates2<T2, T3> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4> struct Templates4 { typedef TemplateSel<T1> Head; typedef Templates3<T2, T3, T4> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5> struct Templates5 { typedef TemplateSel<T1> Head; typedef Templates4<T2, T3, T4, T5> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6> struct Templates6 { typedef TemplateSel<T1> Head; typedef Templates5<T2, T3, T4, T5, T6> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7> struct Templates7 { typedef TemplateSel<T1> Head; typedef Templates6<T2, T3, T4, T5, T6, T7> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8> struct Templates8 { typedef TemplateSel<T1> Head; typedef Templates7<T2, T3, T4, T5, T6, T7, T8> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9> struct Templates9 { typedef TemplateSel<T1> Head; typedef Templates8<T2, T3, T4, T5, T6, T7, T8, T9> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10> struct Templates10 { typedef TemplateSel<T1> Head; typedef Templates9<T2, T3, T4, T5, T6, T7, T8, T9, T10> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11> struct Templates11 { typedef TemplateSel<T1> Head; typedef Templates10<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12> struct Templates12 { typedef TemplateSel<T1> Head; typedef Templates11<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13> struct Templates13 { typedef TemplateSel<T1> Head; typedef Templates12<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14> struct Templates14 { typedef TemplateSel<T1> Head; typedef Templates13<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15> struct Templates15 { typedef TemplateSel<T1> Head; typedef Templates14<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16> struct Templates16 { typedef TemplateSel<T1> Head; typedef Templates15<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17> struct Templates17 { typedef TemplateSel<T1> Head; typedef Templates16<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18> struct Templates18 { typedef TemplateSel<T1> Head; typedef Templates17<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19> struct Templates19 { typedef TemplateSel<T1> Head; typedef Templates18<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20> struct Templates20 { typedef TemplateSel<T1> Head; typedef Templates19<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21> struct Templates21 { typedef TemplateSel<T1> Head; typedef Templates20<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22> struct Templates22 { typedef TemplateSel<T1> Head; typedef Templates21<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23> struct Templates23 { typedef TemplateSel<T1> Head; typedef Templates22<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24> struct Templates24 { typedef TemplateSel<T1> Head; typedef Templates23<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25> struct Templates25 { typedef TemplateSel<T1> Head; typedef Templates24<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26> struct Templates26 { typedef TemplateSel<T1> Head; typedef Templates25<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27> struct Templates27 { typedef TemplateSel<T1> Head; typedef Templates26<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28> struct Templates28 { typedef TemplateSel<T1> Head; typedef Templates27<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29> struct Templates29 { typedef TemplateSel<T1> Head; typedef Templates28<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30> struct Templates30 { typedef TemplateSel<T1> Head; typedef Templates29<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31> struct Templates31 { typedef TemplateSel<T1> Head; typedef Templates30<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32> struct Templates32 { typedef TemplateSel<T1> Head; typedef Templates31<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33> struct Templates33 { typedef TemplateSel<T1> Head; typedef Templates32<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33, GTEST_TEMPLATE_ T34> struct Templates34 { typedef TemplateSel<T1> Head; typedef Templates33<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33, GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35> struct Templates35 { typedef TemplateSel<T1> Head; typedef Templates34<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33, GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36> struct Templates36 { typedef TemplateSel<T1> Head; typedef Templates35<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33, GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36, GTEST_TEMPLATE_ T37> struct Templates37 { typedef TemplateSel<T1> Head; typedef Templates36<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33, GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36, GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38> struct Templates38 { typedef TemplateSel<T1> Head; typedef Templates37<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33, GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36, GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39> struct Templates39 { typedef TemplateSel<T1> Head; typedef Templates38<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33, GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36, GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39, GTEST_TEMPLATE_ T40> struct Templates40 { typedef TemplateSel<T1> Head; typedef Templates39<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33, GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36, GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39, GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41> struct Templates41 { typedef TemplateSel<T1> Head; typedef Templates40<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33, GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36, GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39, GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42> struct Templates42 { typedef TemplateSel<T1> Head; typedef Templates41<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33, GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36, GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39, GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42, GTEST_TEMPLATE_ T43> struct Templates43 { typedef TemplateSel<T1> Head; typedef Templates42<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33, GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36, GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39, GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42, GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44> struct Templates44 { typedef TemplateSel<T1> Head; typedef Templates43<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33, GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36, GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39, GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42, GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44, GTEST_TEMPLATE_ T45> struct Templates45 { typedef TemplateSel<T1> Head; typedef Templates44<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33, GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36, GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39, GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42, GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44, GTEST_TEMPLATE_ T45, GTEST_TEMPLATE_ T46> struct Templates46 { typedef TemplateSel<T1> Head; typedef Templates45<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33, GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36, GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39, GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42, GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44, GTEST_TEMPLATE_ T45, GTEST_TEMPLATE_ T46, GTEST_TEMPLATE_ T47> struct Templates47 { typedef TemplateSel<T1> Head; typedef Templates46<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, T47> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33, GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36, GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39, GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42, GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44, GTEST_TEMPLATE_ T45, GTEST_TEMPLATE_ T46, GTEST_TEMPLATE_ T47, GTEST_TEMPLATE_ T48> struct Templates48 { typedef TemplateSel<T1> Head; typedef Templates47<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, T47, T48> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33, GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36, GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39, GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42, GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44, GTEST_TEMPLATE_ T45, GTEST_TEMPLATE_ T46, GTEST_TEMPLATE_ T47, GTEST_TEMPLATE_ T48, GTEST_TEMPLATE_ T49> struct Templates49 { typedef TemplateSel<T1> Head; typedef Templates48<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, T47, T48, T49> Tail; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33, GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36, GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39, GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42, GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44, GTEST_TEMPLATE_ T45, GTEST_TEMPLATE_ T46, GTEST_TEMPLATE_ T47, GTEST_TEMPLATE_ T48, GTEST_TEMPLATE_ T49, GTEST_TEMPLATE_ T50> struct Templates50 { typedef TemplateSel<T1> Head; typedef Templates49<T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, T47, T48, T49, T50> Tail; }; // We don't want to require the users to write TemplatesN<...> directly, // as that would require them to count the length. Templates<...> is much // easier to write, but generates horrible messages when there is a // compiler error, as gcc insists on printing out each template // argument, even if it has the default value (this means Templates<list> // will appear as Templates<list, NoneT, NoneT, ..., NoneT> in the compiler // errors). // // Our solution is to combine the best part of the two approaches: a // user would write Templates<T1, ..., TN>, and Google Test will translate // that to TemplatesN<T1, ..., TN> internally to make error messages // readable. The translation is done by the 'type' member of the // Templates template. template <GTEST_TEMPLATE_ T1 = NoneT, GTEST_TEMPLATE_ T2 = NoneT, GTEST_TEMPLATE_ T3 = NoneT, GTEST_TEMPLATE_ T4 = NoneT, GTEST_TEMPLATE_ T5 = NoneT, GTEST_TEMPLATE_ T6 = NoneT, GTEST_TEMPLATE_ T7 = NoneT, GTEST_TEMPLATE_ T8 = NoneT, GTEST_TEMPLATE_ T9 = NoneT, GTEST_TEMPLATE_ T10 = NoneT, GTEST_TEMPLATE_ T11 = NoneT, GTEST_TEMPLATE_ T12 = NoneT, GTEST_TEMPLATE_ T13 = NoneT, GTEST_TEMPLATE_ T14 = NoneT, GTEST_TEMPLATE_ T15 = NoneT, GTEST_TEMPLATE_ T16 = NoneT, GTEST_TEMPLATE_ T17 = NoneT, GTEST_TEMPLATE_ T18 = NoneT, GTEST_TEMPLATE_ T19 = NoneT, GTEST_TEMPLATE_ T20 = NoneT, GTEST_TEMPLATE_ T21 = NoneT, GTEST_TEMPLATE_ T22 = NoneT, GTEST_TEMPLATE_ T23 = NoneT, GTEST_TEMPLATE_ T24 = NoneT, GTEST_TEMPLATE_ T25 = NoneT, GTEST_TEMPLATE_ T26 = NoneT, GTEST_TEMPLATE_ T27 = NoneT, GTEST_TEMPLATE_ T28 = NoneT, GTEST_TEMPLATE_ T29 = NoneT, GTEST_TEMPLATE_ T30 = NoneT, GTEST_TEMPLATE_ T31 = NoneT, GTEST_TEMPLATE_ T32 = NoneT, GTEST_TEMPLATE_ T33 = NoneT, GTEST_TEMPLATE_ T34 = NoneT, GTEST_TEMPLATE_ T35 = NoneT, GTEST_TEMPLATE_ T36 = NoneT, GTEST_TEMPLATE_ T37 = NoneT, GTEST_TEMPLATE_ T38 = NoneT, GTEST_TEMPLATE_ T39 = NoneT, GTEST_TEMPLATE_ T40 = NoneT, GTEST_TEMPLATE_ T41 = NoneT, GTEST_TEMPLATE_ T42 = NoneT, GTEST_TEMPLATE_ T43 = NoneT, GTEST_TEMPLATE_ T44 = NoneT, GTEST_TEMPLATE_ T45 = NoneT, GTEST_TEMPLATE_ T46 = NoneT, GTEST_TEMPLATE_ T47 = NoneT, GTEST_TEMPLATE_ T48 = NoneT, GTEST_TEMPLATE_ T49 = NoneT, GTEST_TEMPLATE_ T50 = NoneT> struct Templates { typedef Templates50<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, T47, T48, T49, T50> type; }; template <> struct Templates<NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates0 type; }; template <GTEST_TEMPLATE_ T1> struct Templates<T1, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates1<T1> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2> struct Templates<T1, T2, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates2<T1, T2> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3> struct Templates<T1, T2, T3, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates3<T1, T2, T3> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4> struct Templates<T1, T2, T3, T4, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates4<T1, T2, T3, T4> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5> struct Templates<T1, T2, T3, T4, T5, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates5<T1, T2, T3, T4, T5> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6> struct Templates<T1, T2, T3, T4, T5, T6, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates6<T1, T2, T3, T4, T5, T6> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7> struct Templates<T1, T2, T3, T4, T5, T6, T7, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates7<T1, T2, T3, T4, T5, T6, T7> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates8<T1, T2, T3, T4, T5, T6, T7, T8> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates9<T1, T2, T3, T4, T5, T6, T7, T8, T9> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates10<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates11<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates12<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates13<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates14<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates15<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates16<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates17<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates18<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates19<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates20<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates21<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates22<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates23<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates24<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates25<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates26<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates27<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates28<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates29<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates30<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates31<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates32<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates33<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33, GTEST_TEMPLATE_ T34> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates34<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33, GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates35<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33, GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates36<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33, GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36, GTEST_TEMPLATE_ T37> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates37<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33, GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36, GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates38<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33, GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36, GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates39<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33, GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36, GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39, GTEST_TEMPLATE_ T40> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates40<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33, GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36, GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39, GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates41<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33, GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36, GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39, GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates42<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33, GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36, GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39, GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42, GTEST_TEMPLATE_ T43> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates43<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33, GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36, GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39, GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42, GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, NoneT, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates44<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33, GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36, GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39, GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42, GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44, GTEST_TEMPLATE_ T45> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, NoneT, NoneT, NoneT, NoneT, NoneT> { typedef Templates45<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33, GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36, GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39, GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42, GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44, GTEST_TEMPLATE_ T45, GTEST_TEMPLATE_ T46> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, NoneT, NoneT, NoneT, NoneT> { typedef Templates46<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33, GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36, GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39, GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42, GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44, GTEST_TEMPLATE_ T45, GTEST_TEMPLATE_ T46, GTEST_TEMPLATE_ T47> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, T47, NoneT, NoneT, NoneT> { typedef Templates47<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, T47> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33, GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36, GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39, GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42, GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44, GTEST_TEMPLATE_ T45, GTEST_TEMPLATE_ T46, GTEST_TEMPLATE_ T47, GTEST_TEMPLATE_ T48> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, T47, T48, NoneT, NoneT> { typedef Templates48<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, T47, T48> type; }; template <GTEST_TEMPLATE_ T1, GTEST_TEMPLATE_ T2, GTEST_TEMPLATE_ T3, GTEST_TEMPLATE_ T4, GTEST_TEMPLATE_ T5, GTEST_TEMPLATE_ T6, GTEST_TEMPLATE_ T7, GTEST_TEMPLATE_ T8, GTEST_TEMPLATE_ T9, GTEST_TEMPLATE_ T10, GTEST_TEMPLATE_ T11, GTEST_TEMPLATE_ T12, GTEST_TEMPLATE_ T13, GTEST_TEMPLATE_ T14, GTEST_TEMPLATE_ T15, GTEST_TEMPLATE_ T16, GTEST_TEMPLATE_ T17, GTEST_TEMPLATE_ T18, GTEST_TEMPLATE_ T19, GTEST_TEMPLATE_ T20, GTEST_TEMPLATE_ T21, GTEST_TEMPLATE_ T22, GTEST_TEMPLATE_ T23, GTEST_TEMPLATE_ T24, GTEST_TEMPLATE_ T25, GTEST_TEMPLATE_ T26, GTEST_TEMPLATE_ T27, GTEST_TEMPLATE_ T28, GTEST_TEMPLATE_ T29, GTEST_TEMPLATE_ T30, GTEST_TEMPLATE_ T31, GTEST_TEMPLATE_ T32, GTEST_TEMPLATE_ T33, GTEST_TEMPLATE_ T34, GTEST_TEMPLATE_ T35, GTEST_TEMPLATE_ T36, GTEST_TEMPLATE_ T37, GTEST_TEMPLATE_ T38, GTEST_TEMPLATE_ T39, GTEST_TEMPLATE_ T40, GTEST_TEMPLATE_ T41, GTEST_TEMPLATE_ T42, GTEST_TEMPLATE_ T43, GTEST_TEMPLATE_ T44, GTEST_TEMPLATE_ T45, GTEST_TEMPLATE_ T46, GTEST_TEMPLATE_ T47, GTEST_TEMPLATE_ T48, GTEST_TEMPLATE_ T49> struct Templates<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, T47, T48, T49, NoneT> { typedef Templates49<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, T47, T48, T49> type; }; // The TypeList template makes it possible to use either a single type // or a Types<...> list in TYPED_TEST_CASE() and // INSTANTIATE_TYPED_TEST_CASE_P(). template <typename T> struct TypeList { typedef Types1<T> type; }; template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10, typename T11, typename T12, typename T13, typename T14, typename T15, typename T16, typename T17, typename T18, typename T19, typename T20, typename T21, typename T22, typename T23, typename T24, typename T25, typename T26, typename T27, typename T28, typename T29, typename T30, typename T31, typename T32, typename T33, typename T34, typename T35, typename T36, typename T37, typename T38, typename T39, typename T40, typename T41, typename T42, typename T43, typename T44, typename T45, typename T46, typename T47, typename T48, typename T49, typename T50> struct TypeList<Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, T47, T48, T49, T50> > { typedef typename Types<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, T47, T48, T49, T50>::type type; }; #endif // GTEST_HAS_TYPED_TEST || GTEST_HAS_TYPED_TEST_P } // namespace internal } // namespace testing #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_
0
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest/internal/gtest-linked_ptr.h
// Copyright 2003 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. // // Authors: Dan Egnor ([email protected]) // // A "smart" pointer type with reference tracking. Every pointer to a // particular object is kept on a circular linked list. When the last pointer // to an object is destroyed or reassigned, the object is deleted. // // Used properly, this deletes the object when the last reference goes away. // There are several caveats: // - Like all reference counting schemes, cycles lead to leaks. // - Each smart pointer is actually two pointers (8 bytes instead of 4). // - Every time a pointer is assigned, the entire list of pointers to that // object is traversed. This class is therefore NOT SUITABLE when there // will often be more than two or three pointers to a particular object. // - References are only tracked as long as linked_ptr<> objects are copied. // If a linked_ptr<> is converted to a raw pointer and back, BAD THINGS // will happen (double deletion). // // A good use of this class is storing object references in STL containers. // You can safely put linked_ptr<> in a vector<>. // Other uses may not be as good. // // Note: If you use an incomplete type with linked_ptr<>, the class // *containing* linked_ptr<> must have a constructor and destructor (even // if they do nothing!). // // Bill Gibbons suggested we use something like this. // // Thread Safety: // Unlike other linked_ptr implementations, in this implementation // a linked_ptr object is thread-safe in the sense that: // - it's safe to copy linked_ptr objects concurrently, // - it's safe to copy *from* a linked_ptr and read its underlying // raw pointer (e.g. via get()) concurrently, and // - it's safe to write to two linked_ptrs that point to the same // shared object concurrently. // TODO([email protected]): rename this to safe_linked_ptr to avoid // confusion with normal linked_ptr. #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_ #include <stdlib.h> #include <assert.h> #include "gtest/internal/gtest-port.h" namespace testing { namespace internal { // Protects copying of all linked_ptr objects. GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_linked_ptr_mutex); // This is used internally by all instances of linked_ptr<>. It needs to be // a non-template class because different types of linked_ptr<> can refer to // the same object (linked_ptr<Superclass>(obj) vs linked_ptr<Subclass>(obj)). // So, it needs to be possible for different types of linked_ptr to participate // in the same circular linked list, so we need a single class type here. // // DO NOT USE THIS CLASS DIRECTLY YOURSELF. Use linked_ptr<T>. class linked_ptr_internal { public: // Create a new circle that includes only this instance. void join_new() { next_ = this; } // Many linked_ptr operations may change p.link_ for some linked_ptr // variable p in the same circle as this object. Therefore we need // to prevent two such operations from occurring concurrently. // // Note that different types of linked_ptr objects can coexist in a // circle (e.g. linked_ptr<Base>, linked_ptr<Derived1>, and // linked_ptr<Derived2>). Therefore we must use a single mutex to // protect all linked_ptr objects. This can create serious // contention in production code, but is acceptable in a testing // framework. // Join an existing circle. void join(linked_ptr_internal const* ptr) GTEST_LOCK_EXCLUDED_(g_linked_ptr_mutex) { MutexLock lock(&g_linked_ptr_mutex); linked_ptr_internal const* p = ptr; while (p->next_ != ptr) { assert(p->next_ != this && "Trying to join() a linked ring we are already in. " "Is GMock thread safety enabled?"); p = p->next_; } p->next_ = this; next_ = ptr; } // Leave whatever circle we're part of. Returns true if we were the // last member of the circle. Once this is done, you can join() another. bool depart() GTEST_LOCK_EXCLUDED_(g_linked_ptr_mutex) { MutexLock lock(&g_linked_ptr_mutex); if (next_ == this) return true; linked_ptr_internal const* p = next_; while (p->next_ != this) { assert(p->next_ != next_ && "Trying to depart() a linked ring we are not in. " "Is GMock thread safety enabled?"); p = p->next_; } p->next_ = next_; return false; } private: mutable linked_ptr_internal const* next_; }; template <typename T> class linked_ptr { public: typedef T element_type; // Take over ownership of a raw pointer. This should happen as soon as // possible after the object is created. explicit linked_ptr(T* ptr = NULL) { capture(ptr); } ~linked_ptr() { depart(); } // Copy an existing linked_ptr<>, adding ourselves to the list of references. template <typename U> linked_ptr(linked_ptr<U> const& ptr) { copy(&ptr); } linked_ptr(linked_ptr const& ptr) { // NOLINT assert(&ptr != this); copy(&ptr); } // Assignment releases the old value and acquires the new. template <typename U> linked_ptr& operator=(linked_ptr<U> const& ptr) { depart(); copy(&ptr); return *this; } linked_ptr& operator=(linked_ptr const& ptr) { if (&ptr != this) { depart(); copy(&ptr); } return *this; } // Smart pointer members. void reset(T* ptr = NULL) { depart(); capture(ptr); } T* get() const { return value_; } T* operator->() const { return value_; } T& operator*() const { return *value_; } bool operator==(T* p) const { return value_ == p; } bool operator!=(T* p) const { return value_ != p; } template <typename U> bool operator==(linked_ptr<U> const& ptr) const { return value_ == ptr.get(); } template <typename U> bool operator!=(linked_ptr<U> const& ptr) const { return value_ != ptr.get(); } private: template <typename U> friend class linked_ptr; T* value_; linked_ptr_internal link_; void depart() { if (link_.depart()) delete value_; } void capture(T* ptr) { value_ = ptr; link_.join_new(); } template <typename U> void copy(linked_ptr<U> const* ptr) { value_ = ptr->get(); if (value_) link_.join(&ptr->link_); else link_.join_new(); } }; template<typename T> inline bool operator==(T* ptr, const linked_ptr<T>& x) { return ptr == x.get(); } template<typename T> inline bool operator!=(T* ptr, const linked_ptr<T>& x) { return ptr != x.get(); } // A function to convert T* into linked_ptr<T> // Doing e.g. make_linked_ptr(new FooBarBaz<type>(arg)) is a shorter notation // for linked_ptr<FooBarBaz<type> >(new FooBarBaz<type>(arg)) template <typename T> linked_ptr<T> make_linked_ptr(T* ptr) { return linked_ptr<T>(ptr); } } // namespace internal } // namespace testing #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_LINKED_PTR_H_
0
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest/internal/gtest-tuple.h
// This file was GENERATED by command: // pump.py gtest-tuple.h.pump // DO NOT EDIT BY HAND!!! // Copyright 2009 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. // // Author: [email protected] (Zhanyong Wan) // Implements a subset of TR1 tuple needed by Google Test and Google Mock. #ifndef GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_ #include <utility> // For ::std::pair. // The compiler used in Symbian has a bug that prevents us from declaring the // tuple template as a friend (it complains that tuple is redefined). This // hack bypasses the bug by declaring the members that should otherwise be // private as public. // Sun Studio versions < 12 also have the above bug. #if defined(__SYMBIAN32__) || (defined(__SUNPRO_CC) && __SUNPRO_CC < 0x590) # define GTEST_DECLARE_TUPLE_AS_FRIEND_ public: #else # define GTEST_DECLARE_TUPLE_AS_FRIEND_ \ template <GTEST_10_TYPENAMES_(U)> friend class tuple; \ private: #endif // Visual Studio 2010, 2012, and 2013 define symbols in std::tr1 that conflict // with our own definitions. Therefore using our own tuple does not work on // those compilers. #if defined(_MSC_VER) && _MSC_VER >= 1600 /* 1600 is Visual Studio 2010 */ # error "gtest's tuple doesn't compile on Visual Studio 2010 or later. \ GTEST_USE_OWN_TR1_TUPLE must be set to 0 on those compilers." #endif // GTEST_n_TUPLE_(T) is the type of an n-tuple. #define GTEST_0_TUPLE_(T) tuple<> #define GTEST_1_TUPLE_(T) tuple<T##0, void, void, void, void, void, void, \ void, void, void> #define GTEST_2_TUPLE_(T) tuple<T##0, T##1, void, void, void, void, void, \ void, void, void> #define GTEST_3_TUPLE_(T) tuple<T##0, T##1, T##2, void, void, void, void, \ void, void, void> #define GTEST_4_TUPLE_(T) tuple<T##0, T##1, T##2, T##3, void, void, void, \ void, void, void> #define GTEST_5_TUPLE_(T) tuple<T##0, T##1, T##2, T##3, T##4, void, void, \ void, void, void> #define GTEST_6_TUPLE_(T) tuple<T##0, T##1, T##2, T##3, T##4, T##5, void, \ void, void, void> #define GTEST_7_TUPLE_(T) tuple<T##0, T##1, T##2, T##3, T##4, T##5, T##6, \ void, void, void> #define GTEST_8_TUPLE_(T) tuple<T##0, T##1, T##2, T##3, T##4, T##5, T##6, \ T##7, void, void> #define GTEST_9_TUPLE_(T) tuple<T##0, T##1, T##2, T##3, T##4, T##5, T##6, \ T##7, T##8, void> #define GTEST_10_TUPLE_(T) tuple<T##0, T##1, T##2, T##3, T##4, T##5, T##6, \ T##7, T##8, T##9> // GTEST_n_TYPENAMES_(T) declares a list of n typenames. #define GTEST_0_TYPENAMES_(T) #define GTEST_1_TYPENAMES_(T) typename T##0 #define GTEST_2_TYPENAMES_(T) typename T##0, typename T##1 #define GTEST_3_TYPENAMES_(T) typename T##0, typename T##1, typename T##2 #define GTEST_4_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ typename T##3 #define GTEST_5_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ typename T##3, typename T##4 #define GTEST_6_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ typename T##3, typename T##4, typename T##5 #define GTEST_7_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ typename T##3, typename T##4, typename T##5, typename T##6 #define GTEST_8_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ typename T##3, typename T##4, typename T##5, typename T##6, typename T##7 #define GTEST_9_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ typename T##3, typename T##4, typename T##5, typename T##6, \ typename T##7, typename T##8 #define GTEST_10_TYPENAMES_(T) typename T##0, typename T##1, typename T##2, \ typename T##3, typename T##4, typename T##5, typename T##6, \ typename T##7, typename T##8, typename T##9 // In theory, defining stuff in the ::std namespace is undefined // behavior. We can do this as we are playing the role of a standard // library vendor. namespace std { namespace tr1 { template <typename T0 = void, typename T1 = void, typename T2 = void, typename T3 = void, typename T4 = void, typename T5 = void, typename T6 = void, typename T7 = void, typename T8 = void, typename T9 = void> class tuple; // Anything in namespace gtest_internal is Google Test's INTERNAL // IMPLEMENTATION DETAIL and MUST NOT BE USED DIRECTLY in user code. namespace gtest_internal { // ByRef<T>::type is T if T is a reference; otherwise it's const T&. template <typename T> struct ByRef { typedef const T& type; }; // NOLINT template <typename T> struct ByRef<T&> { typedef T& type; }; // NOLINT // A handy wrapper for ByRef. #define GTEST_BY_REF_(T) typename ::std::tr1::gtest_internal::ByRef<T>::type // AddRef<T>::type is T if T is a reference; otherwise it's T&. This // is the same as tr1::add_reference<T>::type. template <typename T> struct AddRef { typedef T& type; }; // NOLINT template <typename T> struct AddRef<T&> { typedef T& type; }; // NOLINT // A handy wrapper for AddRef. #define GTEST_ADD_REF_(T) typename ::std::tr1::gtest_internal::AddRef<T>::type // A helper for implementing get<k>(). template <int k> class Get; // A helper for implementing tuple_element<k, T>. kIndexValid is true // iff k < the number of fields in tuple type T. template <bool kIndexValid, int kIndex, class Tuple> struct TupleElement; template <GTEST_10_TYPENAMES_(T)> struct TupleElement<true, 0, GTEST_10_TUPLE_(T) > { typedef T0 type; }; template <GTEST_10_TYPENAMES_(T)> struct TupleElement<true, 1, GTEST_10_TUPLE_(T) > { typedef T1 type; }; template <GTEST_10_TYPENAMES_(T)> struct TupleElement<true, 2, GTEST_10_TUPLE_(T) > { typedef T2 type; }; template <GTEST_10_TYPENAMES_(T)> struct TupleElement<true, 3, GTEST_10_TUPLE_(T) > { typedef T3 type; }; template <GTEST_10_TYPENAMES_(T)> struct TupleElement<true, 4, GTEST_10_TUPLE_(T) > { typedef T4 type; }; template <GTEST_10_TYPENAMES_(T)> struct TupleElement<true, 5, GTEST_10_TUPLE_(T) > { typedef T5 type; }; template <GTEST_10_TYPENAMES_(T)> struct TupleElement<true, 6, GTEST_10_TUPLE_(T) > { typedef T6 type; }; template <GTEST_10_TYPENAMES_(T)> struct TupleElement<true, 7, GTEST_10_TUPLE_(T) > { typedef T7 type; }; template <GTEST_10_TYPENAMES_(T)> struct TupleElement<true, 8, GTEST_10_TUPLE_(T) > { typedef T8 type; }; template <GTEST_10_TYPENAMES_(T)> struct TupleElement<true, 9, GTEST_10_TUPLE_(T) > { typedef T9 type; }; } // namespace gtest_internal template <> class tuple<> { public: tuple() {} tuple(const tuple& /* t */) {} tuple& operator=(const tuple& /* t */) { return *this; } }; template <GTEST_1_TYPENAMES_(T)> class GTEST_1_TUPLE_(T) { public: template <int k> friend class gtest_internal::Get; tuple() : f0_() {} explicit tuple(GTEST_BY_REF_(T0) f0) : f0_(f0) {} tuple(const tuple& t) : f0_(t.f0_) {} template <GTEST_1_TYPENAMES_(U)> tuple(const GTEST_1_TUPLE_(U)& t) : f0_(t.f0_) {} tuple& operator=(const tuple& t) { return CopyFrom(t); } template <GTEST_1_TYPENAMES_(U)> tuple& operator=(const GTEST_1_TUPLE_(U)& t) { return CopyFrom(t); } GTEST_DECLARE_TUPLE_AS_FRIEND_ template <GTEST_1_TYPENAMES_(U)> tuple& CopyFrom(const GTEST_1_TUPLE_(U)& t) { f0_ = t.f0_; return *this; } T0 f0_; }; template <GTEST_2_TYPENAMES_(T)> class GTEST_2_TUPLE_(T) { public: template <int k> friend class gtest_internal::Get; tuple() : f0_(), f1_() {} explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1) : f0_(f0), f1_(f1) {} tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_) {} template <GTEST_2_TYPENAMES_(U)> tuple(const GTEST_2_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_) {} template <typename U0, typename U1> tuple(const ::std::pair<U0, U1>& p) : f0_(p.first), f1_(p.second) {} tuple& operator=(const tuple& t) { return CopyFrom(t); } template <GTEST_2_TYPENAMES_(U)> tuple& operator=(const GTEST_2_TUPLE_(U)& t) { return CopyFrom(t); } template <typename U0, typename U1> tuple& operator=(const ::std::pair<U0, U1>& p) { f0_ = p.first; f1_ = p.second; return *this; } GTEST_DECLARE_TUPLE_AS_FRIEND_ template <GTEST_2_TYPENAMES_(U)> tuple& CopyFrom(const GTEST_2_TUPLE_(U)& t) { f0_ = t.f0_; f1_ = t.f1_; return *this; } T0 f0_; T1 f1_; }; template <GTEST_3_TYPENAMES_(T)> class GTEST_3_TUPLE_(T) { public: template <int k> friend class gtest_internal::Get; tuple() : f0_(), f1_(), f2_() {} explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, GTEST_BY_REF_(T2) f2) : f0_(f0), f1_(f1), f2_(f2) {} tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_) {} template <GTEST_3_TYPENAMES_(U)> tuple(const GTEST_3_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_) {} tuple& operator=(const tuple& t) { return CopyFrom(t); } template <GTEST_3_TYPENAMES_(U)> tuple& operator=(const GTEST_3_TUPLE_(U)& t) { return CopyFrom(t); } GTEST_DECLARE_TUPLE_AS_FRIEND_ template <GTEST_3_TYPENAMES_(U)> tuple& CopyFrom(const GTEST_3_TUPLE_(U)& t) { f0_ = t.f0_; f1_ = t.f1_; f2_ = t.f2_; return *this; } T0 f0_; T1 f1_; T2 f2_; }; template <GTEST_4_TYPENAMES_(T)> class GTEST_4_TUPLE_(T) { public: template <int k> friend class gtest_internal::Get; tuple() : f0_(), f1_(), f2_(), f3_() {} explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3) : f0_(f0), f1_(f1), f2_(f2), f3_(f3) {} tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_) {} template <GTEST_4_TYPENAMES_(U)> tuple(const GTEST_4_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_) {} tuple& operator=(const tuple& t) { return CopyFrom(t); } template <GTEST_4_TYPENAMES_(U)> tuple& operator=(const GTEST_4_TUPLE_(U)& t) { return CopyFrom(t); } GTEST_DECLARE_TUPLE_AS_FRIEND_ template <GTEST_4_TYPENAMES_(U)> tuple& CopyFrom(const GTEST_4_TUPLE_(U)& t) { f0_ = t.f0_; f1_ = t.f1_; f2_ = t.f2_; f3_ = t.f3_; return *this; } T0 f0_; T1 f1_; T2 f2_; T3 f3_; }; template <GTEST_5_TYPENAMES_(T)> class GTEST_5_TUPLE_(T) { public: template <int k> friend class gtest_internal::Get; tuple() : f0_(), f1_(), f2_(), f3_(), f4_() {} explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4) {} tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), f4_(t.f4_) {} template <GTEST_5_TYPENAMES_(U)> tuple(const GTEST_5_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), f4_(t.f4_) {} tuple& operator=(const tuple& t) { return CopyFrom(t); } template <GTEST_5_TYPENAMES_(U)> tuple& operator=(const GTEST_5_TUPLE_(U)& t) { return CopyFrom(t); } GTEST_DECLARE_TUPLE_AS_FRIEND_ template <GTEST_5_TYPENAMES_(U)> tuple& CopyFrom(const GTEST_5_TUPLE_(U)& t) { f0_ = t.f0_; f1_ = t.f1_; f2_ = t.f2_; f3_ = t.f3_; f4_ = t.f4_; return *this; } T0 f0_; T1 f1_; T2 f2_; T3 f3_; T4 f4_; }; template <GTEST_6_TYPENAMES_(T)> class GTEST_6_TUPLE_(T) { public: template <int k> friend class gtest_internal::Get; tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_() {} explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, GTEST_BY_REF_(T5) f5) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4), f5_(f5) {} tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), f4_(t.f4_), f5_(t.f5_) {} template <GTEST_6_TYPENAMES_(U)> tuple(const GTEST_6_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), f4_(t.f4_), f5_(t.f5_) {} tuple& operator=(const tuple& t) { return CopyFrom(t); } template <GTEST_6_TYPENAMES_(U)> tuple& operator=(const GTEST_6_TUPLE_(U)& t) { return CopyFrom(t); } GTEST_DECLARE_TUPLE_AS_FRIEND_ template <GTEST_6_TYPENAMES_(U)> tuple& CopyFrom(const GTEST_6_TUPLE_(U)& t) { f0_ = t.f0_; f1_ = t.f1_; f2_ = t.f2_; f3_ = t.f3_; f4_ = t.f4_; f5_ = t.f5_; return *this; } T0 f0_; T1 f1_; T2 f2_; T3 f3_; T4 f4_; T5 f5_; }; template <GTEST_7_TYPENAMES_(T)> class GTEST_7_TUPLE_(T) { public: template <int k> friend class gtest_internal::Get; tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_() {} explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4), f5_(f5), f6_(f6) {} tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_) {} template <GTEST_7_TYPENAMES_(U)> tuple(const GTEST_7_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_) {} tuple& operator=(const tuple& t) { return CopyFrom(t); } template <GTEST_7_TYPENAMES_(U)> tuple& operator=(const GTEST_7_TUPLE_(U)& t) { return CopyFrom(t); } GTEST_DECLARE_TUPLE_AS_FRIEND_ template <GTEST_7_TYPENAMES_(U)> tuple& CopyFrom(const GTEST_7_TUPLE_(U)& t) { f0_ = t.f0_; f1_ = t.f1_; f2_ = t.f2_; f3_ = t.f3_; f4_ = t.f4_; f5_ = t.f5_; f6_ = t.f6_; return *this; } T0 f0_; T1 f1_; T2 f2_; T3 f3_; T4 f4_; T5 f5_; T6 f6_; }; template <GTEST_8_TYPENAMES_(T)> class GTEST_8_TUPLE_(T) { public: template <int k> friend class gtest_internal::Get; tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_() {} explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6, GTEST_BY_REF_(T7) f7) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4), f5_(f5), f6_(f6), f7_(f7) {} tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_) {} template <GTEST_8_TYPENAMES_(U)> tuple(const GTEST_8_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_) {} tuple& operator=(const tuple& t) { return CopyFrom(t); } template <GTEST_8_TYPENAMES_(U)> tuple& operator=(const GTEST_8_TUPLE_(U)& t) { return CopyFrom(t); } GTEST_DECLARE_TUPLE_AS_FRIEND_ template <GTEST_8_TYPENAMES_(U)> tuple& CopyFrom(const GTEST_8_TUPLE_(U)& t) { f0_ = t.f0_; f1_ = t.f1_; f2_ = t.f2_; f3_ = t.f3_; f4_ = t.f4_; f5_ = t.f5_; f6_ = t.f6_; f7_ = t.f7_; return *this; } T0 f0_; T1 f1_; T2 f2_; T3 f3_; T4 f4_; T5 f5_; T6 f6_; T7 f7_; }; template <GTEST_9_TYPENAMES_(T)> class GTEST_9_TUPLE_(T) { public: template <int k> friend class gtest_internal::Get; tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_(), f8_() {} explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6, GTEST_BY_REF_(T7) f7, GTEST_BY_REF_(T8) f8) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4), f5_(f5), f6_(f6), f7_(f7), f8_(f8) {} tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_) {} template <GTEST_9_TYPENAMES_(U)> tuple(const GTEST_9_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_) {} tuple& operator=(const tuple& t) { return CopyFrom(t); } template <GTEST_9_TYPENAMES_(U)> tuple& operator=(const GTEST_9_TUPLE_(U)& t) { return CopyFrom(t); } GTEST_DECLARE_TUPLE_AS_FRIEND_ template <GTEST_9_TYPENAMES_(U)> tuple& CopyFrom(const GTEST_9_TUPLE_(U)& t) { f0_ = t.f0_; f1_ = t.f1_; f2_ = t.f2_; f3_ = t.f3_; f4_ = t.f4_; f5_ = t.f5_; f6_ = t.f6_; f7_ = t.f7_; f8_ = t.f8_; return *this; } T0 f0_; T1 f1_; T2 f2_; T3 f3_; T4 f4_; T5 f5_; T6 f6_; T7 f7_; T8 f8_; }; template <GTEST_10_TYPENAMES_(T)> class tuple { public: template <int k> friend class gtest_internal::Get; tuple() : f0_(), f1_(), f2_(), f3_(), f4_(), f5_(), f6_(), f7_(), f8_(), f9_() {} explicit tuple(GTEST_BY_REF_(T0) f0, GTEST_BY_REF_(T1) f1, GTEST_BY_REF_(T2) f2, GTEST_BY_REF_(T3) f3, GTEST_BY_REF_(T4) f4, GTEST_BY_REF_(T5) f5, GTEST_BY_REF_(T6) f6, GTEST_BY_REF_(T7) f7, GTEST_BY_REF_(T8) f8, GTEST_BY_REF_(T9) f9) : f0_(f0), f1_(f1), f2_(f2), f3_(f3), f4_(f4), f5_(f5), f6_(f6), f7_(f7), f8_(f8), f9_(f9) {} tuple(const tuple& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_), f9_(t.f9_) {} template <GTEST_10_TYPENAMES_(U)> tuple(const GTEST_10_TUPLE_(U)& t) : f0_(t.f0_), f1_(t.f1_), f2_(t.f2_), f3_(t.f3_), f4_(t.f4_), f5_(t.f5_), f6_(t.f6_), f7_(t.f7_), f8_(t.f8_), f9_(t.f9_) {} tuple& operator=(const tuple& t) { return CopyFrom(t); } template <GTEST_10_TYPENAMES_(U)> tuple& operator=(const GTEST_10_TUPLE_(U)& t) { return CopyFrom(t); } GTEST_DECLARE_TUPLE_AS_FRIEND_ template <GTEST_10_TYPENAMES_(U)> tuple& CopyFrom(const GTEST_10_TUPLE_(U)& t) { f0_ = t.f0_; f1_ = t.f1_; f2_ = t.f2_; f3_ = t.f3_; f4_ = t.f4_; f5_ = t.f5_; f6_ = t.f6_; f7_ = t.f7_; f8_ = t.f8_; f9_ = t.f9_; return *this; } T0 f0_; T1 f1_; T2 f2_; T3 f3_; T4 f4_; T5 f5_; T6 f6_; T7 f7_; T8 f8_; T9 f9_; }; // 6.1.3.2 Tuple creation functions. // Known limitations: we don't support passing an // std::tr1::reference_wrapper<T> to make_tuple(). And we don't // implement tie(). inline tuple<> make_tuple() { return tuple<>(); } template <GTEST_1_TYPENAMES_(T)> inline GTEST_1_TUPLE_(T) make_tuple(const T0& f0) { return GTEST_1_TUPLE_(T)(f0); } template <GTEST_2_TYPENAMES_(T)> inline GTEST_2_TUPLE_(T) make_tuple(const T0& f0, const T1& f1) { return GTEST_2_TUPLE_(T)(f0, f1); } template <GTEST_3_TYPENAMES_(T)> inline GTEST_3_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2) { return GTEST_3_TUPLE_(T)(f0, f1, f2); } template <GTEST_4_TYPENAMES_(T)> inline GTEST_4_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, const T3& f3) { return GTEST_4_TUPLE_(T)(f0, f1, f2, f3); } template <GTEST_5_TYPENAMES_(T)> inline GTEST_5_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, const T3& f3, const T4& f4) { return GTEST_5_TUPLE_(T)(f0, f1, f2, f3, f4); } template <GTEST_6_TYPENAMES_(T)> inline GTEST_6_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, const T3& f3, const T4& f4, const T5& f5) { return GTEST_6_TUPLE_(T)(f0, f1, f2, f3, f4, f5); } template <GTEST_7_TYPENAMES_(T)> inline GTEST_7_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, const T3& f3, const T4& f4, const T5& f5, const T6& f6) { return GTEST_7_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6); } template <GTEST_8_TYPENAMES_(T)> inline GTEST_8_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, const T3& f3, const T4& f4, const T5& f5, const T6& f6, const T7& f7) { return GTEST_8_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6, f7); } template <GTEST_9_TYPENAMES_(T)> inline GTEST_9_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, const T3& f3, const T4& f4, const T5& f5, const T6& f6, const T7& f7, const T8& f8) { return GTEST_9_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6, f7, f8); } template <GTEST_10_TYPENAMES_(T)> inline GTEST_10_TUPLE_(T) make_tuple(const T0& f0, const T1& f1, const T2& f2, const T3& f3, const T4& f4, const T5& f5, const T6& f6, const T7& f7, const T8& f8, const T9& f9) { return GTEST_10_TUPLE_(T)(f0, f1, f2, f3, f4, f5, f6, f7, f8, f9); } // 6.1.3.3 Tuple helper classes. template <typename Tuple> struct tuple_size; template <GTEST_0_TYPENAMES_(T)> struct tuple_size<GTEST_0_TUPLE_(T) > { static const int value = 0; }; template <GTEST_1_TYPENAMES_(T)> struct tuple_size<GTEST_1_TUPLE_(T) > { static const int value = 1; }; template <GTEST_2_TYPENAMES_(T)> struct tuple_size<GTEST_2_TUPLE_(T) > { static const int value = 2; }; template <GTEST_3_TYPENAMES_(T)> struct tuple_size<GTEST_3_TUPLE_(T) > { static const int value = 3; }; template <GTEST_4_TYPENAMES_(T)> struct tuple_size<GTEST_4_TUPLE_(T) > { static const int value = 4; }; template <GTEST_5_TYPENAMES_(T)> struct tuple_size<GTEST_5_TUPLE_(T) > { static const int value = 5; }; template <GTEST_6_TYPENAMES_(T)> struct tuple_size<GTEST_6_TUPLE_(T) > { static const int value = 6; }; template <GTEST_7_TYPENAMES_(T)> struct tuple_size<GTEST_7_TUPLE_(T) > { static const int value = 7; }; template <GTEST_8_TYPENAMES_(T)> struct tuple_size<GTEST_8_TUPLE_(T) > { static const int value = 8; }; template <GTEST_9_TYPENAMES_(T)> struct tuple_size<GTEST_9_TUPLE_(T) > { static const int value = 9; }; template <GTEST_10_TYPENAMES_(T)> struct tuple_size<GTEST_10_TUPLE_(T) > { static const int value = 10; }; template <int k, class Tuple> struct tuple_element { typedef typename gtest_internal::TupleElement< k < (tuple_size<Tuple>::value), k, Tuple>::type type; }; #define GTEST_TUPLE_ELEMENT_(k, Tuple) typename tuple_element<k, Tuple >::type // 6.1.3.4 Element access. namespace gtest_internal { template <> class Get<0> { public: template <class Tuple> static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(0, Tuple)) Field(Tuple& t) { return t.f0_; } // NOLINT template <class Tuple> static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(0, Tuple)) ConstField(const Tuple& t) { return t.f0_; } }; template <> class Get<1> { public: template <class Tuple> static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(1, Tuple)) Field(Tuple& t) { return t.f1_; } // NOLINT template <class Tuple> static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(1, Tuple)) ConstField(const Tuple& t) { return t.f1_; } }; template <> class Get<2> { public: template <class Tuple> static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(2, Tuple)) Field(Tuple& t) { return t.f2_; } // NOLINT template <class Tuple> static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(2, Tuple)) ConstField(const Tuple& t) { return t.f2_; } }; template <> class Get<3> { public: template <class Tuple> static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(3, Tuple)) Field(Tuple& t) { return t.f3_; } // NOLINT template <class Tuple> static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(3, Tuple)) ConstField(const Tuple& t) { return t.f3_; } }; template <> class Get<4> { public: template <class Tuple> static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(4, Tuple)) Field(Tuple& t) { return t.f4_; } // NOLINT template <class Tuple> static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(4, Tuple)) ConstField(const Tuple& t) { return t.f4_; } }; template <> class Get<5> { public: template <class Tuple> static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(5, Tuple)) Field(Tuple& t) { return t.f5_; } // NOLINT template <class Tuple> static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(5, Tuple)) ConstField(const Tuple& t) { return t.f5_; } }; template <> class Get<6> { public: template <class Tuple> static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(6, Tuple)) Field(Tuple& t) { return t.f6_; } // NOLINT template <class Tuple> static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(6, Tuple)) ConstField(const Tuple& t) { return t.f6_; } }; template <> class Get<7> { public: template <class Tuple> static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(7, Tuple)) Field(Tuple& t) { return t.f7_; } // NOLINT template <class Tuple> static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(7, Tuple)) ConstField(const Tuple& t) { return t.f7_; } }; template <> class Get<8> { public: template <class Tuple> static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(8, Tuple)) Field(Tuple& t) { return t.f8_; } // NOLINT template <class Tuple> static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(8, Tuple)) ConstField(const Tuple& t) { return t.f8_; } }; template <> class Get<9> { public: template <class Tuple> static GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(9, Tuple)) Field(Tuple& t) { return t.f9_; } // NOLINT template <class Tuple> static GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(9, Tuple)) ConstField(const Tuple& t) { return t.f9_; } }; } // namespace gtest_internal template <int k, GTEST_10_TYPENAMES_(T)> GTEST_ADD_REF_(GTEST_TUPLE_ELEMENT_(k, GTEST_10_TUPLE_(T))) get(GTEST_10_TUPLE_(T)& t) { return gtest_internal::Get<k>::Field(t); } template <int k, GTEST_10_TYPENAMES_(T)> GTEST_BY_REF_(GTEST_TUPLE_ELEMENT_(k, GTEST_10_TUPLE_(T))) get(const GTEST_10_TUPLE_(T)& t) { return gtest_internal::Get<k>::ConstField(t); } // 6.1.3.5 Relational operators // We only implement == and !=, as we don't have a need for the rest yet. namespace gtest_internal { // SameSizeTuplePrefixComparator<k, k>::Eq(t1, t2) returns true if the // first k fields of t1 equals the first k fields of t2. // SameSizeTuplePrefixComparator(k1, k2) would be a compiler error if // k1 != k2. template <int kSize1, int kSize2> struct SameSizeTuplePrefixComparator; template <> struct SameSizeTuplePrefixComparator<0, 0> { template <class Tuple1, class Tuple2> static bool Eq(const Tuple1& /* t1 */, const Tuple2& /* t2 */) { return true; } }; template <int k> struct SameSizeTuplePrefixComparator<k, k> { template <class Tuple1, class Tuple2> static bool Eq(const Tuple1& t1, const Tuple2& t2) { return SameSizeTuplePrefixComparator<k - 1, k - 1>::Eq(t1, t2) && ::std::tr1::get<k - 1>(t1) == ::std::tr1::get<k - 1>(t2); } }; } // namespace gtest_internal template <GTEST_10_TYPENAMES_(T), GTEST_10_TYPENAMES_(U)> inline bool operator==(const GTEST_10_TUPLE_(T)& t, const GTEST_10_TUPLE_(U)& u) { return gtest_internal::SameSizeTuplePrefixComparator< tuple_size<GTEST_10_TUPLE_(T) >::value, tuple_size<GTEST_10_TUPLE_(U) >::value>::Eq(t, u); } template <GTEST_10_TYPENAMES_(T), GTEST_10_TYPENAMES_(U)> inline bool operator!=(const GTEST_10_TUPLE_(T)& t, const GTEST_10_TUPLE_(U)& u) { return !(t == u); } // 6.1.4 Pairs. // Unimplemented. } // namespace tr1 } // namespace std #undef GTEST_0_TUPLE_ #undef GTEST_1_TUPLE_ #undef GTEST_2_TUPLE_ #undef GTEST_3_TUPLE_ #undef GTEST_4_TUPLE_ #undef GTEST_5_TUPLE_ #undef GTEST_6_TUPLE_ #undef GTEST_7_TUPLE_ #undef GTEST_8_TUPLE_ #undef GTEST_9_TUPLE_ #undef GTEST_10_TUPLE_ #undef GTEST_0_TYPENAMES_ #undef GTEST_1_TYPENAMES_ #undef GTEST_2_TYPENAMES_ #undef GTEST_3_TYPENAMES_ #undef GTEST_4_TYPENAMES_ #undef GTEST_5_TYPENAMES_ #undef GTEST_6_TYPENAMES_ #undef GTEST_7_TYPENAMES_ #undef GTEST_8_TYPENAMES_ #undef GTEST_9_TYPENAMES_ #undef GTEST_10_TYPENAMES_ #undef GTEST_DECLARE_TUPLE_AS_FRIEND_ #undef GTEST_BY_REF_ #undef GTEST_ADD_REF_ #undef GTEST_TUPLE_ELEMENT_ #endif // GTEST_INCLUDE_GTEST_INTERNAL_GTEST_TUPLE_H_
0
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest/internal
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest/internal/custom/gtest.h
// Copyright 2015, 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. // // Injection point for custom user configurations. // The following macros can be defined: // // GTEST_OS_STACK_TRACE_GETTER_ - The name of an implementation of // OsStackTraceGetterInterface. // // ** Custom implementation starts here ** #ifndef GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_ #endif // GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_
0
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest/internal
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest/internal/custom/gtest-printers.h
// Copyright 2015, 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. // // This file provides an injection point for custom printers in a local // installation of gTest. // It will be included from gtest-printers.h and the overrides in this file // will be visible to everyone. // See documentation at gtest/gtest-printers.h for details on how to define a // custom printer. // // ** Custom implementation starts here ** #ifndef GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_ #endif // GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_
0
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest/internal
repos/DirectXShaderCompiler/utils/unittest/googletest/include/gtest/internal/custom/gtest-port.h
// Copyright 2015, 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. // // Injection point for custom user configurations. // The following macros can be defined: // // Flag related macros: // GTEST_FLAG(flag_name) // GTEST_USE_OWN_FLAGFILE_FLAG_ - Define to 0 when the system provides its // own flagfile flag parsing. // GTEST_DECLARE_bool_(name) // GTEST_DECLARE_int32_(name) // GTEST_DECLARE_string_(name) // GTEST_DEFINE_bool_(name, default_val, doc) // GTEST_DEFINE_int32_(name, default_val, doc) // GTEST_DEFINE_string_(name, default_val, doc) // // Test filtering: // GTEST_TEST_FILTER_ENV_VAR_ - The name of an environment variable that // will be used if --GTEST_FLAG(test_filter) // is not provided. // // Logging: // GTEST_LOG_(severity) // GTEST_CHECK_(condition) // Functions LogToStderr() and FlushInfoLog() have to be provided too. // // Threading: // GTEST_HAS_NOTIFICATION_ - Enabled if Notification is already provided. // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ - Enabled if Mutex and ThreadLocal are // already provided. // Must also provide GTEST_DECLARE_STATIC_MUTEX_(mutex) and // GTEST_DEFINE_STATIC_MUTEX_(mutex) // // GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks) // GTEST_LOCK_EXCLUDED_(locks) // // ** Custom implementation starts here ** #ifndef GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_ #define GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_ #endif // GTEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_
0
repos/DirectXShaderCompiler/utils/unittest/googletest
repos/DirectXShaderCompiler/utils/unittest/googletest/src/gtest-internal-inl.h
// Copyright 2005, 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. // Utility functions and classes used by the Google C++ testing framework. // // Author: [email protected] (Zhanyong Wan) // // This file contains purely Google Test's internal implementation. Please // DO NOT #INCLUDE IT IN A USER PROGRAM. #ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_ #define GTEST_SRC_GTEST_INTERNAL_INL_H_ // GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is // part of Google Test's implementation; otherwise it's undefined. #if !GTEST_IMPLEMENTATION_ // If this file is included from the user's code, just say no. # error "gtest-internal-inl.h is part of Google Test's internal implementation." # error "It must not be included except by Google Test itself." #endif // GTEST_IMPLEMENTATION_ #ifndef _WIN32_WCE # include <errno.h> #endif // !_WIN32_WCE #include <stddef.h> #include <stdlib.h> // For strtoll/_strtoul64/malloc/free. #include <string.h> // For memmove. #include <algorithm> #include <string> #include <vector> #include "gtest/internal/gtest-port.h" #if GTEST_CAN_STREAM_RESULTS_ # include <arpa/inet.h> // NOLINT # include <netdb.h> // NOLINT #endif #if GTEST_OS_WINDOWS # include <windows.h> // NOLINT #endif // GTEST_OS_WINDOWS #include "gtest/gtest.h" // NOLINT #include "gtest/gtest-spi.h" namespace testing { // Declares the flags. // // We don't want the users to modify this flag in the code, but want // Google Test's own unit tests to be able to access it. Therefore we // declare it here as opposed to in gtest.h. GTEST_DECLARE_bool_(death_test_use_fork); namespace internal { // The value of GetTestTypeId() as seen from within the Google Test // library. This is solely for testing GetTestTypeId(). GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest; // Names of the flags (needed for parsing Google Test flags). const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests"; const char kBreakOnFailureFlag[] = "break_on_failure"; const char kCatchExceptionsFlag[] = "catch_exceptions"; const char kColorFlag[] = "color"; const char kFilterFlag[] = "filter"; const char kListTestsFlag[] = "list_tests"; const char kOutputFlag[] = "output"; const char kPrintTimeFlag[] = "print_time"; const char kRandomSeedFlag[] = "random_seed"; const char kRepeatFlag[] = "repeat"; const char kShuffleFlag[] = "shuffle"; const char kStackTraceDepthFlag[] = "stack_trace_depth"; const char kStreamResultToFlag[] = "stream_result_to"; const char kThrowOnFailureFlag[] = "throw_on_failure"; const char kFlagfileFlag[] = "flagfile"; // A valid random seed must be in [1, kMaxRandomSeed]. const int kMaxRandomSeed = 99999; // g_help_flag is true iff the --help flag or an equivalent form is // specified on the command line. GTEST_API_ extern bool g_help_flag; // Returns the current time in milliseconds. GTEST_API_ TimeInMillis GetTimeInMillis(); // Returns true iff Google Test should use colors in the output. GTEST_API_ bool ShouldUseColor(bool stdout_is_tty); // Formats the given time in milliseconds as seconds. GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms); // Converts the given time in milliseconds to a date string in the ISO 8601 // format, without the timezone information. N.B.: due to the use the // non-reentrant localtime() function, this function is not thread safe. Do // not use it in any code that can be called from multiple threads. GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms); // Parses a string for an Int32 flag, in the form of "--flag=value". // // On success, stores the value of the flag in *value, and returns // true. On failure, returns false without changing *value. GTEST_API_ bool ParseInt32Flag( const char* str, const char* flag, Int32* value); // Returns a random seed in range [1, kMaxRandomSeed] based on the // given --gtest_random_seed flag value. inline int GetRandomSeedFromFlag(Int32 random_seed_flag) { const unsigned int raw_seed = (random_seed_flag == 0) ? static_cast<unsigned int>(GetTimeInMillis()) : static_cast<unsigned int>(random_seed_flag); // Normalizes the actual seed to range [1, kMaxRandomSeed] such that // it's easy to type. const int normalized_seed = static_cast<int>((raw_seed - 1U) % static_cast<unsigned int>(kMaxRandomSeed)) + 1; return normalized_seed; } // Returns the first valid random seed after 'seed'. The behavior is // undefined if 'seed' is invalid. The seed after kMaxRandomSeed is // considered to be 1. inline int GetNextRandomSeed(int seed) { GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed) << "Invalid random seed " << seed << " - must be in [1, " << kMaxRandomSeed << "]."; const int next_seed = seed + 1; return (next_seed > kMaxRandomSeed) ? 1 : next_seed; } // This class saves the values of all Google Test flags in its c'tor, and // restores them in its d'tor. class GTestFlagSaver { public: // The c'tor. GTestFlagSaver() { also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests); break_on_failure_ = GTEST_FLAG(break_on_failure); catch_exceptions_ = GTEST_FLAG(catch_exceptions); color_ = GTEST_FLAG(color); death_test_style_ = GTEST_FLAG(death_test_style); death_test_use_fork_ = GTEST_FLAG(death_test_use_fork); filter_ = GTEST_FLAG(filter); internal_run_death_test_ = GTEST_FLAG(internal_run_death_test); list_tests_ = GTEST_FLAG(list_tests); output_ = GTEST_FLAG(output); print_time_ = GTEST_FLAG(print_time); random_seed_ = GTEST_FLAG(random_seed); repeat_ = GTEST_FLAG(repeat); shuffle_ = GTEST_FLAG(shuffle); stack_trace_depth_ = GTEST_FLAG(stack_trace_depth); stream_result_to_ = GTEST_FLAG(stream_result_to); throw_on_failure_ = GTEST_FLAG(throw_on_failure); } // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS. ~GTestFlagSaver() { GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_; GTEST_FLAG(break_on_failure) = break_on_failure_; GTEST_FLAG(catch_exceptions) = catch_exceptions_; GTEST_FLAG(color) = color_; GTEST_FLAG(death_test_style) = death_test_style_; GTEST_FLAG(death_test_use_fork) = death_test_use_fork_; GTEST_FLAG(filter) = filter_; GTEST_FLAG(internal_run_death_test) = internal_run_death_test_; GTEST_FLAG(list_tests) = list_tests_; GTEST_FLAG(output) = output_; GTEST_FLAG(print_time) = print_time_; GTEST_FLAG(random_seed) = random_seed_; GTEST_FLAG(repeat) = repeat_; GTEST_FLAG(shuffle) = shuffle_; GTEST_FLAG(stack_trace_depth) = stack_trace_depth_; GTEST_FLAG(stream_result_to) = stream_result_to_; GTEST_FLAG(throw_on_failure) = throw_on_failure_; } private: // Fields for saving the original values of flags. bool also_run_disabled_tests_; bool break_on_failure_; bool catch_exceptions_; std::string color_; std::string death_test_style_; bool death_test_use_fork_; std::string filter_; std::string internal_run_death_test_; bool list_tests_; std::string output_; bool print_time_; internal::Int32 random_seed_; internal::Int32 repeat_; bool shuffle_; internal::Int32 stack_trace_depth_; std::string stream_result_to_; bool throw_on_failure_; } GTEST_ATTRIBUTE_UNUSED_; // Converts a Unicode code point to a narrow string in UTF-8 encoding. // code_point parameter is of type UInt32 because wchar_t may not be // wide enough to contain a code point. // If the code_point is not a valid Unicode code point // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted // to "(Invalid Unicode 0xXXXXXXXX)". GTEST_API_ std::string CodePointToUtf8(UInt32 code_point); // Converts a wide string to a narrow string in UTF-8 encoding. // The wide string is assumed to have the following encoding: // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS) // UTF-32 if sizeof(wchar_t) == 4 (on Linux) // Parameter str points to a null-terminated wide string. // Parameter num_chars may additionally limit the number // of wchar_t characters processed. -1 is used when the entire string // should be processed. // If the string contains code points that are not valid Unicode code points // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding // and contains invalid UTF-16 surrogate pairs, values in those pairs // will be encoded as individual Unicode characters from Basic Normal Plane. GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars); // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file // if the variable is present. If a file already exists at this location, this // function will write over it. If the variable is present, but the file cannot // be created, prints an error and exits. void WriteToShardStatusFileIfNeeded(); // Checks whether sharding is enabled by examining the relevant // environment variable values. If the variables are present, // but inconsistent (e.g., shard_index >= total_shards), prints // an error and exits. If in_subprocess_for_death_test, sharding is // disabled because it must only be applied to the original test // process. Otherwise, we could filter out death tests we intended to execute. GTEST_API_ bool ShouldShard(const char* total_shards_str, const char* shard_index_str, bool in_subprocess_for_death_test); // Parses the environment variable var as an Int32. If it is unset, // returns default_val. If it is not an Int32, prints an error and // and aborts. GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val); // Given the total number of shards, the shard index, and the test id, // returns true iff the test should be run on this shard. The test id is // some arbitrary but unique non-negative integer assigned to each test // method. Assumes that 0 <= shard_index < total_shards. GTEST_API_ bool ShouldRunTestOnShard( int total_shards, int shard_index, int test_id); // STL container utilities. // Returns the number of elements in the given container that satisfy // the given predicate. template <class Container, typename Predicate> inline int CountIf(const Container& c, Predicate predicate) { // Implemented as an explicit loop since std::count_if() in libCstd on // Solaris has a non-standard signature. int count = 0; for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) { if (predicate(*it)) ++count; } return count; } // Applies a function/functor to each element in the container. template <class Container, typename Functor> void ForEach(const Container& c, Functor functor) { std::for_each(c.begin(), c.end(), functor); } // Returns the i-th element of the vector, or default_value if i is not // in range [0, v.size()). template <typename E> inline E GetElementOr(const std::vector<E>& v, int i, E default_value) { return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i]; } // Performs an in-place shuffle of a range of the vector's elements. // 'begin' and 'end' are element indices as an STL-style range; // i.e. [begin, end) are shuffled, where 'end' == size() means to // shuffle to the end of the vector. template <typename E> void ShuffleRange(internal::Random* random, int begin, int end, std::vector<E>* v) { const int size = static_cast<int>(v->size()); GTEST_CHECK_(0 <= begin && begin <= size) << "Invalid shuffle range start " << begin << ": must be in range [0, " << size << "]."; GTEST_CHECK_(begin <= end && end <= size) << "Invalid shuffle range finish " << end << ": must be in range [" << begin << ", " << size << "]."; // Fisher-Yates shuffle, from // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle for (int range_width = end - begin; range_width >= 2; range_width--) { const int last_in_range = begin + range_width - 1; const int selected = begin + random->Generate(range_width); std::swap((*v)[selected], (*v)[last_in_range]); } } // Performs an in-place shuffle of the vector's elements. template <typename E> inline void Shuffle(internal::Random* random, std::vector<E>* v) { ShuffleRange(random, 0, static_cast<int>(v->size()), v); } // A function for deleting an object. Handy for being used as a // functor. template <typename T> static void Delete(T* x) { delete x; } // A predicate that checks the key of a TestProperty against a known key. // // TestPropertyKeyIs is copyable. class TestPropertyKeyIs { public: // Constructor. // // TestPropertyKeyIs has NO default constructor. explicit TestPropertyKeyIs(const std::string& key) : key_(key) {} // Returns true iff the test name of test property matches on key_. bool operator()(const TestProperty& test_property) const { return test_property.key() == key_; } private: std::string key_; }; // Class UnitTestOptions. // // This class contains functions for processing options the user // specifies when running the tests. It has only static members. // // In most cases, the user can specify an option using either an // environment variable or a command line flag. E.g. you can set the // test filter using either GTEST_FILTER or --gtest_filter. If both // the variable and the flag are present, the latter overrides the // former. class GTEST_API_ UnitTestOptions { public: // Functions for processing the gtest_output flag. // Returns the output format, or "" for normal printed output. static std::string GetOutputFormat(); // Returns the absolute path of the requested output file, or the // default (test_detail.xml in the original working directory) if // none was explicitly specified. static std::string GetAbsolutePathToOutputFile(); // Functions for processing the gtest_filter flag. // Returns true iff the wildcard pattern matches the string. The // first ':' or '\0' character in pattern marks the end of it. // // This recursive algorithm isn't very efficient, but is clear and // works well enough for matching test names, which are short. static bool PatternMatchesString(const char *pattern, const char *str); // Returns true iff the user-specified filter matches the test case // name and the test name. static bool FilterMatchesTest(const std::string &test_case_name, const std::string &test_name); #if GTEST_OS_WINDOWS // Function for supporting the gtest_catch_exception flag. // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise. // This function is useful as an __except condition. static int GTestShouldProcessSEH(DWORD exception_code); #endif // GTEST_OS_WINDOWS // Returns true if "name" matches the ':' separated list of glob-style // filters in "filter". static bool MatchesFilter(const std::string& name, const char* filter); }; // Returns the current application's name, removing directory path if that // is present. Used by UnitTestOptions::GetOutputFile. GTEST_API_ FilePath GetCurrentExecutableName(); // The role interface for getting the OS stack trace as a string. class OsStackTraceGetterInterface { public: OsStackTraceGetterInterface() {} virtual ~OsStackTraceGetterInterface() {} // Returns the current OS stack trace as an std::string. Parameters: // // max_depth - the maximum number of stack frames to be included // in the trace. // skip_count - the number of top frames to be skipped; doesn't count // against max_depth. virtual string CurrentStackTrace(int max_depth, int skip_count) = 0; // UponLeavingGTest() should be called immediately before Google Test calls // user code. It saves some information about the current stack that // CurrentStackTrace() will use to find and hide Google Test stack frames. virtual void UponLeavingGTest() = 0; // This string is inserted in place of stack frames that are part of // Google Test's implementation. static const char* const kElidedFramesMarker; private: GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface); }; // A working implementation of the OsStackTraceGetterInterface interface. class OsStackTraceGetter : public OsStackTraceGetterInterface { public: OsStackTraceGetter() {} virtual string CurrentStackTrace(int max_depth, int skip_count); virtual void UponLeavingGTest(); private: GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter); }; // Information about a Google Test trace point. struct TraceInfo { const char* file; int line; std::string message; }; // This is the default global test part result reporter used in UnitTestImpl. // This class should only be used by UnitTestImpl. class DefaultGlobalTestPartResultReporter : public TestPartResultReporterInterface { public: explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test); // Implements the TestPartResultReporterInterface. Reports the test part // result in the current test. virtual void ReportTestPartResult(const TestPartResult& result); private: UnitTestImpl* const unit_test_; GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter); }; // This is the default per thread test part result reporter used in // UnitTestImpl. This class should only be used by UnitTestImpl. class DefaultPerThreadTestPartResultReporter : public TestPartResultReporterInterface { public: explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test); // Implements the TestPartResultReporterInterface. The implementation just // delegates to the current global test part result reporter of *unit_test_. virtual void ReportTestPartResult(const TestPartResult& result); private: UnitTestImpl* const unit_test_; GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter); }; // The private implementation of the UnitTest class. We don't protect // the methods under a mutex, as this class is not accessible by a // user and the UnitTest class that delegates work to this class does // proper locking. class GTEST_API_ UnitTestImpl { public: explicit UnitTestImpl(UnitTest* parent); virtual ~UnitTestImpl(); // There are two different ways to register your own TestPartResultReporter. // You can register your own repoter to listen either only for test results // from the current thread or for results from all threads. // By default, each per-thread test result repoter just passes a new // TestPartResult to the global test result reporter, which registers the // test part result for the currently running test. // Returns the global test part result reporter. TestPartResultReporterInterface* GetGlobalTestPartResultReporter(); // Sets the global test part result reporter. void SetGlobalTestPartResultReporter( TestPartResultReporterInterface* reporter); // Returns the test part result reporter for the current thread. TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread(); // Sets the test part result reporter for the current thread. void SetTestPartResultReporterForCurrentThread( TestPartResultReporterInterface* reporter); // Gets the number of successful test cases. int successful_test_case_count() const; // Gets the number of failed test cases. int failed_test_case_count() const; // Gets the number of all test cases. int total_test_case_count() const; // Gets the number of all test cases that contain at least one test // that should run. int test_case_to_run_count() const; // Gets the number of successful tests. int successful_test_count() const; // Gets the number of failed tests. int failed_test_count() const; // Gets the number of disabled tests that will be reported in the XML report. int reportable_disabled_test_count() const; // Gets the number of disabled tests. int disabled_test_count() const; // Gets the number of tests to be printed in the XML report. int reportable_test_count() const; // Gets the number of all tests. int total_test_count() const; // Gets the number of tests that should run. int test_to_run_count() const; // Gets the time of the test program start, in ms from the start of the // UNIX epoch. TimeInMillis start_timestamp() const { return start_timestamp_; } // Gets the elapsed time, in milliseconds. TimeInMillis elapsed_time() const { return elapsed_time_; } // Returns true iff the unit test passed (i.e. all test cases passed). bool Passed() const { return !Failed(); } // Returns true iff the unit test failed (i.e. some test case failed // or something outside of all tests failed). bool Failed() const { return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed(); } // Gets the i-th test case among all the test cases. i can range from 0 to // total_test_case_count() - 1. If i is not in that range, returns NULL. const TestCase* GetTestCase(int i) const { const int index = GetElementOr(test_case_indices_, i, -1); return index < 0 ? NULL : test_cases_[i]; } // Gets the i-th test case among all the test cases. i can range from 0 to // total_test_case_count() - 1. If i is not in that range, returns NULL. TestCase* GetMutableTestCase(int i) { const int index = GetElementOr(test_case_indices_, i, -1); return index < 0 ? NULL : test_cases_[index]; } // Provides access to the event listener list. TestEventListeners* listeners() { return &listeners_; } // Returns the TestResult for the test that's currently running, or // the TestResult for the ad hoc test if no test is running. TestResult* current_test_result(); // Returns the TestResult for the ad hoc test. const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; } // Sets the OS stack trace getter. // // Does nothing if the input and the current OS stack trace getter // are the same; otherwise, deletes the old getter and makes the // input the current getter. void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter); // Returns the current OS stack trace getter if it is not NULL; // otherwise, creates an OsStackTraceGetter, makes it the current // getter, and returns it. OsStackTraceGetterInterface* os_stack_trace_getter(); // Returns the current OS stack trace as an std::string. // // The maximum number of stack frames to be included is specified by // the gtest_stack_trace_depth flag. The skip_count parameter // specifies the number of top frames to be skipped, which doesn't // count against the number of frames to be included. // // For example, if Foo() calls Bar(), which in turn calls // CurrentOsStackTraceExceptTop(1), Foo() will be included in the // trace but Bar() and CurrentOsStackTraceExceptTop() won't. std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_; // Finds and returns a TestCase with the given name. If one doesn't // exist, creates one and returns it. // // Arguments: // // test_case_name: name of the test case // type_param: the name of the test's type parameter, or NULL if // this is not a typed or a type-parameterized test. // set_up_tc: pointer to the function that sets up the test case // tear_down_tc: pointer to the function that tears down the test case TestCase* GetTestCase(const char* test_case_name, const char* type_param, Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc); // Adds a TestInfo to the unit test. // // Arguments: // // set_up_tc: pointer to the function that sets up the test case // tear_down_tc: pointer to the function that tears down the test case // test_info: the TestInfo object void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc, TestInfo* test_info) { // In order to support thread-safe death tests, we need to // remember the original working directory when the test program // was first invoked. We cannot do this in RUN_ALL_TESTS(), as // the user may have changed the current directory before calling // RUN_ALL_TESTS(). Therefore we capture the current directory in // AddTestInfo(), which is called to register a TEST or TEST_F // before main() is reached. if (original_working_dir_.IsEmpty()) { original_working_dir_.Set(FilePath::GetCurrentDir()); GTEST_CHECK_(!original_working_dir_.IsEmpty()) << "Failed to get the current working directory."; } GetTestCase(test_info->test_case_name(), test_info->type_param(), set_up_tc, tear_down_tc)->AddTestInfo(test_info); } #if GTEST_HAS_PARAM_TEST // Returns ParameterizedTestCaseRegistry object used to keep track of // value-parameterized tests and instantiate and register them. internal::ParameterizedTestCaseRegistry& parameterized_test_registry() { return parameterized_test_registry_; } #endif // GTEST_HAS_PARAM_TEST // Sets the TestCase object for the test that's currently running. void set_current_test_case(TestCase* a_current_test_case) { current_test_case_ = a_current_test_case; } // Sets the TestInfo object for the test that's currently running. If // current_test_info is NULL, the assertion results will be stored in // ad_hoc_test_result_. void set_current_test_info(TestInfo* a_current_test_info) { current_test_info_ = a_current_test_info; } // Registers all parameterized tests defined using TEST_P and // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter // combination. This method can be called more then once; it has guards // protecting from registering the tests more then once. If // value-parameterized tests are disabled, RegisterParameterizedTests is // present but does nothing. void RegisterParameterizedTests(); // Runs all tests in this UnitTest object, prints the result, and // returns true if all tests are successful. If any exception is // thrown during a test, this test is considered to be failed, but // the rest of the tests will still be run. bool RunAllTests(); // Clears the results of all tests, except the ad hoc tests. void ClearNonAdHocTestResult() { ForEach(test_cases_, TestCase::ClearTestCaseResult); } // Clears the results of ad-hoc test assertions. void ClearAdHocTestResult() { ad_hoc_test_result_.Clear(); } // Adds a TestProperty to the current TestResult object when invoked in a // context of a test or a test case, or to the global property set. If the // result already contains a property with the same key, the value will be // updated. void RecordProperty(const TestProperty& test_property); enum ReactionToSharding { HONOR_SHARDING_PROTOCOL, IGNORE_SHARDING_PROTOCOL }; // Matches the full name of each test against the user-specified // filter to decide whether the test should run, then records the // result in each TestCase and TestInfo object. // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests // based on sharding variables in the environment. // Returns the number of tests that should run. int FilterTests(ReactionToSharding shard_tests); // Prints the names of the tests matching the user-specified filter flag. void ListTestsMatchingFilter(); const TestCase* current_test_case() const { return current_test_case_; } TestInfo* current_test_info() { return current_test_info_; } const TestInfo* current_test_info() const { return current_test_info_; } // Returns the vector of environments that need to be set-up/torn-down // before/after the tests are run. std::vector<Environment*>& environments() { return environments_; } // Getters for the per-thread Google Test trace stack. std::vector<TraceInfo>& gtest_trace_stack() { return *(gtest_trace_stack_.pointer()); } const std::vector<TraceInfo>& gtest_trace_stack() const { return gtest_trace_stack_.get(); } #if GTEST_HAS_DEATH_TEST void InitDeathTestSubprocessControlInfo() { internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag()); } // Returns a pointer to the parsed --gtest_internal_run_death_test // flag, or NULL if that flag was not specified. // This information is useful only in a death test child process. // Must not be called before a call to InitGoogleTest. const InternalRunDeathTestFlag* internal_run_death_test_flag() const { return internal_run_death_test_flag_.get(); } // Returns a pointer to the current death test factory. internal::DeathTestFactory* death_test_factory() { return death_test_factory_.get(); } void SuppressTestEventsIfInSubprocess(); friend class ReplaceDeathTestFactory; #endif // GTEST_HAS_DEATH_TEST // Initializes the event listener performing XML output as specified by // UnitTestOptions. Must not be called before InitGoogleTest. void ConfigureXmlOutput(); #if GTEST_CAN_STREAM_RESULTS_ // Initializes the event listener for streaming test results to a socket. // Must not be called before InitGoogleTest. void ConfigureStreamingOutput(); #endif // Performs initialization dependent upon flag values obtained in // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest // this function is also called from RunAllTests. Since this function can be // called more than once, it has to be idempotent. void PostFlagParsingInit(); // Gets the random seed used at the start of the current test iteration. int random_seed() const { return random_seed_; } // Gets the random number generator. internal::Random* random() { return &random_; } // Shuffles all test cases, and the tests within each test case, // making sure that death tests are still run first. void ShuffleTests(); // Restores the test cases and tests to their order before the first shuffle. void UnshuffleTests(); // Returns the value of GTEST_FLAG(catch_exceptions) at the moment // UnitTest::Run() starts. bool catch_exceptions() const { return catch_exceptions_; } private: friend class ::testing::UnitTest; // Used by UnitTest::Run() to capture the state of // GTEST_FLAG(catch_exceptions) at the moment it starts. void set_catch_exceptions(bool value) { catch_exceptions_ = value; } // The UnitTest object that owns this implementation object. UnitTest* const parent_; // The working directory when the first TEST() or TEST_F() was // executed. internal::FilePath original_working_dir_; // The default test part result reporters. DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_; DefaultPerThreadTestPartResultReporter default_per_thread_test_part_result_reporter_; // Points to (but doesn't own) the global test part result reporter. TestPartResultReporterInterface* global_test_part_result_repoter_; // Protects read and write access to global_test_part_result_reporter_. internal::Mutex global_test_part_result_reporter_mutex_; // Points to (but doesn't own) the per-thread test part result reporter. internal::ThreadLocal<TestPartResultReporterInterface*> per_thread_test_part_result_reporter_; // The vector of environments that need to be set-up/torn-down // before/after the tests are run. std::vector<Environment*> environments_; // The vector of TestCases in their original order. It owns the // elements in the vector. std::vector<TestCase*> test_cases_; // Provides a level of indirection for the test case list to allow // easy shuffling and restoring the test case order. The i-th // element of this vector is the index of the i-th test case in the // shuffled order. std::vector<int> test_case_indices_; #if GTEST_HAS_PARAM_TEST // ParameterizedTestRegistry object used to register value-parameterized // tests. internal::ParameterizedTestCaseRegistry parameterized_test_registry_; // Indicates whether RegisterParameterizedTests() has been called already. bool parameterized_tests_registered_; #endif // GTEST_HAS_PARAM_TEST // Index of the last death test case registered. Initially -1. int last_death_test_case_; // This points to the TestCase for the currently running test. It // changes as Google Test goes through one test case after another. // When no test is running, this is set to NULL and Google Test // stores assertion results in ad_hoc_test_result_. Initially NULL. TestCase* current_test_case_; // This points to the TestInfo for the currently running test. It // changes as Google Test goes through one test after another. When // no test is running, this is set to NULL and Google Test stores // assertion results in ad_hoc_test_result_. Initially NULL. TestInfo* current_test_info_; // Normally, a user only writes assertions inside a TEST or TEST_F, // or inside a function called by a TEST or TEST_F. Since Google // Test keeps track of which test is current running, it can // associate such an assertion with the test it belongs to. // // If an assertion is encountered when no TEST or TEST_F is running, // Google Test attributes the assertion result to an imaginary "ad hoc" // test, and records the result in ad_hoc_test_result_. TestResult ad_hoc_test_result_; // The list of event listeners that can be used to track events inside // Google Test. TestEventListeners listeners_; // The OS stack trace getter. Will be deleted when the UnitTest // object is destructed. By default, an OsStackTraceGetter is used, // but the user can set this field to use a custom getter if that is // desired. OsStackTraceGetterInterface* os_stack_trace_getter_; // True iff PostFlagParsingInit() has been called. bool post_flag_parse_init_performed_; // The random number seed used at the beginning of the test run. int random_seed_; // Our random number generator. internal::Random random_; // The time of the test program start, in ms from the start of the // UNIX epoch. TimeInMillis start_timestamp_; // How long the test took to run, in milliseconds. TimeInMillis elapsed_time_; #if GTEST_HAS_DEATH_TEST // The decomposed components of the gtest_internal_run_death_test flag, // parsed when RUN_ALL_TESTS is called. internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_; internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_; #endif // GTEST_HAS_DEATH_TEST // A per-thread stack of traces created by the SCOPED_TRACE() macro. internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_; // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests() // starts. bool catch_exceptions_; GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl); }; // class UnitTestImpl // Convenience function for accessing the global UnitTest // implementation object. inline UnitTestImpl* GetUnitTestImpl() { return UnitTest::GetInstance()->impl(); } #if GTEST_USES_SIMPLE_RE // Internal helper functions for implementing the simple regular // expression matcher. GTEST_API_ bool IsInSet(char ch, const char* str); GTEST_API_ bool IsAsciiDigit(char ch); GTEST_API_ bool IsAsciiPunct(char ch); GTEST_API_ bool IsRepeat(char ch); GTEST_API_ bool IsAsciiWhiteSpace(char ch); GTEST_API_ bool IsAsciiWordChar(char ch); GTEST_API_ bool IsValidEscape(char ch); GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch); GTEST_API_ bool ValidateRegex(const char* regex); GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str); GTEST_API_ bool MatchRepetitionAndRegexAtHead( bool escaped, char ch, char repeat, const char* regex, const char* str); GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str); #endif // GTEST_USES_SIMPLE_RE // Parses the command line for Google Test flags, without initializing // other parts of Google Test. GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv); GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv); #if GTEST_HAS_DEATH_TEST // Returns the message describing the last system error, regardless of the // platform. GTEST_API_ std::string GetLastErrnoDescription(); // Attempts to parse a string into a positive integer pointed to by the // number parameter. Returns true if that is possible. // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use // it here. template <typename Integer> bool ParseNaturalNumber(const ::std::string& str, Integer* number) { // Fail fast if the given string does not begin with a digit; // this bypasses strtoXXX's "optional leading whitespace and plus // or minus sign" semantics, which are undesirable here. if (str.empty() || !IsDigit(str[0])) { return false; } errno = 0; char* end; // BiggestConvertible is the largest integer type that system-provided // string-to-number conversion routines can return. # if GTEST_OS_WINDOWS && !defined(__GNUC__) // MSVC and C++ Builder define __int64 instead of the standard long long. typedef unsigned __int64 BiggestConvertible; const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10); # else typedef unsigned long long BiggestConvertible; // NOLINT const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10); # endif // GTEST_OS_WINDOWS && !defined(__GNUC__) const bool parse_success = *end == '\0' && errno == 0; // TODO([email protected]): Convert this to compile time assertion when it is // available. GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed)); const Integer result = static_cast<Integer>(parsed); if (parse_success && static_cast<BiggestConvertible>(result) == parsed) { *number = result; return true; } return false; } #endif // GTEST_HAS_DEATH_TEST // TestResult contains some private methods that should be hidden from // Google Test user but are required for testing. This class allow our tests // to access them. // // This class is supplied only for the purpose of testing Google Test's own // constructs. Do not use it in user tests, either directly or indirectly. class TestResultAccessor { public: static void RecordProperty(TestResult* test_result, const std::string& xml_element, const TestProperty& property) { test_result->RecordProperty(xml_element, property); } static void ClearTestPartResults(TestResult* test_result) { test_result->ClearTestPartResults(); } static const std::vector<testing::TestPartResult>& test_part_results( const TestResult& test_result) { return test_result.test_part_results(); } }; #if GTEST_CAN_STREAM_RESULTS_ // Streams test results to the given port on the given host machine. class GTEST_API_ StreamingListener : public EmptyTestEventListener { public: // Abstract base class for writing strings to a socket. class AbstractSocketWriter { public: virtual ~AbstractSocketWriter() {} // Sends a string to the socket. virtual void Send(const string& message) = 0; // Closes the socket. virtual void CloseConnection() {} // Sends a string and a newline to the socket. void SendLn(const string& message) { Send(message + "\n"); } }; // Concrete class for actually writing strings to a socket. class SocketWriter : public AbstractSocketWriter { public: SocketWriter(const string& host, const string& port) : sockfd_(-1), host_name_(host), port_num_(port) { MakeConnection(); } virtual ~SocketWriter() { if (sockfd_ != -1) CloseConnection(); } // Sends a string to the socket. virtual void Send(const string& message) { GTEST_CHECK_(sockfd_ != -1) << "Send() can be called only when there is a connection."; const int len = static_cast<int>(message.length()); if (write(sockfd_, message.c_str(), len) != len) { GTEST_LOG_(WARNING) << "stream_result_to: failed to stream to " << host_name_ << ":" << port_num_; } } private: // Creates a client socket and connects to the server. void MakeConnection(); // Closes the socket. void CloseConnection() { GTEST_CHECK_(sockfd_ != -1) << "CloseConnection() can be called only when there is a connection."; close(sockfd_); sockfd_ = -1; } int sockfd_; // socket file descriptor const string host_name_; const string port_num_; GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter); }; // class SocketWriter // Escapes '=', '&', '%', and '\n' characters in str as "%xx". static string UrlEncode(const char* str); StreamingListener(const string& host, const string& port) : socket_writer_(new SocketWriter(host, port)) { Start(); } explicit StreamingListener(AbstractSocketWriter* socket_writer) : socket_writer_(socket_writer) { Start(); } void OnTestProgramStart(const UnitTest& /* unit_test */) { SendLn("event=TestProgramStart"); } void OnTestProgramEnd(const UnitTest& unit_test) { // Note that Google Test current only report elapsed time for each // test iteration, not for the entire test program. SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed())); // Notify the streaming server to stop. socket_writer_->CloseConnection(); } void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) { SendLn("event=TestIterationStart&iteration=" + StreamableToString(iteration)); } void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) { SendLn("event=TestIterationEnd&passed=" + FormatBool(unit_test.Passed()) + "&elapsed_time=" + StreamableToString(unit_test.elapsed_time()) + "ms"); } void OnTestCaseStart(const TestCase& test_case) { SendLn(std::string("event=TestCaseStart&name=") + test_case.name()); } void OnTestCaseEnd(const TestCase& test_case) { SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed()) + "&elapsed_time=" + StreamableToString(test_case.elapsed_time()) + "ms"); } void OnTestStart(const TestInfo& test_info) { SendLn(std::string("event=TestStart&name=") + test_info.name()); } void OnTestEnd(const TestInfo& test_info) { SendLn("event=TestEnd&passed=" + FormatBool((test_info.result())->Passed()) + "&elapsed_time=" + StreamableToString((test_info.result())->elapsed_time()) + "ms"); } void OnTestPartResult(const TestPartResult& test_part_result) { const char* file_name = test_part_result.file_name(); if (file_name == NULL) file_name = ""; SendLn("event=TestPartResult&file=" + UrlEncode(file_name) + "&line=" + StreamableToString(test_part_result.line_number()) + "&message=" + UrlEncode(test_part_result.message())); } private: // Sends the given message and a newline to the socket. void SendLn(const string& message) { socket_writer_->SendLn(message); } // Called at the start of streaming to notify the receiver what // protocol we are using. void Start() { SendLn("gtest_streaming_protocol_version=1.0"); } string FormatBool(bool value) { return value ? "1" : "0"; } const scoped_ptr<AbstractSocketWriter> socket_writer_; GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener); }; // class StreamingListener #endif // GTEST_CAN_STREAM_RESULTS_ } // namespace internal } // namespace testing #endif // GTEST_SRC_GTEST_INTERNAL_INL_H_
0
repos/DirectXShaderCompiler/utils/unittest
repos/DirectXShaderCompiler/utils/unittest/googlemock/LICENSE.txt
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
repos/DirectXShaderCompiler/utils/unittest/googlemock/include
repos/DirectXShaderCompiler/utils/unittest/googlemock/include/gmock/gmock-spec-builders.h
// 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. // // Author: [email protected] (Zhanyong Wan) // Google Mock - a framework for writing C++ mock classes. // // This file implements the ON_CALL() and EXPECT_CALL() macros. // // A user can use the ON_CALL() macro to specify the default action of // a mock method. The syntax is: // // ON_CALL(mock_object, Method(argument-matchers)) // .With(multi-argument-matcher) // .WillByDefault(action); // // where the .With() clause is optional. // // A user can use the EXPECT_CALL() macro to specify an expectation on // a mock method. The syntax is: // // EXPECT_CALL(mock_object, Method(argument-matchers)) // .With(multi-argument-matchers) // .Times(cardinality) // .InSequence(sequences) // .After(expectations) // .WillOnce(action) // .WillRepeatedly(action) // .RetiresOnSaturation(); // // where all clauses are optional, and .InSequence()/.After()/ // .WillOnce() can appear any number of times. #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_ #include <map> #include <set> #include <sstream> #include <string> #include <vector> #if GTEST_HAS_EXCEPTIONS # include <stdexcept> // NOLINT #endif #include "gmock/gmock-actions.h" #include "gmock/gmock-cardinalities.h" #include "gmock/gmock-matchers.h" #include "gmock/internal/gmock-internal-utils.h" #include "gmock/internal/gmock-port.h" #include "gtest/gtest.h" namespace testing { // An abstract handle of an expectation. class Expectation; // A set of expectation handles. class ExpectationSet; // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION // and MUST NOT BE USED IN USER CODE!!! namespace internal { // Implements a mock function. template <typename F> class FunctionMocker; // Base class for expectations. class ExpectationBase; // Implements an expectation. template <typename F> class TypedExpectation; // Helper class for testing the Expectation class template. class ExpectationTester; // Base class for function mockers. template <typename F> class FunctionMockerBase; // Protects the mock object registry (in class Mock), all function // mockers, and all expectations. // // The reason we don't use more fine-grained protection is: when a // mock function Foo() is called, it needs to consult its expectations // to see which one should be picked. If another thread is allowed to // call a mock function (either Foo() or a different one) at the same // time, it could affect the "retired" attributes of Foo()'s // expectations when InSequence() is used, and thus affect which // expectation gets picked. Therefore, we sequence all mock function // calls to ensure the integrity of the mock objects' states. GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex); // Untyped base class for ActionResultHolder<R>. class UntypedActionResultHolderBase; // Abstract base class of FunctionMockerBase. This is the // type-agnostic part of the function mocker interface. Its pure // virtual methods are implemented by FunctionMockerBase. class GTEST_API_ UntypedFunctionMockerBase { public: UntypedFunctionMockerBase(); virtual ~UntypedFunctionMockerBase(); // Verifies that all expectations on this mock function have been // satisfied. Reports one or more Google Test non-fatal failures // and returns false if not. bool VerifyAndClearExpectationsLocked() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); // Clears the ON_CALL()s set on this mock function. virtual void ClearDefaultActionsLocked() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0; // In all of the following Untyped* functions, it's the caller's // responsibility to guarantee the correctness of the arguments' // types. // Performs the default action with the given arguments and returns // the action's result. The call description string will be used in // the error message to describe the call in the case the default // action fails. // L = * virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction( const void* untyped_args, const string& call_description) const = 0; // Performs the given action with the given arguments and returns // the action's result. // L = * virtual UntypedActionResultHolderBase* UntypedPerformAction( const void* untyped_action, const void* untyped_args) const = 0; // Writes a message that the call is uninteresting (i.e. neither // explicitly expected nor explicitly unexpected) to the given // ostream. virtual void UntypedDescribeUninterestingCall( const void* untyped_args, ::std::ostream* os) const GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0; // Returns the expectation that matches the given function arguments // (or NULL is there's no match); when a match is found, // untyped_action is set to point to the action that should be // performed (or NULL if the action is "do default"), and // is_excessive is modified to indicate whether the call exceeds the // expected number. virtual const ExpectationBase* UntypedFindMatchingExpectation( const void* untyped_args, const void** untyped_action, bool* is_excessive, ::std::ostream* what, ::std::ostream* why) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0; // Prints the given function arguments to the ostream. virtual void UntypedPrintArgs(const void* untyped_args, ::std::ostream* os) const = 0; // Sets the mock object this mock method belongs to, and registers // this information in the global mock registry. Will be called // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock // method. // TODO([email protected]): rename to SetAndRegisterOwner(). void RegisterOwner(const void* mock_obj) GTEST_LOCK_EXCLUDED_(g_gmock_mutex); // Sets the mock object this mock method belongs to, and sets the // name of the mock function. Will be called upon each invocation // of this mock function. void SetOwnerAndName(const void* mock_obj, const char* name) GTEST_LOCK_EXCLUDED_(g_gmock_mutex); // Returns the mock object this mock method belongs to. Must be // called after RegisterOwner() or SetOwnerAndName() has been // called. const void* MockObject() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex); // Returns the name of this mock method. Must be called after // SetOwnerAndName() has been called. const char* Name() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex); // Returns the result of invoking this mock function with the given // arguments. This function can be safely called from multiple // threads concurrently. The caller is responsible for deleting the // result. UntypedActionResultHolderBase* UntypedInvokeWith( const void* untyped_args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex); protected: typedef std::vector<const void*> UntypedOnCallSpecs; typedef std::vector<internal::linked_ptr<ExpectationBase> > UntypedExpectations; // Returns an Expectation object that references and co-owns exp, // which must be an expectation on this mock function. Expectation GetHandleOf(ExpectationBase* exp); // Address of the mock object this mock method belongs to. Only // valid after this mock method has been called or // ON_CALL/EXPECT_CALL has been invoked on it. const void* mock_obj_; // Protected by g_gmock_mutex. // Name of the function being mocked. Only valid after this mock // method has been called. const char* name_; // Protected by g_gmock_mutex. // All default action specs for this function mocker. UntypedOnCallSpecs untyped_on_call_specs_; // All expectations for this function mocker. UntypedExpectations untyped_expectations_; }; // class UntypedFunctionMockerBase // Untyped base class for OnCallSpec<F>. class UntypedOnCallSpecBase { public: // The arguments are the location of the ON_CALL() statement. UntypedOnCallSpecBase(const char* a_file, int a_line) : file_(a_file), line_(a_line), last_clause_(kNone) {} // Where in the source file was the default action spec defined? const char* file() const { return file_; } int line() const { return line_; } protected: // Gives each clause in the ON_CALL() statement a name. enum Clause { // Do not change the order of the enum members! The run-time // syntax checking relies on it. kNone, kWith, kWillByDefault }; // Asserts that the ON_CALL() statement has a certain property. void AssertSpecProperty(bool property, const string& failure_message) const { Assert(property, file_, line_, failure_message); } // Expects that the ON_CALL() statement has a certain property. void ExpectSpecProperty(bool property, const string& failure_message) const { Expect(property, file_, line_, failure_message); } const char* file_; int line_; // The last clause in the ON_CALL() statement as seen so far. // Initially kNone and changes as the statement is parsed. Clause last_clause_; }; // class UntypedOnCallSpecBase // This template class implements an ON_CALL spec. template <typename F> class OnCallSpec : public UntypedOnCallSpecBase { public: typedef typename Function<F>::ArgumentTuple ArgumentTuple; typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple; // Constructs an OnCallSpec object from the information inside // the parenthesis of an ON_CALL() statement. OnCallSpec(const char* a_file, int a_line, const ArgumentMatcherTuple& matchers) : UntypedOnCallSpecBase(a_file, a_line), matchers_(matchers), // By default, extra_matcher_ should match anything. However, // we cannot initialize it with _ as that triggers a compiler // bug in Symbian's C++ compiler (cannot decide between two // overloaded constructors of Matcher<const ArgumentTuple&>). extra_matcher_(A<const ArgumentTuple&>()) { } // Implements the .With() clause. OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) { // Makes sure this is called at most once. ExpectSpecProperty(last_clause_ < kWith, ".With() cannot appear " "more than once in an ON_CALL()."); last_clause_ = kWith; extra_matcher_ = m; return *this; } // Implements the .WillByDefault() clause. OnCallSpec& WillByDefault(const Action<F>& action) { ExpectSpecProperty(last_clause_ < kWillByDefault, ".WillByDefault() must appear " "exactly once in an ON_CALL()."); last_clause_ = kWillByDefault; ExpectSpecProperty(!action.IsDoDefault(), "DoDefault() cannot be used in ON_CALL()."); action_ = action; return *this; } // Returns true iff the given arguments match the matchers. bool Matches(const ArgumentTuple& args) const { return TupleMatches(matchers_, args) && extra_matcher_.Matches(args); } // Returns the action specified by the user. const Action<F>& GetAction() const { AssertSpecProperty(last_clause_ == kWillByDefault, ".WillByDefault() must appear exactly " "once in an ON_CALL()."); return action_; } private: // The information in statement // // ON_CALL(mock_object, Method(matchers)) // .With(multi-argument-matcher) // .WillByDefault(action); // // is recorded in the data members like this: // // source file that contains the statement => file_ // line number of the statement => line_ // matchers => matchers_ // multi-argument-matcher => extra_matcher_ // action => action_ ArgumentMatcherTuple matchers_; Matcher<const ArgumentTuple&> extra_matcher_; Action<F> action_; }; // class OnCallSpec // Possible reactions on uninteresting calls. enum CallReaction { kAllow, kWarn, kFail, kDefault = kWarn // By default, warn about uninteresting calls. }; } // namespace internal // Utilities for manipulating mock objects. class GTEST_API_ Mock { public: // The following public methods can be called concurrently. // Tells Google Mock to ignore mock_obj when checking for leaked // mock objects. static void AllowLeak(const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Verifies and clears all expectations on the given mock object. // If the expectations aren't satisfied, generates one or more // Google Test non-fatal failures and returns false. static bool VerifyAndClearExpectations(void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Verifies all expectations on the given mock object and clears its // default actions and expectations. Returns true iff the // verification was successful. static bool VerifyAndClear(void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); private: friend class internal::UntypedFunctionMockerBase; // Needed for a function mocker to register itself (so that we know // how to clear a mock object). template <typename F> friend class internal::FunctionMockerBase; template <typename M> friend class NiceMock; template <typename M> friend class NaggyMock; template <typename M> friend class StrictMock; // Tells Google Mock to allow uninteresting calls on the given mock // object. static void AllowUninterestingCalls(const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Tells Google Mock to warn the user about uninteresting calls on // the given mock object. static void WarnUninterestingCalls(const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Tells Google Mock to fail uninteresting calls on the given mock // object. static void FailUninterestingCalls(const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Tells Google Mock the given mock object is being destroyed and // its entry in the call-reaction table should be removed. static void UnregisterCallReaction(const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Returns the reaction Google Mock will have on uninteresting calls // made on the given mock object. static internal::CallReaction GetReactionOnUninterestingCalls( const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Verifies that all expectations on the given mock object have been // satisfied. Reports one or more Google Test non-fatal failures // and returns false if not. static bool VerifyAndClearExpectationsLocked(void* mock_obj) GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex); // Clears all ON_CALL()s set on the given mock object. static void ClearDefaultActionsLocked(void* mock_obj) GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex); // Registers a mock object and a mock method it owns. static void Register( const void* mock_obj, internal::UntypedFunctionMockerBase* mocker) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Tells Google Mock where in the source code mock_obj is used in an // ON_CALL or EXPECT_CALL. In case mock_obj is leaked, this // information helps the user identify which object it is. static void RegisterUseByOnCallOrExpectCall( const void* mock_obj, const char* file, int line) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex); // Unregisters a mock method; removes the owning mock object from // the registry when the last mock method associated with it has // been unregistered. This is called only in the destructor of // FunctionMockerBase. static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker) GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex); }; // class Mock // An abstract handle of an expectation. Useful in the .After() // clause of EXPECT_CALL() for setting the (partial) order of // expectations. The syntax: // // Expectation e1 = EXPECT_CALL(...)...; // EXPECT_CALL(...).After(e1)...; // // sets two expectations where the latter can only be matched after // the former has been satisfied. // // Notes: // - This class is copyable and has value semantics. // - Constness is shallow: a const Expectation object itself cannot // be modified, but the mutable methods of the ExpectationBase // object it references can be called via expectation_base(). // - The constructors and destructor are defined out-of-line because // the Symbian WINSCW compiler wants to otherwise instantiate them // when it sees this class definition, at which point it doesn't have // ExpectationBase available yet, leading to incorrect destruction // in the linked_ptr (or compilation errors if using a checking // linked_ptr). class GTEST_API_ Expectation { public: // Constructs a null object that doesn't reference any expectation. Expectation(); ~Expectation(); // This single-argument ctor must not be explicit, in order to support the // Expectation e = EXPECT_CALL(...); // syntax. // // A TypedExpectation object stores its pre-requisites as // Expectation objects, and needs to call the non-const Retire() // method on the ExpectationBase objects they reference. Therefore // Expectation must receive a *non-const* reference to the // ExpectationBase object. Expectation(internal::ExpectationBase& exp); // NOLINT // The compiler-generated copy ctor and operator= work exactly as // intended, so we don't need to define our own. // Returns true iff rhs references the same expectation as this object does. bool operator==(const Expectation& rhs) const { return expectation_base_ == rhs.expectation_base_; } bool operator!=(const Expectation& rhs) const { return !(*this == rhs); } private: friend class ExpectationSet; friend class Sequence; friend class ::testing::internal::ExpectationBase; friend class ::testing::internal::UntypedFunctionMockerBase; template <typename F> friend class ::testing::internal::FunctionMockerBase; template <typename F> friend class ::testing::internal::TypedExpectation; // This comparator is needed for putting Expectation objects into a set. class Less { public: bool operator()(const Expectation& lhs, const Expectation& rhs) const { return lhs.expectation_base_.get() < rhs.expectation_base_.get(); } }; typedef ::std::set<Expectation, Less> Set; Expectation( const internal::linked_ptr<internal::ExpectationBase>& expectation_base); // Returns the expectation this object references. const internal::linked_ptr<internal::ExpectationBase>& expectation_base() const { return expectation_base_; } // A linked_ptr that co-owns the expectation this handle references. internal::linked_ptr<internal::ExpectationBase> expectation_base_; }; // A set of expectation handles. Useful in the .After() clause of // EXPECT_CALL() for setting the (partial) order of expectations. The // syntax: // // ExpectationSet es; // es += EXPECT_CALL(...)...; // es += EXPECT_CALL(...)...; // EXPECT_CALL(...).After(es)...; // // sets three expectations where the last one can only be matched // after the first two have both been satisfied. // // This class is copyable and has value semantics. class ExpectationSet { public: // A bidirectional iterator that can read a const element in the set. typedef Expectation::Set::const_iterator const_iterator; // An object stored in the set. This is an alias of Expectation. typedef Expectation::Set::value_type value_type; // Constructs an empty set. ExpectationSet() {} // This single-argument ctor must not be explicit, in order to support the // ExpectationSet es = EXPECT_CALL(...); // syntax. ExpectationSet(internal::ExpectationBase& exp) { // NOLINT *this += Expectation(exp); } // This single-argument ctor implements implicit conversion from // Expectation and thus must not be explicit. This allows either an // Expectation or an ExpectationSet to be used in .After(). ExpectationSet(const Expectation& e) { // NOLINT *this += e; } // The compiler-generator ctor and operator= works exactly as // intended, so we don't need to define our own. // Returns true iff rhs contains the same set of Expectation objects // as this does. bool operator==(const ExpectationSet& rhs) const { return expectations_ == rhs.expectations_; } bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); } // Implements the syntax // expectation_set += EXPECT_CALL(...); ExpectationSet& operator+=(const Expectation& e) { expectations_.insert(e); return *this; } int size() const { return static_cast<int>(expectations_.size()); } const_iterator begin() const { return expectations_.begin(); } const_iterator end() const { return expectations_.end(); } private: Expectation::Set expectations_; }; // Sequence objects are used by a user to specify the relative order // in which the expectations should match. They are copyable (we rely // on the compiler-defined copy constructor and assignment operator). class GTEST_API_ Sequence { public: // Constructs an empty sequence. Sequence() : last_expectation_(new Expectation) {} // Adds an expectation to this sequence. The caller must ensure // that no other thread is accessing this Sequence object. void AddExpectation(const Expectation& expectation) const; private: // The last expectation in this sequence. We use a linked_ptr here // because Sequence objects are copyable and we want the copies to // be aliases. The linked_ptr allows the copies to co-own and share // the same Expectation object. internal::linked_ptr<Expectation> last_expectation_; }; // class Sequence // An object of this type causes all EXPECT_CALL() statements // encountered in its scope to be put in an anonymous sequence. The // work is done in the constructor and destructor. You should only // create an InSequence object on the stack. // // The sole purpose for this class is to support easy definition of // sequential expectations, e.g. // // { // InSequence dummy; // The name of the object doesn't matter. // // // The following expectations must match in the order they appear. // EXPECT_CALL(a, Bar())...; // EXPECT_CALL(a, Baz())...; // ... // EXPECT_CALL(b, Xyz())...; // } // // You can create InSequence objects in multiple threads, as long as // they are used to affect different mock objects. The idea is that // each thread can create and set up its own mocks as if it's the only // thread. However, for clarity of your tests we recommend you to set // up mocks in the main thread unless you have a good reason not to do // so. class GTEST_API_ InSequence { public: InSequence(); ~InSequence(); private: bool sequence_created_; GTEST_DISALLOW_COPY_AND_ASSIGN_(InSequence); // NOLINT } GTEST_ATTRIBUTE_UNUSED_; namespace internal { // Points to the implicit sequence introduced by a living InSequence // object (if any) in the current thread or NULL. GTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence; // Base class for implementing expectations. // // There are two reasons for having a type-agnostic base class for // Expectation: // // 1. We need to store collections of expectations of different // types (e.g. all pre-requisites of a particular expectation, all // expectations in a sequence). Therefore these expectation objects // must share a common base class. // // 2. We can avoid binary code bloat by moving methods not depending // on the template argument of Expectation to the base class. // // This class is internal and mustn't be used by user code directly. class GTEST_API_ ExpectationBase { public: // source_text is the EXPECT_CALL(...) source that created this Expectation. ExpectationBase(const char* file, int line, const string& source_text); virtual ~ExpectationBase(); // Where in the source file was the expectation spec defined? const char* file() const { return file_; } int line() const { return line_; } const char* source_text() const { return source_text_.c_str(); } // Returns the cardinality specified in the expectation spec. const Cardinality& cardinality() const { return cardinality_; } // Describes the source file location of this expectation. void DescribeLocationTo(::std::ostream* os) const { *os << FormatFileLocation(file(), line()) << " "; } // Describes how many times a function call matching this // expectation has occurred. void DescribeCallCountTo(::std::ostream* os) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); // If this mock method has an extra matcher (i.e. .With(matcher)), // describes it to the ostream. virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0; protected: friend class ::testing::Expectation; friend class UntypedFunctionMockerBase; enum Clause { // Don't change the order of the enum members! kNone, kWith, kTimes, kInSequence, kAfter, kWillOnce, kWillRepeatedly, kRetiresOnSaturation }; typedef std::vector<const void*> UntypedActions; // Returns an Expectation object that references and co-owns this // expectation. virtual Expectation GetHandle() = 0; // Asserts that the EXPECT_CALL() statement has the given property. void AssertSpecProperty(bool property, const string& failure_message) const { Assert(property, file_, line_, failure_message); } // Expects that the EXPECT_CALL() statement has the given property. void ExpectSpecProperty(bool property, const string& failure_message) const { Expect(property, file_, line_, failure_message); } // Explicitly specifies the cardinality of this expectation. Used // by the subclasses to implement the .Times() clause. void SpecifyCardinality(const Cardinality& cardinality); // Returns true iff the user specified the cardinality explicitly // using a .Times(). bool cardinality_specified() const { return cardinality_specified_; } // Sets the cardinality of this expectation spec. void set_cardinality(const Cardinality& a_cardinality) { cardinality_ = a_cardinality; } // The following group of methods should only be called after the // EXPECT_CALL() statement, and only when g_gmock_mutex is held by // the current thread. // Retires all pre-requisites of this expectation. void RetireAllPreRequisites() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); // Returns true iff this expectation is retired. bool is_retired() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return retired_; } // Retires this expectation. void Retire() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); retired_ = true; } // Returns true iff this expectation is satisfied. bool IsSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return cardinality().IsSatisfiedByCallCount(call_count_); } // Returns true iff this expectation is saturated. bool IsSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return cardinality().IsSaturatedByCallCount(call_count_); } // Returns true iff this expectation is over-saturated. bool IsOverSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return cardinality().IsOverSaturatedByCallCount(call_count_); } // Returns true iff all pre-requisites of this expectation are satisfied. bool AllPrerequisitesAreSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); // Adds unsatisfied pre-requisites of this expectation to 'result'. void FindUnsatisfiedPrerequisites(ExpectationSet* result) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex); // Returns the number this expectation has been invoked. int call_count() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return call_count_; } // Increments the number this expectation has been invoked. void IncrementCallCount() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); call_count_++; } // Checks the action count (i.e. the number of WillOnce() and // WillRepeatedly() clauses) against the cardinality if this hasn't // been done before. Prints a warning if there are too many or too // few actions. void CheckActionCountIfNotDone() const GTEST_LOCK_EXCLUDED_(mutex_); friend class ::testing::Sequence; friend class ::testing::internal::ExpectationTester; template <typename Function> friend class TypedExpectation; // Implements the .Times() clause. void UntypedTimes(const Cardinality& a_cardinality); // This group of fields are part of the spec and won't change after // an EXPECT_CALL() statement finishes. const char* file_; // The file that contains the expectation. int line_; // The line number of the expectation. const string source_text_; // The EXPECT_CALL(...) source text. // True iff the cardinality is specified explicitly. bool cardinality_specified_; Cardinality cardinality_; // The cardinality of the expectation. // The immediate pre-requisites (i.e. expectations that must be // satisfied before this expectation can be matched) of this // expectation. We use linked_ptr in the set because we want an // Expectation object to be co-owned by its FunctionMocker and its // successors. This allows multiple mock objects to be deleted at // different times. ExpectationSet immediate_prerequisites_; // This group of fields are the current state of the expectation, // and can change as the mock function is called. int call_count_; // How many times this expectation has been invoked. bool retired_; // True iff this expectation has retired. UntypedActions untyped_actions_; bool extra_matcher_specified_; bool repeated_action_specified_; // True if a WillRepeatedly() was specified. bool retires_on_saturation_; Clause last_clause_; mutable bool action_count_checked_; // Under mutex_. mutable Mutex mutex_; // Protects action_count_checked_. GTEST_DISALLOW_ASSIGN_(ExpectationBase); }; // class ExpectationBase // Impements an expectation for the given function type. template <typename F> class TypedExpectation : public ExpectationBase { public: typedef typename Function<F>::ArgumentTuple ArgumentTuple; typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple; typedef typename Function<F>::Result Result; TypedExpectation(FunctionMockerBase<F>* owner, const char* a_file, int a_line, const string& a_source_text, const ArgumentMatcherTuple& m) : ExpectationBase(a_file, a_line, a_source_text), owner_(owner), matchers_(m), // By default, extra_matcher_ should match anything. However, // we cannot initialize it with _ as that triggers a compiler // bug in Symbian's C++ compiler (cannot decide between two // overloaded constructors of Matcher<const ArgumentTuple&>). extra_matcher_(A<const ArgumentTuple&>()), repeated_action_(DoDefault()) {} virtual ~TypedExpectation() { // Check the validity of the action count if it hasn't been done // yet (for example, if the expectation was never used). CheckActionCountIfNotDone(); for (UntypedActions::const_iterator it = untyped_actions_.begin(); it != untyped_actions_.end(); ++it) { delete static_cast<const Action<F>*>(*it); } } // Implements the .With() clause. TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) { if (last_clause_ == kWith) { ExpectSpecProperty(false, ".With() cannot appear " "more than once in an EXPECT_CALL()."); } else { ExpectSpecProperty(last_clause_ < kWith, ".With() must be the first " "clause in an EXPECT_CALL()."); } last_clause_ = kWith; extra_matcher_ = m; extra_matcher_specified_ = true; return *this; } // Implements the .Times() clause. TypedExpectation& Times(const Cardinality& a_cardinality) { ExpectationBase::UntypedTimes(a_cardinality); return *this; } // Implements the .Times() clause. TypedExpectation& Times(int n) { return Times(Exactly(n)); } // Implements the .InSequence() clause. TypedExpectation& InSequence(const Sequence& s) { ExpectSpecProperty(last_clause_ <= kInSequence, ".InSequence() cannot appear after .After()," " .WillOnce(), .WillRepeatedly(), or " ".RetiresOnSaturation()."); last_clause_ = kInSequence; s.AddExpectation(GetHandle()); return *this; } TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) { return InSequence(s1).InSequence(s2); } TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2, const Sequence& s3) { return InSequence(s1, s2).InSequence(s3); } TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2, const Sequence& s3, const Sequence& s4) { return InSequence(s1, s2, s3).InSequence(s4); } TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2, const Sequence& s3, const Sequence& s4, const Sequence& s5) { return InSequence(s1, s2, s3, s4).InSequence(s5); } // Implements that .After() clause. TypedExpectation& After(const ExpectationSet& s) { ExpectSpecProperty(last_clause_ <= kAfter, ".After() cannot appear after .WillOnce()," " .WillRepeatedly(), or " ".RetiresOnSaturation()."); last_clause_ = kAfter; for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) { immediate_prerequisites_ += *it; } return *this; } TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) { return After(s1).After(s2); } TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2, const ExpectationSet& s3) { return After(s1, s2).After(s3); } TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2, const ExpectationSet& s3, const ExpectationSet& s4) { return After(s1, s2, s3).After(s4); } TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2, const ExpectationSet& s3, const ExpectationSet& s4, const ExpectationSet& s5) { return After(s1, s2, s3, s4).After(s5); } // Implements the .WillOnce() clause. TypedExpectation& WillOnce(const Action<F>& action) { ExpectSpecProperty(last_clause_ <= kWillOnce, ".WillOnce() cannot appear after " ".WillRepeatedly() or .RetiresOnSaturation()."); last_clause_ = kWillOnce; untyped_actions_.push_back(new Action<F>(action)); if (!cardinality_specified()) { set_cardinality(Exactly(static_cast<int>(untyped_actions_.size()))); } return *this; } // Implements the .WillRepeatedly() clause. TypedExpectation& WillRepeatedly(const Action<F>& action) { if (last_clause_ == kWillRepeatedly) { ExpectSpecProperty(false, ".WillRepeatedly() cannot appear " "more than once in an EXPECT_CALL()."); } else { ExpectSpecProperty(last_clause_ < kWillRepeatedly, ".WillRepeatedly() cannot appear " "after .RetiresOnSaturation()."); } last_clause_ = kWillRepeatedly; repeated_action_specified_ = true; repeated_action_ = action; if (!cardinality_specified()) { set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size()))); } // Now that no more action clauses can be specified, we check // whether their count makes sense. CheckActionCountIfNotDone(); return *this; } // Implements the .RetiresOnSaturation() clause. TypedExpectation& RetiresOnSaturation() { ExpectSpecProperty(last_clause_ < kRetiresOnSaturation, ".RetiresOnSaturation() cannot appear " "more than once."); last_clause_ = kRetiresOnSaturation; retires_on_saturation_ = true; // Now that no more action clauses can be specified, we check // whether their count makes sense. CheckActionCountIfNotDone(); return *this; } // Returns the matchers for the arguments as specified inside the // EXPECT_CALL() macro. const ArgumentMatcherTuple& matchers() const { return matchers_; } // Returns the matcher specified by the .With() clause. const Matcher<const ArgumentTuple&>& extra_matcher() const { return extra_matcher_; } // Returns the action specified by the .WillRepeatedly() clause. const Action<F>& repeated_action() const { return repeated_action_; } // If this mock method has an extra matcher (i.e. .With(matcher)), // describes it to the ostream. virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) { if (extra_matcher_specified_) { *os << " Expected args: "; extra_matcher_.DescribeTo(os); *os << "\n"; } } private: template <typename Function> friend class FunctionMockerBase; // Returns an Expectation object that references and co-owns this // expectation. virtual Expectation GetHandle() { return owner_->GetHandleOf(this); } // The following methods will be called only after the EXPECT_CALL() // statement finishes and when the current thread holds // g_gmock_mutex. // Returns true iff this expectation matches the given arguments. bool Matches(const ArgumentTuple& args) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); return TupleMatches(matchers_, args) && extra_matcher_.Matches(args); } // Returns true iff this expectation should handle the given arguments. bool ShouldHandleArguments(const ArgumentTuple& args) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); // In case the action count wasn't checked when the expectation // was defined (e.g. if this expectation has no WillRepeatedly() // or RetiresOnSaturation() clause), we check it when the // expectation is used for the first time. CheckActionCountIfNotDone(); return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args); } // Describes the result of matching the arguments against this // expectation to the given ostream. void ExplainMatchResultTo( const ArgumentTuple& args, ::std::ostream* os) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); if (is_retired()) { *os << " Expected: the expectation is active\n" << " Actual: it is retired\n"; } else if (!Matches(args)) { if (!TupleMatches(matchers_, args)) { ExplainMatchFailureTupleTo(matchers_, args, os); } StringMatchResultListener listener; if (!extra_matcher_.MatchAndExplain(args, &listener)) { *os << " Expected args: "; extra_matcher_.DescribeTo(os); *os << "\n Actual: don't match"; internal::PrintIfNotEmpty(listener.str(), os); *os << "\n"; } } else if (!AllPrerequisitesAreSatisfied()) { *os << " Expected: all pre-requisites are satisfied\n" << " Actual: the following immediate pre-requisites " << "are not satisfied:\n"; ExpectationSet unsatisfied_prereqs; FindUnsatisfiedPrerequisites(&unsatisfied_prereqs); int i = 0; for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin(); it != unsatisfied_prereqs.end(); ++it) { it->expectation_base()->DescribeLocationTo(os); *os << "pre-requisite #" << i++ << "\n"; } *os << " (end of pre-requisites)\n"; } else { // This line is here just for completeness' sake. It will never // be executed as currently the ExplainMatchResultTo() function // is called only when the mock function call does NOT match the // expectation. *os << "The call matches the expectation.\n"; } } // Returns the action that should be taken for the current invocation. const Action<F>& GetCurrentAction( const FunctionMockerBase<F>* mocker, const ArgumentTuple& args) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); const int count = call_count(); Assert(count >= 1, __FILE__, __LINE__, "call_count() is <= 0 when GetCurrentAction() is " "called - this should never happen."); const int action_count = static_cast<int>(untyped_actions_.size()); if (action_count > 0 && !repeated_action_specified_ && count > action_count) { // If there is at least one WillOnce() and no WillRepeatedly(), // we warn the user when the WillOnce() clauses ran out. ::std::stringstream ss; DescribeLocationTo(&ss); ss << "Actions ran out in " << source_text() << "...\n" << "Called " << count << " times, but only " << action_count << " WillOnce()" << (action_count == 1 ? " is" : "s are") << " specified - "; mocker->DescribeDefaultActionTo(args, &ss); Log(kWarning, ss.str(), 1); } return count <= action_count ? *static_cast<const Action<F>*>(untyped_actions_[count - 1]) : repeated_action(); } // Given the arguments of a mock function call, if the call will // over-saturate this expectation, returns the default action; // otherwise, returns the next action in this expectation. Also // describes *what* happened to 'what', and explains *why* Google // Mock does it to 'why'. This method is not const as it calls // IncrementCallCount(). A return value of NULL means the default // action. const Action<F>* GetActionForArguments( const FunctionMockerBase<F>* mocker, const ArgumentTuple& args, ::std::ostream* what, ::std::ostream* why) GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); if (IsSaturated()) { // We have an excessive call. IncrementCallCount(); *what << "Mock function called more times than expected - "; mocker->DescribeDefaultActionTo(args, what); DescribeCallCountTo(why); // TODO([email protected]): allow the user to control whether // unexpected calls should fail immediately or continue using a // flag --gmock_unexpected_calls_are_fatal. return NULL; } IncrementCallCount(); RetireAllPreRequisites(); if (retires_on_saturation_ && IsSaturated()) { Retire(); } // Must be done after IncrementCount()! *what << "Mock function call matches " << source_text() <<"...\n"; return &(GetCurrentAction(mocker, args)); } // All the fields below won't change once the EXPECT_CALL() // statement finishes. FunctionMockerBase<F>* const owner_; ArgumentMatcherTuple matchers_; Matcher<const ArgumentTuple&> extra_matcher_; Action<F> repeated_action_; GTEST_DISALLOW_COPY_AND_ASSIGN_(TypedExpectation); }; // class TypedExpectation // A MockSpec object is used by ON_CALL() or EXPECT_CALL() for // specifying the default behavior of, or expectation on, a mock // function. // Note: class MockSpec really belongs to the ::testing namespace. // However if we define it in ::testing, MSVC will complain when // classes in ::testing::internal declare it as a friend class // template. To workaround this compiler bug, we define MockSpec in // ::testing::internal and import it into ::testing. // Logs a message including file and line number information. GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity, const char* file, int line, const string& message); template <typename F> class MockSpec { public: typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; typedef typename internal::Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple; // Constructs a MockSpec object, given the function mocker object // that the spec is associated with. explicit MockSpec(internal::FunctionMockerBase<F>* function_mocker) : function_mocker_(function_mocker) {} // Adds a new default action spec to the function mocker and returns // the newly created spec. internal::OnCallSpec<F>& InternalDefaultActionSetAt( const char* file, int line, const char* obj, const char* call) { LogWithLocation(internal::kInfo, file, line, string("ON_CALL(") + obj + ", " + call + ") invoked"); return function_mocker_->AddNewOnCallSpec(file, line, matchers_); } // Adds a new expectation spec to the function mocker and returns // the newly created spec. internal::TypedExpectation<F>& InternalExpectedAt( const char* file, int line, const char* obj, const char* call) { const string source_text(string("EXPECT_CALL(") + obj + ", " + call + ")"); LogWithLocation(internal::kInfo, file, line, source_text + " invoked"); return function_mocker_->AddNewExpectation( file, line, source_text, matchers_); } private: template <typename Function> friend class internal::FunctionMocker; void SetMatchers(const ArgumentMatcherTuple& matchers) { matchers_ = matchers; } // The function mocker that owns this spec. internal::FunctionMockerBase<F>* const function_mocker_; // The argument matchers specified in the spec. ArgumentMatcherTuple matchers_; GTEST_DISALLOW_ASSIGN_(MockSpec); }; // class MockSpec // Wrapper type for generically holding an ordinary value or lvalue reference. // If T is not a reference type, it must be copyable or movable. // ReferenceOrValueWrapper<T> is movable, and will also be copyable unless // T is a move-only value type (which means that it will always be copyable // if the current platform does not support move semantics). // // The primary template defines handling for values, but function header // comments describe the contract for the whole template (including // specializations). template <typename T> class ReferenceOrValueWrapper { public: // Constructs a wrapper from the given value/reference. explicit ReferenceOrValueWrapper(T value) : value_(::testing::internal::move(value)) { } // Unwraps and returns the underlying value/reference, exactly as // originally passed. The behavior of calling this more than once on // the same object is unspecified. T Unwrap() { return ::testing::internal::move(value_); } // Provides nondestructive access to the underlying value/reference. // Always returns a const reference (more precisely, // const RemoveReference<T>&). The behavior of calling this after // calling Unwrap on the same object is unspecified. const T& Peek() const { return value_; } private: T value_; }; // Specialization for lvalue reference types. See primary template // for documentation. template <typename T> class ReferenceOrValueWrapper<T&> { public: // Workaround for debatable pass-by-reference lint warning (c-library-team // policy precludes NOLINT in this context) typedef T& reference; explicit ReferenceOrValueWrapper(reference ref) : value_ptr_(&ref) {} T& Unwrap() { return *value_ptr_; } const T& Peek() const { return *value_ptr_; } private: T* value_ptr_; }; // MSVC warns about using 'this' in base member initializer list, so // we need to temporarily disable the warning. We have to do it for // the entire class to suppress the warning, even though it's about // the constructor only. #ifdef _MSC_VER # pragma warning(push) // Saves the current warning state. # pragma warning(disable:4355) // Temporarily disables warning 4355. #endif // _MSV_VER // C++ treats the void type specially. For example, you cannot define // a void-typed variable or pass a void value to a function. // ActionResultHolder<T> holds a value of type T, where T must be a // copyable type or void (T doesn't need to be default-constructable). // It hides the syntactic difference between void and other types, and // is used to unify the code for invoking both void-returning and // non-void-returning mock functions. // Untyped base class for ActionResultHolder<T>. class UntypedActionResultHolderBase { public: virtual ~UntypedActionResultHolderBase() {} // Prints the held value as an action's result to os. virtual void PrintAsActionResult(::std::ostream* os) const = 0; }; // This generic definition is used when T is not void. template <typename T> class ActionResultHolder : public UntypedActionResultHolderBase { public: // Returns the held value. Must not be called more than once. T Unwrap() { return result_.Unwrap(); } // Prints the held value as an action's result to os. virtual void PrintAsActionResult(::std::ostream* os) const { *os << "\n Returns: "; // T may be a reference type, so we don't use UniversalPrint(). UniversalPrinter<T>::Print(result_.Peek(), os); } // Performs the given mock function's default action and returns the // result in a new-ed ActionResultHolder. template <typename F> static ActionResultHolder* PerformDefaultAction( const FunctionMockerBase<F>* func_mocker, const typename Function<F>::ArgumentTuple& args, const string& call_description) { return new ActionResultHolder(Wrapper( func_mocker->PerformDefaultAction(args, call_description))); } // Performs the given action and returns the result in a new-ed // ActionResultHolder. template <typename F> static ActionResultHolder* PerformAction(const Action<F>& action, const typename Function<F>::ArgumentTuple& args) { return new ActionResultHolder(Wrapper(action.Perform(args))); } private: typedef ReferenceOrValueWrapper<T> Wrapper; explicit ActionResultHolder(Wrapper result) : result_(::testing::internal::move(result)) { } Wrapper result_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder); }; // Specialization for T = void. template <> class ActionResultHolder<void> : public UntypedActionResultHolderBase { public: void Unwrap() { } virtual void PrintAsActionResult(::std::ostream* /* os */) const {} // Performs the given mock function's default action and returns ownership // of an empty ActionResultHolder*. template <typename F> static ActionResultHolder* PerformDefaultAction( const FunctionMockerBase<F>* func_mocker, const typename Function<F>::ArgumentTuple& args, const string& call_description) { func_mocker->PerformDefaultAction(args, call_description); return new ActionResultHolder; } // Performs the given action and returns ownership of an empty // ActionResultHolder*. template <typename F> static ActionResultHolder* PerformAction( const Action<F>& action, const typename Function<F>::ArgumentTuple& args) { action.Perform(args); return new ActionResultHolder; } private: ActionResultHolder() {} GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionResultHolder); }; // The base of the function mocker class for the given function type. // We put the methods in this class instead of its child to avoid code // bloat. template <typename F> class FunctionMockerBase : public UntypedFunctionMockerBase { public: typedef typename Function<F>::Result Result; typedef typename Function<F>::ArgumentTuple ArgumentTuple; typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple; FunctionMockerBase() : current_spec_(this) {} // The destructor verifies that all expectations on this mock // function have been satisfied. If not, it will report Google Test // non-fatal failures for the violations. virtual ~FunctionMockerBase() GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { MutexLock l(&g_gmock_mutex); VerifyAndClearExpectationsLocked(); Mock::UnregisterLocked(this); ClearDefaultActionsLocked(); } // Returns the ON_CALL spec that matches this mock function with the // given arguments; returns NULL if no matching ON_CALL is found. // L = * const OnCallSpec<F>* FindOnCallSpec( const ArgumentTuple& args) const { for (UntypedOnCallSpecs::const_reverse_iterator it = untyped_on_call_specs_.rbegin(); it != untyped_on_call_specs_.rend(); ++it) { const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it); if (spec->Matches(args)) return spec; } return NULL; } // Performs the default action of this mock function on the given // arguments and returns the result. Asserts (or throws if // exceptions are enabled) with a helpful call descrption if there // is no valid return value. This method doesn't depend on the // mutable state of this object, and thus can be called concurrently // without locking. // L = * Result PerformDefaultAction(const ArgumentTuple& args, const string& call_description) const { const OnCallSpec<F>* const spec = this->FindOnCallSpec(args); if (spec != NULL) { return spec->GetAction().Perform(args); } const string message = call_description + "\n The mock function has no default action " "set, and its return type has no default value set."; #if GTEST_HAS_EXCEPTIONS if (!DefaultValue<Result>::Exists()) { throw std::runtime_error(message); } #else Assert(DefaultValue<Result>::Exists(), "", -1, message); #endif return DefaultValue<Result>::Get(); } // Performs the default action with the given arguments and returns // the action's result. The call description string will be used in // the error message to describe the call in the case the default // action fails. The caller is responsible for deleting the result. // L = * virtual UntypedActionResultHolderBase* UntypedPerformDefaultAction( const void* untyped_args, // must point to an ArgumentTuple const string& call_description) const { const ArgumentTuple& args = *static_cast<const ArgumentTuple*>(untyped_args); return ResultHolder::PerformDefaultAction(this, args, call_description); } // Performs the given action with the given arguments and returns // the action's result. The caller is responsible for deleting the // result. // L = * virtual UntypedActionResultHolderBase* UntypedPerformAction( const void* untyped_action, const void* untyped_args) const { // Make a copy of the action before performing it, in case the // action deletes the mock object (and thus deletes itself). const Action<F> action = *static_cast<const Action<F>*>(untyped_action); const ArgumentTuple& args = *static_cast<const ArgumentTuple*>(untyped_args); return ResultHolder::PerformAction(action, args); } // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked(): // clears the ON_CALL()s set on this mock function. virtual void ClearDefaultActionsLocked() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); // Deleting our default actions may trigger other mock objects to be // deleted, for example if an action contains a reference counted smart // pointer to that mock object, and that is the last reference. So if we // delete our actions within the context of the global mutex we may deadlock // when this method is called again. Instead, make a copy of the set of // actions to delete, clear our set within the mutex, and then delete the // actions outside of the mutex. UntypedOnCallSpecs specs_to_delete; untyped_on_call_specs_.swap(specs_to_delete); g_gmock_mutex.Unlock(); for (UntypedOnCallSpecs::const_iterator it = specs_to_delete.begin(); it != specs_to_delete.end(); ++it) { delete static_cast<const OnCallSpec<F>*>(*it); } // Lock the mutex again, since the caller expects it to be locked when we // return. g_gmock_mutex.Lock(); } protected: template <typename Function> friend class MockSpec; typedef ActionResultHolder<Result> ResultHolder; // Returns the result of invoking this mock function with the given // arguments. This function can be safely called from multiple // threads concurrently. Result InvokeWith(const ArgumentTuple& args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { scoped_ptr<ResultHolder> holder( DownCast_<ResultHolder*>(this->UntypedInvokeWith(&args))); return holder->Unwrap(); } // Adds and returns a default action spec for this mock function. OnCallSpec<F>& AddNewOnCallSpec( const char* file, int line, const ArgumentMatcherTuple& m) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line); OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m); untyped_on_call_specs_.push_back(on_call_spec); return *on_call_spec; } // Adds and returns an expectation spec for this mock function. TypedExpectation<F>& AddNewExpectation( const char* file, int line, const string& source_text, const ArgumentMatcherTuple& m) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line); TypedExpectation<F>* const expectation = new TypedExpectation<F>(this, file, line, source_text, m); const linked_ptr<ExpectationBase> untyped_expectation(expectation); untyped_expectations_.push_back(untyped_expectation); // Adds this expectation into the implicit sequence if there is one. Sequence* const implicit_sequence = g_gmock_implicit_sequence.get(); if (implicit_sequence != NULL) { implicit_sequence->AddExpectation(Expectation(untyped_expectation)); } return *expectation; } // The current spec (either default action spec or expectation spec) // being described on this function mocker. MockSpec<F>& current_spec() { return current_spec_; } private: template <typename Func> friend class TypedExpectation; // Some utilities needed for implementing UntypedInvokeWith(). // Describes what default action will be performed for the given // arguments. // L = * void DescribeDefaultActionTo(const ArgumentTuple& args, ::std::ostream* os) const { const OnCallSpec<F>* const spec = FindOnCallSpec(args); if (spec == NULL) { *os << (internal::type_equals<Result, void>::value ? "returning directly.\n" : "returning default value.\n"); } else { *os << "taking default action specified at:\n" << FormatFileLocation(spec->file(), spec->line()) << "\n"; } } // Writes a message that the call is uninteresting (i.e. neither // explicitly expected nor explicitly unexpected) to the given // ostream. virtual void UntypedDescribeUninterestingCall( const void* untyped_args, ::std::ostream* os) const GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { const ArgumentTuple& args = *static_cast<const ArgumentTuple*>(untyped_args); *os << "Uninteresting mock function call - "; DescribeDefaultActionTo(args, os); *os << " Function call: " << Name(); UniversalPrint(args, os); } // Returns the expectation that matches the given function arguments // (or NULL is there's no match); when a match is found, // untyped_action is set to point to the action that should be // performed (or NULL if the action is "do default"), and // is_excessive is modified to indicate whether the call exceeds the // expected number. // // Critical section: We must find the matching expectation and the // corresponding action that needs to be taken in an ATOMIC // transaction. Otherwise another thread may call this mock // method in the middle and mess up the state. // // However, performing the action has to be left out of the critical // section. The reason is that we have no control on what the // action does (it can invoke an arbitrary user function or even a // mock function) and excessive locking could cause a dead lock. virtual const ExpectationBase* UntypedFindMatchingExpectation( const void* untyped_args, const void** untyped_action, bool* is_excessive, ::std::ostream* what, ::std::ostream* why) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) { const ArgumentTuple& args = *static_cast<const ArgumentTuple*>(untyped_args); MutexLock l(&g_gmock_mutex); TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args); if (exp == NULL) { // A match wasn't found. this->FormatUnexpectedCallMessageLocked(args, what, why); return NULL; } // This line must be done before calling GetActionForArguments(), // which will increment the call count for *exp and thus affect // its saturation status. *is_excessive = exp->IsSaturated(); const Action<F>* action = exp->GetActionForArguments(this, args, what, why); if (action != NULL && action->IsDoDefault()) action = NULL; // Normalize "do default" to NULL. *untyped_action = action; return exp; } // Prints the given function arguments to the ostream. virtual void UntypedPrintArgs(const void* untyped_args, ::std::ostream* os) const { const ArgumentTuple& args = *static_cast<const ArgumentTuple*>(untyped_args); UniversalPrint(args, os); } // Returns the expectation that matches the arguments, or NULL if no // expectation matches them. TypedExpectation<F>* FindMatchingExpectationLocked( const ArgumentTuple& args) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); for (typename UntypedExpectations::const_reverse_iterator it = untyped_expectations_.rbegin(); it != untyped_expectations_.rend(); ++it) { TypedExpectation<F>* const exp = static_cast<TypedExpectation<F>*>(it->get()); if (exp->ShouldHandleArguments(args)) { return exp; } } return NULL; } // Returns a message that the arguments don't match any expectation. void FormatUnexpectedCallMessageLocked( const ArgumentTuple& args, ::std::ostream* os, ::std::ostream* why) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); *os << "\nUnexpected mock function call - "; DescribeDefaultActionTo(args, os); PrintTriedExpectationsLocked(args, why); } // Prints a list of expectations that have been tried against the // current mock function call. void PrintTriedExpectationsLocked( const ArgumentTuple& args, ::std::ostream* why) const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) { g_gmock_mutex.AssertHeld(); const int count = static_cast<int>(untyped_expectations_.size()); *why << "Google Mock tried the following " << count << " " << (count == 1 ? "expectation, but it didn't match" : "expectations, but none matched") << ":\n"; for (int i = 0; i < count; i++) { TypedExpectation<F>* const expectation = static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get()); *why << "\n"; expectation->DescribeLocationTo(why); if (count > 1) { *why << "tried expectation #" << i << ": "; } *why << expectation->source_text() << "...\n"; expectation->ExplainMatchResultTo(args, why); expectation->DescribeCallCountTo(why); } } // The current spec (either default action spec or expectation spec) // being described on this function mocker. MockSpec<F> current_spec_; // There is no generally useful and implementable semantics of // copying a mock object, so copying a mock is usually a user error. // Thus we disallow copying function mockers. If the user really // wants to copy a mock object, he should implement his own copy // operation, for example: // // class MockFoo : public Foo { // public: // // Defines a copy constructor explicitly. // MockFoo(const MockFoo& src) {} // ... // }; GTEST_DISALLOW_COPY_AND_ASSIGN_(FunctionMockerBase); }; // class FunctionMockerBase #ifdef _MSC_VER # pragma warning(pop) // Restores the warning state. #endif // _MSV_VER // Implements methods of FunctionMockerBase. // Verifies that all expectations on this mock function have been // satisfied. Reports one or more Google Test non-fatal failures and // returns false if not. // Reports an uninteresting call (whose description is in msg) in the // manner specified by 'reaction'. void ReportUninterestingCall(CallReaction reaction, const string& msg); } // namespace internal // The style guide prohibits "using" statements in a namespace scope // inside a header file. However, the MockSpec 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 MockSpec in ::testing. using internal::MockSpec; // Const(x) is a convenient function for obtaining a const reference // to x. This is useful for setting expectations on an overloaded // const mock method, e.g. // // class MockFoo : public FooInterface { // public: // MOCK_METHOD0(Bar, int()); // MOCK_CONST_METHOD0(Bar, int&()); // }; // // MockFoo foo; // // Expects a call to non-const MockFoo::Bar(). // EXPECT_CALL(foo, Bar()); // // Expects a call to const MockFoo::Bar(). // EXPECT_CALL(Const(foo), Bar()); template <typename T> inline const T& Const(const T& x) { return x; } // Constructs an Expectation object that references and co-owns exp. inline Expectation::Expectation(internal::ExpectationBase& exp) // NOLINT : expectation_base_(exp.GetHandle().expectation_base()) {} } // namespace testing // A separate macro is required to avoid compile errors when the name // of the method used in call is a result of macro expansion. // See CompilesWithMethodNameExpandedFromMacro tests in // internal/gmock-spec-builders_test.cc for more details. #define GMOCK_ON_CALL_IMPL_(obj, call) \ ((obj).gmock_##call).InternalDefaultActionSetAt(__FILE__, __LINE__, \ #obj, #call) #define ON_CALL(obj, call) GMOCK_ON_CALL_IMPL_(obj, call) #define GMOCK_EXPECT_CALL_IMPL_(obj, call) \ ((obj).gmock_##call).InternalExpectedAt(__FILE__, __LINE__, #obj, #call) #define EXPECT_CALL(obj, call) GMOCK_EXPECT_CALL_IMPL_(obj, call) #endif // GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
0
repos/DirectXShaderCompiler/utils/unittest/googlemock/include
repos/DirectXShaderCompiler/utils/unittest/googlemock/include/gmock/gmock-generated-actions.h
// This file was GENERATED by a script. DO NOT EDIT BY HAND!!! // 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. // // Author: [email protected] (Zhanyong Wan) // Google Mock - a framework for writing C++ mock classes. // // This file implements some commonly used variadic actions. #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_ #include "gmock/gmock-actions.h" #include "gmock/internal/gmock-port.h" namespace testing { namespace internal { // InvokeHelper<F> knows how to unpack an N-tuple and invoke an N-ary // function or method with the unpacked values, where F is a function // type that takes N arguments. template <typename Result, typename ArgumentTuple> class InvokeHelper; template <typename R> class InvokeHelper<R, ::testing::tuple<> > { public: template <typename Function> static R Invoke(Function function, const ::testing::tuple<>&) { return function(); } template <class Class, typename MethodPtr> static R InvokeMethod(Class* obj_ptr, MethodPtr method_ptr, const ::testing::tuple<>&) { return (obj_ptr->*method_ptr)(); } }; template <typename R, typename A1> class InvokeHelper<R, ::testing::tuple<A1> > { public: template <typename Function> static R Invoke(Function function, const ::testing::tuple<A1>& args) { return function(get<0>(args)); } template <class Class, typename MethodPtr> static R InvokeMethod(Class* obj_ptr, MethodPtr method_ptr, const ::testing::tuple<A1>& args) { return (obj_ptr->*method_ptr)(get<0>(args)); } }; template <typename R, typename A1, typename A2> class InvokeHelper<R, ::testing::tuple<A1, A2> > { public: template <typename Function> static R Invoke(Function function, const ::testing::tuple<A1, A2>& args) { return function(get<0>(args), get<1>(args)); } template <class Class, typename MethodPtr> static R InvokeMethod(Class* obj_ptr, MethodPtr method_ptr, const ::testing::tuple<A1, A2>& args) { return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args)); } }; template <typename R, typename A1, typename A2, typename A3> class InvokeHelper<R, ::testing::tuple<A1, A2, A3> > { public: template <typename Function> static R Invoke(Function function, const ::testing::tuple<A1, A2, A3>& args) { return function(get<0>(args), get<1>(args), get<2>(args)); } template <class Class, typename MethodPtr> static R InvokeMethod(Class* obj_ptr, MethodPtr method_ptr, const ::testing::tuple<A1, A2, A3>& args) { return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), get<2>(args)); } }; template <typename R, typename A1, typename A2, typename A3, typename A4> class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4> > { public: template <typename Function> static R Invoke(Function function, const ::testing::tuple<A1, A2, A3, A4>& args) { return function(get<0>(args), get<1>(args), get<2>(args), get<3>(args)); } template <class Class, typename MethodPtr> static R InvokeMethod(Class* obj_ptr, MethodPtr method_ptr, const ::testing::tuple<A1, A2, A3, A4>& args) { return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), get<2>(args), get<3>(args)); } }; template <typename R, typename A1, typename A2, typename A3, typename A4, typename A5> class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4, A5> > { public: template <typename Function> static R Invoke(Function function, const ::testing::tuple<A1, A2, A3, A4, A5>& args) { return function(get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args)); } template <class Class, typename MethodPtr> static R InvokeMethod(Class* obj_ptr, MethodPtr method_ptr, const ::testing::tuple<A1, A2, A3, A4, A5>& args) { return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args)); } }; template <typename R, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6> class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4, A5, A6> > { public: template <typename Function> static R Invoke(Function function, const ::testing::tuple<A1, A2, A3, A4, A5, A6>& args) { return function(get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), get<5>(args)); } template <class Class, typename MethodPtr> static R InvokeMethod(Class* obj_ptr, MethodPtr method_ptr, const ::testing::tuple<A1, A2, A3, A4, A5, A6>& args) { return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), get<5>(args)); } }; template <typename R, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7> class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4, A5, A6, A7> > { public: template <typename Function> static R Invoke(Function function, const ::testing::tuple<A1, A2, A3, A4, A5, A6, A7>& args) { return function(get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), get<5>(args), get<6>(args)); } template <class Class, typename MethodPtr> static R InvokeMethod(Class* obj_ptr, MethodPtr method_ptr, const ::testing::tuple<A1, A2, A3, A4, A5, A6, A7>& args) { return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), get<5>(args), get<6>(args)); } }; template <typename R, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8> class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8> > { public: template <typename Function> static R Invoke(Function function, const ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8>& args) { return function(get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), get<5>(args), get<6>(args), get<7>(args)); } template <class Class, typename MethodPtr> static R InvokeMethod(Class* obj_ptr, MethodPtr method_ptr, const ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8>& args) { return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), get<5>(args), get<6>(args), get<7>(args)); } }; template <typename R, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8, typename A9> class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9> > { public: template <typename Function> static R Invoke(Function function, const ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9>& args) { return function(get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), get<5>(args), get<6>(args), get<7>(args), get<8>(args)); } template <class Class, typename MethodPtr> static R InvokeMethod(Class* obj_ptr, MethodPtr method_ptr, const ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9>& args) { return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), get<5>(args), get<6>(args), get<7>(args), get<8>(args)); } }; template <typename R, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8, typename A9, typename A10> class InvokeHelper<R, ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10> > { public: template <typename Function> static R Invoke(Function function, const ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>& args) { return function(get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), get<5>(args), get<6>(args), get<7>(args), get<8>(args), get<9>(args)); } template <class Class, typename MethodPtr> static R InvokeMethod(Class* obj_ptr, MethodPtr method_ptr, const ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10>& args) { return (obj_ptr->*method_ptr)(get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), get<5>(args), get<6>(args), get<7>(args), get<8>(args), get<9>(args)); } }; // An INTERNAL macro for extracting the type of a tuple field. It's // subject to change without notice - DO NOT USE IN USER CODE! #define GMOCK_FIELD_(Tuple, N) \ typename ::testing::tuple_element<N, Tuple>::type // SelectArgs<Result, ArgumentTuple, k1, k2, ..., k_n>::type is the // type of an n-ary function whose i-th (1-based) argument type is the // k{i}-th (0-based) field of ArgumentTuple, which must be a tuple // type, and whose return type is Result. For example, // SelectArgs<int, ::testing::tuple<bool, char, double, long>, 0, 3>::type // is int(bool, long). // // SelectArgs<Result, ArgumentTuple, k1, k2, ..., k_n>::Select(args) // returns the selected fields (k1, k2, ..., k_n) of args as a tuple. // For example, // SelectArgs<int, tuple<bool, char, double>, 2, 0>::Select( // ::testing::make_tuple(true, 'a', 2.5)) // returns tuple (2.5, true). // // The numbers in list k1, k2, ..., k_n must be >= 0, where n can be // in the range [0, 10]. Duplicates are allowed and they don't have // to be in an ascending or descending order. template <typename Result, typename ArgumentTuple, int k1, int k2, int k3, int k4, int k5, int k6, int k7, int k8, int k9, int k10> class SelectArgs { public: typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1), GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3), GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5), GMOCK_FIELD_(ArgumentTuple, k6), GMOCK_FIELD_(ArgumentTuple, k7), GMOCK_FIELD_(ArgumentTuple, k8), GMOCK_FIELD_(ArgumentTuple, k9), GMOCK_FIELD_(ArgumentTuple, k10)); typedef typename Function<type>::ArgumentTuple SelectedArgs; static SelectedArgs Select(const ArgumentTuple& args) { return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args), get<k4>(args), get<k5>(args), get<k6>(args), get<k7>(args), get<k8>(args), get<k9>(args), get<k10>(args)); } }; template <typename Result, typename ArgumentTuple> class SelectArgs<Result, ArgumentTuple, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1> { public: typedef Result type(); typedef typename Function<type>::ArgumentTuple SelectedArgs; static SelectedArgs Select(const ArgumentTuple& /* args */) { return SelectedArgs(); } }; template <typename Result, typename ArgumentTuple, int k1> class SelectArgs<Result, ArgumentTuple, k1, -1, -1, -1, -1, -1, -1, -1, -1, -1> { public: typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1)); typedef typename Function<type>::ArgumentTuple SelectedArgs; static SelectedArgs Select(const ArgumentTuple& args) { return SelectedArgs(get<k1>(args)); } }; template <typename Result, typename ArgumentTuple, int k1, int k2> class SelectArgs<Result, ArgumentTuple, k1, k2, -1, -1, -1, -1, -1, -1, -1, -1> { public: typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1), GMOCK_FIELD_(ArgumentTuple, k2)); typedef typename Function<type>::ArgumentTuple SelectedArgs; static SelectedArgs Select(const ArgumentTuple& args) { return SelectedArgs(get<k1>(args), get<k2>(args)); } }; template <typename Result, typename ArgumentTuple, int k1, int k2, int k3> class SelectArgs<Result, ArgumentTuple, k1, k2, k3, -1, -1, -1, -1, -1, -1, -1> { public: typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1), GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3)); typedef typename Function<type>::ArgumentTuple SelectedArgs; static SelectedArgs Select(const ArgumentTuple& args) { return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args)); } }; template <typename Result, typename ArgumentTuple, int k1, int k2, int k3, int k4> class SelectArgs<Result, ArgumentTuple, k1, k2, k3, k4, -1, -1, -1, -1, -1, -1> { public: typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1), GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3), GMOCK_FIELD_(ArgumentTuple, k4)); typedef typename Function<type>::ArgumentTuple SelectedArgs; static SelectedArgs Select(const ArgumentTuple& args) { return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args), get<k4>(args)); } }; template <typename Result, typename ArgumentTuple, int k1, int k2, int k3, int k4, int k5> class SelectArgs<Result, ArgumentTuple, k1, k2, k3, k4, k5, -1, -1, -1, -1, -1> { public: typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1), GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3), GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5)); typedef typename Function<type>::ArgumentTuple SelectedArgs; static SelectedArgs Select(const ArgumentTuple& args) { return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args), get<k4>(args), get<k5>(args)); } }; template <typename Result, typename ArgumentTuple, int k1, int k2, int k3, int k4, int k5, int k6> class SelectArgs<Result, ArgumentTuple, k1, k2, k3, k4, k5, k6, -1, -1, -1, -1> { public: typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1), GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3), GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5), GMOCK_FIELD_(ArgumentTuple, k6)); typedef typename Function<type>::ArgumentTuple SelectedArgs; static SelectedArgs Select(const ArgumentTuple& args) { return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args), get<k4>(args), get<k5>(args), get<k6>(args)); } }; template <typename Result, typename ArgumentTuple, int k1, int k2, int k3, int k4, int k5, int k6, int k7> class SelectArgs<Result, ArgumentTuple, k1, k2, k3, k4, k5, k6, k7, -1, -1, -1> { public: typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1), GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3), GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5), GMOCK_FIELD_(ArgumentTuple, k6), GMOCK_FIELD_(ArgumentTuple, k7)); typedef typename Function<type>::ArgumentTuple SelectedArgs; static SelectedArgs Select(const ArgumentTuple& args) { return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args), get<k4>(args), get<k5>(args), get<k6>(args), get<k7>(args)); } }; template <typename Result, typename ArgumentTuple, int k1, int k2, int k3, int k4, int k5, int k6, int k7, int k8> class SelectArgs<Result, ArgumentTuple, k1, k2, k3, k4, k5, k6, k7, k8, -1, -1> { public: typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1), GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3), GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5), GMOCK_FIELD_(ArgumentTuple, k6), GMOCK_FIELD_(ArgumentTuple, k7), GMOCK_FIELD_(ArgumentTuple, k8)); typedef typename Function<type>::ArgumentTuple SelectedArgs; static SelectedArgs Select(const ArgumentTuple& args) { return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args), get<k4>(args), get<k5>(args), get<k6>(args), get<k7>(args), get<k8>(args)); } }; template <typename Result, typename ArgumentTuple, int k1, int k2, int k3, int k4, int k5, int k6, int k7, int k8, int k9> class SelectArgs<Result, ArgumentTuple, k1, k2, k3, k4, k5, k6, k7, k8, k9, -1> { public: typedef Result type(GMOCK_FIELD_(ArgumentTuple, k1), GMOCK_FIELD_(ArgumentTuple, k2), GMOCK_FIELD_(ArgumentTuple, k3), GMOCK_FIELD_(ArgumentTuple, k4), GMOCK_FIELD_(ArgumentTuple, k5), GMOCK_FIELD_(ArgumentTuple, k6), GMOCK_FIELD_(ArgumentTuple, k7), GMOCK_FIELD_(ArgumentTuple, k8), GMOCK_FIELD_(ArgumentTuple, k9)); typedef typename Function<type>::ArgumentTuple SelectedArgs; static SelectedArgs Select(const ArgumentTuple& args) { return SelectedArgs(get<k1>(args), get<k2>(args), get<k3>(args), get<k4>(args), get<k5>(args), get<k6>(args), get<k7>(args), get<k8>(args), get<k9>(args)); } }; #undef GMOCK_FIELD_ // Implements the WithArgs action. template <typename InnerAction, int k1 = -1, int k2 = -1, int k3 = -1, int k4 = -1, int k5 = -1, int k6 = -1, int k7 = -1, int k8 = -1, int k9 = -1, int k10 = -1> class WithArgsAction { public: explicit WithArgsAction(const InnerAction& action) : action_(action) {} template <typename F> operator Action<F>() const { return MakeAction(new Impl<F>(action_)); } private: template <typename F> class Impl : public ActionInterface<F> { public: typedef typename Function<F>::Result Result; typedef typename Function<F>::ArgumentTuple ArgumentTuple; explicit Impl(const InnerAction& action) : action_(action) {} virtual Result Perform(const ArgumentTuple& args) { return action_.Perform(SelectArgs<Result, ArgumentTuple, k1, k2, k3, k4, k5, k6, k7, k8, k9, k10>::Select(args)); } private: typedef typename SelectArgs<Result, ArgumentTuple, k1, k2, k3, k4, k5, k6, k7, k8, k9, k10>::type InnerFunctionType; Action<InnerFunctionType> action_; }; const InnerAction action_; GTEST_DISALLOW_ASSIGN_(WithArgsAction); }; // A macro from the ACTION* family (defined later in this file) // defines an action that can be used in a mock function. Typically, // these actions only care about a subset of the arguments of the mock // function. For example, if such an action only uses the second // argument, it can be used in any mock function that takes >= 2 // arguments where the type of the second argument is compatible. // // Therefore, the action implementation must be prepared to take more // arguments than it needs. The ExcessiveArg type is used to // represent those excessive arguments. In order to keep the compiler // error messages tractable, we define it in the testing namespace // instead of testing::internal. However, this is an INTERNAL TYPE // and subject to change without notice, so a user MUST NOT USE THIS // TYPE DIRECTLY. struct ExcessiveArg {}; // A helper class needed for implementing the ACTION* macros. template <typename Result, class Impl> class ActionHelper { public: static Result Perform(Impl* impl, const ::testing::tuple<>& args) { return impl->template gmock_PerformImpl<>(args, ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg()); } template <typename A0> static Result Perform(Impl* impl, const ::testing::tuple<A0>& args) { return impl->template gmock_PerformImpl<A0>(args, get<0>(args), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg()); } template <typename A0, typename A1> static Result Perform(Impl* impl, const ::testing::tuple<A0, A1>& args) { return impl->template gmock_PerformImpl<A0, A1>(args, get<0>(args), get<1>(args), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg()); } template <typename A0, typename A1, typename A2> static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2>& args) { return impl->template gmock_PerformImpl<A0, A1, A2>(args, get<0>(args), get<1>(args), get<2>(args), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg()); } template <typename A0, typename A1, typename A2, typename A3> static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2, A3>& args) { return impl->template gmock_PerformImpl<A0, A1, A2, A3>(args, get<0>(args), get<1>(args), get<2>(args), get<3>(args), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg()); } template <typename A0, typename A1, typename A2, typename A3, typename A4> static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2, A3, A4>& args) { return impl->template gmock_PerformImpl<A0, A1, A2, A3, A4>(args, get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg()); } template <typename A0, typename A1, typename A2, typename A3, typename A4, typename A5> static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2, A3, A4, A5>& args) { return impl->template gmock_PerformImpl<A0, A1, A2, A3, A4, A5>(args, get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), get<5>(args), ExcessiveArg(), ExcessiveArg(), ExcessiveArg(), ExcessiveArg()); } template <typename A0, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6> static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2, A3, A4, A5, A6>& args) { return impl->template gmock_PerformImpl<A0, A1, A2, A3, A4, A5, A6>(args, get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), get<5>(args), get<6>(args), ExcessiveArg(), ExcessiveArg(), ExcessiveArg()); } template <typename A0, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7> static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2, A3, A4, A5, A6, A7>& args) { return impl->template gmock_PerformImpl<A0, A1, A2, A3, A4, A5, A6, A7>(args, get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), get<5>(args), get<6>(args), get<7>(args), ExcessiveArg(), ExcessiveArg()); } template <typename A0, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8> static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2, A3, A4, A5, A6, A7, A8>& args) { return impl->template gmock_PerformImpl<A0, A1, A2, A3, A4, A5, A6, A7, A8>(args, get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), get<5>(args), get<6>(args), get<7>(args), get<8>(args), ExcessiveArg()); } template <typename A0, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8, typename A9> static Result Perform(Impl* impl, const ::testing::tuple<A0, A1, A2, A3, A4, A5, A6, A7, A8, A9>& args) { return impl->template gmock_PerformImpl<A0, A1, A2, A3, A4, A5, A6, A7, A8, A9>(args, get<0>(args), get<1>(args), get<2>(args), get<3>(args), get<4>(args), get<5>(args), get<6>(args), get<7>(args), get<8>(args), get<9>(args)); } }; } // namespace internal // Various overloads for Invoke(). // WithArgs<N1, N2, ..., Nk>(an_action) creates an action that passes // the selected arguments of the mock function to an_action and // performs it. It serves as an adaptor between actions with // different argument lists. C++ doesn't support default arguments for // function templates, so we have to overload it. template <int k1, typename InnerAction> inline internal::WithArgsAction<InnerAction, k1> WithArgs(const InnerAction& action) { return internal::WithArgsAction<InnerAction, k1>(action); } template <int k1, int k2, typename InnerAction> inline internal::WithArgsAction<InnerAction, k1, k2> WithArgs(const InnerAction& action) { return internal::WithArgsAction<InnerAction, k1, k2>(action); } template <int k1, int k2, int k3, typename InnerAction> inline internal::WithArgsAction<InnerAction, k1, k2, k3> WithArgs(const InnerAction& action) { return internal::WithArgsAction<InnerAction, k1, k2, k3>(action); } template <int k1, int k2, int k3, int k4, typename InnerAction> inline internal::WithArgsAction<InnerAction, k1, k2, k3, k4> WithArgs(const InnerAction& action) { return internal::WithArgsAction<InnerAction, k1, k2, k3, k4>(action); } template <int k1, int k2, int k3, int k4, int k5, typename InnerAction> inline internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5> WithArgs(const InnerAction& action) { return internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5>(action); } template <int k1, int k2, int k3, int k4, int k5, int k6, typename InnerAction> inline internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6> WithArgs(const InnerAction& action) { return internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6>(action); } template <int k1, int k2, int k3, int k4, int k5, int k6, int k7, typename InnerAction> inline internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6, k7> WithArgs(const InnerAction& action) { return internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6, k7>(action); } template <int k1, int k2, int k3, int k4, int k5, int k6, int k7, int k8, typename InnerAction> inline internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6, k7, k8> WithArgs(const InnerAction& action) { return internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6, k7, k8>(action); } template <int k1, int k2, int k3, int k4, int k5, int k6, int k7, int k8, int k9, typename InnerAction> inline internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6, k7, k8, k9> WithArgs(const InnerAction& action) { return internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6, k7, k8, k9>(action); } template <int k1, int k2, int k3, int k4, int k5, int k6, int k7, int k8, int k9, int k10, typename InnerAction> inline internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6, k7, k8, k9, k10> WithArgs(const InnerAction& action) { return internal::WithArgsAction<InnerAction, k1, k2, k3, k4, k5, k6, k7, k8, k9, k10>(action); } // Creates an action that does actions a1, a2, ..., sequentially in // each invocation. template <typename Action1, typename Action2> inline internal::DoBothAction<Action1, Action2> DoAll(Action1 a1, Action2 a2) { return internal::DoBothAction<Action1, Action2>(a1, a2); } template <typename Action1, typename Action2, typename Action3> inline internal::DoBothAction<Action1, internal::DoBothAction<Action2, Action3> > DoAll(Action1 a1, Action2 a2, Action3 a3) { return DoAll(a1, DoAll(a2, a3)); } template <typename Action1, typename Action2, typename Action3, typename Action4> inline internal::DoBothAction<Action1, internal::DoBothAction<Action2, internal::DoBothAction<Action3, Action4> > > DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4) { return DoAll(a1, DoAll(a2, a3, a4)); } template <typename Action1, typename Action2, typename Action3, typename Action4, typename Action5> inline internal::DoBothAction<Action1, internal::DoBothAction<Action2, internal::DoBothAction<Action3, internal::DoBothAction<Action4, Action5> > > > DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5) { return DoAll(a1, DoAll(a2, a3, a4, a5)); } template <typename Action1, typename Action2, typename Action3, typename Action4, typename Action5, typename Action6> inline internal::DoBothAction<Action1, internal::DoBothAction<Action2, internal::DoBothAction<Action3, internal::DoBothAction<Action4, internal::DoBothAction<Action5, Action6> > > > > DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6) { return DoAll(a1, DoAll(a2, a3, a4, a5, a6)); } template <typename Action1, typename Action2, typename Action3, typename Action4, typename Action5, typename Action6, typename Action7> inline internal::DoBothAction<Action1, internal::DoBothAction<Action2, internal::DoBothAction<Action3, internal::DoBothAction<Action4, internal::DoBothAction<Action5, internal::DoBothAction<Action6, Action7> > > > > > DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, Action7 a7) { return DoAll(a1, DoAll(a2, a3, a4, a5, a6, a7)); } template <typename Action1, typename Action2, typename Action3, typename Action4, typename Action5, typename Action6, typename Action7, typename Action8> inline internal::DoBothAction<Action1, internal::DoBothAction<Action2, internal::DoBothAction<Action3, internal::DoBothAction<Action4, internal::DoBothAction<Action5, internal::DoBothAction<Action6, internal::DoBothAction<Action7, Action8> > > > > > > DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, Action7 a7, Action8 a8) { return DoAll(a1, DoAll(a2, a3, a4, a5, a6, a7, a8)); } template <typename Action1, typename Action2, typename Action3, typename Action4, typename Action5, typename Action6, typename Action7, typename Action8, typename Action9> inline internal::DoBothAction<Action1, internal::DoBothAction<Action2, internal::DoBothAction<Action3, internal::DoBothAction<Action4, internal::DoBothAction<Action5, internal::DoBothAction<Action6, internal::DoBothAction<Action7, internal::DoBothAction<Action8, Action9> > > > > > > > DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, Action7 a7, Action8 a8, Action9 a9) { return DoAll(a1, DoAll(a2, a3, a4, a5, a6, a7, a8, a9)); } template <typename Action1, typename Action2, typename Action3, typename Action4, typename Action5, typename Action6, typename Action7, typename Action8, typename Action9, typename Action10> inline internal::DoBothAction<Action1, internal::DoBothAction<Action2, internal::DoBothAction<Action3, internal::DoBothAction<Action4, internal::DoBothAction<Action5, internal::DoBothAction<Action6, internal::DoBothAction<Action7, internal::DoBothAction<Action8, internal::DoBothAction<Action9, Action10> > > > > > > > > DoAll(Action1 a1, Action2 a2, Action3 a3, Action4 a4, Action5 a5, Action6 a6, Action7 a7, Action8 a8, Action9 a9, Action10 a10) { return DoAll(a1, DoAll(a2, a3, a4, a5, a6, a7, a8, a9, a10)); } } // namespace testing // The ACTION* family of macros can be used in a namespace scope to // define custom actions easily. The syntax: // // ACTION(name) { statements; } // // will define an action with the given name that executes the // statements. The value returned by the statements will be used as // the return value of the action. Inside the statements, you can // refer to the K-th (0-based) argument of the mock function by // 'argK', and refer to its type by 'argK_type'. For example: // // ACTION(IncrementArg1) { // arg1_type temp = arg1; // return ++(*temp); // } // // allows you to write // // ...WillOnce(IncrementArg1()); // // You can also refer to the entire argument tuple and its type by // 'args' and 'args_type', and refer to the mock function type and its // return type by 'function_type' and 'return_type'. // // Note that you don't need to specify the types of the mock function // arguments. However rest assured that your code is still type-safe: // you'll get a compiler error if *arg1 doesn't support the ++ // operator, or if the type of ++(*arg1) isn't compatible with the // mock function's return type, for example. // // Sometimes you'll want to parameterize the action. For that you can use // another macro: // // ACTION_P(name, param_name) { statements; } // // For example: // // ACTION_P(Add, n) { return arg0 + n; } // // will allow you to write: // // ...WillOnce(Add(5)); // // Note that you don't need to provide the type of the parameter // either. If you need to reference the type of a parameter named // 'foo', you can write 'foo_type'. For example, in the body of // ACTION_P(Add, n) above, you can write 'n_type' to refer to the type // of 'n'. // // We also provide ACTION_P2, ACTION_P3, ..., up to ACTION_P10 to support // multi-parameter actions. // // For the purpose of typing, you can view // // ACTION_Pk(Foo, p1, ..., pk) { ... } // // as shorthand for // // template <typename p1_type, ..., typename pk_type> // FooActionPk<p1_type, ..., pk_type> Foo(p1_type p1, ..., pk_type pk) { ... } // // In particular, you can provide the template type arguments // explicitly when invoking Foo(), as in Foo<long, bool>(5, false); // although usually you can rely on the compiler to infer the types // for you automatically. You can assign the result of expression // Foo(p1, ..., pk) to a variable of type FooActionPk<p1_type, ..., // pk_type>. This can be useful when composing actions. // // You can also overload actions with different numbers of parameters: // // ACTION_P(Plus, a) { ... } // ACTION_P2(Plus, a, b) { ... } // // While it's tempting to always use the ACTION* macros when defining // a new action, you should also consider implementing ActionInterface // or using MakePolymorphicAction() instead, especially if you need to // use the action a lot. While these approaches require more work, // they give you more control on the types of the mock function // arguments and the action parameters, which in general leads to // better compiler error messages that pay off in the long run. They // also allow overloading actions based on parameter types (as opposed // to just based on the number of parameters). // // CAVEAT: // // ACTION*() can only be used in a namespace scope. The reason is // that C++ doesn't yet allow function-local types to be used to // instantiate templates. The up-coming C++0x standard will fix this. // Once that's done, we'll consider supporting using ACTION*() inside // a function. // // MORE INFORMATION: // // To learn more about using these macros, please search for 'ACTION' // on http://code.google.com/p/googlemock/wiki/CookBook. // An internal macro needed for implementing ACTION*(). #define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_\ const args_type& args GTEST_ATTRIBUTE_UNUSED_, \ arg0_type arg0 GTEST_ATTRIBUTE_UNUSED_, \ arg1_type arg1 GTEST_ATTRIBUTE_UNUSED_, \ arg2_type arg2 GTEST_ATTRIBUTE_UNUSED_, \ arg3_type arg3 GTEST_ATTRIBUTE_UNUSED_, \ arg4_type arg4 GTEST_ATTRIBUTE_UNUSED_, \ arg5_type arg5 GTEST_ATTRIBUTE_UNUSED_, \ arg6_type arg6 GTEST_ATTRIBUTE_UNUSED_, \ arg7_type arg7 GTEST_ATTRIBUTE_UNUSED_, \ arg8_type arg8 GTEST_ATTRIBUTE_UNUSED_, \ arg9_type arg9 GTEST_ATTRIBUTE_UNUSED_ // Sometimes you want to give an action explicit template parameters // that cannot be inferred from its value parameters. ACTION() and // ACTION_P*() don't support that. ACTION_TEMPLATE() remedies that // and can be viewed as an extension to ACTION() and ACTION_P*(). // // The syntax: // // ACTION_TEMPLATE(ActionName, // HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m), // AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; } // // defines an action template that takes m explicit template // parameters and n value parameters. name_i is the name of the i-th // template parameter, and kind_i specifies whether it's a typename, // an integral constant, or a template. p_i is the name of the i-th // value parameter. // // Example: // // // DuplicateArg<k, T>(output) converts the k-th argument of the mock // // function to type T and copies it to *output. // ACTION_TEMPLATE(DuplicateArg, // HAS_2_TEMPLATE_PARAMS(int, k, typename, T), // AND_1_VALUE_PARAMS(output)) { // *output = T(::testing::get<k>(args)); // } // ... // int n; // EXPECT_CALL(mock, Foo(_, _)) // .WillOnce(DuplicateArg<1, unsigned char>(&n)); // // To create an instance of an action template, write: // // ActionName<t1, ..., t_m>(v1, ..., v_n) // // where the ts are the template arguments and the vs are the value // arguments. The value argument types are inferred by the compiler. // If you want to explicitly specify the value argument types, you can // provide additional template arguments: // // ActionName<t1, ..., t_m, u1, ..., u_k>(v1, ..., v_n) // // where u_i is the desired type of v_i. // // ACTION_TEMPLATE and ACTION/ACTION_P* can be overloaded on the // number of value parameters, but not on the number of template // parameters. Without the restriction, the meaning of the following // is unclear: // // OverloadedAction<int, bool>(x); // // Are we using a single-template-parameter action where 'bool' refers // to the type of x, or are we using a two-template-parameter action // where the compiler is asked to infer the type of x? // // Implementation notes: // // GMOCK_INTERNAL_*_HAS_m_TEMPLATE_PARAMS and // GMOCK_INTERNAL_*_AND_n_VALUE_PARAMS are internal macros for // implementing ACTION_TEMPLATE. The main trick we use is to create // new macro invocations when expanding a macro. For example, we have // // #define ACTION_TEMPLATE(name, template_params, value_params) // ... GMOCK_INTERNAL_DECL_##template_params ... // // which causes ACTION_TEMPLATE(..., HAS_1_TEMPLATE_PARAMS(typename, T), ...) // to expand to // // ... GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(typename, T) ... // // Since GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS is a macro, the // preprocessor will continue to expand it to // // ... typename T ... // // This technique conforms to the C++ standard and is portable. It // allows us to implement action templates using O(N) code, where N is // the maximum number of template/value parameters supported. Without // using it, we'd have to devote O(N^2) amount of code to implement all // combinations of m and n. // Declares the template parameters. #define GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(kind0, name0) kind0 name0 #define GMOCK_INTERNAL_DECL_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \ name1) kind0 name0, kind1 name1 #define GMOCK_INTERNAL_DECL_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ kind2, name2) kind0 name0, kind1 name1, kind2 name2 #define GMOCK_INTERNAL_DECL_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ kind2, name2, kind3, name3) kind0 name0, kind1 name1, kind2 name2, \ kind3 name3 #define GMOCK_INTERNAL_DECL_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ kind2, name2, kind3, name3, kind4, name4) kind0 name0, kind1 name1, \ kind2 name2, kind3 name3, kind4 name4 #define GMOCK_INTERNAL_DECL_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ kind2, name2, kind3, name3, kind4, name4, kind5, name5) kind0 name0, \ kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5 #define GMOCK_INTERNAL_DECL_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \ name6) kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, \ kind5 name5, kind6 name6 #define GMOCK_INTERNAL_DECL_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \ kind7, name7) kind0 name0, kind1 name1, kind2 name2, kind3 name3, \ kind4 name4, kind5 name5, kind6 name6, kind7 name7 #define GMOCK_INTERNAL_DECL_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \ kind7, name7, kind8, name8) kind0 name0, kind1 name1, kind2 name2, \ kind3 name3, kind4 name4, kind5 name5, kind6 name6, kind7 name7, \ kind8 name8 #define GMOCK_INTERNAL_DECL_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \ name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \ name6, kind7, name7, kind8, name8, kind9, name9) kind0 name0, \ kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5, \ kind6 name6, kind7 name7, kind8 name8, kind9 name9 // Lists the template parameters. #define GMOCK_INTERNAL_LIST_HAS_1_TEMPLATE_PARAMS(kind0, name0) name0 #define GMOCK_INTERNAL_LIST_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, \ name1) name0, name1 #define GMOCK_INTERNAL_LIST_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ kind2, name2) name0, name1, name2 #define GMOCK_INTERNAL_LIST_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ kind2, name2, kind3, name3) name0, name1, name2, name3 #define GMOCK_INTERNAL_LIST_HAS_5_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ kind2, name2, kind3, name3, kind4, name4) name0, name1, name2, name3, \ name4 #define GMOCK_INTERNAL_LIST_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ kind2, name2, kind3, name3, kind4, name4, kind5, name5) name0, name1, \ name2, name3, name4, name5 #define GMOCK_INTERNAL_LIST_HAS_7_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \ name6) name0, name1, name2, name3, name4, name5, name6 #define GMOCK_INTERNAL_LIST_HAS_8_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \ kind7, name7) name0, name1, name2, name3, name4, name5, name6, name7 #define GMOCK_INTERNAL_LIST_HAS_9_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \ kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, name6, \ kind7, name7, kind8, name8) name0, name1, name2, name3, name4, name5, \ name6, name7, name8 #define GMOCK_INTERNAL_LIST_HAS_10_TEMPLATE_PARAMS(kind0, name0, kind1, \ name1, kind2, name2, kind3, name3, kind4, name4, kind5, name5, kind6, \ name6, kind7, name7, kind8, name8, kind9, name9) name0, name1, name2, \ name3, name4, name5, name6, name7, name8, name9 // Declares the types of value parameters. #define GMOCK_INTERNAL_DECL_TYPE_AND_0_VALUE_PARAMS() #define GMOCK_INTERNAL_DECL_TYPE_AND_1_VALUE_PARAMS(p0) , typename p0##_type #define GMOCK_INTERNAL_DECL_TYPE_AND_2_VALUE_PARAMS(p0, p1) , \ typename p0##_type, typename p1##_type #define GMOCK_INTERNAL_DECL_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , \ typename p0##_type, typename p1##_type, typename p2##_type #define GMOCK_INTERNAL_DECL_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \ typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type #define GMOCK_INTERNAL_DECL_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \ typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type #define GMOCK_INTERNAL_DECL_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \ typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type #define GMOCK_INTERNAL_DECL_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ p6) , typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type #define GMOCK_INTERNAL_DECL_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ p6, p7) , typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type, typename p7##_type #define GMOCK_INTERNAL_DECL_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ p6, p7, p8) , typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type, typename p7##_type, typename p8##_type #define GMOCK_INTERNAL_DECL_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ p6, p7, p8, p9) , typename p0##_type, typename p1##_type, \ typename p2##_type, typename p3##_type, typename p4##_type, \ typename p5##_type, typename p6##_type, typename p7##_type, \ typename p8##_type, typename p9##_type // Initializes the value parameters. #define GMOCK_INTERNAL_INIT_AND_0_VALUE_PARAMS()\ () #define GMOCK_INTERNAL_INIT_AND_1_VALUE_PARAMS(p0)\ (p0##_type gmock_p0) : p0(gmock_p0) #define GMOCK_INTERNAL_INIT_AND_2_VALUE_PARAMS(p0, p1)\ (p0##_type gmock_p0, p1##_type gmock_p1) : p0(gmock_p0), p1(gmock_p1) #define GMOCK_INTERNAL_INIT_AND_3_VALUE_PARAMS(p0, p1, p2)\ (p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) #define GMOCK_INTERNAL_INIT_AND_4_VALUE_PARAMS(p0, p1, p2, p3)\ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ p3(gmock_p3) #define GMOCK_INTERNAL_INIT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)\ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4) : p0(gmock_p0), p1(gmock_p1), \ p2(gmock_p2), p3(gmock_p3), p4(gmock_p4) #define GMOCK_INTERNAL_INIT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)\ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, \ p5##_type gmock_p5) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ p3(gmock_p3), p4(gmock_p4), p5(gmock_p5) #define GMOCK_INTERNAL_INIT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)\ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ p6##_type gmock_p6) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6) #define GMOCK_INTERNAL_INIT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)\ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ p6##_type gmock_p6, p7##_type gmock_p7) : p0(gmock_p0), p1(gmock_p1), \ p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \ p7(gmock_p7) #define GMOCK_INTERNAL_INIT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ p7, p8)\ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ p6##_type gmock_p6, p7##_type gmock_p7, \ p8##_type gmock_p8) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \ p8(gmock_p8) #define GMOCK_INTERNAL_INIT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ p7, p8, p9)\ (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \ p9##_type gmock_p9) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \ p8(gmock_p8), p9(gmock_p9) // Declares the fields for storing the value parameters. #define GMOCK_INTERNAL_DEFN_AND_0_VALUE_PARAMS() #define GMOCK_INTERNAL_DEFN_AND_1_VALUE_PARAMS(p0) p0##_type p0; #define GMOCK_INTERNAL_DEFN_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0; \ p1##_type p1; #define GMOCK_INTERNAL_DEFN_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0; \ p1##_type p1; p2##_type p2; #define GMOCK_INTERNAL_DEFN_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0; \ p1##_type p1; p2##_type p2; p3##_type p3; #define GMOCK_INTERNAL_DEFN_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \ p4) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; #define GMOCK_INTERNAL_DEFN_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \ p5) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \ p5##_type p5; #define GMOCK_INTERNAL_DEFN_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ p6) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \ p5##_type p5; p6##_type p6; #define GMOCK_INTERNAL_DEFN_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ p7) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; p4##_type p4; \ p5##_type p5; p6##_type p6; p7##_type p7; #define GMOCK_INTERNAL_DEFN_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ p7, p8) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \ p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8; #define GMOCK_INTERNAL_DEFN_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ p7, p8, p9) p0##_type p0; p1##_type p1; p2##_type p2; p3##_type p3; \ p4##_type p4; p5##_type p5; p6##_type p6; p7##_type p7; p8##_type p8; \ p9##_type p9; // Lists the value parameters. #define GMOCK_INTERNAL_LIST_AND_0_VALUE_PARAMS() #define GMOCK_INTERNAL_LIST_AND_1_VALUE_PARAMS(p0) p0 #define GMOCK_INTERNAL_LIST_AND_2_VALUE_PARAMS(p0, p1) p0, p1 #define GMOCK_INTERNAL_LIST_AND_3_VALUE_PARAMS(p0, p1, p2) p0, p1, p2 #define GMOCK_INTERNAL_LIST_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0, p1, p2, p3 #define GMOCK_INTERNAL_LIST_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) p0, p1, \ p2, p3, p4 #define GMOCK_INTERNAL_LIST_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) p0, \ p1, p2, p3, p4, p5 #define GMOCK_INTERNAL_LIST_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ p6) p0, p1, p2, p3, p4, p5, p6 #define GMOCK_INTERNAL_LIST_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ p7) p0, p1, p2, p3, p4, p5, p6, p7 #define GMOCK_INTERNAL_LIST_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ p7, p8) p0, p1, p2, p3, p4, p5, p6, p7, p8 #define GMOCK_INTERNAL_LIST_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ p7, p8, p9) p0, p1, p2, p3, p4, p5, p6, p7, p8, p9 // Lists the value parameter types. #define GMOCK_INTERNAL_LIST_TYPE_AND_0_VALUE_PARAMS() #define GMOCK_INTERNAL_LIST_TYPE_AND_1_VALUE_PARAMS(p0) , p0##_type #define GMOCK_INTERNAL_LIST_TYPE_AND_2_VALUE_PARAMS(p0, p1) , p0##_type, \ p1##_type #define GMOCK_INTERNAL_LIST_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) , p0##_type, \ p1##_type, p2##_type #define GMOCK_INTERNAL_LIST_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) , \ p0##_type, p1##_type, p2##_type, p3##_type #define GMOCK_INTERNAL_LIST_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) , \ p0##_type, p1##_type, p2##_type, p3##_type, p4##_type #define GMOCK_INTERNAL_LIST_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) , \ p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type #define GMOCK_INTERNAL_LIST_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ p6) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, \ p6##_type #define GMOCK_INTERNAL_LIST_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ p6, p7) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ p5##_type, p6##_type, p7##_type #define GMOCK_INTERNAL_LIST_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ p6, p7, p8) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ p5##_type, p6##_type, p7##_type, p8##_type #define GMOCK_INTERNAL_LIST_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ p6, p7, p8, p9) , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ p5##_type, p6##_type, p7##_type, p8##_type, p9##_type // Declares the value parameters. #define GMOCK_INTERNAL_DECL_AND_0_VALUE_PARAMS() #define GMOCK_INTERNAL_DECL_AND_1_VALUE_PARAMS(p0) p0##_type p0 #define GMOCK_INTERNAL_DECL_AND_2_VALUE_PARAMS(p0, p1) p0##_type p0, \ p1##_type p1 #define GMOCK_INTERNAL_DECL_AND_3_VALUE_PARAMS(p0, p1, p2) p0##_type p0, \ p1##_type p1, p2##_type p2 #define GMOCK_INTERNAL_DECL_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0##_type p0, \ p1##_type p1, p2##_type p2, p3##_type p3 #define GMOCK_INTERNAL_DECL_AND_5_VALUE_PARAMS(p0, p1, p2, p3, \ p4) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4 #define GMOCK_INTERNAL_DECL_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, \ p5) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ p5##_type p5 #define GMOCK_INTERNAL_DECL_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \ p6) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ p5##_type p5, p6##_type p6 #define GMOCK_INTERNAL_DECL_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ p7) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \ p5##_type p5, p6##_type p6, p7##_type p7 #define GMOCK_INTERNAL_DECL_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ p7, p8) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8 #define GMOCK_INTERNAL_DECL_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ p7, p8, p9) p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \ p9##_type p9 // The suffix of the class template implementing the action template. #define GMOCK_INTERNAL_COUNT_AND_0_VALUE_PARAMS() #define GMOCK_INTERNAL_COUNT_AND_1_VALUE_PARAMS(p0) P #define GMOCK_INTERNAL_COUNT_AND_2_VALUE_PARAMS(p0, p1) P2 #define GMOCK_INTERNAL_COUNT_AND_3_VALUE_PARAMS(p0, p1, p2) P3 #define GMOCK_INTERNAL_COUNT_AND_4_VALUE_PARAMS(p0, p1, p2, p3) P4 #define GMOCK_INTERNAL_COUNT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) P5 #define GMOCK_INTERNAL_COUNT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) P6 #define GMOCK_INTERNAL_COUNT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) P7 #define GMOCK_INTERNAL_COUNT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ p7) P8 #define GMOCK_INTERNAL_COUNT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ p7, p8) P9 #define GMOCK_INTERNAL_COUNT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \ p7, p8, p9) P10 // The name of the class template implementing the action template. #define GMOCK_ACTION_CLASS_(name, value_params)\ GTEST_CONCAT_TOKEN_(name##Action, GMOCK_INTERNAL_COUNT_##value_params) #define ACTION_TEMPLATE(name, template_params, value_params)\ template <GMOCK_INTERNAL_DECL_##template_params\ GMOCK_INTERNAL_DECL_TYPE_##value_params>\ class GMOCK_ACTION_CLASS_(name, value_params) {\ public:\ explicit GMOCK_ACTION_CLASS_(name, value_params)\ GMOCK_INTERNAL_INIT_##value_params {}\ template <typename F>\ class gmock_Impl : public ::testing::ActionInterface<F> {\ public:\ typedef F function_type;\ typedef typename ::testing::internal::Function<F>::Result return_type;\ typedef typename ::testing::internal::Function<F>::ArgumentTuple\ args_type;\ explicit gmock_Impl GMOCK_INTERNAL_INIT_##value_params {}\ virtual return_type Perform(const args_type& args) {\ return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\ Perform(this, args);\ }\ template <typename arg0_type, typename arg1_type, typename arg2_type, \ typename arg3_type, typename arg4_type, typename arg5_type, \ typename arg6_type, typename arg7_type, typename arg8_type, \ typename arg9_type>\ return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \ arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \ arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \ arg9_type arg9) const;\ GMOCK_INTERNAL_DEFN_##value_params\ private:\ GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename F> operator ::testing::Action<F>() const {\ return ::testing::Action<F>(\ new gmock_Impl<F>(GMOCK_INTERNAL_LIST_##value_params));\ }\ GMOCK_INTERNAL_DEFN_##value_params\ private:\ GTEST_DISALLOW_ASSIGN_(GMOCK_ACTION_CLASS_(name, value_params));\ };\ template <GMOCK_INTERNAL_DECL_##template_params\ GMOCK_INTERNAL_DECL_TYPE_##value_params>\ inline GMOCK_ACTION_CLASS_(name, value_params)<\ GMOCK_INTERNAL_LIST_##template_params\ GMOCK_INTERNAL_LIST_TYPE_##value_params> name(\ GMOCK_INTERNAL_DECL_##value_params) {\ return GMOCK_ACTION_CLASS_(name, value_params)<\ GMOCK_INTERNAL_LIST_##template_params\ GMOCK_INTERNAL_LIST_TYPE_##value_params>(\ GMOCK_INTERNAL_LIST_##value_params);\ }\ template <GMOCK_INTERNAL_DECL_##template_params\ GMOCK_INTERNAL_DECL_TYPE_##value_params>\ template <typename F>\ template <typename arg0_type, typename arg1_type, typename arg2_type, \ typename arg3_type, typename arg4_type, typename arg5_type, \ typename arg6_type, typename arg7_type, typename arg8_type, \ typename arg9_type>\ typename ::testing::internal::Function<F>::Result\ GMOCK_ACTION_CLASS_(name, value_params)<\ GMOCK_INTERNAL_LIST_##template_params\ GMOCK_INTERNAL_LIST_TYPE_##value_params>::gmock_Impl<F>::\ gmock_PerformImpl(\ GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const #define ACTION(name)\ class name##Action {\ public:\ name##Action() {}\ template <typename F>\ class gmock_Impl : public ::testing::ActionInterface<F> {\ public:\ typedef F function_type;\ typedef typename ::testing::internal::Function<F>::Result return_type;\ typedef typename ::testing::internal::Function<F>::ArgumentTuple\ args_type;\ gmock_Impl() {}\ virtual return_type Perform(const args_type& args) {\ return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\ Perform(this, args);\ }\ template <typename arg0_type, typename arg1_type, typename arg2_type, \ typename arg3_type, typename arg4_type, typename arg5_type, \ typename arg6_type, typename arg7_type, typename arg8_type, \ typename arg9_type>\ return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \ arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \ arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \ arg9_type arg9) const;\ private:\ GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename F> operator ::testing::Action<F>() const {\ return ::testing::Action<F>(new gmock_Impl<F>());\ }\ private:\ GTEST_DISALLOW_ASSIGN_(name##Action);\ };\ inline name##Action name() {\ return name##Action();\ }\ template <typename F>\ template <typename arg0_type, typename arg1_type, typename arg2_type, \ typename arg3_type, typename arg4_type, typename arg5_type, \ typename arg6_type, typename arg7_type, typename arg8_type, \ typename arg9_type>\ typename ::testing::internal::Function<F>::Result\ name##Action::gmock_Impl<F>::gmock_PerformImpl(\ GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const #define ACTION_P(name, p0)\ template <typename p0##_type>\ class name##ActionP {\ public:\ explicit name##ActionP(p0##_type gmock_p0) : p0(gmock_p0) {}\ template <typename F>\ class gmock_Impl : public ::testing::ActionInterface<F> {\ public:\ typedef F function_type;\ typedef typename ::testing::internal::Function<F>::Result return_type;\ typedef typename ::testing::internal::Function<F>::ArgumentTuple\ args_type;\ explicit gmock_Impl(p0##_type gmock_p0) : p0(gmock_p0) {}\ virtual return_type Perform(const args_type& args) {\ return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\ Perform(this, args);\ }\ template <typename arg0_type, typename arg1_type, typename arg2_type, \ typename arg3_type, typename arg4_type, typename arg5_type, \ typename arg6_type, typename arg7_type, typename arg8_type, \ typename arg9_type>\ return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \ arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \ arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \ arg9_type arg9) const;\ p0##_type p0;\ private:\ GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename F> operator ::testing::Action<F>() const {\ return ::testing::Action<F>(new gmock_Impl<F>(p0));\ }\ p0##_type p0;\ private:\ GTEST_DISALLOW_ASSIGN_(name##ActionP);\ };\ template <typename p0##_type>\ inline name##ActionP<p0##_type> name(p0##_type p0) {\ return name##ActionP<p0##_type>(p0);\ }\ template <typename p0##_type>\ template <typename F>\ template <typename arg0_type, typename arg1_type, typename arg2_type, \ typename arg3_type, typename arg4_type, typename arg5_type, \ typename arg6_type, typename arg7_type, typename arg8_type, \ typename arg9_type>\ typename ::testing::internal::Function<F>::Result\ name##ActionP<p0##_type>::gmock_Impl<F>::gmock_PerformImpl(\ GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const #define ACTION_P2(name, p0, p1)\ template <typename p0##_type, typename p1##_type>\ class name##ActionP2 {\ public:\ name##ActionP2(p0##_type gmock_p0, p1##_type gmock_p1) : p0(gmock_p0), \ p1(gmock_p1) {}\ template <typename F>\ class gmock_Impl : public ::testing::ActionInterface<F> {\ public:\ typedef F function_type;\ typedef typename ::testing::internal::Function<F>::Result return_type;\ typedef typename ::testing::internal::Function<F>::ArgumentTuple\ args_type;\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1) : p0(gmock_p0), \ p1(gmock_p1) {}\ virtual return_type Perform(const args_type& args) {\ return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\ Perform(this, args);\ }\ template <typename arg0_type, typename arg1_type, typename arg2_type, \ typename arg3_type, typename arg4_type, typename arg5_type, \ typename arg6_type, typename arg7_type, typename arg8_type, \ typename arg9_type>\ return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \ arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \ arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \ arg9_type arg9) const;\ p0##_type p0;\ p1##_type p1;\ private:\ GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename F> operator ::testing::Action<F>() const {\ return ::testing::Action<F>(new gmock_Impl<F>(p0, p1));\ }\ p0##_type p0;\ p1##_type p1;\ private:\ GTEST_DISALLOW_ASSIGN_(name##ActionP2);\ };\ template <typename p0##_type, typename p1##_type>\ inline name##ActionP2<p0##_type, p1##_type> name(p0##_type p0, \ p1##_type p1) {\ return name##ActionP2<p0##_type, p1##_type>(p0, p1);\ }\ template <typename p0##_type, typename p1##_type>\ template <typename F>\ template <typename arg0_type, typename arg1_type, typename arg2_type, \ typename arg3_type, typename arg4_type, typename arg5_type, \ typename arg6_type, typename arg7_type, typename arg8_type, \ typename arg9_type>\ typename ::testing::internal::Function<F>::Result\ name##ActionP2<p0##_type, p1##_type>::gmock_Impl<F>::gmock_PerformImpl(\ GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const #define ACTION_P3(name, p0, p1, p2)\ template <typename p0##_type, typename p1##_type, typename p2##_type>\ class name##ActionP3 {\ public:\ name##ActionP3(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) {}\ template <typename F>\ class gmock_Impl : public ::testing::ActionInterface<F> {\ public:\ typedef F function_type;\ typedef typename ::testing::internal::Function<F>::Result return_type;\ typedef typename ::testing::internal::Function<F>::ArgumentTuple\ args_type;\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) {}\ virtual return_type Perform(const args_type& args) {\ return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\ Perform(this, args);\ }\ template <typename arg0_type, typename arg1_type, typename arg2_type, \ typename arg3_type, typename arg4_type, typename arg5_type, \ typename arg6_type, typename arg7_type, typename arg8_type, \ typename arg9_type>\ return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \ arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \ arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \ arg9_type arg9) const;\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ private:\ GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename F> operator ::testing::Action<F>() const {\ return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2));\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ private:\ GTEST_DISALLOW_ASSIGN_(name##ActionP3);\ };\ template <typename p0##_type, typename p1##_type, typename p2##_type>\ inline name##ActionP3<p0##_type, p1##_type, p2##_type> name(p0##_type p0, \ p1##_type p1, p2##_type p2) {\ return name##ActionP3<p0##_type, p1##_type, p2##_type>(p0, p1, p2);\ }\ template <typename p0##_type, typename p1##_type, typename p2##_type>\ template <typename F>\ template <typename arg0_type, typename arg1_type, typename arg2_type, \ typename arg3_type, typename arg4_type, typename arg5_type, \ typename arg6_type, typename arg7_type, typename arg8_type, \ typename arg9_type>\ typename ::testing::internal::Function<F>::Result\ name##ActionP3<p0##_type, p1##_type, \ p2##_type>::gmock_Impl<F>::gmock_PerformImpl(\ GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const #define ACTION_P4(name, p0, p1, p2, p3)\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type>\ class name##ActionP4 {\ public:\ name##ActionP4(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2, p3##_type gmock_p3) : p0(gmock_p0), p1(gmock_p1), \ p2(gmock_p2), p3(gmock_p3) {}\ template <typename F>\ class gmock_Impl : public ::testing::ActionInterface<F> {\ public:\ typedef F function_type;\ typedef typename ::testing::internal::Function<F>::Result return_type;\ typedef typename ::testing::internal::Function<F>::ArgumentTuple\ args_type;\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ p3(gmock_p3) {}\ virtual return_type Perform(const args_type& args) {\ return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\ Perform(this, args);\ }\ template <typename arg0_type, typename arg1_type, typename arg2_type, \ typename arg3_type, typename arg4_type, typename arg5_type, \ typename arg6_type, typename arg7_type, typename arg8_type, \ typename arg9_type>\ return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \ arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \ arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \ arg9_type arg9) const;\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ private:\ GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename F> operator ::testing::Action<F>() const {\ return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3));\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ private:\ GTEST_DISALLOW_ASSIGN_(name##ActionP4);\ };\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type>\ inline name##ActionP4<p0##_type, p1##_type, p2##_type, \ p3##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, \ p3##_type p3) {\ return name##ActionP4<p0##_type, p1##_type, p2##_type, p3##_type>(p0, p1, \ p2, p3);\ }\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type>\ template <typename F>\ template <typename arg0_type, typename arg1_type, typename arg2_type, \ typename arg3_type, typename arg4_type, typename arg5_type, \ typename arg6_type, typename arg7_type, typename arg8_type, \ typename arg9_type>\ typename ::testing::internal::Function<F>::Result\ name##ActionP4<p0##_type, p1##_type, p2##_type, \ p3##_type>::gmock_Impl<F>::gmock_PerformImpl(\ GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const #define ACTION_P5(name, p0, p1, p2, p3, p4)\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type>\ class name##ActionP5 {\ public:\ name##ActionP5(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2, p3##_type gmock_p3, \ p4##_type gmock_p4) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ p3(gmock_p3), p4(gmock_p4) {}\ template <typename F>\ class gmock_Impl : public ::testing::ActionInterface<F> {\ public:\ typedef F function_type;\ typedef typename ::testing::internal::Function<F>::Result return_type;\ typedef typename ::testing::internal::Function<F>::ArgumentTuple\ args_type;\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4) : p0(gmock_p0), \ p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), p4(gmock_p4) {}\ virtual return_type Perform(const args_type& args) {\ return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\ Perform(this, args);\ }\ template <typename arg0_type, typename arg1_type, typename arg2_type, \ typename arg3_type, typename arg4_type, typename arg5_type, \ typename arg6_type, typename arg7_type, typename arg8_type, \ typename arg9_type>\ return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \ arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \ arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \ arg9_type arg9) const;\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ p4##_type p4;\ private:\ GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename F> operator ::testing::Action<F>() const {\ return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3, p4));\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ p4##_type p4;\ private:\ GTEST_DISALLOW_ASSIGN_(name##ActionP5);\ };\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type>\ inline name##ActionP5<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ p4##_type p4) {\ return name##ActionP5<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type>(p0, p1, p2, p3, p4);\ }\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type>\ template <typename F>\ template <typename arg0_type, typename arg1_type, typename arg2_type, \ typename arg3_type, typename arg4_type, typename arg5_type, \ typename arg6_type, typename arg7_type, typename arg8_type, \ typename arg9_type>\ typename ::testing::internal::Function<F>::Result\ name##ActionP5<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type>::gmock_Impl<F>::gmock_PerformImpl(\ GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const #define ACTION_P6(name, p0, p1, p2, p3, p4, p5)\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type>\ class name##ActionP6 {\ public:\ name##ActionP6(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ p5##_type gmock_p5) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ p3(gmock_p3), p4(gmock_p4), p5(gmock_p5) {}\ template <typename F>\ class gmock_Impl : public ::testing::ActionInterface<F> {\ public:\ typedef F function_type;\ typedef typename ::testing::internal::Function<F>::Result return_type;\ typedef typename ::testing::internal::Function<F>::ArgumentTuple\ args_type;\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, \ p5##_type gmock_p5) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ p3(gmock_p3), p4(gmock_p4), p5(gmock_p5) {}\ virtual return_type Perform(const args_type& args) {\ return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\ Perform(this, args);\ }\ template <typename arg0_type, typename arg1_type, typename arg2_type, \ typename arg3_type, typename arg4_type, typename arg5_type, \ typename arg6_type, typename arg7_type, typename arg8_type, \ typename arg9_type>\ return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \ arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \ arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \ arg9_type arg9) const;\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ p4##_type p4;\ p5##_type p5;\ private:\ GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename F> operator ::testing::Action<F>() const {\ return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3, p4, p5));\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ p4##_type p4;\ p5##_type p5;\ private:\ GTEST_DISALLOW_ASSIGN_(name##ActionP6);\ };\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type>\ inline name##ActionP6<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, \ p3##_type p3, p4##_type p4, p5##_type p5) {\ return name##ActionP6<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type>(p0, p1, p2, p3, p4, p5);\ }\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type>\ template <typename F>\ template <typename arg0_type, typename arg1_type, typename arg2_type, \ typename arg3_type, typename arg4_type, typename arg5_type, \ typename arg6_type, typename arg7_type, typename arg8_type, \ typename arg9_type>\ typename ::testing::internal::Function<F>::Result\ name##ActionP6<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ p5##_type>::gmock_Impl<F>::gmock_PerformImpl(\ GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const #define ACTION_P7(name, p0, p1, p2, p3, p4, p5, p6)\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type>\ class name##ActionP7 {\ public:\ name##ActionP7(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ p5##_type gmock_p5, p6##_type gmock_p6) : p0(gmock_p0), p1(gmock_p1), \ p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), \ p6(gmock_p6) {}\ template <typename F>\ class gmock_Impl : public ::testing::ActionInterface<F> {\ public:\ typedef F function_type;\ typedef typename ::testing::internal::Function<F>::Result return_type;\ typedef typename ::testing::internal::Function<F>::ArgumentTuple\ args_type;\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ p6##_type gmock_p6) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6) {}\ virtual return_type Perform(const args_type& args) {\ return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\ Perform(this, args);\ }\ template <typename arg0_type, typename arg1_type, typename arg2_type, \ typename arg3_type, typename arg4_type, typename arg5_type, \ typename arg6_type, typename arg7_type, typename arg8_type, \ typename arg9_type>\ return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \ arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \ arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \ arg9_type arg9) const;\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ p4##_type p4;\ p5##_type p5;\ p6##_type p6;\ private:\ GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename F> operator ::testing::Action<F>() const {\ return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3, p4, p5, \ p6));\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ p4##_type p4;\ p5##_type p5;\ p6##_type p6;\ private:\ GTEST_DISALLOW_ASSIGN_(name##ActionP7);\ };\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type>\ inline name##ActionP7<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type> name(p0##_type p0, p1##_type p1, \ p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \ p6##_type p6) {\ return name##ActionP7<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type>(p0, p1, p2, p3, p4, p5, p6);\ }\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type>\ template <typename F>\ template <typename arg0_type, typename arg1_type, typename arg2_type, \ typename arg3_type, typename arg4_type, typename arg5_type, \ typename arg6_type, typename arg7_type, typename arg8_type, \ typename arg9_type>\ typename ::testing::internal::Function<F>::Result\ name##ActionP7<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ p5##_type, p6##_type>::gmock_Impl<F>::gmock_PerformImpl(\ GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const #define ACTION_P8(name, p0, p1, p2, p3, p4, p5, p6, p7)\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type, typename p7##_type>\ class name##ActionP8 {\ public:\ name##ActionP8(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ p5##_type gmock_p5, p6##_type gmock_p6, \ p7##_type gmock_p7) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \ p7(gmock_p7) {}\ template <typename F>\ class gmock_Impl : public ::testing::ActionInterface<F> {\ public:\ typedef F function_type;\ typedef typename ::testing::internal::Function<F>::Result return_type;\ typedef typename ::testing::internal::Function<F>::ArgumentTuple\ args_type;\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ p6##_type gmock_p6, p7##_type gmock_p7) : p0(gmock_p0), \ p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), \ p5(gmock_p5), p6(gmock_p6), p7(gmock_p7) {}\ virtual return_type Perform(const args_type& args) {\ return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\ Perform(this, args);\ }\ template <typename arg0_type, typename arg1_type, typename arg2_type, \ typename arg3_type, typename arg4_type, typename arg5_type, \ typename arg6_type, typename arg7_type, typename arg8_type, \ typename arg9_type>\ return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \ arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \ arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \ arg9_type arg9) const;\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ p4##_type p4;\ p5##_type p5;\ p6##_type p6;\ p7##_type p7;\ private:\ GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename F> operator ::testing::Action<F>() const {\ return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3, p4, p5, \ p6, p7));\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ p4##_type p4;\ p5##_type p5;\ p6##_type p6;\ p7##_type p7;\ private:\ GTEST_DISALLOW_ASSIGN_(name##ActionP8);\ };\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type, typename p7##_type>\ inline name##ActionP8<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type, p7##_type> name(p0##_type p0, \ p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \ p6##_type p6, p7##_type p7) {\ return name##ActionP8<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type, p7##_type>(p0, p1, p2, p3, p4, p5, \ p6, p7);\ }\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type, typename p7##_type>\ template <typename F>\ template <typename arg0_type, typename arg1_type, typename arg2_type, \ typename arg3_type, typename arg4_type, typename arg5_type, \ typename arg6_type, typename arg7_type, typename arg8_type, \ typename arg9_type>\ typename ::testing::internal::Function<F>::Result\ name##ActionP8<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ p5##_type, p6##_type, \ p7##_type>::gmock_Impl<F>::gmock_PerformImpl(\ GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const #define ACTION_P9(name, p0, p1, p2, p3, p4, p5, p6, p7, p8)\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type, typename p7##_type, typename p8##_type>\ class name##ActionP9 {\ public:\ name##ActionP9(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \ p8##_type gmock_p8) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \ p8(gmock_p8) {}\ template <typename F>\ class gmock_Impl : public ::testing::ActionInterface<F> {\ public:\ typedef F function_type;\ typedef typename ::testing::internal::Function<F>::Result return_type;\ typedef typename ::testing::internal::Function<F>::ArgumentTuple\ args_type;\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ p6##_type gmock_p6, p7##_type gmock_p7, \ p8##_type gmock_p8) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \ p7(gmock_p7), p8(gmock_p8) {}\ virtual return_type Perform(const args_type& args) {\ return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\ Perform(this, args);\ }\ template <typename arg0_type, typename arg1_type, typename arg2_type, \ typename arg3_type, typename arg4_type, typename arg5_type, \ typename arg6_type, typename arg7_type, typename arg8_type, \ typename arg9_type>\ return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \ arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \ arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \ arg9_type arg9) const;\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ p4##_type p4;\ p5##_type p5;\ p6##_type p6;\ p7##_type p7;\ p8##_type p8;\ private:\ GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename F> operator ::testing::Action<F>() const {\ return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3, p4, p5, \ p6, p7, p8));\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ p4##_type p4;\ p5##_type p5;\ p6##_type p6;\ p7##_type p7;\ p8##_type p8;\ private:\ GTEST_DISALLOW_ASSIGN_(name##ActionP9);\ };\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type, typename p7##_type, typename p8##_type>\ inline name##ActionP9<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type, p7##_type, \ p8##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, \ p8##_type p8) {\ return name##ActionP9<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type, p7##_type, p8##_type>(p0, p1, p2, \ p3, p4, p5, p6, p7, p8);\ }\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type, typename p7##_type, typename p8##_type>\ template <typename F>\ template <typename arg0_type, typename arg1_type, typename arg2_type, \ typename arg3_type, typename arg4_type, typename arg5_type, \ typename arg6_type, typename arg7_type, typename arg8_type, \ typename arg9_type>\ typename ::testing::internal::Function<F>::Result\ name##ActionP9<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ p5##_type, p6##_type, p7##_type, \ p8##_type>::gmock_Impl<F>::gmock_PerformImpl(\ GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const #define ACTION_P10(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type, typename p7##_type, typename p8##_type, \ typename p9##_type>\ class name##ActionP10 {\ public:\ name##ActionP10(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \ p8##_type gmock_p8, p9##_type gmock_p9) : p0(gmock_p0), p1(gmock_p1), \ p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \ p7(gmock_p7), p8(gmock_p8), p9(gmock_p9) {}\ template <typename F>\ class gmock_Impl : public ::testing::ActionInterface<F> {\ public:\ typedef F function_type;\ typedef typename ::testing::internal::Function<F>::Result return_type;\ typedef typename ::testing::internal::Function<F>::ArgumentTuple\ args_type;\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \ p9##_type gmock_p9) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \ p7(gmock_p7), p8(gmock_p8), p9(gmock_p9) {}\ virtual return_type Perform(const args_type& args) {\ return ::testing::internal::ActionHelper<return_type, gmock_Impl>::\ Perform(this, args);\ }\ template <typename arg0_type, typename arg1_type, typename arg2_type, \ typename arg3_type, typename arg4_type, typename arg5_type, \ typename arg6_type, typename arg7_type, typename arg8_type, \ typename arg9_type>\ return_type gmock_PerformImpl(const args_type& args, arg0_type arg0, \ arg1_type arg1, arg2_type arg2, arg3_type arg3, arg4_type arg4, \ arg5_type arg5, arg6_type arg6, arg7_type arg7, arg8_type arg8, \ arg9_type arg9) const;\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ p4##_type p4;\ p5##_type p5;\ p6##_type p6;\ p7##_type p7;\ p8##_type p8;\ p9##_type p9;\ private:\ GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename F> operator ::testing::Action<F>() const {\ return ::testing::Action<F>(new gmock_Impl<F>(p0, p1, p2, p3, p4, p5, \ p6, p7, p8, p9));\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ p4##_type p4;\ p5##_type p5;\ p6##_type p6;\ p7##_type p7;\ p8##_type p8;\ p9##_type p9;\ private:\ GTEST_DISALLOW_ASSIGN_(name##ActionP10);\ };\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type, typename p7##_type, typename p8##_type, \ typename p9##_type>\ inline name##ActionP10<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, \ p9##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \ p9##_type p9) {\ return name##ActionP10<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, p9##_type>(p0, \ p1, p2, p3, p4, p5, p6, p7, p8, p9);\ }\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type, typename p7##_type, typename p8##_type, \ typename p9##_type>\ template <typename F>\ template <typename arg0_type, typename arg1_type, typename arg2_type, \ typename arg3_type, typename arg4_type, typename arg5_type, \ typename arg6_type, typename arg7_type, typename arg8_type, \ typename arg9_type>\ typename ::testing::internal::Function<F>::Result\ name##ActionP10<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ p5##_type, p6##_type, p7##_type, p8##_type, \ p9##_type>::gmock_Impl<F>::gmock_PerformImpl(\ GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const namespace testing { // The ACTION*() macros trigger warning C4100 (unreferenced formal // parameter) in MSVC with -W4. Unfortunately they cannot be fixed in // the macro definition, as the warnings are generated when the macro // is expanded and macro expansion cannot contain #pragma. Therefore // we suppress them here. #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable:4100) #endif // Various overloads for InvokeArgument<N>(). // // The InvokeArgument<N>(a1, a2, ..., a_k) action invokes the N-th // (0-based) argument, which must be a k-ary callable, of the mock // function, with arguments a1, a2, ..., a_k. // // Notes: // // 1. The arguments are passed by value by default. If you need to // pass an argument by reference, wrap it inside ByRef(). For // example, // // InvokeArgument<1>(5, string("Hello"), ByRef(foo)) // // passes 5 and string("Hello") by value, and passes foo by // reference. // // 2. If the callable takes an argument by reference but ByRef() is // not used, it will receive the reference to a copy of the value, // instead of the original value. For example, when the 0-th // argument of the mock function takes a const string&, the action // // InvokeArgument<0>(string("Hello")) // // makes a copy of the temporary string("Hello") object and passes a // reference of the copy, instead of the original temporary object, // to the callable. This makes it easy for a user to define an // InvokeArgument action from temporary values and have it performed // later. namespace internal { namespace invoke_argument { // Appears in InvokeArgumentAdl's argument list to help avoid // accidental calls to user functions of the same name. struct AdlTag {}; // InvokeArgumentAdl - a helper for InvokeArgument. // The basic overloads are provided here for generic functors. // Overloads for other custom-callables are provided in the // internal/custom/callback-actions.h header. template <typename R, typename F> R InvokeArgumentAdl(AdlTag, F f) { return f(); } template <typename R, typename F, typename A1> R InvokeArgumentAdl(AdlTag, F f, A1 a1) { return f(a1); } template <typename R, typename F, typename A1, typename A2> R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2) { return f(a1, a2); } template <typename R, typename F, typename A1, typename A2, typename A3> R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3) { return f(a1, a2, a3); } template <typename R, typename F, typename A1, typename A2, typename A3, typename A4> R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4) { return f(a1, a2, a3, a4); } template <typename R, typename F, typename A1, typename A2, typename A3, typename A4, typename A5> R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5) { return f(a1, a2, a3, a4, a5); } template <typename R, typename F, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6> R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6) { return f(a1, a2, a3, a4, a5, a6); } template <typename R, typename F, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7> R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7) { return f(a1, a2, a3, a4, a5, a6, a7); } template <typename R, typename F, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8> R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8) { return f(a1, a2, a3, a4, a5, a6, a7, a8); } template <typename R, typename F, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8, typename A9> R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8, A9 a9) { return f(a1, a2, a3, a4, a5, a6, a7, a8, a9); } template <typename R, typename F, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8, typename A9, typename A10> R InvokeArgumentAdl(AdlTag, F f, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8, A9 a9, A10 a10) { return f(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10); } } // namespace invoke_argument } // namespace internal ACTION_TEMPLATE(InvokeArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_0_VALUE_PARAMS()) { using internal::invoke_argument::InvokeArgumentAdl; return InvokeArgumentAdl<return_type>( internal::invoke_argument::AdlTag(), ::testing::get<k>(args)); } ACTION_TEMPLATE(InvokeArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_1_VALUE_PARAMS(p0)) { using internal::invoke_argument::InvokeArgumentAdl; return InvokeArgumentAdl<return_type>( internal::invoke_argument::AdlTag(), ::testing::get<k>(args), p0); } ACTION_TEMPLATE(InvokeArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_2_VALUE_PARAMS(p0, p1)) { using internal::invoke_argument::InvokeArgumentAdl; return InvokeArgumentAdl<return_type>( internal::invoke_argument::AdlTag(), ::testing::get<k>(args), p0, p1); } ACTION_TEMPLATE(InvokeArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_3_VALUE_PARAMS(p0, p1, p2)) { using internal::invoke_argument::InvokeArgumentAdl; return InvokeArgumentAdl<return_type>( internal::invoke_argument::AdlTag(), ::testing::get<k>(args), p0, p1, p2); } ACTION_TEMPLATE(InvokeArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_4_VALUE_PARAMS(p0, p1, p2, p3)) { using internal::invoke_argument::InvokeArgumentAdl; return InvokeArgumentAdl<return_type>( internal::invoke_argument::AdlTag(), ::testing::get<k>(args), p0, p1, p2, p3); } ACTION_TEMPLATE(InvokeArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)) { using internal::invoke_argument::InvokeArgumentAdl; return InvokeArgumentAdl<return_type>( internal::invoke_argument::AdlTag(), ::testing::get<k>(args), p0, p1, p2, p3, p4); } ACTION_TEMPLATE(InvokeArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)) { using internal::invoke_argument::InvokeArgumentAdl; return InvokeArgumentAdl<return_type>( internal::invoke_argument::AdlTag(), ::testing::get<k>(args), p0, p1, p2, p3, p4, p5); } ACTION_TEMPLATE(InvokeArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)) { using internal::invoke_argument::InvokeArgumentAdl; return InvokeArgumentAdl<return_type>( internal::invoke_argument::AdlTag(), ::testing::get<k>(args), p0, p1, p2, p3, p4, p5, p6); } ACTION_TEMPLATE(InvokeArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)) { using internal::invoke_argument::InvokeArgumentAdl; return InvokeArgumentAdl<return_type>( internal::invoke_argument::AdlTag(), ::testing::get<k>(args), p0, p1, p2, p3, p4, p5, p6, p7); } ACTION_TEMPLATE(InvokeArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8)) { using internal::invoke_argument::InvokeArgumentAdl; return InvokeArgumentAdl<return_type>( internal::invoke_argument::AdlTag(), ::testing::get<k>(args), p0, p1, p2, p3, p4, p5, p6, p7, p8); } ACTION_TEMPLATE(InvokeArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)) { using internal::invoke_argument::InvokeArgumentAdl; return InvokeArgumentAdl<return_type>( internal::invoke_argument::AdlTag(), ::testing::get<k>(args), p0, p1, p2, p3, p4, p5, p6, p7, p8, p9); } // Various overloads for ReturnNew<T>(). // // The ReturnNew<T>(a1, a2, ..., a_k) action returns a pointer to a new // instance of type T, constructed on the heap with constructor arguments // a1, a2, ..., and a_k. The caller assumes ownership of the returned value. ACTION_TEMPLATE(ReturnNew, HAS_1_TEMPLATE_PARAMS(typename, T), AND_0_VALUE_PARAMS()) { return new T(); } ACTION_TEMPLATE(ReturnNew, HAS_1_TEMPLATE_PARAMS(typename, T), AND_1_VALUE_PARAMS(p0)) { return new T(p0); } ACTION_TEMPLATE(ReturnNew, HAS_1_TEMPLATE_PARAMS(typename, T), AND_2_VALUE_PARAMS(p0, p1)) { return new T(p0, p1); } ACTION_TEMPLATE(ReturnNew, HAS_1_TEMPLATE_PARAMS(typename, T), AND_3_VALUE_PARAMS(p0, p1, p2)) { return new T(p0, p1, p2); } ACTION_TEMPLATE(ReturnNew, HAS_1_TEMPLATE_PARAMS(typename, T), AND_4_VALUE_PARAMS(p0, p1, p2, p3)) { return new T(p0, p1, p2, p3); } ACTION_TEMPLATE(ReturnNew, HAS_1_TEMPLATE_PARAMS(typename, T), AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4)) { return new T(p0, p1, p2, p3, p4); } ACTION_TEMPLATE(ReturnNew, HAS_1_TEMPLATE_PARAMS(typename, T), AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)) { return new T(p0, p1, p2, p3, p4, p5); } ACTION_TEMPLATE(ReturnNew, HAS_1_TEMPLATE_PARAMS(typename, T), AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6)) { return new T(p0, p1, p2, p3, p4, p5, p6); } ACTION_TEMPLATE(ReturnNew, HAS_1_TEMPLATE_PARAMS(typename, T), AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7)) { return new T(p0, p1, p2, p3, p4, p5, p6, p7); } ACTION_TEMPLATE(ReturnNew, HAS_1_TEMPLATE_PARAMS(typename, T), AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8)) { return new T(p0, p1, p2, p3, p4, p5, p6, p7, p8); } ACTION_TEMPLATE(ReturnNew, HAS_1_TEMPLATE_PARAMS(typename, T), AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)) { return new T(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9); } #ifdef _MSC_VER # pragma warning(pop) #endif } // namespace testing // Include any custom actions added by the local installation. // We must include this header at the end to make sure it can use the // declarations from this file. #include "gmock/internal/custom/gmock-generated-actions.h" #endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_ACTIONS_H_
0
repos/DirectXShaderCompiler/utils/unittest/googlemock/include
repos/DirectXShaderCompiler/utils/unittest/googlemock/include/gmock/gmock-generated-nice-strict.h
// This file was GENERATED by command: // pump.py gmock-generated-nice-strict.h.pump // DO NOT EDIT BY HAND!!! // 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. // // Author: [email protected] (Zhanyong Wan) // Implements class templates NiceMock, NaggyMock, and StrictMock. // // Given a mock class MockFoo that is created using Google Mock, // NiceMock<MockFoo> is a subclass of MockFoo that allows // uninteresting calls (i.e. calls to mock methods that have no // EXPECT_CALL specs), NaggyMock<MockFoo> is a subclass of MockFoo // that prints a warning when an uninteresting call occurs, and // StrictMock<MockFoo> is a subclass of MockFoo that treats all // uninteresting calls as errors. // // Currently a mock is naggy by default, so MockFoo and // NaggyMock<MockFoo> behave like the same. However, we will soon // switch the default behavior of mocks to be nice, as that in general // leads to more maintainable tests. When that happens, MockFoo will // stop behaving like NaggyMock<MockFoo> and start behaving like // NiceMock<MockFoo>. // // NiceMock, NaggyMock, and StrictMock "inherit" the constructors of // their respective base class, with up-to 10 arguments. Therefore // you can write NiceMock<MockFoo>(5, "a") to construct a nice mock // where MockFoo has a constructor that accepts (int, const char*), // for example. // // A known limitation is that NiceMock<MockFoo>, NaggyMock<MockFoo>, // and StrictMock<MockFoo> only works for mock methods defined using // the MOCK_METHOD* family of macros DIRECTLY in the MockFoo class. // If a mock method is defined in a base class of MockFoo, the "nice" // or "strict" modifier may not affect it, depending on the compiler. // In particular, nesting NiceMock, NaggyMock, and StrictMock is NOT // supported. // // Another known limitation is that the constructors of the base mock // cannot have arguments passed by non-const reference, which are // banned by the Google C++ style guide anyway. #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_ #include "gmock/gmock-spec-builders.h" #include "gmock/internal/gmock-port.h" namespace testing { template <class MockClass> class NiceMock : public MockClass { public: // We don't factor out the constructor body to a common method, as // we have to avoid a possible clash with members of MockClass. NiceMock() { ::testing::Mock::AllowUninterestingCalls( internal::ImplicitCast_<MockClass*>(this)); } // C++ doesn't (yet) allow inheritance of constructors, so we have // to define it for each arity. template <typename A1> explicit NiceMock(const A1& a1) : MockClass(a1) { ::testing::Mock::AllowUninterestingCalls( internal::ImplicitCast_<MockClass*>(this)); } template <typename A1, typename A2> NiceMock(const A1& a1, const A2& a2) : MockClass(a1, a2) { ::testing::Mock::AllowUninterestingCalls( internal::ImplicitCast_<MockClass*>(this)); } template <typename A1, typename A2, typename A3> NiceMock(const A1& a1, const A2& a2, const A3& a3) : MockClass(a1, a2, a3) { ::testing::Mock::AllowUninterestingCalls( internal::ImplicitCast_<MockClass*>(this)); } template <typename A1, typename A2, typename A3, typename A4> NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4) : MockClass(a1, a2, a3, a4) { ::testing::Mock::AllowUninterestingCalls( internal::ImplicitCast_<MockClass*>(this)); } template <typename A1, typename A2, typename A3, typename A4, typename A5> NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5) : MockClass(a1, a2, a3, a4, a5) { ::testing::Mock::AllowUninterestingCalls( internal::ImplicitCast_<MockClass*>(this)); } template <typename A1, typename A2, typename A3, typename A4, typename A5, typename A6> NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6) : MockClass(a1, a2, a3, a4, a5, a6) { ::testing::Mock::AllowUninterestingCalls( internal::ImplicitCast_<MockClass*>(this)); } template <typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7> NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7) : MockClass(a1, a2, a3, a4, a5, a6, a7) { ::testing::Mock::AllowUninterestingCalls( internal::ImplicitCast_<MockClass*>(this)); } template <typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8> NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7, const A8& a8) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8) { ::testing::Mock::AllowUninterestingCalls( internal::ImplicitCast_<MockClass*>(this)); } template <typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8, typename A9> NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7, const A8& a8, const A9& a9) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9) { ::testing::Mock::AllowUninterestingCalls( internal::ImplicitCast_<MockClass*>(this)); } template <typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8, typename A9, typename A10> NiceMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7, const A8& a8, const A9& a9, const A10& a10) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) { ::testing::Mock::AllowUninterestingCalls( internal::ImplicitCast_<MockClass*>(this)); } virtual ~NiceMock() { ::testing::Mock::UnregisterCallReaction( internal::ImplicitCast_<MockClass*>(this)); } private: GTEST_DISALLOW_COPY_AND_ASSIGN_(NiceMock); }; template <class MockClass> class NaggyMock : public MockClass { public: // We don't factor out the constructor body to a common method, as // we have to avoid a possible clash with members of MockClass. NaggyMock() { ::testing::Mock::WarnUninterestingCalls( internal::ImplicitCast_<MockClass*>(this)); } // C++ doesn't (yet) allow inheritance of constructors, so we have // to define it for each arity. template <typename A1> explicit NaggyMock(const A1& a1) : MockClass(a1) { ::testing::Mock::WarnUninterestingCalls( internal::ImplicitCast_<MockClass*>(this)); } template <typename A1, typename A2> NaggyMock(const A1& a1, const A2& a2) : MockClass(a1, a2) { ::testing::Mock::WarnUninterestingCalls( internal::ImplicitCast_<MockClass*>(this)); } template <typename A1, typename A2, typename A3> NaggyMock(const A1& a1, const A2& a2, const A3& a3) : MockClass(a1, a2, a3) { ::testing::Mock::WarnUninterestingCalls( internal::ImplicitCast_<MockClass*>(this)); } template <typename A1, typename A2, typename A3, typename A4> NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4) : MockClass(a1, a2, a3, a4) { ::testing::Mock::WarnUninterestingCalls( internal::ImplicitCast_<MockClass*>(this)); } template <typename A1, typename A2, typename A3, typename A4, typename A5> NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5) : MockClass(a1, a2, a3, a4, a5) { ::testing::Mock::WarnUninterestingCalls( internal::ImplicitCast_<MockClass*>(this)); } template <typename A1, typename A2, typename A3, typename A4, typename A5, typename A6> NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6) : MockClass(a1, a2, a3, a4, a5, a6) { ::testing::Mock::WarnUninterestingCalls( internal::ImplicitCast_<MockClass*>(this)); } template <typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7> NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7) : MockClass(a1, a2, a3, a4, a5, a6, a7) { ::testing::Mock::WarnUninterestingCalls( internal::ImplicitCast_<MockClass*>(this)); } template <typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8> NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7, const A8& a8) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8) { ::testing::Mock::WarnUninterestingCalls( internal::ImplicitCast_<MockClass*>(this)); } template <typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8, typename A9> NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7, const A8& a8, const A9& a9) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9) { ::testing::Mock::WarnUninterestingCalls( internal::ImplicitCast_<MockClass*>(this)); } template <typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8, typename A9, typename A10> NaggyMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7, const A8& a8, const A9& a9, const A10& a10) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) { ::testing::Mock::WarnUninterestingCalls( internal::ImplicitCast_<MockClass*>(this)); } virtual ~NaggyMock() { ::testing::Mock::UnregisterCallReaction( internal::ImplicitCast_<MockClass*>(this)); } private: GTEST_DISALLOW_COPY_AND_ASSIGN_(NaggyMock); }; template <class MockClass> class StrictMock : public MockClass { public: // We don't factor out the constructor body to a common method, as // we have to avoid a possible clash with members of MockClass. StrictMock() { ::testing::Mock::FailUninterestingCalls( internal::ImplicitCast_<MockClass*>(this)); } // C++ doesn't (yet) allow inheritance of constructors, so we have // to define it for each arity. template <typename A1> explicit StrictMock(const A1& a1) : MockClass(a1) { ::testing::Mock::FailUninterestingCalls( internal::ImplicitCast_<MockClass*>(this)); } template <typename A1, typename A2> StrictMock(const A1& a1, const A2& a2) : MockClass(a1, a2) { ::testing::Mock::FailUninterestingCalls( internal::ImplicitCast_<MockClass*>(this)); } template <typename A1, typename A2, typename A3> StrictMock(const A1& a1, const A2& a2, const A3& a3) : MockClass(a1, a2, a3) { ::testing::Mock::FailUninterestingCalls( internal::ImplicitCast_<MockClass*>(this)); } template <typename A1, typename A2, typename A3, typename A4> StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4) : MockClass(a1, a2, a3, a4) { ::testing::Mock::FailUninterestingCalls( internal::ImplicitCast_<MockClass*>(this)); } template <typename A1, typename A2, typename A3, typename A4, typename A5> StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5) : MockClass(a1, a2, a3, a4, a5) { ::testing::Mock::FailUninterestingCalls( internal::ImplicitCast_<MockClass*>(this)); } template <typename A1, typename A2, typename A3, typename A4, typename A5, typename A6> StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6) : MockClass(a1, a2, a3, a4, a5, a6) { ::testing::Mock::FailUninterestingCalls( internal::ImplicitCast_<MockClass*>(this)); } template <typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7> StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7) : MockClass(a1, a2, a3, a4, a5, a6, a7) { ::testing::Mock::FailUninterestingCalls( internal::ImplicitCast_<MockClass*>(this)); } template <typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8> StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7, const A8& a8) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8) { ::testing::Mock::FailUninterestingCalls( internal::ImplicitCast_<MockClass*>(this)); } template <typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8, typename A9> StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7, const A8& a8, const A9& a9) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9) { ::testing::Mock::FailUninterestingCalls( internal::ImplicitCast_<MockClass*>(this)); } template <typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8, typename A9, typename A10> StrictMock(const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5, const A6& a6, const A7& a7, const A8& a8, const A9& a9, const A10& a10) : MockClass(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10) { ::testing::Mock::FailUninterestingCalls( internal::ImplicitCast_<MockClass*>(this)); } virtual ~StrictMock() { ::testing::Mock::UnregisterCallReaction( internal::ImplicitCast_<MockClass*>(this)); } private: GTEST_DISALLOW_COPY_AND_ASSIGN_(StrictMock); }; // The following specializations catch some (relatively more common) // user errors of nesting nice and strict mocks. They do NOT catch // all possible errors. // These specializations are declared but not defined, as NiceMock, // NaggyMock, and StrictMock cannot be nested. template <typename MockClass> class NiceMock<NiceMock<MockClass> >; template <typename MockClass> class NiceMock<NaggyMock<MockClass> >; template <typename MockClass> class NiceMock<StrictMock<MockClass> >; template <typename MockClass> class NaggyMock<NiceMock<MockClass> >; template <typename MockClass> class NaggyMock<NaggyMock<MockClass> >; template <typename MockClass> class NaggyMock<StrictMock<MockClass> >; template <typename MockClass> class StrictMock<NiceMock<MockClass> >; template <typename MockClass> class StrictMock<NaggyMock<MockClass> >; template <typename MockClass> class StrictMock<StrictMock<MockClass> >; } // namespace testing #endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_NICE_STRICT_H_
0
repos/DirectXShaderCompiler/utils/unittest/googlemock/include
repos/DirectXShaderCompiler/utils/unittest/googlemock/include/gmock/gmock-generated-function-mockers.h
// This file was GENERATED by command: // pump.py gmock-generated-function-mockers.h.pump // DO NOT EDIT BY HAND!!! // 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. // // Author: [email protected] (Zhanyong Wan) // Google Mock - a framework for writing C++ mock classes. // // This file implements function mockers of various arities. #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_ #include "gmock/gmock-spec-builders.h" #include "gmock/internal/gmock-internal-utils.h" #if GTEST_HAS_STD_FUNCTION_ # include <functional> #endif namespace testing { namespace internal { template <typename F> class FunctionMockerBase; // Note: class FunctionMocker really belongs to the ::testing // namespace. However if we define it in ::testing, MSVC will // complain when classes in ::testing::internal declare it as a // friend class template. To workaround this compiler bug, we define // FunctionMocker in ::testing::internal and import it into ::testing. template <typename F> class FunctionMocker; template <typename R> class FunctionMocker<R()> : public internal::FunctionMockerBase<R()> { public: typedef R F(); typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; MockSpec<F>& With() { return this->current_spec(); } R Invoke() { // Even though gcc and MSVC don't enforce it, 'this->' is required // by the C++ standard [14.6.4] here, as the base class type is // dependent on the template argument (and thus shouldn't be // looked into when resolving InvokeWith). return this->InvokeWith(ArgumentTuple()); } }; template <typename R, typename A1> class FunctionMocker<R(A1)> : public internal::FunctionMockerBase<R(A1)> { public: typedef R F(A1); typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; MockSpec<F>& With(const Matcher<A1>& m1) { this->current_spec().SetMatchers(::testing::make_tuple(m1)); return this->current_spec(); } R Invoke(A1 a1) { // Even though gcc and MSVC don't enforce it, 'this->' is required // by the C++ standard [14.6.4] here, as the base class type is // dependent on the template argument (and thus shouldn't be // looked into when resolving InvokeWith). return this->InvokeWith(ArgumentTuple(a1)); } }; template <typename R, typename A1, typename A2> class FunctionMocker<R(A1, A2)> : public internal::FunctionMockerBase<R(A1, A2)> { public: typedef R F(A1, A2); typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2) { this->current_spec().SetMatchers(::testing::make_tuple(m1, m2)); return this->current_spec(); } R Invoke(A1 a1, A2 a2) { // Even though gcc and MSVC don't enforce it, 'this->' is required // by the C++ standard [14.6.4] here, as the base class type is // dependent on the template argument (and thus shouldn't be // looked into when resolving InvokeWith). return this->InvokeWith(ArgumentTuple(a1, a2)); } }; template <typename R, typename A1, typename A2, typename A3> class FunctionMocker<R(A1, A2, A3)> : public internal::FunctionMockerBase<R(A1, A2, A3)> { public: typedef R F(A1, A2, A3); typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2, const Matcher<A3>& m3) { this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3)); return this->current_spec(); } R Invoke(A1 a1, A2 a2, A3 a3) { // Even though gcc and MSVC don't enforce it, 'this->' is required // by the C++ standard [14.6.4] here, as the base class type is // dependent on the template argument (and thus shouldn't be // looked into when resolving InvokeWith). return this->InvokeWith(ArgumentTuple(a1, a2, a3)); } }; template <typename R, typename A1, typename A2, typename A3, typename A4> class FunctionMocker<R(A1, A2, A3, A4)> : public internal::FunctionMockerBase<R(A1, A2, A3, A4)> { public: typedef R F(A1, A2, A3, A4); typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2, const Matcher<A3>& m3, const Matcher<A4>& m4) { this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4)); return this->current_spec(); } R Invoke(A1 a1, A2 a2, A3 a3, A4 a4) { // Even though gcc and MSVC don't enforce it, 'this->' is required // by the C++ standard [14.6.4] here, as the base class type is // dependent on the template argument (and thus shouldn't be // looked into when resolving InvokeWith). return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4)); } }; template <typename R, typename A1, typename A2, typename A3, typename A4, typename A5> class FunctionMocker<R(A1, A2, A3, A4, A5)> : public internal::FunctionMockerBase<R(A1, A2, A3, A4, A5)> { public: typedef R F(A1, A2, A3, A4, A5); typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2, const Matcher<A3>& m3, const Matcher<A4>& m4, const Matcher<A5>& m5) { this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5)); return this->current_spec(); } R Invoke(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5) { // Even though gcc and MSVC don't enforce it, 'this->' is required // by the C++ standard [14.6.4] here, as the base class type is // dependent on the template argument (and thus shouldn't be // looked into when resolving InvokeWith). return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4, a5)); } }; template <typename R, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6> class FunctionMocker<R(A1, A2, A3, A4, A5, A6)> : public internal::FunctionMockerBase<R(A1, A2, A3, A4, A5, A6)> { public: typedef R F(A1, A2, A3, A4, A5, A6); typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2, const Matcher<A3>& m3, const Matcher<A4>& m4, const Matcher<A5>& m5, const Matcher<A6>& m6) { this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5, m6)); return this->current_spec(); } R Invoke(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6) { // Even though gcc and MSVC don't enforce it, 'this->' is required // by the C++ standard [14.6.4] here, as the base class type is // dependent on the template argument (and thus shouldn't be // looked into when resolving InvokeWith). return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4, a5, a6)); } }; template <typename R, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7> class FunctionMocker<R(A1, A2, A3, A4, A5, A6, A7)> : public internal::FunctionMockerBase<R(A1, A2, A3, A4, A5, A6, A7)> { public: typedef R F(A1, A2, A3, A4, A5, A6, A7); typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2, const Matcher<A3>& m3, const Matcher<A4>& m4, const Matcher<A5>& m5, const Matcher<A6>& m6, const Matcher<A7>& m7) { this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5, m6, m7)); return this->current_spec(); } R Invoke(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7) { // Even though gcc and MSVC don't enforce it, 'this->' is required // by the C++ standard [14.6.4] here, as the base class type is // dependent on the template argument (and thus shouldn't be // looked into when resolving InvokeWith). return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4, a5, a6, a7)); } }; template <typename R, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8> class FunctionMocker<R(A1, A2, A3, A4, A5, A6, A7, A8)> : public internal::FunctionMockerBase<R(A1, A2, A3, A4, A5, A6, A7, A8)> { public: typedef R F(A1, A2, A3, A4, A5, A6, A7, A8); typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2, const Matcher<A3>& m3, const Matcher<A4>& m4, const Matcher<A5>& m5, const Matcher<A6>& m6, const Matcher<A7>& m7, const Matcher<A8>& m8) { this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5, m6, m7, m8)); return this->current_spec(); } R Invoke(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8) { // Even though gcc and MSVC don't enforce it, 'this->' is required // by the C++ standard [14.6.4] here, as the base class type is // dependent on the template argument (and thus shouldn't be // looked into when resolving InvokeWith). return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4, a5, a6, a7, a8)); } }; template <typename R, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8, typename A9> class FunctionMocker<R(A1, A2, A3, A4, A5, A6, A7, A8, A9)> : public internal::FunctionMockerBase<R(A1, A2, A3, A4, A5, A6, A7, A8, A9)> { public: typedef R F(A1, A2, A3, A4, A5, A6, A7, A8, A9); typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2, const Matcher<A3>& m3, const Matcher<A4>& m4, const Matcher<A5>& m5, const Matcher<A6>& m6, const Matcher<A7>& m7, const Matcher<A8>& m8, const Matcher<A9>& m9) { this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5, m6, m7, m8, m9)); return this->current_spec(); } R Invoke(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8, A9 a9) { // Even though gcc and MSVC don't enforce it, 'this->' is required // by the C++ standard [14.6.4] here, as the base class type is // dependent on the template argument (and thus shouldn't be // looked into when resolving InvokeWith). return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4, a5, a6, a7, a8, a9)); } }; template <typename R, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8, typename A9, typename A10> class FunctionMocker<R(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10)> : public internal::FunctionMockerBase<R(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10)> { public: typedef R F(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10); typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; MockSpec<F>& With(const Matcher<A1>& m1, const Matcher<A2>& m2, const Matcher<A3>& m3, const Matcher<A4>& m4, const Matcher<A5>& m5, const Matcher<A6>& m6, const Matcher<A7>& m7, const Matcher<A8>& m8, const Matcher<A9>& m9, const Matcher<A10>& m10) { this->current_spec().SetMatchers(::testing::make_tuple(m1, m2, m3, m4, m5, m6, m7, m8, m9, m10)); return this->current_spec(); } R Invoke(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8, A9 a9, A10 a10) { // Even though gcc and MSVC don't enforce it, 'this->' is required // by the C++ standard [14.6.4] here, as the base class type is // dependent on the template argument (and thus shouldn't be // looked into when resolving InvokeWith). return this->InvokeWith(ArgumentTuple(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10)); } }; } // 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; // GMOCK_RESULT_(tn, F) expands to the result type of function type F. // We define this as a variadic macro in case F contains unprotected // commas (the same reason that we use variadic macros in other places // in this file). // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! #define GMOCK_RESULT_(tn, ...) \ tn ::testing::internal::Function<__VA_ARGS__>::Result // The type of argument N of the given function type. // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! #define GMOCK_ARG_(tn, N, ...) \ tn ::testing::internal::Function<__VA_ARGS__>::Argument##N // The matcher type for argument N of the given function type. // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! #define GMOCK_MATCHER_(tn, N, ...) \ const ::testing::Matcher<GMOCK_ARG_(tn, N, __VA_ARGS__)>& // The variable for mocking the given method. // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! #define GMOCK_MOCKER_(arity, constness, Method) \ GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__) // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! #define GMOCK_METHOD0_(tn, constness, ct, Method, ...) \ GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ ) constness { \ GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ == 0), \ this_method_does_not_take_0_arguments); \ GMOCK_MOCKER_(0, constness, Method).SetOwnerAndName(this, #Method); \ return GMOCK_MOCKER_(0, constness, Method).Invoke(); \ } \ ::testing::MockSpec<__VA_ARGS__>& \ gmock_##Method() constness { \ GMOCK_MOCKER_(0, constness, Method).RegisterOwner(this); \ return GMOCK_MOCKER_(0, constness, Method).With(); \ } \ mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(0, constness, \ Method) // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! #define GMOCK_METHOD1_(tn, constness, ct, Method, ...) \ GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1) constness { \ GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ == 1), \ this_method_does_not_take_1_argument); \ GMOCK_MOCKER_(1, constness, Method).SetOwnerAndName(this, #Method); \ return GMOCK_MOCKER_(1, constness, Method).Invoke(gmock_a1); \ } \ ::testing::MockSpec<__VA_ARGS__>& \ gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1) constness { \ GMOCK_MOCKER_(1, constness, Method).RegisterOwner(this); \ return GMOCK_MOCKER_(1, constness, Method).With(gmock_a1); \ } \ mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(1, constness, \ Method) // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! #define GMOCK_METHOD2_(tn, constness, ct, Method, ...) \ GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \ GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2) constness { \ GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ == 2), \ this_method_does_not_take_2_arguments); \ GMOCK_MOCKER_(2, constness, Method).SetOwnerAndName(this, #Method); \ return GMOCK_MOCKER_(2, constness, Method).Invoke(gmock_a1, gmock_a2); \ } \ ::testing::MockSpec<__VA_ARGS__>& \ gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2) constness { \ GMOCK_MOCKER_(2, constness, Method).RegisterOwner(this); \ return GMOCK_MOCKER_(2, constness, Method).With(gmock_a1, gmock_a2); \ } \ mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(2, constness, \ Method) // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! #define GMOCK_METHOD3_(tn, constness, ct, Method, ...) \ GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \ GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3) constness { \ GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ == 3), \ this_method_does_not_take_3_arguments); \ GMOCK_MOCKER_(3, constness, Method).SetOwnerAndName(this, #Method); \ return GMOCK_MOCKER_(3, constness, Method).Invoke(gmock_a1, gmock_a2, \ gmock_a3); \ } \ ::testing::MockSpec<__VA_ARGS__>& \ gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3) constness { \ GMOCK_MOCKER_(3, constness, Method).RegisterOwner(this); \ return GMOCK_MOCKER_(3, constness, Method).With(gmock_a1, gmock_a2, \ gmock_a3); \ } \ mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(3, constness, \ Method) // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! #define GMOCK_METHOD4_(tn, constness, ct, Method, ...) \ GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \ GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4) constness { \ GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ == 4), \ this_method_does_not_take_4_arguments); \ GMOCK_MOCKER_(4, constness, Method).SetOwnerAndName(this, #Method); \ return GMOCK_MOCKER_(4, constness, Method).Invoke(gmock_a1, gmock_a2, \ gmock_a3, gmock_a4); \ } \ ::testing::MockSpec<__VA_ARGS__>& \ gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4) constness { \ GMOCK_MOCKER_(4, constness, Method).RegisterOwner(this); \ return GMOCK_MOCKER_(4, constness, Method).With(gmock_a1, gmock_a2, \ gmock_a3, gmock_a4); \ } \ mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(4, constness, \ Method) // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! #define GMOCK_METHOD5_(tn, constness, ct, Method, ...) \ GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \ GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \ GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5) constness { \ GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ == 5), \ this_method_does_not_take_5_arguments); \ GMOCK_MOCKER_(5, constness, Method).SetOwnerAndName(this, #Method); \ return GMOCK_MOCKER_(5, constness, Method).Invoke(gmock_a1, gmock_a2, \ gmock_a3, gmock_a4, gmock_a5); \ } \ ::testing::MockSpec<__VA_ARGS__>& \ gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \ GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5) constness { \ GMOCK_MOCKER_(5, constness, Method).RegisterOwner(this); \ return GMOCK_MOCKER_(5, constness, Method).With(gmock_a1, gmock_a2, \ gmock_a3, gmock_a4, gmock_a5); \ } \ mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(5, constness, \ Method) // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! #define GMOCK_METHOD6_(tn, constness, ct, Method, ...) \ GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \ GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \ GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, \ GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6) constness { \ GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ == 6), \ this_method_does_not_take_6_arguments); \ GMOCK_MOCKER_(6, constness, Method).SetOwnerAndName(this, #Method); \ return GMOCK_MOCKER_(6, constness, Method).Invoke(gmock_a1, gmock_a2, \ gmock_a3, gmock_a4, gmock_a5, gmock_a6); \ } \ ::testing::MockSpec<__VA_ARGS__>& \ gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \ GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \ GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6) constness { \ GMOCK_MOCKER_(6, constness, Method).RegisterOwner(this); \ return GMOCK_MOCKER_(6, constness, Method).With(gmock_a1, gmock_a2, \ gmock_a3, gmock_a4, gmock_a5, gmock_a6); \ } \ mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(6, constness, \ Method) // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! #define GMOCK_METHOD7_(tn, constness, ct, Method, ...) \ GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \ GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \ GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, \ GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \ GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7) constness { \ GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ == 7), \ this_method_does_not_take_7_arguments); \ GMOCK_MOCKER_(7, constness, Method).SetOwnerAndName(this, #Method); \ return GMOCK_MOCKER_(7, constness, Method).Invoke(gmock_a1, gmock_a2, \ gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7); \ } \ ::testing::MockSpec<__VA_ARGS__>& \ gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \ GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \ GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \ GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7) constness { \ GMOCK_MOCKER_(7, constness, Method).RegisterOwner(this); \ return GMOCK_MOCKER_(7, constness, Method).With(gmock_a1, gmock_a2, \ gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7); \ } \ mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(7, constness, \ Method) // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! #define GMOCK_METHOD8_(tn, constness, ct, Method, ...) \ GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \ GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \ GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, \ GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \ GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, \ GMOCK_ARG_(tn, 8, __VA_ARGS__) gmock_a8) constness { \ GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ == 8), \ this_method_does_not_take_8_arguments); \ GMOCK_MOCKER_(8, constness, Method).SetOwnerAndName(this, #Method); \ return GMOCK_MOCKER_(8, constness, Method).Invoke(gmock_a1, gmock_a2, \ gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8); \ } \ ::testing::MockSpec<__VA_ARGS__>& \ gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \ GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \ GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \ GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7, \ GMOCK_MATCHER_(tn, 8, __VA_ARGS__) gmock_a8) constness { \ GMOCK_MOCKER_(8, constness, Method).RegisterOwner(this); \ return GMOCK_MOCKER_(8, constness, Method).With(gmock_a1, gmock_a2, \ gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8); \ } \ mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(8, constness, \ Method) // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! #define GMOCK_METHOD9_(tn, constness, ct, Method, ...) \ GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \ GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \ GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, \ GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \ GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, \ GMOCK_ARG_(tn, 8, __VA_ARGS__) gmock_a8, \ GMOCK_ARG_(tn, 9, __VA_ARGS__) gmock_a9) constness { \ GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ == 9), \ this_method_does_not_take_9_arguments); \ GMOCK_MOCKER_(9, constness, Method).SetOwnerAndName(this, #Method); \ return GMOCK_MOCKER_(9, constness, Method).Invoke(gmock_a1, gmock_a2, \ gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, \ gmock_a9); \ } \ ::testing::MockSpec<__VA_ARGS__>& \ gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \ GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \ GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \ GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7, \ GMOCK_MATCHER_(tn, 8, __VA_ARGS__) gmock_a8, \ GMOCK_MATCHER_(tn, 9, __VA_ARGS__) gmock_a9) constness { \ GMOCK_MOCKER_(9, constness, Method).RegisterOwner(this); \ return GMOCK_MOCKER_(9, constness, Method).With(gmock_a1, gmock_a2, \ gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, \ gmock_a9); \ } \ mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(9, constness, \ Method) // INTERNAL IMPLEMENTATION - DON'T USE IN USER CODE!!! #define GMOCK_METHOD10_(tn, constness, ct, Method, ...) \ GMOCK_RESULT_(tn, __VA_ARGS__) ct Method( \ GMOCK_ARG_(tn, 1, __VA_ARGS__) gmock_a1, \ GMOCK_ARG_(tn, 2, __VA_ARGS__) gmock_a2, \ GMOCK_ARG_(tn, 3, __VA_ARGS__) gmock_a3, \ GMOCK_ARG_(tn, 4, __VA_ARGS__) gmock_a4, \ GMOCK_ARG_(tn, 5, __VA_ARGS__) gmock_a5, \ GMOCK_ARG_(tn, 6, __VA_ARGS__) gmock_a6, \ GMOCK_ARG_(tn, 7, __VA_ARGS__) gmock_a7, \ GMOCK_ARG_(tn, 8, __VA_ARGS__) gmock_a8, \ GMOCK_ARG_(tn, 9, __VA_ARGS__) gmock_a9, \ GMOCK_ARG_(tn, 10, __VA_ARGS__) gmock_a10) constness { \ GTEST_COMPILE_ASSERT_((::testing::tuple_size< \ tn ::testing::internal::Function<__VA_ARGS__>::ArgumentTuple>::value \ == 10), \ this_method_does_not_take_10_arguments); \ GMOCK_MOCKER_(10, constness, Method).SetOwnerAndName(this, #Method); \ return GMOCK_MOCKER_(10, constness, Method).Invoke(gmock_a1, gmock_a2, \ gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, gmock_a9, \ gmock_a10); \ } \ ::testing::MockSpec<__VA_ARGS__>& \ gmock_##Method(GMOCK_MATCHER_(tn, 1, __VA_ARGS__) gmock_a1, \ GMOCK_MATCHER_(tn, 2, __VA_ARGS__) gmock_a2, \ GMOCK_MATCHER_(tn, 3, __VA_ARGS__) gmock_a3, \ GMOCK_MATCHER_(tn, 4, __VA_ARGS__) gmock_a4, \ GMOCK_MATCHER_(tn, 5, __VA_ARGS__) gmock_a5, \ GMOCK_MATCHER_(tn, 6, __VA_ARGS__) gmock_a6, \ GMOCK_MATCHER_(tn, 7, __VA_ARGS__) gmock_a7, \ GMOCK_MATCHER_(tn, 8, __VA_ARGS__) gmock_a8, \ GMOCK_MATCHER_(tn, 9, __VA_ARGS__) gmock_a9, \ GMOCK_MATCHER_(tn, 10, \ __VA_ARGS__) gmock_a10) constness { \ GMOCK_MOCKER_(10, constness, Method).RegisterOwner(this); \ return GMOCK_MOCKER_(10, constness, Method).With(gmock_a1, gmock_a2, \ gmock_a3, gmock_a4, gmock_a5, gmock_a6, gmock_a7, gmock_a8, gmock_a9, \ gmock_a10); \ } \ mutable ::testing::FunctionMocker<__VA_ARGS__> GMOCK_MOCKER_(10, constness, \ Method) #define MOCK_METHOD0(m, ...) GMOCK_METHOD0_(, , , m, __VA_ARGS__) #define MOCK_METHOD1(m, ...) GMOCK_METHOD1_(, , , m, __VA_ARGS__) #define MOCK_METHOD2(m, ...) GMOCK_METHOD2_(, , , m, __VA_ARGS__) #define MOCK_METHOD3(m, ...) GMOCK_METHOD3_(, , , m, __VA_ARGS__) #define MOCK_METHOD4(m, ...) GMOCK_METHOD4_(, , , m, __VA_ARGS__) #define MOCK_METHOD5(m, ...) GMOCK_METHOD5_(, , , m, __VA_ARGS__) #define MOCK_METHOD6(m, ...) GMOCK_METHOD6_(, , , m, __VA_ARGS__) #define MOCK_METHOD7(m, ...) GMOCK_METHOD7_(, , , m, __VA_ARGS__) #define MOCK_METHOD8(m, ...) GMOCK_METHOD8_(, , , m, __VA_ARGS__) #define MOCK_METHOD9(m, ...) GMOCK_METHOD9_(, , , m, __VA_ARGS__) #define MOCK_METHOD10(m, ...) GMOCK_METHOD10_(, , , m, __VA_ARGS__) #define MOCK_CONST_METHOD0(m, ...) GMOCK_METHOD0_(, const, , m, __VA_ARGS__) #define MOCK_CONST_METHOD1(m, ...) GMOCK_METHOD1_(, const, , m, __VA_ARGS__) #define MOCK_CONST_METHOD2(m, ...) GMOCK_METHOD2_(, const, , m, __VA_ARGS__) #define MOCK_CONST_METHOD3(m, ...) GMOCK_METHOD3_(, const, , m, __VA_ARGS__) #define MOCK_CONST_METHOD4(m, ...) GMOCK_METHOD4_(, const, , m, __VA_ARGS__) #define MOCK_CONST_METHOD5(m, ...) GMOCK_METHOD5_(, const, , m, __VA_ARGS__) #define MOCK_CONST_METHOD6(m, ...) GMOCK_METHOD6_(, const, , m, __VA_ARGS__) #define MOCK_CONST_METHOD7(m, ...) GMOCK_METHOD7_(, const, , m, __VA_ARGS__) #define MOCK_CONST_METHOD8(m, ...) GMOCK_METHOD8_(, const, , m, __VA_ARGS__) #define MOCK_CONST_METHOD9(m, ...) GMOCK_METHOD9_(, const, , m, __VA_ARGS__) #define MOCK_CONST_METHOD10(m, ...) GMOCK_METHOD10_(, const, , m, __VA_ARGS__) #define MOCK_METHOD0_T(m, ...) GMOCK_METHOD0_(typename, , , m, __VA_ARGS__) #define MOCK_METHOD1_T(m, ...) GMOCK_METHOD1_(typename, , , m, __VA_ARGS__) #define MOCK_METHOD2_T(m, ...) GMOCK_METHOD2_(typename, , , m, __VA_ARGS__) #define MOCK_METHOD3_T(m, ...) GMOCK_METHOD3_(typename, , , m, __VA_ARGS__) #define MOCK_METHOD4_T(m, ...) GMOCK_METHOD4_(typename, , , m, __VA_ARGS__) #define MOCK_METHOD5_T(m, ...) GMOCK_METHOD5_(typename, , , m, __VA_ARGS__) #define MOCK_METHOD6_T(m, ...) GMOCK_METHOD6_(typename, , , m, __VA_ARGS__) #define MOCK_METHOD7_T(m, ...) GMOCK_METHOD7_(typename, , , m, __VA_ARGS__) #define MOCK_METHOD8_T(m, ...) GMOCK_METHOD8_(typename, , , m, __VA_ARGS__) #define MOCK_METHOD9_T(m, ...) GMOCK_METHOD9_(typename, , , m, __VA_ARGS__) #define MOCK_METHOD10_T(m, ...) GMOCK_METHOD10_(typename, , , m, __VA_ARGS__) #define MOCK_CONST_METHOD0_T(m, ...) \ GMOCK_METHOD0_(typename, const, , m, __VA_ARGS__) #define MOCK_CONST_METHOD1_T(m, ...) \ GMOCK_METHOD1_(typename, const, , m, __VA_ARGS__) #define MOCK_CONST_METHOD2_T(m, ...) \ GMOCK_METHOD2_(typename, const, , m, __VA_ARGS__) #define MOCK_CONST_METHOD3_T(m, ...) \ GMOCK_METHOD3_(typename, const, , m, __VA_ARGS__) #define MOCK_CONST_METHOD4_T(m, ...) \ GMOCK_METHOD4_(typename, const, , m, __VA_ARGS__) #define MOCK_CONST_METHOD5_T(m, ...) \ GMOCK_METHOD5_(typename, const, , m, __VA_ARGS__) #define MOCK_CONST_METHOD6_T(m, ...) \ GMOCK_METHOD6_(typename, const, , m, __VA_ARGS__) #define MOCK_CONST_METHOD7_T(m, ...) \ GMOCK_METHOD7_(typename, const, , m, __VA_ARGS__) #define MOCK_CONST_METHOD8_T(m, ...) \ GMOCK_METHOD8_(typename, const, , m, __VA_ARGS__) #define MOCK_CONST_METHOD9_T(m, ...) \ GMOCK_METHOD9_(typename, const, , m, __VA_ARGS__) #define MOCK_CONST_METHOD10_T(m, ...) \ GMOCK_METHOD10_(typename, const, , m, __VA_ARGS__) #define MOCK_METHOD0_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD0_(, , ct, m, __VA_ARGS__) #define MOCK_METHOD1_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD1_(, , ct, m, __VA_ARGS__) #define MOCK_METHOD2_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD2_(, , ct, m, __VA_ARGS__) #define MOCK_METHOD3_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD3_(, , ct, m, __VA_ARGS__) #define MOCK_METHOD4_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD4_(, , ct, m, __VA_ARGS__) #define MOCK_METHOD5_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD5_(, , ct, m, __VA_ARGS__) #define MOCK_METHOD6_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD6_(, , ct, m, __VA_ARGS__) #define MOCK_METHOD7_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD7_(, , ct, m, __VA_ARGS__) #define MOCK_METHOD8_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD8_(, , ct, m, __VA_ARGS__) #define MOCK_METHOD9_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD9_(, , ct, m, __VA_ARGS__) #define MOCK_METHOD10_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD10_(, , ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD0_(, const, ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD1_(, const, ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD2_(, const, ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD3_(, const, ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD4_(, const, ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD5_(, const, ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD6_(, const, ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD7_(, const, ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD8_(, const, ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD9_(, const, ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD10_(, const, ct, m, __VA_ARGS__) #define MOCK_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD0_(typename, , ct, m, __VA_ARGS__) #define MOCK_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD1_(typename, , ct, m, __VA_ARGS__) #define MOCK_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD2_(typename, , ct, m, __VA_ARGS__) #define MOCK_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD3_(typename, , ct, m, __VA_ARGS__) #define MOCK_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD4_(typename, , ct, m, __VA_ARGS__) #define MOCK_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD5_(typename, , ct, m, __VA_ARGS__) #define MOCK_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD6_(typename, , ct, m, __VA_ARGS__) #define MOCK_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD7_(typename, , ct, m, __VA_ARGS__) #define MOCK_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD8_(typename, , ct, m, __VA_ARGS__) #define MOCK_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD9_(typename, , ct, m, __VA_ARGS__) #define MOCK_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD10_(typename, , ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD0_(typename, const, ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD1_(typename, const, ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD2_(typename, const, ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD3_(typename, const, ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD4_(typename, const, ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD5_(typename, const, ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD6_(typename, const, ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD7_(typename, const, ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD8_(typename, const, ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD9_(typename, const, ct, m, __VA_ARGS__) #define MOCK_CONST_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \ GMOCK_METHOD10_(typename, const, ct, m, __VA_ARGS__) // A MockFunction<F> class has one mock method whose type is F. It is // useful when you just want your test code to emit some messages and // have Google Mock verify the right messages are sent (and perhaps at // the right times). For example, if you are exercising code: // // Foo(1); // Foo(2); // Foo(3); // // and want to verify that Foo(1) and Foo(3) both invoke // mock.Bar("a"), but Foo(2) doesn't invoke anything, you can write: // // TEST(FooTest, InvokesBarCorrectly) { // MyMock mock; // MockFunction<void(string check_point_name)> check; // { // InSequence s; // // EXPECT_CALL(mock, Bar("a")); // EXPECT_CALL(check, Call("1")); // EXPECT_CALL(check, Call("2")); // EXPECT_CALL(mock, Bar("a")); // } // Foo(1); // check.Call("1"); // Foo(2); // check.Call("2"); // Foo(3); // } // // The expectation spec says that the first Bar("a") must happen // before check point "1", the second Bar("a") must happen after check // point "2", and nothing should happen between the two check // points. The explicit check points make it easy to tell which // Bar("a") is called by which call to Foo(). // // MockFunction<F> can also be used to exercise code that accepts // std::function<F> callbacks. To do so, use AsStdFunction() method // to create std::function proxy forwarding to original object's Call. // Example: // // TEST(FooTest, RunsCallbackWithBarArgument) { // MockFunction<int(string)> callback; // EXPECT_CALL(callback, Call("bar")).WillOnce(Return(1)); // Foo(callback.AsStdFunction()); // } template <typename F> class MockFunction; template <typename R> class MockFunction<R()> { public: MockFunction() {} MOCK_METHOD0_T(Call, R()); #if GTEST_HAS_STD_FUNCTION_ std::function<R()> AsStdFunction() { return [this]() -> R { return this->Call(); }; } #endif // GTEST_HAS_STD_FUNCTION_ private: GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction); }; template <typename R, typename A0> class MockFunction<R(A0)> { public: MockFunction() {} MOCK_METHOD1_T(Call, R(A0)); #if GTEST_HAS_STD_FUNCTION_ std::function<R(A0)> AsStdFunction() { return [this](A0 a0) -> R { return this->Call(a0); }; } #endif // GTEST_HAS_STD_FUNCTION_ private: GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction); }; template <typename R, typename A0, typename A1> class MockFunction<R(A0, A1)> { public: MockFunction() {} MOCK_METHOD2_T(Call, R(A0, A1)); #if GTEST_HAS_STD_FUNCTION_ std::function<R(A0, A1)> AsStdFunction() { return [this](A0 a0, A1 a1) -> R { return this->Call(a0, a1); }; } #endif // GTEST_HAS_STD_FUNCTION_ private: GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction); }; template <typename R, typename A0, typename A1, typename A2> class MockFunction<R(A0, A1, A2)> { public: MockFunction() {} MOCK_METHOD3_T(Call, R(A0, A1, A2)); #if GTEST_HAS_STD_FUNCTION_ std::function<R(A0, A1, A2)> AsStdFunction() { return [this](A0 a0, A1 a1, A2 a2) -> R { return this->Call(a0, a1, a2); }; } #endif // GTEST_HAS_STD_FUNCTION_ private: GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction); }; template <typename R, typename A0, typename A1, typename A2, typename A3> class MockFunction<R(A0, A1, A2, A3)> { public: MockFunction() {} MOCK_METHOD4_T(Call, R(A0, A1, A2, A3)); #if GTEST_HAS_STD_FUNCTION_ std::function<R(A0, A1, A2, A3)> AsStdFunction() { return [this](A0 a0, A1 a1, A2 a2, A3 a3) -> R { return this->Call(a0, a1, a2, a3); }; } #endif // GTEST_HAS_STD_FUNCTION_ private: GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction); }; template <typename R, typename A0, typename A1, typename A2, typename A3, typename A4> class MockFunction<R(A0, A1, A2, A3, A4)> { public: MockFunction() {} MOCK_METHOD5_T(Call, R(A0, A1, A2, A3, A4)); #if GTEST_HAS_STD_FUNCTION_ std::function<R(A0, A1, A2, A3, A4)> AsStdFunction() { return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) -> R { return this->Call(a0, a1, a2, a3, a4); }; } #endif // GTEST_HAS_STD_FUNCTION_ private: GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction); }; template <typename R, typename A0, typename A1, typename A2, typename A3, typename A4, typename A5> class MockFunction<R(A0, A1, A2, A3, A4, A5)> { public: MockFunction() {} MOCK_METHOD6_T(Call, R(A0, A1, A2, A3, A4, A5)); #if GTEST_HAS_STD_FUNCTION_ std::function<R(A0, A1, A2, A3, A4, A5)> AsStdFunction() { return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5) -> R { return this->Call(a0, a1, a2, a3, a4, a5); }; } #endif // GTEST_HAS_STD_FUNCTION_ private: GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction); }; template <typename R, typename A0, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6> class MockFunction<R(A0, A1, A2, A3, A4, A5, A6)> { public: MockFunction() {} MOCK_METHOD7_T(Call, R(A0, A1, A2, A3, A4, A5, A6)); #if GTEST_HAS_STD_FUNCTION_ std::function<R(A0, A1, A2, A3, A4, A5, A6)> AsStdFunction() { return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6) -> R { return this->Call(a0, a1, a2, a3, a4, a5, a6); }; } #endif // GTEST_HAS_STD_FUNCTION_ private: GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction); }; template <typename R, typename A0, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7> class MockFunction<R(A0, A1, A2, A3, A4, A5, A6, A7)> { public: MockFunction() {} MOCK_METHOD8_T(Call, R(A0, A1, A2, A3, A4, A5, A6, A7)); #if GTEST_HAS_STD_FUNCTION_ std::function<R(A0, A1, A2, A3, A4, A5, A6, A7)> AsStdFunction() { return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7) -> R { return this->Call(a0, a1, a2, a3, a4, a5, a6, a7); }; } #endif // GTEST_HAS_STD_FUNCTION_ private: GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction); }; template <typename R, typename A0, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8> class MockFunction<R(A0, A1, A2, A3, A4, A5, A6, A7, A8)> { public: MockFunction() {} MOCK_METHOD9_T(Call, R(A0, A1, A2, A3, A4, A5, A6, A7, A8)); #if GTEST_HAS_STD_FUNCTION_ std::function<R(A0, A1, A2, A3, A4, A5, A6, A7, A8)> AsStdFunction() { return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8) -> R { return this->Call(a0, a1, a2, a3, a4, a5, a6, a7, a8); }; } #endif // GTEST_HAS_STD_FUNCTION_ private: GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction); }; template <typename R, typename A0, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8, typename A9> class MockFunction<R(A0, A1, A2, A3, A4, A5, A6, A7, A8, A9)> { public: MockFunction() {} MOCK_METHOD10_T(Call, R(A0, A1, A2, A3, A4, A5, A6, A7, A8, A9)); #if GTEST_HAS_STD_FUNCTION_ std::function<R(A0, A1, A2, A3, A4, A5, A6, A7, A8, A9)> AsStdFunction() { return [this](A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8, A9 a9) -> R { return this->Call(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9); }; } #endif // GTEST_HAS_STD_FUNCTION_ private: GTEST_DISALLOW_COPY_AND_ASSIGN_(MockFunction); }; } // namespace testing #endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_FUNCTION_MOCKERS_H_
0
repos/DirectXShaderCompiler/utils/unittest/googlemock/include
repos/DirectXShaderCompiler/utils/unittest/googlemock/include/gmock/gmock.h
// 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. // // Author: [email protected] (Zhanyong Wan) // Google Mock - a framework for writing C++ mock classes. // // This is the main header file a user should include. #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_H_ // This file implements the following syntax: // // ON_CALL(mock_object.Method(...)) // .With(...) ? // .WillByDefault(...); // // where With() is optional and WillByDefault() must appear exactly // once. // // EXPECT_CALL(mock_object.Method(...)) // .With(...) ? // .Times(...) ? // .InSequence(...) * // .WillOnce(...) * // .WillRepeatedly(...) ? // .RetiresOnSaturation() ? ; // // where all clauses are optional and WillOnce() can be repeated. #include "gmock/gmock-actions.h" #include "gmock/gmock-cardinalities.h" #include "gmock/gmock-generated-actions.h" #include "gmock/gmock-generated-function-mockers.h" #include "gmock/gmock-generated-nice-strict.h" #include "gmock/gmock-generated-matchers.h" #include "gmock/gmock-matchers.h" #include "gmock/gmock-more-actions.h" #include "gmock/gmock-more-matchers.h" #include "gmock/internal/gmock-internal-utils.h" namespace testing { // Declares Google Mock flags that we want a user to use programmatically. GMOCK_DECLARE_bool_(catch_leaked_mocks); GMOCK_DECLARE_string_(verbose); // Initializes Google Mock. This must be called before running the // tests. In particular, it parses the command line for the flags // that Google Mock recognizes. Whenever a Google Mock flag is seen, // it is removed from argv, and *argc is decremented. // // No value is returned. Instead, the Google Mock flag variables are // updated. // // Since Google Test is needed for Google Mock to work, this function // also initializes Google Test and parses its flags, if that hasn't // been done. GTEST_API_ void InitGoogleMock(int* argc, char** argv); // This overloaded version can be used in Windows programs compiled in // UNICODE mode. GTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv); } // namespace testing #endif // GMOCK_INCLUDE_GMOCK_GMOCK_H_
0
repos/DirectXShaderCompiler/utils/unittest/googlemock/include
repos/DirectXShaderCompiler/utils/unittest/googlemock/include/gmock/gmock-matchers.h
// 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. // // Author: [email protected] (Zhanyong Wan) // Google Mock - a framework for writing C++ mock classes. // // This file implements some commonly used argument matchers. More // matchers can be defined by the user implementing the // MatcherInterface<T> interface if necessary. #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_ #include <math.h> #include <algorithm> #include <iterator> #include <limits> #include <ostream> // NOLINT #include <sstream> #include <string> #include <utility> #include <vector> #include "gmock/internal/gmock-internal-utils.h" #include "gmock/internal/gmock-port.h" #include "gtest/gtest.h" #if GTEST_HAS_STD_INITIALIZER_LIST_ # include <initializer_list> // NOLINT -- must be after gtest.h #endif #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable:4100) #endif #ifdef __clang__ #if __has_warning("-Wdeprecated-copy") #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-copy" #endif #endif namespace testing { // To implement a matcher Foo for type T, define: // 1. a class FooMatcherImpl that implements the // MatcherInterface<T> interface, and // 2. a factory function that creates a Matcher<T> object from a // FooMatcherImpl*. // // The two-level delegation design makes it possible to allow a user // to write "v" instead of "Eq(v)" where a Matcher is expected, which // is impossible if we pass matchers by pointers. It also eases // ownership management as Matcher objects can now be copied like // plain values. // MatchResultListener is an abstract class. Its << operator can be // used by a matcher to explain why a value matches or doesn't match. // // TODO([email protected]): add method // bool InterestedInWhy(bool result) const; // to indicate whether the listener is interested in why the match // result is 'result'. class MatchResultListener { public: // Creates a listener object with the given underlying ostream. The // listener does not own the ostream, and does not dereference it // in the constructor or destructor. explicit MatchResultListener(::std::ostream* os) : stream_(os) {} virtual ~MatchResultListener() = 0; // Makes this class abstract. // Streams x to the underlying ostream; does nothing if the ostream // is NULL. template <typename T> MatchResultListener& operator<<(const T& x) { if (stream_ != NULL) *stream_ << x; return *this; } // Returns the underlying ostream. ::std::ostream* stream() { return stream_; } // Returns true iff the listener is interested in an explanation of // the match result. A matcher's MatchAndExplain() method can use // this information to avoid generating the explanation when no one // intends to hear it. bool IsInterested() const { return stream_ != NULL; } private: ::std::ostream* const stream_; GTEST_DISALLOW_COPY_AND_ASSIGN_(MatchResultListener); }; inline MatchResultListener::~MatchResultListener() { } // An instance of a subclass of this knows how to describe itself as a // matcher. class MatcherDescriberInterface { public: virtual ~MatcherDescriberInterface() {} // Describes this matcher to an ostream. The function should print // a verb phrase that describes the property a value matching this // matcher should have. The subject of the verb phrase is the value // being matched. For example, the DescribeTo() method of the Gt(7) // matcher prints "is greater than 7". virtual void DescribeTo(::std::ostream* os) const = 0; // Describes the negation of this matcher to an ostream. For // example, if the description of this matcher is "is greater than // 7", the negated description could be "is not greater than 7". // You are not required to override this when implementing // MatcherInterface, but it is highly advised so that your matcher // can produce good error messages. virtual void DescribeNegationTo(::std::ostream* os) const { *os << "not ("; DescribeTo(os); *os << ")"; } }; // The implementation of a matcher. template <typename T> class MatcherInterface : public MatcherDescriberInterface { public: // Returns true iff the matcher matches x; also explains the match // result to 'listener' if necessary (see the next paragraph), in // the form of a non-restrictive relative clause ("which ...", // "whose ...", etc) that describes x. For example, the // MatchAndExplain() method of the Pointee(...) matcher should // generate an explanation like "which points to ...". // // Implementations of MatchAndExplain() should add an explanation of // the match result *if and only if* they can provide additional // information that's not already present (or not obvious) in the // print-out of x and the matcher's description. Whether the match // succeeds is not a factor in deciding whether an explanation is // needed, as sometimes the caller needs to print a failure message // when the match succeeds (e.g. when the matcher is used inside // Not()). // // For example, a "has at least 10 elements" matcher should explain // what the actual element count is, regardless of the match result, // as it is useful information to the reader; on the other hand, an // "is empty" matcher probably only needs to explain what the actual // size is when the match fails, as it's redundant to say that the // size is 0 when the value is already known to be empty. // // You should override this method when defining a new matcher. // // It's the responsibility of the caller (Google Mock) to guarantee // that 'listener' is not NULL. This helps to simplify a matcher's // implementation when it doesn't care about the performance, as it // can talk to 'listener' without checking its validity first. // However, in order to implement dummy listeners efficiently, // listener->stream() may be NULL. virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0; // Inherits these methods from MatcherDescriberInterface: // virtual void DescribeTo(::std::ostream* os) const = 0; // virtual void DescribeNegationTo(::std::ostream* os) const; }; // A match result listener that stores the explanation in a string. class StringMatchResultListener : public MatchResultListener { public: StringMatchResultListener() : MatchResultListener(&ss_) {} // Returns the explanation accumulated so far. internal::string str() const { return ss_.str(); } // Clears the explanation accumulated so far. void Clear() { ss_.str(""); } private: ::std::stringstream ss_; GTEST_DISALLOW_COPY_AND_ASSIGN_(StringMatchResultListener); }; namespace internal { struct AnyEq { template <typename A, typename B> bool operator()(const A& a, const B& b) const { return a == b; } }; struct AnyNe { template <typename A, typename B> bool operator()(const A& a, const B& b) const { return a != b; } }; struct AnyLt { template <typename A, typename B> bool operator()(const A& a, const B& b) const { return a < b; } }; struct AnyGt { template <typename A, typename B> bool operator()(const A& a, const B& b) const { return a > b; } }; struct AnyLe { template <typename A, typename B> bool operator()(const A& a, const B& b) const { return a <= b; } }; struct AnyGe { template <typename A, typename B> bool operator()(const A& a, const B& b) const { return a >= b; } }; // A match result listener that ignores the explanation. class DummyMatchResultListener : public MatchResultListener { public: DummyMatchResultListener() : MatchResultListener(NULL) {} private: GTEST_DISALLOW_COPY_AND_ASSIGN_(DummyMatchResultListener); }; // A match result listener that forwards the explanation to a given // ostream. The difference between this and MatchResultListener is // that the former is concrete. class StreamMatchResultListener : public MatchResultListener { public: explicit StreamMatchResultListener(::std::ostream* os) : MatchResultListener(os) {} private: GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamMatchResultListener); }; // An internal class for implementing Matcher<T>, which will derive // from it. We put functionalities common to all Matcher<T> // specializations here to avoid code duplication. template <typename T> class MatcherBase { public: // Returns true iff the matcher matches x; also explains the match // result to 'listener'. bool MatchAndExplain(T x, MatchResultListener* listener) const { return impl_->MatchAndExplain(x, listener); } // Returns true iff this matcher matches x. bool Matches(T x) const { DummyMatchResultListener dummy; return MatchAndExplain(x, &dummy); } // Describes this matcher to an ostream. void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); } // Describes the negation of this matcher to an ostream. void DescribeNegationTo(::std::ostream* os) const { impl_->DescribeNegationTo(os); } // Explains why x matches, or doesn't match, the matcher. void ExplainMatchResultTo(T x, ::std::ostream* os) const { StreamMatchResultListener listener(os); MatchAndExplain(x, &listener); } // Returns the describer for this matcher object; retains ownership // of the describer, which is only guaranteed to be alive when // this matcher object is alive. const MatcherDescriberInterface* GetDescriber() const { return impl_.get(); } protected: MatcherBase() {} // Constructs a matcher from its implementation. explicit MatcherBase(const MatcherInterface<T>* impl) : impl_(impl) {} virtual ~MatcherBase() {} private: // shared_ptr (util/gtl/shared_ptr.h) and linked_ptr have similar // interfaces. The former dynamically allocates a chunk of memory // to hold the reference count, while the latter tracks all // references using a circular linked list without allocating // memory. It has been observed that linked_ptr performs better in // typical scenarios. However, shared_ptr can out-perform // linked_ptr when there are many more uses of the copy constructor // than the default constructor. // // If performance becomes a problem, we should see if using // shared_ptr helps. ::testing::internal::linked_ptr<const MatcherInterface<T> > impl_; }; } // namespace internal // A Matcher<T> is a copyable and IMMUTABLE (except by assignment) // object that can check whether a value of type T matches. The // implementation of Matcher<T> is just a linked_ptr to const // MatcherInterface<T>, so copying is fairly cheap. Don't inherit // from Matcher! template <typename T> class Matcher : public internal::MatcherBase<T> { public: // Constructs a null matcher. Needed for storing Matcher objects in STL // containers. A default-constructed matcher is not yet initialized. You // cannot use it until a valid value has been assigned to it. explicit Matcher() {} // NOLINT // Constructs a matcher from its implementation. explicit Matcher(const MatcherInterface<T>* impl) : internal::MatcherBase<T>(impl) {} // Implicit constructor here allows people to write // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes Matcher(T value); // NOLINT }; // The following two specializations allow the user to write str // instead of Eq(str) and "foo" instead of Eq("foo") when a string // matcher is expected. template <> class GTEST_API_ Matcher<const internal::string&> : public internal::MatcherBase<const internal::string&> { public: Matcher() {} explicit Matcher(const MatcherInterface<const internal::string&>* impl) : internal::MatcherBase<const internal::string&>(impl) {} // Allows the user to write str instead of Eq(str) sometimes, where // str is a string object. Matcher(const internal::string& s); // NOLINT // Allows the user to write "foo" instead of Eq("foo") sometimes. Matcher(const char* s); // NOLINT }; template <> class GTEST_API_ Matcher<internal::string> : public internal::MatcherBase<internal::string> { public: Matcher() {} explicit Matcher(const MatcherInterface<internal::string>* impl) : internal::MatcherBase<internal::string>(impl) {} // Allows the user to write str instead of Eq(str) sometimes, where // str is a string object. Matcher(const internal::string& s); // NOLINT // Allows the user to write "foo" instead of Eq("foo") sometimes. Matcher(const char* s); // NOLINT }; #if GTEST_HAS_STRING_PIECE_ // The following two specializations allow the user to write str // instead of Eq(str) and "foo" instead of Eq("foo") when a StringPiece // matcher is expected. template <> class GTEST_API_ Matcher<const StringPiece&> : public internal::MatcherBase<const StringPiece&> { public: Matcher() {} explicit Matcher(const MatcherInterface<const StringPiece&>* impl) : internal::MatcherBase<const StringPiece&>(impl) {} // Allows the user to write str instead of Eq(str) sometimes, where // str is a string object. Matcher(const internal::string& s); // NOLINT // Allows the user to write "foo" instead of Eq("foo") sometimes. Matcher(const char* s); // NOLINT // Allows the user to pass StringPieces directly. Matcher(StringPiece s); // NOLINT }; template <> class GTEST_API_ Matcher<StringPiece> : public internal::MatcherBase<StringPiece> { public: Matcher() {} explicit Matcher(const MatcherInterface<StringPiece>* impl) : internal::MatcherBase<StringPiece>(impl) {} // Allows the user to write str instead of Eq(str) sometimes, where // str is a string object. Matcher(const internal::string& s); // NOLINT // Allows the user to write "foo" instead of Eq("foo") sometimes. Matcher(const char* s); // NOLINT // Allows the user to pass StringPieces directly. Matcher(StringPiece s); // NOLINT }; #endif // GTEST_HAS_STRING_PIECE_ // The PolymorphicMatcher class template makes it easy to implement a // polymorphic matcher (i.e. a matcher that can match values of more // than one type, e.g. Eq(n) and NotNull()). // // To define a polymorphic matcher, a user should provide an Impl // class that has a DescribeTo() method and a DescribeNegationTo() // method, and define a member function (or member function template) // // bool MatchAndExplain(const Value& value, // MatchResultListener* listener) const; // // See the definition of NotNull() for a complete example. template <class Impl> class PolymorphicMatcher { public: explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {} // Returns a mutable reference to the underlying matcher // implementation object. Impl& mutable_impl() { return impl_; } // Returns an immutable reference to the underlying matcher // implementation object. const Impl& impl() const { return impl_; } template <typename T> operator Matcher<T>() const { return Matcher<T>(new MonomorphicImpl<T>(impl_)); } private: template <typename T> class MonomorphicImpl : public MatcherInterface<T> { public: explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {} virtual void DescribeTo(::std::ostream* os) const { impl_.DescribeTo(os); } virtual void DescribeNegationTo(::std::ostream* os) const { impl_.DescribeNegationTo(os); } virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { return impl_.MatchAndExplain(x, listener); } private: const Impl impl_; GTEST_DISALLOW_ASSIGN_(MonomorphicImpl); }; Impl impl_; GTEST_DISALLOW_ASSIGN_(PolymorphicMatcher); }; // Creates a matcher from its implementation. This is easier to use // than the Matcher<T> constructor as it doesn't require you to // explicitly write the template argument, e.g. // // MakeMatcher(foo); // vs // Matcher<const string&>(foo); template <typename T> inline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) { return Matcher<T>(impl); } // Creates a polymorphic matcher from its implementation. This is // easier to use than the PolymorphicMatcher<Impl> constructor as it // doesn't require you to explicitly write the template argument, e.g. // // MakePolymorphicMatcher(foo); // vs // PolymorphicMatcher<TypeOfFoo>(foo); template <class Impl> inline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) { return PolymorphicMatcher<Impl>(impl); } // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION // and MUST NOT BE USED IN USER CODE!!! namespace internal { // The MatcherCastImpl class template is a helper for implementing // MatcherCast(). We need this helper in order to partially // specialize the implementation of MatcherCast() (C++ allows // class/struct templates to be partially specialized, but not // function templates.). // This general version is used when MatcherCast()'s argument is a // polymorphic matcher (i.e. something that can be converted to a // Matcher but is not one yet; for example, Eq(value)) or a value (for // example, "hello"). template <typename T, typename M> class MatcherCastImpl { public: static Matcher<T> Cast(const M& polymorphic_matcher_or_value) { // M can be a polymorhic matcher, in which case we want to use // its conversion operator to create Matcher<T>. Or it can be a value // that should be passed to the Matcher<T>'s constructor. // // We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a // polymorphic matcher because it'll be ambiguous if T has an implicit // constructor from M (this usually happens when T has an implicit // constructor from any type). // // It won't work to unconditionally implict_cast // polymorphic_matcher_or_value to Matcher<T> because it won't trigger // a user-defined conversion from M to T if one exists (assuming M is // a value). return CastImpl( polymorphic_matcher_or_value, BooleanConstant< internal::ImplicitlyConvertible<M, Matcher<T> >::value>()); } private: static Matcher<T> CastImpl(const M& value, BooleanConstant<false>) { // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic // matcher. It must be a value then. Use direct initialization to create // a matcher. return Matcher<T>(ImplicitCast_<T>(value)); } static Matcher<T> CastImpl(const M& polymorphic_matcher_or_value, BooleanConstant<true>) { // M is implicitly convertible to Matcher<T>, which means that either // M is a polymorhpic matcher or Matcher<T> has an implicit constructor // from M. In both cases using the implicit conversion will produce a // matcher. // // Even if T has an implicit constructor from M, it won't be called because // creating Matcher<T> would require a chain of two user-defined conversions // (first to create T from M and then to create Matcher<T> from T). return polymorphic_matcher_or_value; } }; // This more specialized version is used when MatcherCast()'s argument // is already a Matcher. This only compiles when type T can be // statically converted to type U. template <typename T, typename U> class MatcherCastImpl<T, Matcher<U> > { public: static Matcher<T> Cast(const Matcher<U>& source_matcher) { return Matcher<T>(new Impl(source_matcher)); } private: class Impl : public MatcherInterface<T> { public: explicit Impl(const Matcher<U>& source_matcher) : source_matcher_(source_matcher) {} // We delegate the matching logic to the source matcher. virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { return source_matcher_.MatchAndExplain(static_cast<U>(x), listener); } virtual void DescribeTo(::std::ostream* os) const { source_matcher_.DescribeTo(os); } virtual void DescribeNegationTo(::std::ostream* os) const { source_matcher_.DescribeNegationTo(os); } private: const Matcher<U> source_matcher_; GTEST_DISALLOW_ASSIGN_(Impl); }; }; // This even more specialized version is used for efficiently casting // a matcher to its own type. template <typename T> class MatcherCastImpl<T, Matcher<T> > { public: static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; } }; } // namespace internal // In order to be safe and clear, casting between different matcher // types is done explicitly via MatcherCast<T>(m), which takes a // matcher m and returns a Matcher<T>. It compiles only when T can be // statically converted to the argument type of m. template <typename T, typename M> inline Matcher<T> MatcherCast(const M& matcher) { return internal::MatcherCastImpl<T, M>::Cast(matcher); } // Implements SafeMatcherCast(). // // We use an intermediate class to do the actual safe casting as Nokia's // Symbian compiler cannot decide between // template <T, M> ... (M) and // template <T, U> ... (const Matcher<U>&) // for function templates but can for member function templates. template <typename T> class SafeMatcherCastImpl { public: // This overload handles polymorphic matchers and values only since // monomorphic matchers are handled by the next one. template <typename M> static inline Matcher<T> Cast(const M& polymorphic_matcher_or_value) { return internal::MatcherCastImpl<T, M>::Cast(polymorphic_matcher_or_value); } // This overload handles monomorphic matchers. // // In general, if type T can be implicitly converted to type U, we can // safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is // contravariant): just keep a copy of the original Matcher<U>, convert the // argument from type T to U, and then pass it to the underlying Matcher<U>. // The only exception is when U is a reference and T is not, as the // underlying Matcher<U> may be interested in the argument's address, which // is not preserved in the conversion from T to U. template <typename U> static inline Matcher<T> Cast(const Matcher<U>& matcher) { // Enforce that T can be implicitly converted to U. GTEST_COMPILE_ASSERT_((internal::ImplicitlyConvertible<T, U>::value), T_must_be_implicitly_convertible_to_U); // Enforce that we are not converting a non-reference type T to a reference // type U. GTEST_COMPILE_ASSERT_( internal::is_reference<T>::value || !internal::is_reference<U>::value, cannot_convert_non_referentce_arg_to_reference); // In case both T and U are arithmetic types, enforce that the // conversion is not lossy. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT; typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU; const bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther; const bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther; GTEST_COMPILE_ASSERT_( kTIsOther || kUIsOther || (internal::LosslessArithmeticConvertible<RawT, RawU>::value), conversion_of_arithmetic_types_must_be_lossless); return MatcherCast<T>(matcher); } }; template <typename T, typename M> inline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher) { return SafeMatcherCastImpl<T>::Cast(polymorphic_matcher); } // A<T>() returns a matcher that matches any value of type T. template <typename T> Matcher<T> A(); // Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION // and MUST NOT BE USED IN USER CODE!!! namespace internal { // If the explanation is not empty, prints it to the ostream. inline void PrintIfNotEmpty(const internal::string& explanation, ::std::ostream* os) { if (explanation != "" && os != NULL) { *os << ", " << explanation; } } // Returns true if the given type name is easy to read by a human. // This is used to decide whether printing the type of a value might // be helpful. inline bool IsReadableTypeName(const string& type_name) { // We consider a type name readable if it's short or doesn't contain // a template or function type. return (type_name.length() <= 20 || type_name.find_first_of("<(") == string::npos); } // Matches the value against the given matcher, prints the value and explains // the match result to the listener. Returns the match result. // 'listener' must not be NULL. // Value cannot be passed by const reference, because some matchers take a // non-const argument. template <typename Value, typename T> bool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher, MatchResultListener* listener) { if (!listener->IsInterested()) { // If the listener is not interested, we do not need to construct the // inner explanation. return matcher.Matches(value); } StringMatchResultListener inner_listener; const bool match = matcher.MatchAndExplain(value, &inner_listener); UniversalPrint(value, listener->stream()); #if GTEST_HAS_RTTI const string& type_name = GetTypeName<Value>(); if (IsReadableTypeName(type_name)) *listener->stream() << " (of type " << type_name << ")"; #endif PrintIfNotEmpty(inner_listener.str(), listener->stream()); return match; } // An internal helper class for doing compile-time loop on a tuple's // fields. template <size_t N> class TuplePrefix { public: // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true // iff the first N fields of matcher_tuple matches the first N // fields of value_tuple, respectively. template <typename MatcherTuple, typename ValueTuple> static bool Matches(const MatcherTuple& matcher_tuple, const ValueTuple& value_tuple) { return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple) && get<N - 1>(matcher_tuple).Matches(get<N - 1>(value_tuple)); } // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os) // describes failures in matching the first N fields of matchers // against the first N fields of values. If there is no failure, // nothing will be streamed to os. template <typename MatcherTuple, typename ValueTuple> static void ExplainMatchFailuresTo(const MatcherTuple& matchers, const ValueTuple& values, ::std::ostream* os) { // First, describes failures in the first N - 1 fields. TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os); // Then describes the failure (if any) in the (N - 1)-th (0-based) // field. typename tuple_element<N - 1, MatcherTuple>::type matcher = get<N - 1>(matchers); typedef typename tuple_element<N - 1, ValueTuple>::type Value; Value value = get<N - 1>(values); StringMatchResultListener listener; if (!matcher.MatchAndExplain(value, &listener)) { // TODO(wan): include in the message the name of the parameter // as used in MOCK_METHOD*() when possible. *os << " Expected arg #" << N - 1 << ": "; get<N - 1>(matchers).DescribeTo(os); *os << "\n Actual: "; // We remove the reference in type Value to prevent the // universal printer from printing the address of value, which // isn't interesting to the user most of the time. The // matcher's MatchAndExplain() method handles the case when // the address is interesting. internal::UniversalPrint(value, os); PrintIfNotEmpty(listener.str(), os); *os << "\n"; } } }; // The base case. template <> class TuplePrefix<0> { public: template <typename MatcherTuple, typename ValueTuple> static bool Matches(const MatcherTuple& /* matcher_tuple */, const ValueTuple& /* value_tuple */) { return true; } template <typename MatcherTuple, typename ValueTuple> static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */, const ValueTuple& /* values */, ::std::ostream* /* os */) {} }; // TupleMatches(matcher_tuple, value_tuple) returns true iff all // matchers in matcher_tuple match the corresponding fields in // value_tuple. It is a compiler error if matcher_tuple and // value_tuple have different number of fields or incompatible field // types. template <typename MatcherTuple, typename ValueTuple> bool TupleMatches(const MatcherTuple& matcher_tuple, const ValueTuple& value_tuple) { // Makes sure that matcher_tuple and value_tuple have the same // number of fields. GTEST_COMPILE_ASSERT_(tuple_size<MatcherTuple>::value == tuple_size<ValueTuple>::value, matcher_and_value_have_different_numbers_of_fields); return TuplePrefix<tuple_size<ValueTuple>::value>:: Matches(matcher_tuple, value_tuple); } // Describes failures in matching matchers against values. If there // is no failure, nothing will be streamed to os. template <typename MatcherTuple, typename ValueTuple> void ExplainMatchFailureTupleTo(const MatcherTuple& matchers, const ValueTuple& values, ::std::ostream* os) { TuplePrefix<tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo( matchers, values, os); } // TransformTupleValues and its helper. // // TransformTupleValuesHelper hides the internal machinery that // TransformTupleValues uses to implement a tuple traversal. template <typename Tuple, typename Func, typename OutIter> class TransformTupleValuesHelper { private: typedef ::testing::tuple_size<Tuple> TupleSize; public: // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'. // Returns the final value of 'out' in case the caller needs it. static OutIter Run(Func f, const Tuple& t, OutIter out) { return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out); } private: template <typename Tup, size_t kRemainingSize> struct IterateOverTuple { OutIter operator() (Func f, const Tup& t, OutIter out) const { *out++ = f(::testing::get<TupleSize::value - kRemainingSize>(t)); return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out); } }; template <typename Tup> struct IterateOverTuple<Tup, 0> { OutIter operator() (Func /* f */, const Tup& /* t */, OutIter out) const { return out; } }; }; // Successively invokes 'f(element)' on each element of the tuple 't', // appending each result to the 'out' iterator. Returns the final value // of 'out'. template <typename Tuple, typename Func, typename OutIter> OutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) { return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out); } // Implements A<T>(). template <typename T> class AnyMatcherImpl : public MatcherInterface<T> { public: virtual bool MatchAndExplain( T /* x */, MatchResultListener* /* listener */) const { return true; } virtual void DescribeTo(::std::ostream* os) const { *os << "is anything"; } virtual void DescribeNegationTo(::std::ostream* os) const { // This is mostly for completeness' safe, as it's not very useful // to write Not(A<bool>()). However we cannot completely rule out // such a possibility, and it doesn't hurt to be prepared. *os << "never matches"; } }; // Implements _, a matcher that matches any value of any // type. This is a polymorphic matcher, so we need a template type // conversion operator to make it appearing as a Matcher<T> for any // type T. class AnythingMatcher { public: template <typename T> operator Matcher<T>() const { return A<T>(); } }; // Implements a matcher that compares a given value with a // pre-supplied value using one of the ==, <=, <, etc, operators. The // two values being compared don't have to have the same type. // // The matcher defined here is polymorphic (for example, Eq(5) can be // used to match an int, a short, a double, etc). Therefore we use // a template type conversion operator in the implementation. // // The following template definition assumes that the Rhs parameter is // a "bare" type (i.e. neither 'const T' nor 'T&'). template <typename D, typename Rhs, typename Op> class ComparisonBase { public: explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {} template <typename Lhs> operator Matcher<Lhs>() const { return MakeMatcher(new Impl<Lhs>(rhs_)); } private: template <typename Lhs> class Impl : public MatcherInterface<Lhs> { public: explicit Impl(const Rhs& rhs) : rhs_(rhs) {} virtual bool MatchAndExplain( Lhs lhs, MatchResultListener* /* listener */) const { return Op()(lhs, rhs_); } virtual void DescribeTo(::std::ostream* os) const { *os << D::Desc() << " "; UniversalPrint(rhs_, os); } virtual void DescribeNegationTo(::std::ostream* os) const { *os << D::NegatedDesc() << " "; UniversalPrint(rhs_, os); } private: Rhs rhs_; GTEST_DISALLOW_ASSIGN_(Impl); }; Rhs rhs_; GTEST_DISALLOW_ASSIGN_(ComparisonBase); }; template <typename Rhs> class EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> { public: explicit EqMatcher(const Rhs& rhs) : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) { } static const char* Desc() { return "is equal to"; } static const char* NegatedDesc() { return "isn't equal to"; } }; template <typename Rhs> class NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> { public: explicit NeMatcher(const Rhs& rhs) : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) { } static const char* Desc() { return "isn't equal to"; } static const char* NegatedDesc() { return "is equal to"; } }; template <typename Rhs> class LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> { public: explicit LtMatcher(const Rhs& rhs) : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) { } static const char* Desc() { return "is <"; } static const char* NegatedDesc() { return "isn't <"; } }; template <typename Rhs> class GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> { public: explicit GtMatcher(const Rhs& rhs) : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) { } static const char* Desc() { return "is >"; } static const char* NegatedDesc() { return "isn't >"; } }; template <typename Rhs> class LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> { public: explicit LeMatcher(const Rhs& rhs) : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) { } static const char* Desc() { return "is <="; } static const char* NegatedDesc() { return "isn't <="; } }; template <typename Rhs> class GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> { public: explicit GeMatcher(const Rhs& rhs) : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) { } static const char* Desc() { return "is >="; } static const char* NegatedDesc() { return "isn't >="; } }; // Implements the polymorphic IsNull() matcher, which matches any raw or smart // pointer that is NULL. class IsNullMatcher { public: template <typename Pointer> bool MatchAndExplain(const Pointer& p, MatchResultListener* /* listener */) const { #if GTEST_LANG_CXX11 return p == nullptr; #else // GTEST_LANG_CXX11 return GetRawPointer(p) == NULL; #endif // GTEST_LANG_CXX11 } void DescribeTo(::std::ostream* os) const { *os << "is NULL"; } void DescribeNegationTo(::std::ostream* os) const { *os << "isn't NULL"; } }; // Implements the polymorphic NotNull() matcher, which matches any raw or smart // pointer that is not NULL. class NotNullMatcher { public: template <typename Pointer> bool MatchAndExplain(const Pointer& p, MatchResultListener* /* listener */) const { #if GTEST_LANG_CXX11 return p != nullptr; #else // GTEST_LANG_CXX11 return GetRawPointer(p) != NULL; #endif // GTEST_LANG_CXX11 } void DescribeTo(::std::ostream* os) const { *os << "isn't NULL"; } void DescribeNegationTo(::std::ostream* os) const { *os << "is NULL"; } }; // Ref(variable) matches any argument that is a reference to // 'variable'. This matcher is polymorphic as it can match any // super type of the type of 'variable'. // // The RefMatcher template class implements Ref(variable). It can // only be instantiated with a reference type. This prevents a user // from mistakenly using Ref(x) to match a non-reference function // argument. For example, the following will righteously cause a // compiler error: // // int n; // Matcher<int> m1 = Ref(n); // This won't compile. // Matcher<int&> m2 = Ref(n); // This will compile. template <typename T> class RefMatcher; template <typename T> class RefMatcher<T&> { // Google Mock is a generic framework and thus needs to support // mocking any function types, including those that take non-const // reference arguments. Therefore the template parameter T (and // Super below) can be instantiated to either a const type or a // non-const type. public: // RefMatcher() takes a T& instead of const T&, as we want the // compiler to catch using Ref(const_value) as a matcher for a // non-const reference. explicit RefMatcher(T& x) : object_(x) {} // NOLINT template <typename Super> operator Matcher<Super&>() const { // By passing object_ (type T&) to Impl(), which expects a Super&, // we make sure that Super is a super type of T. In particular, // this catches using Ref(const_value) as a matcher for a // non-const reference, as you cannot implicitly convert a const // reference to a non-const reference. return MakeMatcher(new Impl<Super>(object_)); } private: template <typename Super> class Impl : public MatcherInterface<Super&> { public: explicit Impl(Super& x) : object_(x) {} // NOLINT // MatchAndExplain() takes a Super& (as opposed to const Super&) // in order to match the interface MatcherInterface<Super&>. virtual bool MatchAndExplain( Super& x, MatchResultListener* listener) const { *listener << "which is located @" << static_cast<const void*>(&x); return &x == &object_; } virtual void DescribeTo(::std::ostream* os) const { *os << "references the variable "; UniversalPrinter<Super&>::Print(object_, os); } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "does not reference the variable "; UniversalPrinter<Super&>::Print(object_, os); } private: const Super& object_; GTEST_DISALLOW_ASSIGN_(Impl); }; T& object_; GTEST_DISALLOW_ASSIGN_(RefMatcher); }; // Polymorphic helper functions for narrow and wide string matchers. inline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) { return String::CaseInsensitiveCStringEquals(lhs, rhs); } inline bool CaseInsensitiveCStringEquals(const wchar_t* lhs, const wchar_t* rhs) { return String::CaseInsensitiveWideCStringEquals(lhs, rhs); } // String comparison for narrow or wide strings that can have embedded NUL // characters. template <typename StringType> bool CaseInsensitiveStringEquals(const StringType& s1, const StringType& s2) { // Are the heads equal? if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) { return false; } // Skip the equal heads. const typename StringType::value_type nul = 0; const size_t i1 = s1.find(nul), i2 = s2.find(nul); // Are we at the end of either s1 or s2? if (i1 == StringType::npos || i2 == StringType::npos) { return i1 == i2; } // Are the tails equal? return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1)); } // String matchers. // Implements equality-based string matchers like StrEq, StrCaseNe, and etc. template <typename StringType> class StrEqualityMatcher { public: StrEqualityMatcher(const StringType& str, bool expect_eq, bool case_sensitive) : string_(str), expect_eq_(expect_eq), case_sensitive_(case_sensitive) {} // Accepts pointer types, particularly: // const char* // char* // const wchar_t* // wchar_t* template <typename CharType> bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { if (s == NULL) { return !expect_eq_; } return MatchAndExplain(StringType(s), listener); } // Matches anything that can convert to StringType. // // This is a template, not just a plain function with const StringType&, // because StringPiece has some interfering non-explicit constructors. template <typename MatcheeStringType> bool MatchAndExplain(const MatcheeStringType& s, MatchResultListener* /* listener */) const { const StringType& s2(s); const bool eq = case_sensitive_ ? s2 == string_ : CaseInsensitiveStringEquals(s2, string_); return expect_eq_ == eq; } void DescribeTo(::std::ostream* os) const { DescribeToHelper(expect_eq_, os); } void DescribeNegationTo(::std::ostream* os) const { DescribeToHelper(!expect_eq_, os); } private: void DescribeToHelper(bool expect_eq, ::std::ostream* os) const { *os << (expect_eq ? "is " : "isn't "); *os << "equal to "; if (!case_sensitive_) { *os << "(ignoring case) "; } UniversalPrint(string_, os); } const StringType string_; const bool expect_eq_; const bool case_sensitive_; GTEST_DISALLOW_ASSIGN_(StrEqualityMatcher); }; // Implements the polymorphic HasSubstr(substring) matcher, which // can be used as a Matcher<T> as long as T can be converted to a // string. template <typename StringType> class HasSubstrMatcher { public: explicit HasSubstrMatcher(const StringType& substring) : substring_(substring) {} // Accepts pointer types, particularly: // const char* // char* // const wchar_t* // wchar_t* template <typename CharType> bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { return s != NULL && MatchAndExplain(StringType(s), listener); } // Matches anything that can convert to StringType. // // This is a template, not just a plain function with const StringType&, // because StringPiece has some interfering non-explicit constructors. template <typename MatcheeStringType> bool MatchAndExplain(const MatcheeStringType& s, MatchResultListener* /* listener */) const { const StringType& s2(s); return s2.find(substring_) != StringType::npos; } // Describes what this matcher matches. void DescribeTo(::std::ostream* os) const { *os << "has substring "; UniversalPrint(substring_, os); } void DescribeNegationTo(::std::ostream* os) const { *os << "has no substring "; UniversalPrint(substring_, os); } private: const StringType substring_; GTEST_DISALLOW_ASSIGN_(HasSubstrMatcher); }; // Implements the polymorphic StartsWith(substring) matcher, which // can be used as a Matcher<T> as long as T can be converted to a // string. template <typename StringType> class StartsWithMatcher { public: explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) { } // Accepts pointer types, particularly: // const char* // char* // const wchar_t* // wchar_t* template <typename CharType> bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { return s != NULL && MatchAndExplain(StringType(s), listener); } // Matches anything that can convert to StringType. // // This is a template, not just a plain function with const StringType&, // because StringPiece has some interfering non-explicit constructors. template <typename MatcheeStringType> bool MatchAndExplain(const MatcheeStringType& s, MatchResultListener* /* listener */) const { const StringType& s2(s); return s2.length() >= prefix_.length() && s2.substr(0, prefix_.length()) == prefix_; } void DescribeTo(::std::ostream* os) const { *os << "starts with "; UniversalPrint(prefix_, os); } void DescribeNegationTo(::std::ostream* os) const { *os << "doesn't start with "; UniversalPrint(prefix_, os); } private: const StringType prefix_; GTEST_DISALLOW_ASSIGN_(StartsWithMatcher); }; // Implements the polymorphic EndsWith(substring) matcher, which // can be used as a Matcher<T> as long as T can be converted to a // string. template <typename StringType> class EndsWithMatcher { public: explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {} // Accepts pointer types, particularly: // const char* // char* // const wchar_t* // wchar_t* template <typename CharType> bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { return s != NULL && MatchAndExplain(StringType(s), listener); } // Matches anything that can convert to StringType. // // This is a template, not just a plain function with const StringType&, // because StringPiece has some interfering non-explicit constructors. template <typename MatcheeStringType> bool MatchAndExplain(const MatcheeStringType& s, MatchResultListener* /* listener */) const { const StringType& s2(s); return s2.length() >= suffix_.length() && s2.substr(s2.length() - suffix_.length()) == suffix_; } void DescribeTo(::std::ostream* os) const { *os << "ends with "; UniversalPrint(suffix_, os); } void DescribeNegationTo(::std::ostream* os) const { *os << "doesn't end with "; UniversalPrint(suffix_, os); } private: const StringType suffix_; GTEST_DISALLOW_ASSIGN_(EndsWithMatcher); }; // Implements polymorphic matchers MatchesRegex(regex) and // ContainsRegex(regex), which can be used as a Matcher<T> as long as // T can be converted to a string. class MatchesRegexMatcher { public: MatchesRegexMatcher(const RE* regex, bool full_match) : regex_(regex), full_match_(full_match) {} // Accepts pointer types, particularly: // const char* // char* // const wchar_t* // wchar_t* template <typename CharType> bool MatchAndExplain(CharType* s, MatchResultListener* listener) const { return s != NULL && MatchAndExplain(internal::string(s), listener); } // Matches anything that can convert to internal::string. // // This is a template, not just a plain function with const internal::string&, // because StringPiece has some interfering non-explicit constructors. template <class MatcheeStringType> bool MatchAndExplain(const MatcheeStringType& s, MatchResultListener* /* listener */) const { const internal::string& s2(s); return full_match_ ? RE::FullMatch(s2, *regex_) : RE::PartialMatch(s2, *regex_); } void DescribeTo(::std::ostream* os) const { *os << (full_match_ ? "matches" : "contains") << " regular expression "; UniversalPrinter<internal::string>::Print(regex_->pattern(), os); } void DescribeNegationTo(::std::ostream* os) const { *os << "doesn't " << (full_match_ ? "match" : "contain") << " regular expression "; UniversalPrinter<internal::string>::Print(regex_->pattern(), os); } private: const internal::linked_ptr<const RE> regex_; const bool full_match_; GTEST_DISALLOW_ASSIGN_(MatchesRegexMatcher); }; // Implements a matcher that compares the two fields of a 2-tuple // using one of the ==, <=, <, etc, operators. The two fields being // compared don't have to have the same type. // // The matcher defined here is polymorphic (for example, Eq() can be // used to match a tuple<int, short>, a tuple<const long&, double>, // etc). Therefore we use a template type conversion operator in the // implementation. template <typename D, typename Op> class PairMatchBase { public: template <typename T1, typename T2> operator Matcher< ::testing::tuple<T1, T2> >() const { return MakeMatcher(new Impl< ::testing::tuple<T1, T2> >); } template <typename T1, typename T2> operator Matcher<const ::testing::tuple<T1, T2>&>() const { return MakeMatcher(new Impl<const ::testing::tuple<T1, T2>&>); } private: static ::std::ostream& GetDesc(::std::ostream& os) { // NOLINT return os << D::Desc(); } template <typename Tuple> class Impl : public MatcherInterface<Tuple> { public: virtual bool MatchAndExplain( Tuple args, MatchResultListener* /* listener */) const { return Op()(::testing::get<0>(args), ::testing::get<1>(args)); } virtual void DescribeTo(::std::ostream* os) const { *os << "are " << GetDesc; } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "aren't " << GetDesc; } }; }; class Eq2Matcher : public PairMatchBase<Eq2Matcher, AnyEq> { public: static const char* Desc() { return "an equal pair"; } }; class Ne2Matcher : public PairMatchBase<Ne2Matcher, AnyNe> { public: static const char* Desc() { return "an unequal pair"; } }; class Lt2Matcher : public PairMatchBase<Lt2Matcher, AnyLt> { public: static const char* Desc() { return "a pair where the first < the second"; } }; class Gt2Matcher : public PairMatchBase<Gt2Matcher, AnyGt> { public: static const char* Desc() { return "a pair where the first > the second"; } }; class Le2Matcher : public PairMatchBase<Le2Matcher, AnyLe> { public: static const char* Desc() { return "a pair where the first <= the second"; } }; class Ge2Matcher : public PairMatchBase<Ge2Matcher, AnyGe> { public: static const char* Desc() { return "a pair where the first >= the second"; } }; // Implements the Not(...) matcher for a particular argument type T. // We do not nest it inside the NotMatcher class template, as that // will prevent different instantiations of NotMatcher from sharing // the same NotMatcherImpl<T> class. template <typename T> class NotMatcherImpl : public MatcherInterface<T> { public: explicit NotMatcherImpl(const Matcher<T>& matcher) : matcher_(matcher) {} virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { return !matcher_.MatchAndExplain(x, listener); } virtual void DescribeTo(::std::ostream* os) const { matcher_.DescribeNegationTo(os); } virtual void DescribeNegationTo(::std::ostream* os) const { matcher_.DescribeTo(os); } private: const Matcher<T> matcher_; GTEST_DISALLOW_ASSIGN_(NotMatcherImpl); }; // Implements the Not(m) matcher, which matches a value that doesn't // match matcher m. template <typename InnerMatcher> class NotMatcher { public: explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {} // This template type conversion operator allows Not(m) to be used // to match any type m can match. template <typename T> operator Matcher<T>() const { return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_))); } private: InnerMatcher matcher_; GTEST_DISALLOW_ASSIGN_(NotMatcher); }; // Implements the AllOf(m1, m2) matcher for a particular argument type // T. We do not nest it inside the BothOfMatcher class template, as // that will prevent different instantiations of BothOfMatcher from // sharing the same BothOfMatcherImpl<T> class. template <typename T> class BothOfMatcherImpl : public MatcherInterface<T> { public: BothOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2) : matcher1_(matcher1), matcher2_(matcher2) {} virtual void DescribeTo(::std::ostream* os) const { *os << "("; matcher1_.DescribeTo(os); *os << ") and ("; matcher2_.DescribeTo(os); *os << ")"; } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "("; matcher1_.DescribeNegationTo(os); *os << ") or ("; matcher2_.DescribeNegationTo(os); *os << ")"; } virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { // If either matcher1_ or matcher2_ doesn't match x, we only need // to explain why one of them fails. StringMatchResultListener listener1; if (!matcher1_.MatchAndExplain(x, &listener1)) { *listener << listener1.str(); return false; } StringMatchResultListener listener2; if (!matcher2_.MatchAndExplain(x, &listener2)) { *listener << listener2.str(); return false; } // Otherwise we need to explain why *both* of them match. const internal::string s1 = listener1.str(); const internal::string s2 = listener2.str(); if (s1 == "") { *listener << s2; } else { *listener << s1; if (s2 != "") { *listener << ", and " << s2; } } return true; } private: const Matcher<T> matcher1_; const Matcher<T> matcher2_; GTEST_DISALLOW_ASSIGN_(BothOfMatcherImpl); }; #if GTEST_LANG_CXX11 // MatcherList provides mechanisms for storing a variable number of matchers in // a list structure (ListType) and creating a combining matcher from such a // list. // The template is defined recursively using the following template paramters: // * kSize is the length of the MatcherList. // * Head is the type of the first matcher of the list. // * Tail denotes the types of the remaining matchers of the list. template <int kSize, typename Head, typename... Tail> struct MatcherList { typedef MatcherList<kSize - 1, Tail...> MatcherListTail; typedef ::std::pair<Head, typename MatcherListTail::ListType> ListType; // BuildList stores variadic type values in a nested pair structure. // Example: // MatcherList<3, int, string, float>::BuildList(5, "foo", 2.0) will return // the corresponding result of type pair<int, pair<string, float>>. static ListType BuildList(const Head& matcher, const Tail&... tail) { return ListType(matcher, MatcherListTail::BuildList(tail...)); } // CreateMatcher<T> creates a Matcher<T> from a given list of matchers (built // by BuildList()). CombiningMatcher<T> is used to combine the matchers of the // list. CombiningMatcher<T> must implement MatcherInterface<T> and have a // constructor taking two Matcher<T>s as input. template <typename T, template <typename /* T */> class CombiningMatcher> static Matcher<T> CreateMatcher(const ListType& matchers) { return Matcher<T>(new CombiningMatcher<T>( SafeMatcherCast<T>(matchers.first), MatcherListTail::template CreateMatcher<T, CombiningMatcher>( matchers.second))); } }; // The following defines the base case for the recursive definition of // MatcherList. template <typename Matcher1, typename Matcher2> struct MatcherList<2, Matcher1, Matcher2> { typedef ::std::pair<Matcher1, Matcher2> ListType; static ListType BuildList(const Matcher1& matcher1, const Matcher2& matcher2) { return ::std::pair<Matcher1, Matcher2>(matcher1, matcher2); } template <typename T, template <typename /* T */> class CombiningMatcher> static Matcher<T> CreateMatcher(const ListType& matchers) { return Matcher<T>(new CombiningMatcher<T>( SafeMatcherCast<T>(matchers.first), SafeMatcherCast<T>(matchers.second))); } }; // VariadicMatcher is used for the variadic implementation of // AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...). // CombiningMatcher<T> is used to recursively combine the provided matchers // (of type Args...). template <template <typename T> class CombiningMatcher, typename... Args> class VariadicMatcher { public: VariadicMatcher(const Args&... matchers) // NOLINT : matchers_(MatcherListType::BuildList(matchers...)) {} // This template type conversion operator allows an // VariadicMatcher<Matcher1, Matcher2...> object to match any type that // all of the provided matchers (Matcher1, Matcher2, ...) can match. template <typename T> operator Matcher<T>() const { return MatcherListType::template CreateMatcher<T, CombiningMatcher>( matchers_); } private: typedef MatcherList<sizeof...(Args), Args...> MatcherListType; const typename MatcherListType::ListType matchers_; GTEST_DISALLOW_ASSIGN_(VariadicMatcher); }; template <typename... Args> using AllOfMatcher = VariadicMatcher<BothOfMatcherImpl, Args...>; #endif // GTEST_LANG_CXX11 // Used for implementing the AllOf(m_1, ..., m_n) matcher, which // matches a value that matches all of the matchers m_1, ..., and m_n. template <typename Matcher1, typename Matcher2> class BothOfMatcher { public: BothOfMatcher(Matcher1 matcher1, Matcher2 matcher2) : matcher1_(matcher1), matcher2_(matcher2) {} // This template type conversion operator allows a // BothOfMatcher<Matcher1, Matcher2> object to match any type that // both Matcher1 and Matcher2 can match. template <typename T> operator Matcher<T>() const { return Matcher<T>(new BothOfMatcherImpl<T>(SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_))); } private: Matcher1 matcher1_; Matcher2 matcher2_; GTEST_DISALLOW_ASSIGN_(BothOfMatcher); }; // Implements the AnyOf(m1, m2) matcher for a particular argument type // T. We do not nest it inside the AnyOfMatcher class template, as // that will prevent different instantiations of AnyOfMatcher from // sharing the same EitherOfMatcherImpl<T> class. template <typename T> class EitherOfMatcherImpl : public MatcherInterface<T> { public: EitherOfMatcherImpl(const Matcher<T>& matcher1, const Matcher<T>& matcher2) : matcher1_(matcher1), matcher2_(matcher2) {} virtual void DescribeTo(::std::ostream* os) const { *os << "("; matcher1_.DescribeTo(os); *os << ") or ("; matcher2_.DescribeTo(os); *os << ")"; } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "("; matcher1_.DescribeNegationTo(os); *os << ") and ("; matcher2_.DescribeNegationTo(os); *os << ")"; } virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { // If either matcher1_ or matcher2_ matches x, we just need to // explain why *one* of them matches. StringMatchResultListener listener1; if (matcher1_.MatchAndExplain(x, &listener1)) { *listener << listener1.str(); return true; } StringMatchResultListener listener2; if (matcher2_.MatchAndExplain(x, &listener2)) { *listener << listener2.str(); return true; } // Otherwise we need to explain why *both* of them fail. const internal::string s1 = listener1.str(); const internal::string s2 = listener2.str(); if (s1 == "") { *listener << s2; } else { *listener << s1; if (s2 != "") { *listener << ", and " << s2; } } return false; } private: const Matcher<T> matcher1_; const Matcher<T> matcher2_; GTEST_DISALLOW_ASSIGN_(EitherOfMatcherImpl); }; #if GTEST_LANG_CXX11 // AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...). template <typename... Args> using AnyOfMatcher = VariadicMatcher<EitherOfMatcherImpl, Args...>; #endif // GTEST_LANG_CXX11 // Used for implementing the AnyOf(m_1, ..., m_n) matcher, which // matches a value that matches at least one of the matchers m_1, ..., // and m_n. template <typename Matcher1, typename Matcher2> class EitherOfMatcher { public: EitherOfMatcher(Matcher1 matcher1, Matcher2 matcher2) : matcher1_(matcher1), matcher2_(matcher2) {} // This template type conversion operator allows a // EitherOfMatcher<Matcher1, Matcher2> object to match any type that // both Matcher1 and Matcher2 can match. template <typename T> operator Matcher<T>() const { return Matcher<T>(new EitherOfMatcherImpl<T>( SafeMatcherCast<T>(matcher1_), SafeMatcherCast<T>(matcher2_))); } private: Matcher1 matcher1_; Matcher2 matcher2_; GTEST_DISALLOW_ASSIGN_(EitherOfMatcher); }; // Used for implementing Truly(pred), which turns a predicate into a // matcher. template <typename Predicate> class TrulyMatcher { public: explicit TrulyMatcher(Predicate pred) : predicate_(pred) {} // This method template allows Truly(pred) to be used as a matcher // for type T where T is the argument type of predicate 'pred'. The // argument is passed by reference as the predicate may be // interested in the address of the argument. template <typename T> bool MatchAndExplain(T& x, // NOLINT MatchResultListener* /* listener */) const { // Without the if-statement, MSVC sometimes warns about converting // a value to bool (warning 4800). // // We cannot write 'return !!predicate_(x);' as that doesn't work // when predicate_(x) returns a class convertible to bool but // having no operator!(). if (predicate_(x)) return true; return false; } void DescribeTo(::std::ostream* os) const { *os << "satisfies the given predicate"; } void DescribeNegationTo(::std::ostream* os) const { *os << "doesn't satisfy the given predicate"; } private: Predicate predicate_; GTEST_DISALLOW_ASSIGN_(TrulyMatcher); }; // Used for implementing Matches(matcher), which turns a matcher into // a predicate. template <typename M> class MatcherAsPredicate { public: explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {} // This template operator() allows Matches(m) to be used as a // predicate on type T where m is a matcher on type T. // // The argument x is passed by reference instead of by value, as // some matcher may be interested in its address (e.g. as in // Matches(Ref(n))(x)). template <typename T> bool operator()(const T& x) const { // We let matcher_ commit to a particular type here instead of // when the MatcherAsPredicate object was constructed. This // allows us to write Matches(m) where m is a polymorphic matcher // (e.g. Eq(5)). // // If we write Matcher<T>(matcher_).Matches(x) here, it won't // compile when matcher_ has type Matcher<const T&>; if we write // Matcher<const T&>(matcher_).Matches(x) here, it won't compile // when matcher_ has type Matcher<T>; if we just write // matcher_.Matches(x), it won't compile when matcher_ is // polymorphic, e.g. Eq(5). // // MatcherCast<const T&>() is necessary for making the code work // in all of the above situations. return MatcherCast<const T&>(matcher_).Matches(x); } private: M matcher_; GTEST_DISALLOW_ASSIGN_(MatcherAsPredicate); }; // For implementing ASSERT_THAT() and EXPECT_THAT(). The template // argument M must be a type that can be converted to a matcher. template <typename M> class PredicateFormatterFromMatcher { public: explicit PredicateFormatterFromMatcher(M m) : matcher_(internal::move(m)) {} // This template () operator allows a PredicateFormatterFromMatcher // object to act as a predicate-formatter suitable for using with // Google Test's EXPECT_PRED_FORMAT1() macro. template <typename T> AssertionResult operator()(const char* value_text, const T& x) const { // We convert matcher_ to a Matcher<const T&> *now* instead of // when the PredicateFormatterFromMatcher object was constructed, // as matcher_ may be polymorphic (e.g. NotNull()) and we won't // know which type to instantiate it to until we actually see the // type of x here. // // We write SafeMatcherCast<const T&>(matcher_) instead of // Matcher<const T&>(matcher_), as the latter won't compile when // matcher_ has type Matcher<T> (e.g. An<int>()). // We don't write MatcherCast<const T&> either, as that allows // potentially unsafe downcasting of the matcher argument. const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_); StringMatchResultListener listener; if (MatchPrintAndExplain(x, matcher, &listener)) return AssertionSuccess(); ::std::stringstream ss; ss << "Value of: " << value_text << "\n" << "Expected: "; matcher.DescribeTo(&ss); ss << "\n Actual: " << listener.str(); return AssertionFailure() << ss.str(); } private: const M matcher_; GTEST_DISALLOW_ASSIGN_(PredicateFormatterFromMatcher); }; // A helper function for converting a matcher to a predicate-formatter // without the user needing to explicitly write the type. This is // used for implementing ASSERT_THAT() and EXPECT_THAT(). // Implementation detail: 'matcher' is received by-value to force decaying. template <typename M> inline PredicateFormatterFromMatcher<M> MakePredicateFormatterFromMatcher(M matcher) { return PredicateFormatterFromMatcher<M>(internal::move(matcher)); } // Implements the polymorphic floating point equality matcher, which matches // two float values using ULP-based approximation or, optionally, a // user-specified epsilon. The template is meant to be instantiated with // FloatType being either float or double. template <typename FloatType> class FloatingEqMatcher { public: // Constructor for FloatingEqMatcher. // The matcher's input will be compared with expected. The matcher treats two // NANs as equal if nan_eq_nan is true. Otherwise, under IEEE standards, // equality comparisons between NANs will always return false. We specify a // negative max_abs_error_ term to indicate that ULP-based approximation will // be used for comparison. FloatingEqMatcher(FloatType expected, bool nan_eq_nan) : expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) { } // Constructor that supports a user-specified max_abs_error that will be used // for comparison instead of ULP-based approximation. The max absolute // should be non-negative. FloatingEqMatcher(FloatType expected, bool nan_eq_nan, FloatType max_abs_error) : expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(max_abs_error) { GTEST_CHECK_(max_abs_error >= 0) << ", where max_abs_error is" << max_abs_error; } // Implements floating point equality matcher as a Matcher<T>. template <typename T> class Impl : public MatcherInterface<T> { public: Impl(FloatType expected, bool nan_eq_nan, FloatType max_abs_error) : expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(max_abs_error) {} virtual bool MatchAndExplain(T value, MatchResultListener* listener) const { const FloatingPoint<FloatType> actual(value), expected(expected_); // Compares NaNs first, if nan_eq_nan_ is true. if (actual.is_nan() || expected.is_nan()) { if (actual.is_nan() && expected.is_nan()) { return nan_eq_nan_; } // One is nan; the other is not nan. return false; } if (HasMaxAbsError()) { // We perform an equality check so that inf will match inf, regardless // of error bounds. If the result of value - expected_ would result in // overflow or if either value is inf, the default result is infinity, // which should only match if max_abs_error_ is also infinity. if (value == expected_) { return true; } const FloatType diff = value - expected_; if (fabs(diff) <= max_abs_error_) { return true; } if (listener->IsInterested()) { *listener << "which is " << diff << " from " << expected_; } return false; } else { return actual.AlmostEquals(expected); } } virtual void DescribeTo(::std::ostream* os) const { // os->precision() returns the previously set precision, which we // store to restore the ostream to its original configuration // after outputting. const ::std::streamsize old_precision = os->precision( ::std::numeric_limits<FloatType>::digits10 + 2); if (FloatingPoint<FloatType>(expected_).is_nan()) { if (nan_eq_nan_) { *os << "is NaN"; } else { *os << "never matches"; } } else { *os << "is approximately " << expected_; if (HasMaxAbsError()) { *os << " (absolute error <= " << max_abs_error_ << ")"; } } os->precision(old_precision); } virtual void DescribeNegationTo(::std::ostream* os) const { // As before, get original precision. const ::std::streamsize old_precision = os->precision( ::std::numeric_limits<FloatType>::digits10 + 2); if (FloatingPoint<FloatType>(expected_).is_nan()) { if (nan_eq_nan_) { *os << "isn't NaN"; } else { *os << "is anything"; } } else { *os << "isn't approximately " << expected_; if (HasMaxAbsError()) { *os << " (absolute error > " << max_abs_error_ << ")"; } } // Restore original precision. os->precision(old_precision); } private: bool HasMaxAbsError() const { return max_abs_error_ >= 0; } const FloatType expected_; const bool nan_eq_nan_; // max_abs_error will be used for value comparison when >= 0. const FloatType max_abs_error_; GTEST_DISALLOW_ASSIGN_(Impl); }; // The following 3 type conversion operators allow FloatEq(expected) and // NanSensitiveFloatEq(expected) to be used as a Matcher<float>, a // Matcher<const float&>, or a Matcher<float&>, but nothing else. // (While Google's C++ coding style doesn't allow arguments passed // by non-const reference, we may see them in code not conforming to // the style. Therefore Google Mock needs to support them.) operator Matcher<FloatType>() const { return MakeMatcher( new Impl<FloatType>(expected_, nan_eq_nan_, max_abs_error_)); } operator Matcher<const FloatType&>() const { return MakeMatcher( new Impl<const FloatType&>(expected_, nan_eq_nan_, max_abs_error_)); } operator Matcher<FloatType&>() const { return MakeMatcher( new Impl<FloatType&>(expected_, nan_eq_nan_, max_abs_error_)); } private: const FloatType expected_; const bool nan_eq_nan_; // max_abs_error will be used for value comparison when >= 0. const FloatType max_abs_error_; GTEST_DISALLOW_ASSIGN_(FloatingEqMatcher); }; // Implements the Pointee(m) matcher for matching a pointer whose // pointee matches matcher m. The pointer can be either raw or smart. template <typename InnerMatcher> class PointeeMatcher { public: explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {} // This type conversion operator template allows Pointee(m) to be // used as a matcher for any pointer type whose pointee type is // compatible with the inner matcher, where type Pointer can be // either a raw pointer or a smart pointer. // // The reason we do this instead of relying on // MakePolymorphicMatcher() is that the latter is not flexible // enough for implementing the DescribeTo() method of Pointee(). template <typename Pointer> operator Matcher<Pointer>() const { return MakeMatcher(new Impl<Pointer>(matcher_)); } private: // The monomorphic implementation that works for a particular pointer type. template <typename Pointer> class Impl : public MatcherInterface<Pointer> { public: typedef typename PointeeOf<GTEST_REMOVE_CONST_( // NOLINT GTEST_REMOVE_REFERENCE_(Pointer))>::type Pointee; explicit Impl(const InnerMatcher& matcher) : matcher_(MatcherCast<const Pointee&>(matcher)) {} virtual void DescribeTo(::std::ostream* os) const { *os << "points to a value that "; matcher_.DescribeTo(os); } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "does not point to a value that "; matcher_.DescribeTo(os); } virtual bool MatchAndExplain(Pointer pointer, MatchResultListener* listener) const { if (GetRawPointer(pointer) == NULL) return false; *listener << "which points to "; return MatchPrintAndExplain(*pointer, matcher_, listener); } private: const Matcher<const Pointee&> matcher_; GTEST_DISALLOW_ASSIGN_(Impl); }; const InnerMatcher matcher_; GTEST_DISALLOW_ASSIGN_(PointeeMatcher); }; // Implements the WhenDynamicCastTo<T>(m) matcher that matches a pointer or // reference that matches inner_matcher when dynamic_cast<T> is applied. // The result of dynamic_cast<To> is forwarded to the inner matcher. // If To is a pointer and the cast fails, the inner matcher will receive NULL. // If To is a reference and the cast fails, this matcher returns false // immediately. template <typename To> class WhenDynamicCastToMatcherBase { public: explicit WhenDynamicCastToMatcherBase(const Matcher<To>& matcher) : matcher_(matcher) {} void DescribeTo(::std::ostream* os) const { GetCastTypeDescription(os); matcher_.DescribeTo(os); } void DescribeNegationTo(::std::ostream* os) const { GetCastTypeDescription(os); matcher_.DescribeNegationTo(os); } protected: const Matcher<To> matcher_; static string GetToName() { #if GTEST_HAS_RTTI return GetTypeName<To>(); #else // GTEST_HAS_RTTI return "the target type"; #endif // GTEST_HAS_RTTI } private: static void GetCastTypeDescription(::std::ostream* os) { *os << "when dynamic_cast to " << GetToName() << ", "; } GTEST_DISALLOW_ASSIGN_(WhenDynamicCastToMatcherBase); }; // Primary template. // To is a pointer. Cast and forward the result. template <typename To> class WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase<To> { public: explicit WhenDynamicCastToMatcher(const Matcher<To>& matcher) : WhenDynamicCastToMatcherBase<To>(matcher) {} template <typename From> bool MatchAndExplain(From from, MatchResultListener* listener) const { // TODO(sbenza): Add more detail on failures. ie did the dyn_cast fail? To to = dynamic_cast<To>(from); return MatchPrintAndExplain(to, this->matcher_, listener); } }; // Specialize for references. // In this case we return false if the dynamic_cast fails. template <typename To> class WhenDynamicCastToMatcher<To&> : public WhenDynamicCastToMatcherBase<To&> { public: explicit WhenDynamicCastToMatcher(const Matcher<To&>& matcher) : WhenDynamicCastToMatcherBase<To&>(matcher) {} template <typename From> bool MatchAndExplain(From& from, MatchResultListener* listener) const { // We don't want an std::bad_cast here, so do the cast with pointers. To* to = dynamic_cast<To*>(&from); if (to == NULL) { *listener << "which cannot be dynamic_cast to " << this->GetToName(); return false; } return MatchPrintAndExplain(*to, this->matcher_, listener); } }; // Implements the Field() matcher for matching a field (i.e. member // variable) of an object. template <typename Class, typename FieldType> class FieldMatcher { public: FieldMatcher(FieldType Class::*field, const Matcher<const FieldType&>& matcher) : field_(field), matcher_(matcher) {} void DescribeTo(::std::ostream* os) const { *os << "is an object whose given field "; matcher_.DescribeTo(os); } void DescribeNegationTo(::std::ostream* os) const { *os << "is an object whose given field "; matcher_.DescribeNegationTo(os); } template <typename T> bool MatchAndExplain(const T& value, MatchResultListener* listener) const { return MatchAndExplainImpl( typename ::testing::internal:: is_pointer<GTEST_REMOVE_CONST_(T)>::type(), value, listener); } private: // The first argument of MatchAndExplainImpl() is needed to help // Symbian's C++ compiler choose which overload to use. Its type is // true_type iff the Field() matcher is used to match a pointer. bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj, MatchResultListener* listener) const { *listener << "whose given field is "; return MatchPrintAndExplain(obj.*field_, matcher_, listener); } bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p, MatchResultListener* listener) const { if (p == NULL) return false; *listener << "which points to an object "; // Since *p has a field, it must be a class/struct/union type and // thus cannot be a pointer. Therefore we pass false_type() as // the first argument. return MatchAndExplainImpl(false_type(), *p, listener); } const FieldType Class::*field_; const Matcher<const FieldType&> matcher_; GTEST_DISALLOW_ASSIGN_(FieldMatcher); }; // Implements the Property() matcher for matching a property // (i.e. return value of a getter method) of an object. template <typename Class, typename PropertyType> class PropertyMatcher { public: // The property may have a reference type, so 'const PropertyType&' // may cause double references and fail to compile. That's why we // need GTEST_REFERENCE_TO_CONST, which works regardless of // PropertyType being a reference or not. typedef GTEST_REFERENCE_TO_CONST_(PropertyType) RefToConstProperty; PropertyMatcher(PropertyType (Class::*property)() const, const Matcher<RefToConstProperty>& matcher) : property_(property), matcher_(matcher) {} void DescribeTo(::std::ostream* os) const { *os << "is an object whose given property "; matcher_.DescribeTo(os); } void DescribeNegationTo(::std::ostream* os) const { *os << "is an object whose given property "; matcher_.DescribeNegationTo(os); } template <typename T> bool MatchAndExplain(const T&value, MatchResultListener* listener) const { return MatchAndExplainImpl( typename ::testing::internal:: is_pointer<GTEST_REMOVE_CONST_(T)>::type(), value, listener); } private: // The first argument of MatchAndExplainImpl() is needed to help // Symbian's C++ compiler choose which overload to use. Its type is // true_type iff the Property() matcher is used to match a pointer. bool MatchAndExplainImpl(false_type /* is_not_pointer */, const Class& obj, MatchResultListener* listener) const { *listener << "whose given property is "; // Cannot pass the return value (for example, int) to MatchPrintAndExplain, // which takes a non-const reference as argument. #if defined(_PREFAST_ ) && _MSC_VER == 1800 // Workaround bug in VC++ 2013's /analyze parser. // https://connect.microsoft.com/VisualStudio/feedback/details/1106363/internal-compiler-error-with-analyze-due-to-failure-to-infer-move posix::Abort(); // To make sure it is never run. return false; #else RefToConstProperty result = (obj.*property_)(); return MatchPrintAndExplain(result, matcher_, listener); #endif } bool MatchAndExplainImpl(true_type /* is_pointer */, const Class* p, MatchResultListener* listener) const { if (p == NULL) return false; *listener << "which points to an object "; // Since *p has a property method, it must be a class/struct/union // type and thus cannot be a pointer. Therefore we pass // false_type() as the first argument. return MatchAndExplainImpl(false_type(), *p, listener); } PropertyType (Class::*property_)() const; const Matcher<RefToConstProperty> matcher_; GTEST_DISALLOW_ASSIGN_(PropertyMatcher); }; // Type traits specifying various features of different functors for ResultOf. // The default template specifies features for functor objects. // Functor classes have to typedef argument_type and result_type // to be compatible with ResultOf. template <typename Functor> struct CallableTraits { typedef typename Functor::result_type ResultType; typedef Functor StorageType; static void CheckIsValid(Functor /* functor */) {} template <typename T> static ResultType Invoke(Functor f, T arg) { return f(arg); } }; // Specialization for function pointers. template <typename ArgType, typename ResType> struct CallableTraits<ResType(*)(ArgType)> { typedef ResType ResultType; typedef ResType(*StorageType)(ArgType); static void CheckIsValid(ResType(*f)(ArgType)) { GTEST_CHECK_(f != NULL) << "NULL function pointer is passed into ResultOf()."; } template <typename T> static ResType Invoke(ResType(*f)(ArgType), T arg) { return (*f)(arg); } }; // Implements the ResultOf() matcher for matching a return value of a // unary function of an object. template <typename Callable> class ResultOfMatcher { public: typedef typename CallableTraits<Callable>::ResultType ResultType; ResultOfMatcher(Callable callable, const Matcher<ResultType>& matcher) : callable_(callable), matcher_(matcher) { CallableTraits<Callable>::CheckIsValid(callable_); } template <typename T> operator Matcher<T>() const { return Matcher<T>(new Impl<T>(callable_, matcher_)); } private: typedef typename CallableTraits<Callable>::StorageType CallableStorageType; template <typename T> class Impl : public MatcherInterface<T> { public: Impl(CallableStorageType callable, const Matcher<ResultType>& matcher) : callable_(callable), matcher_(matcher) {} virtual void DescribeTo(::std::ostream* os) const { *os << "is mapped by the given callable to a value that "; matcher_.DescribeTo(os); } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "is mapped by the given callable to a value that "; matcher_.DescribeNegationTo(os); } virtual bool MatchAndExplain(T obj, MatchResultListener* listener) const { *listener << "which is mapped by the given callable to "; // Cannot pass the return value (for example, int) to // MatchPrintAndExplain, which takes a non-const reference as argument. ResultType result = CallableTraits<Callable>::template Invoke<T>(callable_, obj); return MatchPrintAndExplain(result, matcher_, listener); } private: // Functors often define operator() as non-const method even though // they are actualy stateless. But we need to use them even when // 'this' is a const pointer. It's the user's responsibility not to // use stateful callables with ResultOf(), which does't guarantee // how many times the callable will be invoked. mutable CallableStorageType callable_; const Matcher<ResultType> matcher_; GTEST_DISALLOW_ASSIGN_(Impl); }; // class Impl const CallableStorageType callable_; const Matcher<ResultType> matcher_; GTEST_DISALLOW_ASSIGN_(ResultOfMatcher); }; // Implements a matcher that checks the size of an STL-style container. template <typename SizeMatcher> class SizeIsMatcher { public: explicit SizeIsMatcher(const SizeMatcher& size_matcher) : size_matcher_(size_matcher) { } template <typename Container> operator Matcher<Container>() const { return MakeMatcher(new Impl<Container>(size_matcher_)); } template <typename Container> class Impl : public MatcherInterface<Container> { public: typedef internal::StlContainerView< GTEST_REMOVE_REFERENCE_AND_CONST_(Container)> ContainerView; typedef typename ContainerView::type::size_type SizeType; explicit Impl(const SizeMatcher& size_matcher) : size_matcher_(MatcherCast<SizeType>(size_matcher)) {} virtual void DescribeTo(::std::ostream* os) const { *os << "size "; size_matcher_.DescribeTo(os); } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "size "; size_matcher_.DescribeNegationTo(os); } virtual bool MatchAndExplain(Container container, MatchResultListener* listener) const { SizeType size = container.size(); StringMatchResultListener size_listener; const bool result = size_matcher_.MatchAndExplain(size, &size_listener); *listener << "whose size " << size << (result ? " matches" : " doesn't match"); PrintIfNotEmpty(size_listener.str(), listener->stream()); return result; } private: const Matcher<SizeType> size_matcher_; GTEST_DISALLOW_ASSIGN_(Impl); }; private: const SizeMatcher size_matcher_; GTEST_DISALLOW_ASSIGN_(SizeIsMatcher); }; // Implements a matcher that checks the begin()..end() distance of an STL-style // container. template <typename DistanceMatcher> class BeginEndDistanceIsMatcher { public: explicit BeginEndDistanceIsMatcher(const DistanceMatcher& distance_matcher) : distance_matcher_(distance_matcher) {} template <typename Container> operator Matcher<Container>() const { return MakeMatcher(new Impl<Container>(distance_matcher_)); } template <typename Container> class Impl : public MatcherInterface<Container> { public: typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef internal::StlContainerView<RawContainer> View; typedef typename View::type StlContainer; typedef typename View::const_reference StlContainerReference; typedef decltype(std::begin( std::declval<StlContainerReference>())) StlContainerConstIterator; typedef typename std::iterator_traits< StlContainerConstIterator>::difference_type DistanceType; explicit Impl(const DistanceMatcher& distance_matcher) : distance_matcher_(MatcherCast<DistanceType>(distance_matcher)) {} virtual void DescribeTo(::std::ostream* os) const { *os << "distance between begin() and end() "; distance_matcher_.DescribeTo(os); } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "distance between begin() and end() "; distance_matcher_.DescribeNegationTo(os); } virtual bool MatchAndExplain(Container container, MatchResultListener* listener) const { #if GTEST_HAS_STD_BEGIN_AND_END_ using std::begin; using std::end; DistanceType distance = std::distance(begin(container), end(container)); #else DistanceType distance = std::distance(container.begin(), container.end()); #endif StringMatchResultListener distance_listener; const bool result = distance_matcher_.MatchAndExplain(distance, &distance_listener); *listener << "whose distance between begin() and end() " << distance << (result ? " matches" : " doesn't match"); PrintIfNotEmpty(distance_listener.str(), listener->stream()); return result; } private: const Matcher<DistanceType> distance_matcher_; GTEST_DISALLOW_ASSIGN_(Impl); }; private: const DistanceMatcher distance_matcher_; GTEST_DISALLOW_ASSIGN_(BeginEndDistanceIsMatcher); }; // Implements an equality matcher for any STL-style container whose elements // support ==. This matcher is like Eq(), but its failure explanations provide // more detailed information that is useful when the container is used as a set. // The failure message reports elements that are in one of the operands but not // the other. The failure messages do not report duplicate or out-of-order // elements in the containers (which don't properly matter to sets, but can // occur if the containers are vectors or lists, for example). // // Uses the container's const_iterator, value_type, operator ==, // begin(), and end(). template <typename Container> class ContainerEqMatcher { public: typedef internal::StlContainerView<Container> View; typedef typename View::type StlContainer; typedef typename View::const_reference StlContainerReference; // We make a copy of expected in case the elements in it are modified // after this matcher is created. explicit ContainerEqMatcher(const Container& expected) : expected_(View::Copy(expected)) { // Makes sure the user doesn't instantiate this class template // with a const or reference type. (void)testing::StaticAssertTypeEq<Container, GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>(); } void DescribeTo(::std::ostream* os) const { *os << "equals "; UniversalPrint(expected_, os); } void DescribeNegationTo(::std::ostream* os) const { *os << "does not equal "; UniversalPrint(expected_, os); } template <typename LhsContainer> bool MatchAndExplain(const LhsContainer& lhs, MatchResultListener* listener) const { // GTEST_REMOVE_CONST_() is needed to work around an MSVC 8.0 bug // that causes LhsContainer to be a const type sometimes. typedef internal::StlContainerView<GTEST_REMOVE_CONST_(LhsContainer)> LhsView; typedef typename LhsView::type LhsStlContainer; StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs); if (lhs_stl_container == expected_) return true; ::std::ostream* const os = listener->stream(); if (os != NULL) { // Something is different. Check for extra values first. bool printed_header = false; for (typename LhsStlContainer::const_iterator it = lhs_stl_container.begin(); it != lhs_stl_container.end(); ++it) { if (internal::ArrayAwareFind(expected_.begin(), expected_.end(), *it) == expected_.end()) { if (printed_header) { *os << ", "; } else { *os << "which has these unexpected elements: "; printed_header = true; } UniversalPrint(*it, os); } } // Now check for missing values. bool printed_header2 = false; for (typename StlContainer::const_iterator it = expected_.begin(); it != expected_.end(); ++it) { if (internal::ArrayAwareFind( lhs_stl_container.begin(), lhs_stl_container.end(), *it) == lhs_stl_container.end()) { if (printed_header2) { *os << ", "; } else { *os << (printed_header ? ",\nand" : "which") << " doesn't have these expected elements: "; printed_header2 = true; } UniversalPrint(*it, os); } } } return false; } private: const StlContainer expected_; GTEST_DISALLOW_ASSIGN_(ContainerEqMatcher); }; // A comparator functor that uses the < operator to compare two values. struct LessComparator { template <typename T, typename U> bool operator()(const T& lhs, const U& rhs) const { return lhs < rhs; } }; // Implements WhenSortedBy(comparator, container_matcher). template <typename Comparator, typename ContainerMatcher> class WhenSortedByMatcher { public: WhenSortedByMatcher(const Comparator& comparator, const ContainerMatcher& matcher) : comparator_(comparator), matcher_(matcher) {} template <typename LhsContainer> operator Matcher<LhsContainer>() const { return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_)); } template <typename LhsContainer> class Impl : public MatcherInterface<LhsContainer> { public: typedef internal::StlContainerView< GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView; typedef typename LhsView::type LhsStlContainer; typedef typename LhsView::const_reference LhsStlContainerReference; // Transforms std::pair<const Key, Value> into std::pair<Key, Value> // so that we can match associative containers. typedef typename RemoveConstFromKey< typename LhsStlContainer::value_type>::type LhsValue; Impl(const Comparator& comparator, const ContainerMatcher& matcher) : comparator_(comparator), matcher_(matcher) {} virtual void DescribeTo(::std::ostream* os) const { *os << "(when sorted) "; matcher_.DescribeTo(os); } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "(when sorted) "; matcher_.DescribeNegationTo(os); } virtual bool MatchAndExplain(LhsContainer lhs, MatchResultListener* listener) const { LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs); ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(), lhs_stl_container.end()); ::std::sort( sorted_container.begin(), sorted_container.end(), comparator_); if (!listener->IsInterested()) { // If the listener is not interested, we do not need to // construct the inner explanation. return matcher_.Matches(sorted_container); } *listener << "which is "; UniversalPrint(sorted_container, listener->stream()); *listener << " when sorted"; StringMatchResultListener inner_listener; const bool match = matcher_.MatchAndExplain(sorted_container, &inner_listener); PrintIfNotEmpty(inner_listener.str(), listener->stream()); return match; } private: const Comparator comparator_; const Matcher<const ::std::vector<LhsValue>&> matcher_; GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl); }; private: const Comparator comparator_; const ContainerMatcher matcher_; GTEST_DISALLOW_ASSIGN_(WhenSortedByMatcher); }; // Implements Pointwise(tuple_matcher, rhs_container). tuple_matcher // must be able to be safely cast to Matcher<tuple<const T1&, const // T2&> >, where T1 and T2 are the types of elements in the LHS // container and the RHS container respectively. template <typename TupleMatcher, typename RhsContainer> class PointwiseMatcher { public: typedef internal::StlContainerView<RhsContainer> RhsView; typedef typename RhsView::type RhsStlContainer; typedef typename RhsStlContainer::value_type RhsValue; // Like ContainerEq, we make a copy of rhs in case the elements in // it are modified after this matcher is created. PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs) : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) { // Makes sure the user doesn't instantiate this class template // with a const or reference type. (void)testing::StaticAssertTypeEq<RhsContainer, GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>(); } template <typename LhsContainer> operator Matcher<LhsContainer>() const { return MakeMatcher(new Impl<LhsContainer>(tuple_matcher_, rhs_)); } template <typename LhsContainer> class Impl : public MatcherInterface<LhsContainer> { public: typedef internal::StlContainerView< GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)> LhsView; typedef typename LhsView::type LhsStlContainer; typedef typename LhsView::const_reference LhsStlContainerReference; typedef typename LhsStlContainer::value_type LhsValue; // We pass the LHS value and the RHS value to the inner matcher by // reference, as they may be expensive to copy. We must use tuple // instead of pair here, as a pair cannot hold references (C++ 98, // 20.2.2 [lib.pairs]). typedef ::testing::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg; Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs) // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher. : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)), rhs_(rhs) {} virtual void DescribeTo(::std::ostream* os) const { *os << "contains " << rhs_.size() << " values, where each value and its corresponding value in "; UniversalPrinter<RhsStlContainer>::Print(rhs_, os); *os << " "; mono_tuple_matcher_.DescribeTo(os); } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "doesn't contain exactly " << rhs_.size() << " values, or contains a value x at some index i" << " where x and the i-th value of "; UniversalPrint(rhs_, os); *os << " "; mono_tuple_matcher_.DescribeNegationTo(os); } virtual bool MatchAndExplain(LhsContainer lhs, MatchResultListener* listener) const { LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs); const size_t actual_size = lhs_stl_container.size(); if (actual_size != rhs_.size()) { *listener << "which contains " << actual_size << " values"; return false; } typename LhsStlContainer::const_iterator left = lhs_stl_container.begin(); typename RhsStlContainer::const_iterator right = rhs_.begin(); for (size_t i = 0; i != actual_size; ++i, ++left, ++right) { const InnerMatcherArg value_pair(*left, *right); if (listener->IsInterested()) { StringMatchResultListener inner_listener; if (!mono_tuple_matcher_.MatchAndExplain( value_pair, &inner_listener)) { *listener << "where the value pair ("; UniversalPrint(*left, listener->stream()); *listener << ", "; UniversalPrint(*right, listener->stream()); *listener << ") at index #" << i << " don't match"; PrintIfNotEmpty(inner_listener.str(), listener->stream()); return false; } } else { if (!mono_tuple_matcher_.Matches(value_pair)) return false; } } return true; } private: const Matcher<InnerMatcherArg> mono_tuple_matcher_; const RhsStlContainer rhs_; GTEST_DISALLOW_ASSIGN_(Impl); }; private: const TupleMatcher tuple_matcher_; const RhsStlContainer rhs_; GTEST_DISALLOW_ASSIGN_(PointwiseMatcher); }; // Holds the logic common to ContainsMatcherImpl and EachMatcherImpl. template <typename Container> class QuantifierMatcherImpl : public MatcherInterface<Container> { public: typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef StlContainerView<RawContainer> View; typedef typename View::type StlContainer; typedef typename View::const_reference StlContainerReference; typedef typename StlContainer::value_type Element; template <typename InnerMatcher> explicit QuantifierMatcherImpl(InnerMatcher inner_matcher) : inner_matcher_( testing::SafeMatcherCast<const Element&>(inner_matcher)) {} // Checks whether: // * All elements in the container match, if all_elements_should_match. // * Any element in the container matches, if !all_elements_should_match. bool MatchAndExplainImpl(bool all_elements_should_match, Container container, MatchResultListener* listener) const { StlContainerReference stl_container = View::ConstReference(container); size_t i = 0; for (typename StlContainer::const_iterator it = stl_container.begin(); it != stl_container.end(); ++it, ++i) { StringMatchResultListener inner_listener; const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener); if (matches != all_elements_should_match) { *listener << "whose element #" << i << (matches ? " matches" : " doesn't match"); PrintIfNotEmpty(inner_listener.str(), listener->stream()); return !all_elements_should_match; } } return all_elements_should_match; } protected: const Matcher<const Element&> inner_matcher_; GTEST_DISALLOW_ASSIGN_(QuantifierMatcherImpl); }; // Implements Contains(element_matcher) for the given argument type Container. // Symmetric to EachMatcherImpl. template <typename Container> class ContainsMatcherImpl : public QuantifierMatcherImpl<Container> { public: template <typename InnerMatcher> explicit ContainsMatcherImpl(InnerMatcher inner_matcher) : QuantifierMatcherImpl<Container>(inner_matcher) {} // Describes what this matcher does. virtual void DescribeTo(::std::ostream* os) const { *os << "contains at least one element that "; this->inner_matcher_.DescribeTo(os); } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "doesn't contain any element that "; this->inner_matcher_.DescribeTo(os); } virtual bool MatchAndExplain(Container container, MatchResultListener* listener) const { return this->MatchAndExplainImpl(false, container, listener); } private: GTEST_DISALLOW_ASSIGN_(ContainsMatcherImpl); }; // Implements Each(element_matcher) for the given argument type Container. // Symmetric to ContainsMatcherImpl. template <typename Container> class EachMatcherImpl : public QuantifierMatcherImpl<Container> { public: template <typename InnerMatcher> explicit EachMatcherImpl(InnerMatcher inner_matcher) : QuantifierMatcherImpl<Container>(inner_matcher) {} // Describes what this matcher does. virtual void DescribeTo(::std::ostream* os) const { *os << "only contains elements that "; this->inner_matcher_.DescribeTo(os); } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "contains some element that "; this->inner_matcher_.DescribeNegationTo(os); } virtual bool MatchAndExplain(Container container, MatchResultListener* listener) const { return this->MatchAndExplainImpl(true, container, listener); } private: GTEST_DISALLOW_ASSIGN_(EachMatcherImpl); }; // Implements polymorphic Contains(element_matcher). template <typename M> class ContainsMatcher { public: explicit ContainsMatcher(M m) : inner_matcher_(m) {} template <typename Container> operator Matcher<Container>() const { return MakeMatcher(new ContainsMatcherImpl<Container>(inner_matcher_)); } private: const M inner_matcher_; GTEST_DISALLOW_ASSIGN_(ContainsMatcher); }; // Implements polymorphic Each(element_matcher). template <typename M> class EachMatcher { public: explicit EachMatcher(M m) : inner_matcher_(m) {} template <typename Container> operator Matcher<Container>() const { return MakeMatcher(new EachMatcherImpl<Container>(inner_matcher_)); } private: const M inner_matcher_; GTEST_DISALLOW_ASSIGN_(EachMatcher); }; // Implements Key(inner_matcher) for the given argument pair type. // Key(inner_matcher) matches an std::pair whose 'first' field matches // inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an // std::map that contains at least one element whose key is >= 5. template <typename PairType> class KeyMatcherImpl : public MatcherInterface<PairType> { public: typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType; typedef typename RawPairType::first_type KeyType; template <typename InnerMatcher> explicit KeyMatcherImpl(InnerMatcher inner_matcher) : inner_matcher_( testing::SafeMatcherCast<const KeyType&>(inner_matcher)) { } // Returns true iff 'key_value.first' (the key) matches the inner matcher. virtual bool MatchAndExplain(PairType key_value, MatchResultListener* listener) const { StringMatchResultListener inner_listener; const bool match = inner_matcher_.MatchAndExplain(key_value.first, &inner_listener); const internal::string explanation = inner_listener.str(); if (explanation != "") { *listener << "whose first field is a value " << explanation; } return match; } // Describes what this matcher does. virtual void DescribeTo(::std::ostream* os) const { *os << "has a key that "; inner_matcher_.DescribeTo(os); } // Describes what the negation of this matcher does. virtual void DescribeNegationTo(::std::ostream* os) const { *os << "doesn't have a key that "; inner_matcher_.DescribeTo(os); } private: const Matcher<const KeyType&> inner_matcher_; GTEST_DISALLOW_ASSIGN_(KeyMatcherImpl); }; // Implements polymorphic Key(matcher_for_key). template <typename M> class KeyMatcher { public: explicit KeyMatcher(M m) : matcher_for_key_(m) {} template <typename PairType> operator Matcher<PairType>() const { return MakeMatcher(new KeyMatcherImpl<PairType>(matcher_for_key_)); } private: const M matcher_for_key_; GTEST_DISALLOW_ASSIGN_(KeyMatcher); }; // Implements Pair(first_matcher, second_matcher) for the given argument pair // type with its two matchers. See Pair() function below. template <typename PairType> class PairMatcherImpl : public MatcherInterface<PairType> { public: typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType; typedef typename RawPairType::first_type FirstType; typedef typename RawPairType::second_type SecondType; template <typename FirstMatcher, typename SecondMatcher> PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher) : first_matcher_( testing::SafeMatcherCast<const FirstType&>(first_matcher)), second_matcher_( testing::SafeMatcherCast<const SecondType&>(second_matcher)) { } // Describes what this matcher does. virtual void DescribeTo(::std::ostream* os) const { *os << "has a first field that "; first_matcher_.DescribeTo(os); *os << ", and has a second field that "; second_matcher_.DescribeTo(os); } // Describes what the negation of this matcher does. virtual void DescribeNegationTo(::std::ostream* os) const { *os << "has a first field that "; first_matcher_.DescribeNegationTo(os); *os << ", or has a second field that "; second_matcher_.DescribeNegationTo(os); } // Returns true iff 'a_pair.first' matches first_matcher and 'a_pair.second' // matches second_matcher. virtual bool MatchAndExplain(PairType a_pair, MatchResultListener* listener) const { if (!listener->IsInterested()) { // If the listener is not interested, we don't need to construct the // explanation. return first_matcher_.Matches(a_pair.first) && second_matcher_.Matches(a_pair.second); } StringMatchResultListener first_inner_listener; if (!first_matcher_.MatchAndExplain(a_pair.first, &first_inner_listener)) { *listener << "whose first field does not match"; PrintIfNotEmpty(first_inner_listener.str(), listener->stream()); return false; } StringMatchResultListener second_inner_listener; if (!second_matcher_.MatchAndExplain(a_pair.second, &second_inner_listener)) { *listener << "whose second field does not match"; PrintIfNotEmpty(second_inner_listener.str(), listener->stream()); return false; } ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(), listener); return true; } private: void ExplainSuccess(const internal::string& first_explanation, const internal::string& second_explanation, MatchResultListener* listener) const { *listener << "whose both fields match"; if (first_explanation != "") { *listener << ", where the first field is a value " << first_explanation; } if (second_explanation != "") { *listener << ", "; if (first_explanation != "") { *listener << "and "; } else { *listener << "where "; } *listener << "the second field is a value " << second_explanation; } } const Matcher<const FirstType&> first_matcher_; const Matcher<const SecondType&> second_matcher_; GTEST_DISALLOW_ASSIGN_(PairMatcherImpl); }; // Implements polymorphic Pair(first_matcher, second_matcher). template <typename FirstMatcher, typename SecondMatcher> class PairMatcher { public: PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher) : first_matcher_(first_matcher), second_matcher_(second_matcher) {} template <typename PairType> operator Matcher<PairType> () const { return MakeMatcher( new PairMatcherImpl<PairType>( first_matcher_, second_matcher_)); } private: const FirstMatcher first_matcher_; const SecondMatcher second_matcher_; GTEST_DISALLOW_ASSIGN_(PairMatcher); }; // Implements ElementsAre() and ElementsAreArray(). template <typename Container> class ElementsAreMatcherImpl : public MatcherInterface<Container> { public: typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef internal::StlContainerView<RawContainer> View; typedef typename View::type StlContainer; typedef typename View::const_reference StlContainerReference; typedef decltype(std::begin( std::declval<StlContainerReference>())) StlContainerConstIterator; typedef typename std::remove_reference<decltype( *std::declval<StlContainerConstIterator &>())>::type Element; // Constructs the matcher from a sequence of element values or // element matchers. template <typename InputIter> ElementsAreMatcherImpl(InputIter first, InputIter last) { while (first != last) { matchers_.push_back(MatcherCast<const Element&>(*first++)); } } // Describes what this matcher does. virtual void DescribeTo(::std::ostream* os) const { if (count() == 0) { *os << "is empty"; } else if (count() == 1) { *os << "has 1 element that "; matchers_[0].DescribeTo(os); } else { *os << "has " << Elements(count()) << " where\n"; for (size_t i = 0; i != count(); ++i) { *os << "element #" << i << " "; matchers_[i].DescribeTo(os); if (i + 1 < count()) { *os << ",\n"; } } } } // Describes what the negation of this matcher does. virtual void DescribeNegationTo(::std::ostream* os) const { if (count() == 0) { *os << "isn't empty"; return; } *os << "doesn't have " << Elements(count()) << ", or\n"; for (size_t i = 0; i != count(); ++i) { *os << "element #" << i << " "; matchers_[i].DescribeNegationTo(os); if (i + 1 < count()) { *os << ", or\n"; } } } virtual bool MatchAndExplain(Container container, MatchResultListener* listener) const { // To work with stream-like "containers", we must only walk // through the elements in one pass. const bool listener_interested = listener->IsInterested(); // explanations[i] is the explanation of the element at index i. ::std::vector<internal::string> explanations(count()); StlContainerReference stl_container = View::ConstReference(container); StlContainerConstIterator it = stl_container.begin(); size_t exam_pos = 0; bool mismatch_found = false; // Have we found a mismatched element yet? // Go through the elements and matchers in pairs, until we reach // the end of either the elements or the matchers, or until we find a // mismatch. for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) { bool match; // Does the current element match the current matcher? if (listener_interested) { StringMatchResultListener s; match = matchers_[exam_pos].MatchAndExplain(*it, &s); explanations[exam_pos] = s.str(); } else { match = matchers_[exam_pos].Matches(*it); } if (!match) { mismatch_found = true; break; } } // If mismatch_found is true, 'exam_pos' is the index of the mismatch. // Find how many elements the actual container has. We avoid // calling size() s.t. this code works for stream-like "containers" // that don't define size(). size_t actual_count = exam_pos; for (; it != stl_container.end(); ++it) { ++actual_count; } if (actual_count != count()) { // The element count doesn't match. If the container is empty, // there's no need to explain anything as Google Mock already // prints the empty container. Otherwise we just need to show // how many elements there actually are. if (listener_interested && (actual_count != 0)) { *listener << "which has " << Elements(actual_count); } return false; } if (mismatch_found) { // The element count matches, but the exam_pos-th element doesn't match. if (listener_interested) { *listener << "whose element #" << exam_pos << " doesn't match"; PrintIfNotEmpty(explanations[exam_pos], listener->stream()); } return false; } // Every element matches its expectation. We need to explain why // (the obvious ones can be skipped). if (listener_interested) { bool reason_printed = false; for (size_t i = 0; i != count(); ++i) { const internal::string& s = explanations[i]; if (!s.empty()) { if (reason_printed) { *listener << ",\nand "; } *listener << "whose element #" << i << " matches, " << s; reason_printed = true; } } } return true; } private: static Message Elements(size_t count) { return Message() << count << (count == 1 ? " element" : " elements"); } size_t count() const { return matchers_.size(); } ::std::vector<Matcher<const Element&> > matchers_; GTEST_DISALLOW_ASSIGN_(ElementsAreMatcherImpl); }; // Connectivity matrix of (elements X matchers), in element-major order. // Initially, there are no edges. // Use NextGraph() to iterate over all possible edge configurations. // Use Randomize() to generate a random edge configuration. class GTEST_API_ MatchMatrix { public: MatchMatrix(size_t num_elements, size_t num_matchers) : num_elements_(num_elements), num_matchers_(num_matchers), matched_(num_elements_* num_matchers_, 0) { } size_t LhsSize() const { return num_elements_; } size_t RhsSize() const { return num_matchers_; } bool HasEdge(size_t ilhs, size_t irhs) const { return matched_[SpaceIndex(ilhs, irhs)] == 1; } void SetEdge(size_t ilhs, size_t irhs, bool b) { matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0; } // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number, // adds 1 to that number; returns false if incrementing the graph left it // empty. bool NextGraph(); void Randomize(); string DebugString() const; private: size_t SpaceIndex(size_t ilhs, size_t irhs) const { return ilhs * num_matchers_ + irhs; } size_t num_elements_; size_t num_matchers_; // Each element is a char interpreted as bool. They are stored as a // flattened array in lhs-major order, use 'SpaceIndex()' to translate // a (ilhs, irhs) matrix coordinate into an offset. ::std::vector<char> matched_; }; typedef ::std::pair<size_t, size_t> ElementMatcherPair; typedef ::std::vector<ElementMatcherPair> ElementMatcherPairs; // Returns a maximum bipartite matching for the specified graph 'g'. // The matching is represented as a vector of {element, matcher} pairs. GTEST_API_ ElementMatcherPairs FindMaxBipartiteMatching(const MatchMatrix& g); GTEST_API_ bool FindPairing(const MatchMatrix& matrix, MatchResultListener* listener); // Untyped base class for implementing UnorderedElementsAre. By // putting logic that's not specific to the element type here, we // reduce binary bloat and increase compilation speed. class GTEST_API_ UnorderedElementsAreMatcherImplBase { protected: // A vector of matcher describers, one for each element matcher. // Does not own the describers (and thus can be used only when the // element matchers are alive). typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec; // Describes this UnorderedElementsAre matcher. void DescribeToImpl(::std::ostream* os) const; // Describes the negation of this UnorderedElementsAre matcher. void DescribeNegationToImpl(::std::ostream* os) const; bool VerifyAllElementsAndMatchersAreMatched( const ::std::vector<string>& element_printouts, const MatchMatrix& matrix, MatchResultListener* listener) const; MatcherDescriberVec& matcher_describers() { return matcher_describers_; } static Message Elements(size_t n) { return Message() << n << " element" << (n == 1 ? "" : "s"); } private: MatcherDescriberVec matcher_describers_; GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImplBase); }; // Implements unordered ElementsAre and unordered ElementsAreArray. template <typename Container> class UnorderedElementsAreMatcherImpl : public MatcherInterface<Container>, public UnorderedElementsAreMatcherImplBase { public: typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef internal::StlContainerView<RawContainer> View; typedef typename View::type StlContainer; typedef typename View::const_reference StlContainerReference; typedef decltype(std::begin( std::declval<StlContainerReference>())) StlContainerConstIterator; typedef typename std::remove_reference<decltype( *std::declval<StlContainerConstIterator &>())>::type Element; // Constructs the matcher from a sequence of element values or // element matchers. template <typename InputIter> UnorderedElementsAreMatcherImpl(InputIter first, InputIter last) { for (; first != last; ++first) { matchers_.push_back(MatcherCast<const Element&>(*first)); matcher_describers().push_back(matchers_.back().GetDescriber()); } } // Describes what this matcher does. virtual void DescribeTo(::std::ostream* os) const { return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os); } // Describes what the negation of this matcher does. virtual void DescribeNegationTo(::std::ostream* os) const { return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os); } virtual bool MatchAndExplain(Container container, MatchResultListener* listener) const { StlContainerReference stl_container = View::ConstReference(container); ::std::vector<string> element_printouts; MatchMatrix matrix = AnalyzeElements(stl_container.begin(), stl_container.end(), &element_printouts, listener); const size_t actual_count = matrix.LhsSize(); if (actual_count == 0 && matchers_.empty()) { return true; } if (actual_count != matchers_.size()) { // The element count doesn't match. If the container is empty, // there's no need to explain anything as Google Mock already // prints the empty container. Otherwise we just need to show // how many elements there actually are. if (actual_count != 0 && listener->IsInterested()) { *listener << "which has " << Elements(actual_count); } return false; } return VerifyAllElementsAndMatchersAreMatched(element_printouts, matrix, listener) && FindPairing(matrix, listener); } private: typedef ::std::vector<Matcher<const Element&> > MatcherVec; template <typename ElementIter> MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last, ::std::vector<string>* element_printouts, MatchResultListener* listener) const { element_printouts->clear(); ::std::vector<char> did_match; size_t num_elements = 0; for (; elem_first != elem_last; ++num_elements, ++elem_first) { if (listener->IsInterested()) { element_printouts->push_back(PrintToString(*elem_first)); } for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) { did_match.push_back(Matches(matchers_[irhs])(*elem_first)); } } MatchMatrix matrix(num_elements, matchers_.size()); ::std::vector<char>::const_iterator did_match_iter = did_match.begin(); for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) { for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) { matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0); } } return matrix; } MatcherVec matchers_; GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcherImpl); }; // Functor for use in TransformTuple. // Performs MatcherCast<Target> on an input argument of any type. template <typename Target> struct CastAndAppendTransform { template <typename Arg> Matcher<Target> operator()(const Arg& a) const { return MatcherCast<Target>(a); } }; // Implements UnorderedElementsAre. template <typename MatcherTuple> class UnorderedElementsAreMatcher { public: explicit UnorderedElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {} template <typename Container> operator Matcher<Container>() const { typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef internal::StlContainerView<RawContainer> View; typedef typename View::const_reference StlContainerReference; typedef decltype(std::begin( std::declval<StlContainerReference>())) StlContainerConstIterator; typedef typename std::remove_reference<decltype( *std::declval<StlContainerConstIterator &>())>::type Element; typedef ::std::vector<Matcher<const Element&> > MatcherVec; MatcherVec matchers; matchers.reserve(::testing::tuple_size<MatcherTuple>::value); TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_, ::std::back_inserter(matchers)); return MakeMatcher(new UnorderedElementsAreMatcherImpl<Container>( matchers.begin(), matchers.end())); } private: const MatcherTuple matchers_; GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreMatcher); }; // Implements ElementsAre. template <typename MatcherTuple> class ElementsAreMatcher { public: explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {} template <typename Container> operator Matcher<Container>() const { typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer; typedef internal::StlContainerView<RawContainer> View; typedef typename View::const_reference StlContainerReference; typedef decltype(std::begin( std::declval<StlContainerReference>())) StlContainerConstIterator; typedef typename std::remove_reference<decltype( *std::declval<StlContainerConstIterator &>())>::type Element; typedef ::std::vector<Matcher<const Element&> > MatcherVec; MatcherVec matchers; matchers.reserve(::testing::tuple_size<MatcherTuple>::value); TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_, ::std::back_inserter(matchers)); return MakeMatcher(new ElementsAreMatcherImpl<Container>( matchers.begin(), matchers.end())); } private: const MatcherTuple matchers_; GTEST_DISALLOW_ASSIGN_(ElementsAreMatcher); }; // Implements UnorderedElementsAreArray(). template <typename T> class UnorderedElementsAreArrayMatcher { public: UnorderedElementsAreArrayMatcher() {} template <typename Iter> UnorderedElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {} template <typename Container> operator Matcher<Container>() const { return MakeMatcher( new UnorderedElementsAreMatcherImpl<Container>(matchers_.begin(), matchers_.end())); } private: ::std::vector<T> matchers_; GTEST_DISALLOW_ASSIGN_(UnorderedElementsAreArrayMatcher); }; // Implements ElementsAreArray(). template <typename T> class ElementsAreArrayMatcher { public: template <typename Iter> ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {} template <typename Container> operator Matcher<Container>() const { return MakeMatcher(new ElementsAreMatcherImpl<Container>( matchers_.begin(), matchers_.end())); } private: const ::std::vector<T> matchers_; GTEST_DISALLOW_ASSIGN_(ElementsAreArrayMatcher); }; // Given a 2-tuple matcher tm of type Tuple2Matcher and a value second // of type Second, BoundSecondMatcher<Tuple2Matcher, Second>(tm, // second) is a polymorphic matcher that matches a value x iff tm // matches tuple (x, second). Useful for implementing // UnorderedPointwise() in terms of UnorderedElementsAreArray(). // // BoundSecondMatcher is copyable and assignable, as we need to put // instances of this class in a vector when implementing // UnorderedPointwise(). template <typename Tuple2Matcher, typename Second> class BoundSecondMatcher { public: BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second) : tuple2_matcher_(tm), second_value_(second) {} template <typename T> operator Matcher<T>() const { return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_)); } // We have to define this for UnorderedPointwise() to compile in // C++98 mode, as it puts BoundSecondMatcher instances in a vector, // which requires the elements to be assignable in C++98. The // compiler cannot generate the operator= for us, as Tuple2Matcher // and Second may not be assignable. // // However, this should never be called, so the implementation just // need to assert. void operator=(const BoundSecondMatcher& /*rhs*/) { GTEST_LOG_(FATAL) << "BoundSecondMatcher should never be assigned."; } private: template <typename T> class Impl : public MatcherInterface<T> { public: typedef ::testing::tuple<T, Second> ArgTuple; Impl(const Tuple2Matcher& tm, const Second& second) : mono_tuple2_matcher_(SafeMatcherCast<const ArgTuple&>(tm)), second_value_(second) {} virtual void DescribeTo(::std::ostream* os) const { *os << "and "; UniversalPrint(second_value_, os); *os << " "; mono_tuple2_matcher_.DescribeTo(os); } virtual bool MatchAndExplain(T x, MatchResultListener* listener) const { return mono_tuple2_matcher_.MatchAndExplain(ArgTuple(x, second_value_), listener); } private: const Matcher<const ArgTuple&> mono_tuple2_matcher_; const Second second_value_; GTEST_DISALLOW_ASSIGN_(Impl); }; const Tuple2Matcher tuple2_matcher_; const Second second_value_; }; // Given a 2-tuple matcher tm and a value second, // MatcherBindSecond(tm, second) returns a matcher that matches a // value x iff tm matches tuple (x, second). Useful for implementing // UnorderedPointwise() in terms of UnorderedElementsAreArray(). template <typename Tuple2Matcher, typename Second> BoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond( const Tuple2Matcher& tm, const Second& second) { return BoundSecondMatcher<Tuple2Matcher, Second>(tm, second); } // Returns the description for a matcher defined using the MATCHER*() // macro where the user-supplied description string is "", if // 'negation' is false; otherwise returns the description of the // negation of the matcher. 'param_values' contains a list of strings // that are the print-out of the matcher's parameters. GTEST_API_ string FormatMatcherDescription(bool negation, const char* matcher_name, const Strings& param_values); } // namespace internal // ElementsAreArray(first, last) // ElementsAreArray(pointer, count) // ElementsAreArray(array) // ElementsAreArray(container) // ElementsAreArray({ e1, e2, ..., en }) // // The ElementsAreArray() functions are like ElementsAre(...), except // that they are given a homogeneous sequence rather than taking each // element as a function argument. The sequence can be specified as an // array, a pointer and count, a vector, an initializer list, or an // STL iterator range. In each of these cases, the underlying sequence // can be either a sequence of values or a sequence of matchers. // // All forms of ElementsAreArray() make a copy of the input matcher sequence. template <typename Iter> inline internal::ElementsAreArrayMatcher< typename ::std::iterator_traits<Iter>::value_type> ElementsAreArray(Iter first, Iter last) { typedef typename ::std::iterator_traits<Iter>::value_type T; return internal::ElementsAreArrayMatcher<T>(first, last); } template <typename T> inline internal::ElementsAreArrayMatcher<T> ElementsAreArray( const T* pointer, size_t count) { return ElementsAreArray(pointer, pointer + count); } template <typename T, size_t N> inline internal::ElementsAreArrayMatcher<T> ElementsAreArray( const T (&array)[N]) { return ElementsAreArray(array, N); } template <typename Container> inline internal::ElementsAreArrayMatcher<typename Container::value_type> ElementsAreArray(const Container& container) { return ElementsAreArray(container.begin(), container.end()); } #if GTEST_HAS_STD_INITIALIZER_LIST_ template <typename T> inline internal::ElementsAreArrayMatcher<T> ElementsAreArray(::std::initializer_list<T> xs) { return ElementsAreArray(xs.begin(), xs.end()); } #endif // UnorderedElementsAreArray(first, last) // UnorderedElementsAreArray(pointer, count) // UnorderedElementsAreArray(array) // UnorderedElementsAreArray(container) // UnorderedElementsAreArray({ e1, e2, ..., en }) // // The UnorderedElementsAreArray() functions are like // ElementsAreArray(...), but allow matching the elements in any order. template <typename Iter> inline internal::UnorderedElementsAreArrayMatcher< typename ::std::iterator_traits<Iter>::value_type> UnorderedElementsAreArray(Iter first, Iter last) { typedef typename ::std::iterator_traits<Iter>::value_type T; return internal::UnorderedElementsAreArrayMatcher<T>(first, last); } template <typename T> inline internal::UnorderedElementsAreArrayMatcher<T> UnorderedElementsAreArray(const T* pointer, size_t count) { return UnorderedElementsAreArray(pointer, pointer + count); } template <typename T, size_t N> inline internal::UnorderedElementsAreArrayMatcher<T> UnorderedElementsAreArray(const T (&array)[N]) { return UnorderedElementsAreArray(array, N); } template <typename Container> inline internal::UnorderedElementsAreArrayMatcher< typename Container::value_type> UnorderedElementsAreArray(const Container& container) { return UnorderedElementsAreArray(container.begin(), container.end()); } #if GTEST_HAS_STD_INITIALIZER_LIST_ template <typename T> inline internal::UnorderedElementsAreArrayMatcher<T> UnorderedElementsAreArray(::std::initializer_list<T> xs) { return UnorderedElementsAreArray(xs.begin(), xs.end()); } #endif // _ is a matcher that matches anything of any type. // // This definition is fine as: // // 1. The C++ standard permits using the name _ in a namespace that // is not the global namespace or ::std. // 2. The AnythingMatcher class has no data member or constructor, // so it's OK to create global variables of this type. // 3. c-style has approved of using _ in this case. const internal::AnythingMatcher _ = {}; // Creates a matcher that matches any value of the given type T. template <typename T> inline Matcher<T> A() { return MakeMatcher(new internal::AnyMatcherImpl<T>()); } // Creates a matcher that matches any value of the given type T. template <typename T> inline Matcher<T> An() { return A<T>(); } // Creates a polymorphic matcher that matches anything equal to x. // Note: if the parameter of Eq() were declared as const T&, Eq("foo") // wouldn't compile. template <typename T> inline internal::EqMatcher<T> Eq(T x) { return internal::EqMatcher<T>(x); } // Constructs a Matcher<T> from a 'value' of type T. The constructed // matcher matches any value that's equal to 'value'. template <typename T> Matcher<T>::Matcher(T value) { *this = Eq(value); } // Creates a monomorphic matcher that matches anything with type Lhs // and equal to rhs. A user may need to use this instead of Eq(...) // in order to resolve an overloading ambiguity. // // TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x)) // or Matcher<T>(x), but more readable than the latter. // // We could define similar monomorphic matchers for other comparison // operations (e.g. TypedLt, TypedGe, and etc), but decided not to do // it yet as those are used much less than Eq() in practice. A user // can always write Matcher<T>(Lt(5)) to be explicit about the type, // for example. template <typename Lhs, typename Rhs> inline Matcher<Lhs> TypedEq(const Rhs& rhs) { return Eq(rhs); } // Creates a polymorphic matcher that matches anything >= x. template <typename Rhs> inline internal::GeMatcher<Rhs> Ge(Rhs x) { return internal::GeMatcher<Rhs>(x); } // Creates a polymorphic matcher that matches anything > x. template <typename Rhs> inline internal::GtMatcher<Rhs> Gt(Rhs x) { return internal::GtMatcher<Rhs>(x); } // Creates a polymorphic matcher that matches anything <= x. template <typename Rhs> inline internal::LeMatcher<Rhs> Le(Rhs x) { return internal::LeMatcher<Rhs>(x); } // Creates a polymorphic matcher that matches anything < x. template <typename Rhs> inline internal::LtMatcher<Rhs> Lt(Rhs x) { return internal::LtMatcher<Rhs>(x); } // Creates a polymorphic matcher that matches anything != x. template <typename Rhs> inline internal::NeMatcher<Rhs> Ne(Rhs x) { return internal::NeMatcher<Rhs>(x); } // Creates a polymorphic matcher that matches any NULL pointer. inline PolymorphicMatcher<internal::IsNullMatcher > IsNull() { return MakePolymorphicMatcher(internal::IsNullMatcher()); } // Creates a polymorphic matcher that matches any non-NULL pointer. // This is convenient as Not(NULL) doesn't compile (the compiler // thinks that that expression is comparing a pointer with an integer). inline PolymorphicMatcher<internal::NotNullMatcher > NotNull() { return MakePolymorphicMatcher(internal::NotNullMatcher()); } // Creates a polymorphic matcher that matches any argument that // references variable x. template <typename T> inline internal::RefMatcher<T&> Ref(T& x) { // NOLINT return internal::RefMatcher<T&>(x); } // Creates a matcher that matches any double argument approximately // equal to rhs, where two NANs are considered unequal. inline internal::FloatingEqMatcher<double> DoubleEq(double rhs) { return internal::FloatingEqMatcher<double>(rhs, false); } // Creates a matcher that matches any double argument approximately // equal to rhs, including NaN values when rhs is NaN. inline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) { return internal::FloatingEqMatcher<double>(rhs, true); } // Creates a matcher that matches any double argument approximately equal to // rhs, up to the specified max absolute error bound, where two NANs are // considered unequal. The max absolute error bound must be non-negative. inline internal::FloatingEqMatcher<double> DoubleNear( double rhs, double max_abs_error) { return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error); } // Creates a matcher that matches any double argument approximately equal to // rhs, up to the specified max absolute error bound, including NaN values when // rhs is NaN. The max absolute error bound must be non-negative. inline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear( double rhs, double max_abs_error) { return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error); } // Creates a matcher that matches any float argument approximately // equal to rhs, where two NANs are considered unequal. inline internal::FloatingEqMatcher<float> FloatEq(float rhs) { return internal::FloatingEqMatcher<float>(rhs, false); } // Creates a matcher that matches any float argument approximately // equal to rhs, including NaN values when rhs is NaN. inline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) { return internal::FloatingEqMatcher<float>(rhs, true); } // Creates a matcher that matches any float argument approximately equal to // rhs, up to the specified max absolute error bound, where two NANs are // considered unequal. The max absolute error bound must be non-negative. inline internal::FloatingEqMatcher<float> FloatNear( float rhs, float max_abs_error) { return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error); } // Creates a matcher that matches any float argument approximately equal to // rhs, up to the specified max absolute error bound, including NaN values when // rhs is NaN. The max absolute error bound must be non-negative. inline internal::FloatingEqMatcher<float> NanSensitiveFloatNear( float rhs, float max_abs_error) { return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error); } // Creates a matcher that matches a pointer (raw or smart) that points // to a value that matches inner_matcher. template <typename InnerMatcher> inline internal::PointeeMatcher<InnerMatcher> Pointee( const InnerMatcher& inner_matcher) { return internal::PointeeMatcher<InnerMatcher>(inner_matcher); } // Creates a matcher that matches a pointer or reference that matches // inner_matcher when dynamic_cast<To> is applied. // The result of dynamic_cast<To> is forwarded to the inner matcher. // If To is a pointer and the cast fails, the inner matcher will receive NULL. // If To is a reference and the cast fails, this matcher returns false // immediately. template <typename To> inline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To> > WhenDynamicCastTo(const Matcher<To>& inner_matcher) { return MakePolymorphicMatcher( internal::WhenDynamicCastToMatcher<To>(inner_matcher)); } // Creates a matcher that matches an object whose given field matches // 'matcher'. For example, // Field(&Foo::number, Ge(5)) // matches a Foo object x iff x.number >= 5. template <typename Class, typename FieldType, typename FieldMatcher> inline PolymorphicMatcher< internal::FieldMatcher<Class, FieldType> > Field( FieldType Class::*field, const FieldMatcher& matcher) { return MakePolymorphicMatcher( internal::FieldMatcher<Class, FieldType>( field, MatcherCast<const FieldType&>(matcher))); // The call to MatcherCast() is required for supporting inner // matchers of compatible types. For example, it allows // Field(&Foo::bar, m) // to compile where bar is an int32 and m is a matcher for int64. } // Creates a matcher that matches an object whose given property // matches 'matcher'. For example, // Property(&Foo::str, StartsWith("hi")) // matches a Foo object x iff x.str() starts with "hi". template <typename Class, typename PropertyType, typename PropertyMatcher> inline PolymorphicMatcher< internal::PropertyMatcher<Class, PropertyType> > Property( PropertyType (Class::*property)() const, const PropertyMatcher& matcher) { return MakePolymorphicMatcher( internal::PropertyMatcher<Class, PropertyType>( property, MatcherCast<GTEST_REFERENCE_TO_CONST_(PropertyType)>(matcher))); // The call to MatcherCast() is required for supporting inner // matchers of compatible types. For example, it allows // Property(&Foo::bar, m) // to compile where bar() returns an int32 and m is a matcher for int64. } // Creates a matcher that matches an object iff the result of applying // a callable to x matches 'matcher'. // For example, // ResultOf(f, StartsWith("hi")) // matches a Foo object x iff f(x) starts with "hi". // callable parameter can be a function, function pointer, or a functor. // Callable has to satisfy the following conditions: // * It is required to keep no state affecting the results of // the calls on it and make no assumptions about how many calls // will be made. Any state it keeps must be protected from the // concurrent access. // * If it is a function object, it has to define type result_type. // We recommend deriving your functor classes from std::unary_function. template <typename Callable, typename ResultOfMatcher> internal::ResultOfMatcher<Callable> ResultOf( Callable callable, const ResultOfMatcher& matcher) { return internal::ResultOfMatcher<Callable>( callable, MatcherCast<typename internal::CallableTraits<Callable>::ResultType>( matcher)); // The call to MatcherCast() is required for supporting inner // matchers of compatible types. For example, it allows // ResultOf(Function, m) // to compile where Function() returns an int32 and m is a matcher for int64. } // String matchers. // Matches a string equal to str. inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> > StrEq(const internal::string& str) { return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>( str, true, true)); } // Matches a string not equal to str. inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> > StrNe(const internal::string& str) { return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>( str, false, true)); } // Matches a string equal to str, ignoring case. inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> > StrCaseEq(const internal::string& str) { return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>( str, true, false)); } // Matches a string not equal to str, ignoring case. inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::string> > StrCaseNe(const internal::string& str) { return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::string>( str, false, false)); } // Creates a matcher that matches any string, std::string, or C string // that contains the given substring. inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::string> > HasSubstr(const internal::string& substring) { return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::string>( substring)); } // Matches a string that starts with 'prefix' (case-sensitive). inline PolymorphicMatcher<internal::StartsWithMatcher<internal::string> > StartsWith(const internal::string& prefix) { return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::string>( prefix)); } // Matches a string that ends with 'suffix' (case-sensitive). inline PolymorphicMatcher<internal::EndsWithMatcher<internal::string> > EndsWith(const internal::string& suffix) { return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::string>( suffix)); } // Matches a string that fully matches regular expression 'regex'. // The matcher takes ownership of 'regex'. inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex( const internal::RE* regex) { return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true)); } inline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex( const internal::string& regex) { return MatchesRegex(new internal::RE(regex)); } // Matches a string that contains regular expression 'regex'. // The matcher takes ownership of 'regex'. inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex( const internal::RE* regex) { return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false)); } inline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex( const internal::string& regex) { return ContainsRegex(new internal::RE(regex)); } #if GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING // Wide string matchers. // Matches a string equal to str. inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> > StrEq(const internal::wstring& str) { return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>( str, true, true)); } // Matches a string not equal to str. inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> > StrNe(const internal::wstring& str) { return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>( str, false, true)); } // Matches a string equal to str, ignoring case. inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> > StrCaseEq(const internal::wstring& str) { return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>( str, true, false)); } // Matches a string not equal to str, ignoring case. inline PolymorphicMatcher<internal::StrEqualityMatcher<internal::wstring> > StrCaseNe(const internal::wstring& str) { return MakePolymorphicMatcher(internal::StrEqualityMatcher<internal::wstring>( str, false, false)); } // Creates a matcher that matches any wstring, std::wstring, or C wide string // that contains the given substring. inline PolymorphicMatcher<internal::HasSubstrMatcher<internal::wstring> > HasSubstr(const internal::wstring& substring) { return MakePolymorphicMatcher(internal::HasSubstrMatcher<internal::wstring>( substring)); } // Matches a string that starts with 'prefix' (case-sensitive). inline PolymorphicMatcher<internal::StartsWithMatcher<internal::wstring> > StartsWith(const internal::wstring& prefix) { return MakePolymorphicMatcher(internal::StartsWithMatcher<internal::wstring>( prefix)); } // Matches a string that ends with 'suffix' (case-sensitive). inline PolymorphicMatcher<internal::EndsWithMatcher<internal::wstring> > EndsWith(const internal::wstring& suffix) { return MakePolymorphicMatcher(internal::EndsWithMatcher<internal::wstring>( suffix)); } #endif // GTEST_HAS_GLOBAL_WSTRING || GTEST_HAS_STD_WSTRING // Creates a polymorphic matcher that matches a 2-tuple where the // first field == the second field. inline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); } // Creates a polymorphic matcher that matches a 2-tuple where the // first field >= the second field. inline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); } // Creates a polymorphic matcher that matches a 2-tuple where the // first field > the second field. inline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); } // Creates a polymorphic matcher that matches a 2-tuple where the // first field <= the second field. inline internal::Le2Matcher Le() { return internal::Le2Matcher(); } // Creates a polymorphic matcher that matches a 2-tuple where the // first field < the second field. inline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); } // Creates a polymorphic matcher that matches a 2-tuple where the // first field != the second field. inline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); } // Creates a matcher that matches any value of type T that m doesn't // match. template <typename InnerMatcher> inline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) { return internal::NotMatcher<InnerMatcher>(m); } // Returns a matcher that matches anything that satisfies the given // predicate. The predicate can be any unary function or functor // whose return type can be implicitly converted to bool. template <typename Predicate> inline PolymorphicMatcher<internal::TrulyMatcher<Predicate> > Truly(Predicate pred) { return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred)); } // Returns a matcher that matches the container size. The container must // support both size() and size_type which all STL-like containers provide. // Note that the parameter 'size' can be a value of type size_type as well as // matcher. For instance: // EXPECT_THAT(container, SizeIs(2)); // Checks container has 2 elements. // EXPECT_THAT(container, SizeIs(Le(2)); // Checks container has at most 2. template <typename SizeMatcher> inline internal::SizeIsMatcher<SizeMatcher> SizeIs(const SizeMatcher& size_matcher) { return internal::SizeIsMatcher<SizeMatcher>(size_matcher); } // Returns a matcher that matches the distance between the container's begin() // iterator and its end() iterator, i.e. the size of the container. This matcher // can be used instead of SizeIs with containers such as std::forward_list which // do not implement size(). The container must provide const_iterator (with // valid iterator_traits), begin() and end(). template <typename DistanceMatcher> inline internal::BeginEndDistanceIsMatcher<DistanceMatcher> BeginEndDistanceIs(const DistanceMatcher& distance_matcher) { return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher); } // Returns a matcher that matches an equal container. // This matcher behaves like Eq(), but in the event of mismatch lists the // values that are included in one container but not the other. (Duplicate // values and order differences are not explained.) template <typename Container> inline PolymorphicMatcher<internal::ContainerEqMatcher< // NOLINT GTEST_REMOVE_CONST_(Container)> > ContainerEq(const Container& rhs) { // This following line is for working around a bug in MSVC 8.0, // which causes Container to be a const type sometimes. typedef GTEST_REMOVE_CONST_(Container) RawContainer; return MakePolymorphicMatcher( internal::ContainerEqMatcher<RawContainer>(rhs)); } // Returns a matcher that matches a container that, when sorted using // the given comparator, matches container_matcher. template <typename Comparator, typename ContainerMatcher> inline internal::WhenSortedByMatcher<Comparator, ContainerMatcher> WhenSortedBy(const Comparator& comparator, const ContainerMatcher& container_matcher) { return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>( comparator, container_matcher); } // Returns a matcher that matches a container that, when sorted using // the < operator, matches container_matcher. template <typename ContainerMatcher> inline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher> WhenSorted(const ContainerMatcher& container_matcher) { return internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>( internal::LessComparator(), container_matcher); } // Matches an STL-style container or a native array that contains the // same number of elements as in rhs, where its i-th element and rhs's // i-th element (as a pair) satisfy the given pair matcher, for all i. // TupleMatcher must be able to be safely cast to Matcher<tuple<const // T1&, const T2&> >, where T1 and T2 are the types of elements in the // LHS container and the RHS container respectively. template <typename TupleMatcher, typename Container> inline internal::PointwiseMatcher<TupleMatcher, GTEST_REMOVE_CONST_(Container)> Pointwise(const TupleMatcher& tuple_matcher, const Container& rhs) { // This following line is for working around a bug in MSVC 8.0, // which causes Container to be a const type sometimes (e.g. when // rhs is a const int[]).. typedef GTEST_REMOVE_CONST_(Container) RawContainer; return internal::PointwiseMatcher<TupleMatcher, RawContainer>( tuple_matcher, rhs); } #if GTEST_HAS_STD_INITIALIZER_LIST_ // Supports the Pointwise(m, {a, b, c}) syntax. template <typename TupleMatcher, typename T> inline internal::PointwiseMatcher<TupleMatcher, std::vector<T> > Pointwise( const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) { return Pointwise(tuple_matcher, std::vector<T>(rhs)); } #endif // GTEST_HAS_STD_INITIALIZER_LIST_ // UnorderedPointwise(pair_matcher, rhs) matches an STL-style // container or a native array that contains the same number of // elements as in rhs, where in some permutation of the container, its // i-th element and rhs's i-th element (as a pair) satisfy the given // pair matcher, for all i. Tuple2Matcher must be able to be safely // cast to Matcher<tuple<const T1&, const T2&> >, where T1 and T2 are // the types of elements in the LHS container and the RHS container // respectively. // // This is like Pointwise(pair_matcher, rhs), except that the element // order doesn't matter. template <typename Tuple2Matcher, typename RhsContainer> inline internal::UnorderedElementsAreArrayMatcher< typename internal::BoundSecondMatcher< Tuple2Matcher, typename internal::StlContainerView<GTEST_REMOVE_CONST_( RhsContainer)>::type::value_type> > UnorderedPointwise(const Tuple2Matcher& tuple2_matcher, const RhsContainer& rhs_container) { // This following line is for working around a bug in MSVC 8.0, // which causes RhsContainer to be a const type sometimes (e.g. when // rhs_container is a const int[]). typedef GTEST_REMOVE_CONST_(RhsContainer) RawRhsContainer; // RhsView allows the same code to handle RhsContainer being a // STL-style container and it being a native C-style array. typedef typename internal::StlContainerView<RawRhsContainer> RhsView; typedef typename RhsView::type RhsStlContainer; typedef typename RhsStlContainer::value_type Second; const RhsStlContainer& rhs_stl_container = RhsView::ConstReference(rhs_container); // Create a matcher for each element in rhs_container. ::std::vector<internal::BoundSecondMatcher<Tuple2Matcher, Second> > matchers; for (typename RhsStlContainer::const_iterator it = rhs_stl_container.begin(); it != rhs_stl_container.end(); ++it) { matchers.push_back( internal::MatcherBindSecond(tuple2_matcher, *it)); } // Delegate the work to UnorderedElementsAreArray(). return UnorderedElementsAreArray(matchers); } #if GTEST_HAS_STD_INITIALIZER_LIST_ // Supports the UnorderedPointwise(m, {a, b, c}) syntax. template <typename Tuple2Matcher, typename T> inline internal::UnorderedElementsAreArrayMatcher< typename internal::BoundSecondMatcher<Tuple2Matcher, T> > UnorderedPointwise(const Tuple2Matcher& tuple2_matcher, std::initializer_list<T> rhs) { return UnorderedPointwise(tuple2_matcher, std::vector<T>(rhs)); } #endif // GTEST_HAS_STD_INITIALIZER_LIST_ // Matches an STL-style container or a native array that contains at // least one element matching the given value or matcher. // // Examples: // ::std::set<int> page_ids; // page_ids.insert(3); // page_ids.insert(1); // EXPECT_THAT(page_ids, Contains(1)); // EXPECT_THAT(page_ids, Contains(Gt(2))); // EXPECT_THAT(page_ids, Not(Contains(4))); // // ::std::map<int, size_t> page_lengths; // page_lengths[1] = 100; // EXPECT_THAT(page_lengths, // Contains(::std::pair<const int, size_t>(1, 100))); // // const char* user_ids[] = { "joe", "mike", "tom" }; // EXPECT_THAT(user_ids, Contains(Eq(::std::string("tom")))); template <typename M> inline internal::ContainsMatcher<M> Contains(M matcher) { return internal::ContainsMatcher<M>(matcher); } // Matches an STL-style container or a native array that contains only // elements matching the given value or matcher. // // Each(m) is semantically equivalent to Not(Contains(Not(m))). Only // the messages are different. // // Examples: // ::std::set<int> page_ids; // // Each(m) matches an empty container, regardless of what m is. // EXPECT_THAT(page_ids, Each(Eq(1))); // EXPECT_THAT(page_ids, Each(Eq(77))); // // page_ids.insert(3); // EXPECT_THAT(page_ids, Each(Gt(0))); // EXPECT_THAT(page_ids, Not(Each(Gt(4)))); // page_ids.insert(1); // EXPECT_THAT(page_ids, Not(Each(Lt(2)))); // // ::std::map<int, size_t> page_lengths; // page_lengths[1] = 100; // page_lengths[2] = 200; // page_lengths[3] = 300; // EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100)))); // EXPECT_THAT(page_lengths, Each(Key(Le(3)))); // // const char* user_ids[] = { "joe", "mike", "tom" }; // EXPECT_THAT(user_ids, Not(Each(Eq(::std::string("tom"))))); template <typename M> inline internal::EachMatcher<M> Each(M matcher) { return internal::EachMatcher<M>(matcher); } // Key(inner_matcher) matches an std::pair whose 'first' field matches // inner_matcher. For example, Contains(Key(Ge(5))) can be used to match an // std::map that contains at least one element whose key is >= 5. template <typename M> inline internal::KeyMatcher<M> Key(M inner_matcher) { return internal::KeyMatcher<M>(inner_matcher); } // Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field // matches first_matcher and whose 'second' field matches second_matcher. For // example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), "foo"))) can be used // to match a std::map<int, string> that contains exactly one element whose key // is >= 5 and whose value equals "foo". template <typename FirstMatcher, typename SecondMatcher> inline internal::PairMatcher<FirstMatcher, SecondMatcher> Pair(FirstMatcher first_matcher, SecondMatcher second_matcher) { return internal::PairMatcher<FirstMatcher, SecondMatcher>( first_matcher, second_matcher); } // Returns a predicate that is satisfied by anything that matches the // given matcher. template <typename M> inline internal::MatcherAsPredicate<M> Matches(M matcher) { return internal::MatcherAsPredicate<M>(matcher); } // Returns true iff the value matches the matcher. template <typename T, typename M> inline bool Value(const T& value, M matcher) { return testing::Matches(matcher)(value); } // Matches the value against the given matcher and explains the match // result to listener. template <typename T, typename M> inline bool ExplainMatchResult( M matcher, const T& value, MatchResultListener* listener) { return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener); } #if GTEST_LANG_CXX11 // Define variadic matcher versions. They are overloaded in // gmock-generated-matchers.h for the cases supported by pre C++11 compilers. template <typename... Args> inline internal::AllOfMatcher<Args...> AllOf(const Args&... matchers) { return internal::AllOfMatcher<Args...>(matchers...); } template <typename... Args> inline internal::AnyOfMatcher<Args...> AnyOf(const Args&... matchers) { return internal::AnyOfMatcher<Args...>(matchers...); } #endif // GTEST_LANG_CXX11 // AllArgs(m) is a synonym of m. This is useful in // // EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq())); // // which is easier to read than // // EXPECT_CALL(foo, Bar(_, _)).With(Eq()); template <typename InnerMatcher> inline InnerMatcher AllArgs(const InnerMatcher& matcher) { return matcher; } // These macros allow using matchers to check values in Google Test // tests. ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher) // succeed iff the value matches the matcher. If the assertion fails, // the value and the description of the matcher will be printed. #define ASSERT_THAT(value, matcher) ASSERT_PRED_FORMAT1(\ ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value) #define EXPECT_THAT(value, matcher) EXPECT_PRED_FORMAT1(\ ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value) } // namespace testing // Include any custom callback matchers added by the local installation. // We must include this header at the end to make sure it can use the // declarations from this file. #include "gmock/internal/custom/gmock-matchers.h" #ifdef __clang__ #if __has_warning("-Wdeprecated-copy") #pragma clang diagnostic pop #endif #endif #ifdef _MSC_VER # pragma warning(pop) #endif #endif // GMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_
0
repos/DirectXShaderCompiler/utils/unittest/googlemock/include
repos/DirectXShaderCompiler/utils/unittest/googlemock/include/gmock/gmock-cardinalities.h
// 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. // // Author: [email protected] (Zhanyong Wan) // 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. #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_ #include <limits.h> #include <ostream> // NOLINT #include "gmock/internal/gmock-port.h" #include "gtest/gtest.h" 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 iff call_count calls will satisfy this cardinality. virtual bool IsSatisfiedByCallCount(int call_count) const = 0; // Returns true iff 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 linked_ptr // to const CardinalityInterface, so copying is fairly cheap. // 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 iff call_count calls will satisfy this cardinality. bool IsSatisfiedByCallCount(int call_count) const { return impl_->IsSatisfiedByCallCount(call_count); } // Returns true iff call_count calls will saturate this cardinality. bool IsSaturatedByCallCount(int call_count) const { return impl_->IsSaturatedByCallCount(call_count); } // Returns true iff 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: internal::linked_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 #endif // GMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
0
repos/DirectXShaderCompiler/utils/unittest/googlemock/include
repos/DirectXShaderCompiler/utils/unittest/googlemock/include/gmock/gmock-generated-matchers.h
// This file was GENERATED by command: // pump.py gmock-generated-matchers.h.pump // DO NOT EDIT BY HAND!!! // 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. // Google Mock - a framework for writing C++ mock classes. // // This file implements some commonly used variadic matchers. #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_ #include <iterator> #include <sstream> #include <string> #include <vector> #include "gmock/gmock-matchers.h" namespace testing { namespace internal { // The type of the i-th (0-based) field of Tuple. #define GMOCK_FIELD_TYPE_(Tuple, i) \ typename ::testing::tuple_element<i, Tuple>::type // TupleFields<Tuple, k0, ..., kn> is for selecting fields from a // tuple of type Tuple. It has two members: // // type: a tuple type whose i-th field is the ki-th field of Tuple. // GetSelectedFields(t): returns fields k0, ..., and kn of t as a tuple. // // For example, in class TupleFields<tuple<bool, char, int>, 2, 0>, we have: // // type is tuple<int, bool>, and // GetSelectedFields(make_tuple(true, 'a', 42)) is (42, true). template <class Tuple, int k0 = -1, int k1 = -1, int k2 = -1, int k3 = -1, int k4 = -1, int k5 = -1, int k6 = -1, int k7 = -1, int k8 = -1, int k9 = -1> class TupleFields; // This generic version is used when there are 10 selectors. template <class Tuple, int k0, int k1, int k2, int k3, int k4, int k5, int k6, int k7, int k8, int k9> class TupleFields { public: typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2), GMOCK_FIELD_TYPE_(Tuple, k3), GMOCK_FIELD_TYPE_(Tuple, k4), GMOCK_FIELD_TYPE_(Tuple, k5), GMOCK_FIELD_TYPE_(Tuple, k6), GMOCK_FIELD_TYPE_(Tuple, k7), GMOCK_FIELD_TYPE_(Tuple, k8), GMOCK_FIELD_TYPE_(Tuple, k9)> type; static type GetSelectedFields(const Tuple& t) { return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t), get<k4>(t), get<k5>(t), get<k6>(t), get<k7>(t), get<k8>(t), get<k9>(t)); } }; // The following specialization is used for 0 ~ 9 selectors. template <class Tuple> class TupleFields<Tuple, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1> { public: typedef ::testing::tuple<> type; static type GetSelectedFields(const Tuple& /* t */) { return type(); } }; template <class Tuple, int k0> class TupleFields<Tuple, k0, -1, -1, -1, -1, -1, -1, -1, -1, -1> { public: typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0)> type; static type GetSelectedFields(const Tuple& t) { return type(get<k0>(t)); } }; template <class Tuple, int k0, int k1> class TupleFields<Tuple, k0, k1, -1, -1, -1, -1, -1, -1, -1, -1> { public: typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), GMOCK_FIELD_TYPE_(Tuple, k1)> type; static type GetSelectedFields(const Tuple& t) { return type(get<k0>(t), get<k1>(t)); } }; template <class Tuple, int k0, int k1, int k2> class TupleFields<Tuple, k0, k1, k2, -1, -1, -1, -1, -1, -1, -1> { public: typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2)> type; static type GetSelectedFields(const Tuple& t) { return type(get<k0>(t), get<k1>(t), get<k2>(t)); } }; template <class Tuple, int k0, int k1, int k2, int k3> class TupleFields<Tuple, k0, k1, k2, k3, -1, -1, -1, -1, -1, -1> { public: typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2), GMOCK_FIELD_TYPE_(Tuple, k3)> type; static type GetSelectedFields(const Tuple& t) { return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t)); } }; template <class Tuple, int k0, int k1, int k2, int k3, int k4> class TupleFields<Tuple, k0, k1, k2, k3, k4, -1, -1, -1, -1, -1> { public: typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2), GMOCK_FIELD_TYPE_(Tuple, k3), GMOCK_FIELD_TYPE_(Tuple, k4)> type; static type GetSelectedFields(const Tuple& t) { return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t), get<k4>(t)); } }; template <class Tuple, int k0, int k1, int k2, int k3, int k4, int k5> class TupleFields<Tuple, k0, k1, k2, k3, k4, k5, -1, -1, -1, -1> { public: typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2), GMOCK_FIELD_TYPE_(Tuple, k3), GMOCK_FIELD_TYPE_(Tuple, k4), GMOCK_FIELD_TYPE_(Tuple, k5)> type; static type GetSelectedFields(const Tuple& t) { return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t), get<k4>(t), get<k5>(t)); } }; template <class Tuple, int k0, int k1, int k2, int k3, int k4, int k5, int k6> class TupleFields<Tuple, k0, k1, k2, k3, k4, k5, k6, -1, -1, -1> { public: typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2), GMOCK_FIELD_TYPE_(Tuple, k3), GMOCK_FIELD_TYPE_(Tuple, k4), GMOCK_FIELD_TYPE_(Tuple, k5), GMOCK_FIELD_TYPE_(Tuple, k6)> type; static type GetSelectedFields(const Tuple& t) { return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t), get<k4>(t), get<k5>(t), get<k6>(t)); } }; template <class Tuple, int k0, int k1, int k2, int k3, int k4, int k5, int k6, int k7> class TupleFields<Tuple, k0, k1, k2, k3, k4, k5, k6, k7, -1, -1> { public: typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2), GMOCK_FIELD_TYPE_(Tuple, k3), GMOCK_FIELD_TYPE_(Tuple, k4), GMOCK_FIELD_TYPE_(Tuple, k5), GMOCK_FIELD_TYPE_(Tuple, k6), GMOCK_FIELD_TYPE_(Tuple, k7)> type; static type GetSelectedFields(const Tuple& t) { return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t), get<k4>(t), get<k5>(t), get<k6>(t), get<k7>(t)); } }; template <class Tuple, int k0, int k1, int k2, int k3, int k4, int k5, int k6, int k7, int k8> class TupleFields<Tuple, k0, k1, k2, k3, k4, k5, k6, k7, k8, -1> { public: typedef ::testing::tuple<GMOCK_FIELD_TYPE_(Tuple, k0), GMOCK_FIELD_TYPE_(Tuple, k1), GMOCK_FIELD_TYPE_(Tuple, k2), GMOCK_FIELD_TYPE_(Tuple, k3), GMOCK_FIELD_TYPE_(Tuple, k4), GMOCK_FIELD_TYPE_(Tuple, k5), GMOCK_FIELD_TYPE_(Tuple, k6), GMOCK_FIELD_TYPE_(Tuple, k7), GMOCK_FIELD_TYPE_(Tuple, k8)> type; static type GetSelectedFields(const Tuple& t) { return type(get<k0>(t), get<k1>(t), get<k2>(t), get<k3>(t), get<k4>(t), get<k5>(t), get<k6>(t), get<k7>(t), get<k8>(t)); } }; #undef GMOCK_FIELD_TYPE_ // Implements the Args() matcher. template <class ArgsTuple, int k0 = -1, int k1 = -1, int k2 = -1, int k3 = -1, int k4 = -1, int k5 = -1, int k6 = -1, int k7 = -1, int k8 = -1, int k9 = -1> class ArgsMatcherImpl : public MatcherInterface<ArgsTuple> { public: // ArgsTuple may have top-level const or reference modifiers. typedef GTEST_REMOVE_REFERENCE_AND_CONST_(ArgsTuple) RawArgsTuple; typedef typename internal::TupleFields<RawArgsTuple, k0, k1, k2, k3, k4, k5, k6, k7, k8, k9>::type SelectedArgs; typedef Matcher<const SelectedArgs&> MonomorphicInnerMatcher; template <typename InnerMatcher> explicit ArgsMatcherImpl(const InnerMatcher& inner_matcher) : inner_matcher_(SafeMatcherCast<const SelectedArgs&>(inner_matcher)) {} virtual bool MatchAndExplain(ArgsTuple args, MatchResultListener* listener) const { const SelectedArgs& selected_args = GetSelectedArgs(args); if (!listener->IsInterested()) return inner_matcher_.Matches(selected_args); PrintIndices(listener->stream()); *listener << "are " << PrintToString(selected_args); StringMatchResultListener inner_listener; const bool match = inner_matcher_.MatchAndExplain(selected_args, &inner_listener); PrintIfNotEmpty(inner_listener.str(), listener->stream()); return match; } virtual void DescribeTo(::std::ostream* os) const { *os << "are a tuple "; PrintIndices(os); inner_matcher_.DescribeTo(os); } virtual void DescribeNegationTo(::std::ostream* os) const { *os << "are a tuple "; PrintIndices(os); inner_matcher_.DescribeNegationTo(os); } private: static SelectedArgs GetSelectedArgs(ArgsTuple args) { return TupleFields<RawArgsTuple, k0, k1, k2, k3, k4, k5, k6, k7, k8, k9>::GetSelectedFields(args); } // Prints the indices of the selected fields. static void PrintIndices(::std::ostream* os) { *os << "whose fields ("; const int indices[10] = { k0, k1, k2, k3, k4, k5, k6, k7, k8, k9 }; for (int i = 0; i < 10; i++) { if (indices[i] < 0) break; if (i >= 1) *os << ", "; *os << "#" << indices[i]; } *os << ") "; } const MonomorphicInnerMatcher inner_matcher_; GTEST_DISALLOW_ASSIGN_(ArgsMatcherImpl); }; template <class InnerMatcher, int k0 = -1, int k1 = -1, int k2 = -1, int k3 = -1, int k4 = -1, int k5 = -1, int k6 = -1, int k7 = -1, int k8 = -1, int k9 = -1> class ArgsMatcher { public: explicit ArgsMatcher(const InnerMatcher& inner_matcher) : inner_matcher_(inner_matcher) {} template <typename ArgsTuple> operator Matcher<ArgsTuple>() const { return MakeMatcher(new ArgsMatcherImpl<ArgsTuple, k0, k1, k2, k3, k4, k5, k6, k7, k8, k9>(inner_matcher_)); } private: const InnerMatcher inner_matcher_; GTEST_DISALLOW_ASSIGN_(ArgsMatcher); }; // A set of metafunctions for computing the result type of AllOf. // AllOf(m1, ..., mN) returns // AllOfResultN<decltype(m1), ..., decltype(mN)>::type. // Although AllOf isn't defined for one argument, AllOfResult1 is defined // to simplify the implementation. template <typename M1> struct AllOfResult1 { typedef M1 type; }; template <typename M1, typename M2> struct AllOfResult2 { typedef BothOfMatcher< typename AllOfResult1<M1>::type, typename AllOfResult1<M2>::type > type; }; template <typename M1, typename M2, typename M3> struct AllOfResult3 { typedef BothOfMatcher< typename AllOfResult1<M1>::type, typename AllOfResult2<M2, M3>::type > type; }; template <typename M1, typename M2, typename M3, typename M4> struct AllOfResult4 { typedef BothOfMatcher< typename AllOfResult2<M1, M2>::type, typename AllOfResult2<M3, M4>::type > type; }; template <typename M1, typename M2, typename M3, typename M4, typename M5> struct AllOfResult5 { typedef BothOfMatcher< typename AllOfResult2<M1, M2>::type, typename AllOfResult3<M3, M4, M5>::type > type; }; template <typename M1, typename M2, typename M3, typename M4, typename M5, typename M6> struct AllOfResult6 { typedef BothOfMatcher< typename AllOfResult3<M1, M2, M3>::type, typename AllOfResult3<M4, M5, M6>::type > type; }; template <typename M1, typename M2, typename M3, typename M4, typename M5, typename M6, typename M7> struct AllOfResult7 { typedef BothOfMatcher< typename AllOfResult3<M1, M2, M3>::type, typename AllOfResult4<M4, M5, M6, M7>::type > type; }; template <typename M1, typename M2, typename M3, typename M4, typename M5, typename M6, typename M7, typename M8> struct AllOfResult8 { typedef BothOfMatcher< typename AllOfResult4<M1, M2, M3, M4>::type, typename AllOfResult4<M5, M6, M7, M8>::type > type; }; template <typename M1, typename M2, typename M3, typename M4, typename M5, typename M6, typename M7, typename M8, typename M9> struct AllOfResult9 { typedef BothOfMatcher< typename AllOfResult4<M1, M2, M3, M4>::type, typename AllOfResult5<M5, M6, M7, M8, M9>::type > type; }; template <typename M1, typename M2, typename M3, typename M4, typename M5, typename M6, typename M7, typename M8, typename M9, typename M10> struct AllOfResult10 { typedef BothOfMatcher< typename AllOfResult5<M1, M2, M3, M4, M5>::type, typename AllOfResult5<M6, M7, M8, M9, M10>::type > type; }; // A set of metafunctions for computing the result type of AnyOf. // AnyOf(m1, ..., mN) returns // AnyOfResultN<decltype(m1), ..., decltype(mN)>::type. // Although AnyOf isn't defined for one argument, AnyOfResult1 is defined // to simplify the implementation. template <typename M1> struct AnyOfResult1 { typedef M1 type; }; template <typename M1, typename M2> struct AnyOfResult2 { typedef EitherOfMatcher< typename AnyOfResult1<M1>::type, typename AnyOfResult1<M2>::type > type; }; template <typename M1, typename M2, typename M3> struct AnyOfResult3 { typedef EitherOfMatcher< typename AnyOfResult1<M1>::type, typename AnyOfResult2<M2, M3>::type > type; }; template <typename M1, typename M2, typename M3, typename M4> struct AnyOfResult4 { typedef EitherOfMatcher< typename AnyOfResult2<M1, M2>::type, typename AnyOfResult2<M3, M4>::type > type; }; template <typename M1, typename M2, typename M3, typename M4, typename M5> struct AnyOfResult5 { typedef EitherOfMatcher< typename AnyOfResult2<M1, M2>::type, typename AnyOfResult3<M3, M4, M5>::type > type; }; template <typename M1, typename M2, typename M3, typename M4, typename M5, typename M6> struct AnyOfResult6 { typedef EitherOfMatcher< typename AnyOfResult3<M1, M2, M3>::type, typename AnyOfResult3<M4, M5, M6>::type > type; }; template <typename M1, typename M2, typename M3, typename M4, typename M5, typename M6, typename M7> struct AnyOfResult7 { typedef EitherOfMatcher< typename AnyOfResult3<M1, M2, M3>::type, typename AnyOfResult4<M4, M5, M6, M7>::type > type; }; template <typename M1, typename M2, typename M3, typename M4, typename M5, typename M6, typename M7, typename M8> struct AnyOfResult8 { typedef EitherOfMatcher< typename AnyOfResult4<M1, M2, M3, M4>::type, typename AnyOfResult4<M5, M6, M7, M8>::type > type; }; template <typename M1, typename M2, typename M3, typename M4, typename M5, typename M6, typename M7, typename M8, typename M9> struct AnyOfResult9 { typedef EitherOfMatcher< typename AnyOfResult4<M1, M2, M3, M4>::type, typename AnyOfResult5<M5, M6, M7, M8, M9>::type > type; }; template <typename M1, typename M2, typename M3, typename M4, typename M5, typename M6, typename M7, typename M8, typename M9, typename M10> struct AnyOfResult10 { typedef EitherOfMatcher< typename AnyOfResult5<M1, M2, M3, M4, M5>::type, typename AnyOfResult5<M6, M7, M8, M9, M10>::type > type; }; } // namespace internal // Args<N1, N2, ..., Nk>(a_matcher) matches a tuple if the selected // fields of it matches a_matcher. C++ doesn't support default // arguments for function templates, so we have to overload it. template <typename InnerMatcher> inline internal::ArgsMatcher<InnerMatcher> Args(const InnerMatcher& matcher) { return internal::ArgsMatcher<InnerMatcher>(matcher); } template <int k1, typename InnerMatcher> inline internal::ArgsMatcher<InnerMatcher, k1> Args(const InnerMatcher& matcher) { return internal::ArgsMatcher<InnerMatcher, k1>(matcher); } template <int k1, int k2, typename InnerMatcher> inline internal::ArgsMatcher<InnerMatcher, k1, k2> Args(const InnerMatcher& matcher) { return internal::ArgsMatcher<InnerMatcher, k1, k2>(matcher); } template <int k1, int k2, int k3, typename InnerMatcher> inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3> Args(const InnerMatcher& matcher) { return internal::ArgsMatcher<InnerMatcher, k1, k2, k3>(matcher); } template <int k1, int k2, int k3, int k4, typename InnerMatcher> inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4> Args(const InnerMatcher& matcher) { return internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4>(matcher); } template <int k1, int k2, int k3, int k4, int k5, typename InnerMatcher> inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5> Args(const InnerMatcher& matcher) { return internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5>(matcher); } template <int k1, int k2, int k3, int k4, int k5, int k6, typename InnerMatcher> inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6> Args(const InnerMatcher& matcher) { return internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6>(matcher); } template <int k1, int k2, int k3, int k4, int k5, int k6, int k7, typename InnerMatcher> inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7> Args(const InnerMatcher& matcher) { return internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7>(matcher); } template <int k1, int k2, int k3, int k4, int k5, int k6, int k7, int k8, typename InnerMatcher> inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7, k8> Args(const InnerMatcher& matcher) { return internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7, k8>(matcher); } template <int k1, int k2, int k3, int k4, int k5, int k6, int k7, int k8, int k9, typename InnerMatcher> inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7, k8, k9> Args(const InnerMatcher& matcher) { return internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7, k8, k9>(matcher); } template <int k1, int k2, int k3, int k4, int k5, int k6, int k7, int k8, int k9, int k10, typename InnerMatcher> inline internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7, k8, k9, k10> Args(const InnerMatcher& matcher) { return internal::ArgsMatcher<InnerMatcher, k1, k2, k3, k4, k5, k6, k7, k8, k9, k10>(matcher); } // ElementsAre(e_1, e_2, ... e_n) matches an STL-style container with // n elements, where the i-th element in the container must // match the i-th argument in the list. Each argument of // ElementsAre() can be either a value or a matcher. We support up to // 10 arguments. // // The use of DecayArray in the implementation allows ElementsAre() // to accept string literals, whose type is const char[N], but we // want to treat them as const char*. // // NOTE: Since ElementsAre() cares about the order of the elements, it // must not be used with containers whose elements's order is // undefined (e.g. hash_map). inline internal::ElementsAreMatcher< ::testing::tuple<> > ElementsAre() { typedef ::testing::tuple<> Args; return internal::ElementsAreMatcher<Args>(Args()); } template <typename T1> inline internal::ElementsAreMatcher< ::testing::tuple< typename internal::DecayArray<T1>::type> > ElementsAre(const T1& e1) { typedef ::testing::tuple< typename internal::DecayArray<T1>::type> Args; return internal::ElementsAreMatcher<Args>(Args(e1)); } template <typename T1, typename T2> inline internal::ElementsAreMatcher< ::testing::tuple< typename internal::DecayArray<T1>::type, typename internal::DecayArray<T2>::type> > ElementsAre(const T1& e1, const T2& e2) { typedef ::testing::tuple< typename internal::DecayArray<T1>::type, typename internal::DecayArray<T2>::type> Args; return internal::ElementsAreMatcher<Args>(Args(e1, e2)); } template <typename T1, typename T2, typename T3> inline internal::ElementsAreMatcher< ::testing::tuple< typename internal::DecayArray<T1>::type, typename internal::DecayArray<T2>::type, typename internal::DecayArray<T3>::type> > ElementsAre(const T1& e1, const T2& e2, const T3& e3) { typedef ::testing::tuple< typename internal::DecayArray<T1>::type, typename internal::DecayArray<T2>::type, typename internal::DecayArray<T3>::type> Args; return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3)); } template <typename T1, typename T2, typename T3, typename T4> inline internal::ElementsAreMatcher< ::testing::tuple< typename internal::DecayArray<T1>::type, typename internal::DecayArray<T2>::type, typename internal::DecayArray<T3>::type, typename internal::DecayArray<T4>::type> > ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4) { typedef ::testing::tuple< typename internal::DecayArray<T1>::type, typename internal::DecayArray<T2>::type, typename internal::DecayArray<T3>::type, typename internal::DecayArray<T4>::type> Args; return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3, e4)); } template <typename T1, typename T2, typename T3, typename T4, typename T5> inline internal::ElementsAreMatcher< ::testing::tuple< typename internal::DecayArray<T1>::type, typename internal::DecayArray<T2>::type, typename internal::DecayArray<T3>::type, typename internal::DecayArray<T4>::type, typename internal::DecayArray<T5>::type> > ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, const T5& e5) { typedef ::testing::tuple< typename internal::DecayArray<T1>::type, typename internal::DecayArray<T2>::type, typename internal::DecayArray<T3>::type, typename internal::DecayArray<T4>::type, typename internal::DecayArray<T5>::type> Args; return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5)); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6> inline internal::ElementsAreMatcher< ::testing::tuple< typename internal::DecayArray<T1>::type, typename internal::DecayArray<T2>::type, typename internal::DecayArray<T3>::type, typename internal::DecayArray<T4>::type, typename internal::DecayArray<T5>::type, typename internal::DecayArray<T6>::type> > ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, const T5& e5, const T6& e6) { typedef ::testing::tuple< typename internal::DecayArray<T1>::type, typename internal::DecayArray<T2>::type, typename internal::DecayArray<T3>::type, typename internal::DecayArray<T4>::type, typename internal::DecayArray<T5>::type, typename internal::DecayArray<T6>::type> Args; return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, e6)); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7> inline internal::ElementsAreMatcher< ::testing::tuple< typename internal::DecayArray<T1>::type, typename internal::DecayArray<T2>::type, typename internal::DecayArray<T3>::type, typename internal::DecayArray<T4>::type, typename internal::DecayArray<T5>::type, typename internal::DecayArray<T6>::type, typename internal::DecayArray<T7>::type> > ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, const T5& e5, const T6& e6, const T7& e7) { typedef ::testing::tuple< typename internal::DecayArray<T1>::type, typename internal::DecayArray<T2>::type, typename internal::DecayArray<T3>::type, typename internal::DecayArray<T4>::type, typename internal::DecayArray<T5>::type, typename internal::DecayArray<T6>::type, typename internal::DecayArray<T7>::type> Args; return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, e6, e7)); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8> inline internal::ElementsAreMatcher< ::testing::tuple< typename internal::DecayArray<T1>::type, typename internal::DecayArray<T2>::type, typename internal::DecayArray<T3>::type, typename internal::DecayArray<T4>::type, typename internal::DecayArray<T5>::type, typename internal::DecayArray<T6>::type, typename internal::DecayArray<T7>::type, typename internal::DecayArray<T8>::type> > ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, const T5& e5, const T6& e6, const T7& e7, const T8& e8) { typedef ::testing::tuple< typename internal::DecayArray<T1>::type, typename internal::DecayArray<T2>::type, typename internal::DecayArray<T3>::type, typename internal::DecayArray<T4>::type, typename internal::DecayArray<T5>::type, typename internal::DecayArray<T6>::type, typename internal::DecayArray<T7>::type, typename internal::DecayArray<T8>::type> Args; return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, e6, e7, e8)); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9> inline internal::ElementsAreMatcher< ::testing::tuple< typename internal::DecayArray<T1>::type, typename internal::DecayArray<T2>::type, typename internal::DecayArray<T3>::type, typename internal::DecayArray<T4>::type, typename internal::DecayArray<T5>::type, typename internal::DecayArray<T6>::type, typename internal::DecayArray<T7>::type, typename internal::DecayArray<T8>::type, typename internal::DecayArray<T9>::type> > ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, const T5& e5, const T6& e6, const T7& e7, const T8& e8, const T9& e9) { typedef ::testing::tuple< typename internal::DecayArray<T1>::type, typename internal::DecayArray<T2>::type, typename internal::DecayArray<T3>::type, typename internal::DecayArray<T4>::type, typename internal::DecayArray<T5>::type, typename internal::DecayArray<T6>::type, typename internal::DecayArray<T7>::type, typename internal::DecayArray<T8>::type, typename internal::DecayArray<T9>::type> Args; return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, e6, e7, e8, e9)); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10> inline internal::ElementsAreMatcher< ::testing::tuple< typename internal::DecayArray<T1>::type, typename internal::DecayArray<T2>::type, typename internal::DecayArray<T3>::type, typename internal::DecayArray<T4>::type, typename internal::DecayArray<T5>::type, typename internal::DecayArray<T6>::type, typename internal::DecayArray<T7>::type, typename internal::DecayArray<T8>::type, typename internal::DecayArray<T9>::type, typename internal::DecayArray<T10>::type> > ElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, const T5& e5, const T6& e6, const T7& e7, const T8& e8, const T9& e9, const T10& e10) { typedef ::testing::tuple< typename internal::DecayArray<T1>::type, typename internal::DecayArray<T2>::type, typename internal::DecayArray<T3>::type, typename internal::DecayArray<T4>::type, typename internal::DecayArray<T5>::type, typename internal::DecayArray<T6>::type, typename internal::DecayArray<T7>::type, typename internal::DecayArray<T8>::type, typename internal::DecayArray<T9>::type, typename internal::DecayArray<T10>::type> Args; return internal::ElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, e6, e7, e8, e9, e10)); } // UnorderedElementsAre(e_1, e_2, ..., e_n) is an ElementsAre extension // that matches n elements in any order. We support up to n=10 arguments. inline internal::UnorderedElementsAreMatcher< ::testing::tuple<> > UnorderedElementsAre() { typedef ::testing::tuple<> Args; return internal::UnorderedElementsAreMatcher<Args>(Args()); } template <typename T1> inline internal::UnorderedElementsAreMatcher< ::testing::tuple< typename internal::DecayArray<T1>::type> > UnorderedElementsAre(const T1& e1) { typedef ::testing::tuple< typename internal::DecayArray<T1>::type> Args; return internal::UnorderedElementsAreMatcher<Args>(Args(e1)); } template <typename T1, typename T2> inline internal::UnorderedElementsAreMatcher< ::testing::tuple< typename internal::DecayArray<T1>::type, typename internal::DecayArray<T2>::type> > UnorderedElementsAre(const T1& e1, const T2& e2) { typedef ::testing::tuple< typename internal::DecayArray<T1>::type, typename internal::DecayArray<T2>::type> Args; return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2)); } template <typename T1, typename T2, typename T3> inline internal::UnorderedElementsAreMatcher< ::testing::tuple< typename internal::DecayArray<T1>::type, typename internal::DecayArray<T2>::type, typename internal::DecayArray<T3>::type> > UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3) { typedef ::testing::tuple< typename internal::DecayArray<T1>::type, typename internal::DecayArray<T2>::type, typename internal::DecayArray<T3>::type> Args; return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3)); } template <typename T1, typename T2, typename T3, typename T4> inline internal::UnorderedElementsAreMatcher< ::testing::tuple< typename internal::DecayArray<T1>::type, typename internal::DecayArray<T2>::type, typename internal::DecayArray<T3>::type, typename internal::DecayArray<T4>::type> > UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4) { typedef ::testing::tuple< typename internal::DecayArray<T1>::type, typename internal::DecayArray<T2>::type, typename internal::DecayArray<T3>::type, typename internal::DecayArray<T4>::type> Args; return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3, e4)); } template <typename T1, typename T2, typename T3, typename T4, typename T5> inline internal::UnorderedElementsAreMatcher< ::testing::tuple< typename internal::DecayArray<T1>::type, typename internal::DecayArray<T2>::type, typename internal::DecayArray<T3>::type, typename internal::DecayArray<T4>::type, typename internal::DecayArray<T5>::type> > UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, const T5& e5) { typedef ::testing::tuple< typename internal::DecayArray<T1>::type, typename internal::DecayArray<T2>::type, typename internal::DecayArray<T3>::type, typename internal::DecayArray<T4>::type, typename internal::DecayArray<T5>::type> Args; return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5)); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6> inline internal::UnorderedElementsAreMatcher< ::testing::tuple< typename internal::DecayArray<T1>::type, typename internal::DecayArray<T2>::type, typename internal::DecayArray<T3>::type, typename internal::DecayArray<T4>::type, typename internal::DecayArray<T5>::type, typename internal::DecayArray<T6>::type> > UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, const T5& e5, const T6& e6) { typedef ::testing::tuple< typename internal::DecayArray<T1>::type, typename internal::DecayArray<T2>::type, typename internal::DecayArray<T3>::type, typename internal::DecayArray<T4>::type, typename internal::DecayArray<T5>::type, typename internal::DecayArray<T6>::type> Args; return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, e6)); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7> inline internal::UnorderedElementsAreMatcher< ::testing::tuple< typename internal::DecayArray<T1>::type, typename internal::DecayArray<T2>::type, typename internal::DecayArray<T3>::type, typename internal::DecayArray<T4>::type, typename internal::DecayArray<T5>::type, typename internal::DecayArray<T6>::type, typename internal::DecayArray<T7>::type> > UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, const T5& e5, const T6& e6, const T7& e7) { typedef ::testing::tuple< typename internal::DecayArray<T1>::type, typename internal::DecayArray<T2>::type, typename internal::DecayArray<T3>::type, typename internal::DecayArray<T4>::type, typename internal::DecayArray<T5>::type, typename internal::DecayArray<T6>::type, typename internal::DecayArray<T7>::type> Args; return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, e6, e7)); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8> inline internal::UnorderedElementsAreMatcher< ::testing::tuple< typename internal::DecayArray<T1>::type, typename internal::DecayArray<T2>::type, typename internal::DecayArray<T3>::type, typename internal::DecayArray<T4>::type, typename internal::DecayArray<T5>::type, typename internal::DecayArray<T6>::type, typename internal::DecayArray<T7>::type, typename internal::DecayArray<T8>::type> > UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, const T5& e5, const T6& e6, const T7& e7, const T8& e8) { typedef ::testing::tuple< typename internal::DecayArray<T1>::type, typename internal::DecayArray<T2>::type, typename internal::DecayArray<T3>::type, typename internal::DecayArray<T4>::type, typename internal::DecayArray<T5>::type, typename internal::DecayArray<T6>::type, typename internal::DecayArray<T7>::type, typename internal::DecayArray<T8>::type> Args; return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, e6, e7, e8)); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9> inline internal::UnorderedElementsAreMatcher< ::testing::tuple< typename internal::DecayArray<T1>::type, typename internal::DecayArray<T2>::type, typename internal::DecayArray<T3>::type, typename internal::DecayArray<T4>::type, typename internal::DecayArray<T5>::type, typename internal::DecayArray<T6>::type, typename internal::DecayArray<T7>::type, typename internal::DecayArray<T8>::type, typename internal::DecayArray<T9>::type> > UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, const T5& e5, const T6& e6, const T7& e7, const T8& e8, const T9& e9) { typedef ::testing::tuple< typename internal::DecayArray<T1>::type, typename internal::DecayArray<T2>::type, typename internal::DecayArray<T3>::type, typename internal::DecayArray<T4>::type, typename internal::DecayArray<T5>::type, typename internal::DecayArray<T6>::type, typename internal::DecayArray<T7>::type, typename internal::DecayArray<T8>::type, typename internal::DecayArray<T9>::type> Args; return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, e6, e7, e8, e9)); } template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10> inline internal::UnorderedElementsAreMatcher< ::testing::tuple< typename internal::DecayArray<T1>::type, typename internal::DecayArray<T2>::type, typename internal::DecayArray<T3>::type, typename internal::DecayArray<T4>::type, typename internal::DecayArray<T5>::type, typename internal::DecayArray<T6>::type, typename internal::DecayArray<T7>::type, typename internal::DecayArray<T8>::type, typename internal::DecayArray<T9>::type, typename internal::DecayArray<T10>::type> > UnorderedElementsAre(const T1& e1, const T2& e2, const T3& e3, const T4& e4, const T5& e5, const T6& e6, const T7& e7, const T8& e8, const T9& e9, const T10& e10) { typedef ::testing::tuple< typename internal::DecayArray<T1>::type, typename internal::DecayArray<T2>::type, typename internal::DecayArray<T3>::type, typename internal::DecayArray<T4>::type, typename internal::DecayArray<T5>::type, typename internal::DecayArray<T6>::type, typename internal::DecayArray<T7>::type, typename internal::DecayArray<T8>::type, typename internal::DecayArray<T9>::type, typename internal::DecayArray<T10>::type> Args; return internal::UnorderedElementsAreMatcher<Args>(Args(e1, e2, e3, e4, e5, e6, e7, e8, e9, e10)); } // AllOf(m1, m2, ..., mk) matches any value that matches all of the given // sub-matchers. AllOf is called fully qualified to prevent ADL from firing. template <typename M1, typename M2> inline typename internal::AllOfResult2<M1, M2>::type AllOf(M1 m1, M2 m2) { return typename internal::AllOfResult2<M1, M2>::type( m1, m2); } template <typename M1, typename M2, typename M3> inline typename internal::AllOfResult3<M1, M2, M3>::type AllOf(M1 m1, M2 m2, M3 m3) { return typename internal::AllOfResult3<M1, M2, M3>::type( m1, ::testing::AllOf(m2, m3)); } template <typename M1, typename M2, typename M3, typename M4> inline typename internal::AllOfResult4<M1, M2, M3, M4>::type AllOf(M1 m1, M2 m2, M3 m3, M4 m4) { return typename internal::AllOfResult4<M1, M2, M3, M4>::type( ::testing::AllOf(m1, m2), ::testing::AllOf(m3, m4)); } template <typename M1, typename M2, typename M3, typename M4, typename M5> inline typename internal::AllOfResult5<M1, M2, M3, M4, M5>::type AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5) { return typename internal::AllOfResult5<M1, M2, M3, M4, M5>::type( ::testing::AllOf(m1, m2), ::testing::AllOf(m3, m4, m5)); } template <typename M1, typename M2, typename M3, typename M4, typename M5, typename M6> inline typename internal::AllOfResult6<M1, M2, M3, M4, M5, M6>::type AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6) { return typename internal::AllOfResult6<M1, M2, M3, M4, M5, M6>::type( ::testing::AllOf(m1, m2, m3), ::testing::AllOf(m4, m5, m6)); } template <typename M1, typename M2, typename M3, typename M4, typename M5, typename M6, typename M7> inline typename internal::AllOfResult7<M1, M2, M3, M4, M5, M6, M7>::type AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7) { return typename internal::AllOfResult7<M1, M2, M3, M4, M5, M6, M7>::type( ::testing::AllOf(m1, m2, m3), ::testing::AllOf(m4, m5, m6, m7)); } template <typename M1, typename M2, typename M3, typename M4, typename M5, typename M6, typename M7, typename M8> inline typename internal::AllOfResult8<M1, M2, M3, M4, M5, M6, M7, M8>::type AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8) { return typename internal::AllOfResult8<M1, M2, M3, M4, M5, M6, M7, M8>::type( ::testing::AllOf(m1, m2, m3, m4), ::testing::AllOf(m5, m6, m7, m8)); } template <typename M1, typename M2, typename M3, typename M4, typename M5, typename M6, typename M7, typename M8, typename M9> inline typename internal::AllOfResult9<M1, M2, M3, M4, M5, M6, M7, M8, M9>::type AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9) { return typename internal::AllOfResult9<M1, M2, M3, M4, M5, M6, M7, M8, M9>::type( ::testing::AllOf(m1, m2, m3, m4), ::testing::AllOf(m5, m6, m7, m8, m9)); } template <typename M1, typename M2, typename M3, typename M4, typename M5, typename M6, typename M7, typename M8, typename M9, typename M10> inline typename internal::AllOfResult10<M1, M2, M3, M4, M5, M6, M7, M8, M9, M10>::type AllOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { return typename internal::AllOfResult10<M1, M2, M3, M4, M5, M6, M7, M8, M9, M10>::type( ::testing::AllOf(m1, m2, m3, m4, m5), ::testing::AllOf(m6, m7, m8, m9, m10)); } // AnyOf(m1, m2, ..., mk) matches any value that matches any of the given // sub-matchers. AnyOf is called fully qualified to prevent ADL from firing. template <typename M1, typename M2> inline typename internal::AnyOfResult2<M1, M2>::type AnyOf(M1 m1, M2 m2) { return typename internal::AnyOfResult2<M1, M2>::type( m1, m2); } template <typename M1, typename M2, typename M3> inline typename internal::AnyOfResult3<M1, M2, M3>::type AnyOf(M1 m1, M2 m2, M3 m3) { return typename internal::AnyOfResult3<M1, M2, M3>::type( m1, ::testing::AnyOf(m2, m3)); } template <typename M1, typename M2, typename M3, typename M4> inline typename internal::AnyOfResult4<M1, M2, M3, M4>::type AnyOf(M1 m1, M2 m2, M3 m3, M4 m4) { return typename internal::AnyOfResult4<M1, M2, M3, M4>::type( ::testing::AnyOf(m1, m2), ::testing::AnyOf(m3, m4)); } template <typename M1, typename M2, typename M3, typename M4, typename M5> inline typename internal::AnyOfResult5<M1, M2, M3, M4, M5>::type AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5) { return typename internal::AnyOfResult5<M1, M2, M3, M4, M5>::type( ::testing::AnyOf(m1, m2), ::testing::AnyOf(m3, m4, m5)); } template <typename M1, typename M2, typename M3, typename M4, typename M5, typename M6> inline typename internal::AnyOfResult6<M1, M2, M3, M4, M5, M6>::type AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6) { return typename internal::AnyOfResult6<M1, M2, M3, M4, M5, M6>::type( ::testing::AnyOf(m1, m2, m3), ::testing::AnyOf(m4, m5, m6)); } template <typename M1, typename M2, typename M3, typename M4, typename M5, typename M6, typename M7> inline typename internal::AnyOfResult7<M1, M2, M3, M4, M5, M6, M7>::type AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7) { return typename internal::AnyOfResult7<M1, M2, M3, M4, M5, M6, M7>::type( ::testing::AnyOf(m1, m2, m3), ::testing::AnyOf(m4, m5, m6, m7)); } template <typename M1, typename M2, typename M3, typename M4, typename M5, typename M6, typename M7, typename M8> inline typename internal::AnyOfResult8<M1, M2, M3, M4, M5, M6, M7, M8>::type AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8) { return typename internal::AnyOfResult8<M1, M2, M3, M4, M5, M6, M7, M8>::type( ::testing::AnyOf(m1, m2, m3, m4), ::testing::AnyOf(m5, m6, m7, m8)); } template <typename M1, typename M2, typename M3, typename M4, typename M5, typename M6, typename M7, typename M8, typename M9> inline typename internal::AnyOfResult9<M1, M2, M3, M4, M5, M6, M7, M8, M9>::type AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9) { return typename internal::AnyOfResult9<M1, M2, M3, M4, M5, M6, M7, M8, M9>::type( ::testing::AnyOf(m1, m2, m3, m4), ::testing::AnyOf(m5, m6, m7, m8, m9)); } template <typename M1, typename M2, typename M3, typename M4, typename M5, typename M6, typename M7, typename M8, typename M9, typename M10> inline typename internal::AnyOfResult10<M1, M2, M3, M4, M5, M6, M7, M8, M9, M10>::type AnyOf(M1 m1, M2 m2, M3 m3, M4 m4, M5 m5, M6 m6, M7 m7, M8 m8, M9 m9, M10 m10) { return typename internal::AnyOfResult10<M1, M2, M3, M4, M5, M6, M7, M8, M9, M10>::type( ::testing::AnyOf(m1, m2, m3, m4, m5), ::testing::AnyOf(m6, m7, m8, m9, m10)); } } // namespace testing // The MATCHER* family of macros can be used in a namespace scope to // define custom matchers easily. // // Basic Usage // =========== // // The syntax // // MATCHER(name, description_string) { statements; } // // defines a matcher with the given name that executes the statements, // which must return a bool to indicate if the match succeeds. Inside // the statements, you can refer to the value being matched by 'arg', // and refer to its type by 'arg_type'. // // The description string documents what the matcher does, and is used // to generate the failure message when the match fails. Since a // MATCHER() is usually defined in a header file shared by multiple // C++ source files, we require the description to be a C-string // literal to avoid possible side effects. It can be empty, in which // case we'll use the sequence of words in the matcher name as the // description. // // For example: // // MATCHER(IsEven, "") { return (arg % 2) == 0; } // // allows you to write // // // Expects mock_foo.Bar(n) to be called where n is even. // EXPECT_CALL(mock_foo, Bar(IsEven())); // // or, // // // Verifies that the value of some_expression is even. // EXPECT_THAT(some_expression, IsEven()); // // If the above assertion fails, it will print something like: // // Value of: some_expression // Expected: is even // Actual: 7 // // where the description "is even" is automatically calculated from the // matcher name IsEven. // // Argument Type // ============= // // Note that the type of the value being matched (arg_type) is // determined by the context in which you use the matcher and is // supplied to you by the compiler, so you don't need to worry about // declaring it (nor can you). This allows the matcher to be // polymorphic. For example, IsEven() can be used to match any type // where the value of "(arg % 2) == 0" can be implicitly converted to // a bool. In the "Bar(IsEven())" example above, if method Bar() // takes an int, 'arg_type' will be int; if it takes an unsigned long, // 'arg_type' will be unsigned long; and so on. // // Parameterizing Matchers // ======================= // // Sometimes you'll want to parameterize the matcher. For that you // can use another macro: // // MATCHER_P(name, param_name, description_string) { statements; } // // For example: // // MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; } // // will allow you to write: // // EXPECT_THAT(Blah("a"), HasAbsoluteValue(n)); // // which may lead to this message (assuming n is 10): // // Value of: Blah("a") // Expected: has absolute value 10 // Actual: -9 // // Note that both the matcher description and its parameter are // printed, making the message human-friendly. // // In the matcher definition body, you can write 'foo_type' to // reference the type of a parameter named 'foo'. For example, in the // body of MATCHER_P(HasAbsoluteValue, value) above, you can write // 'value_type' to refer to the type of 'value'. // // We also provide MATCHER_P2, MATCHER_P3, ..., up to MATCHER_P10 to // support multi-parameter matchers. // // Describing Parameterized Matchers // ================================= // // The last argument to MATCHER*() is a string-typed expression. The // expression can reference all of the matcher's parameters and a // special bool-typed variable named 'negation'. When 'negation' is // false, the expression should evaluate to the matcher's description; // otherwise it should evaluate to the description of the negation of // the matcher. For example, // // using testing::PrintToString; // // MATCHER_P2(InClosedRange, low, hi, // string(negation ? "is not" : "is") + " in range [" + // PrintToString(low) + ", " + PrintToString(hi) + "]") { // return low <= arg && arg <= hi; // } // ... // EXPECT_THAT(3, InClosedRange(4, 6)); // EXPECT_THAT(3, Not(InClosedRange(2, 4))); // // would generate two failures that contain the text: // // Expected: is in range [4, 6] // ... // Expected: is not in range [2, 4] // // If you specify "" as the description, the failure message will // contain the sequence of words in the matcher name followed by the // parameter values printed as a tuple. For example, // // MATCHER_P2(InClosedRange, low, hi, "") { ... } // ... // EXPECT_THAT(3, InClosedRange(4, 6)); // EXPECT_THAT(3, Not(InClosedRange(2, 4))); // // would generate two failures that contain the text: // // Expected: in closed range (4, 6) // ... // Expected: not (in closed range (2, 4)) // // Types of Matcher Parameters // =========================== // // For the purpose of typing, you can view // // MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... } // // as shorthand for // // template <typename p1_type, ..., typename pk_type> // FooMatcherPk<p1_type, ..., pk_type> // Foo(p1_type p1, ..., pk_type pk) { ... } // // When you write Foo(v1, ..., vk), the compiler infers the types of // the parameters v1, ..., and vk for you. If you are not happy with // the result of the type inference, you can specify the types by // explicitly instantiating the template, as in Foo<long, bool>(5, // false). As said earlier, you don't get to (or need to) specify // 'arg_type' as that's determined by the context in which the matcher // is used. You can assign the result of expression Foo(p1, ..., pk) // to a variable of type FooMatcherPk<p1_type, ..., pk_type>. This // can be useful when composing matchers. // // While you can instantiate a matcher template with reference types, // passing the parameters by pointer usually makes your code more // readable. If, however, you still want to pass a parameter by // reference, be aware that in the failure message generated by the // matcher you will see the value of the referenced object but not its // address. // // Explaining Match Results // ======================== // // Sometimes the matcher description alone isn't enough to explain why // the match has failed or succeeded. For example, when expecting a // long string, it can be very helpful to also print the diff between // the expected string and the actual one. To achieve that, you can // optionally stream additional information to a special variable // named result_listener, whose type is a pointer to class // MatchResultListener: // // MATCHER_P(EqualsLongString, str, "") { // if (arg == str) return true; // // *result_listener << "the difference: " /// << DiffStrings(str, arg); // return false; // } // // Overloading Matchers // ==================== // // You can overload matchers with different numbers of parameters: // // MATCHER_P(Blah, a, description_string1) { ... } // MATCHER_P2(Blah, a, b, description_string2) { ... } // // Caveats // ======= // // When defining a new matcher, you should also consider implementing // MatcherInterface or using MakePolymorphicMatcher(). These // approaches require more work than the MATCHER* macros, but also // give you more control on the types of the value being matched and // the matcher parameters, which may leads to better compiler error // messages when the matcher is used wrong. They also allow // overloading matchers based on parameter types (as opposed to just // based on the number of parameters). // // MATCHER*() can only be used in a namespace scope. The reason is // that C++ doesn't yet allow function-local types to be used to // instantiate templates. The up-coming C++0x standard will fix this. // Once that's done, we'll consider supporting using MATCHER*() inside // a function. // // More Information // ================ // // To learn more about using these macros, please search for 'MATCHER' // on http://code.google.com/p/googlemock/wiki/CookBook. #define MATCHER(name, description)\ class name##Matcher {\ public:\ template <typename arg_type>\ class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ public:\ gmock_Impl()\ {}\ virtual bool MatchAndExplain(\ arg_type arg, ::testing::MatchResultListener* result_listener) const;\ virtual void DescribeTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(false);\ }\ virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(true);\ }\ private:\ ::testing::internal::string FormatDescription(bool negation) const {\ const ::testing::internal::string gmock_description = (description);\ if (!gmock_description.empty())\ return gmock_description;\ return ::testing::internal::FormatMatcherDescription(\ negation, #name, \ ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ ::testing::tuple<>()));\ }\ GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename arg_type>\ operator ::testing::Matcher<arg_type>() const {\ return ::testing::Matcher<arg_type>(\ new gmock_Impl<arg_type>());\ }\ name##Matcher() {\ }\ private:\ GTEST_DISALLOW_ASSIGN_(name##Matcher);\ };\ inline name##Matcher name() {\ return name##Matcher();\ }\ template <typename arg_type>\ bool name##Matcher::gmock_Impl<arg_type>::MatchAndExplain(\ arg_type arg, \ ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ const #define MATCHER_P(name, p0, description)\ template <typename p0##_type>\ class name##MatcherP {\ public:\ template <typename arg_type>\ class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ public:\ explicit gmock_Impl(p0##_type gmock_p0)\ : p0(gmock_p0) {}\ virtual bool MatchAndExplain(\ arg_type arg, ::testing::MatchResultListener* result_listener) const;\ virtual void DescribeTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(false);\ }\ virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(true);\ }\ p0##_type p0;\ private:\ ::testing::internal::string FormatDescription(bool negation) const {\ const ::testing::internal::string gmock_description = (description);\ if (!gmock_description.empty())\ return gmock_description;\ return ::testing::internal::FormatMatcherDescription(\ negation, #name, \ ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ ::testing::tuple<p0##_type>(p0)));\ }\ GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename arg_type>\ operator ::testing::Matcher<arg_type>() const {\ return ::testing::Matcher<arg_type>(\ new gmock_Impl<arg_type>(p0));\ }\ explicit name##MatcherP(p0##_type gmock_p0) : p0(gmock_p0) {\ }\ p0##_type p0;\ private:\ GTEST_DISALLOW_ASSIGN_(name##MatcherP);\ };\ template <typename p0##_type>\ inline name##MatcherP<p0##_type> name(p0##_type p0) {\ return name##MatcherP<p0##_type>(p0);\ }\ template <typename p0##_type>\ template <typename arg_type>\ bool name##MatcherP<p0##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ arg_type arg, \ ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ const #define MATCHER_P2(name, p0, p1, description)\ template <typename p0##_type, typename p1##_type>\ class name##MatcherP2 {\ public:\ template <typename arg_type>\ class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ public:\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1)\ : p0(gmock_p0), p1(gmock_p1) {}\ virtual bool MatchAndExplain(\ arg_type arg, ::testing::MatchResultListener* result_listener) const;\ virtual void DescribeTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(false);\ }\ virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(true);\ }\ p0##_type p0;\ p1##_type p1;\ private:\ ::testing::internal::string FormatDescription(bool negation) const {\ const ::testing::internal::string gmock_description = (description);\ if (!gmock_description.empty())\ return gmock_description;\ return ::testing::internal::FormatMatcherDescription(\ negation, #name, \ ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ ::testing::tuple<p0##_type, p1##_type>(p0, p1)));\ }\ GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename arg_type>\ operator ::testing::Matcher<arg_type>() const {\ return ::testing::Matcher<arg_type>(\ new gmock_Impl<arg_type>(p0, p1));\ }\ name##MatcherP2(p0##_type gmock_p0, p1##_type gmock_p1) : p0(gmock_p0), \ p1(gmock_p1) {\ }\ p0##_type p0;\ p1##_type p1;\ private:\ GTEST_DISALLOW_ASSIGN_(name##MatcherP2);\ };\ template <typename p0##_type, typename p1##_type>\ inline name##MatcherP2<p0##_type, p1##_type> name(p0##_type p0, \ p1##_type p1) {\ return name##MatcherP2<p0##_type, p1##_type>(p0, p1);\ }\ template <typename p0##_type, typename p1##_type>\ template <typename arg_type>\ bool name##MatcherP2<p0##_type, \ p1##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ arg_type arg, \ ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ const #define MATCHER_P3(name, p0, p1, p2, description)\ template <typename p0##_type, typename p1##_type, typename p2##_type>\ class name##MatcherP3 {\ public:\ template <typename arg_type>\ class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ public:\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2)\ : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) {}\ virtual bool MatchAndExplain(\ arg_type arg, ::testing::MatchResultListener* result_listener) const;\ virtual void DescribeTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(false);\ }\ virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(true);\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ private:\ ::testing::internal::string FormatDescription(bool negation) const {\ const ::testing::internal::string gmock_description = (description);\ if (!gmock_description.empty())\ return gmock_description;\ return ::testing::internal::FormatMatcherDescription(\ negation, #name, \ ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ ::testing::tuple<p0##_type, p1##_type, p2##_type>(p0, p1, \ p2)));\ }\ GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename arg_type>\ operator ::testing::Matcher<arg_type>() const {\ return ::testing::Matcher<arg_type>(\ new gmock_Impl<arg_type>(p0, p1, p2));\ }\ name##MatcherP3(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2) {\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ private:\ GTEST_DISALLOW_ASSIGN_(name##MatcherP3);\ };\ template <typename p0##_type, typename p1##_type, typename p2##_type>\ inline name##MatcherP3<p0##_type, p1##_type, p2##_type> name(p0##_type p0, \ p1##_type p1, p2##_type p2) {\ return name##MatcherP3<p0##_type, p1##_type, p2##_type>(p0, p1, p2);\ }\ template <typename p0##_type, typename p1##_type, typename p2##_type>\ template <typename arg_type>\ bool name##MatcherP3<p0##_type, p1##_type, \ p2##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ arg_type arg, \ ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ const #define MATCHER_P4(name, p0, p1, p2, p3, description)\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type>\ class name##MatcherP4 {\ public:\ template <typename arg_type>\ class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ public:\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3)\ : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3) {}\ virtual bool MatchAndExplain(\ arg_type arg, ::testing::MatchResultListener* result_listener) const;\ virtual void DescribeTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(false);\ }\ virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(true);\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ private:\ ::testing::internal::string FormatDescription(bool negation) const {\ const ::testing::internal::string gmock_description = (description);\ if (!gmock_description.empty())\ return gmock_description;\ return ::testing::internal::FormatMatcherDescription(\ negation, #name, \ ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ ::testing::tuple<p0##_type, p1##_type, p2##_type, \ p3##_type>(p0, p1, p2, p3)));\ }\ GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename arg_type>\ operator ::testing::Matcher<arg_type>() const {\ return ::testing::Matcher<arg_type>(\ new gmock_Impl<arg_type>(p0, p1, p2, p3));\ }\ name##MatcherP4(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2, p3##_type gmock_p3) : p0(gmock_p0), p1(gmock_p1), \ p2(gmock_p2), p3(gmock_p3) {\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ private:\ GTEST_DISALLOW_ASSIGN_(name##MatcherP4);\ };\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type>\ inline name##MatcherP4<p0##_type, p1##_type, p2##_type, \ p3##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, \ p3##_type p3) {\ return name##MatcherP4<p0##_type, p1##_type, p2##_type, p3##_type>(p0, \ p1, p2, p3);\ }\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type>\ template <typename arg_type>\ bool name##MatcherP4<p0##_type, p1##_type, p2##_type, \ p3##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ arg_type arg, \ ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ const #define MATCHER_P5(name, p0, p1, p2, p3, p4, description)\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type>\ class name##MatcherP5 {\ public:\ template <typename arg_type>\ class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ public:\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4)\ : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \ p4(gmock_p4) {}\ virtual bool MatchAndExplain(\ arg_type arg, ::testing::MatchResultListener* result_listener) const;\ virtual void DescribeTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(false);\ }\ virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(true);\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ p4##_type p4;\ private:\ ::testing::internal::string FormatDescription(bool negation) const {\ const ::testing::internal::string gmock_description = (description);\ if (!gmock_description.empty())\ return gmock_description;\ return ::testing::internal::FormatMatcherDescription(\ negation, #name, \ ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ ::testing::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type>(p0, p1, p2, p3, p4)));\ }\ GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename arg_type>\ operator ::testing::Matcher<arg_type>() const {\ return ::testing::Matcher<arg_type>(\ new gmock_Impl<arg_type>(p0, p1, p2, p3, p4));\ }\ name##MatcherP5(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2, p3##_type gmock_p3, \ p4##_type gmock_p4) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ p3(gmock_p3), p4(gmock_p4) {\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ p4##_type p4;\ private:\ GTEST_DISALLOW_ASSIGN_(name##MatcherP5);\ };\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type>\ inline name##MatcherP5<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ p4##_type p4) {\ return name##MatcherP5<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type>(p0, p1, p2, p3, p4);\ }\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type>\ template <typename arg_type>\ bool name##MatcherP5<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ arg_type arg, \ ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ const #define MATCHER_P6(name, p0, p1, p2, p3, p4, p5, description)\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type>\ class name##MatcherP6 {\ public:\ template <typename arg_type>\ class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ public:\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5)\ : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \ p4(gmock_p4), p5(gmock_p5) {}\ virtual bool MatchAndExplain(\ arg_type arg, ::testing::MatchResultListener* result_listener) const;\ virtual void DescribeTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(false);\ }\ virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(true);\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ p4##_type p4;\ p5##_type p5;\ private:\ ::testing::internal::string FormatDescription(bool negation) const {\ const ::testing::internal::string gmock_description = (description);\ if (!gmock_description.empty())\ return gmock_description;\ return ::testing::internal::FormatMatcherDescription(\ negation, #name, \ ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ ::testing::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type>(p0, p1, p2, p3, p4, p5)));\ }\ GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename arg_type>\ operator ::testing::Matcher<arg_type>() const {\ return ::testing::Matcher<arg_type>(\ new gmock_Impl<arg_type>(p0, p1, p2, p3, p4, p5));\ }\ name##MatcherP6(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ p5##_type gmock_p5) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ p3(gmock_p3), p4(gmock_p4), p5(gmock_p5) {\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ p4##_type p4;\ p5##_type p5;\ private:\ GTEST_DISALLOW_ASSIGN_(name##MatcherP6);\ };\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type>\ inline name##MatcherP6<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, \ p3##_type p3, p4##_type p4, p5##_type p5) {\ return name##MatcherP6<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type>(p0, p1, p2, p3, p4, p5);\ }\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type>\ template <typename arg_type>\ bool name##MatcherP6<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ p5##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ arg_type arg, \ ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ const #define MATCHER_P7(name, p0, p1, p2, p3, p4, p5, p6, description)\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type>\ class name##MatcherP7 {\ public:\ template <typename arg_type>\ class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ public:\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ p6##_type gmock_p6)\ : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \ p4(gmock_p4), p5(gmock_p5), p6(gmock_p6) {}\ virtual bool MatchAndExplain(\ arg_type arg, ::testing::MatchResultListener* result_listener) const;\ virtual void DescribeTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(false);\ }\ virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(true);\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ p4##_type p4;\ p5##_type p5;\ p6##_type p6;\ private:\ ::testing::internal::string FormatDescription(bool negation) const {\ const ::testing::internal::string gmock_description = (description);\ if (!gmock_description.empty())\ return gmock_description;\ return ::testing::internal::FormatMatcherDescription(\ negation, #name, \ ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ ::testing::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type>(p0, p1, p2, p3, p4, p5, \ p6)));\ }\ GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename arg_type>\ operator ::testing::Matcher<arg_type>() const {\ return ::testing::Matcher<arg_type>(\ new gmock_Impl<arg_type>(p0, p1, p2, p3, p4, p5, p6));\ }\ name##MatcherP7(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ p5##_type gmock_p5, p6##_type gmock_p6) : p0(gmock_p0), p1(gmock_p1), \ p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), \ p6(gmock_p6) {\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ p4##_type p4;\ p5##_type p5;\ p6##_type p6;\ private:\ GTEST_DISALLOW_ASSIGN_(name##MatcherP7);\ };\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type>\ inline name##MatcherP7<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type> name(p0##_type p0, p1##_type p1, \ p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \ p6##_type p6) {\ return name##MatcherP7<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type>(p0, p1, p2, p3, p4, p5, p6);\ }\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type>\ template <typename arg_type>\ bool name##MatcherP7<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ p5##_type, p6##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ arg_type arg, \ ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ const #define MATCHER_P8(name, p0, p1, p2, p3, p4, p5, p6, p7, description)\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type, typename p7##_type>\ class name##MatcherP8 {\ public:\ template <typename arg_type>\ class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ public:\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ p6##_type gmock_p6, p7##_type gmock_p7)\ : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \ p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7) {}\ virtual bool MatchAndExplain(\ arg_type arg, ::testing::MatchResultListener* result_listener) const;\ virtual void DescribeTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(false);\ }\ virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(true);\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ p4##_type p4;\ p5##_type p5;\ p6##_type p6;\ p7##_type p7;\ private:\ ::testing::internal::string FormatDescription(bool negation) const {\ const ::testing::internal::string gmock_description = (description);\ if (!gmock_description.empty())\ return gmock_description;\ return ::testing::internal::FormatMatcherDescription(\ negation, #name, \ ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ ::testing::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type, p7##_type>(p0, p1, p2, \ p3, p4, p5, p6, p7)));\ }\ GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename arg_type>\ operator ::testing::Matcher<arg_type>() const {\ return ::testing::Matcher<arg_type>(\ new gmock_Impl<arg_type>(p0, p1, p2, p3, p4, p5, p6, p7));\ }\ name##MatcherP8(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ p5##_type gmock_p5, p6##_type gmock_p6, \ p7##_type gmock_p7) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \ p7(gmock_p7) {\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ p4##_type p4;\ p5##_type p5;\ p6##_type p6;\ p7##_type p7;\ private:\ GTEST_DISALLOW_ASSIGN_(name##MatcherP8);\ };\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type, typename p7##_type>\ inline name##MatcherP8<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type, p7##_type> name(p0##_type p0, \ p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, p5##_type p5, \ p6##_type p6, p7##_type p7) {\ return name##MatcherP8<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type, p7##_type>(p0, p1, p2, p3, p4, p5, \ p6, p7);\ }\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type, typename p7##_type>\ template <typename arg_type>\ bool name##MatcherP8<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ p5##_type, p6##_type, \ p7##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ arg_type arg, \ ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ const #define MATCHER_P9(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, description)\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type, typename p7##_type, typename p8##_type>\ class name##MatcherP9 {\ public:\ template <typename arg_type>\ class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ public:\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8)\ : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \ p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \ p8(gmock_p8) {}\ virtual bool MatchAndExplain(\ arg_type arg, ::testing::MatchResultListener* result_listener) const;\ virtual void DescribeTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(false);\ }\ virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(true);\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ p4##_type p4;\ p5##_type p5;\ p6##_type p6;\ p7##_type p7;\ p8##_type p8;\ private:\ ::testing::internal::string FormatDescription(bool negation) const {\ const ::testing::internal::string gmock_description = (description);\ if (!gmock_description.empty())\ return gmock_description;\ return ::testing::internal::FormatMatcherDescription(\ negation, #name, \ ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ ::testing::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type, p7##_type, \ p8##_type>(p0, p1, p2, p3, p4, p5, p6, p7, p8)));\ }\ GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename arg_type>\ operator ::testing::Matcher<arg_type>() const {\ return ::testing::Matcher<arg_type>(\ new gmock_Impl<arg_type>(p0, p1, p2, p3, p4, p5, p6, p7, p8));\ }\ name##MatcherP9(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \ p8##_type gmock_p8) : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), \ p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \ p8(gmock_p8) {\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ p4##_type p4;\ p5##_type p5;\ p6##_type p6;\ p7##_type p7;\ p8##_type p8;\ private:\ GTEST_DISALLOW_ASSIGN_(name##MatcherP9);\ };\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type, typename p7##_type, typename p8##_type>\ inline name##MatcherP9<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type, p7##_type, \ p8##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, \ p8##_type p8) {\ return name##MatcherP9<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type, p7##_type, p8##_type>(p0, p1, p2, \ p3, p4, p5, p6, p7, p8);\ }\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type, typename p7##_type, typename p8##_type>\ template <typename arg_type>\ bool name##MatcherP9<p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, \ p5##_type, p6##_type, p7##_type, \ p8##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ arg_type arg, \ ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ const #define MATCHER_P10(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, description)\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type, typename p7##_type, typename p8##_type, \ typename p9##_type>\ class name##MatcherP10 {\ public:\ template <typename arg_type>\ class gmock_Impl : public ::testing::MatcherInterface<arg_type> {\ public:\ gmock_Impl(p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \ p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5, \ p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8, \ p9##_type gmock_p9)\ : p0(gmock_p0), p1(gmock_p1), p2(gmock_p2), p3(gmock_p3), \ p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), p7(gmock_p7), \ p8(gmock_p8), p9(gmock_p9) {}\ virtual bool MatchAndExplain(\ arg_type arg, ::testing::MatchResultListener* result_listener) const;\ virtual void DescribeTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(false);\ }\ virtual void DescribeNegationTo(::std::ostream* gmock_os) const {\ *gmock_os << FormatDescription(true);\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ p4##_type p4;\ p5##_type p5;\ p6##_type p6;\ p7##_type p7;\ p8##_type p8;\ p9##_type p9;\ private:\ ::testing::internal::string FormatDescription(bool negation) const {\ const ::testing::internal::string gmock_description = (description);\ if (!gmock_description.empty())\ return gmock_description;\ return ::testing::internal::FormatMatcherDescription(\ negation, #name, \ ::testing::internal::UniversalTersePrintTupleFieldsToStrings(\ ::testing::tuple<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, \ p9##_type>(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9)));\ }\ GTEST_DISALLOW_ASSIGN_(gmock_Impl);\ };\ template <typename arg_type>\ operator ::testing::Matcher<arg_type>() const {\ return ::testing::Matcher<arg_type>(\ new gmock_Impl<arg_type>(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9));\ }\ name##MatcherP10(p0##_type gmock_p0, p1##_type gmock_p1, \ p2##_type gmock_p2, p3##_type gmock_p3, p4##_type gmock_p4, \ p5##_type gmock_p5, p6##_type gmock_p6, p7##_type gmock_p7, \ p8##_type gmock_p8, p9##_type gmock_p9) : p0(gmock_p0), p1(gmock_p1), \ p2(gmock_p2), p3(gmock_p3), p4(gmock_p4), p5(gmock_p5), p6(gmock_p6), \ p7(gmock_p7), p8(gmock_p8), p9(gmock_p9) {\ }\ p0##_type p0;\ p1##_type p1;\ p2##_type p2;\ p3##_type p3;\ p4##_type p4;\ p5##_type p5;\ p6##_type p6;\ p7##_type p7;\ p8##_type p8;\ p9##_type p9;\ private:\ GTEST_DISALLOW_ASSIGN_(name##MatcherP10);\ };\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type, typename p7##_type, typename p8##_type, \ typename p9##_type>\ inline name##MatcherP10<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, \ p9##_type> name(p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, \ p4##_type p4, p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, \ p9##_type p9) {\ return name##MatcherP10<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, p9##_type>(p0, \ p1, p2, p3, p4, p5, p6, p7, p8, p9);\ }\ template <typename p0##_type, typename p1##_type, typename p2##_type, \ typename p3##_type, typename p4##_type, typename p5##_type, \ typename p6##_type, typename p7##_type, typename p8##_type, \ typename p9##_type>\ template <typename arg_type>\ bool name##MatcherP10<p0##_type, p1##_type, p2##_type, p3##_type, \ p4##_type, p5##_type, p6##_type, p7##_type, p8##_type, \ p9##_type>::gmock_Impl<arg_type>::MatchAndExplain(\ arg_type arg, \ ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_)\ const #endif // GMOCK_INCLUDE_GMOCK_GMOCK_GENERATED_MATCHERS_H_
0
repos/DirectXShaderCompiler/utils/unittest/googlemock/include
repos/DirectXShaderCompiler/utils/unittest/googlemock/include/gmock/gmock-more-actions.h
// 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. // // Author: [email protected] (Zhanyong Wan) // Google Mock - a framework for writing C++ mock classes. // // This file implements some actions that depend on gmock-generated-actions.h. #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_ #include <algorithm> #include "gmock/gmock-generated-actions.h" namespace testing { namespace internal { // Implements the Invoke(f) action. The template argument // FunctionImpl is the implementation type of f, which can be either a // function pointer or a functor. Invoke(f) can be used as an // Action<F> as long as f's type is compatible with F (i.e. f can be // assigned to a tr1::function<F>). template <typename FunctionImpl> class InvokeAction { public: // The c'tor makes a copy of function_impl (either a function // pointer or a functor). explicit InvokeAction(FunctionImpl function_impl) : function_impl_(function_impl) {} template <typename Result, typename ArgumentTuple> Result Perform(const ArgumentTuple& args) { return InvokeHelper<Result, ArgumentTuple>::Invoke(function_impl_, args); } private: FunctionImpl function_impl_; GTEST_DISALLOW_ASSIGN_(InvokeAction); }; // Implements the Invoke(object_ptr, &Class::Method) action. template <class Class, typename MethodPtr> class InvokeMethodAction { public: InvokeMethodAction(Class* obj_ptr, MethodPtr method_ptr) : method_ptr_(method_ptr), obj_ptr_(obj_ptr) {} template <typename Result, typename ArgumentTuple> Result Perform(const ArgumentTuple& args) const { return InvokeHelper<Result, ArgumentTuple>::InvokeMethod( obj_ptr_, method_ptr_, args); } private: // The order of these members matters. Reversing the order can trigger // warning C4121 in MSVC (see // http://computer-programming-forum.com/7-vc.net/6fbc30265f860ad1.htm ). const MethodPtr method_ptr_; Class* const obj_ptr_; GTEST_DISALLOW_ASSIGN_(InvokeMethodAction); }; // An internal replacement for std::copy which mimics its behavior. This is // necessary because Visual Studio deprecates ::std::copy, issuing warning 4996. // However Visual Studio 2010 and later do not honor #pragmas which disable that // warning. template<typename InputIterator, typename OutputIterator> inline OutputIterator CopyElements(InputIterator first, InputIterator last, OutputIterator output) { for (; first != last; ++first, ++output) { *output = *first; } return output; } } // namespace internal // Various overloads for Invoke(). // Creates an action that invokes 'function_impl' with the mock // function's arguments. template <typename FunctionImpl> PolymorphicAction<internal::InvokeAction<FunctionImpl> > Invoke( FunctionImpl function_impl) { return MakePolymorphicAction( internal::InvokeAction<FunctionImpl>(function_impl)); } // Creates an action that invokes the given method on the given object // with the mock function's arguments. template <class Class, typename MethodPtr> PolymorphicAction<internal::InvokeMethodAction<Class, MethodPtr> > Invoke( Class* obj_ptr, MethodPtr method_ptr) { return MakePolymorphicAction( internal::InvokeMethodAction<Class, MethodPtr>(obj_ptr, method_ptr)); } // WithoutArgs(inner_action) can be used in a mock function with a // non-empty argument list to perform inner_action, which takes no // argument. In other words, it adapts an action accepting no // argument to one that accepts (and ignores) arguments. template <typename InnerAction> inline internal::WithArgsAction<InnerAction> WithoutArgs(const InnerAction& action) { return internal::WithArgsAction<InnerAction>(action); } // WithArg<k>(an_action) creates an action that passes the k-th // (0-based) argument of the mock function to an_action and performs // it. It adapts an action accepting one argument to one that accepts // multiple arguments. For convenience, we also provide // WithArgs<k>(an_action) (defined below) as a synonym. template <int k, typename InnerAction> inline internal::WithArgsAction<InnerAction, k> WithArg(const InnerAction& action) { return internal::WithArgsAction<InnerAction, k>(action); } // The ACTION*() macros trigger warning C4100 (unreferenced formal // parameter) in MSVC with -W4. Unfortunately they cannot be fixed in // the macro definition, as the warnings are generated when the macro // is expanded and macro expansion cannot contain #pragma. Therefore // we suppress them here. #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable:4100) #endif // Action ReturnArg<k>() returns the k-th argument of the mock function. ACTION_TEMPLATE(ReturnArg, HAS_1_TEMPLATE_PARAMS(int, k), AND_0_VALUE_PARAMS()) { return ::testing::get<k>(args); } // Action SaveArg<k>(pointer) saves the k-th (0-based) argument of the // mock function to *pointer. ACTION_TEMPLATE(SaveArg, HAS_1_TEMPLATE_PARAMS(int, k), AND_1_VALUE_PARAMS(pointer)) { *pointer = ::testing::get<k>(args); } // Action SaveArgPointee<k>(pointer) saves the value pointed to // by the k-th (0-based) argument of the mock function to *pointer. ACTION_TEMPLATE(SaveArgPointee, HAS_1_TEMPLATE_PARAMS(int, k), AND_1_VALUE_PARAMS(pointer)) { *pointer = *::testing::get<k>(args); } // Action SetArgReferee<k>(value) assigns 'value' to the variable // referenced by the k-th (0-based) argument of the mock function. ACTION_TEMPLATE(SetArgReferee, HAS_1_TEMPLATE_PARAMS(int, k), AND_1_VALUE_PARAMS(value)) { typedef typename ::testing::tuple_element<k, args_type>::type argk_type; // Ensures that argument #k is a reference. If you get a compiler // error on the next line, you are using SetArgReferee<k>(value) in // a mock function whose k-th (0-based) argument is not a reference. GTEST_COMPILE_ASSERT_(internal::is_reference<argk_type>::value, SetArgReferee_must_be_used_with_a_reference_argument); ::testing::get<k>(args) = value; } // Action SetArrayArgument<k>(first, last) copies the elements in // source range [first, last) to the array pointed to by the k-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. ACTION_TEMPLATE(SetArrayArgument, HAS_1_TEMPLATE_PARAMS(int, k), AND_2_VALUE_PARAMS(first, last)) { // Visual Studio deprecates ::std::copy, so we use our own copy in that case. #ifdef _MSC_VER internal::CopyElements(first, last, ::testing::get<k>(args)); #else ::std::copy(first, last, ::testing::get<k>(args)); #endif } // Action DeleteArg<k>() deletes the k-th (0-based) argument of the mock // function. ACTION_TEMPLATE(DeleteArg, HAS_1_TEMPLATE_PARAMS(int, k), AND_0_VALUE_PARAMS()) { delete ::testing::get<k>(args); } // This action returns the value pointed to by 'pointer'. ACTION_P(ReturnPointee, pointer) { return *pointer; } // Action Throw(exception) can be used in a mock function of any type // to throw the given exception. Any copyable value can be thrown. #if GTEST_HAS_EXCEPTIONS // Suppresses the 'unreachable code' warning that VC generates in opt modes. # ifdef _MSC_VER # pragma warning(push) // Saves the current warning state. # pragma warning(disable:4702) // Temporarily disables warning 4702. # endif ACTION_P(Throw, exception) { throw exception; } # ifdef _MSC_VER # pragma warning(pop) // Restores the warning state. # endif #endif // GTEST_HAS_EXCEPTIONS #ifdef _MSC_VER # pragma warning(pop) #endif } // namespace testing #endif // GMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_
0
repos/DirectXShaderCompiler/utils/unittest/googlemock/include
repos/DirectXShaderCompiler/utils/unittest/googlemock/include/gmock/gmock-more-matchers.h
// Copyright 2013, 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. // // Author: [email protected] (Marcus Boerger) // Google Mock - a framework for writing C++ mock classes. // // This file implements some matchers that depend on gmock-generated-matchers.h. // // Note that tests are implemented in gmock-matchers_test.cc rather than // gmock-more-matchers-test.cc. #ifndef GMOCK_GMOCK_MORE_MATCHERS_H_ #define GMOCK_GMOCK_MORE_MATCHERS_H_ #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable:4100) #endif #ifdef __clang__ #if __has_warning("-Wdeprecated-copy") #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-copy" #endif #endif #include "gmock/gmock-generated-matchers.h" namespace testing { // Defines a matcher that matches an empty container. The container must // support both size() and empty(), which all STL-like containers provide. MATCHER(IsEmpty, negation ? "isn't empty" : "is empty") { if (arg.empty()) { return true; } *result_listener << "whose size is " << arg.size(); return false; } } // namespace testing #ifdef __clang__ #if __has_warning("-Wdeprecated-copy") #pragma clang diagnostic pop #endif #endif #ifdef _MSC_VER # pragma warning(pop) #endif #endif // GMOCK_GMOCK_MORE_MATCHERS_H_
0
repos/DirectXShaderCompiler/utils/unittest/googlemock/include
repos/DirectXShaderCompiler/utils/unittest/googlemock/include/gmock/gmock-actions.h
// 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. // // Author: [email protected] (Zhanyong Wan) // Google Mock - a framework for writing C++ mock classes. // // This file implements some commonly used actions. #ifndef GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ #define GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_ #ifndef _WIN32_WCE # include <errno.h> #endif #include <algorithm> #include <string> #include "gmock/internal/gmock-internal-utils.h" #include "gmock/internal/gmock-port.h" #if GTEST_HAS_STD_TYPE_TRAITS_ // Defined by gtest-port.h via gmock-port.h. #include <type_traits> #endif #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable:4100) #endif #ifdef __clang__ #if __has_warning("-Wdeprecated-copy") #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-copy" #endif #endif namespace testing { // To implement an action Foo, define: // 1. a class FooAction that implements the ActionInterface interface, and // 2. a factory function that creates an Action object from a // const FooAction*. // // The two-level delegation design follows that of Matcher, providing // consistency for extension developers. It also eases ownership // management as Action objects can now be copied like plain values. namespace internal { template <typename F1, typename F2> class ActionAdaptor; // BuiltInDefaultValueGetter<T, true>::Get() returns a // default-constructed T value. BuiltInDefaultValueGetter<T, // false>::Get() crashes with an error. // // This primary template is used when kDefaultConstructible is true. template <typename T, bool kDefaultConstructible> struct BuiltInDefaultValueGetter { static T Get() { return T(); } }; template <typename T> struct BuiltInDefaultValueGetter<T, false> { static T Get() { Assert(false, __FILE__, __LINE__, "Default action undefined for the function return type."); return internal::Invalid<T>(); // The above statement will never be reached, but is required in // order for this function to compile. } }; // BuiltInDefaultValue<T>::Get() returns the "built-in" default value // for type T, which is NULL when T is a raw pointer type, 0 when T is // a numeric type, false when T is bool, or "" when T is string or // std::string. In addition, in C++11 and above, it turns a // default-constructed T value if T is default constructible. For any // other type T, the built-in default T value is undefined, and the // function will abort the process. template <typename T> class BuiltInDefaultValue { public: #if GTEST_HAS_STD_TYPE_TRAITS_ // This function returns true iff type T has a built-in default value. static bool Exists() { return ::std::is_default_constructible<T>::value; } static T Get() { return BuiltInDefaultValueGetter< T, ::std::is_default_constructible<T>::value>::Get(); } #else // GTEST_HAS_STD_TYPE_TRAITS_ // This function returns true iff type T has a built-in default value. static bool Exists() { return false; } static T Get() { return BuiltInDefaultValueGetter<T, false>::Get(); } #endif // GTEST_HAS_STD_TYPE_TRAITS_ }; // This partial specialization says that we use the same built-in // default value for T and const T. template <typename T> class BuiltInDefaultValue<const T> { public: static bool Exists() { return BuiltInDefaultValue<T>::Exists(); } static T Get() { return BuiltInDefaultValue<T>::Get(); } }; // This partial specialization defines the default values for pointer // types. template <typename T> class BuiltInDefaultValue<T*> { public: static bool Exists() { return true; } static T* Get() { return NULL; } }; // The following specializations define the default values for // specific types we care about. #define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \ template <> \ class BuiltInDefaultValue<type> { \ public: \ static bool Exists() { return true; } \ static type Get() { return value; } \ } GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, ); // NOLINT #if GTEST_HAS_GLOBAL_STRING GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::string, ""); #endif // GTEST_HAS_GLOBAL_STRING GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, ""); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\0'); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\0'); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\0'); // There's no need for a default action for signed wchar_t, as that // type is the same as wchar_t for gcc, and invalid for MSVC. // // There's also no need for a default action for unsigned wchar_t, as // that type is the same as unsigned int for gcc, and invalid for // MSVC. #if GMOCK_WCHAR_T_IS_NATIVE_ GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U); // NOLINT #endif GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U); // NOLINT GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0); // NOLINT GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL); // NOLINT GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L); // NOLINT GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(UInt64, 0); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(Int64, 0); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0); GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0); #undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_ } // namespace internal // When an unexpected function call is encountered, Google Mock will // let it return a default value if the user has specified one for its // return type, or if the return type has a built-in default value; // otherwise Google Mock won't know what value to return and will have // to abort the process. // // The DefaultValue<T> class 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). The usage is: // // // Sets the default value for type T to be foo. // DefaultValue<T>::Set(foo); template <typename T> class DefaultValue { public: // Sets the default value for type T; requires T to be // copy-constructable and have a public destructor. static void Set(T x) { delete producer_; producer_ = new FixedValueProducer(x); } // Provides a factory function to be called to generate the default value. // This method can be used even if T is only move-constructible, but it is not // limited to that case. typedef T (*FactoryFunction)(); static void SetFactory(FactoryFunction factory) { delete producer_; producer_ = new FactoryValueProducer(factory); } // Unsets the default value for type T. static void Clear() { delete producer_; producer_ = NULL; } // Returns true iff the user has set the default value for type T. static bool IsSet() { return producer_ != NULL; } // Returns true if T has a default return value set by the user or there // exists a built-in default value. static bool Exists() { return IsSet() || internal::BuiltInDefaultValue<T>::Exists(); } // Returns the default value for type T if the user has set one; // otherwise returns the built-in default value. Requires that Exists() // is true, which ensures that the return value is well-defined. static T Get() { return producer_ == NULL ? internal::BuiltInDefaultValue<T>::Get() : producer_->Produce(); } private: class ValueProducer { public: virtual ~ValueProducer() {} virtual T Produce() = 0; }; class FixedValueProducer : public ValueProducer { public: explicit FixedValueProducer(T value) : value_(value) {} virtual T Produce() { return value_; } private: const T value_; GTEST_DISALLOW_COPY_AND_ASSIGN_(FixedValueProducer); }; class FactoryValueProducer : public ValueProducer { public: explicit FactoryValueProducer(FactoryFunction factory) : factory_(factory) {} virtual T Produce() { return factory_(); } private: const FactoryFunction factory_; GTEST_DISALLOW_COPY_AND_ASSIGN_(FactoryValueProducer); }; static ValueProducer* producer_; }; // This partial specialization allows a user to set default values for // reference types. template <typename T> class DefaultValue<T&> { public: // Sets the default value for type T&. static void Set(T& x) { // NOLINT address_ = &x; } // Unsets the default value for type T&. static void Clear() { address_ = NULL; } // Returns true iff the user has set the default value for type T&. static bool IsSet() { return address_ != NULL; } // Returns true if T has a default return value set by the user or there // exists a built-in default value. static bool Exists() { return IsSet() || internal::BuiltInDefaultValue<T&>::Exists(); } // Returns the default value for type T& if the user has set one; // otherwise returns the built-in default value if there is one; // otherwise aborts the process. static T& Get() { return address_ == NULL ? internal::BuiltInDefaultValue<T&>::Get() : *address_; } private: static T* address_; }; // This specialization allows DefaultValue<void>::Get() to // compile. template <> class DefaultValue<void> { public: static bool Exists() { return true; } static void Get() {} }; // Points to the user-set default value for type T. template <typename T> typename DefaultValue<T>::ValueProducer* DefaultValue<T>::producer_ = NULL; // Points to the user-set default value for type T&. template <typename T> T* DefaultValue<T&>::address_ = NULL; // Implement this interface to define an action for function type F. template <typename F> class ActionInterface { public: typedef typename internal::Function<F>::Result Result; typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; ActionInterface() {} virtual ~ActionInterface() {} // Performs the action. This method is not const, as in general an // action can have side effects and be stateful. For example, a // get-the-next-element-from-the-collection action will need to // remember the current element. virtual Result Perform(const ArgumentTuple& args) = 0; private: GTEST_DISALLOW_COPY_AND_ASSIGN_(ActionInterface); }; // An Action<F> is a copyable and IMMUTABLE (except by assignment) // object that represents an action to be taken when a mock function // of type F is called. The implementation of Action<T> is just a // linked_ptr to const ActionInterface<T>, so copying is fairly cheap. // Don't inherit from Action! // // You can view an object implementing ActionInterface<F> as a // concrete action (including its current state), and an Action<F> // object as a handle to it. template <typename F> class Action { public: typedef typename internal::Function<F>::Result Result; typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; // Constructs a null Action. Needed for storing Action objects in // STL containers. Action() : impl_(NULL) {} // Constructs an Action from its implementation. A NULL impl is // used to represent the "do-default" action. explicit Action(ActionInterface<F>* impl) : impl_(impl) {} // Copy constructor. Action(const Action& action) : impl_(action.impl_) {} // This constructor allows us to turn an Action<Func> object into an // Action<F>, as long as F's arguments can be implicitly converted // to Func's and Func's return type can be implicitly converted to // F's. template <typename Func> explicit Action(const Action<Func>& action); // Returns true iff this is the DoDefault() action. bool IsDoDefault() const { return impl_.get() == NULL; } // Performs the action. Note that this method is const even though // the corresponding method in ActionInterface is not. The reason // is that a const Action<F> means that it cannot be re-bound to // another concrete action, not that the concrete action it binds to // cannot change state. (Think of the difference between a const // pointer and a pointer to const.) Result Perform(const ArgumentTuple& args) const { internal::Assert( !IsDoDefault(), __FILE__, __LINE__, "You are using DoDefault() inside a composite action like " "DoAll() or WithArgs(). This is not supported for technical " "reasons. Please instead spell out the default action, or " "assign the default action to an Action variable and use " "the variable in various places."); return impl_->Perform(args); } private: template <typename F1, typename F2> friend class internal::ActionAdaptor; internal::linked_ptr<ActionInterface<F> > impl_; }; // The PolymorphicAction class template makes it easy to implement a // polymorphic action (i.e. an action that can be used in mock // functions of than one type, e.g. Return()). // // To define a polymorphic action, a user first provides a COPYABLE // implementation class that has a Perform() method template: // // class FooAction { // public: // template <typename Result, typename ArgumentTuple> // Result Perform(const ArgumentTuple& args) const { // // Processes the arguments and returns a result, using // // tr1::get<N>(args) to get the N-th (0-based) argument in the tuple. // } // ... // }; // // Then the user creates the polymorphic action using // MakePolymorphicAction(object) where object has type FooAction. See // the definition of Return(void) and SetArgumentPointee<N>(value) for // complete examples. template <typename Impl> class PolymorphicAction { public: explicit PolymorphicAction(const Impl& impl) : impl_(impl) {} template <typename F> operator Action<F>() const { return Action<F>(new MonomorphicImpl<F>(impl_)); } private: template <typename F> class MonomorphicImpl : public ActionInterface<F> { public: typedef typename internal::Function<F>::Result Result; typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {} virtual Result Perform(const ArgumentTuple& args) { return impl_.template Perform<Result>(args); } private: Impl impl_; GTEST_DISALLOW_ASSIGN_(MonomorphicImpl); }; Impl impl_; GTEST_DISALLOW_ASSIGN_(PolymorphicAction); }; // Creates an Action from its implementation and returns it. The // created Action object owns the implementation. template <typename F> Action<F> MakeAction(ActionInterface<F>* impl) { return Action<F>(impl); } // Creates a polymorphic action from its implementation. This is // easier to use than the PolymorphicAction<Impl> constructor as it // doesn't require you to explicitly write the template argument, e.g. // // MakePolymorphicAction(foo); // vs // PolymorphicAction<TypeOfFoo>(foo); template <typename Impl> inline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) { return PolymorphicAction<Impl>(impl); } namespace internal { // Allows an Action<F2> object to pose as an Action<F1>, as long as F2 // and F1 are compatible. template <typename F1, typename F2> class ActionAdaptor : public ActionInterface<F1> { public: typedef typename internal::Function<F1>::Result Result; typedef typename internal::Function<F1>::ArgumentTuple ArgumentTuple; explicit ActionAdaptor(const Action<F2>& from) : impl_(from.impl_) {} virtual Result Perform(const ArgumentTuple& args) { return impl_->Perform(args); } private: const internal::linked_ptr<ActionInterface<F2> > impl_; GTEST_DISALLOW_ASSIGN_(ActionAdaptor); }; // Helper struct to specialize ReturnAction to execute a move instead of a copy // on return. Useful for move-only types, but could be used on any type. template <typename T> struct ByMoveWrapper { explicit ByMoveWrapper(T value) : payload(internal::move(value)) {} T payload; }; // Implements the polymorphic Return(x) action, which can be used in // any function that returns the type of x, regardless of the argument // types. // // Note: The value passed into Return must be converted into // Function<F>::Result when this action is cast to Action<F> rather than // when that action is performed. This is important in scenarios like // // MOCK_METHOD1(Method, T(U)); // ... // { // Foo foo; // X x(&foo); // EXPECT_CALL(mock, Method(_)).WillOnce(Return(x)); // } // // In the example above the variable x holds reference to foo which leaves // scope and gets destroyed. If copying X just copies a reference to foo, // that copy will be left with a hanging reference. If conversion to T // makes a copy of foo, the above code is safe. To support that scenario, we // need to make sure that the type conversion happens inside the EXPECT_CALL // statement, and conversion of the result of Return to Action<T(U)> is a // good place for that. // template <typename R> class ReturnAction { public: // Constructs a ReturnAction object from the value to be returned. // 'value' is passed by value instead of by const reference in order // to allow Return("string literal") to compile. explicit ReturnAction(R value) : value_(new R(internal::move(value))) {} // This template type conversion operator allows Return(x) to be // used in ANY function that returns x's type. template <typename F> operator Action<F>() const { // Assert statement belongs here because this is the best place to verify // conditions on F. It produces the clearest error messages // in most compilers. // Impl really belongs in this scope as a local class but can't // because MSVC produces duplicate symbols in different translation units // in this case. Until MS fixes that bug we put Impl into the class scope // and put the typedef both here (for use in assert statement) and // in the Impl class. But both definitions must be the same. typedef typename Function<F>::Result Result; GTEST_COMPILE_ASSERT_( !is_reference<Result>::value, use_ReturnRef_instead_of_Return_to_return_a_reference); return Action<F>(new Impl<R, F>(value_)); } private: // Implements the Return(x) action for a particular function type F. template <typename R_, typename F> class Impl : public ActionInterface<F> { public: typedef typename Function<F>::Result Result; typedef typename Function<F>::ArgumentTuple ArgumentTuple; // The implicit cast is necessary when Result has more than one // single-argument constructor (e.g. Result is std::vector<int>) and R // has a type conversion operator template. In that case, value_(value) // won't compile as the compiler doesn't known which constructor of // Result to call. ImplicitCast_ forces the compiler to convert R to // Result without considering explicit constructors, thus resolving the // ambiguity. value_ is then initialized using its copy constructor. explicit Impl(const linked_ptr<R>& value) : value_before_cast_(*value), value_(ImplicitCast_<Result>(value_before_cast_)) {} virtual Result Perform(const ArgumentTuple&) { return value_; } private: GTEST_COMPILE_ASSERT_(!is_reference<Result>::value, Result_cannot_be_a_reference_type); // We save the value before casting just in case it is being cast to a // wrapper type. R value_before_cast_; Result value_; GTEST_DISALLOW_COPY_AND_ASSIGN_(Impl); }; // Partially specialize for ByMoveWrapper. This version of ReturnAction will // move its contents instead. template <typename R_, typename F> class Impl<ByMoveWrapper<R_>, F> : public ActionInterface<F> { public: typedef typename Function<F>::Result Result; typedef typename Function<F>::ArgumentTuple ArgumentTuple; explicit Impl(const linked_ptr<R>& wrapper) : performed_(false), wrapper_(wrapper) {} virtual Result Perform(const ArgumentTuple&) { GTEST_CHECK_(!performed_) << "A ByMove() action should only be performed once."; performed_ = true; return internal::move(wrapper_->payload); } private: bool performed_; const linked_ptr<R> wrapper_; GTEST_DISALLOW_ASSIGN_(Impl); }; const linked_ptr<R> value_; GTEST_DISALLOW_ASSIGN_(ReturnAction); }; // Implements the ReturnNull() action. class ReturnNullAction { public: // Allows ReturnNull() to be used in any pointer-returning function. In C++11 // this is enforced by returning nullptr, and in non-C++11 by asserting a // pointer type on compile time. template <typename Result, typename ArgumentTuple> static Result Perform(const ArgumentTuple&) { #if GTEST_LANG_CXX11 return nullptr; #else GTEST_COMPILE_ASSERT_(internal::is_pointer<Result>::value, ReturnNull_can_be_used_to_return_a_pointer_only); return NULL; #endif // GTEST_LANG_CXX11 } }; // Implements the Return() action. class ReturnVoidAction { public: // Allows Return() to be used in any void-returning function. template <typename Result, typename ArgumentTuple> static void Perform(const ArgumentTuple&) { CompileAssertTypesEqual<void, Result>(); } }; // Implements the polymorphic ReturnRef(x) action, which can be used // in any function that returns a reference to the type of x, // regardless of the argument types. template <typename T> class ReturnRefAction { public: // Constructs a ReturnRefAction object from the reference to be returned. explicit ReturnRefAction(T& ref) : ref_(ref) {} // NOLINT // This template type conversion operator allows ReturnRef(x) to be // used in ANY function that returns a reference to x's type. template <typename F> operator Action<F>() const { typedef typename Function<F>::Result Result; // Asserts that the function return type is a reference. This // catches the user error of using ReturnRef(x) when Return(x) // should be used, and generates some helpful error message. GTEST_COMPILE_ASSERT_(internal::is_reference<Result>::value, use_Return_instead_of_ReturnRef_to_return_a_value); return Action<F>(new Impl<F>(ref_)); } private: // Implements the ReturnRef(x) action for a particular function type F. template <typename F> class Impl : public ActionInterface<F> { public: typedef typename Function<F>::Result Result; typedef typename Function<F>::ArgumentTuple ArgumentTuple; explicit Impl(T& ref) : ref_(ref) {} // NOLINT virtual Result Perform(const ArgumentTuple&) { return ref_; } private: T& ref_; GTEST_DISALLOW_ASSIGN_(Impl); }; T& ref_; GTEST_DISALLOW_ASSIGN_(ReturnRefAction); }; // Implements the polymorphic ReturnRefOfCopy(x) action, which can be // used in any function that returns a reference to the type of x, // regardless of the argument types. template <typename T> class ReturnRefOfCopyAction { public: // Constructs a ReturnRefOfCopyAction object from the reference to // be returned. explicit ReturnRefOfCopyAction(const T& value) : value_(value) {} // NOLINT // This template type conversion operator allows ReturnRefOfCopy(x) to be // used in ANY function that returns a reference to x's type. template <typename F> operator Action<F>() const { typedef typename Function<F>::Result Result; // Asserts that the function return type is a reference. This // catches the user error of using ReturnRefOfCopy(x) when Return(x) // should be used, and generates some helpful error message. GTEST_COMPILE_ASSERT_( internal::is_reference<Result>::value, use_Return_instead_of_ReturnRefOfCopy_to_return_a_value); return Action<F>(new Impl<F>(value_)); } private: // Implements the ReturnRefOfCopy(x) action for a particular function type F. template <typename F> class Impl : public ActionInterface<F> { public: typedef typename Function<F>::Result Result; typedef typename Function<F>::ArgumentTuple ArgumentTuple; explicit Impl(const T& value) : value_(value) {} // NOLINT virtual Result Perform(const ArgumentTuple&) { return value_; } private: T value_; GTEST_DISALLOW_ASSIGN_(Impl); }; const T value_; GTEST_DISALLOW_ASSIGN_(ReturnRefOfCopyAction); }; // Implements the polymorphic DoDefault() action. class DoDefaultAction { public: // This template type conversion operator allows DoDefault() to be // used in any function. template <typename F> operator Action<F>() const { return Action<F>(NULL); } }; // Implements the Assign action to set a given pointer referent to a // particular value. template <typename T1, typename T2> class AssignAction { public: AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {} template <typename Result, typename ArgumentTuple> void Perform(const ArgumentTuple& /* args */) const { *ptr_ = value_; } private: T1* const ptr_; const T2 value_; GTEST_DISALLOW_ASSIGN_(AssignAction); }; #if !GTEST_OS_WINDOWS_MOBILE // Implements the SetErrnoAndReturn action to simulate return from // various system calls and libc functions. template <typename T> class SetErrnoAndReturnAction { public: SetErrnoAndReturnAction(int errno_value, T result) : errno_(errno_value), result_(result) {} template <typename Result, typename ArgumentTuple> Result Perform(const ArgumentTuple& /* args */) const { errno = errno_; return result_; } private: const int errno_; const T result_; GTEST_DISALLOW_ASSIGN_(SetErrnoAndReturnAction); }; #endif // !GTEST_OS_WINDOWS_MOBILE // Implements the SetArgumentPointee<N>(x) action for any function // whose N-th argument (0-based) is a pointer to x's type. The // template parameter kIsProto is true iff type A is ProtocolMessage, // proto2::Message, or a sub-class of those. template <size_t N, typename A, bool kIsProto> class SetArgumentPointeeAction { public: // Constructs an action that sets the variable pointed to by the // N-th function argument to 'value'. explicit SetArgumentPointeeAction(const A& value) : value_(value) {} template <typename Result, typename ArgumentTuple> void Perform(const ArgumentTuple& args) const { CompileAssertTypesEqual<void, Result>(); *::testing::get<N>(args) = value_; } private: const A value_; GTEST_DISALLOW_ASSIGN_(SetArgumentPointeeAction); }; template <size_t N, typename Proto> class SetArgumentPointeeAction<N, Proto, true> { public: // Constructs an action that sets the variable pointed to by the // N-th function argument to 'proto'. Both ProtocolMessage and // proto2::Message have the CopyFrom() method, so the same // implementation works for both. explicit SetArgumentPointeeAction(const Proto& proto) : proto_(new Proto) { proto_->CopyFrom(proto); } template <typename Result, typename ArgumentTuple> void Perform(const ArgumentTuple& args) const { CompileAssertTypesEqual<void, Result>(); ::testing::get<N>(args)->CopyFrom(*proto_); } private: const internal::linked_ptr<Proto> proto_; GTEST_DISALLOW_ASSIGN_(SetArgumentPointeeAction); }; // Implements the InvokeWithoutArgs(f) action. The template argument // FunctionImpl is the implementation type of f, which can be either a // function pointer or a functor. InvokeWithoutArgs(f) can be used as an // Action<F> as long as f's type is compatible with F (i.e. f can be // assigned to a tr1::function<F>). template <typename FunctionImpl> class InvokeWithoutArgsAction { public: // The c'tor makes a copy of function_impl (either a function // pointer or a functor). explicit InvokeWithoutArgsAction(FunctionImpl function_impl) : function_impl_(function_impl) {} // Allows InvokeWithoutArgs(f) to be used as any action whose type is // compatible with f. template <typename Result, typename ArgumentTuple> Result Perform(const ArgumentTuple&) { return function_impl_(); } private: FunctionImpl function_impl_; GTEST_DISALLOW_ASSIGN_(InvokeWithoutArgsAction); }; // Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action. template <class Class, typename MethodPtr> class InvokeMethodWithoutArgsAction { public: InvokeMethodWithoutArgsAction(Class* obj_ptr, MethodPtr method_ptr) : obj_ptr_(obj_ptr), method_ptr_(method_ptr) {} template <typename Result, typename ArgumentTuple> Result Perform(const ArgumentTuple&) const { return (obj_ptr_->*method_ptr_)(); } private: Class* const obj_ptr_; const MethodPtr method_ptr_; GTEST_DISALLOW_ASSIGN_(InvokeMethodWithoutArgsAction); }; // Implements the IgnoreResult(action) action. template <typename A> class IgnoreResultAction { public: explicit IgnoreResultAction(const A& action) : action_(action) {} template <typename F> operator Action<F>() const { // Assert statement belongs here because this is the best place to verify // conditions on F. It produces the clearest error messages // in most compilers. // Impl really belongs in this scope as a local class but can't // because MSVC produces duplicate symbols in different translation units // in this case. Until MS fixes that bug we put Impl into the class scope // and put the typedef both here (for use in assert statement) and // in the Impl class. But both definitions must be the same. typedef typename internal::Function<F>::Result Result; // Asserts at compile time that F returns void. CompileAssertTypesEqual<void, Result>(); return Action<F>(new Impl<F>(action_)); } private: template <typename F> class Impl : public ActionInterface<F> { public: typedef typename internal::Function<F>::Result Result; typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple; explicit Impl(const A& action) : action_(action) {} virtual void Perform(const ArgumentTuple& args) { // Performs the action and ignores its result. action_.Perform(args); } private: // Type OriginalFunction is the same as F except that its return // type is IgnoredValue. typedef typename internal::Function<F>::MakeResultIgnoredValue OriginalFunction; const Action<OriginalFunction> action_; GTEST_DISALLOW_ASSIGN_(Impl); }; const A action_; GTEST_DISALLOW_ASSIGN_(IgnoreResultAction); }; // A ReferenceWrapper<T> object represents a reference to type T, // which can be either const or not. It can be explicitly converted // from, and implicitly converted to, a T&. Unlike a reference, // ReferenceWrapper<T> can be copied and can survive template type // inference. This is used to support by-reference arguments in the // InvokeArgument<N>(...) action. The idea was from "reference // wrappers" in tr1, which we don't have in our source tree yet. template <typename T> class ReferenceWrapper { public: // Constructs a ReferenceWrapper<T> object from a T&. explicit ReferenceWrapper(T& l_value) : pointer_(&l_value) {} // NOLINT // Allows a ReferenceWrapper<T> object to be implicitly converted to // a T&. operator T&() const { return *pointer_; } private: T* pointer_; }; // Allows the expression ByRef(x) to be printed as a reference to x. template <typename T> void PrintTo(const ReferenceWrapper<T>& ref, ::std::ostream* os) { T& value = ref; UniversalPrinter<T&>::Print(value, os); } // Does two actions sequentially. Used for implementing the DoAll(a1, // a2, ...) action. template <typename Action1, typename Action2> class DoBothAction { public: DoBothAction(Action1 action1, Action2 action2) : action1_(action1), action2_(action2) {} // This template type conversion operator allows DoAll(a1, ..., a_n) // to be used in ANY function of compatible type. template <typename F> operator Action<F>() const { return Action<F>(new Impl<F>(action1_, action2_)); } private: // Implements the DoAll(...) action for a particular function type F. template <typename F> class Impl : public ActionInterface<F> { public: typedef typename Function<F>::Result Result; typedef typename Function<F>::ArgumentTuple ArgumentTuple; typedef typename Function<F>::MakeResultVoid VoidResult; Impl(const Action<VoidResult>& action1, const Action<F>& action2) : action1_(action1), action2_(action2) {} virtual Result Perform(const ArgumentTuple& args) { action1_.Perform(args); return action2_.Perform(args); } private: const Action<VoidResult> action1_; const Action<F> action2_; GTEST_DISALLOW_ASSIGN_(Impl); }; Action1 action1_; Action2 action2_; GTEST_DISALLOW_ASSIGN_(DoBothAction); }; } // namespace internal // An Unused object can be implicitly constructed from ANY value. // This is handy when defining actions that ignore some or all of the // mock function arguments. For example, given // // MOCK_METHOD3(Foo, double(const string& label, double x, double y)); // MOCK_METHOD3(Bar, double(int index, double x, double y)); // // instead of // // double DistanceToOriginWithLabel(const string& label, double x, double y) { // return sqrt(x*x + y*y); // } // double DistanceToOriginWithIndex(int index, double x, double y) { // return sqrt(x*x + y*y); // } // ... // EXEPCT_CALL(mock, Foo("abc", _, _)) // .WillOnce(Invoke(DistanceToOriginWithLabel)); // EXEPCT_CALL(mock, Bar(5, _, _)) // .WillOnce(Invoke(DistanceToOriginWithIndex)); // // you could write // // // We can declare any uninteresting argument as Unused. // double DistanceToOrigin(Unused, double x, double y) { // return sqrt(x*x + y*y); // } // ... // EXEPCT_CALL(mock, Foo("abc", _, _)).WillOnce(Invoke(DistanceToOrigin)); // EXEPCT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin)); typedef internal::IgnoredValue Unused; // This constructor allows us to turn an Action<From> object into an // Action<To>, as long as To's arguments can be implicitly converted // to From's and From's return type cann be implicitly converted to // To's. template <typename To> template <typename From> Action<To>::Action(const Action<From>& from) : impl_(new internal::ActionAdaptor<To, From>(from)) {} // Creates an action that returns 'value'. 'value' is passed by value // instead of const reference - otherwise Return("string literal") // will trigger a compiler error about using array as initializer. template <typename R> internal::ReturnAction<R> Return(R value) { return internal::ReturnAction<R>(internal::move(value)); } // Creates an action that returns NULL. inline PolymorphicAction<internal::ReturnNullAction> ReturnNull() { return MakePolymorphicAction(internal::ReturnNullAction()); } // Creates an action that returns from a void function. inline PolymorphicAction<internal::ReturnVoidAction> Return() { return MakePolymorphicAction(internal::ReturnVoidAction()); } // Creates an action that returns the reference to a variable. template <typename R> inline internal::ReturnRefAction<R> ReturnRef(R& x) { // NOLINT return internal::ReturnRefAction<R>(x); } // Creates an action that returns the reference to a copy of the // argument. The copy is created when the action is constructed and // lives as long as the action. template <typename R> inline internal::ReturnRefOfCopyAction<R> ReturnRefOfCopy(const R& x) { return internal::ReturnRefOfCopyAction<R>(x); } // Modifies the parent action (a Return() action) to perform a move of the // argument instead of a copy. // Return(ByMove()) actions can only be executed once and will assert this // invariant. template <typename R> internal::ByMoveWrapper<R> ByMove(R x) { return internal::ByMoveWrapper<R>(internal::move(x)); } // Creates an action that does the default action for the give mock function. inline internal::DoDefaultAction DoDefault() { return internal::DoDefaultAction(); } // Creates an action that sets the variable pointed by the N-th // (0-based) function argument to 'value'. template <size_t N, typename T> PolymorphicAction< internal::SetArgumentPointeeAction< N, T, internal::IsAProtocolMessage<T>::value> > SetArgPointee(const T& x) { return MakePolymorphicAction(internal::SetArgumentPointeeAction< N, T, internal::IsAProtocolMessage<T>::value>(x)); } #if !((GTEST_GCC_VER_ && GTEST_GCC_VER_ < 40000) || GTEST_OS_SYMBIAN) // This overload allows SetArgPointee() to accept a string literal. // GCC prior to the version 4.0 and Symbian C++ compiler cannot distinguish // this overload from the templated version and emit a compile error. template <size_t N> PolymorphicAction< internal::SetArgumentPointeeAction<N, const char*, false> > SetArgPointee(const char* p) { return MakePolymorphicAction(internal::SetArgumentPointeeAction< N, const char*, false>(p)); } template <size_t N> PolymorphicAction< internal::SetArgumentPointeeAction<N, const wchar_t*, false> > SetArgPointee(const wchar_t* p) { return MakePolymorphicAction(internal::SetArgumentPointeeAction< N, const wchar_t*, false>(p)); } #endif // The following version is DEPRECATED. template <size_t N, typename T> PolymorphicAction< internal::SetArgumentPointeeAction< N, T, internal::IsAProtocolMessage<T>::value> > SetArgumentPointee(const T& x) { return MakePolymorphicAction(internal::SetArgumentPointeeAction< N, T, internal::IsAProtocolMessage<T>::value>(x)); } // Creates an action that sets a pointer referent to a given value. template <typename T1, typename T2> PolymorphicAction<internal::AssignAction<T1, T2> > Assign(T1* ptr, T2 val) { return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val)); } #if !GTEST_OS_WINDOWS_MOBILE // Creates an action that sets errno and returns the appropriate error. template <typename T> PolymorphicAction<internal::SetErrnoAndReturnAction<T> > SetErrnoAndReturn(int errval, T result) { return MakePolymorphicAction( internal::SetErrnoAndReturnAction<T>(errval, result)); } #endif // !GTEST_OS_WINDOWS_MOBILE // Various overloads for InvokeWithoutArgs(). // Creates an action that invokes 'function_impl' with no argument. template <typename FunctionImpl> PolymorphicAction<internal::InvokeWithoutArgsAction<FunctionImpl> > InvokeWithoutArgs(FunctionImpl function_impl) { return MakePolymorphicAction( internal::InvokeWithoutArgsAction<FunctionImpl>(function_impl)); } // Creates an action that invokes the given method on the given object // with no argument. template <class Class, typename MethodPtr> PolymorphicAction<internal::InvokeMethodWithoutArgsAction<Class, MethodPtr> > InvokeWithoutArgs(Class* obj_ptr, MethodPtr method_ptr) { return MakePolymorphicAction( internal::InvokeMethodWithoutArgsAction<Class, MethodPtr>( obj_ptr, method_ptr)); } // Creates an action that performs an_action and throws away its // result. In other words, it changes the return type of an_action to // void. an_action MUST NOT return void, or the code won't compile. template <typename A> inline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) { return internal::IgnoreResultAction<A>(an_action); } // Creates a reference wrapper for the given L-value. If necessary, // you can explicitly specify the type of the reference. For example, // suppose 'derived' is an object of type Derived, ByRef(derived) // would wrap a Derived&. If you want to wrap a const Base& instead, // where Base is a base class of Derived, just write: // // ByRef<const Base>(derived) template <typename T> inline internal::ReferenceWrapper<T> ByRef(T& l_value) { // NOLINT return internal::ReferenceWrapper<T>(l_value); } } // namespace testing #ifdef __clang__ #if __has_warning("-Wdeprecated-copy") #pragma clang diagnostic pop #endif #endif #ifdef _MSC_VER # pragma warning(pop) #endif #endif // GMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_
0
repos/DirectXShaderCompiler/utils/unittest/googlemock/include/gmock
repos/DirectXShaderCompiler/utils/unittest/googlemock/include/gmock/internal/gmock-generated-internal-utils.h
// This file was GENERATED by command: // pump.py gmock-generated-internal-utils.h.pump // DO NOT EDIT BY HAND!!! // 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. // // Author: [email protected] (Zhanyong Wan) // Google Mock - a framework for writing C++ mock classes. // // This file contains template meta-programming utility classes needed // for implementing Google Mock. #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_ #define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_ #include "gmock/internal/gmock-port.h" namespace testing { template <typename T> class Matcher; namespace internal { // An IgnoredValue object can be implicitly constructed from ANY value. // This is used in implementing the IgnoreResult(a) action. class IgnoredValue { public: // This constructor template allows any value to be implicitly // converted to IgnoredValue. The object has no data member and // doesn't try to remember anything about the argument. We // deliberately omit the 'explicit' keyword in order to allow the // conversion to be implicit. template <typename T> IgnoredValue(const T& /* ignored */) {} // NOLINT(runtime/explicit) }; // MatcherTuple<T>::type is a tuple type where each field is a Matcher // for the corresponding field in tuple type T. template <typename Tuple> struct MatcherTuple; template <> struct MatcherTuple< ::testing::tuple<> > { typedef ::testing::tuple< > type; }; template <typename A1> struct MatcherTuple< ::testing::tuple<A1> > { typedef ::testing::tuple<Matcher<A1> > type; }; template <typename A1, typename A2> struct MatcherTuple< ::testing::tuple<A1, A2> > { typedef ::testing::tuple<Matcher<A1>, Matcher<A2> > type; }; template <typename A1, typename A2, typename A3> struct MatcherTuple< ::testing::tuple<A1, A2, A3> > { typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3> > type; }; template <typename A1, typename A2, typename A3, typename A4> struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4> > { typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4> > type; }; template <typename A1, typename A2, typename A3, typename A4, typename A5> struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5> > { typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>, Matcher<A5> > type; }; template <typename A1, typename A2, typename A3, typename A4, typename A5, typename A6> struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6> > { typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>, Matcher<A5>, Matcher<A6> > type; }; template <typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7> struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6, A7> > { typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>, Matcher<A5>, Matcher<A6>, Matcher<A7> > type; }; template <typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8> struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8> > { typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>, Matcher<A5>, Matcher<A6>, Matcher<A7>, Matcher<A8> > type; }; template <typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8, typename A9> struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9> > { typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>, Matcher<A5>, Matcher<A6>, Matcher<A7>, Matcher<A8>, Matcher<A9> > type; }; template <typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8, typename A9, typename A10> struct MatcherTuple< ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10> > { typedef ::testing::tuple<Matcher<A1>, Matcher<A2>, Matcher<A3>, Matcher<A4>, Matcher<A5>, Matcher<A6>, Matcher<A7>, Matcher<A8>, Matcher<A9>, Matcher<A10> > type; }; // Template struct Function<F>, where F must be a function type, contains // the following typedefs: // // Result: the function's return type. // ArgumentN: the type of the N-th argument, where N starts with 1. // ArgumentTuple: the tuple type consisting of all parameters of F. // ArgumentMatcherTuple: the tuple type consisting of Matchers for all // parameters of F. // MakeResultVoid: the function type obtained by substituting void // for the return type of F. // MakeResultIgnoredValue: // the function type obtained by substituting Something // for the return type of F. template <typename F> struct Function; template <typename R> struct Function<R()> { typedef R Result; typedef ::testing::tuple<> ArgumentTuple; typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple; typedef void MakeResultVoid(); typedef IgnoredValue MakeResultIgnoredValue(); }; template <typename R, typename A1> struct Function<R(A1)> : Function<R()> { typedef A1 Argument1; typedef ::testing::tuple<A1> ArgumentTuple; typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple; typedef void MakeResultVoid(A1); typedef IgnoredValue MakeResultIgnoredValue(A1); }; template <typename R, typename A1, typename A2> struct Function<R(A1, A2)> : Function<R(A1)> { typedef A2 Argument2; typedef ::testing::tuple<A1, A2> ArgumentTuple; typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple; typedef void MakeResultVoid(A1, A2); typedef IgnoredValue MakeResultIgnoredValue(A1, A2); }; template <typename R, typename A1, typename A2, typename A3> struct Function<R(A1, A2, A3)> : Function<R(A1, A2)> { typedef A3 Argument3; typedef ::testing::tuple<A1, A2, A3> ArgumentTuple; typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple; typedef void MakeResultVoid(A1, A2, A3); typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3); }; template <typename R, typename A1, typename A2, typename A3, typename A4> struct Function<R(A1, A2, A3, A4)> : Function<R(A1, A2, A3)> { typedef A4 Argument4; typedef ::testing::tuple<A1, A2, A3, A4> ArgumentTuple; typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple; typedef void MakeResultVoid(A1, A2, A3, A4); typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4); }; template <typename R, typename A1, typename A2, typename A3, typename A4, typename A5> struct Function<R(A1, A2, A3, A4, A5)> : Function<R(A1, A2, A3, A4)> { typedef A5 Argument5; typedef ::testing::tuple<A1, A2, A3, A4, A5> ArgumentTuple; typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple; typedef void MakeResultVoid(A1, A2, A3, A4, A5); typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5); }; template <typename R, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6> struct Function<R(A1, A2, A3, A4, A5, A6)> : Function<R(A1, A2, A3, A4, A5)> { typedef A6 Argument6; typedef ::testing::tuple<A1, A2, A3, A4, A5, A6> ArgumentTuple; typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple; typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6); typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6); }; template <typename R, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7> struct Function<R(A1, A2, A3, A4, A5, A6, A7)> : Function<R(A1, A2, A3, A4, A5, A6)> { typedef A7 Argument7; typedef ::testing::tuple<A1, A2, A3, A4, A5, A6, A7> ArgumentTuple; typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple; typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6, A7); typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6, A7); }; template <typename R, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8> struct Function<R(A1, A2, A3, A4, A5, A6, A7, A8)> : Function<R(A1, A2, A3, A4, A5, A6, A7)> { typedef A8 Argument8; typedef ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8> ArgumentTuple; typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple; typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6, A7, A8); typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6, A7, A8); }; template <typename R, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8, typename A9> struct Function<R(A1, A2, A3, A4, A5, A6, A7, A8, A9)> : Function<R(A1, A2, A3, A4, A5, A6, A7, A8)> { typedef A9 Argument9; typedef ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9> ArgumentTuple; typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple; typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6, A7, A8, A9); typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6, A7, A8, A9); }; template <typename R, typename A1, typename A2, typename A3, typename A4, typename A5, typename A6, typename A7, typename A8, typename A9, typename A10> struct Function<R(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10)> : Function<R(A1, A2, A3, A4, A5, A6, A7, A8, A9)> { typedef A10 Argument10; typedef ::testing::tuple<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10> ArgumentTuple; typedef typename MatcherTuple<ArgumentTuple>::type ArgumentMatcherTuple; typedef void MakeResultVoid(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10); typedef IgnoredValue MakeResultIgnoredValue(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10); }; } // namespace internal } // namespace testing #endif // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_GENERATED_INTERNAL_UTILS_H_
0
repos/DirectXShaderCompiler/utils/unittest/googlemock/include/gmock
repos/DirectXShaderCompiler/utils/unittest/googlemock/include/gmock/internal/gmock-port.h
// 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. // // Author: [email protected] (Vadim Berman) // // Low-level types and utilities for porting Google Mock to various // platforms. All macros ending with _ and symbols defined in an // internal namespace are subject to change without notice. Code // outside Google Mock MUST NOT USE THEM DIRECTLY. Macros that don't // end with _ are part of Google Mock's public API and can be used by // code outside Google Mock. #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_ #define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_ #include <assert.h> #include <stdlib.h> #include <iostream> // Most of the utilities needed for porting Google Mock are also // required for Google Test and are defined in gtest-port.h. // // Note to maintainers: to reduce code duplication, prefer adding // portability utilities to Google Test's gtest-port.h instead of // here, as Google Mock depends on Google Test. Only add a utility // here if it's truly specific to Google Mock. #include "gtest/internal/gtest-linked_ptr.h" #include "gtest/internal/gtest-port.h" #include "gmock/internal/custom/gmock-port.h" // To avoid conditional compilation everywhere, we make it // gmock-port.h's responsibility to #include the header implementing // tr1/tuple. gmock-port.h does this via gtest-port.h, which is // guaranteed to pull in the tuple header. // For MS Visual C++, check the compiler version. At least VS 2003 is // required to compile Google Mock. #if defined(_MSC_VER) && _MSC_VER < 1310 # error "At least Visual C++ 2003 (7.1) is required to compile Google Mock." #endif // Macro for referencing flags. This is public as we want the user to // use this syntax to reference Google Mock flags. #define GMOCK_FLAG(name) FLAGS_gmock_##name #if !defined(GMOCK_DECLARE_bool_) // Macros for declaring flags. #define GMOCK_DECLARE_bool_(name) extern GTEST_API_ bool GMOCK_FLAG(name) #define GMOCK_DECLARE_int32_(name) \ extern GTEST_API_ ::testing::internal::Int32 GMOCK_FLAG(name) #define GMOCK_DECLARE_string_(name) \ extern GTEST_API_ ::std::string GMOCK_FLAG(name) // Macros for defining flags. #define GMOCK_DEFINE_bool_(name, default_val, doc) \ GTEST_API_ bool GMOCK_FLAG(name) = (default_val) #define GMOCK_DEFINE_int32_(name, default_val, doc) \ GTEST_API_ ::testing::internal::Int32 GMOCK_FLAG(name) = (default_val) #define GMOCK_DEFINE_string_(name, default_val, doc) \ GTEST_API_ ::std::string GMOCK_FLAG(name) = (default_val) #endif // !defined(GMOCK_DECLARE_bool_) #endif // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_
0
repos/DirectXShaderCompiler/utils/unittest/googlemock/include/gmock
repos/DirectXShaderCompiler/utils/unittest/googlemock/include/gmock/internal/gmock-internal-utils.h
// 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. // // Author: [email protected] (Zhanyong Wan) // Google Mock - a framework for writing C++ mock classes. // // This file defines some utilities useful for implementing Google // Mock. They are subject to change without notice, so please DO NOT // USE THEM IN USER CODE. #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_ #define GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_ #include <stdio.h> #include <ostream> // NOLINT #include <string> #include "gmock/internal/gmock-generated-internal-utils.h" #include "gmock/internal/gmock-port.h" #include "gtest/gtest.h" namespace testing { namespace internal { // Converts an identifier name to a space-separated list of lower-case // words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is // treated as one word. For example, both "FooBar123" and // "foo_bar_123" are converted to "foo bar 123". GTEST_API_ string ConvertIdentifierNameToWords(const char* id_name); // PointeeOf<Pointer>::type is the type of a value pointed to by a // Pointer, which can be either a smart pointer or a raw pointer. The // following default implementation is for the case where Pointer is a // smart pointer. template <typename Pointer> struct PointeeOf { // Smart pointer classes define type element_type as the type of // their pointees. typedef typename Pointer::element_type type; }; // This specialization is for the raw pointer case. template <typename T> struct PointeeOf<T*> { typedef T type; }; // NOLINT // GetRawPointer(p) returns the raw pointer underlying p when p is a // smart pointer, or returns p itself when p is already a raw pointer. // The following default implementation is for the smart pointer case. template <typename Pointer> inline const typename Pointer::element_type* GetRawPointer(const Pointer& p) { return p.get(); } // This overloaded version is for the raw pointer case. template <typename Element> inline Element* GetRawPointer(Element* p) { return p; } // This comparator allows linked_ptr to be stored in sets. template <typename T> struct LinkedPtrLessThan { bool operator()(const ::testing::internal::linked_ptr<T>& lhs, const ::testing::internal::linked_ptr<T>& rhs) const { return lhs.get() < rhs.get(); } }; // Symbian compilation can be done with wchar_t being either a native // type or a typedef. Using Google Mock with OpenC without wchar_t // should require the definition of _STLP_NO_WCHAR_T. // // MSVC treats wchar_t as a native type usually, but treats it as the // same as unsigned short when the compiler option /Zc:wchar_t- is // specified. It defines _NATIVE_WCHAR_T_DEFINED symbol when wchar_t // is a native type. #if (GTEST_OS_SYMBIAN && defined(_STLP_NO_WCHAR_T)) || \ (defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED)) // wchar_t is a typedef. #else # define GMOCK_WCHAR_T_IS_NATIVE_ 1 #endif // signed wchar_t and unsigned wchar_t are NOT in the C++ standard. // Using them is a bad practice and not portable. So DON'T use them. // // Still, Google Mock is designed to work even if the user uses signed // wchar_t or unsigned wchar_t (obviously, assuming the compiler // supports them). // // To gcc, // wchar_t == signed wchar_t != unsigned wchar_t == unsigned int #ifdef __GNUC__ // signed/unsigned wchar_t are valid types. # define GMOCK_HAS_SIGNED_WCHAR_T_ 1 #endif // In what follows, we use the term "kind" to indicate whether a type // is bool, an integer type (excluding bool), a floating-point type, // or none of them. This categorization is useful for determining // when a matcher argument type can be safely converted to another // type in the implementation of SafeMatcherCast. enum TypeKind { kBool, kInteger, kFloatingPoint, kOther }; // KindOf<T>::value is the kind of type T. template <typename T> struct KindOf { enum { value = kOther }; // The default kind. }; // This macro declares that the kind of 'type' is 'kind'. #define GMOCK_DECLARE_KIND_(type, kind) \ template <> struct KindOf<type> { enum { value = kind }; } GMOCK_DECLARE_KIND_(bool, kBool); // All standard integer types. GMOCK_DECLARE_KIND_(char, kInteger); GMOCK_DECLARE_KIND_(signed char, kInteger); GMOCK_DECLARE_KIND_(unsigned char, kInteger); GMOCK_DECLARE_KIND_(short, kInteger); // NOLINT GMOCK_DECLARE_KIND_(unsigned short, kInteger); // NOLINT GMOCK_DECLARE_KIND_(int, kInteger); GMOCK_DECLARE_KIND_(unsigned int, kInteger); GMOCK_DECLARE_KIND_(long, kInteger); // NOLINT GMOCK_DECLARE_KIND_(unsigned long, kInteger); // NOLINT #if GMOCK_WCHAR_T_IS_NATIVE_ GMOCK_DECLARE_KIND_(wchar_t, kInteger); #endif // Non-standard integer types. GMOCK_DECLARE_KIND_(Int64, kInteger); GMOCK_DECLARE_KIND_(UInt64, kInteger); // All standard floating-point types. GMOCK_DECLARE_KIND_(float, kFloatingPoint); GMOCK_DECLARE_KIND_(double, kFloatingPoint); GMOCK_DECLARE_KIND_(long double, kFloatingPoint); #undef GMOCK_DECLARE_KIND_ // Evaluates to the kind of 'type'. #define GMOCK_KIND_OF_(type) \ static_cast< ::testing::internal::TypeKind>( \ ::testing::internal::KindOf<type>::value) // Evaluates to true iff integer type T is signed. #define GMOCK_IS_SIGNED_(T) (static_cast<T>(-1) < 0) // LosslessArithmeticConvertibleImpl<kFromKind, From, kToKind, To>::value // is true iff arithmetic type From can be losslessly converted to // arithmetic type To. // // It's the user's responsibility to ensure that both From and To are // raw (i.e. has no CV modifier, is not a pointer, and is not a // reference) built-in arithmetic types, kFromKind is the kind of // From, and kToKind is the kind of To; the value is // implementation-defined when the above pre-condition is violated. template <TypeKind kFromKind, typename From, TypeKind kToKind, typename To> struct LosslessArithmeticConvertibleImpl : public false_type {}; // Converting bool to bool is lossless. template <> struct LosslessArithmeticConvertibleImpl<kBool, bool, kBool, bool> : public true_type {}; // NOLINT // Converting bool to any integer type is lossless. template <typename To> struct LosslessArithmeticConvertibleImpl<kBool, bool, kInteger, To> : public true_type {}; // NOLINT // Converting bool to any floating-point type is lossless. template <typename To> struct LosslessArithmeticConvertibleImpl<kBool, bool, kFloatingPoint, To> : public true_type {}; // NOLINT // Converting an integer to bool is lossy. template <typename From> struct LosslessArithmeticConvertibleImpl<kInteger, From, kBool, bool> : public false_type {}; // NOLINT // Converting an integer to another non-bool integer is lossless iff // the target type's range encloses the source type's range. template <typename From, typename To> struct LosslessArithmeticConvertibleImpl<kInteger, From, kInteger, To> : public bool_constant< // When converting from a smaller size to a larger size, we are // fine as long as we are not converting from signed to unsigned. ((sizeof(From) < sizeof(To)) && (!GMOCK_IS_SIGNED_(From) || GMOCK_IS_SIGNED_(To))) || // When converting between the same size, the signedness must match. ((sizeof(From) == sizeof(To)) && (GMOCK_IS_SIGNED_(From) == GMOCK_IS_SIGNED_(To)))> {}; // NOLINT #undef GMOCK_IS_SIGNED_ // Converting an integer to a floating-point type may be lossy, since // the format of a floating-point number is implementation-defined. template <typename From, typename To> struct LosslessArithmeticConvertibleImpl<kInteger, From, kFloatingPoint, To> : public false_type {}; // NOLINT // Converting a floating-point to bool is lossy. template <typename From> struct LosslessArithmeticConvertibleImpl<kFloatingPoint, From, kBool, bool> : public false_type {}; // NOLINT // Converting a floating-point to an integer is lossy. template <typename From, typename To> struct LosslessArithmeticConvertibleImpl<kFloatingPoint, From, kInteger, To> : public false_type {}; // NOLINT // Converting a floating-point to another floating-point is lossless // iff the target type is at least as big as the source type. template <typename From, typename To> struct LosslessArithmeticConvertibleImpl< kFloatingPoint, From, kFloatingPoint, To> : public bool_constant<sizeof(From) <= sizeof(To)> {}; // NOLINT // LosslessArithmeticConvertible<From, To>::value is true iff arithmetic // type From can be losslessly converted to arithmetic type To. // // It's the user's responsibility to ensure that both From and To are // raw (i.e. has no CV modifier, is not a pointer, and is not a // reference) built-in arithmetic types; the value is // implementation-defined when the above pre-condition is violated. template <typename From, typename To> struct LosslessArithmeticConvertible : public LosslessArithmeticConvertibleImpl< GMOCK_KIND_OF_(From), From, GMOCK_KIND_OF_(To), To> {}; // NOLINT // This interface knows how to report a Google Mock failure (either // non-fatal or fatal). class FailureReporterInterface { public: // The type of a failure (either non-fatal or fatal). enum FailureType { kNonfatal, kFatal }; virtual ~FailureReporterInterface() {} // Reports a failure that occurred at the given source file location. virtual void ReportFailure(FailureType type, const char* file, int line, const string& message) = 0; }; // Returns the failure reporter used by Google Mock. GTEST_API_ FailureReporterInterface* GetFailureReporter(); // Asserts that condition is true; aborts the process with the given // message if condition is false. We cannot use LOG(FATAL) or CHECK() // as Google Mock might be used to mock the log sink itself. We // inline this function to prevent it from showing up in the stack // trace. inline void Assert(bool condition, const char* file, int line, const string& msg) { if (!condition) { GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal, file, line, msg); } } inline void Assert(bool condition, const char* file, int line) { Assert(condition, file, line, "Assertion failed."); } // Verifies that condition is true; generates a non-fatal failure if // condition is false. inline void Expect(bool condition, const char* file, int line, const string& msg) { if (!condition) { GetFailureReporter()->ReportFailure(FailureReporterInterface::kNonfatal, file, line, msg); } } inline void Expect(bool condition, const char* file, int line) { Expect(condition, file, line, "Expectation failed."); } // Severity level of a log. enum LogSeverity { kInfo = 0, kWarning = 1 }; // Valid values for the --gmock_verbose flag. // All logs (informational and warnings) are printed. const char kInfoVerbosity[] = "info"; // Only warnings are printed. const char kWarningVerbosity[] = "warning"; // No logs are printed. const char kErrorVerbosity[] = "error"; // Returns true iff a log with the given severity is visible according // to the --gmock_verbose flag. GTEST_API_ bool LogIsVisible(LogSeverity severity); // Prints the given message to stdout iff 'severity' >= the level // specified by the --gmock_verbose flag. If stack_frames_to_skip >= // 0, also prints the stack trace excluding the top // stack_frames_to_skip frames. In opt mode, any positive // stack_frames_to_skip is treated as 0, since we don't know which // function calls will be inlined by the compiler and need to be // conservative. GTEST_API_ void Log(LogSeverity severity, const string& message, int stack_frames_to_skip); // TODO([email protected]): group all type utilities together. // Type traits. // is_reference<T>::value is non-zero iff T is a reference type. template <typename T> struct is_reference : public false_type {}; template <typename T> struct is_reference<T&> : public true_type {}; // type_equals<T1, T2>::value is non-zero iff T1 and T2 are the same type. template <typename T1, typename T2> struct type_equals : public false_type {}; template <typename T> struct type_equals<T, T> : public true_type {}; // remove_reference<T>::type removes the reference from type T, if any. template <typename T> struct remove_reference { typedef T type; }; // NOLINT template <typename T> struct remove_reference<T&> { typedef T type; }; // NOLINT // DecayArray<T>::type turns an array type U[N] to const U* and preserves // other types. Useful for saving a copy of a function argument. template <typename T> struct DecayArray { typedef T type; }; // NOLINT template <typename T, size_t N> struct DecayArray<T[N]> { typedef const T* type; }; // Sometimes people use arrays whose size is not available at the use site // (e.g. extern const char kNamePrefix[]). This specialization covers that // case. template <typename T> struct DecayArray<T[]> { typedef const T* type; }; // Disable MSVC warnings for infinite recursion, since in this case the // the recursion is unreachable. #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable:4717) #endif // Invalid<T>() is usable as an expression of type T, but will terminate // the program with an assertion failure if actually run. This is useful // when a value of type T is needed for compilation, but the statement // will not really be executed (or we don't care if the statement // crashes). template <typename T> inline T Invalid() { Assert(false, "", -1, "Internal error: attempt to return invalid value"); // This statement is unreachable, and would never terminate even if it // could be reached. It is provided only to placate compiler warnings // about missing return statements. return Invalid<T>(); } #ifdef _MSC_VER # pragma warning(pop) #endif // Given a raw type (i.e. having no top-level reference or const // modifier) RawContainer that's either an STL-style container or a // native array, class StlContainerView<RawContainer> has the // following members: // // - type is a type that provides an STL-style container view to // (i.e. implements the STL container concept for) RawContainer; // - const_reference is a type that provides a reference to a const // RawContainer; // - ConstReference(raw_container) returns a const reference to an STL-style // container view to raw_container, which is a RawContainer. // - Copy(raw_container) returns an STL-style container view of a // copy of raw_container, which is a RawContainer. // // This generic version is used when RawContainer itself is already an // STL-style container. template <class RawContainer> class StlContainerView { public: typedef RawContainer type; typedef const type& const_reference; static const_reference ConstReference(const RawContainer& container) { // Ensures that RawContainer is not a const type. testing::StaticAssertTypeEq<RawContainer, GTEST_REMOVE_CONST_(RawContainer)>(); return container; } static type Copy(const RawContainer& container) { return container; } }; // This specialization is used when RawContainer is a native array type. template <typename Element, size_t N> class StlContainerView<Element[N]> { public: typedef GTEST_REMOVE_CONST_(Element) RawElement; typedef internal::NativeArray<RawElement> type; // NativeArray<T> can represent a native array either by value or by // reference (selected by a constructor argument), so 'const type' // can be used to reference a const native array. We cannot // 'typedef const type& const_reference' here, as that would mean // ConstReference() has to return a reference to a local variable. typedef const type const_reference; static const_reference ConstReference(const Element (&array)[N]) { // Ensures that Element is not a const type. testing::StaticAssertTypeEq<Element, RawElement>(); #if GTEST_OS_SYMBIAN // The Nokia Symbian compiler confuses itself in template instantiation // for this call without the cast to Element*: // function call '[testing::internal::NativeArray<char *>].NativeArray( // {lval} const char *[4], long, testing::internal::RelationToSource)' // does not match // 'testing::internal::NativeArray<char *>::NativeArray( // char *const *, unsigned int, testing::internal::RelationToSource)' // (instantiating: 'testing::internal::ContainsMatcherImpl // <const char * (&)[4]>::Matches(const char * (&)[4]) const') // (instantiating: 'testing::internal::StlContainerView<char *[4]>:: // ConstReference(const char * (&)[4])') // (and though the N parameter type is mismatched in the above explicit // conversion of it doesn't help - only the conversion of the array). return type(const_cast<Element*>(&array[0]), N, RelationToSourceReference()); #else return type(array, N, RelationToSourceReference()); #endif // GTEST_OS_SYMBIAN } static type Copy(const Element (&array)[N]) { #if GTEST_OS_SYMBIAN return type(const_cast<Element*>(&array[0]), N, RelationToSourceCopy()); #else return type(array, N, RelationToSourceCopy()); #endif // GTEST_OS_SYMBIAN } }; // This specialization is used when RawContainer is a native array // represented as a (pointer, size) tuple. template <typename ElementPointer, typename Size> class StlContainerView< ::testing::tuple<ElementPointer, Size> > { public: typedef GTEST_REMOVE_CONST_( typename internal::PointeeOf<ElementPointer>::type) RawElement; typedef internal::NativeArray<RawElement> type; typedef const type const_reference; static const_reference ConstReference( const ::testing::tuple<ElementPointer, Size>& array) { return type(get<0>(array), get<1>(array), RelationToSourceReference()); } static type Copy(const ::testing::tuple<ElementPointer, Size>& array) { return type(get<0>(array), get<1>(array), RelationToSourceCopy()); } }; // The following specialization prevents the user from instantiating // StlContainer with a reference type. template <typename T> class StlContainerView<T&>; // A type transform to remove constness from the first part of a pair. // Pairs like that are used as the value_type of associative containers, // and this transform produces a similar but assignable pair. template <typename T> struct RemoveConstFromKey { typedef T type; }; // Partially specialized to remove constness from std::pair<const K, V>. template <typename K, typename V> struct RemoveConstFromKey<std::pair<const K, V> > { typedef std::pair<K, V> type; }; // Mapping from booleans to types. Similar to boost::bool_<kValue> and // std::integral_constant<bool, kValue>. template <bool kValue> struct BooleanConstant {}; } // namespace internal } // namespace testing #endif // GMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_
0
repos/DirectXShaderCompiler/utils/unittest/googlemock/include/gmock/internal
repos/DirectXShaderCompiler/utils/unittest/googlemock/include/gmock/internal/custom/gmock-port.h
// Copyright 2015, 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. // // Injection point for custom user configurations. // The following macros can be defined: // // Flag related macros: // GMOCK_DECLARE_bool_(name) // GMOCK_DECLARE_int32_(name) // GMOCK_DECLARE_string_(name) // GMOCK_DEFINE_bool_(name, default_val, doc) // GMOCK_DEFINE_int32_(name, default_val, doc) // GMOCK_DEFINE_string_(name, default_val, doc) // // ** Custom implementation starts here ** #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_ #define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_ #endif // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_
0
repos/DirectXShaderCompiler/utils/unittest/googlemock/include/gmock/internal
repos/DirectXShaderCompiler/utils/unittest/googlemock/include/gmock/internal/custom/gmock-generated-actions.h
// This file was GENERATED by command: // pump.py gmock-generated-actions.h.pump // DO NOT EDIT BY HAND!!! #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_ #define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_ #endif // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_
0
repos/DirectXShaderCompiler/utils/unittest/googlemock/include/gmock/internal
repos/DirectXShaderCompiler/utils/unittest/googlemock/include/gmock/internal/custom/gmock-matchers.h
// Copyright 2015, 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. // // ============================================================ // An installation-specific extension point for gmock-matchers.h. // ============================================================ // // Adds google3 callback support to CallableTraits. // #ifndef GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_CALLBACK_MATCHERS_H_ #define GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_CALLBACK_MATCHERS_H_ #endif // GMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_CALLBACK_MATCHERS_H_
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/kate/llvm.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE language SYSTEM "language.dtd"> <language name="LLVM" section="Sources" version="1.00" kateversion="3.4.4" extensions="*.ll" mimetype="" author="LLVM Team" license="LLVM Release License"> <highlighting> <list name="keywords"> <item> begin </item> <item> end </item> <item> true </item> <item> false </item> <item> declare </item> <item> define </item> <item> global </item> <item> constant </item> <item> gc </item> <item> module </item> <item> asm </item> <item> target </item> <item> datalayout </item> <item> null </item> <item> undef </item> <item> blockaddress </item> <item> sideeffect </item> <item> alignstack </item> <item> to </item> <item> unwind </item> <item> nuw </item> <item> nsw </item> <item> inbounds </item> <item> tail </item> <item> triple </item> <item> type </item> <item> align </item> <item> alias </item> </list> <list name="linkage-types"> <item> private </item> <item> internal </item> <item> available_externally </item> <item> linkonce </item> <item> weak </item> <item> common </item> <item> appending </item> <item> extern_weak </item> <item> linkonce_odr </item> <item> weak_odr </item> <item> dllimport </item> <item> dllexport </item> </list> <list name="calling-conventions"> <item> ccc </item> <item> fastcc </item> <item> coldcc </item> <item> cc </item> </list> <list name="visibility-styles"> <item> default </item> <item> hidden </item> <item> protected </item> </list> <list name="parameter-attributes"> <item> zeroext </item> <item> signext </item> <item> inreg </item> <item> byval </item> <item> sret </item> <item> noalias </item> <item> nocapture </item> <item> nest </item> </list> <list name="function-attributes"> <item> alignstack </item> <item> alwaysinline </item> <item> inlinehint </item> <item> naked </item> <item> noimplicitfloat </item> <item> noinline </item> <item> noredzone </item> <item> noreturn </item> <item> nounwind </item> <item> optnone </item> <item> optsize </item> <item> readnone </item> <item> readonly </item> <item> ssp </item> <item> sspreq </item> <item> sspstrong </item> </list> <list name="types"> <item> float </item> <item> double </item> <item> fp128 </item> <item> x86_fp80 </item> <item> ppc_fp128 </item> <item> x86mmx </item> <item> void </item> <item> label </item> <item> metadata </item> <item> opaque </item> </list> <list name="intrinsic-global-variables"> <item> llvm.used </item> <item> llvm.compiler.used </item> <item> llvm.global_ctors </item> <item> llvm.global_dtors </item> </list> <list name="instructions"> <item> ret </item> <item> br </item> <item> switch </item> <item> indirectbr </item> <item> invoke </item> <item> unwind </item> <item> unreachable </item> <item> add </item> <item> fadd </item> <item> sub </item> <item> fsub </item> <item> mul </item> <item> fmul </item> <item> udiv </item> <item> sdiv </item> <item> fdiv </item> <item> urem </item> <item> srem </item> <item> frem </item> <item> shl </item> <item> lshr </item> <item> ashr </item> <item> and </item> <item> or </item> <item> xor </item> <item> extractelement </item> <item> insertelement </item> <item> shufflevector </item> <item> extractvalue </item> <item> insertvalue </item> <item> alloca </item> <item> load </item> <item> store </item> <item> getelementptr </item> <item> trunc </item> <item> zext </item> <item> sext </item> <item> fptrunc </item> <item> fpext </item> <item> fptoui </item> <item> fptosi </item> <item> uitofp </item> <item> sitofp </item> <item> ptrtoint </item> <item> inttoptr </item> <item> bitcast </item> <item> addrspacecast </item> <item> icmp </item> <item> fcmp </item> <item> phi </item> <item> select </item> <item> call </item> <item> va_arg </item> </list> <list name="conditions"> <item> eq </item> <item> ne </item> <item> ugt </item> <item> uge </item> <item> ult </item> <item> ule </item> <item> sgt </item> <item> sge </item> <item> slt </item> <item> sle </item> <item> oeq </item> <item> ogt </item> <item> oge </item> <item> olt </item> <item> ole </item> <item> one </item> <item> ord </item> <item> ueq </item> <item> une </item> <item> uno </item> </list> <contexts> <context name="llvm" attribute="Normal Text" lineEndContext="#stay"> <DetectSpaces /> <AnyChar String="@%" attribute="Symbol" context="symbol" /> <DetectChar char="{" beginRegion="Brace1" /> <DetectChar char="}" endRegion="Brace1" /> <DetectChar char=";" attribute="Comment" context="comment" /> <DetectChar attribute="String" context="string" char="&quot;" /> <RegExpr String="i[0-9]+" attribute="Data Type" context="#stay" /> <RegExpr attribute="Symbol" String="[-a-zA-Z$._][-a-zA-Z$._0-9]*:" context="#stay" /> <Int attribute="Int" context="#stay" /> <keyword attribute="Keyword" String="keywords" /> <keyword attribute="Keyword" String="linkage-types" /> <keyword attribute="Keyword" String="calling-conventions" /> <keyword attribute="Keyword" String="visibility-styles" /> <keyword attribute="Keyword" String="parameter-attributes" /> <keyword attribute="Keyword" String="function-attributes" /> <keyword attribute="Data Type" String="types" /> <keyword attribute="Keyword" String="intrinsic-global-variables" /> <keyword attribute="Keyword" String="instructions" /> <keyword attribute="Keyword" String="conditions" /> </context> <context name="symbol" attribute="Symbol" lineEndContext="#pop"> <DetectChar attribute="Symbol" context="symbol-string" char="&quot;" /> <RegExpr attribute="Symbol" String="([-a-zA-Z$._][-a-zA-Z$._0-9]*|[0-9]+)" context="#pop" /> </context> <context name="symbol-string" attribute="Symbol" lineEndContext="#stay"> <DetectChar attribute="Symbol" context="#pop#pop" char="&quot;" /> </context> <context name="string" attribute="String" lineEndContext="#stay"> <DetectChar attribute="String" context="#pop" char="&quot;" /> </context> <context name="comment" attribute="Comment" lineEndContext="#pop"> <DetectSpaces /> <!-- TODO: Add FileCheck syntax highlighting --> <IncludeRules context="##Alerts" /> <DetectIdentifier /> </context> </contexts> <itemDatas> <itemData name="Normal Text" defStyleNum="dsNormal" /> <itemData name="Keyword" defStyleNum="dsKeyword" /> <itemData name="Data Type" defStyleNum="dsDataType" /> <itemData name="Int" defStyleNum="dsDecVal" /> <itemData name="Hex" defStyleNum="dsBaseN" /> <itemData name="Float" defStyleNum="dsFloat" /> <itemData name="String" defStyleNum="dsString" /> <itemData name="Comment" defStyleNum="dsComment" /> <itemData name="Function" defStyleNum="dsFunction" /> <itemData name="Symbol" defStyleNum="dsFunction" /> </itemDatas> </highlighting> <general> <comments> <comment name="singleLine" start=";" /> </comments> <keywords casesensitive="1" weakDeliminator="." /> </general> </language> <!-- // kate: space-indent on; indent-width 2; replace-tabs on; -->
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/KillTheDoctor/CMakeLists.txt
add_llvm_utility(KillTheDoctor KillTheDoctor.cpp ) target_link_libraries(KillTheDoctor LLVMSupport)
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/KillTheDoctor/KillTheDoctor.cpp
//===- KillTheDoctor - Prevent Dr. Watson from stopping tests ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This program provides an extremely hacky way to stop Dr. Watson from starting // due to unhandled exceptions in child processes. // // This simply starts the program named in the first positional argument with // the arguments following it under a debugger. All this debugger does is catch // any unhandled exceptions thrown in the child process and close the program // (and hopefully tells someone about it). // // This also provides another really hacky method to prevent assert dialog boxes // from popping up. When --no-user32 is passed, if any process loads user32.dll, // we assume it is trying to call MessageBoxEx and terminate it. The proper way // to do this would be to actually set a break point, but there's quite a bit // of code involved to get the address of MessageBoxEx in the remote process's // address space due to Address space layout randomization (ASLR). This can be // added if it's ever actually needed. // // If the subprocess exits for any reason other than successful termination, -1 // is returned. If the process exits normally the value it returned is returned. // // I hate Windows. // //===----------------------------------------------------------------------===// #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/Path.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/Support/WindowsError.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/type_traits.h" #include <algorithm> #include <cerrno> #include <cstdlib> #include <map> #include <string> #include <system_error> // These includes must be last. #include <windows.h> #include <winerror.h> #include <dbghelp.h> #include <psapi.h> using namespace llvm; #undef max namespace { cl::opt<std::string> ProgramToRun(cl::Positional, cl::desc("<program to run>")); cl::list<std::string> Argv(cl::ConsumeAfter, cl::desc("<program arguments>...")); cl::opt<bool> TraceExecution("x", cl::desc("Print detailed output about what is being run to stderr.")); cl::opt<unsigned> Timeout("t", cl::init(0), cl::desc("Set maximum runtime in seconds. Defaults to infinite.")); cl::opt<bool> NoUser32("no-user32", cl::desc("Terminate process if it loads user32.dll.")); StringRef ToolName; template <typename HandleType> class ScopedHandle { typedef typename HandleType::handle_type handle_type; handle_type Handle; public: ScopedHandle() : Handle(HandleType::GetInvalidHandle()) {} explicit ScopedHandle(handle_type handle) : Handle(handle) {} ~ScopedHandle() { HandleType::Destruct(Handle); } ScopedHandle& operator=(handle_type handle) { // Cleanup current handle. if (!HandleType::isValid(Handle)) HandleType::Destruct(Handle); Handle = handle; return *this; } operator bool() const { return HandleType::isValid(Handle); } operator handle_type() { return Handle; } }; // This implements the most common handle in the Windows API. struct CommonHandle { typedef HANDLE handle_type; static handle_type GetInvalidHandle() { return INVALID_HANDLE_VALUE; } static void Destruct(handle_type Handle) { ::CloseHandle(Handle); } static bool isValid(handle_type Handle) { return Handle != GetInvalidHandle(); } }; struct FileMappingHandle { typedef HANDLE handle_type; static handle_type GetInvalidHandle() { return NULL; } static void Destruct(handle_type Handle) { ::CloseHandle(Handle); } static bool isValid(handle_type Handle) { return Handle != GetInvalidHandle(); } }; struct MappedViewOfFileHandle { typedef LPVOID handle_type; static handle_type GetInvalidHandle() { return NULL; } static void Destruct(handle_type Handle) { ::UnmapViewOfFile(Handle); } static bool isValid(handle_type Handle) { return Handle != GetInvalidHandle(); } }; struct ProcessHandle : CommonHandle {}; struct ThreadHandle : CommonHandle {}; struct TokenHandle : CommonHandle {}; struct FileHandle : CommonHandle {}; typedef ScopedHandle<FileMappingHandle> FileMappingScopedHandle; typedef ScopedHandle<MappedViewOfFileHandle> MappedViewOfFileScopedHandle; typedef ScopedHandle<ProcessHandle> ProcessScopedHandle; typedef ScopedHandle<ThreadHandle> ThreadScopedHandle; typedef ScopedHandle<TokenHandle> TokenScopedHandle; typedef ScopedHandle<FileHandle> FileScopedHandle; } static std::error_code windows_error(DWORD E) { return mapWindowsError(E); } static std::error_code GetFileNameFromHandle(HANDLE FileHandle, std::string &Name) { char Filename[MAX_PATH+1]; bool Success = false; Name.clear(); // Get the file size. LARGE_INTEGER FileSize; Success = ::GetFileSizeEx(FileHandle, &FileSize); if (!Success) return windows_error(::GetLastError()); // Create a file mapping object. FileMappingScopedHandle FileMapping( ::CreateFileMappingA(FileHandle, NULL, PAGE_READONLY, 0, 1, NULL)); if (!FileMapping) return windows_error(::GetLastError()); // Create a file mapping to get the file name. MappedViewOfFileScopedHandle MappedFile( ::MapViewOfFile(FileMapping, FILE_MAP_READ, 0, 0, 1)); if (!MappedFile) return windows_error(::GetLastError()); Success = ::GetMappedFileNameA(::GetCurrentProcess(), MappedFile, Filename, array_lengthof(Filename) - 1); if (!Success) return windows_error(::GetLastError()); else { Name = Filename; return std::error_code(); } } /// @brief Find program using shell lookup rules. /// @param Program This is either an absolute path, relative path, or simple a /// program name. Look in PATH for any programs that match. If no /// extension is present, try all extensions in PATHEXT. /// @return If ec == errc::success, The absolute path to the program. Otherwise /// the return value is undefined. static std::string FindProgram(const std::string &Program, std::error_code &ec) { char PathName[MAX_PATH + 1]; typedef SmallVector<StringRef, 12> pathext_t; pathext_t pathext; // Check for the program without an extension (in case it already has one). pathext.push_back(""); SplitString(std::getenv("PATHEXT"), pathext, ";"); for (pathext_t::iterator i = pathext.begin(), e = pathext.end(); i != e; ++i){ SmallString<5> ext; for (std::size_t ii = 0, e = i->size(); ii != e; ++ii) ext.push_back(::tolower((*i)[ii])); LPCSTR Extension = NULL; if (ext.size() && ext[0] == '.') Extension = ext.c_str(); DWORD length = ::SearchPathA(NULL, Program.c_str(), Extension, array_lengthof(PathName), PathName, NULL); if (length == 0) ec = windows_error(::GetLastError()); else if (length > array_lengthof(PathName)) { // This may have been the file, return with error. ec = windows_error(ERROR_BUFFER_OVERFLOW); break; } else { // We found the path! Return it. ec = std::error_code(); break; } } // Make sure PathName is valid. PathName[MAX_PATH] = 0; return PathName; } static StringRef ExceptionCodeToString(DWORD ExceptionCode) { switch(ExceptionCode) { case EXCEPTION_ACCESS_VIOLATION: return "EXCEPTION_ACCESS_VIOLATION"; case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: return "EXCEPTION_ARRAY_BOUNDS_EXCEEDED"; case EXCEPTION_BREAKPOINT: return "EXCEPTION_BREAKPOINT"; case EXCEPTION_DATATYPE_MISALIGNMENT: return "EXCEPTION_DATATYPE_MISALIGNMENT"; case EXCEPTION_FLT_DENORMAL_OPERAND: return "EXCEPTION_FLT_DENORMAL_OPERAND"; case EXCEPTION_FLT_DIVIDE_BY_ZERO: return "EXCEPTION_FLT_DIVIDE_BY_ZERO"; case EXCEPTION_FLT_INEXACT_RESULT: return "EXCEPTION_FLT_INEXACT_RESULT"; case EXCEPTION_FLT_INVALID_OPERATION: return "EXCEPTION_FLT_INVALID_OPERATION"; case EXCEPTION_FLT_OVERFLOW: return "EXCEPTION_FLT_OVERFLOW"; case EXCEPTION_FLT_STACK_CHECK: return "EXCEPTION_FLT_STACK_CHECK"; case EXCEPTION_FLT_UNDERFLOW: return "EXCEPTION_FLT_UNDERFLOW"; case EXCEPTION_ILLEGAL_INSTRUCTION: return "EXCEPTION_ILLEGAL_INSTRUCTION"; case EXCEPTION_IN_PAGE_ERROR: return "EXCEPTION_IN_PAGE_ERROR"; case EXCEPTION_INT_DIVIDE_BY_ZERO: return "EXCEPTION_INT_DIVIDE_BY_ZERO"; case EXCEPTION_INT_OVERFLOW: return "EXCEPTION_INT_OVERFLOW"; case EXCEPTION_INVALID_DISPOSITION: return "EXCEPTION_INVALID_DISPOSITION"; case EXCEPTION_NONCONTINUABLE_EXCEPTION: return "EXCEPTION_NONCONTINUABLE_EXCEPTION"; case EXCEPTION_PRIV_INSTRUCTION: return "EXCEPTION_PRIV_INSTRUCTION"; case EXCEPTION_SINGLE_STEP: return "EXCEPTION_SINGLE_STEP"; case EXCEPTION_STACK_OVERFLOW: return "EXCEPTION_STACK_OVERFLOW"; default: return "<unknown>"; } } int main(int argc, char **argv) { // Print a stack trace if we signal out. sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. ToolName = argv[0]; cl::ParseCommandLineOptions(argc, argv, "Dr. Watson Assassin.\n"); if (ProgramToRun.size() == 0) { cl::PrintHelpMessage(); return -1; } if (Timeout > std::numeric_limits<uint32_t>::max() / 1000) { errs() << ToolName << ": Timeout value too large, must be less than: " << std::numeric_limits<uint32_t>::max() / 1000 << '\n'; return -1; } std::string CommandLine(ProgramToRun); std::error_code ec; ProgramToRun = FindProgram(ProgramToRun, ec); if (ec) { errs() << ToolName << ": Failed to find program: '" << CommandLine << "': " << ec.message() << '\n'; return -1; } if (TraceExecution) errs() << ToolName << ": Found Program: " << ProgramToRun << '\n'; for (std::vector<std::string>::iterator i = Argv.begin(), e = Argv.end(); i != e; ++i) { CommandLine.push_back(' '); CommandLine.append(*i); } if (TraceExecution) errs() << ToolName << ": Program Image Path: " << ProgramToRun << '\n' << ToolName << ": Command Line: " << CommandLine << '\n'; STARTUPINFO StartupInfo; PROCESS_INFORMATION ProcessInfo; std::memset(&StartupInfo, 0, sizeof(StartupInfo)); StartupInfo.cb = sizeof(StartupInfo); std::memset(&ProcessInfo, 0, sizeof(ProcessInfo)); // Set error mode to not display any message boxes. The child process inherits // this. ::SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX); ::_set_error_mode(_OUT_TO_STDERR); BOOL success = ::CreateProcessA(ProgramToRun.c_str(), LPSTR(CommandLine.c_str()), NULL, NULL, FALSE, DEBUG_PROCESS, NULL, NULL, &StartupInfo, &ProcessInfo); if (!success) { errs() << ToolName << ": Failed to run program: '" << ProgramToRun << "': " << std::error_code(windows_error(::GetLastError())).message() << '\n'; return -1; } // Make sure ::CloseHandle is called on exit. std::map<DWORD, HANDLE> ProcessIDToHandle; DEBUG_EVENT DebugEvent; std::memset(&DebugEvent, 0, sizeof(DebugEvent)); DWORD dwContinueStatus = DBG_CONTINUE; // Run the program under the debugger until either it exits, or throws an // exception. if (TraceExecution) errs() << ToolName << ": Debugging...\n"; while(true) { DWORD TimeLeft = INFINITE; if (Timeout > 0) { FILETIME CreationTime, ExitTime, KernelTime, UserTime; ULARGE_INTEGER a, b; success = ::GetProcessTimes(ProcessInfo.hProcess, &CreationTime, &ExitTime, &KernelTime, &UserTime); if (!success) { ec = windows_error(::GetLastError()); errs() << ToolName << ": Failed to get process times: " << ec.message() << '\n'; return -1; } a.LowPart = KernelTime.dwLowDateTime; a.HighPart = KernelTime.dwHighDateTime; b.LowPart = UserTime.dwLowDateTime; b.HighPart = UserTime.dwHighDateTime; // Convert 100-nanosecond units to milliseconds. uint64_t TotalTimeMiliseconds = (a.QuadPart + b.QuadPart) / 10000; // Handle the case where the process has been running for more than 49 // days. if (TotalTimeMiliseconds > std::numeric_limits<uint32_t>::max()) { errs() << ToolName << ": Timeout Failed: Process has been running for" "more than 49 days.\n"; return -1; } // We check with > instead of using Timeleft because if // TotalTimeMiliseconds is greater than Timeout * 1000, TimeLeft would // underflow. if (TotalTimeMiliseconds > (Timeout * 1000)) { errs() << ToolName << ": Process timed out.\n"; ::TerminateProcess(ProcessInfo.hProcess, -1); // Otherwise other stuff starts failing... return -1; } TimeLeft = (Timeout * 1000) - static_cast<uint32_t>(TotalTimeMiliseconds); } success = WaitForDebugEvent(&DebugEvent, TimeLeft); if (!success) { DWORD LastError = ::GetLastError(); ec = windows_error(LastError); if (LastError == ERROR_SEM_TIMEOUT || LastError == WSAETIMEDOUT) { errs() << ToolName << ": Process timed out.\n"; ::TerminateProcess(ProcessInfo.hProcess, -1); // Otherwise other stuff starts failing... return -1; } errs() << ToolName << ": Failed to wait for debug event in program: '" << ProgramToRun << "': " << ec.message() << '\n'; return -1; } switch(DebugEvent.dwDebugEventCode) { case CREATE_PROCESS_DEBUG_EVENT: // Make sure we remove the handle on exit. if (TraceExecution) errs() << ToolName << ": Debug Event: CREATE_PROCESS_DEBUG_EVENT\n"; ProcessIDToHandle[DebugEvent.dwProcessId] = DebugEvent.u.CreateProcessInfo.hProcess; ::CloseHandle(DebugEvent.u.CreateProcessInfo.hFile); break; case EXIT_PROCESS_DEBUG_EVENT: { if (TraceExecution) errs() << ToolName << ": Debug Event: EXIT_PROCESS_DEBUG_EVENT\n"; // If this is the process we originally created, exit with its exit // code. if (DebugEvent.dwProcessId == ProcessInfo.dwProcessId) return DebugEvent.u.ExitProcess.dwExitCode; // Otherwise cleanup any resources we have for it. std::map<DWORD, HANDLE>::iterator ExitingProcess = ProcessIDToHandle.find(DebugEvent.dwProcessId); if (ExitingProcess == ProcessIDToHandle.end()) { errs() << ToolName << ": Got unknown process id!\n"; return -1; } ::CloseHandle(ExitingProcess->second); ProcessIDToHandle.erase(ExitingProcess); } break; case CREATE_THREAD_DEBUG_EVENT: ::CloseHandle(DebugEvent.u.CreateThread.hThread); break; case LOAD_DLL_DEBUG_EVENT: { // Cleanup the file handle. FileScopedHandle DLLFile(DebugEvent.u.LoadDll.hFile); std::string DLLName; ec = GetFileNameFromHandle(DLLFile, DLLName); if (ec) { DLLName = "<failed to get file name from file handle> : "; DLLName += ec.message(); } if (TraceExecution) { errs() << ToolName << ": Debug Event: LOAD_DLL_DEBUG_EVENT\n"; errs().indent(ToolName.size()) << ": DLL Name : " << DLLName << '\n'; } if (NoUser32 && sys::path::stem(DLLName) == "user32") { // Program is loading user32.dll, in the applications we are testing, // this only happens if an assert has fired. By now the message has // already been printed, so simply close the program. errs() << ToolName << ": user32.dll loaded!\n"; errs().indent(ToolName.size()) << ": This probably means that assert was called. Closing " "program to prevent message box from popping up.\n"; dwContinueStatus = DBG_CONTINUE; ::TerminateProcess(ProcessIDToHandle[DebugEvent.dwProcessId], -1); return -1; } } break; case EXCEPTION_DEBUG_EVENT: { // Close the application if this exception will not be handled by the // child application. if (TraceExecution) errs() << ToolName << ": Debug Event: EXCEPTION_DEBUG_EVENT\n"; EXCEPTION_DEBUG_INFO &Exception = DebugEvent.u.Exception; if (Exception.dwFirstChance > 0) { if (TraceExecution) { errs().indent(ToolName.size()) << ": Debug Info : "; errs() << "First chance exception at " << Exception.ExceptionRecord.ExceptionAddress << ", exception code: " << ExceptionCodeToString( Exception.ExceptionRecord.ExceptionCode) << " (" << Exception.ExceptionRecord.ExceptionCode << ")\n"; } dwContinueStatus = DBG_EXCEPTION_NOT_HANDLED; } else { errs() << ToolName << ": Unhandled exception in: " << ProgramToRun << "!\n"; errs().indent(ToolName.size()) << ": location: "; errs() << Exception.ExceptionRecord.ExceptionAddress << ", exception code: " << ExceptionCodeToString( Exception.ExceptionRecord.ExceptionCode) << " (" << Exception.ExceptionRecord.ExceptionCode << ")\n"; dwContinueStatus = DBG_CONTINUE; ::TerminateProcess(ProcessIDToHandle[DebugEvent.dwProcessId], -1); return -1; } } break; default: // Do nothing. if (TraceExecution) errs() << ToolName << ": Debug Event: <unknown>\n"; break; } success = ContinueDebugEvent(DebugEvent.dwProcessId, DebugEvent.dwThreadId, dwContinueStatus); if (!success) { ec = windows_error(::GetLastError()); errs() << ToolName << ": Failed to continue debugging program: '" << ProgramToRun << "': " << ec.message() << '\n'; return -1; } dwContinueStatus = DBG_CONTINUE; } assert(0 && "Fell out of debug loop. This shouldn't be possible!"); return -1; }
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/crosstool/create-snapshots.sh
#!/bin/bash # # Creates LLVM SVN snapshots: llvm-$REV.tar.bz2 and llvm-gcc-4.2-$REV.tar.bz2, # where $REV is an SVN revision of LLVM. This is used for creating stable # tarballs which can be used to build known-to-work crosstools. # # Syntax: # $0 [REV] -- grabs the revision $REV from SVN; if not specified, grabs the # latest SVN revision. set -o nounset set -o errexit readonly LLVM_PROJECT_SVN="http://llvm.org/svn/llvm-project" getLatestRevisionFromSVN() { svn info ${LLVM_PROJECT_SVN} | egrep ^Revision | sed 's/^Revision: //' } readonly REV="${1:-$(getLatestRevisionFromSVN)}" createTarballFromSVN() { local module=$1 local log="${module}.log" echo "Running: svn export -r ${REV} ${module}; log in ${log}" svn -q export -r ${REV} ${LLVM_PROJECT_SVN}/${module}/trunk \ ${module} > ${log} 2>&1 # Create "module-revision.tar.bz2" packages from the SVN checkout dirs. local tarball="${module}-${REV}.tar.bz2" echo "Creating tarball: ${tarball}" tar cjf ${tarball} ${module} echo "Cleaning up '${module}'" rm -rf ${module} ${log} } for module in "llvm" "llvm-gcc-4.2"; do createTarballFromSVN ${module} done
0
repos/DirectXShaderCompiler/utils/crosstool
repos/DirectXShaderCompiler/utils/crosstool/ARM/build-install-linux.sh
#!/bin/bash # # Compiles and installs a Linux/x86_64 -> Linux/ARM crosstool based on LLVM and # LLVM-GCC-4.2 using SVN snapshots in provided tarballs. set -o nounset set -o errexit echo -n "Welcome to LLVM Linux/X86_64 -> Linux/ARM crosstool " echo "builder/installer; some steps will require sudo privileges." readonly INSTALL_ROOT="${INSTALL_ROOT:-/usr/local/crosstool}" # Both $USER and root *must* have read/write access to this dir. readonly SCRATCH_ROOT=$(mktemp -d "${TMPDIR:-/tmp}/llvm-project.XXXXXX") readonly SRC_ROOT="${SCRATCH_ROOT}/src" readonly OBJ_ROOT="${SCRATCH_ROOT}/obj" readonly CROSS_HOST="x86_64-unknown-linux-gnu" readonly CROSS_TARGET="arm-none-linux-gnueabi" readonly CROSS_MARCH="${CROSS_MARCH:-armv6}" readonly CODE_SOURCERY="${INSTALL_ROOT}/codesourcery" readonly CODE_SOURCERY_PKG_PATH="${CODE_SOURCERY_PKG_PATH:-${HOME}/codesourcery}" readonly CODE_SOURCERY_HTTP="http://www.codesourcery.com/sgpp/lite/arm/portal/package1787/public" readonly CODE_SOURCERY_PKG="arm-2007q3-51-arm-none-linux-gnueabi-i686-pc-linux-gnu.tar.bz2" readonly CODE_SOURCERY_ROOT="${CODE_SOURCERY}/arm-2007q3" readonly CODE_SOURCERY_BIN="${CODE_SOURCERY_ROOT}/bin" # Make sure ${CROSS_TARGET}-* binutils are in command path export PATH="${CODE_SOURCERY_BIN}:${PATH}" readonly CROSS_TARGET_AS="${CODE_SOURCERY_BIN}/${CROSS_TARGET}-as" readonly CROSS_TARGET_LD="${CODE_SOURCERY_BIN}/${CROSS_TARGET}-ld" readonly SYSROOT="${CODE_SOURCERY_ROOT}/${CROSS_TARGET}/libc" readonly LLVM_PKG_PATH="${LLVM_PKG_PATH:-${HOME}/llvm-project/snapshots}" # Latest SVN revisions known to be working in this configuration. readonly LLVM_DEFAULT_REV="74530" readonly LLVMGCC_DEFAULT_REV="74535" readonly LLVM_PKG="llvm-${LLVM_SVN_REV:-${LLVM_DEFAULT_REV}}.tar.bz2" readonly LLVM_SRC_DIR="${SRC_ROOT}/llvm" readonly LLVM_OBJ_DIR="${OBJ_ROOT}/llvm" readonly LLVM_INSTALL_DIR="${INSTALL_ROOT}/${CROSS_TARGET}/llvm" readonly LLVMGCC_PKG="llvm-gcc-4.2-${LLVMGCC_SVN_REV:-${LLVMGCC_DEFAULT_REV}}.tar.bz2" readonly LLVMGCC_SRC_DIR="${SRC_ROOT}/llvm-gcc-4.2" readonly LLVMGCC_OBJ_DIR="${OBJ_ROOT}/llvm-gcc-4.2" readonly LLVMGCC_INSTALL_DIR="${INSTALL_ROOT}/${CROSS_TARGET}/llvm-gcc-4.2" readonly MAKE_OPTS="${MAKE_OPTS:--j2}" # Params: # $1: directory to be created # $2: optional mkdir command prefix, e.g. "sudo" createDir() { if [[ ! -e $1 ]]; then ${2:-} mkdir -p $1 elif [[ -e $1 && ! -d $1 ]]; then echo "$1 exists but is not a directory; exiting." exit 3 fi } sudoCreateDir() { createDir $1 sudo sudo chown ${USER} $1 } # Prints out and runs the command, but without logging -- intended for use with # lightweight commands that don't have useful output to parse, e.g. mkdir, tar, # etc. runCommand() { local message="$1" shift echo "=> $message" echo "==> Running: $*" $* } runAndLog() { local message="$1" local log_file="$2" shift 2 echo "=> $message; log in $log_file" echo "==> Running: $*" # Pop-up a terminal with the output of the current command? # e.g.: xterm -e /bin/bash -c "$* >| tee $log_file" $* &> $log_file if [[ $? != 0 ]]; then echo "Error occurred: see most recent log file for details." exit fi } installCodeSourcery() { # Unpack the tarball, creating the CodeSourcery dir, if necessary. if [[ ! -d ${CODE_SOURCERY_ROOT} ]]; then sudoCreateDir ${CODE_SOURCERY} cd ${CODE_SOURCERY} if [[ -e ${CODE_SOURCERY_PKG_PATH}/${CODE_SOURCERY_PKG} ]]; then runCommand "Unpacking CodeSourcery in ${CODE_SOURCERY}" \ tar jxf ${CODE_SOURCERY_PKG_PATH}/${CODE_SOURCERY_PKG} else echo -n "CodeSourcery tarball not found in " echo "${CODE_SOURCERY_PKG_PATH}/${CODE_SOURCERY_PKG}" echo -n "Fix the path or download it from " echo "${CODE_SOURCERY_HTTP}/${CROSS_TARGET}/${CODE_SOURCERY_PKG}" exit fi else echo "CodeSourcery install dir already exists; skipping." fi # Verify our CodeSourcery toolchain installation. if [[ ! -d "${SYSROOT}" ]]; then echo -n "Error: CodeSourcery does not contain libc for ${CROSS_TARGET}: " echo "${SYSROOT} not found." exit fi for tool in ${CROSS_TARGET_AS} ${CROSS_TARGET_LD}; do if [[ ! -e $tool ]]; then echo "${tool} not found; exiting." exit fi done } installLLVM() { if [[ -d ${LLVM_INSTALL_DIR} ]]; then echo "LLVM install dir ${LLVM_INSTALL_DIR} exists; skipping." return fi sudoCreateDir ${LLVM_INSTALL_DIR} # Unpack LLVM tarball; should create the directory "llvm". cd ${SRC_ROOT} runCommand "Unpacking LLVM" tar jxf ${LLVM_PKG_PATH}/${LLVM_PKG} # Configure, build, and install LLVM. createDir ${LLVM_OBJ_DIR} cd ${LLVM_OBJ_DIR} runAndLog "Configuring LLVM" ${LLVM_OBJ_DIR}/llvm-configure.log \ ${LLVM_SRC_DIR}/configure \ --disable-jit \ --enable-optimized \ --prefix=${LLVM_INSTALL_DIR} \ --target=${CROSS_TARGET} \ --with-llvmgccdir=${LLVMGCC_INSTALL_DIR} runAndLog "Building LLVM" ${LLVM_OBJ_DIR}/llvm-build.log \ make ${MAKE_OPTS} runAndLog "Installing LLVM" ${LLVM_OBJ_DIR}/llvm-install.log \ make ${MAKE_OPTS} install } installLLVMGCC() { if [[ -d ${LLVMGCC_INSTALL_DIR} ]]; then echo "LLVM-GCC install dir ${LLVMGCC_INSTALL_DIR} exists; skipping." return fi sudoCreateDir ${LLVMGCC_INSTALL_DIR} # Unpack LLVM-GCC tarball; should create the directory "llvm-gcc-4.2". cd ${SRC_ROOT} runCommand "Unpacking LLVM-GCC" tar jxf ${LLVM_PKG_PATH}/${LLVMGCC_PKG} # Configure, build, and install LLVM-GCC. createDir ${LLVMGCC_OBJ_DIR} cd ${LLVMGCC_OBJ_DIR} runAndLog "Configuring LLVM-GCC" ${LLVMGCC_OBJ_DIR}/llvmgcc-configure.log \ ${LLVMGCC_SRC_DIR}/configure \ --enable-languages=c,c++ \ --enable-llvm=${LLVM_INSTALL_DIR} \ --prefix=${LLVMGCC_INSTALL_DIR} \ --program-prefix=llvm- \ --target=${CROSS_TARGET} \ --with-arch=${CROSS_MARCH} \ --with-as=${CROSS_TARGET_AS} \ --with-ld=${CROSS_TARGET_LD} \ --with-sysroot=${SYSROOT} runAndLog "Building LLVM-GCC" ${LLVMGCC_OBJ_DIR}/llvmgcc-build.log \ make runAndLog "Installing LLVM-GCC" ${LLVMGCC_OBJ_DIR}/llvmgcc-install.log \ make install } echo "Building in ${SCRATCH_ROOT}; installing in ${INSTALL_ROOT}" createDir ${SRC_ROOT} createDir ${OBJ_ROOT} installCodeSourcery installLLVM installLLVMGCC echo "Done."
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/valgrind/i386-pc-linux-gnu.supp
{ False leak under RegisterPass Memcheck:Leak ... fun:_ZN83_GLOBAL_*PassRegistrar12RegisterPassERKN4llvm8PassInfoE fun:_ZN4llvm8PassInfo12registerPassEv } # Python false positives according to # http://svn.python.org/projects/python/trunk/Misc/README.valgrind { ADDRESS_IN_RANGE/Invalid read of size 4 Memcheck:Addr4 obj:/usr/bin/python* } { ADDRESS_IN_RANGE/Invalid read of size 4 Memcheck:Value4 obj:/usr/bin/python* } { ADDRESS_IN_RANGE/Conditional jump or move depends on uninitialised value Memcheck:Cond obj:/usr/bin/python* } { We don't care if as leaks Memcheck:Leak obj:/usr/bin/as } { We don't care if python leaks Memcheck:Leak fun:malloc obj:/usr/bin/python* } { We don't care about anything ld.so does. Memcheck:Cond obj:/lib/ld*.so }
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/valgrind/x86_64-pc-linux-gnu.supp
{ False leak under RegisterPass Memcheck:Leak ... fun:_ZN4llvm12PassRegistry12registerPassERKNS_8PassInfoE } # Python false positives according to # http://svn.python.org/projects/python/trunk/Misc/README.valgrind { ADDRESS_IN_RANGE/Invalid read of size 4 Memcheck:Addr4 obj:/usr/bin/python* } { ADDRESS_IN_RANGE/Invalid read of size 4 Memcheck:Value8 obj:/usr/bin/python* } { ADDRESS_IN_RANGE/Conditional jump or move depends on uninitialised value Memcheck:Cond obj:/usr/bin/python* } { We don't care if as leaks Memcheck:Leak obj:/usr/bin/as } { We don't care if bash leaks Memcheck:Leak fun:malloc fun:xmalloc obj:/bin/bash } { We don't care of cmp Memcheck:Cond obj:/usr/bin/cmp } { We don't care if grep leaks Memcheck:Leak obj:/bin/grep } { We don't care if python leaks Memcheck:Leak fun:malloc obj:/usr/bin/python* } { We don't care if sed leaks Memcheck:Leak fun:calloc fun:malloc obj:/bin/sed } { We don't care about anything ld.so does. Memcheck:Cond obj:/lib/ld*.so } { suppress optimized strcasecmp, to be fixed in valgrind 3.6.1 Memcheck:Value8 fun:__GI___strcasecmp_l } { suppress optimized strcasecmp, to be fixed in valgrind 3.6.1 Memcheck:Addr8 fun:__GI___strcasecmp_l }
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/llvm-build/README.txt
============================== llvm-build - LLVM Build Tool ============================== `llvm-build` is a tool for helping build the LLVM project.
0
repos/DirectXShaderCompiler/utils/llvm-build
repos/DirectXShaderCompiler/utils/llvm-build/llvmbuild/main.py
from __future__ import absolute_import import filecmp import os import sys import llvmbuild.componentinfo as componentinfo import llvmbuild.configutil as configutil from llvmbuild.util import fatal, note ### def cmake_quote_string(value): """ cmake_quote_string(value) -> str Return a quoted form of the given value that is suitable for use in CMake language files. """ # Currently, we only handle escaping backslashes. value = value.replace("\\", "\\\\") return value def cmake_quote_path(value): """ cmake_quote_path(value) -> str Return a quoted form of the given value that is suitable for use in CMake language files. """ # CMake has a bug in it's Makefile generator that doesn't properly quote # strings it generates. So instead of using proper quoting, we just use "/" # style paths. Currently, we only handle escaping backslashes. value = value.replace("\\", "/") return value def mk_quote_string_for_target(value): """ mk_quote_string_for_target(target_name) -> str Return a quoted form of the given target_name suitable for including in a Makefile as a target name. """ # The only quoting we currently perform is for ':', to support msys users. return value.replace(":", "\\:") def make_install_dir(path): """ make_install_dir(path) -> None Create the given directory path for installation, including any parents. """ # os.makedirs considers it an error to be called with an existent path. if not os.path.exists(path): os.makedirs(path) ### class LLVMProjectInfo(object): @staticmethod def load_infos_from_path(llvmbuild_source_root): def recurse(subpath): # Load the LLVMBuild file. llvmbuild_path = os.path.join(llvmbuild_source_root + subpath, 'LLVMBuild.txt') if not os.path.exists(llvmbuild_path): fatal("missing LLVMBuild.txt file at: %r" % (llvmbuild_path,)) # Parse the components from it. common,info_iter = componentinfo.load_from_path(llvmbuild_path, subpath) for info in info_iter: yield info # Recurse into the specified subdirectories. for subdir in common.get_list("subdirectories"): for item in recurse(os.path.join(subpath, subdir)): yield item return recurse("/") @staticmethod def load_from_path(source_root, llvmbuild_source_root): infos = list( LLVMProjectInfo.load_infos_from_path(llvmbuild_source_root)) return LLVMProjectInfo(source_root, infos) def __init__(self, source_root, component_infos): # Store our simple ivars. self.source_root = source_root self.component_infos = list(component_infos) self.component_info_map = None self.ordered_component_infos = None def validate_components(self): """validate_components() -> None Validate that the project components are well-defined. Among other things, this checks that: - Components have valid references. - Components references do not form cycles. We also construct the map from component names to info, and the topological ordering of components. """ # Create the component info map and validate that component names are # unique. self.component_info_map = {} for ci in self.component_infos: existing = self.component_info_map.get(ci.name) if existing is not None: # We found a duplicate component name, report it and error out. fatal("found duplicate component %r (at %r and %r)" % ( ci.name, ci.subpath, existing.subpath)) self.component_info_map[ci.name] = ci # Disallow 'all' as a component name, which is a special case. if 'all' in self.component_info_map: fatal("project is not allowed to define 'all' component") # Add the root component. if '$ROOT' in self.component_info_map: fatal("project is not allowed to define $ROOT component") self.component_info_map['$ROOT'] = componentinfo.GroupComponentInfo( '/', '$ROOT', None) self.component_infos.append(self.component_info_map['$ROOT']) # Topologically order the component information according to their # component references. def visit_component_info(ci, current_stack, current_set): # Check for a cycles. if ci in current_set: # We found a cycle, report it and error out. cycle_description = ' -> '.join( '%r (%s)' % (ci.name, relation) for relation,ci in current_stack) fatal("found cycle to %r after following: %s -> %s" % ( ci.name, cycle_description, ci.name)) # If we have already visited this item, we are done. if ci not in components_to_visit: return # Otherwise, mark the component info as visited and traverse. components_to_visit.remove(ci) # Validate the parent reference, which we treat specially. if ci.parent is not None: parent = self.component_info_map.get(ci.parent) if parent is None: fatal("component %r has invalid reference %r (via %r)" % ( ci.name, ci.parent, 'parent')) ci.set_parent_instance(parent) for relation,referent_name in ci.get_component_references(): # Validate that the reference is ok. referent = self.component_info_map.get(referent_name) if referent is None: fatal("component %r has invalid reference %r (via %r)" % ( ci.name, referent_name, relation)) # Visit the reference. current_stack.append((relation,ci)) current_set.add(ci) visit_component_info(referent, current_stack, current_set) current_set.remove(ci) current_stack.pop() # Finally, add the component info to the ordered list. self.ordered_component_infos.append(ci) # FIXME: We aren't actually correctly checking for cycles along the # parent edges. Haven't decided how I want to handle this -- I thought # about only checking cycles by relation type. If we do that, it falls # out easily. If we don't, we should special case the check. self.ordered_component_infos = [] components_to_visit = sorted( set(self.component_infos), key = lambda c: c.name) while components_to_visit: visit_component_info(components_to_visit[0], [], set()) # Canonicalize children lists. for c in self.ordered_component_infos: c.children.sort(key = lambda c: c.name) def print_tree(self): def visit(node, depth = 0): print('%s%-40s (%s)' % (' '*depth, node.name, node.type_name)) for c in node.children: visit(c, depth + 1) visit(self.component_info_map['$ROOT']) def write_components(self, output_path): # Organize all the components by the directory their LLVMBuild file # should go in. info_basedir = {} for ci in self.component_infos: # Ignore the $ROOT component. if ci.parent is None: continue info_basedir[ci.subpath] = info_basedir.get(ci.subpath, []) + [ci] # Compute the list of subdirectories to scan. subpath_subdirs = {} for ci in self.component_infos: # Ignore root components. if ci.subpath == '/': continue # Otherwise, append this subpath to the parent list. parent_path = os.path.dirname(ci.subpath) subpath_subdirs[parent_path] = parent_list = subpath_subdirs.get( parent_path, set()) parent_list.add(os.path.basename(ci.subpath)) # Generate the build files. for subpath, infos in info_basedir.items(): # Order the components by name to have a canonical ordering. infos.sort(key = lambda ci: ci.name) # Format the components into llvmbuild fragments. fragments = [] # Add the common fragments. subdirectories = subpath_subdirs.get(subpath) if subdirectories: fragment = """\ subdirectories = %s """ % (" ".join(sorted(subdirectories)),) fragments.append(("common", fragment)) # Add the component fragments. num_common_fragments = len(fragments) for ci in infos: fragment = ci.get_llvmbuild_fragment() if fragment is None: continue name = "component_%d" % (len(fragments) - num_common_fragments) fragments.append((name, fragment)) if not fragments: continue assert subpath.startswith('/') directory_path = os.path.join(output_path, subpath[1:]) # Create the directory if it does not already exist. if not os.path.exists(directory_path): os.makedirs(directory_path) # In an effort to preserve comments (which aren't parsed), read in # the original file and extract the comments. We only know how to # associate comments that prefix a section name. f = open(infos[0]._source_path) comments_map = {} comment_block = "" for ln in f: if ln.startswith(';'): comment_block += ln elif ln.startswith('[') and ln.endswith(']\n'): comments_map[ln[1:-2]] = comment_block else: comment_block = "" f.close() # Create the LLVMBuild fil[e. file_path = os.path.join(directory_path, 'LLVMBuild.txt') f = open(file_path, "w") # Write the header. header_fmt = ';===- %s %s-*- Conf -*--===;' header_name = '.' + os.path.join(subpath, 'LLVMBuild.txt') header_pad = '-' * (80 - len(header_fmt % (header_name, ''))) header_string = header_fmt % (header_name, header_pad) f.write("""\ %s ; ; The LLVM Compiler Infrastructure ; ; This file is distributed under the University of Illinois Open Source ; License. See LICENSE.TXT for details. ; ;===------------------------------------------------------------------------===; ; ; This is an LLVMBuild description file for the components in this subdirectory. ; ; For more information on the LLVMBuild system, please see: ; ; http://llvm.org/docs/LLVMBuild.html ; ;===------------------------------------------------------------------------===; """ % header_string) # Write out each fragment.each component fragment. for name,fragment in fragments: comment = comments_map.get(name) if comment is not None: f.write(comment) f.write("[%s]\n" % name) f.write(fragment) if fragment is not fragments[-1][1]: f.write('\n') f.close() def write_library_table(self, output_path, enabled_optional_components): # Write out the mapping from component names to required libraries. # # We do this in topological order so that we know we can append the # dependencies for added library groups. entries = {} for c in self.ordered_component_infos: # Skip optional components which are not enabled. if c.type_name == 'OptionalLibrary' \ and c.name not in enabled_optional_components: continue # Skip target groups which are not enabled. tg = c.get_parent_target_group() if tg and not tg.enabled: continue # Only certain components are in the table. if c.type_name not in ('Library', 'OptionalLibrary', \ 'LibraryGroup', 'TargetGroup'): continue # Compute the llvm-config "component name". For historical reasons, # this is lowercased based on the library name. llvmconfig_component_name = c.get_llvmconfig_component_name() # Get the library name, or None for LibraryGroups. if c.type_name == 'Library' or c.type_name == 'OptionalLibrary': library_name = c.get_prefixed_library_name() is_installed = c.installed else: library_name = None is_installed = True # Get the component names of all the required libraries. required_llvmconfig_component_names = [ self.component_info_map[dep].get_llvmconfig_component_name() for dep in c.required_libraries] # Insert the entries for library groups we should add to. for dep in c.add_to_library_groups: entries[dep][2].append(llvmconfig_component_name) # Add the entry. entries[c.name] = (llvmconfig_component_name, library_name, required_llvmconfig_component_names, is_installed) # Convert to a list of entries and sort by name. entries = list(entries.values()) # Create an 'all' pseudo component. We keep the dependency list small by # only listing entries that have no other dependents. root_entries = set(e[0] for e in entries) for _,_,deps,_ in entries: root_entries -= set(deps) entries.append(('all', None, root_entries, True)) entries.sort() # Compute the maximum number of required libraries, plus one so there is # always a sentinel. max_required_libraries = max(len(deps) for _,_,deps,_ in entries) + 1 # Write out the library table. make_install_dir(os.path.dirname(output_path)) f = open(output_path+'.new', 'w') f.write("""\ //===- llvm-build generated file --------------------------------*- C++ -*-===// // // Component Library Depenedency Table // // Automatically generated file, do not edit! // //===----------------------------------------------------------------------===// """) f.write('struct AvailableComponent {\n') f.write(' /// The name of the component.\n') f.write(' const char *Name;\n') f.write('\n') f.write(' /// The name of the library for this component (or NULL).\n') f.write(' const char *Library;\n') f.write('\n') f.write(' /// Whether the component is installed.\n') f.write(' bool IsInstalled;\n') f.write('\n') f.write('\ /// The list of libraries required when linking this component.\n') f.write(' const char *RequiredLibraries[%d];\n' % ( max_required_libraries)) f.write('} AvailableComponents[%d] = {\n' % len(entries)) for name,library_name,required_names,is_installed in entries: if library_name is None: library_name_as_cstr = '0' else: library_name_as_cstr = '"lib%s.a"' % library_name f.write(' { "%s", %s, %d, { %s } },\n' % ( name, library_name_as_cstr, is_installed, ', '.join('"%s"' % dep for dep in required_names))) f.write('};\n') f.close() if not os.path.isfile(output_path): os.rename(output_path+'.new', output_path) elif filecmp.cmp(output_path, output_path+'.new'): os.remove(output_path+'.new') else: os.remove(output_path) os.rename(output_path+'.new', output_path) def get_required_libraries_for_component(self, ci, traverse_groups = False): """ get_required_libraries_for_component(component_info) -> iter Given a Library component info descriptor, return an iterator over all of the directly required libraries for linking with this component. If traverse_groups is True, then library and target groups will be traversed to include their required libraries. """ assert ci.type_name in ('Library', 'OptionalLibrary', 'LibraryGroup', 'TargetGroup') for name in ci.required_libraries: # Get the dependency info. dep = self.component_info_map[name] # If it is a library, yield it. if dep.type_name == 'Library' or dep.type_name == 'OptionalLibrary': yield dep continue # Otherwise if it is a group, yield or traverse depending on what # was requested. if dep.type_name in ('LibraryGroup', 'TargetGroup'): if not traverse_groups: yield dep continue for res in self.get_required_libraries_for_component(dep, True): yield res def get_fragment_dependencies(self): """ get_fragment_dependencies() -> iter Compute the list of files (as absolute paths) on which the output fragments depend (i.e., files for which a modification should trigger a rebuild of the fragment). """ # Construct a list of all the dependencies of the Makefile fragment # itself. These include all the LLVMBuild files themselves, as well as # all of our own sources. # # Many components may come from the same file, so we make sure to unique # these. build_paths = set() for ci in self.component_infos: p = os.path.join(self.source_root, ci.subpath[1:], 'LLVMBuild.txt') if p not in build_paths: yield p build_paths.add(p) # Gather the list of necessary sources by just finding all loaded # modules that are inside the LLVM source tree. for module in sys.modules.values(): # Find the module path. if not hasattr(module, '__file__'): continue path = getattr(module, '__file__') if not path: continue # Strip off any compiled suffix. if os.path.splitext(path)[1] in ['.pyc', '.pyo', '.pyd']: path = path[:-1] # If the path exists and is in the source tree, consider it a # dependency. if (path.startswith(self.source_root) and os.path.exists(path)): yield path def write_cmake_fragment(self, output_path, enabled_optional_components): """ write_cmake_fragment(output_path) -> None Generate a CMake fragment which includes all of the collated LLVMBuild information in a format that is easily digestible by a CMake. The exact contents of this are closely tied to how the CMake configuration integrates LLVMBuild, see CMakeLists.txt in the top-level. """ dependencies = list(self.get_fragment_dependencies()) # Write out the CMake fragment. make_install_dir(os.path.dirname(output_path)) f = open(output_path, 'w') # Write the header. header_fmt = '\ #===-- %s - LLVMBuild Configuration for LLVM %s-*- CMake -*--===#' header_name = os.path.basename(output_path) header_pad = '-' * (80 - len(header_fmt % (header_name, ''))) header_string = header_fmt % (header_name, header_pad) f.write("""\ %s # # The LLVM Compiler Infrastructure # # This file is distributed under the University of Illinois Open Source # License. See LICENSE.TXT for details. # #===------------------------------------------------------------------------===# # # This file contains the LLVMBuild project information in a format easily # consumed by the CMake based build system. # # This file is autogenerated by llvm-build, do not edit! # #===------------------------------------------------------------------------===# """ % header_string) # Write the dependency information in the best way we can. f.write(""" # LLVMBuild CMake fragment dependencies. # # CMake has no builtin way to declare that the configuration depends on # a particular file. However, a side effect of configure_file is to add # said input file to CMake's internal dependency list. So, we use that # and a dummy output file to communicate the dependency information to # CMake. # # FIXME: File a CMake RFE to get a properly supported version of this # feature. if(NOT HLSL_OFFICIAL_BUILD) """) for dep in dependencies: f.write("""\ configure_file(\"%s\" ${CMAKE_CURRENT_BINARY_DIR}/DummyConfigureOutput)\n""" % ( cmake_quote_path(dep),)) f.write(""" endif(NOT HLSL_OFFICIAL_BUILD) """) # Write the properties we use to encode the required library dependency # information in a form CMake can easily use directly. f.write(""" # Explicit library dependency information. # # The following property assignments effectively create a map from component # names to required libraries, in a way that is easily accessed from CMake. """) for ci in self.ordered_component_infos: # Skip optional components which are not enabled. if ci.type_name == 'OptionalLibrary' \ and ci.name not in enabled_optional_components: continue # We only write the information for certain components currently. if ci.type_name not in ('Library', 'OptionalLibrary'): continue f.write("""\ set_property(GLOBAL PROPERTY LLVMBUILD_LIB_DEPS_%s %s)\n""" % ( ci.get_prefixed_library_name(), " ".join(sorted( dep.get_prefixed_library_name() for dep in self.get_required_libraries_for_component(ci))))) f.close() def write_cmake_exports_fragment(self, output_path, enabled_optional_components): """ write_cmake_exports_fragment(output_path) -> None Generate a CMake fragment which includes LLVMBuild library dependencies expressed similarly to how CMake would write them via install(EXPORT). """ dependencies = list(self.get_fragment_dependencies()) # Write out the CMake exports fragment. make_install_dir(os.path.dirname(output_path)) f = open(output_path, 'w') f.write("""\ # Explicit library dependency information. # # The following property assignments tell CMake about link # dependencies of libraries imported from LLVM. """) for ci in self.ordered_component_infos: # Skip optional components which are not enabled. if ci.type_name == 'OptionalLibrary' \ and ci.name not in enabled_optional_components: continue # We only write the information for libraries currently. if ci.type_name not in ('Library', 'OptionalLibrary'): continue # Skip disabled targets. tg = ci.get_parent_target_group() if tg and not tg.enabled: continue f.write("""\ set_property(TARGET %s PROPERTY IMPORTED_LINK_INTERFACE_LIBRARIES %s)\n""" % ( ci.get_prefixed_library_name(), " ".join(sorted( dep.get_prefixed_library_name() for dep in self.get_required_libraries_for_component(ci))))) f.close() def write_make_fragment(self, output_path): """ write_make_fragment(output_path) -> None Generate a Makefile fragment which includes all of the collated LLVMBuild information in a format that is easily digestible by a Makefile. The exact contents of this are closely tied to how the LLVM Makefiles integrate LLVMBuild, see Makefile.rules in the top-level. """ dependencies = list(self.get_fragment_dependencies()) # Write out the Makefile fragment. make_install_dir(os.path.dirname(output_path)) f = open(output_path, 'w') # Write the header. header_fmt = '\ #===-- %s - LLVMBuild Configuration for LLVM %s-*- Makefile -*--===#' header_name = os.path.basename(output_path) header_pad = '-' * (80 - len(header_fmt % (header_name, ''))) header_string = header_fmt % (header_name, header_pad) f.write("""\ %s # # The LLVM Compiler Infrastructure # # This file is distributed under the University of Illinois Open Source # License. See LICENSE.TXT for details. # #===------------------------------------------------------------------------===# # # This file contains the LLVMBuild project information in a format easily # consumed by the Makefile based build system. # # This file is autogenerated by llvm-build, do not edit! # #===------------------------------------------------------------------------===# """ % header_string) # Write the dependencies for the fragment. # # FIXME: Technically, we need to properly quote for Make here. f.write("""\ # Clients must explicitly enable LLVMBUILD_INCLUDE_DEPENDENCIES to get # these dependencies. This is a compromise to help improve the # performance of recursive Make systems. """) f.write('ifeq ($(LLVMBUILD_INCLUDE_DEPENDENCIES),1)\n') f.write("# The dependencies for this Makefile fragment itself.\n") f.write("%s: \\\n" % (mk_quote_string_for_target(output_path),)) for dep in dependencies: f.write("\t%s \\\n" % (dep,)) f.write('\n') # Generate dummy rules for each of the dependencies, so that things # continue to work correctly if any of those files are moved or removed. f.write("""\ # The dummy targets to allow proper regeneration even when files are moved or # removed. """) for dep in dependencies: f.write("%s:\n" % (mk_quote_string_for_target(dep),)) f.write('endif\n') f.close() def add_magic_target_components(parser, project, opts): """add_magic_target_components(project, opts) -> None Add the "magic" target based components to the project, which can only be determined based on the target configuration options. This currently is responsible for populating the required_libraries list of the "all-targets", "Native", "NativeCodeGen", and "Engine" components. """ # Determine the available targets. available_targets = dict((ci.name,ci) for ci in project.component_infos if ci.type_name == 'TargetGroup') # Find the configured native target. # We handle a few special cases of target names here for historical # reasons, as these are the names configure currently comes up with. native_target_name = { 'x86' : 'X86', 'x86_64' : 'X86', 'Unknown' : None }.get(opts.native_target, opts.native_target) if native_target_name is None: native_target = None else: native_target = available_targets.get(native_target_name) if native_target is None: parser.error("invalid native target: %r (not in project)" % ( opts.native_target,)) if native_target.type_name != 'TargetGroup': parser.error("invalid native target: %r (not a target)" % ( opts.native_target,)) # Find the list of targets to enable. if opts.enable_targets is None: enable_targets = available_targets.values() else: # We support both space separated and semi-colon separated lists. if opts.enable_targets == '': enable_target_names = [] elif ' ' in opts.enable_targets: enable_target_names = opts.enable_targets.split() else: enable_target_names = opts.enable_targets.split(';') enable_targets = [] for name in enable_target_names: if name == "None": continue # HLSL Change target = available_targets.get(name) if target is None: parser.error("invalid target to enable: %r (not in project)" % ( name,)) if target.type_name != 'TargetGroup': parser.error("invalid target to enable: %r (not a target)" % ( name,)) enable_targets.append(target) # Find the special library groups we are going to populate. We enforce that # these appear in the project (instead of just adding them) so that they at # least have an explicit representation in the project LLVMBuild files (and # comments explaining how they are populated). def find_special_group(name): info = info_map.get(name) if info is None: fatal("expected project to contain special %r component" % ( name,)) if info.type_name != 'LibraryGroup': fatal("special component %r should be a LibraryGroup" % ( name,)) if info.required_libraries: fatal("special component %r must have empty %r list" % ( name, 'required_libraries')) if info.add_to_library_groups: fatal("special component %r must have empty %r list" % ( name, 'add_to_library_groups')) info._is_special_group = True return info info_map = dict((ci.name, ci) for ci in project.component_infos) all_targets = find_special_group('all-targets') native_group = find_special_group('Native') native_codegen_group = find_special_group('NativeCodeGen') engine_group = find_special_group('Engine') # Set the enabled bit in all the target groups, and append to the # all-targets list. for ci in enable_targets: all_targets.required_libraries.append(ci.name) ci.enabled = True # If we have a native target, then that defines the native and # native_codegen libraries. if native_target and native_target.enabled: native_group.required_libraries.append(native_target.name) native_codegen_group.required_libraries.append( '%sCodeGen' % native_target.name) # If we have a native target with a JIT, use that for the engine. Otherwise, # use the interpreter. if native_target and native_target.enabled and native_target.has_jit: engine_group.required_libraries.append('MCJIT') engine_group.required_libraries.append(native_group.name) else: engine_group.required_libraries.append('Interpreter') def main(): from optparse import OptionParser, OptionGroup parser = OptionParser("usage: %prog [options]") group = OptionGroup(parser, "Input Options") group.add_option("", "--source-root", dest="source_root", metavar="PATH", help="Path to the LLVM source (inferred if not given)", action="store", default=None) group.add_option("", "--llvmbuild-source-root", dest="llvmbuild_source_root", help=( "If given, an alternate path to search for LLVMBuild.txt files"), action="store", default=None, metavar="PATH") group.add_option("", "--build-root", dest="build_root", metavar="PATH", help="Path to the build directory (if needed) [%default]", action="store", default=None) parser.add_option_group(group) group = OptionGroup(parser, "Output Options") group.add_option("", "--print-tree", dest="print_tree", help="Print out the project component tree [%default]", action="store_true", default=False) group.add_option("", "--write-llvmbuild", dest="write_llvmbuild", help="Write out the LLVMBuild.txt files to PATH", action="store", default=None, metavar="PATH") group.add_option("", "--write-library-table", dest="write_library_table", metavar="PATH", help="Write the C++ library dependency table to PATH", action="store", default=None) group.add_option("", "--write-cmake-fragment", dest="write_cmake_fragment", metavar="PATH", help="Write the CMake project information to PATH", action="store", default=None) group.add_option("", "--write-cmake-exports-fragment", dest="write_cmake_exports_fragment", metavar="PATH", help="Write the CMake exports information to PATH", action="store", default=None) group.add_option("", "--write-make-fragment", dest="write_make_fragment", metavar="PATH", help="Write the Makefile project information to PATH", action="store", default=None) group.add_option("", "--configure-target-def-file", dest="configure_target_def_files", help="""Configure the given file at SUBPATH (relative to the inferred or given source root, and with a '.in' suffix) by replacing certain substitution variables with lists of targets that support certain features (for example, targets with AsmPrinters) and write the result to the build root (as given by --build-root) at the same SUBPATH""", metavar="SUBPATH", action="append", default=None) parser.add_option_group(group) group = OptionGroup(parser, "Configuration Options") group.add_option("", "--native-target", dest="native_target", metavar="NAME", help=("Treat the named target as the 'native' one, if " "given [%default]"), action="store", default=None) group.add_option("", "--enable-targets", dest="enable_targets", metavar="NAMES", help=("Enable the given space or semi-colon separated " "list of targets, or all targets if not present"), action="store", default=None) group.add_option("", "--enable-optional-components", dest="optional_components", metavar="NAMES", help=("Enable the given space or semi-colon separated " "list of optional components"), action="store", default="") parser.add_option_group(group) (opts, args) = parser.parse_args() # Determine the LLVM source path, if not given. source_root = opts.source_root if source_root: if not os.path.exists(os.path.join(source_root, 'lib', 'IR', 'Function.cpp')): parser.error('invalid LLVM source root: %r' % source_root) else: llvmbuild_path = os.path.dirname(__file__) llvm_build_path = os.path.dirname(llvmbuild_path) utils_path = os.path.dirname(llvm_build_path) source_root = os.path.dirname(utils_path) if not os.path.exists(os.path.join(source_root, 'lib', 'IR', 'Function.cpp')): parser.error('unable to infer LLVM source root, please specify') # Construct the LLVM project information. llvmbuild_source_root = opts.llvmbuild_source_root or source_root project_info = LLVMProjectInfo.load_from_path( source_root, llvmbuild_source_root) # Add the magic target based components. add_magic_target_components(parser, project_info, opts) # Validate the project component info. project_info.validate_components() # Print the component tree, if requested. if opts.print_tree: project_info.print_tree() # Write out the components, if requested. This is useful for auto-upgrading # the schema. if opts.write_llvmbuild: project_info.write_components(opts.write_llvmbuild) # Write out the required library table, if requested. if opts.write_library_table: project_info.write_library_table(opts.write_library_table, opts.optional_components) # Write out the make fragment, if requested. if opts.write_make_fragment: project_info.write_make_fragment(opts.write_make_fragment) # Write out the cmake fragment, if requested. if opts.write_cmake_fragment: project_info.write_cmake_fragment(opts.write_cmake_fragment, opts.optional_components) if opts.write_cmake_exports_fragment: project_info.write_cmake_exports_fragment(opts.write_cmake_exports_fragment, opts.optional_components) # Configure target definition files, if requested. if opts.configure_target_def_files: # Verify we were given a build root. if not opts.build_root: parser.error("must specify --build-root when using " "--configure-target-def-file") # Create the substitution list. available_targets = [ci for ci in project_info.component_infos if ci.type_name == 'TargetGroup'] substitutions = [ ("@LLVM_ENUM_TARGETS@", ' '.join('LLVM_TARGET(%s)' % ci.name for ci in available_targets)), ("@LLVM_ENUM_ASM_PRINTERS@", ' '.join('LLVM_ASM_PRINTER(%s)' % ci.name for ci in available_targets if ci.has_asmprinter)), ("@LLVM_ENUM_ASM_PARSERS@", ' '.join('LLVM_ASM_PARSER(%s)' % ci.name for ci in available_targets if ci.has_asmparser)), ("@LLVM_ENUM_DISASSEMBLERS@", ' '.join('LLVM_DISASSEMBLER(%s)' % ci.name for ci in available_targets if ci.has_disassembler))] # Configure the given files. for subpath in opts.configure_target_def_files: inpath = os.path.join(source_root, subpath + '.in') outpath = os.path.join(opts.build_root, subpath) result = configutil.configure_file(inpath, outpath, substitutions) if not result: note("configured file %r hasn't changed" % outpath) if __name__=='__main__': main()
0
repos/DirectXShaderCompiler/utils/llvm-build
repos/DirectXShaderCompiler/utils/llvm-build/llvmbuild/__init__.py
from llvmbuild.main import main
0
repos/DirectXShaderCompiler/utils/llvm-build
repos/DirectXShaderCompiler/utils/llvm-build/llvmbuild/componentinfo.py
""" Descriptor objects for entities that are part of the LLVM project. """ from __future__ import absolute_import try: import configparser except: import ConfigParser as configparser import sys from llvmbuild.util import fatal, warning class ParseError(Exception): pass class ComponentInfo(object): """ Base class for component descriptions. """ type_name = None @staticmethod def parse_items(items, has_dependencies = True): kwargs = {} kwargs['name'] = items.get_string('name') kwargs['parent'] = items.get_optional_string('parent') if has_dependencies: kwargs['dependencies'] = items.get_list('dependencies') return kwargs def __init__(self, subpath, name, dependencies, parent): if not subpath.startswith('/'): raise ValueError("invalid subpath: %r" % subpath) self.subpath = subpath self.name = name self.dependencies = list(dependencies) # The name of the parent component to logically group this component # under. self.parent = parent # The parent instance, once loaded. self.parent_instance = None self.children = [] # The original source path. self._source_path = None # A flag to mark "special" components which have some amount of magic # handling (generally based on command line options). self._is_special_group = False def set_parent_instance(self, parent): assert parent.name == self.parent, "Unexpected parent!" self.parent_instance = parent self.parent_instance.children.append(self) def get_component_references(self): """get_component_references() -> iter Return an iterator over the named references to other components from this object. Items are of the form (reference-type, component-name). """ # Parent references are handled specially. for r in self.dependencies: yield ('dependency', r) def get_llvmbuild_fragment(self): abstract def get_parent_target_group(self): """get_parent_target_group() -> ComponentInfo or None Return the nearest parent target group (if any), or None if the component is not part of any target group. """ # If this is a target group, return it. if self.type_name == 'TargetGroup': return self # Otherwise recurse on the parent, if any. if self.parent_instance: return self.parent_instance.get_parent_target_group() class GroupComponentInfo(ComponentInfo): """ Group components have no semantics as far as the build system are concerned, but exist to help organize other components into a logical tree structure. """ type_name = 'Group' @staticmethod def parse(subpath, items): kwargs = ComponentInfo.parse_items(items, has_dependencies = False) return GroupComponentInfo(subpath, **kwargs) def __init__(self, subpath, name, parent): ComponentInfo.__init__(self, subpath, name, [], parent) def get_llvmbuild_fragment(self): return """\ type = %s name = %s parent = %s """ % (self.type_name, self.name, self.parent) class LibraryComponentInfo(ComponentInfo): type_name = 'Library' @staticmethod def parse_items(items): kwargs = ComponentInfo.parse_items(items) kwargs['library_name'] = items.get_optional_string('library_name') kwargs['required_libraries'] = items.get_list('required_libraries') kwargs['add_to_library_groups'] = items.get_list( 'add_to_library_groups') kwargs['installed'] = items.get_optional_bool('installed', True) return kwargs @staticmethod def parse(subpath, items): kwargs = LibraryComponentInfo.parse_items(items) return LibraryComponentInfo(subpath, **kwargs) def __init__(self, subpath, name, dependencies, parent, library_name, required_libraries, add_to_library_groups, installed): ComponentInfo.__init__(self, subpath, name, dependencies, parent) # If given, the name to use for the library instead of deriving it from # the component name. self.library_name = library_name # The names of the library components which are required when linking # with this component. self.required_libraries = list(required_libraries) # The names of the library group components this component should be # considered part of. self.add_to_library_groups = list(add_to_library_groups) # Whether or not this library is installed. self.installed = installed def get_component_references(self): for r in ComponentInfo.get_component_references(self): yield r for r in self.required_libraries: yield ('required library', r) for r in self.add_to_library_groups: yield ('library group', r) def get_llvmbuild_fragment(self): result = """\ type = %s name = %s parent = %s """ % (self.type_name, self.name, self.parent) if self.library_name is not None: result += 'library_name = %s\n' % self.library_name if self.required_libraries: result += 'required_libraries = %s\n' % ' '.join( self.required_libraries) if self.add_to_library_groups: result += 'add_to_library_groups = %s\n' % ' '.join( self.add_to_library_groups) if not self.installed: result += 'installed = 0\n' return result def get_library_name(self): return self.library_name or self.name def get_prefixed_library_name(self): """ get_prefixed_library_name() -> str Return the library name prefixed by the project name. This is generally what the library name will be on disk. """ basename = self.get_library_name() # FIXME: We need to get the prefix information from an explicit project # object, or something. if basename in ('gtest', 'gtest_main'): return basename return 'LLVM%s' % basename def get_llvmconfig_component_name(self): return self.get_library_name().lower() class OptionalLibraryComponentInfo(LibraryComponentInfo): type_name = "OptionalLibrary" @staticmethod def parse(subpath, items): kwargs = LibraryComponentInfo.parse_items(items) return OptionalLibraryComponentInfo(subpath, **kwargs) def __init__(self, subpath, name, dependencies, parent, library_name, required_libraries, add_to_library_groups, installed): LibraryComponentInfo.__init__(self, subpath, name, dependencies, parent, library_name, required_libraries, add_to_library_groups, installed) class LibraryGroupComponentInfo(ComponentInfo): type_name = 'LibraryGroup' @staticmethod def parse(subpath, items): kwargs = ComponentInfo.parse_items(items, has_dependencies = False) kwargs['required_libraries'] = items.get_list('required_libraries') kwargs['add_to_library_groups'] = items.get_list( 'add_to_library_groups') return LibraryGroupComponentInfo(subpath, **kwargs) def __init__(self, subpath, name, parent, required_libraries = [], add_to_library_groups = []): ComponentInfo.__init__(self, subpath, name, [], parent) # The names of the library components which are required when linking # with this component. self.required_libraries = list(required_libraries) # The names of the library group components this component should be # considered part of. self.add_to_library_groups = list(add_to_library_groups) def get_component_references(self): for r in ComponentInfo.get_component_references(self): yield r for r in self.required_libraries: yield ('required library', r) for r in self.add_to_library_groups: yield ('library group', r) def get_llvmbuild_fragment(self): result = """\ type = %s name = %s parent = %s """ % (self.type_name, self.name, self.parent) if self.required_libraries and not self._is_special_group: result += 'required_libraries = %s\n' % ' '.join( self.required_libraries) if self.add_to_library_groups: result += 'add_to_library_groups = %s\n' % ' '.join( self.add_to_library_groups) return result def get_llvmconfig_component_name(self): return self.name.lower() class TargetGroupComponentInfo(ComponentInfo): type_name = 'TargetGroup' @staticmethod def parse(subpath, items): kwargs = ComponentInfo.parse_items(items, has_dependencies = False) kwargs['required_libraries'] = items.get_list('required_libraries') kwargs['add_to_library_groups'] = items.get_list( 'add_to_library_groups') kwargs['has_jit'] = items.get_optional_bool('has_jit', False) kwargs['has_asmprinter'] = items.get_optional_bool('has_asmprinter', False) kwargs['has_asmparser'] = items.get_optional_bool('has_asmparser', False) kwargs['has_disassembler'] = items.get_optional_bool('has_disassembler', False) return TargetGroupComponentInfo(subpath, **kwargs) def __init__(self, subpath, name, parent, required_libraries = [], add_to_library_groups = [], has_jit = False, has_asmprinter = False, has_asmparser = False, has_disassembler = False): ComponentInfo.__init__(self, subpath, name, [], parent) # The names of the library components which are required when linking # with this component. self.required_libraries = list(required_libraries) # The names of the library group components this component should be # considered part of. self.add_to_library_groups = list(add_to_library_groups) # Whether or not this target supports the JIT. self.has_jit = bool(has_jit) # Whether or not this target defines an assembly printer. self.has_asmprinter = bool(has_asmprinter) # Whether or not this target defines an assembly parser. self.has_asmparser = bool(has_asmparser) # Whether or not this target defines an disassembler. self.has_disassembler = bool(has_disassembler) # Whether or not this target is enabled. This is set in response to # configuration parameters. self.enabled = False def get_component_references(self): for r in ComponentInfo.get_component_references(self): yield r for r in self.required_libraries: yield ('required library', r) for r in self.add_to_library_groups: yield ('library group', r) def get_llvmbuild_fragment(self): result = """\ type = %s name = %s parent = %s """ % (self.type_name, self.name, self.parent) if self.required_libraries: result += 'required_libraries = %s\n' % ' '.join( self.required_libraries) if self.add_to_library_groups: result += 'add_to_library_groups = %s\n' % ' '.join( self.add_to_library_groups) for bool_key in ('has_asmparser', 'has_asmprinter', 'has_disassembler', 'has_jit'): if getattr(self, bool_key): result += '%s = 1\n' % (bool_key,) return result def get_llvmconfig_component_name(self): return self.name.lower() class ToolComponentInfo(ComponentInfo): type_name = 'Tool' @staticmethod def parse(subpath, items): kwargs = ComponentInfo.parse_items(items) kwargs['required_libraries'] = items.get_list('required_libraries') return ToolComponentInfo(subpath, **kwargs) def __init__(self, subpath, name, dependencies, parent, required_libraries): ComponentInfo.__init__(self, subpath, name, dependencies, parent) # The names of the library components which are required to link this # tool. self.required_libraries = list(required_libraries) def get_component_references(self): for r in ComponentInfo.get_component_references(self): yield r for r in self.required_libraries: yield ('required library', r) def get_llvmbuild_fragment(self): return """\ type = %s name = %s parent = %s required_libraries = %s """ % (self.type_name, self.name, self.parent, ' '.join(self.required_libraries)) class BuildToolComponentInfo(ToolComponentInfo): type_name = 'BuildTool' @staticmethod def parse(subpath, items): kwargs = ComponentInfo.parse_items(items) kwargs['required_libraries'] = items.get_list('required_libraries') return BuildToolComponentInfo(subpath, **kwargs) ### class IniFormatParser(dict): def get_list(self, key): # Check if the value is defined. value = self.get(key) if value is None: return [] # Lists are just whitespace separated strings. return value.split() def get_optional_string(self, key): value = self.get_list(key) if not value: return None if len(value) > 1: raise ParseError("multiple values for scalar key: %r" % key) return value[0] def get_string(self, key): value = self.get_optional_string(key) if not value: raise ParseError("missing value for required string: %r" % key) return value def get_optional_bool(self, key, default = None): value = self.get_optional_string(key) if not value: return default if value not in ('0', '1'): raise ParseError("invalid value(%r) for boolean property: %r" % ( value, key)) return bool(int(value)) def get_bool(self, key): value = self.get_optional_bool(key) if value is None: raise ParseError("missing value for required boolean: %r" % key) return value _component_type_map = dict( (t.type_name, t) for t in (GroupComponentInfo, LibraryComponentInfo, LibraryGroupComponentInfo, ToolComponentInfo, BuildToolComponentInfo, TargetGroupComponentInfo, OptionalLibraryComponentInfo)) def load_from_path(path, subpath): # Load the LLVMBuild.txt file as an .ini format file. parser = configparser.RawConfigParser() parser.read(path) # Extract the common section. if parser.has_section("common"): common = IniFormatParser(parser.items("common")) parser.remove_section("common") else: common = IniFormatParser({}) return common, _read_components_from_parser(parser, path, subpath) def _read_components_from_parser(parser, path, subpath): # We load each section which starts with 'component' as a distinct component # description (so multiple components can be described in one file). for section in parser.sections(): if not section.startswith('component'): # We don't expect arbitrary sections currently, warn the user. warning("ignoring unknown section %r in %r" % (section, path)) continue # Determine the type of the component to instantiate. if not parser.has_option(section, 'type'): fatal("invalid component %r in %r: %s" % ( section, path, "no component type")) type_name = parser.get(section, 'type') type_class = _component_type_map.get(type_name) if type_class is None: fatal("invalid component %r in %r: %s" % ( section, path, "invalid component type: %r" % type_name)) # Instantiate the component based on the remaining values. try: info = type_class.parse(subpath, IniFormatParser(parser.items(section))) except TypeError: print >>sys.stderr, "error: invalid component %r in %r: %s" % ( section, path, "unable to instantiate: %r" % type_name) import traceback traceback.print_exc() raise SystemExit(1) except ParseError: e = sys.exc_info()[1] fatal("unable to load component %r in %r: %s" % ( section, path, e.message)) info._source_path = path yield info
0
repos/DirectXShaderCompiler/utils/llvm-build
repos/DirectXShaderCompiler/utils/llvm-build/llvmbuild/util.py
import os import sys def _write_message(kind, message): program = os.path.basename(sys.argv[0]) sys.stderr.write('%s: %s: %s\n' % (program, kind, message)) note = lambda message: _write_message('note', message) warning = lambda message: _write_message('warning', message) error = lambda message: _write_message('error', message) fatal = lambda message: (_write_message('fatal error', message), sys.exit(1)) __all__ = ['note', 'warning', 'error', 'fatal']
0
repos/DirectXShaderCompiler/utils/llvm-build
repos/DirectXShaderCompiler/utils/llvm-build/llvmbuild/configutil.py
""" Defines utilities useful for performing standard "configuration" style tasks. """ import re import os def configure_file(input_path, output_path, substitutions): """configure_file(input_path, output_path, substitutions) -> bool Given an input and output path, "configure" the file at the given input path by replacing variables in the file with those given in the substitutions list. Returns true if the output file was written. The substitutions list should be given as a list of tuples (regex string, replacement), where the regex and replacement will be used as in 're.sub' to execute the variable replacement. The output path's parent directory need not exist (it will be created). If the output path does exist and the configured data is not different than it's current contents, the output file will not be modified. This is designed to limit the impact of configured files on build dependencies. """ # Read in the input data. f = open(input_path, "rb") try: data = f.read() finally: f.close() # Perform the substitutions. for regex_string,replacement in substitutions: regex = re.compile(regex_string) data = regex.sub(replacement, data) # Ensure the output parent directory exists. output_parent_path = os.path.dirname(os.path.abspath(output_path)) if not os.path.exists(output_parent_path): os.makedirs(output_parent_path) # If the output path exists, load it and compare to the configured contents. if os.path.exists(output_path): current_data = None try: f = open(output_path, "rb") try: current_data = f.read() except: current_data = None f.close() except: current_data = None if current_data is not None and current_data == data: return False # Write the output contents. f = open(output_path, "wb") try: f.write(data) finally: f.close() return True
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/hct/hctjs.js
/////////////////////////////////////////////////////////////////////////////// // // // hctjs.js // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // /////////////////////////////////////////////////////////////////////////////// // // References: // // JScript Language Reference // http://msdn2.microsoft.com/en-us/library/yek4tbz0 // // Windows Script Host Object Model // http://msdn2.microsoft.com/en-us/library/a74hyyw0 // // Script Runtime // http://msdn2.microsoft.com/en-us/library/hww8txat.aspx // // Include this file with: // eval(new ActiveXObject("Scripting.FileSystemObject").OpenTextFile(new ActiveXObject("WScript.Shell").ExpandEnvironmentStrings("%HLSL_SRC_DIR%\\utils\\hct\\hctjs.js"), 1).ReadAll()); function ArrayAny(arr, callback) { /// <summary>Checks whether any element in an array satisfies a predicate.</summary> /// <param name="arr" type="Array">Array to operate on.</param> /// <param name="callback" type="Function">Function to test with element and index, returning true or false.</param> /// <returns type="Boolean">true if 'callback' returns true for any element; false otherwise.</returns> for (var i = 0; i < arr.length; i++) { if (callback(arr[i], i)) { return true; } } return false; } function ArrayDistinct(arr, comparer) { /// <summary>Returns each element in the array at-most-once.</summary> /// <param name="arr" type="Array">Array to operate on.</param> /// <param name="comparer" type="Function">Optional comparer.</param> /// <returns type="Array">Array of elements from arr, sorted as the comparer, with no repeating elements.</returns> var result = arr.slice(0); if (result.length === 0) { return result; } if (!comparer) { comparer = CompareValues; } result.sort(comparer); var readIndex = 1, lastWriteIndex = 0; while (readIndex < result.length) { if (comparer(result[readIndex], result[lastWriteIndex]) !== 0) { lastWriteIndex += 1; if (readIndex !== lastWriteIndex) { result[lastWriteIndex] = result[readIndex]; } } readIndex += 1; } lastWriteIndex += 1; if (lastWriteIndex < result.length) { result = result.slice(0, lastWriteIndex); } return result; } function ArrayForEach(arr, callback) { /// <summary>Invokes a callback for each element in the array.</summary> /// <param name="arr" type="Array">Array to operate on.</param> /// <param name="callback" type="Function">Function to invoke with element and index.</param> for (var i = 0; i < arr.length; i++) { callback(arr[i], i); } } function ArrayIndexOf(arr, element) { /// <summary>Scans the specified array for the given element.</summary> /// <param name="arr" type="Array">Array to operate on.</param> /// <param name="element">Element to look for.</param> for (var i = 0; i < arr.length; i++) { if (arr[i] == element) { return i; } } return -1; } function ArrayMax(arr) { /// <summary>Gets the maximum value of the specified array.</summary> if (arr.length === 0) { return undefined; } var result = arr[0]; for (var i = 1; i < arr.length; i++) { if (arr[i] > result) { result = arr[i]; } } return result; } function ArraySelect(arr, selector) { /// <summary>Invokes a selector callback for each element in the array.</summary> /// <param name="arr" type="Array">Array to operate on.</param> /// <param name="callback" type="Function">Function to invoke with element and index.</param> /// <returns type="Array">Array of selections for the arr element.</returns> var result = []; for (var i = 0; i < arr.length; i++) { result.push(selector(arr[i], i)); } return result; } function ArraySelectMany(arr, selector) { /// <summary>Invokes a selector callback for each element in the array to produce multiple results.</summary> /// <param name="arr" type="Array">Array to operate on.</param> /// <param name="callback" type="Function">Function to invoke with element and index.</param> /// <returns type="Array">Array of flattened selections for the arr element.</returns> var result = []; for (var i = 0; i < arr.length; i++) { var selectorArr = selector(arr[i], i); if (selectorArr) { for (var j = 0; j < selectorArr.length; j++) { result.push(selectorArr[j]); } } } return result; } function ArraySelectMember(arr, memberName) { /// <summary>Invokes a selector callback for each element in the array.</summary> /// <param name="arr" type="Array">Array to operate on.</param> /// <param name="memberName" type="String">Member name to select from each array element.</param> /// <returns type="Array">Array of members for the arr elements.</returns> var result = []; for (var i = 0; i < arr.length; i++) { result.push(arr[i][memberName]); } return result; } function ArraySort(arr, comparer) { /// <summary>Adds the values in the array.</summary> /// <param name="arr" type="Array">Array to operate on.</param> /// <returns type="Number">Sum of the arr elements.</returns> var result = arr.slice(0); result.sort(comparer); return result; } function ArraySum(arr) { /// <summary>Adds the values in the array.</summary> /// <param name="arr" type="Array">Array to operate on.</param> /// <returns type="Number">Sum of the arr elements.</returns> var result = 0; for (var i = 0; i < arr.length; i++) { if (arr[i]) { result += arr[i]; } } return result; } function ArrayTake(arr, count) { /// <summary>Returns the first count elements (or the original array if it has less than count elements.</summary> if (arr.length < count) { return arr; } return arr.slice(0, count); } function ArrayWhere(arr, callback) { /// <summary>Returns the elements in an array that satisfy a predicate.</summary> /// <param name="arr" type="Array">Array to operate on.</param> /// <param name="callback" type="Function">Function to test with element and index, returning true or false.</param> /// <returns type="Array">Array of elements from arr that satisfy the predicate.</returns> var result = []; for (var i = 0; i < arr.length; i++) { if (callback(arr[i], i)) { result.push(arr[i]); } } return result; } function CheckScriptFlag(name) { /// <summary>Checks whether a script argument was given with true or false.</summary> /// <param name="name" type="String">Argument name to check.</param> /// <returns type="Boolean"> /// true if the argument was given witha value of 'true' or 'True'; false otherwise. /// </returns> var flag = WScript.Arguments.Named(name); if (!flag) { return false; } return flag === "true" || flag === "True"; } function CreateFolderIfMissing(path) { /// <summary>Creates a folder if it doesn't exist.</summary> /// <param name="path" type="String">Path to folder to create.</param> /// <remarks>This function will write out to the console on creation.</remarks> if (!path) return; var parent = PathGetDirectory(path); var fso = new ActiveXObject("Scripting.FileSystemObject"); if (!fso.FolderExists(parent)) { CreateFolderIfMissing(parent); } if (!fso.FolderExists(path)) { WScript.Echo("Creating " + path + "..."); fso.CreateFolder(path); } } function CompareValues(left, right) { if (left === right) return 0; if (left < right) return -1; return 1; } function CompareValuesAsStrings(left, right) { if (left === right) return 0; left = (left === null) ? "" : left.toString(); right = (right === null) ? "" : right.toString(); if (left === right) return 0; if (left < right) return -1; return 1; } function DbValueToString(value) { /// <summary>Returns a string representation for a database value.</summary> /// <param name="value">Value from database.</param> /// <returns type="String">A string representing the specified value.</returns> if (value === null || value === undefined) { return "NULL"; } return value.toString(); } function DeleteFile(path, force) { /// <summary>Deletes a file.</summary> /// <param name="path" type="String">Path to the file.</param> /// <param name="force" type="Boolean">Whether to delete the file even if it has the read-only attribute set.</param> var fso = new ActiveXObject("Scripting.FileSystemObject"); fso.DeleteFile(path, force); } function DeleteFolder(path, force) { /// <summary>Deletes a folder.</summary> /// <param name="path" type="String">Path to the folder.</param> /// <param name="force" type="Boolean">Whether to delete the folder even if it has the read-only attribute set.</param> var fso = new ActiveXObject("Scripting.FileSystemObject"); fso.DeleteFolder(path, force); } function CopyFolder(source, dest, overwrite) { /// <summary>Recursively copies a folder and its contents from source to dest.</summary> /// <param name="source" type="String">Path to the source folder location.</param> /// <param name="dest" type="String">Path to the destination folder location.</param> /// <param name="overwrite" type="Boolean">Whether to overwrite a folder in the destination location.</param> var fso = new ActiveXObject("Scripting.FileSystemObject"); fso.CopyFolder(source, dest, overwrite); } function CopyFile(source, dest, overwrite) { /// <summary>Copies a file from source to dest.</summary> /// <param name="source" type="String">Path to the source file location.</param> /// <param name="dest" type="String">Path to the destination file location.</param> /// <param name="overwrite" type="Boolean">Whether to overwrite a file in the destination location.</param> var fso = new ActiveXObject("Scripting.FileSystemObject"); if (overwrite && fso.FileExists(dest)) { var f = fso.getFile(dest); f.attributes = 0; } fso.CopyFile(source, dest, overwrite); } function ExpandEnvironmentVariables(name) { /// <summary> /// Replaces the name of each environment variable embedded in the specified string with the /// string equivalent of the value of the variable, then returns the resulting string. /// </summary> /// <param name="name" type="String"> /// A string containing the names of zero or more environment variables. Each environment variable is quoted with the percent sign character (%). /// </param> /// <returns type="String">A string with each environment variable replaced by its value.</returns> var shell = new ActiveXObject("WScript.Shell"); var result = shell.ExpandEnvironmentStrings(name); return result; } function ExtractContentsBetweenMarkers(path, contentOnly, isExclusion, startMarker, endMarker, callback) { /// <summary> /// Extracts the lines from the 'path' text file between the start and end markers. /// </summary> /// <param name="path" type="String">Path to file.</param> /// <param name="contentOnly" type="Boolean"> /// true to skip everything until it's found between markers, false to start including everything from the start. /// </param> /// <param name="isExclusion" type="Boolean"> /// false if the 'extraction' means keeping the content; true if it means not excluding it from the result. /// </param> /// <param name="startMarker" type="String">Line content to match for content start.</param> /// <param name="endMarker" type="String">Line content to match for content end.</param> /// <param name="callback" type="Function" mayBeNull="true"> /// If true, then this function is called for every line along with the inContent flag /// before the line is added; the called function may return a line /// to be added in its place, null to skip processing. /// </param> /// <returns type="String">The string content of the file.</returns> var content = ReadAllTextFile(path); return ExtractContentsBetweenMarkersForText(content, contentOnly, isExclusion, startMarker, endMarker, callback); } function ExtractContentsBetweenMarkersForText(content, contentOnly, isExclusion, startMarker, endMarker, callback) { /// <summary> /// Extracts the lines from the specified text between the start and end markers. /// </summary> /// <param name="content" type="String">Text to process.</param> /// <param name="contentOnly" type="Boolean"> /// true to skip everything until it's found between markers, false to start including everything from the start. /// </param> /// <param name="isExclusion" type="Boolean"> /// false if the 'extraction' means keeping the content; true if it means not excluding it from the result. /// </param> /// <param name="startMarker" type="String">Line content to match for content start.</param> /// <param name="endMarker" type="String">Line content to match for content end.</param> /// <param name="callback" type="Function" mayBeNull="true"> /// If true, then this function is called for every line along with the inContent flag /// before the line is added; the called function may return a line /// to be added in its place, null to skip processing. /// </param> /// <returns type="String">The extracted content.</returns> var inContent = contentOnly === false; var lines = StringSplit(content, "\r\n"); var result = []; var i, len; for (i = 0, len = lines.length; i < len; i++) { var line = lines[i]; var contentStartIndex = line.indexOf(startMarker); if (inContent === false && contentStartIndex !== -1) { inContent = true; continue; } var contentEndIndex = line.indexOf(endMarker); if (inContent === true && contentEndIndex !== -1) { inContent = false; continue; } if (callback) { var callbackResult = callback(line, inContent); if (callbackResult !== null && callbackResult !== undefined) { result.push(callbackResult); } } else { if (inContent && !isExclusion) { result.push(line); } else if (!inContent && isExclusion) { result.push(line); } } } return result.join("\r\n"); } function FolderExists(path) { /// <summary>Checks whether the specified directory exists.</summary> var fso = new ActiveXObject("Scripting.FileSystemObject"); if (fso.FolderExists(path)) { return true; } else { return false; } } function FileExists(path) { /// <summary>Checks whether the specified file exists.</summary> var fso = new ActiveXObject("Scripting.FileSystemObject"); if (fso.FileExists(path)) { return true; } else { return false; } } function GetEnvironmentVariable(name) { /// <summary>Gets the value of the specified environment variable.</summary> /// <param name="name" type="String">Name of the variable value to get.</param> /// <returns type="String">Value for the given environment variable; null if undefined.</returns> var shell = new ActiveXObject("WScript.Shell"); var result = shell.ExpandEnvironmentStrings("%" + name + "%"); if (result == "%" + name + "%") { result = null; } return result; } function GetFilesRecursive(path) { /// <summary>Gets all file names under the specified directory path.</summary> /// <param name="path" type="String">Path to directory.</param> /// <returns type="Array">Array of all file names under path.</returns> var result = []; var fso = new ActiveXObject("Scripting.FileSystemObject"); var pending = [path]; while (pending.length) { var item = pending.pop(); var folder = fso.GetFolder(item); for (var files = new Enumerator(folder.Files); !files.atEnd(); files.moveNext()) { result.push(files.item().Path); } for (var subFolders = new Enumerator(folder.SubFolders); !subFolders.atEnd(); subFolders.moveNext()) { pending.push(subFolders.item().Path); } } return result; } function GetRelativePathFrom(startPath, endPath) { if (startPath[startPath.length - 1] !== "\\") { startPath += "\\"; } if (startPath.length > endPath.length) { throw { message: "traversing up NYI" }; } return endPath.substr(startPath.length); } function MatchesMask(file, mask) { if (!mask) { return false; } if (file === mask) { return true; } if (mask.substr(0, 1) === "*") { var rest = mask.substr(1); return file.substr(file.length - rest.length) === rest; } else if (mask.substr(mask.length - 1) === "*") { var end = mask.substr(0, mask.length - 1); return file.substr(0, end.length) === end; } return false; } function OpenCsvConnection(path) { /// <summary>Opens an ADO Connection object to the directory path where CSV files are found.</summary> /// <param name="path" type="String">Directory path where .csv files are.</param> /// <returns type="ADODB.Connection">An open connection.</returns> var connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + path + ";" + "Extended Properties=\"text;HDR=YES;FMT=Delimited\""; var objConnection = WScript.CreateObject("ADODB.Connection"); objConnection.Open(connectionString); return objConnection; } function OpenSqlCeConnection(path) { /// <summary>Opens an ADO Connection object to a SQL CE file.</summary> /// <param name="path" type="String">File path for .sdf file.</param> /// <returns type="ADODB.Connection">An open connection.</returns> var connectionString = "Provider=Microsoft.SQLSERVER.CE.OLEDB.4.0;" + "Data Source=" + path + ";"; var objConnection = WScript.CreateObject("ADODB.Connection"); objConnection.Open(connectionString); return objConnection; } function PathGetDirectory(path) { /// <summary> /// Returns the directory of the specified path string (excluding the trailing "\\"); /// empty if there is no path. /// </summary> var l = path.length; var startIndex = l; while (--startIndex >= 0) { var ch = path.substr(startIndex, 1); if (ch == "\\") { if (startIndex === 0) { return ""; } else { return path.substr(0, startIndex); } } } return ""; } function PathGetFileName(path) { /// <summary> /// Returns the file name for the specified path string; empty if there is no /// directory information. /// </summary> var l = path.length; var startIndex = l; while (--startIndex >= 0) { var ch = path.substr(startIndex, 1); if (ch == "\\" || ch == "/" || ch == ":") { return path.substr(startIndex + 1); } } return ""; } function PathGetExtension(path) { /// <summary> /// Returns the extension of the specified path string (including the "."); /// empty if there is no extension. /// </summary> /// <returns type="String">The extension of the specified path, including the '.'.</returns> var l = path.length; var startIndex = l; while (--startIndex >= 0) { var ch = path.substr(startIndex, 1); if (ch == ".") { if (startIndex != (l - 1)) { return path.substr(startIndex, l - startIndex); } return ""; } else if (ch == "\\" || ch == ":") { break; } } return ""; } function ReadAllTextFile(path) { /// <summary>Reads all the content of the file into a string.</summary> /// <param name="path" type="String">File name to read from.</param> /// <returns type="String">File contents.</returns> var ForReading = 1, ForWriting = 2; var fso = new ActiveXObject("Scripting.FileSystemObject"); var file = fso.OpenTextFile(path, ForReading); try { var result; if (file.AtEndOfStream) { result = ""; } else { result = file.ReadAll(); } } finally { file.Close(); } return result; } function ReadXmlFile(path) { /// <summary>Reads an XML document from the specified path.</summary> /// <param name="path" type="String">Path to file on disk.</param> /// <returns>A DOMDocument with the contents of the given file.</returns> var result = new ActiveXObject("Msxml2.DOMDocument.6.0"); result.async = false; result.load(path); if (result.parseError.errorCode !== 0) { throw { message: "Error reading '" + path + "': " + result.parseError.reason }; } return result; } // Runs the specified function catching exceptions and quits the current script. function RunAndQuit(f) { try { f(); } catch (e) { // An error with 'statusCode' defined will avoid the usual error dump handling. if (e.statusCode !== undefined) { if (e.message) { WScript.Echo(e.message); } WScript.Quit(e.statusCode); } WScript.Echo("Error caught while running this function:"); WScript.Echo(f.toString()); WScript.Echo("Error details:"); if (typeof (e) == "object" && e.toString() == "[object Object]" || e.toString() === "[object Error]") { for (var p in e) WScript.Echo(" " + p + ": " + e[p]); } else { WScript.Echo(e); } WScript.Quit(1); } WScript.Quit(0); } function RunConsoleCommand(strCommand, timeout, retry) { /// <summary>Runs a command and waits for it to exit.</summary> /// <param name="strCommand" type="String">Command to run.</param> /// <param name="timeout" type="int">Timeout in seconds.</param> /// <param name="timeout" type="bool">Boolean specifying whether to retry on timeout or not.</param> /// <returns type="Array"> /// An array with stdout in 0, stderr in 1 and exit code in 2. Forced /// termination sets the exit code to 1. /// </returns> // WScript.Echo("running [" + strCommand + "]"); var WshShell = new ActiveXObject("WScript.Shell"); var result = new Array(3); var oExec = WshShell.Exec(strCommand); var counter = 0; if (timeout) { // Status of 0 means the process is still running while (oExec.Status === 0 && counter < timeout) { WScript.Sleep(1000); counter++; } if (timeout === counter && oExec.Status === 0) { WScript.Echo("Forcefully terminating " + strCommand + " after " + timeout + " seconds."); oExec.Terminate(); result[2] = 1; if (retry) { return RunConsoleCommand(strCommand, timeout, false); } } } result[0] = oExec.StdOut.ReadAll(); result[1] = oExec.StdErr.ReadAll(); if (!result[2]) { result[2] = oExec.ExitCode; } // WScript.Echo(" stdout: " + result[0]); // WScript.Echo(" stderr: " + result[1]); // WScript.Echo(" exit code: " + result[2]); return result; } function Say(text) { /// <summary>Uses the Speech API to speak to the user.</summary> var voice = new ActiveXObject("SAPI.SpVoice"); try { voice.Speak(text); } catch (e) { // See http://msdn2.microsoft.com/en-us/library/ms717306.aspx for error codes. // SPERR_DEVICE_BUSY 0x80045006 -2147201018 if (e.number == -2147201018) { WScript.Echo("The wave device is busy."); WScript.Echo("Happens sometimes over Terminal Services."); } } } function SaveTextToFile(content, path) { /// <summary>Saves text content into a file.</summary> /// <param name="content" type="String">Content to save.</param> /// <param name="path" type="String">Path of file to save into.</param> var ForReading = 1, ForWriting = 2; var fso = new ActiveXObject("Scripting.FileSystemObject"); var file = fso.OpenTextFile(path, ForWriting, true); file.Write(content); file.Close(); } function SelectLength(value) { return value.length; } function SendMicrosoftMail(subject, text, toAddress) { var shell = new ActiveXObject("WScript.Shell"); var userName = shell.ExpandEnvironmentStrings("%username%"); var fromAddress = userName + "@microsoft.com"; var server = "smtphost.redmond.corp.microsoft.com"; if (!toAddress) { toAddress = fromAddress; } var message = new ActiveXObject("CDO.Message"); var configuration = message.Configuration; // 2 = cdoSendUsingPort; 2 = cdoNTLM configuration.Fields("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2; configuration.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserver") = server; configuration.Fields("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 2; configuration.Fields.Update(); message.To = toAddress; message.From = fromAddress; message.Subject = subject; message.TextBody = text; message.Send(); } function StringBetween(text, startMarker, endMarker) { /// <summary>Returns the text between startMarker and endMarker in text, null if not found.</summary> var startIndex = text.indexOf(startMarker); if (startIndex == -1) return null; var endIndex = text.indexOf(endMarker, startIndex + startMarker.length); if (endIndex == -1) return null; return text.substring(startIndex + startMarker.length, endIndex); } function StringPadRight(value, length, padString) { /// <summary>Returns a padded string.</summary> /// <param name="value" type="String">Value to pad.</param> /// <param name="length" type="Number" integer="true">Target length for string.</param> /// <param name="padString" type="String" optional="true">Optional string to pad with; defaults to space.</param> /// <returns type="String">The padded string.</returns> if (!padString) padString = " "; if (value.length < length) { value = value + Array(length + 1 - value.length).join(padString); } return value; } function StringToLower(text) { /// <summary>Returns the lowercase form of the specified string.</summary> /// <param name="text" type="String">Value to lower.</param> /// <returns type="String">The lowercase value.</returns> if (text) { return text.toLowerCase(); } else { return text; } } function StringSplit(strLine, strSeparator) { /// <summary>Splits a string into a string array.</summary> var result = new Array(); var startIndex = 0; var resultIndex = 0; while (startIndex < strLine.length) { var endIndex = strLine.indexOf(strSeparator, startIndex); if (endIndex == -1) { endIndex = strLine.length; } result[resultIndex] = strLine.substring(startIndex, endIndex); startIndex = endIndex + strSeparator.length; resultIndex++; } return result; } function StringTrim(text) { var result = text.replace(/^\s*/, "").replace(/\s*$/, ""); return result } function PathCombine(path1, path2) { if (path1.charAt(path1.length - 1) !== "\\") { return path1 + "\\" + path2; } return path1 + path2; } function RemoveReadOnlyAttribute(path) { /// <summary>Removes the read-only attribute on the specified file.</summary> /// <param name="path" type="String">Path to the file.</param> var fso = new ActiveXObject("Scripting.FileSystemObject"); var f = fso.getFile(path); if (1 === (f.attributes & 1)) { f.attributes = (f.attributes & ~1); } } function RunWmiQuery(query) { /// <summary>Runs a WMI query and returns all objects.</summary> /// <param name="query" type="String">Query to run.</param> /// <returns type="Array">Array with results.</returns> var result = []; var wmiService = GetObject("winmgmts:\\\\.\\root\\cimv2"); var items = wmiService.ExecQuery(query); var e = new Enumerator(items); while (!e.atEnd()) { result.push(e.item()); e.moveNext(); } return result; } function WriteRecordSetToTextStreamAsAsciiTable(objRecordSet, stream) { /// <summary>Writes all content of the specified ADO RecordSet into the given text stream.</summary> /// <param name="objRecordSet">RecordSet to write out to.</param> /// <param name="stream">Optional TextStream to write to; defaults to WScript.Out.</param> var outStream = (stream) ? stream : WScript.StdOut; var fields = objRecordSet.Fields; var columns = new Array(fields.Count); var rowCount = 1; for (var i = 0; i < fields.Count; i++) { columns[i] = []; columns[i].push(fields.Item(i).Name); } while (!objRecordSet.EOF) { for (var i = 0; i < fields.Count; i++) { columns[i].push(DbValueToString(fields.Item(i).Value)); } ++rowCount; objRecordSet.MoveNext(); } var columnSizes = new Array(columns.length); for (var i = 0; i < columns.length; ++i) { var valueLengths = ArraySelect(columns[i], SelectLength); columnSizes[i] = ArrayMax(valueLengths); } for (var rowIndex = 0; rowIndex < rowCount; ++rowIndex) { for (var i = 0; i < columnSizes.length; ++i) { outStream.Write(StringPadRight(columns[i][rowIndex], 1 + columnSizes[i])); } outStream.WriteLine(); if (rowIndex === 0) { for (var i = 0; i < columnSizes.length; ++i) { outStream.Write(StringPadRight("", columnSizes[i], "-")); outStream.Write(" "); } outStream.WriteLine(); } } } function WriteRecordSetToTextStream(objRecordSet, separator, stream) { /// <summary>Writes all content of the specified ADO RecordSet into the given text stream.</summary> /// <param name="objRecordSet">RecordSet to write out to.</param> /// <param name="separator" type="String">Text between fields.</param> /// <param name="stream">Optional TextStream to write to; defaults to WScript.Out.</param> var outStream = (stream) ? stream : WScript.StdOut; var fields = objRecordSet.Fields; for (var i = 0; i < fields.Count; i++) { if (i > 0) outStream.Write(separator); outStream.Write(fields.Item(i).Name); } outStream.WriteLine(); while (!objRecordSet.EOF) { for (var i = 0; i < fields.Count; i++) { if (i > 0) outStream.Write(separator); outStream.Write(fields.Item(i).Value); } outStream.WriteLine(); objRecordSet.MoveNext(); } } function WriteXmlFile(document, path) { /// <summary>Write an XML document to the specified path.</summary> /// <param name="path" type="String">Path to file on disk.</param> document.save(path); }
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/hct/VerifierHelper.py
# Copyright (C) Microsoft Corporation. All rights reserved. # This file is distributed under the University of Illinois Open Source License. See LICENSE.TXT for details. r"""VerifierHelper.py - help with test content used with: ClangHLSLTests /name:VerifierTest.* This script will produce an HLSL file with expected-error and expected-warning statements corresponding to actual errors/warnings produced from ClangHLSLTests. The new file will be located in %TEMP%, named after the original file, but with the added extension '.result'. This can then be compared with the original file (such as varmods-syntax.hlsl) to see the differences in errors. It may also be used to replace the original file, once the correct output behavior is verified. This script can also be used to do the same with fxc, adding expected errors there too. If there were errors/warnings/notes reported by clang, but nothing reported by fxc, an "fxc-pass {{}}" entry will be added. If copied to reference, it means that you sign off on the difference in behavior between clang and fxc. In ast mode, this will find the ast subtree corresponding to a line of code preceding a line containing only: "/*verify-ast", and insert a stripped subtree between this marker and a line containing only: "*/". This relies on clang.exe in the build directory. This tool expects clang.exe and ClangHLSLTests.dll to be in %HLSL_BLD_DIR%\bin\Debug. Usage: VerifierHelper.py clang <testname> - run test through ClangHLSLTests and show differences VerifierHelper.py fxc <testname> - run test through fxc and show differences VerifierHelper.py ast <testname> - run test through ast-dump and show differences VerifierHelper.py all <testname> - run test through ClangHLSLTests, ast-dump, and fxc, then show differences <testname> - name of verifier test as passed to "te ClangHLSLTests.dll /name:VerifierTest::<testname>": Example: RunVarmodsSyntax Can also specify * to run all tests Environment variables - set these to ensure this tool works properly: HLSL_SRC_DIR - root path of HLSLonLLVM enlistment HLSL_BLD_DIR - path to projects and build output HLSL_FXC_PATH - fxc.exe to use for comparison purposes HLSL_DIFF_TOOL - tool to use for file comparison (optional) """ import os, sys, re import subprocess try: DiffTool = os.environ["HLSL_DIFF_TOOL"] except: DiffTool = None try: FxcPath = os.environ["HLSL_FXC_PATH"] except: FxcPath = "fxc" HlslVerifierTestCpp = os.path.expandvars( r"${HLSL_SRC_DIR}\tools\clang\unittests\HLSL\VerifierTest.cpp" ) HlslDataDir = os.path.expandvars(r"${HLSL_SRC_DIR}\tools\clang\test\HLSL") HlslBinDir = os.path.expandvars(r"${HLSL_BLD_DIR}\Debug\bin") VerifierTests = { "RunArrayConstAssign": "array-const-assign.hlsl", "RunArrayIndexOutOfBounds": "array-index-out-of-bounds-HV-2016.hlsl", "RunArrayLength": "array-length.hlsl", "RunAttributes": "attributes.hlsl", "RunBadInclude": "bad-include.hlsl", "RunBinopDims": "binop-dims.hlsl", "RunBitfields": "bitfields.hlsl", "RunBuiltinTypesNoInheritance": "builtin-types-no-inheritance.hlsl", "RunCXX11Attributes": "cxx11-attributes.hlsl", "RunConstAssign": "const-assign.hlsl", "RunConstDefault": "const-default.hlsl", "RunConstExpr": "const-expr.hlsl", "RunConversionsBetweenTypeShapes": "conversions-between-type-shapes.hlsl", "RunConversionsBetweenTypeShapesStrictUDT": "conversions-between-type-shapes-strictudt.hlsl", "RunConversionsNonNumericAggregates": "conversions-non-numeric-aggregates.hlsl", "RunCppErrors": "cpp-errors.hlsl", "RunCppErrorsHV2015": "cpp-errors-hv2015.hlsl", "RunDerivedToBaseCasts": "derived-to-base.hlsl", "RunEffectsSyntax": "effects-syntax.hlsl", "RunEnums": "enums.hlsl", "RunFunctions": "functions.hlsl", "RunImplicitCasts": "implicit-casts.hlsl", "RunIncompleteArray": "incomp_array_err.hlsl", "RunIncompleteType": "incomplete-type.hlsl", "RunIndexingOperator": "indexing-operator.hlsl", "RunInputPatchConst": "InputPatch-const.hlsl", "RunIntrinsicExamples": "intrinsic-examples.hlsl", "RunLiterals": "literals.hlsl", "RunMatrixAssignments": "matrix-assignments.hlsl", "RunMatrixSyntax": "matrix-syntax.hlsl", "RunMatrixSyntaxExactPrecision": "matrix-syntax-exact-precision.hlsl", "RunMintypesPromotionWarnings": "mintypes-promotion-warnings.hlsl", "RunMoreOperators": "more-operators.hlsl", "RunObjectOperators": "object-operators.hlsl", "RunObjectTemplateDiagDeferred": "object-template-diag-deferred.hlsl", "RunOperatorOverloadingForNewDelete": "overloading-new-delete-errors.hlsl", "RunOperatorOverloadingNotDefinedBinaryOp": "use-undefined-overloaded-operator.hlsl", "RunPackReg": "packreg.hlsl", "RunRayTracings": "raytracings.hlsl", "RunScalarAssignments": "scalar-assignments.hlsl", "RunScalarAssignmentsExactPrecision": "scalar-assignments-exact-precision.hlsl", "RunScalarOperators": "scalar-operators.hlsl", "RunScalarOperatorsAssign": "scalar-operators-assign.hlsl", "RunScalarOperatorsAssignExactPrecision": "scalar-operators-assign-exact-precision.hlsl", "RunScalarOperatorsExactPrecision": "scalar-operators-exact-precision.hlsl", "RunSemantics": "semantics.hlsl", "RunSizeof": "sizeof.hlsl", "RunString": "string.hlsl", "RunStructAssignments": "struct-assignments.hlsl", "RunSubobjects": "subobjects-syntax.hlsl", "RunTemplateChecks": "template-checks.hlsl", "RunTemplateLiteralSubstitutionFailure": "template-literal-substitution-failure.hlsl", "RunTypemodsSyntax": "typemods-syntax.hlsl", "RunUint4Add3": "uint4_add3.hlsl", "RunVarmodsSyntax": "varmods-syntax.hlsl", "RunVectorAnd": "vector-and.hlsl", "RunVectorAssignments": "vector-assignments.hlsl", "RunVectorConditional": "vector-conditional.hlsl", "RunVectorOr": "vector-or.hlsl", "RunVectorSelect": "vector-select.hlsl", "RunVectorSyntax": "vector-syntax.hlsl", "RunVectorSyntaxExactPrecision": "vector-syntax-exact-precision.hlsl", "RunVectorSyntaxMix": "vector-syntax-mix.hlsl", "RunWave": "wave.hlsl", "RunWriteConstArrays": "write-const-arrays.hlsl", "RunAtomicsOnBitfields": "atomics-on-bitfields.hlsl", "RunWorkGraphs": "work-graphs.hlsl", "RunUnboundedResourceArrays": "invalid-unbounded-resource-arrays.hlsl", } # The following test(s) do not work in fxc mode: fxcExcludedTests = [ "RunArrayLength", "RunBitfields", "RunCppErrors", "RunCppErrorsHV2015", "RunCXX11Attributes", "RunConversionsBetweenTypeShapesStrictUDT", "RunEnums", "RunIncompleteType", "RunIntrinsicExamples", "RunMatrixSyntaxExactPrecision", "RunObjectTemplateDiagDeferred", "RunOperatorOverloadingForNewDelete", "RunOperatorOverloadingNotDefinedBinaryOp", "RunRayTracings", "RunScalarAssignmentsExactPrecision", "RunScalarOperatorsAssignExactPrecision", "RunScalarOperatorsExactPrecision", "RunSizeof", "RunSubobjects", "RunTemplateChecks", "RunTemplateLiteralSubstitutionFailure", "RunVectorSyntaxExactPrecision", "RunWave", "RunAtomicsOnBitfields", "RunWorkGraphs", ] # rxRUN = re.compile(r'[ RUN ] VerifierTest.(\w+)') # gtest syntax rxRUN = re.compile(r"StartGroup: VerifierTest::(\w+)") # TAEF syntax rxEndGroup = re.compile(r"EndGroup: VerifierTest::(\w+)\s+\[(\w+)\]") # TAEF syntax rxForProgram = re.compile(r"^for program (.*?) with errors\:$") # rxExpected = re.compile(r"^error\: \'(\w+)\' diagnostics (expected but not seen|seen but not expected)\: $") # gtest syntax rxExpected = re.compile( r"^\'(\w+)\' diagnostics (expected but not seen|seen but not expected)\: $" ) # TAEF syntax rxDiagReport = re.compile(r" (?:File (.*?) )?Line (\d+): (.*)$") rxDiag = re.compile(r"((expected|fxc)-(error|warning|note|pass)\s*\{\{(.*?)\}\}\s*)") rxFxcErr = re.compile( r"(.+)\((\d+)(?:,(\d+)(?:\-(\d+))?)?\)\: (error|warning) (.*?)\: (.*)" ) # groups = (filename, line, colstart, colend, ew, error_code, error_message) rxCommentStart = re.compile(r"(//|/\*)") rxStrings = re.compile(r"(\'|\").*?((?<!\\)\1)") rxBraces = re.compile(r"(\(|\)|\{|\}|\[|\])") rxStatementEndOrBlockBegin = re.compile(r"(\;|\{)") rxLineContinued = re.compile(r".*\\$") rxVerifyArguments = re.compile(r"\s*//\s*\:FXC_VERIFY_ARGUMENTS\:\s+(.*)") rxVerifierTestMethod = re.compile(r"TEST_F\(VerifierTest,\s*(\w+)\)\s*") rxVerifierTestCheckFile = re.compile(r'CheckVerifiesHLSL\s*\(\s*L?\"([^"]+)"\s*\)') rxVerifyAst = re.compile( r"^\s*(\/\*verify\-ast)\s*$" ) # must start with line containing only "/*verify-ast" rxEndVerifyAst = re.compile(r"^\s*\*\/\s*$") # ends with line containing only "*/" rxAstSourceLocation = re.compile( r"""\<(?:(?P<Invalid>\<invalid\ sloc\>) | (?: (?:(?:(?P<FromFileLine>line|\S*):(?P<FromLine>\d+):(?P<FromLineCol>\d+)) | col:(?P<FromCol>\d+) ) (?:,\s+ (?:(?:(?P<ToFileLine>line|\S*):(?P<ToLine>\d+):(?P<ToLineCol>\d+)) | col:(?P<ToCol>\d+) ) )? ) )\>""", re.VERBOSE, ) rxAstHexAddress = re.compile(r"\b(0x[0-9a-f]+) ?") rxAstNode = re.compile(r"((?:\<\<\<NULL\>\>\>)|(?:\w+))\s*(.*)") # matches ignored portion of line for first AST node in subgraph to match rxAstIgnoredIndent = re.compile(r"^(\s+|\||\`|\-)*") # The purpose of StripComments and CountBraces is to be used when commenting lines of code out to allow # Fxc testing to continue even when it doesn't recover as well as clang. Some error lines are on the # beginning of a function, where commenting just that line will comment out the beginning of the function # block, but not the body or end of the block, producing invalid syntax. Here's an example: # void foo(error is here) { /* expected-error {{some expected clang error}} */ # return; # } # If the first line is commented without the rest of the function, it will be incorrect code. # So the intent is to detect when the line being commented out results in an unbalanced brace matching. # Then these functions will be used to comment additional lines until the braces match again. # It's simple and won't handle the general case, but should handle the cases in the test files, and if # not, the tests should be easily modifyable to work with it. # This still does not handle preprocessor directives, or escaped characters (like line ends or escaped # quotes), or other cases that a real parser would handle. def StripComments(line, multiline_comment_continued=False): "Remove comments from line, returns stripped line and multiline_comment_continued if a multiline comment continues beyond the line" if multiline_comment_continued: # in multiline comment, only look for end of that idx = line.find("*/") if idx < 0: return "", True return StripComments(line[idx + 2 :]) # look for start of multiline comment or eol comment: m = rxCommentStart.search(line) if m: if m.group(1) == "/*": line_end, multiline_comment_continued = StripComments( line[m.end(1) :], True ) return line[: m.start(1)] + line_end, multiline_comment_continued elif m.group(1) == "//": return line[: m.start(1)], False return line, False def CountBraces(line, bracestacks): m = rxStrings.search(line) if m: CountBraces(line[: m.start(1)], bracestacks) CountBraces(line[m.end(2) :], bracestacks) return for b in rxBraces.findall(line): if b in "()": bracestacks["()"] = bracestacks.get("()", 0) + ((b == "(") and 1 or -1) elif b in "{}": bracestacks["{}"] = bracestacks.get("{}", 0) + ((b == "{") and 1 or -1) elif b in "[]": bracestacks["[]"] = bracestacks.get("[]", 0) + ((b == "[") and 1 or -1) def ProcessStatementOrBlock(lines, start, fn_process): num = 0 # statement_continued initialized with whether line has non-whitespace content statement_continued = not not StripComments(lines[start], False)[0].strip() # Assumes start of line is not inside multiline comment multiline_comment_continued = False bracestacks = {} while start + num < len(lines): line = lines[start + num] lines[start + num] = fn_process(line) num += 1 line, multiline_comment_continued = StripComments( line, multiline_comment_continued ) CountBraces(line, bracestacks) if statement_continued and not rxStatementEndOrBlockBegin.search(line): continue statement_continued = False if rxLineContinued.match(line): continue if ( bracestacks.get("{}", 0) < 1 and bracestacks.get("()", 0) < 1 and bracestacks.get("[]", 0) < 1 ): break return num def CommentStatementOrBlock(lines, start): def fn_process(line): return "// " + line return ProcessStatementOrBlock(lines, start, fn_process) def ParseVerifierTestCpp(): "Returns dictionary mapping Run* test name to hlsl filename by parsing VerifierTest.cpp" tests = {} FoundTest = None def fn_null(line): return line def fn_process(line): searching = FoundTest is not None if searching: m = rxVerifierTestCheckFile.search(line) if m: tests[FoundTest] = m.group(1) searching = False return line with open(HlslVerifierTestCpp, "rt") as f: lines = f.readlines() start = 0 while start < len(lines): m = rxVerifierTestMethod.search(lines[start]) if m: FoundTest = m.group(1) start += ProcessStatementOrBlock(lines, start, fn_process) if FoundTest not in tests: print("Could not parse file for test %s" % FoundTest) FoundTest = None else: start += ProcessStatementOrBlock(lines, start, fn_null) return tests class SourceLocation(object): def __init__(self, line=None, **kwargs): if not kwargs: self.Invalid = "<invalid sloc>" return for key, value in kwargs.items(): try: value = int(value) except: pass setattr(self, key, value) if line and not self.FromLine: self.FromLine = line self.FromCol = self.FromCol or self.FromLineCol self.ToCol = self.ToCol or self.ToLineCol def Offset(self, offset): "Offset From/To Lines by specified value" if self.Invalid: return if self.FromLine: self.FromLine = self.FromLine + offset if self.ToLine: self.ToLine = self.ToLine + offset def ToStringAtLine(self, line): "convert to string relative to specified line" if self.Invalid: sloc = self.Invalid else: if self.FromLine and line != self.FromLine: sloc = "line:%d:%d" % (self.FromLine, self.FromCol) line = self.FromLine else: sloc = "col:%d" % self.FromCol if self.ToCol: if self.ToLine and line != self.ToLine: sloc += ", line:%d:%d" % (self.ToLine, self.ToCol) else: sloc += ", col:%d" % self.ToCol return "<" + sloc + ">" class AstNode(object): def __init__(self, name, sloc, prefix, text, indent=""): self.name, self.sloc, self.prefix, self.text, self.indent = ( name, sloc, prefix, text, indent, ) self.children = [] def ToStringAtLine(self, line): "convert to string relative to specified line" if self.name == "<<<NULL>>>": return self.name return ( "%s %s%s %s" % (self.name, self.prefix, self.sloc.ToStringAtLine(line), self.text) ).strip() def WalkAstChildren(ast_root): "yield each child node in the ast tree in depth-first order" for node in ast_root.children: yield node for child in WalkAstChildren(node): yield child def WriteAstSubtree(ast_root, line, indent=""): output = [] output.append(indent + ast_root.ToStringAtLine(line)) if not ast_root.sloc.Invalid and ast_root.sloc.FromLine: line = ast_root.sloc.FromLine root_indent_len = len(ast_root.indent) for child in WalkAstChildren(ast_root): output.append( indent + child.indent[root_indent_len:] + child.ToStringAtLine(line) ) if not child.sloc.Invalid and child.sloc.FromLine: line = child.sloc.FromLine return output def FindAstNodesByLine(ast_root, line): nodes = [] if not ast_root.sloc.Invalid and ast_root.sloc.FromLine == line: return [ast_root] if ( not ast_root.sloc.Invalid and ast_root.sloc.ToLine and ast_root.sloc.ToLine < line ): return [] for child in ast_root.children: sub_nodes = FindAstNodesByLine(child, line) if sub_nodes: nodes += sub_nodes return nodes def ParseAst(astlines): cur_line = 0 # current source line root_node = None ast_stack = ( [] ) # stack of nodes and column numbers so we can pop the right number of nodes up the stack i = 0 # ast line index def push(node, col): if ast_stack: cur_node, prior_col = ast_stack[-1] cur_node.children.append(node) ast_stack.append((node, col)) def popto(col): cur_node, prior_col = ast_stack[-1] while ast_stack and col <= prior_col: ast_stack.pop() cur_node, prior_col = ast_stack[-1] assert ast_stack def parsenode(text, indent): m = rxAstNode.match(text) if m: name = m.group(1) text = text[m.end(1) :].strip() else: print("rxAstNode match failed on:\n %s" % text) return AstNode("ast-parse-failed", SourceLocation(), "", "", indent) text = rxAstHexAddress.sub("", text).strip() m = rxAstSourceLocation.search(text) if m: prefix = text[: m.start()] sloc = SourceLocation(cur_line, **m.groupdict()) text = text[m.end() :].strip() else: prefix = "" sloc = SourceLocation() return AstNode(name, sloc, prefix, text, indent) # Look for TranslationUnitDecl and start from there while i < len(astlines): text = astlines[i] if text.startswith("TranslationUnitDecl"): root_node = parsenode(text, "") push(root_node, 0) break i += 1 i += 1 # gather ast nodes while i < len(astlines): line = astlines[i] # get starting column and update stack m = rxAstIgnoredIndent.match(line) indent = "" col = 0 if m: indent = m.group(0) col = m.end() if col == 0: break # at this point we should be done parsing the translation unit! popto(col) # parse and add the node node = parsenode(line[col:], indent) if not node: print("error parsing line %d:\n%s" % (i + 1, line)) assert False push(node, col) # update current source line sloc = node.sloc if not sloc.Invalid and sloc.FromLine: cur_line = sloc.FromLine i += 1 return root_node class File(object): def __init__(self, filename): self.filename = filename self.expected = ( {} ) # {line_num: [('error' or 'warning', 'error or warning message'), ...], ...} self.unexpected = ( {} ) # {line_num: [('error' or 'warning', 'error or warning message'), ...], ...} self.last_diag_col = None def AddExpected(self, line_num, ew, message): self.expected.setdefault(line_num, []).append((ew, message)) def AddUnexpected(self, line_num, ew, message): self.unexpected.setdefault(line_num, []).append((ew, message)) def MatchDiags(self, line, diags=[], prefix="expected", matchall=False): diags = diags[:] diag_col = None matches = [] for m in rxDiag.finditer(line): if diag_col is None: diag_col = m.start() self.last_diag_col = diag_col if m.group(2) == prefix: pattern = m.groups()[2:4] for idx, (ew, message) in enumerate(diags): if pattern == (ew, message): matches.append(m) break else: if matchall: matches.append(m) continue del diags[idx] return sorted(matches, key=lambda m: m.start()), diags, diag_col def RemoveDiags(self, line, diags, prefix="expected", removeall=False): """Removes expected-* diags from line, returns result_line, remaining_diags, diag_col Where, result_line is the line without the matching diagnostics, remaining is the list of diags not found on the line, diag_col is the column of the first diagnostic found on the line. """ matches, diags, diag_col = self.MatchDiags(line, diags, prefix, removeall) for m in reversed(matches): line = line[: m.start()] + line[m.end() :] return line, diags, diag_col def AddDiags(self, line, diags, diag_col=None, prefix="expected"): "Adds expected-* diags to line." if diags: if diag_col is None: if self.last_diag_col is not None and self.last_diag_col - 3 > len( line ): diag_col = self.last_diag_col else: diag_col = max( len(line) + 7, 63 ) # 4 spaces + '/* ' or at column 63, whichever is greater line = line + (" " * ((diag_col - 3) - len(line))) + "/* */" for ew, message in reversed(diags): line = ( line[:diag_col] + ("%s-%s {{%s}} " % (prefix, ew, message)) + line[diag_col:] ) return line.rstrip() def SortDiags(self, line): matches = list(rxDiag.finditer(line)) if matches: for m in sorted(matches, key=lambda m: m.start(), reverse=True): line = line[: m.start()] + line[m.end() :] diag_col = m.start() for m in sorted(matches, key=lambda m: m.groups()[1:], reverse=True): line = ( line[:diag_col] + ("%s-%s {{%s}} " % m.groups()[1:]) + line[diag_col:] ) return line.rstrip() def OutputResult(self): temp_filename = os.path.expandvars( r"${TEMP}\%s" % os.path.split(self.filename)[1] ) with open(self.filename, "rt") as fin: with open(temp_filename + ".result", "wt") as fout: line_num = 0 for line in fin.readlines(): if line[-1] == "\n": line = line[:-1] line_num += 1 line, expected, diag_col = self.RemoveDiags( line, self.expected.get(line_num, []) ) for ew, message in expected: print( "Error: Line %d: Could not find: expected-%s {{%s}}!!" % (line_num, ew, message) ) line = self.AddDiags( line, self.unexpected.get(line_num, []), diag_col ) line = self.SortDiags(line) fout.write(line + "\n") def TryFxc(self, result_filename=None): temp_filename = os.path.expandvars( r"${TEMP}\%s" % os.path.split(self.filename)[1] ) if result_filename is None: result_filename = temp_filename + ".fxc" inlines = [] with open(self.filename, "rt") as fin: for line in fin.readlines(): if line[-1] == "\n": line = line[:-1] inlines.append(line) verify_arguments = None for line in inlines: m = rxVerifyArguments.search(line) if m: verify_arguments = m.group(1) print("Found :FXC_VERIFY_ARGUMENTS: %s" % verify_arguments) break # result will hold the final result after adding fxc error messages # initialize it by removing all the expected diagnostics result = [(line, None, False) for line in inlines] for n, (line, diag_col, expected) in enumerate(result): line, diags, diag_col = self.RemoveDiags( line, [], prefix="fxc", removeall=True ) matches, diags, diag_col2 = self.MatchDiags( line, [], prefix="expected", matchall=True ) if matches: expected = True ## if diag_col is None: ## diag_col = diag_col2 ## elif diag_col2 < diag_col: ## diag_col = diag_col2 result[n] = (line, diag_col, expected) # commented holds the version that gets progressively commented as fxc reports errors commented = inlines[:] # diags_by_line is a dictionary of a set of errors and warnings keyed off line_num diags_by_line = {} while True: with open(temp_filename + ".fxc_temp", "wt") as fout: fout.write("\n".join(commented)) if verify_arguments is None: fout.write("\n[numthreads(1,1,1)] void _test_main() { }\n") if verify_arguments is None: args = "/E _test_main /T cs_5_1".split() else: args = verify_arguments.split() fxcres = subprocess.run( [ "%s" % FxcPath, temp_filename + ".fxc_temp", *args, "/nologo", "/DVERIFY_FXC=1", "/Fo", temp_filename + ".fxo", "/Fe", temp_filename + ".err", ], capture_output=True, text=True, ) with open(temp_filename + ".err", "rt") as f: errors = [m for m in map(rxFxcErr.match, f.readlines()) if m] errors = sorted(errors, key=lambda m: int(m.group(2))) first_error = None for m in errors: line_num = int(m.group(2)) if not first_error and m.group(5) == "error": first_error = line_num elif first_error and line_num > first_error: break diags_by_line.setdefault(line_num, set()).add( (m.group(5), m.group(6) + ": " + m.group(7)) ) if first_error and first_error <= len(commented): CommentStatementOrBlock(commented, first_error - 1) else: break # Add diagnostic messages from fxc to result: self.last_diag_col = None for i, (line, diag_col, expected) in enumerate(result): line_num = i + 1 if diag_col: self.last_diag_col = diag_col diags = diags_by_line.get(line_num, set()) if not diags: if expected: diags.add(("pass", "")) else: continue diags = sorted(list(diags)) line = self.SortDiags(self.AddDiags(line, diags, diag_col, prefix="fxc")) result[i] = line, diag_col, expected with open(result_filename, "wt") as f: f.write("\n".join(map((lambda res: res[0]), result))) def TryAst(self, result_filename=None): temp_filename = os.path.expandvars( r"${TEMP}\%s" % os.path.split(self.filename)[1] ) if result_filename is None: result_filename = temp_filename + ".ast" try: os.unlink(result_filename) except: pass result = subprocess.run( [ "%s\\dxc.exe" % HlslBinDir, "-ast-dump", "-E", "main", "-T", "ps_5_0", self.filename, ], capture_output=True, text=True, ) # dxc dumps ast even if there exists any syntax error. If there is any error, dxc returns some nonzero errorcode. if not result.stdout: with open("%s.log" % temp_filename, "wt") as f: f.write(result.stderr) print('ast-dump failed, see log:\n "%s.log"' % (temp_filename)) return try: ast_root = ParseAst(result.stdout.splitlines()) except: with open("%s" % result_filename, "wt") as f: f.write(result.stdout) print('ParseAst failed on "%s"' % (result_filename)) raise inlines = [] with open(self.filename, "rt") as fin: for line in fin.readlines(): if line[-1] == "\n": line = line[:-1] inlines.append(line) outlines = [] i = 0 while i < len(inlines): line = inlines[i] outlines.append(line) m = rxVerifyAst.match(line) if m: indent = line[: m.start(1)] + " " # at this point i is the ONE based source line number # (since it's one past the line we want to verify in zero based index) ast_nodes = FindAstNodesByLine(ast_root, i) if not ast_nodes: outlines += [indent + "No matching AST found for line!"] else: for ast in ast_nodes: outlines += WriteAstSubtree(ast, i, indent) while i + 1 < len(inlines) and not rxEndVerifyAst.match(inlines[i + 1]): i += 1 i += 1 with open(result_filename, "wt") as f: f.write("\n".join(outlines)) def ProcessVerifierOutput(lines): files = {} cur_filename = None cur_test = None state = "WaitingForFile" ew = "" expected = None for line in lines: if not line: continue if line[-1] == "\n": line = line[:-1] m = rxRUN.match(line) if m: cur_test = m.group(1) m = rxForProgram.match(line) if m: cur_filename = m.group(1) files[cur_filename] = File(cur_filename) state = "WaitingForCategory" continue if state == "WaitingForFile": m = rxEndGroup.match(line) if m and m.group(2) == "Failed": # This usually happens when compiler crashes print( "Fatal Error: test %s failed without verifier results." % cur_test ) if state == "WaitingForCategory" or state == "ReadingErrors": m = rxExpected.match(line) if m: ew = m.group(1) expected = m.group(2) == "expected but not seen" state = "ReadingErrors" continue if state == "ReadingErrors": m = rxDiagReport.match(line) if m: line_num = int(m.group(2)) if expected: files[cur_filename].AddExpected(line_num, ew, m.group(3)) else: files[cur_filename].AddUnexpected(line_num, ew, m.group(3)) continue for f in files.values(): f.OutputResult() return files def maybe_compare(filename1, filename2): with open(filename1, "rt") as fbefore: with open(filename2, "rt") as fafter: before = fbefore.read() after = fafter.read() if before.strip() != after.strip(): print( "Differences found. Compare:\n %s\nwith:\n %s" % (filename1, filename2) ) if DiffTool: subprocess.Popen( [DiffTool, filename1, filename2], creationflags=subprocess.DETACHED_PROCESS, ) return True return False def PrintUsage(): print(__doc__) print("Available tests and corresponding files:") tests = sorted(VerifierTests.keys()) width = len(max(tests, key=len)) for name in tests: print((" %%-%ds %%s" % width) % (name, VerifierTests[name])) print("Tests incompatible with fxc mode:") for name in fxcExcludedTests: print(" %s" % name) def RunVerifierTest(test, HlslDataDir=HlslDataDir): import codecs temp_filename = os.path.expandvars(r"${TEMP}\VerifierHelper_temp.txt") cmd = ( 'te %s\\ClangHLSLTests.dll /p:"HlslDataDir=%s" /name:VerifierTest::%s > %s' % (HlslBinDir, HlslDataDir, test, temp_filename) ) print(cmd) os.system(cmd) # TAEF test # TAEF outputs unicode, so read as binary and convert: with open(temp_filename, "rb") as f: return ( codecs.decode(f.read(), "UTF-16") .replace("\x7f", "") .replace("\r\n", "\n") .splitlines() ) def main(*args): global VerifierTests try: VerifierTests = ParseVerifierTestCpp() except: print("Unable to parse tests from VerifierTest.cpp; using defaults") if len(args) < 1 or ( args[0][0] in "-/" and args[0][1:].lower() in ("h", "?", "help") ): PrintUsage() return -1 mode = args[0] if mode == "fxc": allFxcTests = sorted( filter(lambda key: key not in fxcExcludedTests, VerifierTests.keys()) ) if args[1] == "*": tests = allFxcTests else: if args[1] not in allFxcTests: PrintUsage() return -1 tests = [args[1]] differences = False for test in tests: print("---- %s ----" % test) filename = os.path.join(HlslDataDir, VerifierTests[test]) result_filename = os.path.expandvars( r"${TEMP}\%s.fxc" % os.path.split(filename)[1] ) File(filename).TryFxc() differences = maybe_compare(filename, result_filename) or differences if not differences: print("No differences found!") elif mode == "clang": if args[1] != "*" and args[1] not in VerifierTests: PrintUsage() return -1 files = ProcessVerifierOutput(RunVerifierTest(args[1])) differences = False if files: for f in files.values(): if f.expected or f.unexpected: result_filename = os.path.expandvars( r"${TEMP}\%s.result" % os.path.split(f.filename)[1] ) differences = ( maybe_compare(f.filename, result_filename) or differences ) if not differences: print("No differences found!") elif mode == "ast": allAstTests = sorted(VerifierTests.keys()) if args[1] == "*": tests = allAstTests else: if args[1] not in allAstTests: PrintUsage() return -1 tests = [args[1]] differences = False for test in tests: print("---- %s ----" % test) filename = os.path.join(HlslDataDir, VerifierTests[test]) result_filename = os.path.expandvars( r"${TEMP}\%s.ast" % os.path.split(filename)[1] ) File(filename).TryAst() differences = maybe_compare(filename, result_filename) or differences if not differences: print("No differences found!") elif mode == "all": allTests = sorted(VerifierTests.keys()) if args[1] == "*": tests = allTests else: if args[1] not in allTests: PrintUsage() return -1 tests = [args[1]] # Do clang verifier tests, updating source file paths for changed files: sourceFiles = dict( [ (VerifierTests[test], os.path.join(HlslDataDir, VerifierTests[test])) for test in tests ] ) files = ProcessVerifierOutput(RunVerifierTest(args[1])) if files: for f in files.values(): if f.expected or f.unexpected: name = os.path.split(f.filename)[1] sourceFiles[name] = os.path.expandvars(r"${TEMP}\%s.result" % name) # update verify-ast blocks: for name, sourceFile in sourceFiles.items(): result_filename = os.path.expandvars(r"${TEMP}\%s.ast" % name) File(sourceFile).TryAst(result_filename) sourceFiles[name] = result_filename # now do fxc verification and final comparison differences = False fxcExcludedFiles = [VerifierTests[test] for test in fxcExcludedTests] width = len(max(tests, key=len)) for test in tests: name = VerifierTests[test] sourceFile = sourceFiles[name] print(("Test %%-%ds - %%s" % width) % (test, name)) result_filename = os.path.expandvars(r"${TEMP}\%s.fxc" % name) if name not in fxcExcludedFiles: File(sourceFile).TryFxc(result_filename) sourceFiles[name] = result_filename differences = ( maybe_compare(os.path.join(HlslDataDir, name), sourceFiles[name]) or differences ) if not differences: print("No differences found!") else: PrintUsage() return -1 return 0 if __name__ == "__main__": sys.exit(main(*sys.argv[1:]))
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/hct/hctdb_test.py
# This file is distributed under the University of Illinois Open Source License. See LICENSE.TXT for details ############################################################################### # This file contains driver test information for DXIL operations # ############################################################################### from hctdb import * import xml.etree.ElementTree as ET import argparse parser = argparse.ArgumentParser( description="contains information about dxil op test cases." ) parser.add_argument("mode", help="'gen-xml' or 'info'") g_db_dxil = None def get_db_dxil(): global g_db_dxil if g_db_dxil is None: g_db_dxil = db_dxil() return g_db_dxil """ This class represents a test case for instructions for driver testings DXIL instructions and test cases are two disjoint sets where each instruction can have multiple test cases, and each test case can cover different DXIL instructions. So these two sets form a bipartite graph. test_name: Test case identifier. Must be unique for each test case. insts: dxil instructions validation_type: validation type for test epsilon: absolute difference check ulp: units in last place check relative: relative error check validation_tolerance: tolerance value for a given test inputs: testing inputs outputs: expected outputs for each input shader_target: target for testing shader_text: hlsl file that is used for testing dxil op """ class test_case(object): def __init__( self, test_name, insts, validation_type, validation_tolerance, input_lists, output_lists, shader_target, shader_text, **kwargs ): self.test_name = test_name self.validation_type = validation_type self.validation_tolerance = validation_tolerance self.input_lists = input_lists self.output_lists = output_lists self.shader_target = shader_target self.shader_text = shader_text self.insts = insts # list of instructions each test case cover self.warp_version = -1 # known warp version that works self.shader_arguments = "" for k, v in kwargs.items(): setattr(self, k, v) # Wrapper for each DXIL instruction class inst_node(object): def __init__(self, inst): self.inst = inst self.test_cases = [] # list of test_case def add_test_case( test_name, inst_names, validation_type, validation_tolerance, input_lists, output_lists, shader_target, shader_text, **kwargs ): insts = [] for inst_name in inst_names: assert inst_name in g_instruction_nodes insts += [g_instruction_nodes[inst_name].inst] case = test_case( test_name, insts, validation_type, validation_tolerance, input_lists, output_lists, shader_target, shader_text, **kwargs ) g_test_cases[test_name] = case # update instruction nodes for inst_name in inst_names: g_instruction_nodes[inst_name].test_cases += [case] def add_test_case_int( test_name, inst_names, validation_type, validation_tolerance, input_lists, output_lists, shader_key, shader_op_name, **kwargs ): add_test_case( test_name, inst_names, validation_type, validation_tolerance, input_lists, output_lists, "cs_6_0", get_shader_text(shader_key, shader_op_name), **kwargs ) input_lists_16, output_lists_16 = input_lists, output_lists if "input_16" in kwargs: input_lists_16 = kwargs["input_16"] if "output_16" in kwargs: output_lists_16 = kwargs["output_16"] add_test_case( test_name + "Bit16", inst_names, validation_type, validation_tolerance, input_lists_16, output_lists_16, "cs_6_2", get_shader_text(shader_key.replace("int", "int16_t"), shader_op_name), shader_arguments="-enable-16bit-types", **kwargs ) def add_test_case_float_half( test_name, inst_names, validation_type, validation_tolerance, float_input_lists, float_output_lists, shader_key, shader_op_name, **kwargs ): add_test_case( test_name, inst_names, validation_type, validation_tolerance, float_input_lists, float_output_lists, "cs_6_0", get_shader_text(shader_key, shader_op_name), **kwargs ) # if half test cases are different from float input lists, use those lists instead for half testings ( half_input_lists, half_output_lists, half_validation_type, half_validation_tolerance, ) = (float_input_lists, float_output_lists, validation_type, validation_tolerance) if "half_inputs" in kwargs: half_input_lists = kwargs["half_inputs"] if "half_outputs" in kwargs: half_output_lists = kwargs["half_outputs"] if "half_validation_type" in kwargs: half_validation_type = kwargs["half_validation_type"] if "half_validation_tolerance" in kwargs: half_validation_tolerance = kwargs["half_validation_tolerance"] # skip relative error test check for half for now if validation_type != "Relative": add_test_case( test_name + "Half", inst_names, half_validation_type, half_validation_tolerance, half_input_lists, half_output_lists, "cs_6_2", get_shader_text(shader_key.replace("float", "half"), shader_op_name), shader_arguments="-enable-16bit-types", **kwargs ) def add_test_case_denorm( test_name, inst_names, validation_type, validation_tolerance, input_lists, output_lists_ftz, output_lists_preserve, shader_target, shader_text, **kwargs ): add_test_case( test_name + "FTZ", inst_names, validation_type, validation_tolerance, input_lists, output_lists_ftz, shader_target, shader_text, shader_arguments="-denorm ftz", ) add_test_case( test_name + "Preserve", inst_names, validation_type, validation_tolerance, input_lists, output_lists_preserve, shader_target, shader_text, shader_arguments="-denorm preserve", ) # we can expect the same output for "any" and "preserve" mode. We should make sure that for validation zero are accepted outputs for denormal outputs. add_test_case( test_name + "Any", inst_names, validation_type, validation_tolerance, input_lists, output_lists_preserve + output_lists_ftz, shader_target, shader_text, shader_arguments="-denorm any", ) g_shader_texts = { "unary int": """ struct SUnaryIntOp { int input; int output; }; RWStructuredBuffer<SUnaryIntOp> g_buf : register(u0); [numthreads(8,8,1)] void main(uint GI : SV_GroupIndex) { SUnaryIntOp l = g_buf[GI]; l.output = %s(l.input); g_buf[GI] = l; };""", "unary int16_t": """ struct SUnaryInt16Op { int16_t input; int16_t output; }; RWStructuredBuffer<SUnaryInt16Op> g_buf : register(u0); [numthreads(8,8,1)] void main(uint GI : SV_GroupIndex) { SUnaryInt16Op l = g_buf[GI]; l.output = %s(l.input); g_buf[GI] = l; };""", "unary uint": """ struct SUnaryUintOp { uint input; uint output; }; RWStructuredBuffer<SUnaryUintOp> g_buf : register(u0); [numthreads(8,8,1)] void main(uint GI : SV_GroupIndex) { SUnaryUintOp l = g_buf[GI]; l.output = %s(l.input); g_buf[GI] = l; };""", "unary uint16_t": """ struct SUnaryUint16Op { uint16_t input; uint16_t output; }; RWStructuredBuffer<SUnaryUint16Op> g_buf : register(u0); [numthreads(8,8,1)] void main(uint GI : SV_GroupIndex) { SUnaryUint16Op l = g_buf[GI]; l.output = %s(l.input); g_buf[GI] = l; };""", "unary float": """ struct SUnaryFPOp { float input; float output; }; RWStructuredBuffer<SUnaryFPOp> g_buf : register(u0); [numthreads(8,8,1)] void main(uint GI : SV_GroupIndex) { SUnaryFPOp l = g_buf[GI]; l.output = %s(l.input); g_buf[GI] = l; };""", "unary float bool": """ struct SUnaryFPOp { float input; float output; }; RWStructuredBuffer<SUnaryFPOp> g_buf : register(u0); [numthreads(8,8,1)] void main(uint GI : SV_GroupIndex) { SUnaryFPOp l = g_buf[GI]; if (%s(l.input)) l.output = 1; else l.output = 0; g_buf[GI] = l; };""", "unary half": """ struct SUnaryFPOp { float16_t input; float16_t output; }; RWStructuredBuffer<SUnaryFPOp> g_buf : register(u0); [numthreads(8,8,1)] void main(uint GI : SV_GroupIndex) { SUnaryFPOp l = g_buf[GI]; l.output = %s(l.input); g_buf[GI] = l; };""", "unary half bool": """ struct SUnaryFPOp { float16_t input; float16_t output; }; RWStructuredBuffer<SUnaryFPOp> g_buf : register(u0); [numthreads(8,8,1)] void main(uint GI : SV_GroupIndex) { SUnaryFPOp l = g_buf[GI]; if (%s(l.input)) l.output = 1; else l.output = 0; g_buf[GI] = l; };""", "binary int": """ struct SBinaryIntOp { int input1; int input2; int output1; int output2; }; RWStructuredBuffer<SBinaryIntOp> g_buf : register(u0); [numthreads(8,8,1)] void main(uint GI : SV_GroupIndex) { SBinaryIntOp l = g_buf[GI]; l.output1 = l.input1 %s l.input2; g_buf[GI] = l; };""", "binary int16_t": """ struct SBinaryInt16Op { int16_t input1; int16_t input2; int16_t output1; int16_t output2; }; RWStructuredBuffer<SBinaryInt16Op> g_buf : register(u0); [numthreads(8,8,1)] void main(uint GI : SV_GroupIndex) { SBinaryInt16Op l = g_buf[GI]; l.output1 = l.input1 %s l.input2; g_buf[GI] = l; };""", "binary int call": """ struct SBinaryIntOp { int input1; int input2; int output1; int output2; }; RWStructuredBuffer<SBinaryIntOp> g_buf : register(u0); [numthreads(8,8,1)] void main(uint GI : SV_GroupIndex) { SBinaryIntOp l = g_buf[GI]; l.output1 = %s(l.input1,l.input2); g_buf[GI] = l; };""", "binary int16_t call": """ struct SBinaryInt16Op { int16_t input1; int16_t input2; int16_t output1; int16_t output2; }; RWStructuredBuffer<SBinaryInt16Op> g_buf : register(u0); [numthreads(8,8,1)] void main(uint GI : SV_GroupIndex) { SBinaryInt16Op l = g_buf[GI]; l.output1 = %s(l.input1,l.input2); g_buf[GI] = l; };""", "binary uint": """ struct SBinaryUintOp { uint input1; uint input2; uint output1; uint output2; }; RWStructuredBuffer<SBinaryUintOp> g_buf : register(u0); [numthreads(8,8,1)] void main(uint GI : SV_GroupIndex) { SBinaryUintOp l = g_buf[GI]; l.output1 = l.input1 %s l.input2; g_buf[GI] = l; };""", "binary uint16_t": """ struct SBinaryUint16Op { uint16_t input1; uint16_t input2; uint16_t output1; uint16_t output2; }; RWStructuredBuffer<SBinaryUint16Op> g_buf : register(u0); [numthreads(8,8,1)] void main(uint GI : SV_GroupIndex) { SBinaryUint16Op l = g_buf[GI]; l.output1 = l.input1 %s l.input2; g_buf[GI] = l; };""", "binary uint call": """ struct SBinaryUintOp { uint input1; uint input2; uint output1; uint output2; }; RWStructuredBuffer<SBinaryUintOp> g_buf : register(u0); [numthreads(8,8,1)] void main(uint GI : SV_GroupIndex) { SBinaryUintOp l = g_buf[GI]; l.output1 = %s(l.input1,l.input2); g_buf[GI] = l; };""", "binary uint16_t call": """ struct SBinaryUint16Op { uint16_t input1; uint16_t input2; uint16_t output1; uint16_t output2; }; RWStructuredBuffer<SBinaryUint16Op> g_buf : register(u0); [numthreads(8,8,1)] void main(uint GI : SV_GroupIndex) { SBinaryUint16Op l = g_buf[GI]; l.output1 = %s(l.input1,l.input2); g_buf[GI] = l; };""", "binary float": """ struct SBinaryFPOp { float input1; float input2; float output1; float output2; }; RWStructuredBuffer<SBinaryFPOp> g_buf : register(u0); [numthreads(8,8,1)] void main(uint GI : SV_GroupIndex) { SBinaryFPOp l = g_buf[GI]; l.output1 = l.input1 %s l.input2; g_buf[GI] = l; };""", "binary float call": """ struct SBinaryFPOp { float input1; float input2; float output1; float output2; }; RWStructuredBuffer<SBinaryFPOp> g_buf : register(u0); [numthreads(8,8,1)] void main(uint GI : SV_GroupIndex) { SBinaryFPOp l = g_buf[GI]; l.output1 = %s(l.input1,l.input2); g_buf[GI] = l; };""", "binary half": """ struct SBinaryFPOp { half input1; half input2; half output1; half output2; }; RWStructuredBuffer<SBinaryFPOp> g_buf : register(u0); [numthreads(8,8,1)] void main(uint GI : SV_GroupIndex) { SBinaryFPOp l = g_buf[GI]; l.output1 = l.input1 %s l.input2; g_buf[GI] = l; };""", "binary half call": """ struct SBinaryFPOp { half input1; half input2; half output1; half output2; }; RWStructuredBuffer<SBinaryFPOp> g_buf : register(u0); [numthreads(8,8,1)] void main(uint GI : SV_GroupIndex) { SBinaryFPOp l = g_buf[GI]; l.output1 = %s(l.input1,l.input2); g_buf[GI] = l; };""", "tertiary int": """ struct STertiaryIntOp { int input1; int input2; int input3; int output; }; RWStructuredBuffer<STertiaryIntOp> g_buf : register(u0); [numthreads(8,8,1)] void main(uint GI : SV_GroupIndex) { STertiaryIntOp l = g_buf[GI]; l.output = %s(l.input1, l.input2, l.input3); g_buf[GI] = l; };""", "tertiary int16_t": """ struct STertiaryInt16Op { int16_t input1; int16_t input2; int16_t input3; int16_t output; }; RWStructuredBuffer<STertiaryInt16Op> g_buf : register(u0); [numthreads(8,8,1)] void main(uint GI : SV_GroupIndex) { STertiaryInt16Op l = g_buf[GI]; l.output = %s(l.input1, l.input2, l.input3); g_buf[GI] = l; };""", "tertiary uint": """ struct STertiaryUintOp { uint input1; uint input2; uint input3; uint output; }; RWStructuredBuffer<STertiaryUintOp> g_buf : register(u0); [numthreads(8,8,1)] void main(uint GI : SV_GroupIndex) { STertiaryUintOp l = g_buf[GI]; l.output = %s(l.input1, l.input2, l.input3); g_buf[GI] = l; };""", "tertiary uint16_t": """ struct STertiaryUint16Op { uint16_t input1; uint16_t input2; uint16_t input3; uint16_t output; }; RWStructuredBuffer<STertiaryUint16Op> g_buf : register(u0); [numthreads(8,8,1)] void main(uint GI : SV_GroupIndex) { STertiaryUint16Op l = g_buf[GI]; l.output = %s(l.input1, l.input2, l.input3); g_buf[GI] = l; };""", "tertiary float": """ struct STertiaryFloatOp { float input1; float input2; float input3; float output; }; RWStructuredBuffer<STertiaryFloatOp> g_buf : register(u0); [numthreads(8,8,1)] void main(uint GI : SV_GroupIndex) { STertiaryFloatOp l = g_buf[GI]; l.output = %s(l.input1, l.input2, l.input3); g_buf[GI] = l; };""", "tertiary half": """ struct STertiaryHalfOp { half input1; half input2; half input3; half output; }; RWStructuredBuffer<STertiaryHalfOp> g_buf : register(u0); [numthreads(8,8,1)] void main(uint GI : SV_GroupIndex) { STertiaryHalfOp l = g_buf[GI]; l.output = %s(l.input1, l.input2, l.input3); g_buf[GI] = l; };""", "wave op int": """ struct PerThreadData { uint firstLaneId; uint laneIndex; int mask; int input; int output; }; RWStructuredBuffer<PerThreadData> g_sb : register(u0); [numthreads(8,12,1)] void main(uint GI : SV_GroupIndex) { PerThreadData pts = g_sb[GI]; pts.firstLaneId = WaveReadLaneFirst(GI); pts.laneIndex = WaveGetLaneIndex(); if (pts.mask != 0) { pts.output = %s(pts.input); } else { pts.output = %s(pts.input); } g_sb[GI] = pts; };""", "wave op uint": """ struct PerThreadData { uint firstLaneId; uint laneIndex; int mask; uint input; uint output; }; RWStructuredBuffer<PerThreadData> g_sb : register(u0); [numthreads(8,12,1)] void main(uint GI : SV_GroupIndex) { PerThreadData pts = g_sb[GI]; pts.firstLaneId = WaveReadLaneFirst(GI); pts.laneIndex = WaveGetLaneIndex(); if (pts.mask != 0) { pts.output = %s(pts.input); } else { pts.output = %s(pts.input); } g_sb[GI] = pts; };""", "wave op int count": """ struct PerThreadData { uint firstLaneId; uint laneIndex; int mask; int input; int output; }; RWStructuredBuffer<PerThreadData> g_sb : register(u0); [numthreads(8,12,1)] void main(uint GI : SV_GroupIndex) { PerThreadData pts = g_sb[GI]; pts.firstLaneId = WaveReadLaneFirst(GI); pts.laneIndex = WaveGetLaneIndex(); if (pts.mask != 0) { pts.output = %s(pts.input > 3); } else { pts.output = %s(pts.input > 3); } g_sb[GI] = pts; };""", "wave op multi prefix int": """ struct ThreadData { uint key; uint firstLaneId; uint laneId; uint mask; int value; int result; }; RWStructuredBuffer<ThreadData> g_buffer : register(u0); [numthreads(8, 12, 1)] void main(uint id : SV_GroupIndex) { ThreadData data = g_buffer[id]; data.firstLaneId = WaveReadLaneFirst(id); data.laneId = WaveGetLaneIndex(); if (data.mask != 0) { uint4 mask = WaveMatch(data.key); data.result = %s(data.value, mask); } else { uint4 mask = WaveMatch(data.key); data.result = %s(data.value, mask); } g_buffer[id] = data; }""", "wave op multi prefix uint": """ struct ThreadData { uint key; uint firstLaneId; uint laneId; uint mask; uint value; uint result; }; RWStructuredBuffer<ThreadData> g_buffer : register(u0); [numthreads(8, 12, 1)] void main(uint id : SV_GroupIndex) { ThreadData data = g_buffer[id]; data.firstLaneId = WaveReadLaneFirst(id); data.laneId = WaveGetLaneIndex(); if (data.mask != 0) { uint4 mask = WaveMatch(data.key); data.result = %s(data.value, mask); } else { uint4 mask = WaveMatch(data.key); data.result = %s(data.value, mask); } g_buffer[id] = data; }""", } def get_shader_text(op_type, op_call): assert op_type in g_shader_texts if op_type.startswith("wave op"): return g_shader_texts[op_type] % (op_call, op_call) return g_shader_texts[op_type] % (op_call) g_denorm_tests = [ "FAddDenormAny", "FAddDenormFTZ", "FAddDenormPreserve", "FSubDenormAny", "FSubDenormFTZ", "FSubDenormPreserve", "FMulDenormAny", "FMulDenormFTZ", "FMulDenormPreserve", "FDivDenormAny", "FDivDenormFTZ", "FDivDenormPreserve", "FMadDenormAny", "FMadDenormFTZ", "FMadDenormPreserve", "FAbsDenormAny", "FAbsDenormFTZ", "FAbsDenormPreserve", "FMinDenormAny", "FMinDenormFTZ", "FMinDenormPreserve", "FMaxDenormAny", "FMaxDenormFTZ", "FMaxDenormPreserve", ] # This is a collection of test case for driver tests per instruction # Warning: For test cases, when you want to pass in signed 32-bit integer, # make sure to pass in negative numbers with decimal values instead of hexadecimal representation. # For some reason, TAEF is not handling them properly. # For half values, hex is preferable since the test framework will read string as float values # and convert them to float16, possibly losing precision. The test will read hex values as it is. def add_test_cases(): nan = float("nan") p_inf = float("inf") n_inf = float("-inf") p_denorm = float("1e-38") n_denorm = float("-1e-38") # Unary Float add_test_case_float_half( "Sin", ["Sin"], "Epsilon", 0.0008, [["NaN", "-Inf", "-denorm", "-0", "0", "denorm", "Inf", "-314.16", "314.16"]], [["NaN", "NaN", "-0", "-0", "0", "0", "NaN", "-0.0007346401", "0.0007346401"]], "unary float", "sin", half_validation_tolerance=0.003, half_inputs=[ [ "NaN", "-Inf", "-denorm", "-0", "0", "denorm", "Inf", "0.6279297", "1.255859", "1.884766", "2.511719", "3.140625", "3.769531", "4.398438", "5.023438", "5.652344", "6.281250", ] ], half_outputs=[ [ "NaN", "NaN", "-0", "-0", "0", "0", "NaN", "0.58747065", "0.95081574", "0.95111507", "0.58904284", "0.00096773", "-0.58747751", "-0.95112079", "-0.95201313", "-0.58982444", "-0.00193545", ] ], ) add_test_case_float_half( "Cos", ["Cos"], "Epsilon", 0.0008, [["NaN", "-Inf", "-denorm", "-0", "0", "denorm", "Inf", "-314.16", "314.16"]], [ [ "NaN", "NaN", "1.0", "1.0", "1.0", "1.0", "NaN", "0.99999973015", "0.99999973015", ] ], "unary float", "cos", half_validation_tolerance=0.003, half_inputs=[ [ "NaN", "-Inf", "-denorm", "-0", "0", "denorm", "Inf", "0.6279297", "1.255859", "1.884766", "2.511719", "3.140625", "3.769531", "4.398438", "5.023438", "5.652344", "6.281250", ] ], half_outputs=[ [ "NaN", "NaN", "1.0", "1.0", "1.0", "1.0", "NaN", "0.80924553", "0.30975693", "-0.30883664", "-0.80810183", "-0.99999952", "-0.80924052", "-0.30881903", "0.30605716", "0.80753154", "0.99999809", ] ], ) add_test_case_float_half( "Tan", ["Tan"], "Epsilon", 0.0008, [["NaN", "-Inf", "-denorm", "-0", "0", "denorm", "Inf", "-314.16", "314.16"]], [["NaN", "NaN", "-0.0", "-0.0", "0.0", "0.0", "NaN", "-0.000735", "0.000735"]], "unary float", "tan", half_validation_tolerance=0.016, half_inputs=[ [ "NaN", "-Inf", "-denorm", "-0", "0", "denorm", "Inf", "0.6279297", "1.255859", "1.884766", "2.511719", "3.140625", "3.769531", "4.398438", "5.652344", "6.281250", ] ], half_outputs=[ [ "NaN", "NaN", "-0", "-0", "0", "0", "NaN", "0.72594857", "3.06955433", "-3.07967043", "-0.72892153", "-0.00096773", "0.72596157", "3.07986474", "-0.7304042", "-0.00193546", ] ], ) add_test_case_float_half( "Hcos", ["Hcos"], "Epsilon", 0.0008, [["NaN", "-Inf", "-denorm", "-0", "0", "denorm", "Inf", "1", "-1"]], [["NaN", "Inf", "1.0", "1.0", "1.0", "1.0", "Inf", "1.543081", "1.543081"]], "unary float", "cosh", half_validation_type="ulp", half_validation_tolerance=2, ) add_test_case_float_half( "Hsin", ["Hsin"], "Epsilon", 0.0008, [["NaN", "-Inf", "-denorm", "-0", "0", "denorm", "Inf", "1", "-1"]], [["NaN", "-Inf", "0.0", "0.0", "0.0", "0.0", "Inf", "1.175201", "-1.175201"]], "unary float", "sinh", ) add_test_case_float_half( "Htan", ["Htan"], "Epsilon", 0.0008, [["NaN", "-Inf", "-denorm", "-0", "0", "denorm", "Inf", "1", "-1"]], [["NaN", "-1", "-0.0", "-0.0", "0.0", "0.0", "1", "0.761594", "-0.761594"]], "unary float", "tanh", warp_version=16202, ) add_test_case_float_half( "Acos", ["Acos"], "Epsilon", 0.0008, [ [ "NaN", "-Inf", "-denorm", "-0", "0", "denorm", "Inf", "1", "-1", "1.5", "-1.5", ] ], [ [ "NaN", "NaN", "1.570796", "1.570796", "1.570796", "1.570796", "NaN", "0", "3.1415926", "NaN", "NaN", ] ], "unary float", "acos", ) add_test_case_float_half( "Asin", ["Asin"], "Epsilon", 0.0008, [ [ "NaN", "-Inf", "-denorm", "-0", "0", "denorm", "Inf", "1", "-1", "1.5", "-1.5", ] ], [ [ "NaN", "NaN", "0.0", "0.0", "0.0", "0.0", "NaN", "1.570796", "-1.570796", "NaN", "NaN", ] ], "unary float", "asin", ) add_test_case_float_half( "Atan", ["Atan"], "Epsilon", 0.0008, [["NaN", "-Inf", "-denorm", "-0", "0", "denorm", "Inf", "1", "-1"]], [ [ "NaN", "-1.570796", "0.0", "0.0", "0.0", "0.0", "1.570796", "0.785398163", "-0.785398163", ] ], "unary float", "atan", warp_version=16202, ) add_test_case_float_half( "Exp", ["Exp"], "Relative", 21, [["NaN", "-Inf", "-denorm", "-0", "0", "denorm", "Inf", "-1", "10"]], [["NaN", "0", "1", "1", "1", "1", "Inf", "0.367879441", "22026.46579"]], "unary float", "exp", ) add_test_case_float_half( "Frc", ["Frc"], "Epsilon", 0.0008, [ [ "NaN", "-Inf", "-denorm", "-0", "0", "denorm", "Inf", "-1", "2.718280", "1000.599976", "-7.389", ] ], [ [ "NaN", "NaN", "0", "0", "0", "0", "NaN", "0", "0.718280", "0.599976", "0.611", ] ], "unary float", "frac", half_inputs=[ [ "NaN", "-Inf", "0x03FF", "-0", "0", "Inf", "-1", "2.719", "1000.5", "0xC764", ] ], half_outputs=[ ["NaN", "NaN", "0x03FF", "0", "0", "NaN", "0", "0.719", "0.5", "0x38E1"] ], ) add_test_case_float_half( "Log", ["Log"], "Relative", 21, [ [ "NaN", "-Inf", "-denorm", "-0", "0", "denorm", "Inf", "-1", "2.718281828", "7.389056", "100", ] ], [ [ "NaN", "NaN", "-Inf", "-Inf", "-Inf", "-Inf", "Inf", "NaN", "1.0", "1.99999998", "4.6051701", ] ], "unary float", "log", half_inputs=[ [ "NaN", "-Inf", "-denorm", "-0", "0", "denorm", "Inf", "-1", "2.719", "7.39", "100", ] ], half_outputs=[ [ "NaN", "NaN", "-Inf", "-Inf", "-Inf", "-Inf", "Inf", "NaN", "1.0", "2", "4.605", ] ], ) add_test_case_float_half( "Sqrt", ["Sqrt"], "ulp", 1, [ [ "NaN", "-Inf", "-denorm", "-0", "0", "denorm", "Inf", "-1", "2", "16.0", "256.0", ] ], [ [ "NaN", "NaN", "-0", "-0", "0", "0", "Inf", "NaN", "1.41421356237", "4.0", "16.0", ] ], "unary float", "sqrt", half_inputs=[ [ "NaN", "-Inf", "-denorm", "-0", "0", "0x03FF", "Inf", "-1", "2", "16.0", "256.0", ] ], half_outputs=[ [ "NaN", "NaN", "NaN", "-0", "0", "0x1FFF", "Inf", "NaN", "1.41421", "4.0", "16.0", ] ], ) add_test_case_float_half( "Rsqrt", ["Rsqrt"], "ulp", 1, [ [ "NaN", "-Inf", "-denorm", "-0", "0", "denorm", "Inf", "-1", "16.0", "256.0", "65536.0", ] ], [ [ "NaN", "NaN", "-Inf", "-Inf", "Inf", "Inf", "0", "NaN", "0.25", "0.0625", "0.00390625", ] ], "unary float", "rsqrt", half_inputs=[ [ "NaN", "-Inf", "-denorm", "-0", "0", "0x03FF", "Inf", "-1", "16.0", "256.0", "0x7bff", ] ], half_outputs=[ [ "NaN", "NaN", "NaN", "-Inf", "Inf", "0x5801", "0", "NaN", "0.25", "0.0625", "0x1C00", ] ], ) add_test_case_float_half( "Round_ne", ["Round_ne"], "Epsilon", 0, [ [ "NaN", "-Inf", "-denorm", "-0", "0", "denorm", "Inf", "10.0", "10.4", "10.5", "10.6", "11.5", "-10.0", "-10.4", "-10.5", "-10.6", ] ], [ [ "NaN", "-Inf", "-0", "-0", "0", "0", "Inf", "10.0", "10.0", "10.0", "11.0", "12.0", "-10.0", "-10.0", "-10.0", "-11.0", ] ], "unary float", "round", ) add_test_case_float_half( "Round_ni", ["Round_ni"], "Epsilon", 0, [ [ "NaN", "-Inf", "-denorm", "-0", "0", "denorm", "Inf", "10.0", "10.4", "10.5", "10.6", "-10.0", "-10.4", "-10.5", "-10.6", ] ], [ [ "NaN", "-Inf", "-0", "-0", "0", "0", "Inf", "10.0", "10.0", "10.0", "10.0", "-10.0", "-11.0", "-11.0", "-11.0", ] ], "unary float", "floor", half_inputs=[ [ "NaN", "-Inf", "-denorm", "-0", "0", "denorm", "Inf", "10.0", "10.4", "10.5", "10.6", "-10.0", "-10.4", "-10.5", "-10.6", ] ], half_outputs=[ [ "NaN", "-Inf", "-1", "-0", "0", "0", "Inf", "10.0", "10.0", "10.0", "10.0", "-10.0", "-11.0", "-11.0", "-11.0", ] ], ) add_test_case_float_half( "Round_pi", ["Round_pi"], "Epsilon", 0, [ [ "NaN", "-Inf", "-denorm", "-0", "0", "denorm", "Inf", "10.0", "10.4", "10.5", "10.6", "-10.0", "-10.4", "-10.5", "-10.6", ] ], [ [ "NaN", "-Inf", "-0", "-0", "0", "0", "Inf", "10.0", "11.0", "11.0", "11.0", "-10.0", "-10.0", "-10.0", "-10.0", ] ], "unary float", "ceil", half_inputs=[ [ "NaN", "-Inf", "-denorm", "-0", "0", "denorm", "Inf", "10.0", "10.4", "10.5", "10.6", "-10.0", "-10.4", "-10.5", "-10.6", ] ], half_outputs=[ [ "NaN", "-Inf", "-0", "-0", "0", "1", "Inf", "10.0", "11.0", "11.0", "11.0", "-10.0", "-10.0", "-10.0", "-10.0", ] ], ) add_test_case_float_half( "Round_z", ["Round_z"], "Epsilon", 0, [ [ "NaN", "-Inf", "-denorm", "-0", "0", "denorm", "Inf", "10.0", "10.4", "10.5", "10.6", "-10.0", "-10.4", "-10.5", "-10.6", ] ], [ [ "NaN", "-Inf", "-0", "-0", "0", "0", "Inf", "10.0", "10.0", "10.0", "10.0", "-10.0", "-10.0", "-10.0", "-10.0", ] ], "unary float", "trunc", ) add_test_case_float_half( "IsNaN", ["IsNaN"], "Epsilon", 0, [["NaN", "-Inf", "-denorm", "-0", "0", "denorm", "Inf", "1.0", "-1.0"]], [["1", "0", "0", "0", "0", "0", "0", "0", "0"]], "unary float bool", "isnan", ) add_test_case_float_half( "IsInf", ["IsInf"], "Epsilon", 0, [["NaN", "-Inf", "-denorm", "-0", "0", "denorm", "Inf", "1.0", "-1.0"]], [["0", "1", "0", "0", "0", "0", "1", "0", "0"]], "unary float bool", "isinf", ) add_test_case_float_half( "IsFinite", ["IsFinite"], "Epsilon", 0, [["NaN", "-Inf", "-denorm", "-0", "0", "denorm", "Inf", "1.0", "-1.0"]], [["0", "0", "1", "1", "1", "1", "0", "1", "1"]], "unary float bool", "isfinite", warp_version=16202, ) add_test_case_float_half( "FAbs", ["FAbs"], "Epsilon", 0, [["NaN", "-Inf", "-denorm", "-0", "0", "denorm", "Inf", "1.0", "-1.0"]], [["NaN", "Inf", "denorm", "0", "0", "denorm", "Inf", "1", "1"]], "unary float", "abs", ) # Binary Float add_test_case( "FMin", ["FMin", "FMax"], "epsilon", 0, [ [ "-inf", "-inf", "-inf", "-inf", "inf", "inf", "inf", "inf", "NaN", "NaN", "NaN", "NaN", "1.0", "1.0", "-1.0", "-1.0", "1.0", ], [ "-inf", "inf", "1.0", "NaN", "-inf", "inf", "1.0", "NaN", "-inf", "inf", "1.0", "NaN", "-inf", "inf", "1.0", "NaN", "-1.0", ], ], [ [ "-inf", "-inf", "-inf", "-inf", "-inf", "inf", "1.0", "inf", "-inf", "inf", "1.0", "NaN", "-inf", "1.0", "-1.0", "-1.0", "-1.0", ], [ "-inf", "inf", "1.0", "-inf", "inf", "inf", "inf", "inf", "-inf", "inf", "1.0", "NaN", "1.0", "inf", "1.0", "-1.0", "1.0", ], ], "cs_6_0", """ struct SBinaryFPOp { float input1; float input2; float output1; float output2; }; RWStructuredBuffer<SBinaryFPOp> g_buf : register(u0); [numthreads(8,8,1)] void main(uint GI : SV_GroupIndex) { SBinaryFPOp l = g_buf[GI]; l.output1 = min(l.input1, l.input2); l.output2 = max(l.input1, l.input2); g_buf[GI] = l; };""", ) add_test_case( "FMinHalf", ["FMin", "FMax"], "epsilon", 0, [ [ "-inf", "-inf", "-inf", "-inf", "inf", "inf", "inf", "inf", "NaN", "NaN", "NaN", "NaN", "1.0", "1.0", "-1.0", "-1.0", "1.0", ], [ "-inf", "inf", "1.0", "NaN", "-inf", "inf", "1.0", "NaN", "-inf", "inf", "1.0", "NaN", "-inf", "inf", "1.0", "NaN", "-1.0", ], ], [ [ "-inf", "-inf", "-inf", "-inf", "-inf", "inf", "1.0", "inf", "-inf", "inf", "1.0", "NaN", "-inf", "1.0", "-1.0", "-1.0", "-1.0", ], [ "-inf", "inf", "1.0", "-inf", "inf", "inf", "inf", "inf", "-inf", "inf", "1.0", "NaN", "1.0", "inf", "1.0", "-1.0", "1.0", ], ], "cs_6_2", """ struct SBinaryHalfOp { half input1; half input2; half output1; half output2; }; RWStructuredBuffer<SBinaryHalfOp> g_buf : register(u0); [numthreads(8,8,1)] void main(uint GI : SV_GroupIndex) { SBinaryHalfOp l = g_buf[GI]; l.output1 = min(l.input1, l.input2); l.output2 = max(l.input1, l.input2); g_buf[GI] = l; };""", shader_arguments="-enable-16bit-types", ) add_test_case_float_half( "FAdd", ["FAdd"], "ulp", 1, [ ["-1.0", "1.0", "32.5", "1.0000001000"], ["4", "5.5", "334.7", "0.5000001000"], ], [["3.0", "6.5", "367.2", "1.5000002000"]], "binary float", "+", ) add_test_case_float_half( "FSub", ["FSub"], "ulp", 1, [ ["-1.0", "5.5", "32.5", "1.0000001000"], ["4", "1.25", "334.7", "0.5000001000"], ], [["-5", "4.25", "-302.2", "0.5000"]], "binary float", "-", ) add_test_case_float_half( "FMul", ["FMul"], "ulp", 1, [["-1.0", "5.5", "1.0000001"], ["4", "1.25", "2.0"]], [["-4.0", "6.875", "2.0000002"]], "binary float", "*", ) add_test_case_float_half( "FDiv", ["FDiv"], "ulp", 1, [["-1.0", "5.5", "1.0000001"], ["4", "1.25", "2.0"]], [["-0.25", "4.4", "0.50000006"]], "binary float", "/", ) # Denorm Binary Float add_test_case_denorm( "FAddDenorm", ["FAdd"], "ulp", 1, [ ["0x007E0000", "0x00200000", "0x007E0000", "0x007E0000"], ["0x007E0000", "0x00200000", "0x807E0000", "0x800E0000"], ], [["0", "0", "0", "0"]], [["0x00FC0000", "0x00400000", "0", "0x00700000"]], "cs_6_2", get_shader_text("binary float", "+"), ) add_test_case_denorm( "FSubDenorm", ["FSub"], "ulp", 1, [ ["0x007E0000", "0x007F0000", "0x00FF0000", "0x007A0000"], ["0x007E0000", "0x807F0000", "0x00800000", "0"], ], [["0x0", "0", "0", "0"]], [["0x0", "0x00FE0000", "0x007F0000", "0x007A0000"]], "cs_6_2", get_shader_text("binary float", "-"), ) add_test_case_denorm( "FDivDenorm", ["FDiv"], "ulp", 1, [ ["0x007F0000", "0x807F0000", "0x20000000", "0x00800000"], ["1", "4", "0x607F0000", "0x40000000"], ], [["0", "0", "0", "0"]], [["0x007F0000", "0x801FC000", "0x00101010", "0x00400000"]], "cs_6_2", get_shader_text("binary float", "/"), ) add_test_case_denorm( "FMulDenorm", ["FMul"], "ulp", 1, [ ["0x00000300", "0x007F0000", "0x007F0000", "0x001E0000", "0x00000300"], ["128", "1", "0x007F0000", "20", "0x78000000"], ], [["0", "0", "0", "0", "0"]], [["0x00018000", "0x007F0000", "0", "0x01960000", "0x32400000"]], "cs_6_2", get_shader_text("binary float", "*"), ) # Tertiary Float add_test_case_float_half( "FMad", ["FMad"], "ulp", 1, [ [ "NaN", "-Inf", "-denorm", "-0", "0", "denorm", "Inf", "1.0", "-1.0", "0", "1", "1.5", ], [ "NaN", "-Inf", "-denorm", "-0", "0", "denorm", "Inf", "1.0", "-1.0", "0", "1", "10", ], [ "NaN", "-Inf", "-denorm", "-0", "0", "denorm", "Inf", "1.0", "-1.0", "1", "0", "-5.5", ], ], [["NaN", "NaN", "0", "0", "0", "0", "Inf", "2", "0", "1", "1", "9.5"]], "tertiary float", "mad", half_inputs=[ ["NaN", "-Inf", "0x03FF", "-0", "0", "Inf", "1.0", "-1.0", "0", "1", "1.5"], ["NaN", "-Inf", "1", "-0", "0", "Inf", "1.0", "-1.0", "0", "1", "10"], [ "NaN", "-Inf", "0x03FF", "-0", "0", "Inf", "1.0", "-1.0", "1", "0", "-5.5", ], ], half_outputs=[ ["NaN", "NaN", "0x07FE", "0", "0", "Inf", "2", "0", "1", "1", "9.5"] ], ) # Denorm Tertiary Float add_test_case_denorm( "FMadDenorm", ["FMad"], "ulp", 1, [ ["0x80780000", "0x80780000", "0x00780000"], ["1", "2", "2"], ["0x80780000", "0x00800000", "0x00800000"], ], [["0", "0x00800000", "0x00800000"]], [["0x80F00000", "0x80700000", "0x01380000"]], "cs_6_2", get_shader_text("tertiary float", "mad"), ) # Unary Int int8_min, int8_max = "-128", "127" int16_min, int16_max = "-32768", "32767" int32_min, int32_max = "-2147483648", "2147483647" uint16_max = "65535" uint32_max = "4294967295" add_test_case_int( "Bfrev", ["Bfrev"], "Epsilon", 0, [[int32_min, "-65536", "-8", "-1", "0", "1", "8", "65536", int32_max]], [["1", "65535", "536870911", "-1", "0", int32_min, "268435456", "32768", "-2"]], "unary int", "reversebits", input_16=[[int16_min, "-256", "-8", "-1", "0", "1", "8", "256", int16_max]], output_16=[["1", "255", "8191", "-1", "0", int16_min, "4096", "128", "-2"]], ) # firstbit_shi (s for signed) returns the # first 0 from the MSB if the number is negative, # else the first 1 from the MSB. # all the variants of the instruction return ~0 if no match was found add_test_case_int( "FirstbitSHi", ["FirstbitSHi"], "Epsilon", 0, [[int32_min, "-65536", "-8", "-1", "0", "1", "8", "65536", int32_max]], [["30", "15", "2", "-1", "-1", "0", "3", "16", "30"]], "unary int", "firstbithigh", input_16=[[int16_min, "-256", "-8", "-1", "0", "1", "8", "256", int16_max]], output_16=[["14", "7", "2", "-1", "-1", "0", "3", "8", "14"]], ) add_test_case_int( "FirstbitLo", ["FirstbitLo"], "Epsilon", 0, [[int32_min, "-65536", "-8", "-1", "0", "1", "8", "65536", int32_max]], [["31", "16", "3", "0", "-1", "0", "3", "16", "0"]], "unary int", "firstbitlow", input_16=[[int16_min, "-256", "-8", "-1", "0", "1", "8", "256", int16_max]], output_16=[["15", "8", "3", "0", "-1", "0", "3", "8", "0"]], ) # TODO: there is a known bug in countbits when passing in immediate values. # Fix this later add_test_case( "Countbits", ["Countbits"], "Epsilon", 0, [[int32_min, "-65536", "-8", "-1", "0", "1", "8", "65536", int32_max]], [["1", "16", "29", "32", "0", "1", "1", "1", "31"]], "cs_6_0", get_shader_text("unary int", "countbits"), ) # Unary uint add_test_case_int( "FirstbitHi", ["FirstbitHi"], "Epsilon", 0, [["0", "1", "8", "65536", int32_max, uint32_max]], [["-1", "0", "3", "16", "30", "31"]], "unary uint", "firstbithigh", input_16=[["0", "1", "8", uint16_max]], output_16=[["-1", "0", "3", "15"]], ) # Binary Int add_test_case_int( "IAdd", ["Add"], "Epsilon", 0, [ [int32_min, "-10", "0", "0", "10", int32_max, "486"], ["0", "10", "-10", "10", "10", "0", "54238"], ], [[int32_min, "0", "-10", "10", "20", int32_max, "54724"]], "binary int", "+", input_16=[ [int16_min, "-10", "0", "0", "10", int16_max], ["0", "10", "-3114", "272", "15", "0"], ], output_16=[[int16_min, "0", "-3114", "272", "25", int16_max]], ) add_test_case_int( "ISub", ["Sub"], "Epsilon", 0, [ [int32_min, "-10", "0", "0", "10", int32_max, "486"], ["0", "10", "-10", "10", "10", "0", "54238"], ], [[int32_min, "-20", "10", "-10", "0", int32_max, "-53752"]], "binary int", "-", input_16=[ [int16_min, "-10", "0", "0", "10", int16_max], ["0", "10", "-3114", "272", "15", "0"], ], output_16=[[int16_min, "-20", "3114", "-272", "-5", int16_max]], ) add_test_case_int( "IMax", ["IMax"], "Epsilon", 0, [ [int32_min, "-10", "0", "0", "10", int32_max], ["0", "10", "-10", "10", "10", "0"], ], [["0", "10", "0", "10", "10", int32_max]], "binary int call", "max", input_16=[ [int16_min, "-10", "0", "0", "10", int16_max], ["0", "10", "-3114", "272", "15", "0"], ], output_16=[["0", "10", "0", "272", "15", int16_max]], ) add_test_case_int( "IMin", ["IMin"], "Epsilon", 0, [ [int32_min, "-10", "0", "0", "10", int32_max], ["0", "10", "-10", "10", "10", "0"], ], [[int32_min, "-10", "-10", "0", "10", "0"]], "binary int call", "min", input_16=[ [int16_min, "-10", "0", "0", "10", int16_max], ["0", "10", "-3114", "272", "15", "0"], ], output_16=[[int16_min, "-10", "-3114", "0", "10", "0"]], ) add_test_case_int( "IMul", ["Mul"], "Epsilon", 0, [ [int32_min, "-10", "-1", "0", "1", "10", "10000", int32_max, int32_max], ["-10", "-10", "10", "0", "256", "4", "10001", "0", int32_max], ], [["0", "100", "-10", "0", "256", "40", "100010000", "0", "1"]], "binary int", "*", input_16=[ [int16_min, "-10", "-1", "0", "1", "10", int16_max], ["-10", "-10", "10", "0", "256", "4", "0"], ], output_16=[["0", "100", "-10", "0", "256", "40", "0"]], ) add_test_case( "IDiv", ["SDiv", "SRem"], "Epsilon", 0, [ ["1", "1", "10", "10000", int32_max, int32_max, "-1"], ["1", "256", "4", "10001", "2", int32_max, "1"], ], [ ["1", "0", "2", "0", "1073741823", "1", "-1"], ["0", "1", "2", "10000", "1", "0", "0"], ], "cs_6_0", """ struct SBinaryIntOp { int input1; int input2; int output1; int output2; }; RWStructuredBuffer<SBinaryIntOp> g_buf : register(u0); [numthreads(8,8,1)] void main(uint GI : SV_GroupIndex) { SBinaryIntOp l = g_buf[GI]; l.output1 = l.input1 / l.input2; l.output2 = l.input1 % l.input2; g_buf[GI] = l; };""", ) add_test_case_int( "Shl", ["Shl"], "Epsilon", 0, [ ["1", "1", "0x1010", "0xa", "-1", "0x12341234", "-1"], ["0", "259", "4", "2", "0", "15", "3"], ], [["0x1", "0x8", "0x10100", "0x28", "-1", "0x091a0000", "-8"]], "binary int", "<<", input_16=[ ["1", "1", "0x0101", "0xa", "-1", "0x1234", "-1"], ["0", "259", "4", "2", "0", "13", "3"], ], output_16=[["0x1", "0x8", "0x1010", "0x28", "-1", "0x8000", "-8"]], ) add_test_case_int( "LShr", ["LShr"], "Epsilon", 0, [ [ "1", "1", "0xffff", "0x7fffffff", "0x70001234", "0x12340ab3", "0x7fffffff", ], ["0", "1", "4", "30", "15", "16", "1"], ], [["1", "0", "0xfff", "1", "0xe000", "0x1234", "0x3fffffff"]], "binary int", ">>", input_16=[["1", "1", "0x7fff", "0x7fff"], ["0", "1", "4", "14"]], output_16=[["1", "0", "0x07ff", "1"]], ) add_test_case_int( "And", ["And"], "Epsilon", 0, [ [ "0x1", "0x01", "0x7fff0000", "0x33333333", "0x137f", "0x12345678", "0xa341", "-1", ], ["0x1", "0xf0", "0x0000ffff", "0x22222222", "0xec80", "-1", "0x3471", "-1"], ], [["0x1", "0x00", "0x0", "0x22222222", "0x0", "0x12345678", "0x2041", "-1"]], "binary int", "&", input_16=[ ["0x1", "0x01", "0x7fff", "0x3333", "0x137f", "0x1234", "0xa341", "-1"], ["0x1", "0xf0", "0x0000", "0x2222", "0xec80", "-1", "0x3471", "-1"], ], output_16=[["0x1", "0x00", "0x0", "0x2222", "0x0", "0x1234", "0x2041", "-1"]], ) add_test_case_int( "Or", ["Or"], "Epsilon", 0, [ [ "0x1", "0x01", "0x7fff0000", "0x11111111", "0x137f", "0x0", "0x12345678", "0xa341", "-1", ], [ "0x1", "0xf0", "0x0000ffff", "0x22222222", "0xec80", "0x0", "0x00000000", "0x3471", "-1", ], ], [ [ "0x1", "0xf1", "0x7fffffff", "0x33333333", "0xffff", "0x0", "0x12345678", "0xb771", "-1", ] ], "binary int", "|", input_16=[ ["0x1", "0x01", "0x7fff", "0x3333", "0x137f", "0x1234", "0xa341", "-1"], ["0x1", "0xf0", "0x0000", "0x2222", "0xec80", "0xffff", "0x3471", "-1"], ], output_16=[ ["0x1", "0xf1", "0x7fff", "0x3333", "0xffff", "0xffff", "0xb771", "-1"] ], ) add_test_case_int( "Xor", ["Xor"], "Epsilon", 0, [ [ "0x1", "0x01", "0x7fff0000", "0x11111111", "0x137f", "0x0", "0x12345678", "0xa341", "-1", ], [ "0x1", "0xf0", "0x0000ffff", "0x22222222", "0xec80", "0x0", "0x00000000", "0x3471", "-1", ], ], [ [ "0x0", "0xf1", "0x7fffffff", "0x33333333", "0xffff", "0x0", "0x12345678", "0x9730", "0x00000000", ] ], "binary int", "^", input_16=[ [ "0x1", "0x01", "0x7fff", "0x1111", "0x137f", "0x0", "0x1234", "0xa341", "-1", ], [ "0x1", "0xf0", "0x0000", "0x2222", "0xec80", "0x0", "0x0000", "0x3471", "-1", ], ], output_16=[ [ "0x0", "0xf1", "0x7fff", "0x3333", "0xffff", "0x0", "0x1234", "0x9730", "0x0000", ] ], ) # Binary Uint add_test_case_int( "UAdd", ["Add"], "Epsilon", 0, [ ["2147483648", "4294967285", "0", "0", "10", int32_max, "486"], ["0", "10", "0", "10", "10", "0", "54238"], ], [["2147483648", uint32_max, "0", "10", "20", int32_max, "54724"]], "binary uint", "+", input_16=[ ["323", "0xfff5", "0", "0", "10", uint16_max, "486"], ["0", "10", "0", "10", "10", "0", "334"], ], output_16=[["323", uint16_max, "0", "10", "20", uint16_max, "820"]], ) add_test_case_int( "USub", ["Sub"], "Epsilon", 0, [ ["2147483648", uint32_max, "0", "0", "30", int32_max, "54724"], ["0", "10", "0", "10", "10", "0", "54238"], ], [["2147483648", "4294967285", "0", "4294967286", "20", int32_max, "486"]], "binary uint", "-", input_16=[ ["323", uint16_max, "0", "0", "10", uint16_max, "486"], ["0", "10", "0", "10", "10", "0", "334"], ], output_16=[["323", "0xfff5", "0", "-10", "0", uint16_max, "152"]], ) add_test_case_int( "UMax", ["UMax"], "Epsilon", 0, [ ["0", "0", "10", "10000", int32_max, uint32_max], ["0", "256", "4", "10001", "0", uint32_max], ], [["0", "256", "10", "10001", int32_max, uint32_max]], "binary uint call", "max", input_16=[ ["0", "0", "10", "10000", int16_max, uint16_max], ["0", "256", "4", "10001", "0", uint16_max], ], output_16=[["0", "256", "10", "10001", int16_max, uint16_max]], ) add_test_case_int( "UMin", ["UMin"], "Epsilon", 0, [ ["0", "0", "10", "10000", int32_max, uint32_max], ["0", "256", "4", "10001", "0", uint32_max], ], [["0", "0", "4", "10000", "0", uint32_max]], "binary uint call", "min", input_16=[ ["0", "0", "10", "10000", int16_max, uint16_max], ["0", "256", "4", "10001", "0", uint16_max], ], output_16=[["0", "0", "4", "10000", "0", uint16_max]], ) add_test_case_int( "UMul", ["Mul"], "Epsilon", 0, [["0", "1", "10", "10000", int32_max], ["0", "256", "4", "10001", "0"]], [["0", "256", "40", "100010000", "0"]], "binary uint", "*", input_16=[["0", "0", "10", "100", int16_max], ["0", "256", "4", "101", "0"]], output_16=[["0", "0", "40", "10100", "0"]], ) add_test_case( "UDiv", ["UDiv", "URem"], "Epsilon", 0, [ ["1", "1", "10", "10000", int32_max, int32_max, "0xffffffff"], ["0", "256", "4", "10001", "0", int32_max, "1"], ], [ ["0xffffffff", "0", "2", "0", "0xffffffff", "1", "0xffffffff"], ["0xffffffff", "1", "2", "10000", "0xffffffff", "0", "0"], ], "cs_6_0", """ struct SBinaryUintOp { uint input1; uint input2; uint output1; uint output2; }; RWStructuredBuffer<SBinaryUintOp> g_buf : register(u0); [numthreads(8,8,1)] void main(uint GI : SV_GroupIndex) { SBinaryUintOp l = g_buf[GI]; l.output1 = l.input1 / l.input2; l.output2 = l.input1 % l.input2; g_buf[GI] = l; };""", ) add_test_case( "UAddc", ["UAddc"], "Epsilon", 0, [ ["1", "1", "10000", "0x80000000", "0x7fffffff", "0xffffffff"], ["0", "256", "10001", "1", "0x7fffffff", "0x7fffffff"], ], [ ["2", "2", "20000", "0", "0xfffffffe", "0xfffffffe"], ["0", "512", "20002", "3", "0xfffffffe", "0xffffffff"], ], "cs_6_0", """ struct SBinaryUintOp { uint input1; uint input2; uint output1; uint output2; }; RWStructuredBuffer<SBinaryUintOp> g_buf : register(u0); [numthreads(8,8,1)] void main(uint GI : SV_GroupIndex) { SBinaryUintOp l = g_buf[GI]; uint2 x = uint2(l.input1, l.input2); uint2 y = AddUint64(x, x); l.output1 = y.x; l.output2 = y.y; g_buf[GI] = l; };""", ) # Tertiary Int add_test_case_int( "IMad", ["IMad"], "epsilon", 0, [ [ "-2147483647", "-256", "-1", "0", "1", "2", "16", int32_max, "1", "-1", "1", "10", ], ["1", "-256", "-1", "0", "1", "3", "16", "0", "1", "-1", "10", "100"], [ "0", "0", "0", "0", "1", "3", "1", "255", "2147483646", "-2147483647", "-10", "-2000", ], ], [ [ "-2147483647", "65536", "1", "0", "2", "9", "257", "255", int32_max, "-2147483646", "0", "-1000", ] ], "tertiary int", "mad", input_16=[ [int16_min, "-256", "-1", "0", "1", "2", "16", int16_max], ["1", "8", "-1", "0", "1", "3", "16", "1"], ["0", "0", "1", "3", "250", "-30", int16_min, "-50"], ], output_16=[[int16_min, "-2048", "2", "3", "251", "-24", "-32512", "32717"]], ) add_test_case_int( "UMad", ["UMad"], "epsilon", 0, [ ["0", "1", "2", "16", int32_max, "0", "10"], ["0", "1", "2", "16", "1", "0", "10"], ["0", "0", "1", "15", "0", "10", "10"], ], [["0", "1", "5", "271", int32_max, "10", "110"]], "tertiary uint", "mad", input_16=[ ["0", "1", "2", "16", int16_max, "0", "10"], ["0", "1", "2", "16", "1", "0", "10"], ["0", "0", "1", "15", "0", "10", "10"], ], output_16=[["0", "1", "5", "271", int16_max, "10", "110"]], ) # Dot add_test_case( "Dot", ["Dot2", "Dot3", "Dot4"], "epsilon", 0.008, [ [ "NaN,NaN,NaN,NaN", "-Inf,-Inf,-Inf,-Inf", "-denorm,-denorm,-denorm,-denorm", "-0,-0,-0,-0", "0,0,0,0", "denorm,denorm,denorm,denorm", "Inf,Inf,Inf,Inf", "1,1,1,1", "-10,0,0,10", "Inf,Inf,Inf,-Inf", ], [ "NaN,NaN,NaN,NaN", "-Inf,-Inf,-Inf,-Inf", "-denorm,-denorm,-denorm,-denorm", "-0,-0,-0,-0", "0,0,0,0", "denorm,denorm,denorm,denorm", "Inf,Inf,Inf,Inf", "1,1,1,1", "10,0,0,10", "Inf,Inf,Inf,Inf", ], ], [ [nan, p_inf, 0, 0, 0, 0, p_inf, 2, -100, p_inf], [nan, p_inf, 0, 0, 0, 0, p_inf, 3, -100, p_inf], [nan, p_inf, 0, 0, 0, 0, p_inf, 4, 0, nan], ], "cs_6_0", """ struct SDotOp { float4 input1; float4 input2; float o_dot2; float o_dot3; float o_dot4; }; RWStructuredBuffer<SDotOp> g_buf : register(u0); [numthreads(8,8,1)] void main(uint GI : SV_GroupIndex) { SDotOp l = g_buf[GI]; l.o_dot2 = dot(l.input1.xy, l.input2.xy); l.o_dot3 = dot(l.input1.xyz, l.input2.xyz); l.o_dot4 = dot(l.input1.xyzw, l.input2.xyzw); g_buf[GI] = l; };""", ) # Dot2AddHalf add_test_case( "Dot2AddHalf", ["Dot2AddHalf"], "epsilon", 0.008, [ [ "1,2", "1,-2", "1,2", "-1,2", "1,2", "-1,2", "1,2", "-1,-2", "65504,1", "-65504,1", "1,65504", "1,-65504", "inf,inf", "denorm,denorm", "-denorm,-denorm", "nan,nan", ], [ "3,4", "-3,4", "3,4", "3,-4", "3,4", "-3,4", "3,4", "-3,-4", "1,65504", "1,-65504", "65504,1", "-65504,1", "inf,inf", "denorm,denorm", "-denorm,-denorm", "nan,nan", ], [ "0", "0", "10", "10", "-5", "-5", "-30", "-30", "0", "0", "10000000", "-10000000", "inf", "denorm", "-denorm", "nan", ], ], [ [ 11, -11, 21, -1, 6, 6, -19, -19, 131008, -131008, 10131008, -10131008, p_inf, 0, 0, nan, ], ], "cs_6_4", """ struct SDot2AddHalfOp { half2 input1; half2 input2; float acc; float result; }; RWStructuredBuffer<SDot2AddHalfOp> g_buf : register(u0); [numthreads(8,8,1)] void main(uint GI : SV_GroupIndex) { SDot2AddHalfOp l = g_buf[GI]; l.result = dot2add(l.input1, l.input2, l.acc); g_buf[GI] = l; };""", shader_arguments="-enable-16bit-types", ) # Dot4AddI8Packed add_test_case( "Dot4AddI8Packed", ["Dot4AddI8Packed"], "epsilon", 0, [ [ "0x00000102", "0x00000102", "0x00000102", "0x00000102", "0XFFFFFFFF", "0x80808080", "0x80808080", "0x807F807F", "0x7F7F7F7F", "0x80808080", ], [ "0x00000304", "0x00000304", "0x00000304", "0x00000304", "0xFFFFFFFF", "0x01010101", "0x7F7F7F7F", "0x807F807F", "0x7F7F7F7F", "0x80808080", ], ["0", "10", "-5", "-30", "0", "0", "0", "0", "0", "0"], ], [ [11, 21, 6, -19, 4, -512, -65024, 65026, 64516, 65536], ], "cs_6_4", """ struct SDot4AddI8PackedOp { dword input1; dword input2; int acc; int result; }; RWStructuredBuffer<SDot4AddI8PackedOp> g_buf : register(u0); [numthreads(8,8,1)] void main(uint GI : SV_GroupIndex) { SDot4AddI8PackedOp l = g_buf[GI]; l.result = dot4add_i8packed(l.input1, l.input2, l.acc); g_buf[GI] = l; };""", ) # Dot4AddU8Packed add_test_case( "Dot4AddU8Packed", ["Dot4AddU8Packed"], "epsilon", 0, [ ["0x00000102", "0x00000102", "0x01234567", "0xFFFFFFFF", "0xFFFFFFFF"], ["0x00000304", "0x00000304", "0x23456789", "0xFFFFFFFF", "0xFFFFFFFF"], ["0", "10", "10000", "0", "3000000000"], ], [ [11, 21, 33668, 260100, 3000260100], ], "cs_6_4", """ struct SDot4AddU8PackedOp { dword input1; dword input2; dword acc; dword result; }; RWStructuredBuffer<SDot4AddU8PackedOp> g_buf : register(u0); [numthreads(8,8,1)] void main(uint GI : SV_GroupIndex) { SDot4AddU8PackedOp l = g_buf[GI]; l.result = dot4add_u8packed(l.input1, l.input2, l.acc); g_buf[GI] = l; };""", ) # Quaternary # Msad4 intrinsic calls both Bfi and Msad. Currently this is the only way to call bfi instruction from HLSL add_test_case( "Bfi", ["Bfi", "Msad"], "epsilon", 0, [ ["0xA100B2C3", "0x00000000", "0xFFFF01C1", "0xFFFFFFFF"], [ "0xD7B0C372, 0x4F57C2A3", "0xFFFFFFFF, 0x00000000", "0x38A03AEF, 0x38194DA3", "0xFFFFFFFF, 0x00000000", ], ["1,2,3,4", "1,2,3,4", "0,0,0,0", "10,10,10,10"], ], [["153,6,92,113", "1,2,3,4", "397,585,358,707", "10,265,520,775"]], "cs_6_0", """ struct SMsad4 { uint ref; uint2 source; uint4 accum; uint4 result; }; RWStructuredBuffer<SMsad4> g_buf : register(u0); [numthreads(8,8,1)] void main(uint GI : SV_GroupIndex) { SMsad4 l = g_buf[GI]; l.result = msad4(l.ref, l.source, l.accum); g_buf[GI] = l; };""", ) # Wave Active Tests add_test_case( "WaveActiveSum", ["WaveActiveOp", "WaveReadLaneFirst", "WaveReadLaneAt"], "Epsilon", 0, [["1", "2", "3", "4"], ["0"], ["2", "4", "8", "-64"]], [], "cs_6_0", get_shader_text("wave op int", "WaveActiveSum"), ) add_test_case( "WaveActiveProduct", ["WaveActiveOp", "WaveReadLaneFirst", "WaveReadLaneAt"], "Epsilon", 0, [["1", "2", "3", "4"], ["0"], ["1", "2", "4", "-64"]], [], "cs_6_0", get_shader_text("wave op int", "WaveActiveProduct"), ) add_test_case( "WaveActiveCountBits", ["WaveAllBitCount", "WaveReadLaneFirst", "WaveReadLaneAt"], "Epsilon", 0, [ ["1", "2", "3", "4"], ["0"], ["1", "10", "-4", "-64"], ["-100", "-1000", "300"], ], [], "cs_6_0", get_shader_text("wave op int count", "WaveActiveCountBits"), ) add_test_case( "WaveActiveMax", ["WaveActiveOp", "WaveReadLaneFirst", "WaveReadLaneAt"], "Epsilon", 0, [ ["1", "2", "3", "4"], ["0"], ["1", "10", "-4", "-64"], ["-100", "-1000", "300"], ], [], "cs_6_0", get_shader_text("wave op int", "WaveActiveMax"), ) add_test_case( "WaveActiveMin", ["WaveActiveOp", "WaveReadLaneFirst", "WaveReadLaneAt"], "Epsilon", 0, [ ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"], ["0"], ["1", "10", "-4", "-64"], ["-100", "-1000", "300"], ], [], "cs_6_0", get_shader_text("wave op int", "WaveActiveMin"), ) add_test_case( "WaveActiveAllEqual", ["WaveActiveAllEqual"], "Epsilon", 0, [["1", "2", "3", "4", "1", "1", "1", "1"], ["3"], ["-10"]], [], "cs_6_0", get_shader_text("wave op int", "WaveActiveAllEqual"), ) add_test_case( "WaveActiveAnyTrue", ["WaveAnyTrue", "WaveReadLaneFirst", "WaveReadLaneAt"], "Epsilon", 0, [["1", "0", "1", "0", "1"], ["1"], ["0"]], [], "cs_6_0", get_shader_text("wave op int", "WaveActiveAnyTrue"), ) add_test_case( "WaveActiveAllTrue", ["WaveAllTrue", "WaveReadLaneFirst", "WaveReadLaneAt"], "Epsilon", 0, [["1", "0", "1", "0", "1"], ["1"], ["1"]], [], "cs_6_0", get_shader_text("wave op int", "WaveActiveAllTrue"), ) add_test_case( "WaveActiveUSum", ["WaveActiveOp", "WaveReadLaneFirst", "WaveReadLaneAt"], "Epsilon", 0, [["1", "2", "3", "4"], ["0"], ["2", "4", "8", "64"]], [], "cs_6_0", get_shader_text("wave op uint", "WaveActiveSum"), ) add_test_case( "WaveActiveUProduct", ["WaveActiveOp", "WaveReadLaneFirst", "WaveReadLaneAt"], "Epsilon", 0, [["1", "2", "3", "4"], ["0"], ["1", "2", "4", "64"]], [], "cs_6_0", get_shader_text("wave op uint", "WaveActiveProduct"), ) add_test_case( "WaveActiveUMax", ["WaveActiveOp", "WaveReadLaneFirst", "WaveReadLaneAt"], "Epsilon", 0, [["1", "2", "3", "4"], ["0"], ["1", "10", "4", "64"]], [], "cs_6_0", get_shader_text("wave op uint", "WaveActiveMax"), ) add_test_case( "WaveActiveUMin", ["WaveActiveOp", "WaveReadLaneFirst", "WaveReadLaneAt"], "Epsilon", 0, [ ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"], ["0"], ["1", "10", "4", "64"], ], [], "cs_6_0", get_shader_text("wave op uint", "WaveActiveMin"), ) add_test_case( "WaveActiveBitOr", ["WaveActiveBit"], "Epsilon", 0, [ [ "0xe0000000", "0x0d000000", "0x00b00000", "0x00070000", "0x0000e000", "0x00000d00", "0x000000b0", "0x00000007", ], ["0xedb7edb7", "0xdb7edb7e", "0xb7edb7ed", "0x7edb7edb"], ["0x12481248", "0x24812481", "0x48124812", "0x81248124"], ["0x00000000", "0xffffffff"], ], [], "cs_6_0", get_shader_text("wave op uint", "WaveActiveBitOr"), ) add_test_case( "WaveActiveBitAnd", ["WaveActiveBit"], "Epsilon", 0, [ [ "0xefffffff", "0xfdffffff", "0xffbfffff", "0xfff7ffff", "0xffffefff", "0xfffffdff", "0xffffffbf", "0xfffffff7", ], ["0xedb7edb7", "0xdb7edb7e", "0xb7edb7ed", "0x7edb7edb"], ["0x12481248", "0x24812481", "0x48124812", "0x81248124"], ["0x00000000", "0xffffffff"], ], [], "cs_6_0", get_shader_text("wave op uint", "WaveActiveBitAnd"), ) add_test_case( "WaveActiveBitXor", ["WaveActiveBit"], "Epsilon", 0, [ [ "0xe0000000", "0x0d000000", "0x00b00000", "0x00070000", "0x0000e000", "0x00000d00", "0x000000b0", "0x00000007", ], ["0xedb7edb7", "0xdb7edb7e", "0xb7edb7ed", "0x7edb7edb"], ["0x12481248", "0x24812481", "0x48124812", "0x81248124"], ["0x00000000", "0xffffffff"], ], [], "cs_6_0", get_shader_text("wave op uint", "WaveActiveBitXor"), ) add_test_case( "WavePrefixCountBits", ["WavePrefixBitCount"], "Epsilon", 0, [ ["1", "2", "3", "4", "5"], ["0"], ["1", "10", "-4", "-64"], ["-100", "-1000", "300"], ], [], "cs_6_0", get_shader_text("wave op int count", "WavePrefixCountBits"), ) add_test_case( "WavePrefixSum", ["WavePrefixOp"], "Epsilon", 0, [["1", "2", "3", "4", "5"], ["0", "1"], ["1", "2", "4", "-64", "128"]], [], "cs_6_0", get_shader_text("wave op int", "WavePrefixSum"), ) add_test_case( "WavePrefixProduct", ["WavePrefixOp"], "Epsilon", 0, [["1", "2", "3", "4", "5"], ["0", "1"], ["1", "2", "4", "-64", "128"]], [], "cs_6_0", get_shader_text("wave op int", "WavePrefixProduct"), ) add_test_case( "WavePrefixUSum", ["WavePrefixOp"], "Epsilon", 0, [["1", "2", "3", "4", "5"], ["0", "1"], ["1", "2", "4", "128"]], [], "cs_6_0", get_shader_text("wave op uint", "WavePrefixSum"), ) add_test_case( "WavePrefixUProduct", ["WavePrefixOp"], "Epsilon", 0, [["1", "2", "3", "4", "5"], ["0", "1"], ["1", "2", "4", "128"]], [], "cs_6_0", get_shader_text("wave op uint", "WavePrefixProduct"), ) # Wave Multi Prefix Tests add_test_case( "WaveMultiPrefixBitAnd", ["WaveMultiPrefixOp"], "Epsilon", 0, [ ["0", "3", "1", "5", "4"], ["10", "42", "1", "64", "11", "76", "90", "111", "9", "6", "79", "34"], ], [], "cs_6_5", get_shader_text("wave op multi prefix int", "WaveMultiPrefixBitAnd"), ) add_test_case( "WaveMultiPrefixBitOr", ["WaveMultiPrefixOp"], "Epsilon", 0, [ ["0", "3", "1", "5", "4"], ["10", "42", "1", "64", "11", "76", "90", "111", "9", "6", "79", "34"], ], [], "cs_6_5", get_shader_text("wave op multi prefix int", "WaveMultiPrefixBitOr"), ) add_test_case( "WaveMultiPrefixBitXor", ["WaveMultiPrefixOp"], "Epsilon", 0, [ ["0", "3", "1", "5", "4"], ["10", "42", "1", "64", "11", "76", "90", "111", "9", "6", "79", "34"], ], [], "cs_6_5", get_shader_text("wave op multi prefix int", "WaveMultiPrefixBitXor"), ) add_test_case( "WaveMultiPrefixSum", ["WaveMultiPrefixOp"], "Epsilon", 0, [ ["0", "3", "1", "5", "4"], ["10", "42", "1", "64", "11", "76", "90", "111", "9", "6", "79", "34"], ], [], "cs_6_5", get_shader_text("wave op multi prefix int", "WaveMultiPrefixSum"), ) add_test_case( "WaveMultiPrefixProduct", ["WaveMultiPrefixOp"], "Epsilon", 0, [ ["0", "3", "1", "5", "4"], ["10", "42", "1", "64", "11", "76", "90", "111", "9", "6", "79", "34"], ], [], "cs_6_5", get_shader_text("wave op multi prefix int", "WaveMultiPrefixProduct"), ) add_test_case( "WaveMultiPrefixCountBits", ["WaveMultiPrefixOp"], "Epsilon", 0, [ ["0", "3", "1", "5", "4"], ["0", "42", "0", "64", "11", "76", "90", "111", "0", "0", "79", "34"], ], [], "cs_6_5", get_shader_text("wave op multi prefix int", "WaveMultiPrefixCountBits"), ) add_test_case( "WaveMultiPrefixUBitAnd", ["WaveMultiPrefixOp"], "Epsilon", 0, [ ["0", "3", "1", "5", "4"], ["10", "42", "1", "64", "11", "76", "90", "111", "9", "6", "79", "34"], ], [], "cs_6_5", get_shader_text("wave op multi prefix uint", "WaveMultiPrefixBitAnd"), ) add_test_case( "WaveMultiPrefixUBitOr", ["WaveMultiPrefixOp"], "Epsilon", 0, [ ["0", "3", "1", "5", "4"], ["10", "42", "1", "64", "11", "76", "90", "111", "9", "6", "79", "34"], ], [], "cs_6_5", get_shader_text("wave op multi prefix uint", "WaveMultiPrefixBitOr"), ) add_test_case( "WaveMultiPrefixUBitXor", ["WaveMultiPrefixOp"], "Epsilon", 0, [ ["0", "3", "1", "5", "4"], ["10", "42", "1", "64", "11", "76", "90", "111", "9", "6", "79", "34"], ], [], "cs_6_5", get_shader_text("wave op multi prefix uint", "WaveMultiPrefixBitXor"), ) add_test_case( "WaveMultiPrefixUSum", ["WaveMultiPrefixOp"], "Epsilon", 0, [ ["0", "3", "1", "5", "4"], ["10", "42", "1", "64", "11", "76", "90", "111", "9", "6", "79", "34"], ], [], "cs_6_5", get_shader_text("wave op multi prefix uint", "WaveMultiPrefixSum"), ) add_test_case( "WaveMultiPrefixUProduct", ["WaveMultiPrefixOp"], "Epsilon", 0, [ ["0", "3", "1", "5", "4"], ["10", "42", "1", "64", "11", "76", "90", "111", "9", "6", "79", "34"], ], [], "cs_6_5", get_shader_text("wave op multi prefix uint", "WaveMultiPrefixProduct"), ) add_test_case( "WaveMultiPrefixUCountBits", ["WaveMultiPrefixOp"], "Epsilon", 0, [ ["0", "3", "1", "5", "4"], ["0", "42", "0", "64", "11", "76", "90", "111", "0", "0", "79", "34"], ], [], "cs_6_5", get_shader_text("wave op multi prefix uint", "WaveMultiPrefixCountBits"), ) # generating xml file for execution test using data driven method # TODO: ElementTree is not generating formatted XML. Currently xml file is checked in after VS Code formatter. # Implement xml formatter or import formatter library and use that instead. def generate_parameter_types( table, num_inputs, num_outputs, has_known_warp_issue=False ): param_types = ET.SubElement(table, "ParameterTypes") ET.SubElement( param_types, "ParameterType", attrib={"Name": "ShaderOp.Target"} ).text = "String" ET.SubElement( param_types, "ParameterType", attrib={"Name": "ShaderOp.Arguments"} ).text = "String" ET.SubElement( param_types, "ParameterType", attrib={"Name": "ShaderOp.Text"} ).text = "String" ET.SubElement( param_types, "ParameterType", attrib={"Name": "Validation.Type"} ).text = "String" ET.SubElement( param_types, "ParameterType", attrib={"Name": "Validation.Tolerance"} ).text = "double" for i in range(0, num_inputs): ET.SubElement( param_types, "ParameterType", attrib={"Name": "Validation.Input{}".format(i + 1), "Array": "true"}, ).text = "String" for i in range(0, num_outputs): ET.SubElement( param_types, "ParameterType", attrib={"Name": "Validation.Expected{}".format(i + 1), "Array": "true"}, ).text = "String" if has_known_warp_issue: ET.SubElement( param_types, "ParameterType", attrib={"Name": "Warp.Version"} ).text = "unsigned int" def generate_parameter_types_wave(table): param_types = ET.SubElement(table, "ParameterTypes") ET.SubElement( param_types, "ParameterType", attrib={"Name": "ShaderOp.Target"} ).text = "String" ET.SubElement( param_types, "ParameterType", attrib={"Name": "ShaderOp.Text"} ).text = "String" ET.SubElement( param_types, "ParameterType", attrib={"Name": "Validation.NumInputSet"} ).text = "String" ET.SubElement( param_types, "ParameterType", attrib={"Name": "Validation.InputSet1", "Array": "true"}, ).text = "String" ET.SubElement( param_types, "ParameterType", attrib={"Name": "Validation.InputSet2", "Array": "true"}, ).text = "String" ET.SubElement( param_types, "ParameterType", attrib={"Name": "Validation.InputSet3", "Array": "true"}, ).text = "String" ET.SubElement( param_types, "ParameterType", attrib={"Name": "Validation.InputSet4", "Array": "true"}, ).text = "String" def generate_parameter_types_wave_multi_prefix(table): param_types = ET.SubElement(table, "ParameterTypes") ET.SubElement( param_types, "ParameterType", attrib={"Name": "ShaderOp.Target"} ).text = "String" ET.SubElement( param_types, "ParameterType", attrib={"Name": "ShaderOp.Text"} ).text = "String" ET.SubElement( param_types, "ParameterType", attrib={"Name": "Validation.Keys", "Array": "true"}, ).text = "String" ET.SubElement( param_types, "ParameterType", attrib={"Name": "Validation.Values", "Array": "true"}, ).text = "String" def generate_parameter_types_msad(table): param_types = ET.SubElement(table, "ParameterTypes") ET.SubElement( param_types, "ParameterType", attrib={"Name": "ShaderOp.Text"} ).text = "String" ET.SubElement( param_types, "ParameterType", attrib={"Name": "Validation.Tolerance"} ).text = "int" ET.SubElement( param_types, "ParameterType", attrib={"Name": "Validation.Input1", "Array": "true"}, ).text = "unsigned int" ET.SubElement( param_types, "ParameterType", attrib={"Name": "Validation.Input2", "Array": "true"}, ).text = "String" ET.SubElement( param_types, "ParameterType", attrib={"Name": "Validation.Input3", "Array": "true"}, ).text = "String" ET.SubElement( param_types, "ParameterType", attrib={"Name": "Validation.Expected1", "Array": "true"}, ).text = "String" def generate_row(table, case): row = ET.SubElement(table, "Row", {"Name": case.test_name}) ET.SubElement( row, "Parameter", {"Name": "Validation.Type"} ).text = case.validation_type ET.SubElement(row, "Parameter", {"Name": "Validation.Tolerance"}).text = str( case.validation_tolerance ) ET.SubElement(row, "Parameter", {"Name": "ShaderOp.Text"}).text = case.shader_text ET.SubElement( row, "Parameter", {"Name": "ShaderOp.Target"} ).text = case.shader_target for i in range(len(case.input_lists)): inputs = ET.SubElement( row, "Parameter", {"Name": "Validation.Input{}".format(i + 1)} ) for val in case.input_lists[i]: ET.SubElement(inputs, "Value").text = str(val) for i in range(len(case.output_lists)): outputs = ET.SubElement( row, "Parameter", {"Name": "Validation.Expected{}".format(i + 1)} ) for val in case.output_lists[i]: ET.SubElement(outputs, "Value").text = str(val) # Optional parameters if case.warp_version > 0: ET.SubElement(row, "Parameter", {"Name": "Warp.Version"}).text = str( case.warp_version ) if case.shader_arguments != "": ET.SubElement( row, "Parameter", {"Name": "ShaderOp.Arguments"} ).text = case.shader_arguments def generate_row_wave(table, case): row = ET.SubElement(table, "Row", {"Name": case.test_name}) ET.SubElement(row, "Parameter", {"Name": "ShaderOp.Name"}).text = case.test_name ET.SubElement(row, "Parameter", {"Name": "ShaderOp.Text"}).text = case.shader_text ET.SubElement(row, "Parameter", {"Name": "Validation.NumInputSet"}).text = str( len(case.input_lists) ) for i in range(len(case.input_lists)): inputs = ET.SubElement( row, "Parameter", {"Name": "Validation.InputSet{}".format(i + 1)} ) for val in case.input_lists[i]: ET.SubElement(inputs, "Value").text = str(val) def generate_row_wave_multi(table, case): row = ET.SubElement(table, "Row", {"Name": case.test_name}) ET.SubElement(row, "Parameter", {"Name": "ShaderOp.Name"}).text = case.test_name ET.SubElement( row, "Parameter", {"Name": "ShaderOp.Target"} ).text = case.shader_target ET.SubElement(row, "Parameter", {"Name": "ShaderOp.Text"}).text = case.shader_text inputs = ET.SubElement(row, "Parameter", {"Name": "Validation.Keys"}) for val in case.input_lists[0]: ET.SubElement(inputs, "Value").text = str(val) inputs = ET.SubElement(row, "Parameter", {"Name": "Validation.Values"}) for val in case.input_lists[1]: ET.SubElement(inputs, "Value").text = str(val) def generate_table_for_taef(): with open( "..\\..\\tools\\clang\\unittests\\HLSL\\ShaderOpArithTable.xml", "w" ) as f: tree = ET.ElementTree() root = ET.Element("Data") # Create tables generate_parameter_types( ET.SubElement(root, "Table", attrib={"Id": "UnaryFloatOpTable"}), 1, 1, True ) generate_parameter_types( ET.SubElement(root, "Table", attrib={"Id": "BinaryFloatOpTable"}), 2, 2 ) generate_parameter_types( ET.SubElement(root, "Table", attrib={"Id": "TertiaryFloatOpTable"}), 3, 1 ) generate_parameter_types( ET.SubElement(root, "Table", attrib={"Id": "UnaryHalfOpTable"}), 1, 1, True ) generate_parameter_types( ET.SubElement(root, "Table", attrib={"Id": "BinaryHalfOpTable"}), 2, 2 ) generate_parameter_types( ET.SubElement(root, "Table", attrib={"Id": "TertiaryHalfOpTable"}), 3, 1 ) generate_parameter_types( ET.SubElement(root, "Table", attrib={"Id": "UnaryIntOpTable"}), 1, 1 ) generate_parameter_types( ET.SubElement(root, "Table", attrib={"Id": "BinaryIntOpTable"}), 2, 2 ) generate_parameter_types( ET.SubElement(root, "Table", attrib={"Id": "TertiaryIntOpTable"}), 3, 1 ) generate_parameter_types( ET.SubElement(root, "Table", attrib={"Id": "UnaryInt16OpTable"}), 1, 1 ) generate_parameter_types( ET.SubElement(root, "Table", attrib={"Id": "BinaryInt16OpTable"}), 2, 2 ) generate_parameter_types( ET.SubElement(root, "Table", attrib={"Id": "TertiaryInt16OpTable"}), 3, 1 ) generate_parameter_types( ET.SubElement(root, "Table", attrib={"Id": "UnaryUintOpTable"}), 1, 1 ) generate_parameter_types( ET.SubElement(root, "Table", attrib={"Id": "BinaryUintOpTable"}), 2, 2 ) generate_parameter_types( ET.SubElement(root, "Table", attrib={"Id": "TertiaryUintOpTable"}), 3, 1 ) generate_parameter_types( ET.SubElement(root, "Table", attrib={"Id": "UnaryUint16OpTable"}), 1, 1 ) generate_parameter_types( ET.SubElement(root, "Table", attrib={"Id": "BinaryUint16OpTable"}), 2, 2 ) generate_parameter_types( ET.SubElement(root, "Table", attrib={"Id": "TertiaryUint16OpTable"}), 3, 1 ) generate_parameter_types( ET.SubElement(root, "Table", attrib={"Id": "DotOpTable"}), 2, 3 ) generate_parameter_types( ET.SubElement(root, "Table", attrib={"Id": "Dot2AddHalfOpTable"}), 3, 1 ) generate_parameter_types( ET.SubElement(root, "Table", attrib={"Id": "Dot4AddI8PackedOpTable"}), 3, 1 ) generate_parameter_types( ET.SubElement(root, "Table", attrib={"Id": "Dot4AddU8PackedOpTable"}), 3, 1 ) generate_parameter_types_msad( ET.SubElement(root, "Table", attrib={"Id": "Msad4Table"}) ) generate_parameter_types_wave( ET.SubElement(root, "Table", attrib={"Id": "WaveIntrinsicsActiveIntTable"}) ) generate_parameter_types_wave( ET.SubElement(root, "Table", attrib={"Id": "WaveIntrinsicsActiveUintTable"}) ) generate_parameter_types_wave( ET.SubElement(root, "Table", attrib={"Id": "WaveIntrinsicsPrefixIntTable"}) ) generate_parameter_types_wave( ET.SubElement(root, "Table", attrib={"Id": "WaveIntrinsicsPrefixUintTable"}) ) generate_parameter_types_wave_multi_prefix( ET.SubElement( root, "Table", attrib={"Id": "WaveIntrinsicsMultiPrefixIntTable"} ) ) generate_parameter_types_wave_multi_prefix( ET.SubElement( root, "Table", attrib={"Id": "WaveIntrinsicsMultiPrefixUintTable"} ) ) generate_parameter_types( ET.SubElement(root, "Table", attrib={"Id": "DenormBinaryFloatOpTable"}), 2, 2, ) # 2 sets of expected values for any mode generate_parameter_types( ET.SubElement(root, "Table", attrib={"Id": "DenormTertiaryFloatOpTable"}), 3, 2, ) for case in g_test_cases.values(): cur_inst = case.insts[0] if cur_inst.is_cast or cur_inst.category.startswith("Unary"): if "f" in cur_inst.oload_types and not "Half" in case.test_name: generate_row(root.find("./Table[@Id='UnaryFloatOpTable']"), case) if "h" in cur_inst.oload_types and "Half" in case.test_name: generate_row(root.find("./Table[@Id='UnaryHalfOpTable']"), case) if "i" in cur_inst.oload_types and "Bit16" not in case.test_name: if cur_inst.category.startswith("Unary int"): generate_row(root.find("./Table[@Id='UnaryIntOpTable']"), case) elif cur_inst.category.startswith("Unary uint"): generate_row(root.find("./Table[@Id='UnaryUintOpTable']"), case) else: print("unknown op: " + cur_inst.name) print(cur_inst.dxil_class) if "w" in cur_inst.oload_types and "Bit16" in case.test_name: if cur_inst.category.startswith("Unary int"): generate_row( root.find("./Table[@Id='UnaryInt16OpTable']"), case ) elif cur_inst.category.startswith("Unary uint"): generate_row( root.find("./Table[@Id='UnaryUint16OpTable']"), case ) else: print("unknown op: " + cur_inst.name) print(cur_inst.dxil_class) elif cur_inst.is_binary or cur_inst.category.startswith("Binary"): if "f" in cur_inst.oload_types and not "Half" in case.test_name: if case.test_name in g_denorm_tests: # for denorm tests generate_row( root.find("./Table[@Id='DenormBinaryFloatOpTable']"), case ) else: generate_row( root.find("./Table[@Id='BinaryFloatOpTable']"), case ) if "h" in cur_inst.oload_types and "Half" in case.test_name: generate_row(root.find("./Table[@Id='BinaryHalfOpTable']"), case) if "i" in cur_inst.oload_types and "Bit16" not in case.test_name: if cur_inst.category.startswith("Binary int"): if case.test_name in [ "UAdd", "USub", "UMul", ]: # Add, Sub, Mul use same operations for int and uint. generate_row( root.find("./Table[@Id='BinaryUintOpTable']"), case ) else: generate_row( root.find("./Table[@Id='BinaryIntOpTable']"), case ) elif cur_inst.category.startswith("Binary uint"): generate_row( root.find("./Table[@Id='BinaryUintOpTable']"), case ) else: print("unknown op: " + cur_inst.name) print(cur_inst.dxil_class) if "w" in cur_inst.oload_types and "Bit16" in case.test_name: if cur_inst.category.startswith("Binary int"): if case.test_name in [ "UAdd", "USub", "UMul", ]: # Add, Sub, Mul use same operations for int and uint. generate_row( root.find("./Table[@Id='BinaryUint16OpTable']"), case ) else: generate_row( root.find("./Table[@Id='BinaryInt16OpTable']"), case ) elif cur_inst.category.startswith("Binary uint"): generate_row( root.find("./Table[@Id='BinaryUint16OpTable']"), case ) else: print("unknown op: " + cur_inst.name) print(cur_inst.dxil_class) elif cur_inst.category.startswith("Tertiary"): if "f" in cur_inst.oload_types and not "Half" in case.test_name: if case.test_name in g_denorm_tests: # for denorm tests generate_row( root.find("./Table[@Id='DenormTertiaryFloatOpTable']"), case ) else: generate_row( root.find("./Table[@Id='TertiaryFloatOpTable']"), case ) if "h" in cur_inst.oload_types and "Half" in case.test_name: generate_row(root.find("./Table[@Id='TertiaryHalfOpTable']"), case) if "i" in cur_inst.oload_types and "Bit16" not in case.test_name: if cur_inst.category.startswith("Tertiary int"): generate_row( root.find("./Table[@Id='TertiaryIntOpTable']"), case ) elif cur_inst.category.startswith("Tertiary uint"): generate_row( root.find("./Table[@Id='TertiaryUintOpTable']"), case ) else: print("unknown op: " + cur_inst.name) print(cur_inst.dxil_class) if "w" in cur_inst.oload_types and "Bit16" in case.test_name: if cur_inst.category.startswith("Tertiary int"): generate_row( root.find("./Table[@Id='TertiaryInt16OpTable']"), case ) elif cur_inst.category.startswith("Tertiary uint"): generate_row( root.find("./Table[@Id='TertiaryUint16OpTable']"), case ) else: print("unknown op: " + cur_inst.name) print(cur_inst.dxil_class) elif cur_inst.category.startswith("Quaternary"): if cur_inst.name == "Bfi": generate_row(root.find("./Table[@Id='Msad4Table']"), case) else: print("unknown op: " + cur_inst.name) print(cur_inst.dxil_class) elif cur_inst.category == "Dot": generate_row(root.find("./Table[@Id='DotOpTable']"), case) elif cur_inst.category == "Dot product with accumulate": if cur_inst.name == "Dot2AddHalf": generate_row(root.find("./Table[@Id='Dot2AddHalfOpTable']"), case) elif cur_inst.name == "Dot4AddI8Packed": generate_row( root.find("./Table[@Id='Dot4AddI8PackedOpTable']"), case ) elif cur_inst.name == "Dot4AddU8Packed": generate_row( root.find("./Table[@Id='Dot4AddU8PackedOpTable']"), case ) else: print("unknown op: " + cur_inst.name) print(cur_inst.dxil_class) elif cur_inst.dxil_class in [ "WaveActiveOp", "WaveAllOp", "WaveActiveAllEqual", "WaveAnyTrue", "WaveAllTrue", ]: if case.test_name.startswith("WaveActiveU"): generate_row_wave( root.find("./Table[@Id='WaveIntrinsicsActiveUintTable']"), case ) else: generate_row_wave( root.find("./Table[@Id='WaveIntrinsicsActiveIntTable']"), case ) elif cur_inst.dxil_class == "WaveActiveBit": generate_row_wave( root.find("./Table[@Id='WaveIntrinsicsActiveUintTable']"), case ) elif cur_inst.dxil_class == "WavePrefixOp": if case.test_name.startswith("WavePrefixU"): generate_row_wave( root.find("./Table[@Id='WaveIntrinsicsPrefixUintTable']"), case ) else: generate_row_wave( root.find("./Table[@Id='WaveIntrinsicsPrefixIntTable']"), case ) elif cur_inst.dxil_class == "WaveMultiPrefixOp": if case.test_name.startswith("WaveMultiPrefixU"): generate_row_wave_multi( root.find("./Table[@Id='WaveIntrinsicsMultiPrefixUintTable']"), case, ) else: generate_row_wave_multi( root.find("./Table[@Id='WaveIntrinsicsMultiPrefixIntTable']"), case, ) else: print("unknown op: " + cur_inst.name) print(cur_inst.dxil_class) tree._setroot(root) from xml.dom.minidom import parseString pretty_xml = parseString(ET.tostring(root)).toprettyxml(indent=" ") f.write(pretty_xml) print("Saved file at: " + f.name) f.close() def print_untested_inst(): lst = [] for name in [ node.inst.name for node in g_instruction_nodes.values() if len(node.test_cases) == 0 ]: lst += [name] lst.sort() print("Untested dxil ops: ") for name in lst: print(name) print("Total uncovered dxil ops: " + str(len(lst))) print("Total covered dxil ops: " + str(len(g_instruction_nodes) - len(lst))) # inst name to instruction dict g_instruction_nodes = {} # test name to test case dict g_test_cases = {} if __name__ == "__main__": db = get_db_dxil() for inst in db.instr: g_instruction_nodes[inst.name] = inst_node(inst) add_test_cases() args = vars(parser.parse_args()) mode = args["mode"] if mode == "info": print_untested_inst() elif mode == "gen-xml": generate_table_for_taef() else: print("unknown mode: " + mode) exit(1) exit(0)
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/hct/hcttest-samples.py
# Copyright (C) Microsoft Corporation. All rights reserved. # This file is distributed under the University of Illinois Open Source License. See LICENSE.TXT for details. import argparse import glob import shutil import os import subprocess import re try: import xml.etree.cElementTree as ET except ImportError: import xml.etree.ElementTree as ET # Comment namespace to make working with ElementTree easier: def ReadXmlString(text): global xmlheader text = text.replace("xmlns=", "xmlns_commented=") xmlheader = text[: text.find("\n") + 1] # TODO: read xml and return xml root return ET.fromstring(text) def WriteXmlString(root): global xmlheader text = ET.tostring(root, encoding="utf-8") return xmlheader + text.replace("xmlns_commented=", "xmlns=") def DeepCopyElement(e): cpy = ET.Element(e.tag, e.attrib) cpy.text = e.text cpy.tail = e.tail for child in e: cpy.append(DeepCopyElement(child)) return cpy sample_names = [ "D3D1211On12", "D3D12Bundles", "D3D12DynamicIndexing", "D3D12ExecuteIndirect", "D3D12Fullscreen", # "D3D12HelloWorld", "D3D12HelloWorld\\src\\HelloBundles", "D3D12HelloWorld\\src\\HelloConstBuffers", "D3D12HelloWorld\\src\\HelloFrameBuffering", "D3D12HelloWorld\\src\\HelloTexture", "D3D12HelloWorld\\src\\HelloTriangle", "D3D12HelloWorld\\src\\HelloWindow", "D3D12HeterogeneousMultiadapter", # WarpAssert in ReadPointerOperand: pInfoSrc->getName().startswith("dx.var.x"). # Fix tested - incorrect rendered result produced. # Worked around in sample shaders for now by moving to non-static locals. "D3D12Multithreading", # works and is visually impressive! "D3D12nBodyGravity", # expected empty cbuffer culling due to static members causes this to fail! FIXED! "D3D12PipelineStateCache", # Requires workaround for static globals "D3D12PredicationQueries", "D3D12ReservedResources", "D3D12Residency", # has problems on x86 due to mem limitations. The following seems to help: # change NumTextures to 1024 * 1, and add min with 1GB here: # UINT64 memoryToUse = UINT64 (float(min(memoryInfo.Budget, UINT64(1 << 30))) * 0.95f); # Still produces a bunch of these errors: # D3D12 ERROR: ID3D12CommandAllocator::Reset: A command allocator is being reset before previous executions associated with the allocator have completed. [ EXECUTION ERROR #552: COMMAND_ALLOCATOR_SYNC] # but at least it no longer crashes "D3D12SmallResources", ] class Sample(object): def __init__(self, name): self.name = name self.preBuild = [] self.postBuild = [] samples = dict([(name, Sample(name)) for name in sample_names]) def SetSampleActions(): # Actions called with (name, args, dxil) # Actions for all projects: for name, sample in samples.items(): sample.postBuild.append(ActionCopyD3DBins) sample.postBuild.append(ActionCopySDKLayers) sample.postBuild.append(ActionCopyWarp12) sample.postBuild.append( ActionCopyCompilerBins ) # Do this for all projects for now # TODO: limit ActionCopyCompilerBins action to ones that do run-time compilation. # # Runtime HLSL compilation: # for name in [ "D3D1211On12", # "D3D12HelloWorld\\src\\HelloTriangle", # "D3D12ExecuteIndirect", # ]: # samples[name].postBuild.append(ActionCopyCompilerBins) def CopyFiles(source_path, dest_path, filenames, symbols=False): for filename in filenames: renamed = filename try: filename, renamed = filename.split(";") print("Copying %s from %s to %s" % (filename, source_path, dest_path)) print(".. with new name: %s" % (renamed)) except: print("Copying %s from %s to %s" % (filename, source_path, dest_path)) try: shutil.copy2( os.path.join(source_path, filename), os.path.join(dest_path, renamed) ) except: print( 'Error copying "%s" from "%s" to "%s"' % (filename, source_path, dest_path) ) # sys.excepthook(*sys.exc_info()) continue if symbols and (filename.endswith(".exe") or filename.endswith(".dll")): symbol_filename = filename[:-4] + ".pdb" try: shutil.copy2( os.path.join(source_path, symbol_filename), os.path.join(dest_path, symbol_filename), ) except: print( 'Error copying symbols "%s" from "%s" to "%s"' % (symbol_filename, source_path, dest_path) ) def CopyBins(args, name, dxil, filenames, symbols=False): samples_path = args.samples config = dxil and "DxilDebug" or "Debug" CopyFiles( args.bins, os.path.join(PathToSampleSrc(samples_path, name), "bin", args.arch, config), filenames, symbols, ) def ActionCopyCompilerBins(args, name, dxil): if dxil: CopyBins( args, name, dxil, [ "dxcompiler.dll", "dxil.dll", "d3dcompiler_dxc_bridge.dll;d3dcompiler_47.dll", # Wrapper version that calls into dxcompiler.dll ], args.symbols, ) def ActionCopyD3DBins(args, name, dxil): if dxil: CopyBins( args, name, dxil, [ "d3d12.dll", ], args.symbols, ) def ActionCopySDKLayers(args, name, dxil): CopyBins( args, name, dxil, [ "D3D11_3SDKLayers.dll", "D3D12SDKLayers.dll", "DXGIDebug.dll", ], args.symbols, ) def ActionCopyWarp12(args, name, dxil): CopyBins( args, name, dxil, [ "d3d12warp.dll", ], args.symbols, ) def MakeD3D12WarpCopy(bin_path): # Copy d3d10warp.dll to d3d12warp.dll shutil.copy2( os.path.join(bin_path, "d3d10warp.dll"), os.path.join(bin_path, "d3d12warp.dll") ) def PathSplitAll(p): s = filter(None, os.path.split(p)) if len(s) > 1: return PathSplitAll(s[0]) + (s[1],) else: return (s[0],) def GetBinPath(args, name): return os.path.join(args.bins, name) def GetProjectBinFilePath(args, samples_path, sample_name, file_name): src = PathToSampleSrc(samples_path, sample_name) return os.path.join(src, "bin", args.arch, file_name) def ListRuntimeCompilePaths(args): return [ os.path.join(args.bins, name) for name in [ "fxc.exe", "dxc.exe", "dxcompiler.dll", "dxil.dll", "d3dcompiler_47.dll", "d3d12.dll", "D3D11_3SDKLayers.dll", "D3D12SDKLayers.dll", "DXGIDebug.dll", "d3d12warp.dll", ] ] def CheckEnvironment(args): if not args.bins: print("The -bins argument is needed to populate tool binaries.") exit(1) if not os.path.exists(args.bins): print("The -bins argument '" + args.bins + "' does not exist.") exit(1) for fn in ListRuntimeCompilePaths(args): if not os.path.exists(fn): print("Expected file '" + fn + "' not found.") exit(1) if os.path.getmtime(GetBinPath(args, "fxc.exe")) != os.path.getmtime( GetBinPath(args, "dxc.exe") ): print("fxc.exe should be a copy of dxc.exe.") print( "Please copy " + GetBinPath(args, "dxc.exe") + " " + GetBinPath(args, "fxc.exe") ) exit(1) try: msbuild_version = subprocess.check_output(["msbuild", "-nologo", "-ver"]) print("msbuild version: " + msbuild_version) except Exception as E: print("Unable to get the version from msbuild: " + str(E)) print("This command should be run from a Developer Command Prompt") exit(1) def SampleIsNested(name): return "\\src\\" in name def PathToSampleSrc(basePath, sampleName): if SampleIsNested(sampleName): return os.path.join(basePath, "Samples", "Desktop", sampleName) return os.path.join(basePath, "Samples", "Desktop", sampleName, "src") reConfig = r"(Debug|Release|DxilDebug|DxilRelease)\|(Win32|x64)" def AddProjectConfigs(root, args): rxConfig = re.compile(reConfig) changed = False for e in root.findall(".//WindowsTargetPlatformVersion"): if e.text == "10.0.10240.0": e.text = "10.0.10586.0" changed = True # Override fxc path for Dxil configs: for config in ["DxilDebug", "DxilRelease"]: for arch in ["Win32", "x64"]: if not root.find( """./PropertyGroup[@Condition="'$(Configuration)|$(Platform)'=='%s|%s'"]/FXCToolPath""" % (config, arch) ): e = ET.Element( "PropertyGroup", { "Condition": "'$(Configuration)|$(Platform)'=='%s|%s'" % (config, arch) }, ) e.text = "\n " e.tail = "\n " root.insert(0, e) e = ET.SubElement(e, "FXCToolPath") e.text = "$(DXC_BIN_PATH)" # args.bins e.tail = "\n " # Extend ProjectConfiguration for Win32 and Dxil configs ig = root.find('./ItemGroup[@Label="ProjectConfigurations"]') or [] debug_config = release_config = None # ProjectConfiguration configs = {} for e in ig: try: m = rxConfig.match(e.attrib["Include"]) if m: key = m.groups() configs[key] = e if m.group(1) == "Debug": debug_config = key, e elif m.group(1) == "Release": release_config = key, e except: continue parents = root.findall( """.//*[@Condition="'$(Configuration)|$(Platform)'=='%s|%s'"]/..""" % ("Debug", "x64") ) if not configs or not debug_config or not release_config: print("No ProjectConfigurations found") return False for arch in ["Win32", "x64"]: for config in ["Debug", "DxilDebug", "Release", "DxilRelease"]: if config in ("Debug", "DxilDebug"): t_config = "Debug", "x64" else: t_config = "Release", "x64" config_condition = "'$(Configuration)|$(Platform)'=='%s|%s'" % t_config if not configs.get((config, arch), None): changed = True if config in ("Debug", "DxilDebug"): e = DeepCopyElement(debug_config[1]) else: e = DeepCopyElement(release_config[1]) e.set("Include", "%s|%s" % (config, arch)) e.find("./Configuration").text = config e.find("./Platform").text = arch ig.append(e) for parent in reversed(parents): for n, e in reversed(list(enumerate(parent))): try: cond = e.attrib["Condition"] except KeyError: continue if cond == config_condition: e = DeepCopyElement(e) # Override DisableOptimizations for DxilDebug since this flag is problematic right now if e.tag == "ItemDefinitionGroup" and config == "DxilDebug": FxCompile = e.find("./FxCompile") or ET.SubElement( e, "FxCompile" ) DisableOptimizations = FxCompile.find( "./DisableOptimizations" ) or ET.SubElement(FxCompile, "DisableOptimizations") DisableOptimizations.text = "false" e.attrib[ "Condition" ] = "'$(Configuration)|$(Platform)'=='%s|%s'" % ( config, arch, ) parent.insert(n + 1, e) return changed def AddSlnConfigs(sln_text): # sln: GlobalSection(SolutionConfigurationPlatforms) rxSlnConfig = re.compile(r"^\s+%s = \1\|\2$" % reConfig) # sln: GlobalSection(ProjectConfigurationPlatforms) rxActiveCfg = re.compile(r"^\s+\{[0-9A-Z-]+\}\.%s\.ActiveCfg = \1\|\2$" % reConfig) rxBuild = re.compile(r"^\s+\{[0-9A-Z-]+\}\.%s\.Build\.0 = \1\|\2$" % reConfig) sln_changed = [] line_set = set(sln_text.splitlines()) def add_line(lst, line): "Prevent duplicates from being added" if line not in line_set: lst.append(line) for line in sln_text.splitlines(): if line == "VisualStudioVersion = 14.0.23107.0": sln_changed.append("VisualStudioVersion = 14.0.25123.0") continue m = rxSlnConfig.match(line) if not m: m = rxActiveCfg.match(line) if not m: m = rxBuild.match(line) if m: sln_changed.append(line) config = m.group(1) if config in ("Debug", "Release") and m.group(2) == "x64": add_line(sln_changed, line.replace("x64", "Win32")) add_line(sln_changed, line.replace(config, "Dxil" + config)) add_line( sln_changed, line.replace(config, "Dxil" + config).replace("x64", "Win32"), ) continue sln_changed.append(line) return "\n".join(sln_changed) def PatchProjects(args): for name in sample_names + ["D3D12HelloWorld"]: sample_path = PathToSampleSrc(args.samples, name) print("Patching " + name + " in " + sample_path) for proj_path in glob.glob(os.path.join(sample_path, "*.vcxproj")): # Consider looking for msbuild and other tool paths in registry, etg: # reg query HKLM\Software\Microsoft\MSBuild\ToolsVersions\14.0 with open(proj_path, "r") as proj_file: proj_text = proj_file.read() root = ReadXmlString(proj_text) if AddProjectConfigs(root, args): changed_text = WriteXmlString(root) print("Patching the Windows SDK version in " + proj_path) with open(proj_path, "w") as proj_file: proj_file.write(changed_text) # Extend project configs in solution file for sln_path in glob.glob(os.path.join(sample_path, "*.sln")): with open(sln_path, "r") as sln_file: sln_text = sln_file.read() changed_text = AddSlnConfigs(sln_text) if changed_text != sln_text: print("Adding additional configurations to " + sln_path) with open(sln_path, "w") as sln_file: sln_file.write(changed_text) def BuildSample(samples_path, name, x86, dxil): sample_path = PathToSampleSrc(samples_path, name) if not SampleIsNested(name): print("Building " + name + " in " + sample_path) Platform = x86 and "Win32" or "x64" Configuration = dxil and "DxilDebug" or "Debug" subprocess.check_call( [ "msbuild", "-nologo", "/p:Configuration=%s;Platform=%s" % (Configuration, Platform), "/t:Rebuild", ], cwd=sample_path, ) def BuildSamples(args, dxil): samples_path = args.samples rxSample = args.sample and re.compile(args.sample, re.I) buildHelloWorld = False os.environ["DXC_BIN_PATH"] = args.bins for sample_name in sample_names: if rxSample and not rxSample.match(sample_name): continue if SampleIsNested(sample_name): buildHelloWorld = True continue BuildSample(samples_path, sample_name, args.x86, dxil) if buildHelloWorld: # HelloWorld containts sub-samples that must be built from the solution file. BuildSample(samples_path, "D3D12HelloWorld", args.x86, dxil) def PatchSample(args, name, dxil, afterBuild): if args.sample and not re.match(args.sample, name, re.I): return try: sample = samples[name] except: print("Error: selected sample missing from sample map '" + name + "'.") return if afterBuild: actions = sample.postBuild else: actions = sample.preBuild for action in actions: action(args, name, dxil) def PatchSamplesAfterBuild(args, dxil): for sample_name in sample_names: PatchSample(args, sample_name, dxil, True) def PatchSamplesBeforeBuild(args, dxil): for sample_name in sample_names: PatchSample(args, sample_name, dxil, False) def RunSampleTests(args): CheckEnvironment(args) print("Building Debug config ...") BuildSamples(args, False) print("Building DxilDebug config ...") BuildSamples(args, True) print("Applying patch to post-build binaries to enable dxc ...") PatchSamplesAfterBuild(args, False) PatchSamplesAfterBuild(args, True) print( "TODO - run Debug config vs. DxilDebug config and verify results are the same" ) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Run D3D sample tests...") parser.add_argument("-x86", action="store_true", help="add x86 targets") parser.add_argument("-samples", help="path to root of D3D12 samples") parser.add_argument("-bins", help="path to dxcompiler.dll and related binaries") parser.add_argument( "-sample", help="choose a single sample to build/test (* wildcard supported)" ) parser.add_argument( "-postbuild", action="store_true", help="only perform post-build operations" ) parser.add_argument("-patch", action="store_true", help="patch projects") parser.add_argument( "-symbols", action="store_true", help="try to copy symbols for various dependencies", ) args = parser.parse_args() SetSampleActions() if args.x86: args.arch = "Win32" else: args.arch = "x64" if not args.samples: print("The -samples option must be used to indicate the root of D3D12 Samples.") print("Samples are available at this URL.") print("https://github.com/Microsoft/DirectX-Graphics-Samples") exit(1) if args.sample: print("Applying sample filter: %s" % args.sample) args.sample = re.escape(args.sample).replace("\\*", ".*") rxSample = re.compile(args.sample, re.I) for name in samples: if rxSample.match(name): print(" %s" % name) if args.postbuild: print("Applying patch to post-build binaries to enable dxc ...") PatchSamplesAfterBuild(args, False) PatchSamplesAfterBuild(args, True) elif args.patch: print("Patching projects ...") PatchProjects(args) else: RunSampleTests(args)
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/hct/hcttest-system-values.py
# Copyright (C) Microsoft Corporation. All rights reserved. # This file is distributed under the University of Illinois Open Source License. See LICENSE.TXT for details. """hcttest-system-values.py - Test all system values with each signature point through fxc. Builds csv tables for the results for each shader model from 4.0 through 5.1. """ import re SignaturePoints = [ # sig point, stage, tessfactors already present ("VSIn", "vs", False), ("VSOut", "vs", False), ("PCIn", "hs", False), ("HSIn", "hs", False), ("HSCPIn", "hs", False), ("HSCPOut", "hs", False), ("PCOut", "hs", True), ("DSIn", "ds", True), ("DSCPIn", "ds", False), ("DSOut", "ds", False), ("GSVIn", "gs", False), ("GSIn", "gs", False), ("GSOut", "gs", False), ("PSIn", "ps", False), ("PSOut", "ps", False), ("CSIn", "cs", False), ] SysValues = """ VertexID InstanceID Position RenderTargetArrayIndex ViewportArrayIndex ClipDistance CullDistance OutputControlPointID DomainLocation PrimitiveID GSInstanceID SampleIndex IsFrontFace Coverage InnerCoverage Target Depth DepthLessEqual DepthGreaterEqual StencilRef DispatchThreadID GroupID GroupIndex GroupThreadID TessFactor InsideTessFactor """.split() def run(cmd, output_filename=None): import os print(cmd) if output_filename: if os.path.isfile(output_filename): os.unlink(output_filename) with file(output_filename, "wt") as f: f.write("%s\n\n" % cmd) ret = os.system(cmd + ' >> "%s" 2>&1' % output_filename) output = "" if os.path.isfile(output_filename): with open(output_filename, "rt") as f: output = f.read() return ret, output else: ret = os.system(cmd) return ret, None sig_examples = """ // Patch Constant signature: // // Name Index Mask Register SysValue Format Used // -------------------- ----- ------ -------- -------- ------- ------ // Arb 0 x 0 NONE float x // SV_TessFactor 0 x 1 QUADEDGE float x // SV_TessFactor 1 x 2 QUADEDGE float x // SV_TessFactor 2 x 3 QUADEDGE float x // SV_TessFactor 3 x 4 QUADEDGE float x // SV_InsideTessFactor 0 x 5 QUADINT float x // SV_InsideTessFactor 1 x 6 QUADINT float x // // // Input signature: // // Name Index Mask Register SysValue Format Used // -------------------- ----- ------ -------- -------- ------- ------ // Arb 0 x 0 NONE float // // // Output signature: // // Name Index Mask Register SysValue Format Used // -------------------- ----- ------ -------- -------- ------- ------ // Arb 0 x 0 NONE float x """ rxSigBegin = re.compile(r"^// (Input|Output|Patch Constant) signature:\s*$") rxSigElementsBegin = re.compile( r"^// -------------------- ----- ------ -------- -------- ------- ------\s*$" ) # // SV_Target 1 xyzw 1 TARGET float xyzw rxSigElement = re.compile( r"^// ([^\s]+)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)\s*([^\s]+)?\s*$" ) # Name, Index, Mask, Register, SysValue, Format, Used = m.groups() # For now, ParseSigs just looks for a matching semantic name and reports whether it uses # a separate register (unpacked) and whether it's treated as arbitrary. def ParseSigs(text, semantic): "return separate_reg, as_arb for matching semantic" it = iter(text.splitlines()) sigtype = None try: while True: line = it.next() m = rxSigBegin.match(line) if m: sigtype = m.group(1) continue m = rxSigElementsBegin.match(line) if m: while True: line = it.next() m = rxSigElement.match(line) if m: Name, Index, Mask, Register, SysValue, Format, Used = m.groups() if Name.lower() == semantic.lower(): try: regnum = int(Register) reg = False except: reg = True arb = SysValue == "NONE" return reg, arb except StopIteration: pass return None # Internal error or validation error: rxInternalError = re.compile(r"^(internal error:.*|error X8000:.*)$") # error X4502: invalid ps input semantic 'Foo' # error X4502: SV_Coverage input not supported on ps_4_0 # error X4502: SV_SampleIndex isn't supported on ps_4_0 # error X3514: SV_GSInstanceID is an invalid input semantic for geometry shader primitives, it must be its own parameter. # error X3514: 'GSMain': input parameter 'tfactor' must have a geometry specifier # also errors for unsupported shader models # error X3660: cs_4_0 does not support interlocked operations rxSemanticErrors = [ re.compile(r".*?\.hlsl.*?: error X4502: invalid .*? semantic '(\w+)'"), re.compile(r".*?\.hlsl.*?: error X4502: (\w+) .*? supported on \w+"), re.compile( r".*?\.hlsl.*?: error X3514: (\w+) is an invalid input semantic for geometry shader primitives, it must be its own parameter\." ), re.compile( r".*?\.hlsl.*?: error X3514: 'GSMain': input parameter '\w+' must have a geometry specifier" ), ] def map_gen(fn, *sequences): "generator style map" iters = map(iter, sequences) while True: yield fn(*map(next, iters)) def firstTrue(iterable): "returns first non-False element, or None." for it in iterable: if it: return it def ParseSVError(text, semantic): "return true if error is about illegal use of matching semantic" for line in text.splitlines(): m = firstTrue(map_gen(lambda rx: rx.match(line), rxSemanticErrors)) if m: if len(m.groups()) < 1 or m.group(1).lower() == semantic.lower(): return True else: m = rxInternalError.match(line) if m: print("#### Internal error detected!") print(m.group(1)) return "InternalError" return False # TODO: Fill in the correct error pattern # error X4576: Non system-generated input signature parameter (Arb) cannot appear after a system generated value. rxMustBeLastError = re.compile( r".*?\.hlsl.*?: error X4576: Non system-generated input signature parameter \(\w+\) cannot appear after a system generated value." ) def ParseSGVError(text, semantic): "return true if error is about matching semantic having to be declared last" for line in text.splitlines(): m = rxMustBeLastError.match(line) if m: return True else: m = rxInternalError.match(line) if m: print("#### Internal error detected!") print(m.group(1)) return "InternalError" return False hlsl_filename = os.abspath( os.path.join( os.environ["HLSL_SRC_DIR"], r"tools\clang\test\HLSL", "system-values.hlsl" ) ) def main(): do("5_1") do("5_0") do("4_1") do("4_0") def do(sm): import os, sys # set up table: table = [[None] * len(SignaturePoints) for sv in SysValues] null_filename = "output\\test_sv_null.txt" for col, (sigpoint, stage, tfpresent) in enumerate(SignaturePoints): entry = stage.upper() + "Main" target = stage + "_%s" % sm # test arb support: ret, output = run( "fxc %s /E %s /T %s /D%s_Defs=Def_Arb(float,Arb1,Arb1)" % (hlsl_filename, entry, target, sigpoint), null_filename, ) arb_supported = ret == 0 # iterate all system values sysvalues = tfpresent and SysValues[:-2] or SysValues for row, sv in enumerate(sysvalues): output_filename = "output\\test_sv_output_%s_%s_%s.txt" % (sm, sv, sigpoint) separate_reg, as_arb, def_last, result = False, False, False, "NotInSig" ret, output = run( "fxc %s /E %s /T %s /D%s_Defs=Def_%s" % (hlsl_filename, entry, target, sigpoint, sv), output_filename, ) if ret: # Failed, look for expected error message: found = ParseSVError(output, "SV_" + sv) if found == "InternalError": table[row][col] = "InternalError" print( '#### Internal error from ParseSVError - see "%s"' % output_filename ) elif not found: table[row][col] = "ParseSVError" print('#### Error from ParseSVError - see "%s"' % output_filename) else: table[row][col] = "NA" if os.path.isfile(output_filename): os.unlink(output_filename) continue parse_result = ParseSigs(output, "SV_" + sv) if parse_result: separate_reg, as_arb = parse_result if as_arb: if separate_reg: table[row][col] = "Error: both as_arb and separate_reg set!" print( '#### Error from ParseSigs, both as_arb and separate_reg set - see "%s"' % output_filename ) continue result = "Arb" else: if separate_reg: result = "NotPacked" else: result = "SV" if os.path.isfile(output_filename): os.unlink(output_filename) else: print('## Not in signature? See "%s"' % output_filename) if arb_supported and not as_arb and not separate_reg: output_filename = "output\\test_sv_output_last_%s_%s_%s.txt" % ( sm, sv, sigpoint, ) # must system value be declared last? test by adding arb last if arb support ret, output = run( 'fxc %s /E %s /T %s /D%s_Defs="Def_%s Def_Arb(float,Arb1,Arb1)"' % (hlsl_filename, entry, target, sigpoint, sv), output_filename, ) if ret: found = ParseSGVError(output, "SV_" + sv) if found == "InternalError": result += " | InternalError found with ParseSGVError" print( '#### Internal error from ParseSGVError - see "%s"' % output_filename ) elif not found: result += " | ParseSGVError" print( '#### Error from ParseSGVError - see "%s"' % output_filename ) elif result == "SV": result = "SGV" if os.path.isfile(output_filename): os.unlink(output_filename) else: result += " | Error: last required detected, but not SV?" print( '#### Error: last required detected, but not SV? - see "%s"' % output_filename ) else: if os.path.isfile(output_filename): os.unlink(output_filename) table[row][col] = result for row in range(row + 1, len(SysValues)): table[row][col] = "TessFactor" def WriteTable(writefn, table): writefn( "Semantic," + ",".join([sigpoint for sigpoint, stage, tfpresent in SignaturePoints]) + "\n" ) for n, row in enumerate(table): writefn((SysValues[n]) + ",".join(row) + "\n") WriteTable(sys.stdout.write, table) with open("fxc_sig_packing_table_%s.csv" % sm, "wt") as f: WriteTable(f.write, table) if __name__ == "__main__": main()
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/hct/hctversion.txt
1.0
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/hct/query.py
from hctdb_instrhelp import get_db_dxil from hctdb_instrhelp import get_db_hlsl import argparse # user defined function def inst_query_dxil(insts, inst): # example if inst.ret_type == "v" and inst.fn_attr != "": return True return False # example """ if inst.fn_attr == "" and "Quad" in inst.name: found = false for other_inst in insts: if not (other_inst == inst) and "Quad" in other_inst.name and other_inst.fn_attr != "" found = true break return found return false """ def inst_query_hlsl(insts, inst): # example """ if inst.ret_type == "v": return true return false """ # example """ if inst.fn_attr == "" and "Quad" in inst.name: found = false for other_inst in insts: if not (other_inst == inst) and "Quad" in other_inst.name and other_inst.fn_attr != "" found = true break return found return false """ # example if inst.wave: return True return False class DxilInstructionWrapper: def set_ret_type_and_args(self, dxil_inst): ops = [] for op in dxil_inst.ops: ops.append(op.llvm_type) if len(ops) > 0: self.ret_type = ops[0] if len(ops) > 1: self.args = ops[1:] def __init__(self, dxil_inst): self.dxil_inst = dxil_inst # db_dxil_inst type, defined in hctdb.py self.name = dxil_inst.name self.fn_attr = dxil_inst.fn_attr self.wave = dxil_inst.is_wave # bool self.ret_type = "" self.args = [] self.set_ret_type_and_args(dxil_inst) def __str__(self): str_args = ", ".join(self.args) return "[{}] {} {}({})".format(self.fn_attr, self.ret_type, self.name, str_args) class HLOperationWrapper: def set_ret_type_and_args(self, hl_op): ops = hl_op.params if len(ops) > 0: self.ret_type = ops[0].type_name if len(ops) > 1: self.args = [x.name + " " + x.type_name for x in ops[1:]] def __init__(self, hl_op): self.hl_op = hl_op # db_hlsl_intrinsic type, defined in hctdb.py self.name = hl_op.name self.fn_attr = "rn" if hl_op.readnone else "" self.fn_attr += "ro" if hl_op.readonly else "" self.wave = hl_op.wave # bool self.ret_type = "" self.args = [] self.set_ret_type_and_args(hl_op) def __str__(self): str_args = ", ".join(self.args) return "[{}] {} {}({})".format(self.fn_attr, self.ret_type, self.name, str_args) def parse_query_hlsl(db, options): HLInstructions = [] # The query function should be using the HLOperationWrapper interface # because that is what's being loaded into the instructions list. for hl_op in db.intrinsics: new_op = HLOperationWrapper(hl_op) HLInstructions.append(new_op) # apply the query filter print("\nQUERY RESULTS:\n") for instruction in HLInstructions: if inst_query_hlsl(HLInstructions, instruction): print(instruction) def parse_query_dxil(db, options): DxilInstructions = [] # The query function should use the DxilInstructionWrapper interface # because that's what's being loaded into the DxilInstructions list for dxil_inst in db.instr: i = DxilInstructionWrapper(dxil_inst) DxilInstructions.append(i) # apply the query filter print("\nQUERY RESULTS:\n") for instruction in DxilInstructions: if inst_query_dxil(DxilInstructions, instruction): print(instruction) parser = argparse.ArgumentParser(description="Query instructions.") parser.add_argument( "-query", choices=["dxil", "hlsl"], help="type of instructions to query." ) args = parser.parse_args() if args.query == "dxil": db_dxil = get_db_dxil() parse_query_dxil(db_dxil, args) if args.query == "hlsl": db_hlsl = get_db_hlsl() parse_query_hlsl(db_hlsl, args)
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/hct/hctdb_inst_docs.txt
# Extended documenation for DXIL instructions. # # File format: # * Inst: [instruction name] - [brief description] # further remarks # # Keep these ordered alphabetically for ease of maintenance. # # Dump instructions with no extra documentation with this snippet. # import hctdb # h = hctdb.db_dxil() # for i in [item.name for item in h.instr if item.is_dxil_op and not item.remarks]: print(i) * Inst: Acos - Returns the arccosine of the specified value. Input should be a floating-point value within the range of -1 to 1. The return value is within the range of -PI/2 to PI/2. +----------+------+--------------+---------+------+------+---------+------+-----+ | src | -inf | [-1,1] | -denorm | -0 | +0 | +denorm | +inf | NaN | +----------+------+--------------+---------+------+------+---------+------+-----+ | acos(src)| NaN | (-PI/2,+PI/2)| PI/2 | PI/2 | PI/2 | PI/2 | NaN | NaN | +----------+------+--------------+---------+------+------+---------+------+-----+ * Inst: Asin - Returns the arccosine of the specified value. Input should be a floating-point value within the range of -1 to 1 The return value is within the range of -PI/2 to PI/2. +----------+------+--------------+---------+------+------+---------+------+-----+ | src | -inf | [-1,1] | -denorm | -0 | +0 | +denorm | +inf | NaN | +----------+------+--------------+---------+------+------+---------+------+-----+ | asin(src)| NaN | (-PI/2,+PI/2)| 0 | 0 | 0 | 0 | NaN | NaN | +----------+------+--------------+---------+------+------+---------+------+-----+ * Inst: Atan - Returns the arctangent of the specified value. The return value is within the range of -PI/2 to PI/2. +----------+------+--------------+---------+------+------+---------+---------------+-----+-----+ | src | -inf | -F | -denorm | -0 | +0 | +denorm | +F |+inf | NaN | +----------+------+--------------+---------+------+------+---------+---------------+-----+-----+ | atan(src)| -PI/2| (-PI/2,+PI/2)| 0 | 0 | 0 | 0 | (-PI/2,+PI/2) |PI/2 | NaN | +----------+------+--------------+---------+------+------+---------+---------------+-----+-----+ Returns the arctangent of the specified value. The return value is within the range of -PI/2 to PI/2 * Inst: Bfrev - Reverses the order of the bits. Reverses the order of the bits. For example given 0x12345678 the result would be 0x1e6a2c48. * Inst: Bfi - Given a bit range from the LSB of a number, places that number of bits in another number at any offset Given a bit range from the LSB of a number, place that number of bits in another number at any offset. dst = Bfi(src0, src1, src2, src3); The LSB 5 bits of src0 provide the bitfield width (0-31) to take from src2. The LSB 5 bits of src1 provide the bitfield offset (0-31) to start replacing bits in the number read from src3. Given width, offset: bitmask = (((1 << width)-1) << offset) & 0xffffffff, dest = ((src2 << offset) & bitmask) | (src3 & ~bitmask) * Inst: Cos - returns cosine(theta) for theta in radians. Theta values can be any IEEE 32-bit floating point values. The maximum absolute error is 0.0008 in the interval from -100*Pi to +100*Pi. +----------+------+------------+---------+----+----+---------+------------+------+-----+ | src | -inf | -F | -denorm | -0 | +0 | +denorm | +F | +inf | NaN | +----------+------+------------+---------+----+----+---------+------------+------+-----+ | cos(src) | NaN | [-1 to +1] | +1 | +1 | +1 | +1 | [-1 to +1] | NaN | NaN | +----------+------+------------+---------+----+----+---------+------------+------+-----+ * Inst: Countbits - Counts the number of bits in the input integer. Counts the number of bits in the input integer. * Inst: DerivCoarseX - computes the rate of change per stamp in x direction. dst = DerivCoarseX(src); Computes the rate of change per stamp in x direction. Only a single x derivative pair is computed for each 2x2 stamp of pixels. The data in the current Pixel Shader invocation may or may not participate in the calculation of the requested derivative, given the derivative will be calculated only once per 2x2 quad: As an example, the x derivative could be a delta from the top row of pixels. The exact calculation is up to the hardware vendor. There is also no specification dictating how the 2x2 quads will be aligned/tiled over a primitive. * Inst: DerivCoarseY - computes the rate of change per stamp in y direction. dst = DerivCoarseY(src); Computes the rate of change per stamp in y direction. Only a single y derivative pair is computed for each 2x2 stamp of pixels. The data in the current Pixel Shader invocation may or may not participate in the calculation of the requested derivative, given the derivative will be calculated only once per 2x2 quad: As an example, the y derivative could be a delta from the left column of pixels. The exact calculation is up to the hardware vendor. There is also no specification dictating how the 2x2 quads will be aligned/tiled over a primitive. * Inst: DerivFineX - computes the rate of change per pixel in x direction. dst = DerivFineX(src); Computes the rate of change per pixel in x direction. Each pixel in the 2x2 stamp gets a unique pair of x derivative calculations The data in the current Pixel Shader invocation always participates in the calculation of the requested derivative. There is no specification dictating how the 2x2 quads will be aligned/tiled over a primitive. * Inst: DerivFineY - computes the rate of change per pixel in y direction. dst = DerivFineY(src); Computes the rate of change per pixel in y direction. Each pixel in the 2x2 stamp gets a unique pair of y derivative calculations The data in the current Pixel Shader invocation always participates in the calculation of the requested derivative. There is no specification dictating how the 2x2 quads will be aligned/tiled over a primitive. * Inst: Dot2 - Two-dimensional vector dot-product Two-dimensional vector dot-product * Inst: Dot3 - Three-dimensional vector dot-product Three-dimensional vector dot-product * Inst: Dot4 - Four-dimensional vector dot-product Four-dimensional vector dot-product * Inst: Exp - returns 2^exponent Returns 2^exponent. Note that hlsl log intrinsic returns the base-e exponent. Maximum relative error is e^-21. +----------+------+------------+---------+----+----+---------+------------+------+-----+ | src | -inf | -F | -denorm | -0 | +0 | +denorm | +F | +inf | NaN | +----------+------+------------+---------+----+----+---------+------------+------+-----+ | exp(src) | 0 | +F | 1 | 1 | 1 | 1 | +F | +inf | NaN | +----------+------+------------+---------+----+----+---------+------------+------+-----+ * Inst: FAbs - returns the absolute value of the input value. The FAbs instruction takes simply forces the sign of the number(s) on the source operand positive, including on INF and denorm values. Applying FAbs on NaN preserves NaN, although the particular NaN bit pattern that results is not defined. * Inst: FirstbitHi - Returns the location of the first set bit starting from the highest order bit and working downward. Returns the integer position of the first bit set in the 32-bit input starting from the MSB. For example, 0x10000000 would return 3. Returns 0xffffffff if no match was found. * Inst: FirstbitLo - Returns the location of the first set bit starting from the lowest order bit and working upward. Returns the integer position of the first bit set in the 32-bit input starting from the LSB. For example, 0x00000000 would return 1. Returns 0xffffffff if no match was found. * Inst: FirstbitSHi - Returns the location of the first set bit from the highest order bit based on the sign. Returns the first 0 from the MSB if the number is negative, else the first 1 from the MSB. Returns 0xffffffff if no match was found. * Inst: Fma - fused multiply-add Fused multiply-add. This operation is only defined in double precision. Fma(a,b,c) = a * b + c * Inst: FMad - floating point multiply & add Floating point multiply & add. This operation is not fused for "precise" operations. FMad(a,b,c) = a * b + c * Inst: FMax - returns a if a >= b, else b >= is used instead of > so that if min(x,y) = x then max(x,y) = y. NaN has special handling: If one source operand is NaN, then the other source operand is returned. If both are NaN, any NaN representation is returned. This conforms to new IEEE 754R rules. Denorms are flushed (sign preserved) before comparison, however the result written to dest may or may not be denorm flushed. +------+-----------------------------+ | a | b | | +------+--------+------+------+ | | -inf | F | +inf | NaN | +------+------+--------+------+------+ | -inf | -inf | b | +inf | -inf | +------+------+--------+------+------+ | F | a | a or b | +inf | a | +------+------+--------+------+------+ | +inf | +inf | +inf | +inf | +inf | +------+------+--------+------+------+ | NaN | -inf | b | +inf | NaN | +------+------+--------+------+------+ * Inst: FMin - returns a if a < b, else b NaN has special handling: If one source operand is NaN, then the other source operand is returned. If both are NaN, any NaN representation is returned. This conforms to new IEEE 754R rules. Denorms are flushed (sign preserved) before comparison, however the result written to dest may or may not be denorm flushed. +------+-----------------------------+ | a | b | | +------+--------+------+------+ | | -inf | F | +inf | NaN | +------+------+--------+------+------+ | -inf | -inf | -inf | -inf | -inf | +------+------+--------+------+------+ | F | -inf | a or b | a | a | +------+------+--------+------+------+ | +inf | -inf | b | +inf | +inf | +------+------+--------+------+------+ | NaN | -inf | b | +inf | NaN | +------+------+--------+------+------+ * Inst: Frc - extract fracitonal component. +--------------+------+------+---------+----+----+---------+--------+------+-----+ | src | -inf | -F | -denorm | -0 | +0 | +denorm | +F | +inf | NaN | +--------------+------+------+---------+----+----+---------+--------+------+-----+ | log(src) | NaN |[+0,1)| +0 | +0 | +0 | +0 | [+0,1) | NaN | NaN | +--------------+------+------+---------+----+----+---------+--------+------+-----+ * Inst: Hcos - returns the hyperbolic cosine of the specified value. Returns the hyperbolic cosine of the specified value. +----------+------+------------+---------+----+----+---------+------------+------+-----+ | src | -inf | -F | -denorm | -0 | +0 | +denorm | +F | +inf | NaN | +----------+------+------------+---------+----+----+---------+------------+------+-----+ | hcos(src)| +inf | (1, +inf) | +1 | +1 | +1 | +1 | (1, +inf) | +inf | NaN | +----------+------+------------+---------+----+----+---------+------------+------+-----+ * Inst: Hsin - returns the hyperbolic sine of the specified value. Returns the hyperbolic sine of the specified value. +----------+------+------------+---------+----+----+---------+------------+------+-----+ | src | -inf | -F | -denorm | -0 | +0 | +denorm | +F | +inf | NaN | +----------+------+------------+---------+----+----+---------+------------+------+-----+ | hsin(src)| -inf | -F | 0 | 0 | 0 | 0 | +F | +inf | NaN | +----------+------+------------+---------+----+----+---------+------------+------+-----+ * Inst: Htan - returns the hyperbolic tangent of the specified value. Returns the hyperbolic tangent of the specified value. +----------+------+------------+---------+----+----+---------+------------+------+-----+ | src | -inf | -F | -denorm | -0 | +0 | +denorm | +F | +inf | NaN | +----------+------+------------+---------+----+----+---------+------------+------+-----+ | htan(src)| -1 | -F | 0 | 0 | 0 | 0 | +F | +1 | NaN | +----------+------+------------+---------+----+----+---------+------------+------+-----+ * Inst: Ibfe - Integer bitfield extract dest = Ibfe(src0, src1, src2) Given a range of bits in a number, shift those bits to the LSB and sign extend the MSB of the range. width : The LSB 5 bits of src0 (0-31). offset: The LSB 5 bits of src1 (0-31) * BLOCK-BEGIN .. code:: c if( width == 0 ) { dest = 0 } else if( width + offset < 32 ) { shl dest, src2, 32-(width+offset) ishr dest, dest, 32-width } else { ishr dest, src2, offset } * BLOCK-END * Inst: IMad - Signed integer multiply & add Signed integer multiply & add IMad(a,b,c) = a * b + c * Inst: IMax - IMax(a,b) returns a if a > b, else b IMax(a,b) returns a if a > b, else b. Optional negate modifier on source operands takes 2's complement before performing operation. * Inst: IMin - IMin(a,b) returns a if a < b, else b IMin(a,b) returns a if a < b, else b. Optional negate modifier on source operands takes 2's complement before performing operation. * Inst: IMul - multiply of 32-bit operands to produce the correct full 64-bit result. IMul(src0, src1) = destHi, destLo multiply of 32-bit operands src0 and src1 (note they are signed), producing the correct full 64-bit result. The low 32 bits are placed in destLO. The high 32 bits are placed in destHI. Either of destHI or destLO may be specified as NULL instead of specifying a register, in the case high or low 32 bits of the 64-bit result are not needed. Optional negate modifier on source operands takes 2's complement before performing arithmetic operation. * Inst: IsFinite - Returns true if x is finite, false otherwise. Returns true if x is finite, false otherwise. * Inst: IsInf - Returns true if x is +INF or -INF, false otherwise. Returns true if x is +INF or -INF, false otherwise. * Inst: IsNaN - Returns true if x is NAN or QNAN, false otherwise. Returns true if x is NAN or QNAN, false otherwise. * Inst: IsNormal - returns IsNormal Returns IsNormal. * Inst: Log - returns log base 2. Returns log base 2. Note that hlsl log intrinsic returns natural log. +----------+------+------------+---------+----+----+---------+------------+------+-----+ | src | -inf | -F | -denorm | -0 | +0 | +denorm | +F | +inf | NaN | +----------+------+------------+---------+----+----+---------+------------+------+-----+ | log(src) | NaN | NaN | -inf |-inf|-inf| -inf | F | +inf | NaN | +----------+------+------------+---------+----+----+---------+------------+------+-----+ * Inst: LoadInput - Loads the value from shader input Loads the value from shader input * Inst: MinPrecXRegLoad - Helper load operation for minprecision Helper load operation for minprecision * Inst: MinPrecXRegStore - Helper store operation for minprecision Helper store operation for minprecision * Inst: Msad - masked Sum of Absolute Differences. Returns the masked Sum of Absolute Differences. dest = msad(ref, src, accum) ref: contains 4 packed 8-bit unsigned integers in 32 bits. src: contains 4 packed 8-bit unsigned integers in 32 bits. accum: a 32-bit unsigned integer, providing an existing accumulation. dest receives the result of the masked SAD operation added to the accumulation value. * BLOCK-BEGIN .. code:: c UINT msad( UINT ref, UINT src, UINT accum ) { for (UINT i = 0; i < 4; i++) { BYTE refByte, srcByte, absDiff; refByte = (BYTE)(ref >> (i * 8)); if (!refByte) { continue; } srcByte = (BYTE)(src >> (i * 8)); if (refByte >= srcByte) { absDiff = refByte - srcByte; } else { absDiff = srcByte - refByte; } // The recommended overflow behavior for MSAD is // to do a 32-bit saturate. This is not // required, however, and wrapping is allowed. // So from an application point of view, // overflow behavior is undefined. if (UINT_MAX - accum < absDiff) { accum = UINT_MAX; break; } accum += absDiff; } return accum; } * BLOCK-END * Inst: Round_ne - floating-point round to integral float. Floating-point round of the values in src, writing integral floating-point values to dest. round_ne rounds towards nearest even. For halfway, it rounds away from zero. +--------------+------+----+---------+----+----+---------+----+------+-----+ | src | -inf | -F | -denorm | -0 | +0 | +denorm | +F | +inf | NaN | +--------------+------+----+---------+----+----+---------+----+------+-----+ | round_ne(src)| -inf | -F | -0 | -0 | +0 | +0 | +F | +inf | NaN | +--------------+------+----+---------+----+----+---------+----+------+-----+ * Inst: Round_ni - floating-point round to integral float. Floating-point round of the values in src, writing integral floating-point values to dest. round_ni rounds towards -INF, commonly known as floor(). +--------------+------+----+---------+----+----+---------+----+------+-----+ | src | -inf | -F | -denorm | -0 | +0 | +denorm | +F | +inf | NaN | +--------------+------+----+---------+----+----+---------+----+------+-----+ | round_ni(src)| -inf | -F | -0 | -0 | +0 | +0 | +F | +inf | NaN | +--------------+------+----+---------+----+----+---------+----+------+-----+ * Inst: Round_pi - floating-point round to integral float. Floating-point round of the values in src, writing integral floating-point values to dest. round_pi rounds towards +INF, commonly known as ceil(). +--------------+------+----+---------+----+----+---------+----+------+-----+ | src | -inf | -F | -denorm | -0 | +0 | +denorm | +F | +inf | NaN | +--------------+------+----+---------+----+----+---------+----+------+-----+ | round_pi(src)| -inf | -F | -0 | -0 | +0 | +0 | +F | +inf | NaN | +--------------+------+----+---------+----+----+---------+----+------+-----+ * Inst: Round_z - floating-point round to integral float. Floating-point round of the values in src, writing integral floating-point values to dest. round_z rounds towards zero. +--------------+------+----+---------+----+----+---------+----+------+-----+ | src | -inf | -F | -denorm | -0 | +0 | +denorm | +F | +inf | NaN | +--------------+------+----+---------+----+----+---------+----+------+-----+ | round_z(src) | -inf | -F | -0 | -0 | +0 | +0 | +F | +inf | NaN | +--------------+------+----+---------+----+----+---------+----+------+-----+ * Inst: Rsqrt- returns reciprocal square root (1 / sqrt(src) Maximum relative error is 2^21. +--------------+------+----+---------+----+----+---------+----+------+-----+ | src | -inf | -F | -denorm | -0 | +0 | +denorm | +F | +inf | NaN | +--------------+------+----+---------+----+----+---------+----+------+-----+ | rsqrt(src) | -inf | -F | -0 | -0 | +0 | +0 | +F | +inf | NaN | +--------------+------+----+---------+----+----+---------+----+------+-----+ * Inst: Saturate - clamps the result of a single or double precision floating point value to [0.0f...1.0f] The Saturate instruction performs the following operation on its input value: min(1.0f, max(0.0f, value)) where min() and max() in the above expression behave in the way Min and Max behave. Saturate(NaN) returns 0, by the rules for min and max. * Inst: Sin - returns sine(theta) for theta in radians. Theta values can be any IEEE 32-bit floating point values. The maximum absolute error is 0.0008 in the interval from -100*Pi to +100*Pi. +----------+------+------------+---------+----+----+---------+------------+------+-----+ | src | -inf | -F | -denorm | -0 | +0 | +denorm | +F | +inf | NaN | +----------+------+------------+---------+----+----+---------+------------+------+-----+ | sin(src) | NaN | [-1 to +1] | -0 | -0 | +0 | +0 | [-1 to +1] | NaN | NaN | +----------+------+------------+---------+----+----+---------+------------+------+-----+ * Inst: Sqrt - returns square root Precision is 1 ulp. +--------------+------+----+---------+----+----+---------+----+------+-----+ | src | -inf | -F | -denorm | -0 | +0 | +denorm | +F | +inf | NaN | +--------------+------+----+---------+----+----+---------+----+------+-----+ | sqrt(src) | NaN | NaN| -0 | -0 | +0 | +0 | +F | +inf | NaN | +--------------+------+----+---------+----+----+---------+----+------+-----+ * Inst: StoreOutput - Stores the value to shader output Stores the value to shader output * Inst: Tan - returns tan(theta) for theta in radians. Theta values can be any IEEE 32-bit floating point values. +----------+----------+----------------+---------+----+----+---------+----------------+------+-----+ | src | -inf | -F | -denorm | -0 | +0 | +denorm | +F | +inf | NaN | +----------+----------+----------------+---------+----+----+---------+----------------+------+-----+ | tan(src) | NaN | [-inf to +inf] | -0 | -0 | +0 | +0 | [-inf to +inf] | NaN | NaN | +----------+----------+----------------+---------+----+----+---------+----------------+------+-----+ * Inst: TempRegLoad - Helper load operation Helper load operation * Inst: TempRegStore - Helper store operation Helper store operation * Inst: UAddc - unsigned add of 32-bit operand with the carry dest0, dest1 = UAddc(src0, src1) unsigned add of 32-bit operands src0 and src1, placing the LSB part of the 32-bit result in dest0. dest1 is written with: 1 if a carry is produced, 0 otherwise. Dest1 can be NULL if the carry is not needed * Inst: Ubfe - Unsigned integer bitfield extract dest = ubfe(src0, src1, src2) Given a range of bits in a number, shift those bits to the LSB and set remaining bits to 0. width : The LSB 5 bits of src0 (0-31). offset: The LSB 5 bits of src1 (0-31). Given width, offset: * BLOCK-BEGIN .. code:: c if( width == 0 ) { dest = 0 } else if( width + offset < 32 ) { shl dest, src2, 32-(width+offset) ushr dest, dest, 32-width } else { ushr dest, src2, offset } * BLOCK-END * Inst: UDiv - unsigned divide of the 32-bit operand src0 by the 32-bit operand src1. destQUOT, destREM = UDiv(src0, src1); unsigned divide of the 32-bit operand src0 by the 32-bit operand src1. The results of the divides are the 32-bit quotients (placed in destQUOT) and 32-bit remainders (placed in destREM). Divide by zero returns 0xffffffff for both quotient and remainder. Either destQUOT or destREM may be specified as NULL instead of specifying a register, in the case the quotient or remainder are not needed. Unsigned subtract of 32-bit operands src1 from src0, placing the LSB part of the 32-bit result in dest0. dest1 is written with: 1 if a borrow is produced, 0 otherwise. Dest1 can be NULL if the borrow is not needed * Inst: UMad - Unsigned integer multiply & add Unsigned integer multiply & add. Umad(a,b,c) = a * b + c * Inst: UMax - unsigned integer maximum. UMax(a,b) = a > b ? a : b unsigned integer maximum. UMax(a,b) = a > b ? a : b * Inst: UMin - unsigned integer minimum. UMin(a,b) = a < b ? a : b unsigned integer minimum. UMin(a,b) = a < b ? a : b * Inst: UMul - multiply of 32-bit operands to produce the correct full 64-bit result. multiply of 32-bit operands src0 and src1 (note they are unsigned), producing the correct full 64-bit result. The low 32 bits are placed in destLO. The high 32 bits are placed in destHI. Either of destHI or destLO may be specified as NULL instead of specifying a register, in the case high or low 32 bits of the 64-bit result are not needed * Inst: USubb - unsigned subtract of 32-bit operands with the borrow dest0, dest1 = USubb(src0, src1) * Inst: AttributeAtVertex - returns the values of the attributes at the vertex. returns the values of the attributes at the vertex. VertexID ranges from 0 to 2. * Inst: FDiv - returns the quotient of its two operands %dest = fdiv float %src0, %src1 The following table shows the results obtained when executing the instruction with various classes of numbers, assuming that fast math flag is not used and "fp32-denorm-mode"="preserve". When "fp32-denorm-mode"="ftz", denorm inputs should be interpreted as corresponding signed zero, and any resulting denorm is also flushed to zero. When fast math is enabled, implementation may use reciprocal form: src0*(1/src1). This may result in evaluating src0*(+/-)INF from src0*(1/(+/-)denorm). This may produce NaN in some cases or (+/-)INF in others. +-----------+----------+--------+-------+---------+----+----+---------+-------+--------+------+-----+ | src0\\src1| -inf | -F | -1 | -denorm | -0 | +0 | +denorm | +1 | +F | +inf | NaN | +-----------+----------+--------+-------+---------+----+----+---------+-------+--------+------+-----+ | -inf | NaN | +inf | +inf | +inf |+inf|-inf| -inf | -inf | -inf | NaN | NaN | +-----------+----------+--------+-------+---------+----+----+---------+-------+--------+------+-----+ | -F | +0 | +F | -src0 | +F |+inf|-inf| -F | src0 | -F | -0 | NaN | +-----------+----------+--------+-------+---------+----+----+---------+-------+--------+------+-----+ | -denorm | +0 | +denorm| -src0 | +F |+inf|-inf| -F | src0 |-denorm | -0 | NaN | +-----------+----------+--------+-------+---------+----+----+---------+-------+--------+------+-----+ | -0 | +0 | +0 | +0 | 0 |NaN |NaN | 0 | -0 | -0 | -0 | NaN | +-----------+----------+--------+-------+---------+----+----+---------+-------+--------+------+-----+ | +0 | -0 | -0 | -0 | 0 |NaN |NaN | 0 | +0 | +0 | +0 | NaN | +-----------+----------+--------+-------+---------+----+----+---------+-------+--------+------+-----+ | +denorm | -0 | -denorm| -src0 | -F |-inf|+inf| +F | src0 |+denorm | +0 | NaN | +-----------+----------+--------+-------+---------+----+----+---------+-------+--------+------+-----+ | +F | -0 | -F | -src0 | -F |-inf|+inf| +F | src0 | +F | +0 | NaN | +-----------+----------+--------+-------+---------+----+----+---------+-------+--------+------+-----+ | +inf | NaN | -inf | -inf | -inf |-inf|+inf| +inf | +inf | +inf | NaN | NaN | +-----------+----------+--------+-------+---------+----+----+---------+-------+--------+------+-----+ | NaN | NaN | NaN | NaN | NaN |NaN |NaN | NaN | NaN | NaN | NaN | NaN | +-----------+----------+--------+-------+---------+----+----+---------+-------+--------+------+-----+ * Inst: FAdd - component-wise add %des = fadd float %src0, %src1 The following table shows the results obtained when executing the instruction with various classes of numbers, assuming that "fp32-denorm-mode"="preserve". For "fp32-denorm-mode"="ftz" mode, denorms inputs should be treated as corresponding signed zero, and any resulting denorm is also flushed to zero. +----------+----------+--------+----------+----+----+-----------+--------+------+-----+ | src0\src1| -inf | -F | -denorm | -0 | +0 | +denorm | +F | +inf | NaN | +----------+----------+--------+----------+----+----+-----------+--------+------+-----+ | -inf | -inf | -inf | -inf |-inf|-inf| -inf | -inf | NaN | NaN | +----------+----------+--------+----------+----+----+-----------+--------+------+-----+ | -F | -inf | -F | -F |src0|src0| -F | +/-F | +inf | NaN | +----------+----------+--------+----------+----+----+-----------+--------+------+-----+ | -denorm | -inf | -F |-F/denorm |src0|src0| +/-denorm | +F | +inf | NaN | +----------+----------+--------+----------+----+----+-----------+--------+------+-----+ | -0 | -inf | src1 | src1 |-0 |+0 | src1 | src1 | +inf | NaN | +----------+----------+--------+----------+----+----+-----------+--------+------+-----+ | +0 | -inf | src1 | src1 |-0 |+0 | src1 | src1 | +inf | NaN | +----------+----------+--------+----------+----+----+-----------+--------+------+-----+ | +denorm | -inf | -F |+/-denorm |src0|src0| +F/denorm | +F | +inf | NaN | +----------+----------+--------+----------+----+----+-----------+--------+------+-----+ | +F | -inf | +/-F | +F |src0|src0| +F | +F | +inf | NaN | +----------+----------+--------+----------+----+----+-----------+--------+------+-----+ | +inf | NaN | +inf | +inf |+inf|+inf| +inf | +inf | +inf | NaN | +----------+----------+--------+----------+----+----+-----------+--------+------+-----+ | NaN | NaN | NaN | NaN |NaN |NaN | NaN | NaN | NaN | NaN | +----------+----------+--------+----------+----+----+-----------+--------+------+-----+
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/hct/hctgettaef.py
import urllib.request import os import ssl import zipfile url = "https://github.com/Microsoft/WinObjC/raw/develop/deps/prebuilt/nuget/taef.redist.wlk.1.0.170206001-nativetargets.nupkg" zipfile_name = os.path.join( os.environ["TEMP"], "taef.redist.wlk.1.0.170206001-nativetargets.nupkg.zip" ) src_dir = os.environ["HLSL_SRC_DIR"] taef_dir = os.path.join(src_dir, "external", "taef") os.makedirs(taef_dir, exist_ok=True) try: ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) response = urllib.request.urlopen(url, context=ctx) f = open(zipfile_name, "wb") f.write(response.read()) f.close() except: print("Unable to read file with urllib, trying via powershell...") from subprocess import check_call cmd = "" cmd += "[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12;" cmd += ( "(new-object System.Net.WebClient).DownloadFile('" + url + "', '" + zipfile_name + "')" ) check_call(["powershell.exe", "-Command", cmd]) z = zipfile.ZipFile(zipfile_name) z.extractall(taef_dir) z.close()
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/hct/hcttodo.js
/////////////////////////////////////////////////////////////////////////////// // // // hcttodo.js // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // /////////////////////////////////////////////////////////////////////////////// // // Verifies that all TODO comments have some explanation. // eval(new ActiveXObject("Scripting.FileSystemObject").OpenTextFile(new ActiveXObject("WScript.Shell").ExpandEnvironmentStrings("%HLSL_SRC_DIR%\\utils\\hct\\hctjs.js"), 1).ReadAll()); // It would be nice to tag with issue numbers. // var goodToDoLine = /TODO: HLSL #[0-9]+ - [0-9a-zA-Z]+/; var goodToDoLine = /TODO: HLSL #[0-9]+ - [0-9a-zA-Z]+/; var fileExts = [ ".c", ".cpp", ".h", ".td", ".cs", ".hlsl", ".fx" ]; function CountBadTodoLines(files) { var badTodoCount = 0; for (var i = 0; i < files.length; i++) { var path = files[i]; var extension = PathGetExtension(path).toLowerCase(); if (ArrayIndexOf(fileExts, extension) >= 0) { var content = ReadAllTextFile(path); var lines = StringSplit(content, "\n"); for (var j = 0; j < lines.length; j++) { var line = lines[j]; var todoIndex = line.indexOf("TODO"); if (todoIndex !== -1) { // if (!goodToDoLine.exec(line)) { WScript.Echo(path + "(" + (j+1) + ":" + (todoIndex+1) + "): " + lines[j]); // badTodoCount += 1; // } } } } } return badTodoCount; } function ExpandPath(path) { return new ActiveXObject("WScript.Shell").ExpandEnvironmentStrings(path); } var ignorePaths = [ "%HLSL_SRC_DIR%\\lib\\target\\hexagon", "%HLSL_SRC_DIR%\\lib\\executionengine", "%HLSL_SRC_DIR%\\lib\\target\\arm", "%HLSL_SRC_DIR%\\lib\\target\\mips", "%HLSL_SRC_DIR%\\lib\\target\\nvptx", "%HLSL_SRC_DIR%\\lib\\target\\r600", "%HLSL_SRC_DIR%\\lib\\target\\powerpc", "%HLSL_SRC_DIR%\\lib\\target\\x86", "%HLSL_SRC_DIR%\\lib\\target\\xcore" ]; ignorePaths = ArraySelect(ignorePaths, function(path) { return StringToLower(ExpandPath(path)); }); var files = GetFilesRecursive(ExpandPath("%HLSL_SRC_DIR%")); files = ArraySelectMany(files, function (path) { path = StringToLower(path); if (ArrayAny(ignorePaths, function (ignore) { return path.indexOf(ignore) === 0; })) { return []; } else { return [path]; } }); var counts = CountBadTodoLines(files); // Fail on any bad TODO lines. if (counts !== 0) { WScript.Echo("Badly formatted TODO comments found in " + files.length + " files: " + counts); WScript.Echo("\nFormat should be something like this, with the right number and description (spaces and symbols enforced for consistency)."); WScript.Echo(" // TODO: HLSL #123 - description"); WScript.Quit(1); } else { WScript.Echo("No badly formatted TODO comments found in " + files.length + " files."); WScript.Quit(0); }
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/hct/hctspeak.js
/////////////////////////////////////////////////////////////////////////////// // // // hctspeak.js // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // /////////////////////////////////////////////////////////////////////////////// // This script uses the Speech API to speak to the user. // // Useful for batch scripts or typing on the command-line to compensate for // short attention spans (or multitasking). // // Usage: // hctspeak.js -- says 'Task complete' // hctspeak.js /say:"Hello, world!" -- says 'Hello, world!' eval(new ActiveXObject("Scripting.FileSystemObject").OpenTextFile(new ActiveXObject("WScript.Shell").ExpandEnvironmentStrings("%HLSL_SRC_DIR%\\utils\\hct\\hctjs.js"), 1).ReadAll()); var text = WScript.Arguments.Named.Item("say"); if (text == null) { if (WScript.Arguments.Unnamed.length === 1) { text = WScript.Arguments.Unnamed.Item(0); } else { text = "Task complete"; } } Say(text);
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/hct/ExtractIRForPassTest.py
#! /usr/bin/env python3 """ExtractIRForPassTest.py - extract IR just before selected pass would be run. This script automates some operations to make it easier to write IR tests: 1. Gets the pass list for an HLSL compilation using -Odump 2. Compiles HLSL with -fcgl and outputs to intermediate IR 3. Collects list of passes before the desired pass and adds -hlsl-passes-pause to write correct metadata 4. Invokes dxopt to run passes on -fcgl output and write bitcode result 5. Disassembles bitcode to .ll file for use as a test 6. Inserts RUN line with -hlsl-passes-resume and desired pass Examples: ExtractIRForPassTest.py -p scalarrepl-param-hlsl -o my_test.ll my_test.hlsl -- -T cs_6_0 -Od - stop before 'scalarrepl-param-hlsl' pass; output to my_test.ll ExtractIRForPassTest.py -p simplifycfg -n 2 -o my_test.ll my_test.hlsl -- -T cs_6_0 - stop before the second invocation of 'simplifycfg' pass Use dxc with -Odump to dump the pass sequence for reference. """ import os import sys import subprocess import tempfile import argparse def ParseArgs(): parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description=__doc__ ) parser.add_argument( "-p", dest="desired_pass", metavar="<desired-pass>", required=True, help="stop before this module pass (per-function prepass not supported).", ) parser.add_argument( "-n", dest="invocation", metavar="<invocation>", type=int, default=1, help="pass invocation number on which to stop (default=1)", ) parser.add_argument( "hlsl_file", metavar="<hlsl-file>", help="input HLSL file path to compile" ) parser.add_argument( "-o", dest="output_file", metavar="<output-file>", required=True, help="output file name", ) parser.add_argument( "compilation_options", nargs="*", metavar="-- <DXC options>", help="set of compilation options needed to compile the HLSL file with DXC", ) return parser.parse_args() def SplitAtPass(passes, pass_name, invocation=1): pass_name = "-" + pass_name before = [] fn_passes = True count = 0 after = None for line in passes: line = line.strip() if not line or line.startswith("#"): continue if line == "-opt-mod-passes": fn_passes = False if after: after.append(line) continue if not fn_passes: if line == pass_name: count += 1 if count >= invocation: after = [line] continue before.append(line) if count == 0: raise ValueError( "Pass '{}' not found in pass list. Check spelling and that it is a module pass. Pass list: {}".format( pass_name, passes ) ) elif count < invocation: raise ValueError( "Pass '{}' found {} times, but {} invocations requested. Pass list: {}".format( pass_name, count, invocation, passes ) ) return before, after def GetTempFilename(*args, **kwargs): "Get temp filename and close the file handle for use by others" fd, name = tempfile.mkstemp(*args, **kwargs) os.close(fd) return name def main(args): try: # 1. Gets the pass list for an HLSL compilation using -Odump cmd = ["dxc", "/Odump", args.hlsl_file] + args.compilation_options # print(cmd) all_passes = subprocess.check_output(cmd, text=True) all_passes = all_passes.splitlines() # 2. Compiles HLSL with -fcgl and outputs to intermediate IR fcgl_file = GetTempFilename(".ll") cmd = [ "dxc", "-fcgl", "-Fc", fcgl_file, args.hlsl_file, ] + args.compilation_options # print(cmd) subprocess.check_call(cmd) # 3. Collects list of passes before the desired pass and adds # -hlsl-passes-pause to write correct metadata passes_before, passes_after = SplitAtPass( all_passes, args.desired_pass, args.invocation ) print( "\nPasses before: {}\n\nRemaining passes: {}".format( " ".join(passes_before), " ".join(passes_after) ) ) passes_before.append("-hlsl-passes-pause") # 4. Invokes dxopt to run passes on -fcgl output and write bitcode result bitcode_file = GetTempFilename(".bc") cmd = ["dxopt", "-o=" + bitcode_file, fcgl_file] + passes_before # print(cmd) subprocess.check_call(cmd) # 5. Disassembles bitcode to .ll file for use as a test temp_out = GetTempFilename(".ll") cmd = ["dxc", "/dumpbin", "-Fc", temp_out, bitcode_file] # print(cmd) subprocess.check_call(cmd) # 6. Inserts RUN line with -hlsl-passes-resume and desired pass with open(args.output_file, "wt") as f: f.write( "; RUN: %dxopt %s -hlsl-passes-resume -{} -S | FileCheck %s\n\n".format( args.desired_pass ) ) with open(temp_out, "rt") as f_in: f.write(f_in.read()) # Clean up temp files os.unlink(fcgl_file) os.unlink(bitcode_file) os.unlink(temp_out) except: print(f"\nSomething went wrong!\nMost recent command and arguments: {cmd}\n") raise if __name__ == "__main__": args = ParseArgs() main(args) print("\nSuccess! See output file:\n{}".format(args.output_file))
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/hct/hctgen.py
#!/usr/bin/env python3 import argparse from hctdb_instrhelp import * from hctdb import * import sys import os import CodeTags parser = argparse.ArgumentParser() parser.add_argument( "mode", choices=[ "HLSLIntrinsicOp", "DxilConstants", "DxilInstructions", "DxilSigPoint", "DxilIntrinsicTables", "DxilOperations", "DxilDocs", "DxilShaderModelInc", "DxilShaderModel", "DxilValidationInc", "DxilValidation", "HLSLOptions", "DxcOptimizer", "DxilPIXPasses", "DxcDisassembler", "DxilCounters", "DxilMetadata", "RDAT_LibraryTypes", ], ) parser.add_argument("--output", required=True) parser.add_argument("--input", default=None) parser.add_argument( "--force-lf", action="store_true", ) parser.add_argument( "--force-crlf", action="store_true", ) def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def getNewline(args): if args.force_lf: return "\n" if args.force_crlf: return "\r\n" return None def writeCodeTag(args): out = openOutput(args) if not args.input: eprint("Writing %s requires --input" % args.mode) return 1 argsList = [args.input, args.output] result = CodeTags.main(argsList, getNewline(args)) return 0 def openOutput(args): outputDir = os.path.dirname(os.path.realpath(args.output)) os.makedirs(outputDir, exist_ok=True) return open(args.output, "w", newline=getNewline(args)) def printHeader(out, filename): out.write("// %s - Generated by hctgen.py\n" % filename) out.write("// DO NOT MODIFY!!!\n") out.write("// Changes to this code are made in gen_intrin_main.txt\n\n") def writeHLSLIntrinsicOp(args): out = openOutput(args) printHeader(out, "HlslIntrinsicOp.h") out.write( "\n".join(["#pragma once", "namespace hlsl {", "enum class IntrinsicOp {"]) ) out.write(enum_hlsl_intrinsics()) out.write("};\n") out.write( "\n".join( [ "inline bool HasUnsignedIntrinsicOpcode(IntrinsicOp opcode) {", " switch (opcode) {", ] ) ) out.write(has_unsigned_hlsl_intrinsics()) out.write( "\n".join( [ " return true;", " default:", " return false;", " }", "}", "inline unsigned GetUnsignedIntrinsicOpcode(IntrinsicOp opcode) {", " switch (opcode) {", ] ) ) out.write(get_unsigned_hlsl_intrinsics()) out.write( "\n".join( [ " default:", " return static_cast<unsigned>(opcode);", " }", "}", "} // namespace hlsl\n", ] ) ) return 0 def writeDxilIntrinsicTables(args): out = openOutput(args) printHeader(out, "gen_intrin_main_tables_15.h") out.write(get_hlsl_intrinsics()) out.write(get_hlsl_intrinsic_stats()) return 0 def writeDxcDisassembler(args): out = openOutput(args) printHeader(out, "DxcDisassembler.inc") out.write(get_opsigs()) out.write("\n") return 0 def writeDxcOptimizer(args): out = openOutput(args) printHeader(out, "DxcOptimizer.inc") out.write( "\n".join( [ "namespace hlsl {", "HRESULT SetupRegistryPassForHLSL() {", " try {", " PassRegistry &Registry = *PassRegistry::getPassRegistry();\n", ] ) ) out.write(get_init_passes(set(["llvm", "dxil_gen"]))) out.write( "\n".join( [ " // Not schematized - exclusively for compiler authors.", " initializeCFGPrinterPasses(Registry);", " }", " CATCH_CPP_RETURN_HRESULT();", " return S_OK;", "}", "} // namespace hlsl\n", "static ArrayRef<LPCSTR> GetPassArgNames(LPCSTR passName) {", ] ) ) out.write(get_pass_arg_names()) out.write("\nreturn ArrayRef<LPCSTR>();\n}\n\n") out.write("static ArrayRef<LPCSTR> GetPassArgDescriptions(LPCSTR passName) {\n") out.write(get_pass_arg_descs()) out.write("\nreturn ArrayRef<LPCSTR>();\n}\n\n") out.write("static bool IsPassOptionName(StringRef S) {\n") out.write(get_is_pass_option_name()) out.write("}\n") return 0 def writeDxilValidationInc(args): out = openOutput(args) printHeader(out, "DxilValidation.inc") out.write(get_valrule_enum()) out.write("\n") return 0 def writeDxilValidation(args): out = openOutput(args) printHeader(out, "DxilValidationImpl.inc") out.write("const char *hlsl::GetValidationRuleText(ValidationRule value) {\n") out.write(get_valrule_text()) out.write( "\n".join( [ ' llvm_unreachable("invalid value");', ' return "<unknown>";', "}\nnamespace hlsl {\n", "static bool ValidateOpcodeInProfile(DXIL::OpCode opcode,", " DXIL::ShaderKind SK,", " unsigned major,", " unsigned minor) {", " unsigned op = (unsigned)opcode;", ] ) ) out.write(get_valopcode_sm_text()) out.write( "\n".join( [ "}\n", "static bool IsLLVMInstructionAllowed(llvm::Instruction &I) {", " unsigned op = I.getOpcode();", ] ) ) out.write( get_instrs_pred("op", lambda i: not i.is_dxil_op and i.is_allowed, "llvm_id") ) out.write("}\n\nvoid GetValidationVersion(unsigned *pMajor, unsigned *pMinor) {") out.write(get_validation_version()) out.write("}\n}\n") return 0 def writeDxilPIXPasses(args): out = openOutput(args) printHeader(out, "DxilPIXPasses.inc") out.write(get_init_passes(set(["pix"]))) out.write("\n") return 0 args = parser.parse_args() if args.force_lf and args.force_crlf: eprint("--force-lf and --force-crlf are mutually exclusive, only pass one") exit(1) writeFnName = "write%s" % args.mode if writeFnName in locals(): exit(locals()[writeFnName](args)) else: exit(writeCodeTag(args))
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/hct/hctdb_instrhelp.py
# Copyright (C) Microsoft Corporation. All rights reserved. # This file is distributed under the University of Illinois Open Source License. See LICENSE.TXT for details. import argparse import functools import collections from hctdb import * # get db singletons g_db_dxil = None def get_db_dxil(): global g_db_dxil if g_db_dxil is None: g_db_dxil = db_dxil() return g_db_dxil g_db_hlsl = None def get_db_hlsl(): global g_db_hlsl if g_db_hlsl is None: thisdir = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(thisdir, "gen_intrin_main.txt"), "r") as f: g_db_hlsl = db_hlsl(f) return g_db_hlsl def format_comment(prefix, val): "Formats a value with a line-comment prefix." result = "" line_width = 80 content_width = line_width - len(prefix) l = len(val) while l: if l < content_width: result += prefix + val.strip() result += "\n" l = 0 else: split_idx = val.rfind(" ", 0, content_width) result += prefix + val[:split_idx].strip() result += "\n" val = val[split_idx + 1 :] l = len(val) return result def format_rst_table(list_of_tuples): "Produces a reStructuredText simple table from the specified list of tuples." # Calculate widths. widths = None for t in list_of_tuples: if widths is None: widths = [0] * len(t) for i, v in enumerate(t): widths[i] = max(widths[i], len(str(v))) # Build banner line. banner = "" for i, w in enumerate(widths): if i > 0: banner += " " banner += "=" * w banner += "\n" # Build the result. result = banner for i, t in enumerate(list_of_tuples): for j, v in enumerate(t): if j > 0: result += " " result += str(v) result += " " * (widths[j] - len(str(v))) result = result.rstrip() result += "\n" if i == 0: result += banner result += banner return result def build_range_tuples(i): "Produces a list of tuples with contiguous ranges in the input list." i = sorted(i) low_bound = None high_bound = None for val in i: if low_bound is None: low_bound = val high_bound = val else: assert not high_bound is None if val == high_bound + 1: high_bound = val else: yield (low_bound, high_bound) low_bound = val high_bound = val if not low_bound is None: yield (low_bound, high_bound) def build_range_code(var, i): "Produces a fragment of code that tests whether the variable name matches values in the given range." ranges = build_range_tuples(i) result = "" for r in ranges: if r[0] == r[1]: cond = var + " == " + str(r[0]) else: cond = "(%d <= %s && %s <= %d)" % (r[0], var, var, r[1]) if result == "": result = cond else: result = result + " || " + cond return result class db_docsref_gen: "A generator of reference documentation." def __init__(self, db): self.db = db instrs = [i for i in self.db.instr if i.is_dxil_op] instrs = sorted( instrs, key=lambda v: ("" if v.category == None else v.category) + "." + v.name, ) self.instrs = instrs val_rules = sorted( db.val_rules, key=lambda v: ("" if v.category == None else v.category) + "." + v.name, ) self.val_rules = val_rules def print_content(self): self.print_header() self.print_body() self.print_footer() def print_header(self): print("<!DOCTYPE html>") print("<html><head><title>DXIL Reference</title>") print("<style>body { font-family: Verdana; font-size: small; }</style>") print("</head><body><h1>DXIL Reference</h1>") self.print_toc("Instructions", "i", self.instrs) self.print_toc("Rules", "r", self.val_rules) def print_body(self): self.print_instruction_details() self.print_valrule_details() def print_instruction_details(self): print("<h2>Instruction Details</h2>") for i in self.instrs: print("<h3><a name='i%s'>%s</a></h3>" % (i.name, i.name)) print("<div>Opcode: %d. This instruction %s.</div>" % (i.dxil_opid, i.doc)) if i.remarks: # This is likely a .rst fragment, but this will do for now. print("<div> " + i.remarks + "</div>") print("<div>Operands:</div>") print("<ul>") for o in i.ops: if o.pos == 0: print("<li>result: %s - %s</li>" % (o.llvm_type, o.doc)) else: enum_desc = ( "" if o.enum_name == "" else " one of %s: %s" % ( o.enum_name, ",".join(db.enum_idx[o.enum_name].value_names()), ) ) print( "<li>%d - %s: %s%s%s</li>" % ( o.pos - 1, o.name, o.llvm_type, "" if o.doc == "" else " - " + o.doc, enum_desc, ) ) print("</ul>") print("<div><a href='#Instructions'>(top)</a></div>") def print_valrule_details(self): print("<h2>Rule Details</h2>") for i in self.val_rules: print("<h3><a name='r%s'>%s</a></h3>" % (i.name, i.name)) print("<div>" + i.doc + "</div>") print("<div><a href='#Rules'>(top)</a></div>") def print_toc(self, name, aprefix, values): print("<h2><a name='" + name + "'>" + name + "</a></h2>") last_category = "" for i in values: if i.category != last_category: if last_category != None: print("</ul>") print("<div><b>%s</b></div><ul>" % i.category) last_category = i.category print("<li><a href='#" + aprefix + "%s'>%s</a></li>" % (i.name, i.name)) print("</ul>") def print_footer(self): print("</body></html>") class db_instrhelp_gen: "A generator of instruction helper classes." def __init__(self, db): self.db = db TypeInfo = collections.namedtuple("TypeInfo", "name bits") self.llvm_type_map = { "i1": TypeInfo("bool", 1), "i8": TypeInfo("int8_t", 8), "u8": TypeInfo("uint8_t", 8), "i32": TypeInfo("int32_t", 32), "u32": TypeInfo("uint32_t", 32), } self.IsDxilOpFuncCallInst = "hlsl::OP::IsDxilOpFuncCallInst" def print_content(self): self.print_header() self.print_body() self.print_footer() def print_header(self): print( "///////////////////////////////////////////////////////////////////////////////" ) print( "// //" ) print( "// Copyright (C) Microsoft Corporation. All rights reserved. //" ) print( "// DxilInstructions.h //" ) print( "// //" ) print( "// This file provides a library of instruction helper classes. //" ) print( "// //" ) print( "// MUCH WORK YET TO BE DONE - EXPECT THIS WILL CHANGE - GENERATED FILE //" ) print( "// //" ) print( "///////////////////////////////////////////////////////////////////////////////" ) print("") print("// TODO: add correct include directives") print("// TODO: add accessors with values") print("// TODO: add validation support code, including calling into right fn") print("// TODO: add type hierarchy") print("namespace hlsl {") def bool_lit(self, val): return "true" if val else "false" def op_type(self, o): if o.llvm_type in self.llvm_type_map: return self.llvm_type_map[o.llvm_type].name raise ValueError( "Don't know how to describe type %s for operand %s." % (o.llvm_type, o.name) ) def op_size(self, o): if o.llvm_type in self.llvm_type_map: return self.llvm_type_map[o.llvm_type].bits raise ValueError( "Don't know how to describe type %s for operand %s." % (o.llvm_type, o.name) ) def op_const_expr(self, o): return ( "(%s)(llvm::dyn_cast<llvm::ConstantInt>(Instr->getOperand(%d))->getZExtValue())" % (self.op_type(o), o.pos - 1) ) def op_set_const_expr(self, o): type_size = self.op_size(o) return ( "llvm::Constant::getIntegerValue(llvm::IntegerType::get(Instr->getContext(), %d), llvm::APInt(%d, (uint64_t)val))" % (type_size, type_size) ) def print_body(self): for i in self.db.instr: if i.is_reserved: continue if i.inst_helper_prefix: struct_name = "%s_%s" % (i.inst_helper_prefix, i.name) elif i.is_dxil_op: struct_name = "DxilInst_%s" % i.name else: struct_name = "LlvmInst_%s" % i.name if i.doc: print("/// This instruction %s" % i.doc) print("struct %s {" % struct_name) print(" llvm::Instruction *Instr;") print(" // Construction and identification") print(" %s(llvm::Instruction *pInstr) : Instr(pInstr) {}" % struct_name) print(" operator bool() const {") if i.is_dxil_op: op_name = i.fully_qualified_name() print( " return %s(Instr, %s);" % (self.IsDxilOpFuncCallInst, op_name) ) else: print( " return Instr->getOpcode() == llvm::Instruction::%s;" % i.name ) print(" }") print(" // Validation support") print( " bool isAllowed() const { return %s; }" % self.bool_lit(i.is_allowed) ) if i.is_dxil_op: print(" bool isArgumentListValid() const {") print( " if (%d != llvm::dyn_cast<llvm::CallInst>(Instr)->getNumArgOperands()) return false;" % (len(i.ops) - 1) ) print(" return true;") # TODO - check operand types print(" }") print(" // Metadata") print( " bool requiresUniformInputs() const { return %s; }" % self.bool_lit(i.requires_uniform_inputs) ) EnumWritten = False for o in i.ops: if o.pos > 1: # 0 is return type, 1 is DXIL OP id if not EnumWritten: print(" // Operand indexes") print(" enum OperandIdx {") EnumWritten = True print(" arg_%s = %d," % (o.name, o.pos - 1)) if EnumWritten: print(" };") AccessorsWritten = False for o in i.ops: if o.pos > 1: # 0 is return type, 1 is DXIL OP id if not AccessorsWritten: print(" // Accessors") AccessorsWritten = True print( " llvm::Value *get_%s() const { return Instr->getOperand(%d); }" % (o.name, o.pos - 1) ) print( " void set_%s(llvm::Value *val) { Instr->setOperand(%d, val); }" % (o.name, o.pos - 1) ) if o.is_const: if o.llvm_type in self.llvm_type_map: print( " %s get_%s_val() const { return %s; }" % (self.op_type(o), o.name, self.op_const_expr(o)) ) print( " void set_%s_val(%s val) { Instr->setOperand(%d, %s); }" % ( o.name, self.op_type(o), o.pos - 1, self.op_set_const_expr(o), ) ) print("};") print("") def print_footer(self): print("} // namespace hlsl") class db_enumhelp_gen: "A generator of enumeration declarations." def __init__(self, db): self.db = db # Some enums should get a last enum marker. self.lastEnumNames = {"OpCode": "NumOpCodes", "OpCodeClass": "NumOpClasses"} def print_enum(self, e, **kwargs): print("// %s" % e.doc) print("enum class %s : unsigned {" % e.name) hide_val = kwargs.get("hide_val", False) sorted_values = e.values if kwargs.get("sort_val", True): sorted_values = sorted( e.values, key=lambda v: ("" if v.category == None else v.category) + "." + v.name, ) last_category = None for v in sorted_values: if v.category != last_category: if last_category != None: print("") print(" // %s" % v.category) last_category = v.category line_format = " {name}" if not e.is_internal and not hide_val: line_format += " = {value}" line_format += "," if v.doc: line_format += " // {doc}" print(line_format.format(name=v.name, value=v.value, doc=v.doc)) if e.name in self.lastEnumNames: lastName = self.lastEnumNames[e.name] versioned = [ "%s_Dxil_%d_%d = %d," % (lastName, major, minor, info[lastName]) for (major, minor), info in sorted(self.db.dxil_version_info.items()) if lastName in info ] if versioned: print("") for val in versioned: print(" " + val) print("") print( " " + lastName + " = " + str(len(sorted_values)) + " // exclusive last value of enumeration" ) print("};") def print_rdat_enum(self, e, **kwargs): nodef = kwargs.get("nodef", False) for v in e.values: line_format = ( "RDAT_ENUM_VALUE_NODEF({name})" if nodef else "RDAT_ENUM_VALUE({value}, {name})" ) if v.doc: line_format += " // {doc}" print(line_format.format(name=v.name, value=v.value, doc=v.doc)) def print_content(self): for e in sorted(self.db.enums, key=lambda e: e.name): self.print_enum(e) class db_oload_gen: "A generator of overload tables." def __init__(self, db): self.db = db instrs = [i for i in self.db.instr if i.is_dxil_op] self.instrs = sorted(instrs, key=lambda i: i.dxil_opid) # Allow these to be overridden by external scripts. self.OP = "OP" self.OC = "OC" self.OCC = "OCC" def print_content(self): self.print_opfunc_props() print("...") self.print_opfunc_table() def print_opfunc_props(self): print( "const {OP}::OpCodeProperty {OP}::m_OpCodeProps[(unsigned){OP}::OpCode::NumOpCodes] = {{".format( OP=self.OP ) ) print( "// OpCode OpCode name, OpCodeClass OpCodeClass name, void, h, f, d, i1, i8, i16, i32, i64, udt, obj, function attribute" ) # Example formatted string: # { OC::TempRegLoad, "TempRegLoad", OCC::TempRegLoad, "tempRegLoad", false, true, true, false, true, false, true, true, false, Attribute::ReadOnly, }, # 012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789 # 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 last_category = None # overload types are a string of (v)oid, (h)alf, (f)loat, (d)ouble, (1)-bit, (8)-bit, (w)ord, (i)nt, (l)ong, u(dt) f = lambda i, c: "true" if i.oload_types.find(c) >= 0 else "false" lower_exceptions = { "CBufferLoad": "cbufferLoad", "CBufferLoadLegacy": "cbufferLoadLegacy", "GSInstanceID": "gsInstanceID", } lower_fn = ( lambda t: lower_exceptions[t] if t in lower_exceptions else t[:1].lower() + t[1:] ) attr_dict = { "": "None", "ro": "ReadOnly", "rn": "ReadNone", "amo": "ArgMemOnly", "nd": "NoDuplicate", "nr": "NoReturn", "wv": "None", } attr_fn = lambda i: "Attribute::" + attr_dict[i.fn_attr] + "," for i in self.instrs: if last_category != i.category: if last_category != None: print("") print( " // {category:118} void, h, f, d, i1, i8, i16, i32, i64, udt, obj , function attribute".format( category=i.category ) ) last_category = i.category print( " {{ {OC}::{name:24} {quotName:27} {OCC}::{className:25} {classNameQuot:28} {{{v:>6},{h:>6},{f:>6},{d:>6},{b:>6},{e:>6},{w:>6},{i:>6},{l:>6},{u:>6},{o:>6}}}, {attr:20} }},".format( name=i.name + ",", quotName='"' + i.name + '",', className=i.dxil_class + ",", classNameQuot='"' + lower_fn(i.dxil_class) + '",', v=f(i, "v"), h=f(i, "h"), f=f(i, "f"), d=f(i, "d"), b=f(i, "1"), e=f(i, "8"), w=f(i, "w"), i=f(i, "i"), l=f(i, "l"), u=f(i, "u"), o=f(i, "o"), attr=attr_fn(i), OC=self.OC, OCC=self.OCC, ) ) print("};") def print_opfunc_table(self): # Print the table for OP::GetOpFunc op_type_texts = { "$cb": "CBRT(pETy);", "$o": "A(pETy);", "$r": "RRT(pETy);", "d": "A(pF64);", "dims": "A(pDim);", "f": "A(pF32);", "h": "A(pF16);", "i1": "A(pI1);", "i16": "A(pI16);", "i32": "A(pI32);", "i32c": "A(pI32C);", "i64": "A(pI64);", "i8": "A(pI8);", "$u4": "A(pI4S);", "pf32": "A(pPF32);", "res": "A(pRes);", "splitdouble": "A(pSDT);", "twoi32": "A(p2I32);", "twof32": "A(p2F32);", "twof16": "A(p2F16);", "twoi16": "A(p2I16);", "threei32": "A(p3I32);", "threef32": "A(p3F32);", "fouri32": "A(p4I32);", "fourf32": "A(p4F32);", "fouri16": "A(p4I16);", "fourf16": "A(p4F16);", "u32": "A(pI32);", "u64": "A(pI64);", "u8": "A(pI8);", "v": "A(pV);", "$vec4": "VEC4(pETy);", "w": "A(pWav);", "SamplePos": "A(pPos);", "udt": "A(udt);", "obj": "A(obj);", "resproperty": "A(resProperty);", "resbind": "A(resBind);", "waveMat": "A(pWaveMatPtr);", "waveMatProps": "A(pWaveMatProps);", "$gsptr": "A(pGSEltPtrTy);", "nodehandle": "A(pNodeHandle);", "noderecordhandle": "A(pNodeRecordHandle);", "nodeproperty": "A(nodeProperty);", "noderecordproperty": "A(nodeRecordProperty);", } last_category = None for i in self.instrs: if last_category != i.category: if last_category != None: print("") print(" // %s" % i.category) last_category = i.category line = " case OpCode::{name:24}".format(name=i.name + ":") for index, o in enumerate(i.ops): assert ( o.llvm_type in op_type_texts ), "llvm type %s in instruction %s is unknown" % (o.llvm_type, i.name) op_type_text = op_type_texts[o.llvm_type] if index == 0: line = line + "{val:13}".format(val=op_type_text) else: line = line + "{val:9}".format(val=op_type_text) line = line + "break;" print(line) def print_opfunc_oload_type(self): # Print the function for OP::GetOverloadType elt_ty = "$o" res_ret_ty = "$r" cb_ret_ty = "$cb" udt_ty = "udt" obj_ty = "obj" vec_ty = "$vec" gsptr_ty = "$gsptr" last_category = None index_dict = collections.OrderedDict() ptr_index_dict = collections.OrderedDict() single_dict = collections.OrderedDict() struct_list = [] for instr in self.instrs: ret_ty = instr.ops[0].llvm_type # Skip case return type is overload type if ret_ty == elt_ty: continue if ret_ty == res_ret_ty: struct_list.append(instr.name) continue if ret_ty == cb_ret_ty: struct_list.append(instr.name) continue if ret_ty.startswith(vec_ty): struct_list.append(instr.name) continue in_param_ty = False # Try to find elt_ty in parameter types. for index, op in enumerate(instr.ops): # Skip return type. if op.pos == 0: continue # Skip dxil opcode. if op.pos == 1: continue op_type = op.llvm_type if op_type == elt_ty: # Skip return op index = index - 1 if index not in index_dict: index_dict[index] = [instr.name] else: index_dict[index].append(instr.name) in_param_ty = True break if op_type == gsptr_ty: # Skip return op index = index - 1 if index not in ptr_index_dict: ptr_index_dict[index] = [instr.name] else: ptr_index_dict[index].append(instr.name) in_param_ty = True break if op_type == udt_ty or op_type == obj_ty: # Skip return op index = index - 1 if index not in index_dict: index_dict[index] = [instr.name] else: index_dict[index].append(instr.name) in_param_ty = True if in_param_ty: continue # No overload, just return the single oload_type. assert len(instr.oload_types) == 1, "overload no elt_ty %s" % (instr.name) ty = instr.oload_types[0] type_code_texts = { "d": "Type::getDoubleTy(Ctx)", "f": "Type::getFloatTy(Ctx)", "h": "Type::getHalfTy", "1": "IntegerType::get(Ctx, 1)", "8": "IntegerType::get(Ctx, 8)", "w": "IntegerType::get(Ctx, 16)", "i": "IntegerType::get(Ctx, 32)", "l": "IntegerType::get(Ctx, 64)", "v": "Type::getVoidTy(Ctx)", "u": "Type::getInt32PtrTy(Ctx)", "o": "Type::getInt32PtrTy(Ctx)", } assert ty in type_code_texts, "llvm type %s is unknown" % (ty) ty_code = type_code_texts[ty] if ty_code not in single_dict: single_dict[ty_code] = [instr.name] else: single_dict[ty_code].append(instr.name) for index, opcodes in index_dict.items(): line = "" for opcode in opcodes: line = line + "case OpCode::{name}".format(name=opcode + ":\n") line = ( line + " if (FT->getNumParams() <= " + str(index) + ") return nullptr;\n" ) line = line + " return FT->getParamType(" + str(index) + ");" print(line) # ptr_index_dict for overload based on pointer element type for index, opcodes in ptr_index_dict.items(): line = "" for opcode in opcodes: line = line + "case OpCode::{name}".format(name=opcode + ":\n") line = ( line + " if (FT->getNumParams() <= " + str(index) + ") return nullptr;\n" ) line = ( line + " return FT->getParamType(" + str(index) + ")->getPointerElementType();" ) print(line) for code, opcodes in single_dict.items(): line = "" for opcode in opcodes: line = line + "case OpCode::{name}".format(name=opcode + ":\n") line = line + " return " + code + ";" print(line) line = "" for opcode in struct_list: line = line + "case OpCode::{name}".format(name=opcode + ":\n") line = line + "{\n" line = line + " StructType *ST = cast<StructType>(Ty);\n" line = line + " return ST->getElementType(0);\n" line = line + "}" print(line) class db_valfns_gen: "A generator of validation functions." def __init__(self, db): self.db = db def print_content(self): self.print_header() self.print_body() def print_header(self): print( "///////////////////////////////////////////////////////////////////////////////" ) print( "// Instruction validation functions. //" ) def bool_lit(self, val): return "true" if val else "false" def op_type(self, o): if o.llvm_type == "i8": return "int8_t" if o.llvm_type == "u8": return "uint8_t" raise ValueError( "Don't know how to describe type %s for operand %s." % (o.llvm_type, o.name) ) def op_const_expr(self, o): if o.llvm_type == "i8" or o.llvm_type == "u8": return ( "(%s)(llvm::dyn_cast<llvm::ConstantInt>(Instr->getOperand(%d))->getZExtValue())" % (self.op_type(o), o.pos - 1) ) raise ValueError( "Don't know how to describe type %s for operand %s." % (o.llvm_type, o.name) ) def print_body(self): llvm_instrs = [i for i in self.db.instr if i.is_allowed and not i.is_dxil_op] print("static bool IsLLVMInstructionAllowed(llvm::Instruction &I) {") self.print_comment( " // ", "Allow: %s" % ", ".join([i.name + "=" + str(i.llvm_id) for i in llvm_instrs]), ) print(" unsigned op = I.getOpcode();") print(" return %s;" % build_range_code("op", [i.llvm_id for i in llvm_instrs])) print("}") print("") def print_comment(self, prefix, val): print(format_comment(prefix, val)) class macro_table_gen: "A generator for macro tables." def format_row(self, row, widths, sep=", "): frow = [ str(item) + sep + (" " * (width - len(item))) for item, width in list(zip(row, widths))[:-1] ] + [str(row[-1])] return "".join(frow) def format_table(self, table, *args, **kwargs): widths = [ functools.reduce(max, [len(row[i]) for row in table], 1) for i in range(len(table[0])) ] formatted = [] for row in table: formatted.append(self.format_row(row, widths, *args, **kwargs)) return formatted def print_table(self, table, macro_name): formatted = self.format_table(table) print( "// %s\n" % formatted[0] + "#define %s(ROW) \\\n" % macro_name + " \\\n".join([" ROW(%s)" % frow for frow in formatted[1:]]) ) class db_sigpoint_gen(macro_table_gen): "A generator for SigPoint tables." def __init__(self, db): self.db = db def print_sigpoint_table(self): self.print_table(self.db.sigpoint_table, "DO_SIGPOINTS") def print_interpretation_table(self): self.print_table(self.db.interpretation_table, "DO_INTERPRETATION_TABLE") def print_content(self): self.print_sigpoint_table() self.print_interpretation_table() class string_output: def __init__(self): self.val = "" def write(self, text): self.val = self.val + str(text) def __str__(self): return self.val def run_with_stdout(fn): import sys _stdout_saved = sys.stdout so = string_output() try: sys.stdout = so fn() finally: sys.stdout = _stdout_saved return str(so) def get_hlsl_intrinsic_stats(): db = get_db_hlsl() longest_fn = db.intrinsics[0] longest_param = None longest_arglist_fn = db.intrinsics[0] for i in sorted(db.intrinsics, key=lambda x: x.key): # Get some values for maximum lengths. if len(i.name) > len(longest_fn.name): longest_fn = i for p_idx, p in enumerate(i.params): if p_idx > 0 and ( longest_param is None or len(p.name) > len(longest_param.name) ): longest_param = p if len(i.params) > len(longest_arglist_fn.params): longest_arglist_fn = i result = "" for k in sorted(db.namespaces.keys()): v = db.namespaces[k] result += "static const UINT g_u%sCount = %d;\n" % (k, len(v.intrinsics)) result += "\n" # NOTE:The min limits are needed to support allowing intrinsics in the extension mechanism that use longer values than the builtin hlsl intrisics. # TODO: remove code which dependent on g_MaxIntrinsic*. MIN_FUNCTION_NAME_LENTH = 44 MIN_PARAM_NAME_LENTH = 48 MIN_PARAM_COUNT = 29 max_fn_name = longest_fn.name max_fn_name_len = len(longest_fn.name) max_param_name = longest_param.name max_param_name_len = len(longest_param.name) max_param_count_name = longest_arglist_fn.name max_param_count = len(longest_arglist_fn.params) - 1 if max_fn_name_len < MIN_FUNCTION_NAME_LENTH: max_fn_name_len = MIN_FUNCTION_NAME_LENTH max_fn_name = "MIN_FUNCTION_NAME_LENTH" if max_param_name_len < MIN_PARAM_NAME_LENTH: max_param_name_len = MIN_PARAM_NAME_LENTH max_param_name = "MIN_PARAM_NAME_LENTH" if max_param_count < MIN_PARAM_COUNT: max_param_count = MIN_PARAM_COUNT max_param_count_name = "MIN_PARAM_COUNT" result += ( "static const int g_MaxIntrinsicName = %d; // Count of characters for longest intrinsic name - '%s'\n" % (max_fn_name_len, max_fn_name) ) result += ( "static const int g_MaxIntrinsicParamName = %d; // Count of characters for longest intrinsic parameter name - '%s'\n" % (max_param_name_len, max_param_name) ) result += ( "static const int g_MaxIntrinsicParamCount = %d; // Count of parameters (without return) for longest intrinsic argument list - '%s'\n" % (max_param_count, max_param_count_name) ) return result def get_hlsl_intrinsics(): db = get_db_hlsl() result = "" last_ns = "" ns_table = "" is_vk_table = False # SPIRV Change id_prefix = "" arg_idx = 0 opcode_namespace = db.opcode_namespace for i in sorted(db.intrinsics, key=lambda x: x.key): if last_ns != i.ns: last_ns = i.ns id_prefix = ( "IOP" if last_ns == "Intrinsics" or last_ns == "VkIntrinsics" else "MOP" ) # SPIRV Change if len(ns_table): result += ns_table + "};\n" # SPIRV Change Starts if is_vk_table: result += "\n#endif // ENABLE_SPIRV_CODEGEN\n" is_vk_table = False # SPIRV Change Ends result += "\n//\n// Start of %s\n//\n\n" % (last_ns) # This used to be qualified as __declspec(selectany), but that's no longer necessary. ns_table = "static const HLSL_INTRINSIC g_%s[] =\n{\n" % (last_ns) # SPIRV Change Starts if i.vulkanSpecific: is_vk_table = True result += "#ifdef ENABLE_SPIRV_CODEGEN\n\n" # SPIRV Change Ends arg_idx = 0 ns_table += " {(UINT)%s::%s_%s, %s, %s, %s, %d, %d, g_%s_Args%s},\n" % ( opcode_namespace, id_prefix, i.name, str(i.readonly).lower(), str(i.readnone).lower(), str(i.wave).lower(), i.overload_param_index, len(i.params), last_ns, arg_idx, ) result += "static const HLSL_INTRINSIC_ARGUMENT g_%s_Args%s[] =\n{\n" % ( last_ns, arg_idx, ) for p in i.params: name = p.name if name == i.name and i.hidden: # First parameter defines intrinsic name for parsing in HLSL. # Prepend '$hidden$' for hidden intrinsic so it can't be used in HLSL. name = "$hidden$" + name result += ' {"%s", %s, %s, %s, %s, %s, %s, %s},\n' % ( name, p.param_qual, p.template_id, p.template_list, p.component_id, p.component_list, p.rows, p.cols, ) result += "};\n\n" arg_idx += 1 result += ns_table + "};\n" result += ( "\n#endif // ENABLE_SPIRV_CODEGEN\n" if is_vk_table else "" ) # SPIRV Change return result # SPIRV Change Starts def wrap_with_ifdef_if_vulkan_specific(intrinsic, text): if intrinsic.vulkanSpecific: return ( "#ifdef ENABLE_SPIRV_CODEGEN\n" + text + "#endif // ENABLE_SPIRV_CODEGEN\n" ) return text # SPIRV Change Ends def enum_hlsl_intrinsics(): db = get_db_hlsl() result = "" enumed = [] for i in sorted(db.intrinsics, key=lambda x: x.key): if i.enum_name not in enumed: enumerant = " %s,\n" % (i.enum_name) result += wrap_with_ifdef_if_vulkan_specific(i, enumerant) # SPIRV Change enumed.append(i.enum_name) # unsigned result += " // unsigned\n" for i in sorted(db.intrinsics, key=lambda x: x.key): if i.unsigned_op != "": if i.unsigned_op not in enumed: result += " %s,\n" % (i.unsigned_op) enumed.append(i.unsigned_op) result += " Num_Intrinsics,\n" return result def has_unsigned_hlsl_intrinsics(): db = get_db_hlsl() result = "" enumed = [] # unsigned for i in sorted(db.intrinsics, key=lambda x: x.key): if i.unsigned_op != "": if i.enum_name not in enumed: result += " case IntrinsicOp::%s:\n" % (i.enum_name) enumed.append(i.enum_name) return result def get_unsigned_hlsl_intrinsics(): db = get_db_hlsl() result = "" enumed = [] # unsigned for i in sorted(db.intrinsics, key=lambda x: x.key): if i.unsigned_op != "": if i.enum_name not in enumed: enumed.append(i.enum_name) result += " case IntrinsicOp::%s:\n" % (i.enum_name) result += " return static_cast<unsigned>(IntrinsicOp::%s);\n" % ( i.unsigned_op ) return result def get_oloads_props(): db = get_db_dxil() gen = db_oload_gen(db) return run_with_stdout(lambda: gen.print_opfunc_props()) def get_oloads_funcs(): db = get_db_dxil() gen = db_oload_gen(db) return run_with_stdout(lambda: gen.print_opfunc_table()) def get_funcs_oload_type(): db = get_db_dxil() gen = db_oload_gen(db) return run_with_stdout(lambda: gen.print_opfunc_oload_type()) def get_enum_decl(name, **kwargs): db = get_db_dxil() gen = db_enumhelp_gen(db) return run_with_stdout(lambda: gen.print_enum(db.enum_idx[name], **kwargs)) def get_rdat_enum_decl(name, **kwargs): db = get_db_dxil() gen = db_enumhelp_gen(db) return run_with_stdout(lambda: gen.print_rdat_enum(db.enum_idx[name], **kwargs)) def get_valrule_enum(): return get_enum_decl("ValidationRule", hide_val=True) def get_valrule_text(): db = get_db_dxil() result = "switch(value) {\n" for v in db.enum_idx["ValidationRule"].values: result += ( " case hlsl::ValidationRule::" + v.name + ': return "' + v.err_msg + '";\n' ) result += "}\n" return result def get_instrhelper(): db = get_db_dxil() gen = db_instrhelp_gen(db) return run_with_stdout(lambda: gen.print_body()) def get_instrs_pred(varname, pred, attr_name="dxil_opid"): db = get_db_dxil() if type(pred) == str: pred_fn = lambda i: getattr(i, pred) else: pred_fn = pred llvm_instrs = [i for i in db.instr if pred_fn(i)] result = format_comment( "// ", "Instructions: %s" % ", ".join([i.name + "=" + str(getattr(i, attr_name)) for i in llvm_instrs]), ) result += "return %s;" % build_range_code( varname, [getattr(i, attr_name) for i in llvm_instrs] ) result += "\n" return result def counter_pred(name, dxil_op=True): def pred(i): return ( (dxil_op == i.is_dxil_op) and getattr(i, "props") and "counters" in i.props and name in i.props["counters"] ) return pred def get_counters(): db = get_db_dxil() return db.counters def get_llvm_op_counters(): db = get_db_dxil() return [c for c in db.counters if c in db.llvm_op_counters] def get_dxil_op_counters(): db = get_db_dxil() return [c for c in db.counters if c in db.dxil_op_counters] def get_instrs_rst(): "Create an rst table of allowed LLVM instructions." db = get_db_dxil() instrs = [i for i in db.instr if i.is_allowed and not i.is_dxil_op] instrs = sorted(instrs, key=lambda v: v.llvm_id) rows = [] rows.append(["Instruction", "Action", "Operand overloads"]) for i in instrs: rows.append([i.name, i.doc, i.oload_types]) result = "\n\n" + format_rst_table(rows) + "\n\n" # Add detailed instruction information where available. for i in instrs: if i.remarks: result += i.name + "\n" + ("~" * len(i.name)) + "\n\n" + i.remarks + "\n\n" return result + "\n" def get_init_passes(category_libs): "Create a series of statements to initialize passes in a registry." db = get_db_dxil() result = "" for p in sorted(db.passes, key=lambda p: p.type_name): # Skip if not in target category. if p.category_lib not in category_libs: continue result += "initialize%sPass(Registry);\n" % p.type_name return result def get_pass_arg_names(): "Return an ArrayRef of argument names based on passName" db = get_db_dxil() decl_result = "" check_result = "" for p in sorted(db.passes, key=lambda p: p.type_name): if len(p.args): decl_result += "static const LPCSTR %sArgs[] = { " % p.type_name check_result += ( 'if (strcmp(passName, "%s") == 0) return ArrayRef<LPCSTR>(%sArgs, _countof(%sArgs));\n' % (p.name, p.type_name, p.type_name) ) sep = "" for a in p.args: decl_result += sep + '"%s"' % a.name sep = ", " decl_result += " };\n" return decl_result + check_result def get_pass_arg_descs(): "Return an ArrayRef of argument descriptions based on passName" db = get_db_dxil() decl_result = "" check_result = "" for p in sorted(db.passes, key=lambda p: p.type_name): if len(p.args): decl_result += "static const LPCSTR %sArgs[] = { " % p.type_name check_result += ( 'if (strcmp(passName, "%s") == 0) return ArrayRef<LPCSTR>(%sArgs, _countof(%sArgs));\n' % (p.name, p.type_name, p.type_name) ) sep = "" for a in p.args: decl_result += sep + '"%s"' % a.doc sep = ", " decl_result += " };\n" return decl_result + check_result def get_is_pass_option_name(): "Create a return expression to check whether a value 'S' is a pass option name." db = get_db_dxil() prefix = "" result = "return " for k in sorted(db.pass_idx_args): result += prefix + 'S.equals("%s")' % k prefix = "\n || " return result + ";" def get_opcodes_rst(): "Create an rst table of opcodes" db = get_db_dxil() instrs = [i for i in db.instr if i.is_allowed and i.is_dxil_op] instrs = sorted(instrs, key=lambda v: v.dxil_opid) rows = [] rows.append(["ID", "Name", "Description"]) for i in instrs: op_name = i.dxil_op if i.remarks: op_name = ( op_name + "_" ) # append _ to enable internal hyperlink on rst files rows.append([i.dxil_opid, op_name, i.doc]) result = "\n\n" + format_rst_table(rows) + "\n\n" # Add detailed instruction information where available. instrs = sorted(instrs, key=lambda v: v.name) for i in instrs: if i.remarks: result += i.name + "\n" + ("~" * len(i.name)) + "\n\n" + i.remarks + "\n\n" return result + "\n" def get_valrules_rst(): "Create an rst table of validation rules instructions." db = get_db_dxil() rules = [i for i in db.val_rules if not i.is_disabled] rules = sorted(rules, key=lambda v: v.name) rows = [] rows.append(["Rule Code", "Description"]) for i in rules: rows.append([i.name, i.doc]) return "\n\n" + format_rst_table(rows) + "\n\n" def get_opsigs(): # Create a list of DXIL operation signatures, sorted by ID. db = get_db_dxil() instrs = [i for i in db.instr if i.is_dxil_op] instrs = sorted(instrs, key=lambda v: v.dxil_opid) # db_dxil already asserts that the numbering is dense. # Create the code to write out. code = "static const char *OpCodeSignatures[] = {\n" for inst_idx, i in enumerate(instrs): code += ' "(' for operand in i.ops: if operand.pos > 1: # skip 0 (the return value) and 1 (the opcode itself) code += operand.name if operand.pos < len(i.ops) - 1: code += "," code += ')"' if inst_idx < len(instrs) - 1: code += "," code += " // " + i.name code += "\n" code += "};\n" return code shader_stage_to_ShaderKind = { "vertex": "Vertex", "pixel": "Pixel", "geometry": "Geometry", "compute": "Compute", "hull": "Hull", "domain": "Domain", "library": "Library", "raygeneration": "RayGeneration", "intersection": "Intersection", "anyhit": "AnyHit", "closesthit": "ClosestHit", "miss": "Miss", "callable": "Callable", "mesh": "Mesh", "amplification": "Amplification", "node": "Node", } def get_min_sm_and_mask_text(): db = get_db_dxil() instrs = [i for i in db.instr if i.is_dxil_op] instrs = sorted( instrs, key=lambda v: ( v.shader_model, v.shader_model_translated, v.shader_stages, v.dxil_opid, ), ) last_model = None last_model_translated = None last_stage = None grouped_instrs = [] code = "" def flush_instrs(grouped_instrs, last_model, last_model_translated, last_stage): if len(grouped_instrs) == 0: return "" result = format_comment( "// ", "Instructions: %s" % ", ".join([i.name + "=" + str(i.dxil_opid) for i in grouped_instrs]), ) result += ( "if (" + build_range_code("op", [i.dxil_opid for i in grouped_instrs]) + ") {\n" ) default = True if last_model != (6, 0): default = False if last_model_translated: result += " if (bWithTranslation) {\n" result += ( " major = %d; minor = %d;\n } else {\n " % last_model_translated ) result += " major = %d; minor = %d;\n" % last_model if last_model_translated: result += " }\n" if last_stage: default = False result += " mask = %s;\n" % " | ".join( ["SFLAG(%s)" % shader_stage_to_ShaderKind[c] for c in last_stage] ) if default: # don't write these out, instead fall through return "" return result + " return;\n}\n" for i in instrs: if (i.shader_model, i.shader_model_translated, i.shader_stages) != ( last_model, last_model_translated, last_stage, ): code += flush_instrs( grouped_instrs, last_model, last_model_translated, last_stage ) grouped_instrs = [] last_model = i.shader_model last_model_translated = i.shader_model_translated last_stage = i.shader_stages grouped_instrs.append(i) code += flush_instrs(grouped_instrs, last_model, last_model_translated, last_stage) return code check_pSM_for_shader_stage = { "vertex": "SK == DXIL::ShaderKind::Vertex", "pixel": "SK == DXIL::ShaderKind::Pixel", "geometry": "SK == DXIL::ShaderKind::Geometry", "compute": "SK == DXIL::ShaderKind::Compute", "hull": "SK == DXIL::ShaderKind::Hull", "domain": "SK == DXIL::ShaderKind::Domain", "library": "SK == DXIL::ShaderKind::Library", "raygeneration": "SK == DXIL::ShaderKind::RayGeneration", "intersection": "SK == DXIL::ShaderKind::Intersection", "anyhit": "SK == DXIL::ShaderKind::AnyHit", "closesthit": "SK == DXIL::ShaderKind::ClosestHit", "miss": "SK == DXIL::ShaderKind::Miss", "callable": "SK == DXIL::ShaderKind::Callable", "mesh": "SK == DXIL::ShaderKind::Mesh", "amplification": "SK == DXIL::ShaderKind::Amplification", "node": "SK == DXIL::ShaderKind::Node", } def get_valopcode_sm_text(): db = get_db_dxil() instrs = [i for i in db.instr if i.is_dxil_op] instrs = sorted( instrs, key=lambda v: (v.shader_model, v.shader_stages, v.dxil_opid) ) last_model = None last_stage = None grouped_instrs = [] code = "" def flush_instrs(grouped_instrs, last_model, last_stage): if len(grouped_instrs) == 0: return "" result = format_comment( "// ", "Instructions: %s" % ", ".join([i.name + "=" + str(i.dxil_opid) for i in grouped_instrs]), ) result += ( "if (" + build_range_code("op", [i.dxil_opid for i in grouped_instrs]) + ")\n" ) result += " return " model_cond = stage_cond = None if last_model != (6, 0): model_cond = "major > %d || (major == %d && minor >= %d)" % ( last_model[0], last_model[0], last_model[1], ) if last_stage: stage_cond = " || ".join( [check_pSM_for_shader_stage[c] for c in last_stage] ) if model_cond or stage_cond: result += "\n && ".join( ["(%s)" % expr for expr in (model_cond, stage_cond) if expr] ) return result + ";\n" else: # don't write these out, instead fall through return "" for i in instrs: if (i.shader_model, i.shader_stages) != (last_model, last_stage): code += flush_instrs(grouped_instrs, last_model, last_stage) grouped_instrs = [] last_model = i.shader_model last_stage = i.shader_stages grouped_instrs.append(i) code += flush_instrs(grouped_instrs, last_model, last_stage) code += "return true;\n" return code def get_sigpoint_table(): db = get_db_dxil() gen = db_sigpoint_gen(db) return run_with_stdout(lambda: gen.print_sigpoint_table()) def get_sigpoint_rst(): "Create an rst table for SigPointKind." db = get_db_dxil() rows = [row[:] for row in db.sigpoint_table[:-1]] # Copy table e = dict([(v.name, v) for v in db.enum_idx["SigPointKind"].values]) rows[0] = ["ID"] + rows[0] + ["Description"] for i in range(1, len(rows)): row = rows[i] v = e[row[0]] rows[i] = [v.value] + row + [v.doc] return "\n\n" + format_rst_table(rows) + "\n\n" def get_sem_interpretation_enum_rst(): db = get_db_dxil() rows = [["ID", "Name", "Description"]] + [ [v.value, v.name, v.doc] for v in db.enum_idx["SemanticInterpretationKind"].values[:-1] ] return "\n\n" + format_rst_table(rows) + "\n\n" def get_sem_interpretation_table_rst(): db = get_db_dxil() return "\n\n" + format_rst_table(db.interpretation_table) + "\n\n" def get_interpretation_table(): db = get_db_dxil() gen = db_sigpoint_gen(db) return run_with_stdout(lambda: gen.print_interpretation_table()) highest_major = 6 highest_minor = 8 highest_shader_models = {4: 1, 5: 1, 6: highest_minor} def getShaderModels(): shader_models = [] for major, minor in highest_shader_models.items(): for i in range(0, minor + 1): shader_models.append(str(major) + "_" + str(i)) return shader_models def get_highest_shader_model(): result = """static const unsigned kHighestMajor = %d; static const unsigned kHighestMinor = %d;""" % ( highest_major, highest_minor, ) return result def get_dxil_version_minor(): return "const unsigned kDxilMinor = %d;" % highest_minor def get_dxil_version_minor_int(): return highest_minor def get_is_shader_model_plus(): result = "" for i in range(0, highest_minor + 1): result += "bool IsSM%d%dPlus() const { return IsSMAtLeast(%d, %d); }\n" % ( highest_major, i, highest_major, i, ) return result profile_to_kind = { "ps": "Kind::Pixel", "vs": "Kind::Vertex", "gs": "Kind::Geometry", "hs": "5_0", "ds": "5_0", "cs": "4_0", "lib": "6_1", "ms": "6_5", "as": "6_5", } class shader_profile(object): "The profile description for a DXIL instruction" def __init__(self, kind, kind_name, enum_name, start_sm, input_size, output_size): self.kind = kind # position in parameter list self.kind_name = kind_name self.enum_name = enum_name self.start_sm = start_sm self.input_size = input_size self.output_size = output_size # kind is from DXIL::ShaderKind. shader_profiles = [ shader_profile(0, "ps", "Kind::Pixel", "4_0", 32, 8), shader_profile(1, "vs", "Kind::Vertex", "4_0", 32, 32), shader_profile(2, "gs", "Kind::Geometry", "4_0", 32, 32), shader_profile(3, "hs", "Kind::Hull", "5_0", 32, 32), shader_profile(4, "ds", "Kind::Domain", "5_0", 32, 32), shader_profile(5, "cs", "Kind::Compute", "4_0", 0, 0), shader_profile(6, "lib", "Kind::Library", "6_1", 32, 32), shader_profile(13, "ms", "Kind::Mesh", "6_5", 0, 0), shader_profile(14, "as", "Kind::Amplification", "6_5", 0, 0), ] def getShaderProfiles(): # order match DXIL::ShaderKind. profiles = ( ("ps", "4_0"), ("vs", "4_0"), ("gs", "4_0"), ("hs", "5_0"), ("ds", "5_0"), ("cs", "4_0"), ("lib", "6_1"), ("ms", "6_5"), ("as", "6_5"), ) return profiles def get_shader_models(): result = "" for profile in shader_profiles: min_sm = profile.start_sm input_size = profile.input_size output_size = profile.output_size kind = profile.kind kind_name = profile.kind_name enum_name = profile.enum_name for major, minor in highest_shader_models.items(): UAV_info = "true, true, UINT_MAX" if major > 5: pass elif major == 4: UAV_info = "false, false, 0" if kind == "cs": UAV_info = "true, false, 1" elif major == 5: UAV_info = "true, true, 64" for i in range(0, minor + 1): sm = "%d_%d" % (major, i) if min_sm > sm: continue input_size = profile.input_size output_size = profile.output_size if major == 4: if i == 0: if kind_name == "gs": input_size = 16 elif kind_name == "vs": input_size = 16 output_size = 16 sm_name = "%s_%s" % (kind_name, sm) result += 'SM(%s, %d, %d, "%s", %d, %d, %s),\n' % ( enum_name, major, i, sm_name, input_size, output_size, UAV_info, ) if kind_name == "lib": result += ( "// lib_6_x is for offline linking only, and relaxes restrictions\n" ) result += 'SM(Kind::Library, 6, kOfflineMinor, "lib_6_x", 32, 32, true, true, UINT_MAX),\n' result += ( "// Values before Invalid must remain sorted by Kind, then Major, then Minor.\n" ) result += 'SM(Kind::Invalid, 0, 0, "invalid", 0, 0, false, false, 0),\n' return result def get_num_shader_models(): count = 0 for profile in shader_profiles: min_sm = profile.start_sm input_size = profile.input_size output_size = profile.output_size kind = profile.kind kind_name = profile.kind_name enum_name = profile.enum_name for major, minor in highest_shader_models.items(): for i in range(0, minor + 1): sm = "%d_%d" % (major, i) if min_sm > sm: continue count += 1 if kind_name == "lib": # for lib_6_x count += 1 # for invalid shader_model. count += 1 return "static const unsigned kNumShaderModels = %d;" % count def build_shader_model_hash_idx_map(): # must match get_shader_models. result = "const static std::pair<unsigned, unsigned> hashToIdxMap[] = {\n" count = 0 for profile in shader_profiles: min_sm = profile.start_sm kind = profile.kind kind_name = profile.kind_name for major, minor in highest_shader_models.items(): for i in range(0, minor + 1): sm = "%d_%d" % (major, i) if min_sm > sm: continue sm_name = "%s_%s" % (kind_name, sm) hash_v = kind << 16 | major << 8 | i result += "{%d,%d}, //%s\n" % (hash_v, count, sm_name) count += 1 if kind_name == "lib": result += ( "// lib_6_x is for offline linking only, and relaxes restrictions\n" ) major = 6 # static const unsigned kOfflineMinor = 0xF; i = 15 hash_v = kind << 16 | major << 8 | i result += "{%d,%d},//%s\n" % (hash_v, count, "lib_6_x") count += 1 result += "};\n" return result def get_validation_version(): result = ( """// 1.0 is the first validator. // 1.1 adds: // - ILDN container part support // 1.2 adds: // - Metadata for floating point denorm mode // 1.3 adds: // - Library support // - Raytracing support // - i64/f64 overloads for rawBufferLoad/Store // 1.4 adds: // - packed u8x4/i8x4 dot with accumulate to i32 // - half dot2 with accumulate to float // 1.5 adds: // - WaveMatch, WaveMultiPrefixOp, WaveMultiPrefixBitCount // - HASH container part support // - Mesh and Amplification shaders // - DXR 1.1 & RayQuery support *pMajor = 1; *pMinor = %d; """ % highest_minor ) return result def get_target_profiles(): result = 'HelpText<"Set target profile. \\n' result += "\\t<profile>: " profiles = getShaderProfiles() shader_models = getShaderModels() base_sm = "%d_0" % highest_major for profile, min_sm in profiles: for shader_model in shader_models: if base_sm > shader_model: continue if min_sm > shader_model: continue result += "%s_%s, " % (profile, shader_model) result += "\\n\\t\\t " result += '">;' return result def get_min_validator_version(): result = "" for i in range(0, highest_minor + 1): result += "case %d:\n" % i result += " ValMinor = %d;\n" % i result += " break;\n" return result def get_dxil_version(): result = "" for i in range(0, highest_minor + 1): result += "case %d:\n" % i result += " DxilMinor = %d;\n" % i result += " break;\n" result += "case kOfflineMinor: // Always update this to highest dxil version\n" result += " DxilMinor = %d;\n" % highest_minor result += " break;\n" return result def get_shader_model_get(): # const static std::pair<unsigned, unsigned> hashToIdxMap[] = {}; result = build_shader_model_hash_idx_map() result += "unsigned hash = (unsigned)Kind << 16 | Major << 8 | Minor;\n" result += "auto pred = [](const std::pair<unsigned, unsigned>& elem, unsigned val){ return elem.first < val;};\n" result += "auto it = std::lower_bound(std::begin(hashToIdxMap), std::end(hashToIdxMap), hash, pred);\n" result += "if (it == std::end(hashToIdxMap) || it->first != hash)\n" result += " return GetInvalid();\n" result += "return &ms_ShaderModels[it->second];" return result def get_shader_model_by_name(): result = "" for i in range(2, highest_minor + 1): result += "case '%d':\n" % i result += " if (Major == %d) {\n" % highest_major result += " Minor = %d;\n" % i result += " break;\n" result += " }\n" result += "else return GetInvalid();\n" return result def get_is_valid_for_dxil(): result = "" for i in range(0, highest_minor + 1): result += "case %d:\n" % i return result def RunCodeTagUpdate(file_path): import os import CodeTags print(" ... updating " + file_path) args = [file_path, file_path + ".tmp"] result = CodeTags.main(args) if result != 0: print(" ... error: %d" % result) else: with open(file_path, "rt") as f: before = f.read() with open(file_path + ".tmp", "rt") as f: after = f.read() if before == after: print(" --- no changes found") else: print(" +++ changes found, updating file") with open(file_path, "wt") as f: f.write(after) os.remove(file_path + ".tmp") if __name__ == "__main__": parser = argparse.ArgumentParser( description="Generate code to handle instructions." ) parser.add_argument( "-gen", choices=["docs-ref", "docs-spec", "inst-header", "enums", "oloads", "valfns"], help="Output type to generate.", ) parser.add_argument("-update-files", action="store_const", const=True) args = parser.parse_args() db = get_db_dxil() # used by all generators, also handy to have it run validation if args.gen == "docs-ref": gen = db_docsref_gen(db) gen.print_content() if args.gen == "docs-spec": import os, docutils.core assert ( "HLSL_SRC_DIR" in os.environ ), "Environment variable HLSL_SRC_DIR is not defined" hlsl_src_dir = os.environ["HLSL_SRC_DIR"] spec_file = os.path.abspath(os.path.join(hlsl_src_dir, "docs/DXIL.rst")) with open(spec_file) as f: s = docutils.core.publish_file(f, writer_name="html") if args.gen == "inst-header": gen = db_instrhelp_gen(db) gen.print_content() if args.gen == "enums": gen = db_enumhelp_gen(db) gen.print_content() if args.gen == "oloads": gen = db_oload_gen(db) gen.print_content() if args.gen == "valfns": gen = db_valfns_gen(db) gen.print_content() if args.update_files: print("Updating files ...") import CodeTags import os assert ( "HLSL_SRC_DIR" in os.environ ), "Environment variable HLSL_SRC_DIR is not defined" hlsl_src_dir = os.environ["HLSL_SRC_DIR"] pj = lambda *parts: os.path.abspath(os.path.join(*parts)) files = [ "docs/DXIL.rst", "lib/DXIL/DxilOperations.cpp", "lib/DXIL/DxilShaderModel.cpp", "include/dxc/DXIL/DxilConstants.h", "include/dxc/DXIL/DxilShaderModel.h", "include/dxc/Support/HLSLOptions.td", "include/dxc/DXIL/DxilInstructions.h", "lib/HLSL/DxcOptimizer.cpp", "lib/DxilPIXPasses/DxilPIXPasses.cpp", "lib/HLSL/DxilValidation.cpp", "tools/clang/lib/Sema/gen_intrin_main_tables_15.h", "include/dxc/HlslIntrinsicOp.h", "tools/clang/tools/dxcompiler/dxcdisassembler.cpp", "include/dxc/DXIL/DxilSigPoint.inl", "include/dxc/DXIL/DxilCounters.h", "lib/DXIL/DxilCounters.cpp", "lib/DXIL/DxilMetadataHelper.cpp", "include/dxc/DxilContainer/RDAT_LibraryTypes.inl", ] for relative_file_path in files: RunCodeTagUpdate(pj(hlsl_src_dir, relative_file_path))
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/hct/hctshortcut.js
/////////////////////////////////////////////////////////////////////////////// // // // hctshortcut.js // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // /////////////////////////////////////////////////////////////////////////////// // // Use this script to create a shortcut on your desktop that will set up the // right console environment. // var shell = WScript.CreateObject("WScript.Shell"); var linkName = "HLSL console"; var hctPath = WScript.ScriptFullName; hctPath = hctPath.substr(0, hctPath.lastIndexOf("\\")); var hctStartPath = hctPath + "\\hctstart.cmd"; var srcPath = hctPath; // root\utils\hct srcPath = srcPath.substr(0, srcPath.lastIndexOf("\\")); // root\utils srcPath = srcPath.substr(0, srcPath.lastIndexOf("\\")); // root var binPath = srcPath; // somewhere\root binPath = srcPath.substr(0, srcPath.lastIndexOf("\\")); // somewhere\ binPath = binPath + "\\hlsl.bin"; var desktopPath = shell.SpecialFolders("Desktop"); var shortcut = shell.CreateShortcut(desktopPath + "\\" + linkName + ".lnk"); shortcut.TargetPath = shell.ExpandEnvironmentStrings("%windir%\\System32\\cmd.exe"); shortcut.Arguments = "/k " + hctStartPath + " " + srcPath + " " + binPath; shortcut.Save(); WScript.Echo("Shortcut '" + linkName + "' created on desktop.");
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/hct/hctdb.py
# Copyright (C) Microsoft Corporation. All rights reserved. # This file is distributed under the University of Illinois Open Source License. See LICENSE.TXT for details. ############################################################################### # DXIL information. # ############################################################################### import os all_stages = ( "vertex", "pixel", "geometry", "compute", "hull", "domain", "library", "raygeneration", "intersection", "anyhit", "closesthit", "miss", "callable", "mesh", "amplification", ) # These counters aren't collected directly from instructions, # so they need to be added manually so they can be accessed # with custom code in DxilCounters.cpp. extra_counters = [ "insts", "branches", "array_tgsm_bytes", "array_static_bytes", "array_local_bytes", "array_tgsm_ldst", "array_static_ldst", "array_local_ldst", ] class db_dxil_enum_value(object): "A representation for a value in an enumeration type" def __init__(self, name, value, doc): self.name = name # Name (identifier) self.value = value # Numeric value self.doc = doc # Documentation string self.category = None class db_dxil_enum(object): "A representation for an enumeration type" def __init__(self, name, doc, valNameDocTuples=()): self.name = name self.doc = doc self.values = [ db_dxil_enum_value(n, v, d) for v, n, d in valNameDocTuples ] # Note transmutation self.is_internal = False # whether this is never serialized def value_names(self): return [i.name for i in self.values] class db_dxil_inst(object): "A representation for a DXIL instruction" def __init__(self, name, **kwargs): self.name = name # short, unique name self.llvm_id = 0 # ID of LLVM instruction self.llvm_name = "" # name of LLVM instruction type self.is_dxil_op = False # whether this is a call into a built-in DXIL function self.dxil_op = "" # name of DXIL operation self.dxil_opid = 0 # ID of DXIL operation self.dxil_class = "" # name of the opcode class self.category = "" # classification for this instruction self.doc = "" # the documentation description of this instruction self.remarks = "" # long-form remarks on this instruction self.ops = [] # the operands that this instruction takes self.is_allowed = True # whether this instruction is allowed in a DXIL program self.oload_types = "" # overload types if applicable self.fn_attr = "" # attribute shorthands: rn=does not access memory,ro=only reads from memory, self.is_deriv = False # whether this is some kind of derivative self.is_gradient = False # whether this requires a gradient calculation self.is_feedback = False # whether this is a sampler feedback op self.is_wave = False # whether this requires in-wave, cross-lane functionality self.requires_uniform_inputs = False # whether this operation requires that all of its inputs are uniform across the wave self.is_barrier = False # whether this is a barrier operation self.shader_stages = () # shader stages to which this applies, empty for all. self.shader_model = 6, 0 # minimum shader model required self.inst_helper_prefix = None self.fully_qualified_name_prefix = "hlsl::OP::OpCode" for k, v in list(kwargs.items()): setattr(self, k, v) self.is_dxil_op = self.dxil_op != "" # whether this is a DXIL operation self.is_reserved = self.dxil_class == "Reserved" self.shader_model_translated = () # minimum shader model required with translation by linker self.props = {} # extra properties def __str__(self): return self.name def fully_qualified_name(self): return "{}::{}".format(self.fully_qualified_name_prefix, self.name) class db_dxil_metadata(object): "A representation for a metadata record" def __init__(self, name, doc, **kwargs): self.name = name # named metadata, possibly empty self.doc = doc # the documentation description of this record for k, v in list(kwargs.items()): setattr(self, k, v) class db_dxil_param(object): "The parameter description for a DXIL instruction" def __init__(self, pos, llvm_type, name, doc, **kwargs): self.pos = pos # position in parameter list self.llvm_type = llvm_type # llvm type name, $o for overload, $r for resource type, $cb for legacy cbuffer, $u4 for u4 struct self.name = name # short, unique name self.doc = doc # the documentation description of this parameter self.is_const = ( False # whether this argument requires a constant value in the IR ) self.enum_name = "" # the name of the enum type if applicable self.max_value = None # the maximum value for this parameter if applicable for k, v in kwargs.items(): setattr(self, k, v) class db_dxil_pass(object): "The description for a DXIL optimization pass" def __init__(self, name, **kwargs): self.name = name # name for the option, typically the command-line switch name self.args = [] # modifiers for the option self.type_name = "" # name of the class that implements the pass self.doc = "" # documentation for the pass self.category_lib = "" # lib which pass belongs to for k, v in kwargs.items(): setattr(self, k, v) class db_dxil_pass_arg(object): "An argument to a DXIL optimization pass" def __init__(self, name, **kwargs): self.name = name # name for the option, typically the command-line switch name self.ident = "" # identifier for a parameter or global switch self.is_ctor_param = False # whether this is a constructor parameter for k, v in kwargs.items(): setattr(self, k, v) if self.is_ctor_param: self.is_ctor_param = True class db_dxil_valrule(object): "The description of a validation rule." def __init__(self, name, id, **kwargs): self.name = name.upper() # short, unique name, eg META.KNOWN self.rule_id = id # unique identifier self.enum_name = name.replace(".", "") # remove period for enum name self.group_name = self.name[: self.name.index(".")] # group name, eg META self.rule_name = self.name[self.name.index(".") + 1 :] # rule name, eg KNOWN self.definition = ( "Check" + self.group_name + self.rule_name ) # function name that defines this constraint self.is_disabled = False # True if the validation rule does not apply self.err_msg = "" # error message associated with rule self.category = "" # classification for this rule self.doc = "" # the documentation description of this rule self.shader_stages = () # shader stages to which this applies, empty for all. self.shader_model = 6, 0 # minimum shader model required for k, v in list(kwargs.items()): setattr(self, k, v) def __str__(self): return self.name class db_dxil(object): "A database of DXIL instruction data" def __init__(self): self.instr = [] # DXIL instructions self.enums = [] # enumeration types self.val_rules = [] # validation rules self.metadata = [] # named metadata (db_dxil_metadata) self.passes = [] # inventory of available passes (db_dxil_pass) self.name_idx = {} # DXIL instructions by name self.enum_idx = {} # enumerations by name self.dxil_version_info = {} # list of counters for instructions and dxil ops, # starting with extra ones specified here self.counters = extra_counters self.populate_llvm_instructions() self.call_instr = self.get_instr_by_llvm_name("CallInst") self.populate_dxil_operations() self.build_indices() self.populate_extended_docs() self.populate_categories_and_models() self.build_opcode_enum() self.mark_disallowed_operations() self.populate_metadata() self.populate_passes() self.build_valrules() self.build_semantics() self.build_indices() self.populate_counters() def __str__(self): return "\n".join(str(i) for i in self.instr) def add_enum_type(self, name, doc, valNameDocTuples): "Adds a new enumeration type with name/value/doc tuples" self.enums.append(db_dxil_enum(name, doc, valNameDocTuples)) def build_indices(self): "Build a name_idx dictionary with instructions and an enum_idx dictionary with enumeration types" self.name_idx = {} for i in self.instr: self.name_idx[i.name] = i self.enum_idx = {} for i in self.enums: self.enum_idx[i.name] = i def build_opcode_enum(self): # Build enumeration from instructions OpCodeEnum = db_dxil_enum( "OpCode", "Enumeration for operations specified by DXIL" ) class_dict = {} class_dict["LlvmInst"] = "LLVM Instructions" for i in self.instr: if i.is_dxil_op: v = db_dxil_enum_value(i.dxil_op, i.dxil_opid, i.doc) v.category = i.category class_dict[i.dxil_class] = i.category OpCodeEnum.values.append(v) self.enums.append(OpCodeEnum) OpCodeClass = db_dxil_enum( "OpCodeClass", "Groups for DXIL operations with equivalent function templates", ) OpCodeClass.is_internal = True for k, v in iter(class_dict.items()): ev = db_dxil_enum_value(k, 0, None) ev.category = v OpCodeClass.values.append(ev) self.enums.append(OpCodeClass) def mark_disallowed_operations(self): # Disallow indirect branching, unreachable instructions and support for exception unwinding. for i in "IndirectBr,Invoke,Resume,LandingPad,Unreachable".split(","): self.name_idx[i].is_allowed = False for i in "UserOp1,UserOp2,VAArg".split(","): self.name_idx[i].is_allowed = False # Disallow conversions used for pointer math; GEP is used exclusively in the current model. for i in "PtrToInt,IntToPtr".split(","): self.name_idx[i].is_allowed = False # Barrier supersedes Fence. self.name_idx["Fence"].is_allowed = False def verify_dense(self, it, pred, name_proj): val = None for i in it: i_val = pred(i) if not val is None: assert val + 1 == i_val, ( "values in predicate are not sequential and dense, %d follows %d for %s" % (i_val, val, name_proj(i)) ) val = i_val def set_op_count_for_version(self, major, minor, op_count): info = self.dxil_version_info.setdefault((major, minor), dict()) info["NumOpCodes"] = op_count info["NumOpClasses"] = len(set([op.dxil_class for op in self.instr])) def populate_categories_and_models(self): "Populate the category and shader_stages member of instructions." for ( i ) in "TempRegLoad,TempRegStore,MinPrecXRegLoad,MinPrecXRegStore,LoadInput,StoreOutput".split( "," ): self.name_idx[i].category = "Temporary, indexable, input, output registers" for ( i ) in "FAbs,Saturate,IsNaN,IsInf,IsFinite,IsNormal,Cos,Sin,Tan,Acos,Asin,Atan,Hcos,Hsin,Htan,Exp,Frc,Log,Sqrt,Rsqrt".split( "," ): self.name_idx[i].category = "Unary float" for i in "Round_ne,Round_ni,Round_pi,Round_z".split(","): self.name_idx[i].category = "Unary float - rounding" for i in "Bfrev,Countbits,FirstbitLo,FirstbitSHi".split(","): self.name_idx[i].category = "Unary int" for i in "FirstbitHi".split(","): self.name_idx[i].category = "Unary uint" for i in "FMax,FMin".split(","): self.name_idx[i].category = "Binary float" for i in "IMax,IMin,Add,Sub,Mul,SDiv,SRem,And,Or,Xor,AShr,LShr,Shl".split(","): self.name_idx[i].category = "Binary int" for i in "UMax,UMin,UMul,UDiv,URem".split(","): self.name_idx[i].category = "Binary uint" for i in "IMul".split(","): self.name_idx[i].category = "Binary int with two outputs" for i in "UMul,UDiv".split(","): # Rename this UDiv OpCode to UDivMod self.name_idx[i].category = "Binary uint with two outputs" for i in "UAddc,USubb".split(","): self.name_idx[i].category = "Binary uint with carry or borrow" for i in "FMad,Fma".split(","): self.name_idx[i].category = "Tertiary float" for i in "IMad,Msad,Ibfe".split(","): self.name_idx[i].category = "Tertiary int" for i in "UMad,Ubfe".split(","): self.name_idx[i].category = "Tertiary uint" for i in "Bfi".split(","): self.name_idx[i].category = "Quaternary" for i in "Dot2,Dot3,Dot4".split(","): self.name_idx[i].category = "Dot" for ( i ) in "CreateHandle,CBufferLoad,CBufferLoadLegacy,TextureLoad,TextureStore,TextureStoreSample,BufferLoad,BufferStore,BufferUpdateCounter,CheckAccessFullyMapped,GetDimensions,RawBufferLoad,RawBufferStore".split( "," ): self.name_idx[i].category = "Resources" for ( i ) in "Sample,SampleBias,SampleLevel,SampleGrad,SampleCmp,SampleCmpLevelZero,SampleCmpLevel,SampleCmpBias,SampleCmpGrad,Texture2DMSGetSamplePosition,RenderTargetGetSamplePosition,RenderTargetGetSampleCount".split( "," ): self.name_idx[i].category = "Resources - sample" for i in "Sample,SampleBias,SampleCmp,SampleCmpBias".split(","): self.name_idx[i].shader_stages = ( "library", "pixel", "compute", "amplification", "mesh", "node", ) for i in "RenderTargetGetSamplePosition,RenderTargetGetSampleCount".split(","): self.name_idx[i].shader_stages = ("pixel",) for i in "TextureGather,TextureGatherCmp,TextureGatherRaw".split(","): self.name_idx[i].category = "Resources - gather" for i in "AtomicBinOp,AtomicCompareExchange".split(","): self.name_idx[i].category = "Synchronization" for i in "CalculateLOD,DerivCoarseX,DerivCoarseY,DerivFineX,DerivFineY".split( "," ): self.name_idx[i].category = "Derivatives" self.name_idx[i].shader_stages = ( "library", "pixel", "compute", "amplification", "mesh", "node", ) for ( i ) in "Discard,EvalSnapped,EvalSampleIndex,EvalCentroid,SampleIndex,Coverage,InnerCoverage,AttributeAtVertex".split( "," ): self.name_idx[i].category = "Pixel shader" self.name_idx[i].shader_stages = ("pixel",) for i in "ThreadId,GroupId,ThreadIdInGroup,FlattenedThreadIdInGroup".split(","): self.name_idx[i].category = "Compute/Mesh/Amplification/Node shader" self.name_idx[i].shader_stages = ( "compute", "mesh", "amplification", "node", ) for i in "EmitStream,CutStream,EmitThenCutStream,GSInstanceID".split(","): self.name_idx[i].category = "Geometry shader" self.name_idx[i].shader_stages = ("geometry",) for i in "LoadOutputControlPoint,LoadPatchConstant".split(","): self.name_idx[i].category = "Domain and hull shader" self.name_idx[i].shader_stages = ("domain", "hull") for i in "DomainLocation".split(","): self.name_idx[i].category = "Domain shader" self.name_idx[i].shader_stages = ("domain",) for i in "StorePatchConstant,OutputControlPointID".split(","): self.name_idx[i].category = "Hull shader" self.name_idx[i].shader_stages = ("hull",) for i in "PrimitiveID".split(","): self.name_idx[i].category = "Hull, Domain and Geometry shaders" self.name_idx[i].shader_stages = ("geometry", "domain", "hull") for i in "ViewID".split(","): self.name_idx[i].category = "Graphics shader" self.name_idx[i].shader_stages = ( "vertex", "hull", "domain", "geometry", "pixel", "mesh", ) for ( i ) in "MakeDouble,SplitDouble,LegacyDoubleToFloat,LegacyDoubleToSInt32,LegacyDoubleToUInt32".split( "," ): self.name_idx[i].category = "Double precision" for i in "CycleCounterLegacy".split(","): self.name_idx[i].category = "Other" for i in "LegacyF32ToF16,LegacyF16ToF32".split(","): self.name_idx[i].category = "Legacy floating-point" for i in self.instr: if i.name.startswith("Wave"): i.category = "Wave" i.is_wave = True i.shader_stages = ( "library", "compute", "amplification", "mesh", "pixel", "vertex", "hull", "domain", "geometry", "raygeneration", "intersection", "anyhit", "closesthit", "miss", "callable", "node", ) elif i.name.startswith("Quad"): i.category = "Quad Wave Ops" i.is_wave = True i.shader_stages = ( "library", "compute", "amplification", "mesh", "pixel", "node", ) elif i.name.startswith("Bitcast"): i.category = "Bitcasts with different sizes" for i in "ViewID,AttributeAtVertex".split(","): self.name_idx[i].shader_model = 6, 1 for i in "RawBufferLoad,RawBufferStore".split(","): self.name_idx[i].shader_model = 6, 2 self.name_idx[i].shader_model_translated = 6, 0 for i in "DispatchRaysIndex,DispatchRaysDimensions".split(","): self.name_idx[i].category = "Ray Dispatch Arguments" self.name_idx[i].shader_model = 6, 3 self.name_idx[i].shader_stages = ( "library", "raygeneration", "intersection", "anyhit", "closesthit", "miss", "callable", ) for i in "InstanceID,InstanceIndex,PrimitiveIndex".split(","): self.name_idx[i].category = "Raytracing object space uint System Values" self.name_idx[i].shader_model = 6, 3 self.name_idx[i].shader_stages = ( "library", "intersection", "anyhit", "closesthit", ) for i in "GeometryIndex".split(","): self.name_idx[ i ].category = ( "Raytracing object space uint System Values, raytracing tier 1.1" ) self.name_idx[i].shader_model = 6, 5 self.name_idx[i].shader_stages = ( "library", "intersection", "anyhit", "closesthit", ) for i in "HitKind".split(","): self.name_idx[i].category = "Raytracing hit uint System Values" self.name_idx[i].shader_model = 6, 3 self.name_idx[i].shader_stages = ( "library", "intersection", "anyhit", "closesthit", ) for i in "RayFlags".split(","): self.name_idx[i].category = "Raytracing uint System Values" self.name_idx[i].shader_model = 6, 3 self.name_idx[i].shader_stages = ( "library", "intersection", "anyhit", "closesthit", "miss", ) for i in "WorldRayOrigin,WorldRayDirection".split(","): self.name_idx[i].category = "Ray Vectors" self.name_idx[i].shader_model = 6, 3 self.name_idx[i].shader_stages = ( "library", "intersection", "anyhit", "closesthit", "miss", ) for i in "ObjectRayOrigin,ObjectRayDirection".split(","): self.name_idx[i].category = "Ray object space Vectors" self.name_idx[i].shader_model = 6, 3 self.name_idx[i].shader_stages = ( "library", "intersection", "anyhit", "closesthit", ) for i in "ObjectToWorld,WorldToObject".split(","): self.name_idx[i].category = "Ray Transforms" self.name_idx[i].shader_model = 6, 3 self.name_idx[i].shader_stages = ( "library", "intersection", "anyhit", "closesthit", ) for i in "RayTMin,RayTCurrent".split(","): self.name_idx[i].category = "RayT" self.name_idx[i].shader_model = 6, 3 self.name_idx[i].shader_stages = ( "library", "intersection", "anyhit", "closesthit", "miss", ) for i in "IgnoreHit,AcceptHitAndEndSearch".split(","): self.name_idx[i].category = "AnyHit Terminals" self.name_idx[i].shader_model = 6, 3 self.name_idx[i].shader_stages = ("anyhit",) for i in "CallShader".split(","): self.name_idx[i].category = "Indirect Shader Invocation" self.name_idx[i].shader_model = 6, 3 self.name_idx[i].shader_stages = ( "library", "closesthit", "raygeneration", "miss", "callable", ) for i in "TraceRay".split(","): self.name_idx[i].category = "Indirect Shader Invocation" self.name_idx[i].shader_model = 6, 3 self.name_idx[i].shader_stages = ( "library", "raygeneration", "closesthit", "miss", ) for i in "ReportHit".split(","): self.name_idx[i].category = "Indirect Shader Invocation" self.name_idx[i].shader_model = 6, 3 self.name_idx[i].shader_stages = ("library", "intersection") for i in "CreateHandleForLib".split(","): self.name_idx[ i ].category = ( "Library create handle from resource struct (like HL intrinsic)" ) self.name_idx[i].shader_model = 6, 3 self.name_idx[i].shader_model_translated = 6, 0 for i in "AnnotateHandle,CreateHandleFromBinding,CreateHandleFromHeap".split( "," ): self.name_idx[i].category = "Get handle from heap" self.name_idx[i].shader_model = 6, 6 for i in "AnnotateHandle,CreateHandleFromBinding".split(","): self.name_idx[i].shader_model_translated = 6, 0 for i in "Dot4AddU8Packed,Dot4AddI8Packed,Dot2AddHalf".split(","): self.name_idx[i].category = "Dot product with accumulate" self.name_idx[i].shader_model = 6, 4 for i in "WaveMatch,WaveMultiPrefixOp,WaveMultiPrefixBitCount".split(","): self.name_idx[i].category = "Wave" self.name_idx[i].shader_model = 6, 5 for ( i ) in "SetMeshOutputCounts,EmitIndices,GetMeshPayload,StoreVertexOutput,StorePrimitiveOutput".split( "," ): self.name_idx[i].category = "Mesh shader instructions" self.name_idx[i].shader_stages = ("mesh",) self.name_idx[i].shader_model = 6, 5 for i in "DispatchMesh".split(","): self.name_idx[i].category = "Amplification shader instructions" self.name_idx[i].shader_stages = ("amplification",) self.name_idx[i].shader_model = 6, 5 for i in "WriteSamplerFeedback,WriteSamplerFeedbackBias".split(","): self.name_idx[i].category = "Sampler Feedback" self.name_idx[i].is_feedback = True self.name_idx[i].is_gradient = True self.name_idx[i].shader_model = 6, 5 self.name_idx[i].shader_stages = ( "library", "pixel", ) for i in "WriteSamplerFeedbackLevel,WriteSamplerFeedbackGrad".split(","): self.name_idx[i].category = "Sampler Feedback" self.name_idx[i].is_feedback = True self.name_idx[i].shader_model = 6, 5 for i in ( "AllocateRayQuery,RayQuery_TraceRayInline,RayQuery_Proceed,RayQuery_Abort,RayQuery_CommitNonOpaqueTriangleHit,RayQuery_CommitProceduralPrimitiveHit,RayQuery_RayFlags,RayQuery_WorldRayOrigin,RayQuery_WorldRayDirection,RayQuery_RayTMin," + "RayQuery_CandidateTriangleRayT,RayQuery_CommittedRayT,RayQuery_CandidateInstanceIndex,RayQuery_CandidateInstanceID,RayQuery_CandidateGeometryIndex,RayQuery_CandidatePrimitiveIndex," + "RayQuery_CandidateObjectRayOrigin,RayQuery_CandidateObjectRayDirection,RayQuery_CommittedInstanceIndex,RayQuery_CommittedInstanceID,RayQuery_CommittedGeometryIndex,RayQuery_CommittedPrimitiveIndex," + "RayQuery_CommittedObjectRayOrigin,RayQuery_CommittedObjectRayDirection,RayQuery_CandidateProceduralPrimitiveNonOpaque,RayQuery_CandidateTriangleFrontFace,RayQuery_CommittedTriangleFrontFace," + "RayQuery_CandidateTriangleBarycentrics,RayQuery_CommittedTriangleBarycentrics,RayQuery_CommittedStatus,RayQuery_CandidateType,RayQuery_CandidateObjectToWorld3x4," + "RayQuery_CandidateWorldToObject3x4,RayQuery_CommittedObjectToWorld3x4,RayQuery_CommittedWorldToObject3x4,RayQuery_CandidateInstanceContributionToHitGroupIndex,RayQuery_CommittedInstanceContributionToHitGroupIndex" ).split(","): self.name_idx[i].category = "Inline Ray Query" self.name_idx[i].shader_model = 6, 5 for i in "Unpack4x8".split(","): self.name_idx[i].category = "Unpacking intrinsics" self.name_idx[i].shader_model = 6, 6 for i in "Pack4x8".split(","): self.name_idx[i].category = "Packing intrinsics" self.name_idx[i].shader_model = 6, 6 for i in "IsHelperLane".split(","): self.name_idx[i].category = "Helper Lanes" self.name_idx[i].shader_model = 6, 6 for i in "QuadVote,TextureGatherRaw,SampleCmpLevel,TextureStoreSample".split( "," ): self.name_idx[i].shader_model = 6, 7 for i in "QuadVote".split(","): self.name_idx[i].shader_model_translated = 6, 0 for i in "CreateNodeOutputHandle".split(","): self.name_idx[i].category = "Create/Annotate Node Handles" self.name_idx[i].shader_model = 6, 8 self.name_idx[i].shader_stages = ("node",) for i in "CreateNodeInputRecordHandle,AllocateNodeOutputRecords".split(","): self.name_idx[i].category = "Create/Annotate Node Handles" self.name_idx[i].shader_model = 6, 8 self.name_idx[i].shader_stages = ("node",) for i in "IndexNodeHandle".split(","): self.name_idx[i].category = "Create/Annotate Node Handles" self.name_idx[i].shader_model = 6, 8 self.name_idx[i].shader_stages = ("node",) # TBD: add "library" for i in "AnnotateNodeHandle,AnnotateNodeRecordHandle".split(","): self.name_idx[i].category = "Create/Annotate Node Handles" self.name_idx[i].shader_model = 6, 8 self.name_idx[i].shader_stages = ("node",) # TBD: add "library" for i in "GetNodeRecordPtr".split(","): self.name_idx[i].category = "Get Pointer to Node Record in Address Space 6" self.name_idx[i].shader_model = 6, 8 self.name_idx[i].shader_stages = ("node",) # TBD: add "library" for i in ( "IncrementOutputCount,OutputComplete,GetInputRecordCount,FinishedCrossGroupSharing,NodeOutputIsValid,GetRemainingRecursionLevels" ).split(","): self.name_idx[i].category = "Work Graph intrinsics" self.name_idx[i].shader_model = 6, 8 self.name_idx[i].shader_stages = ("node",) # All barrier ops: for i in "Barrier".split(","): self.name_idx[i].category = "Synchronization" self.name_idx[i].is_barrier = True for i in "BarrierByMemoryType".split(","): self.name_idx[i].category = "Synchronization" self.name_idx[i].is_barrier = True self.name_idx[i].shader_model = 6, 8 self.name_idx[i].shader_model_translated = 6, 0 for i in "BarrierByMemoryHandle".split(","): self.name_idx[i].category = "Synchronization" self.name_idx[i].is_barrier = True self.name_idx[i].shader_model = 6, 8 for i in "BarrierByNodeRecordHandle".split(","): self.name_idx[i].category = "Synchronization" self.name_idx[i].is_barrier = True self.name_idx[i].shader_model = 6, 8 self.name_idx[i].shader_stages = ("node",) for i in "SampleCmpBias,SampleCmpGrad".split(","): self.name_idx[i].category = "Comparison Samples" self.name_idx[i].shader_model = 6, 8 for i in "StartVertexLocation,StartInstanceLocation".split(","): self.name_idx[i].category = "Extended Command Information" self.name_idx[i].shader_stages = ("vertex",) self.name_idx[i].shader_model = 6, 8 def populate_llvm_instructions(self): # Add instructions that map to LLVM instructions. # This is basically include\llvm\IR\Instruction.def # # Some instructions don't have their operands defined here because they are # very specific and expanding generality isn't worth it; for example, # branching refers to basic block arguments. retvoid_param = db_dxil_param(0, "v", "", "no return value") retoload_param = db_dxil_param(0, "$o", "", "no return value") oload_all_arith = "hfd1wil" # note that 8 is missing oload_all_arith_v = "v" + oload_all_arith oload_int_arith = "wil" # note that 8 is missing oload_int_arith_b = "1wil" # note that 8 is missing oload_float_arith = "hfd" oload_cast_params = [ retoload_param, db_dxil_param(1, "$o", "value", "Value to cast/convert"), ] oload_binary_params = [ retoload_param, db_dxil_param(1, "$o", "a", "first value"), db_dxil_param(2, "$o", "b", "second value"), ] self.add_llvm_instr( "TERM", 1, "Ret", "ReturnInst", "returns a value (possibly void), from a function.", oload_all_arith_v, [retoload_param], ) self.add_llvm_instr( "TERM", 2, "Br", "BranchInst", "branches (conditional or unconditional)", "", [], ) self.add_llvm_instr( "TERM", 3, "Switch", "SwitchInst", "performs a multiway switch", "", [] ) self.add_llvm_instr( "TERM", 4, "IndirectBr", "IndirectBrInst", "branches indirectly", "", [] ) self.add_llvm_instr( "TERM", 5, "Invoke", "InvokeInst", "invokes function with normal and exceptional returns", "", [], ) self.add_llvm_instr( "TERM", 6, "Resume", "ResumeInst", "resumes the propagation of an exception", "", [], ) self.add_llvm_instr( "TERM", 7, "Unreachable", "UnreachableInst", "is unreachable", "", [] ) self.add_llvm_instr( "BINARY", 8, "Add", "BinaryOperator", "returns the sum of its two operands", oload_int_arith, oload_binary_params, counters=("ints",), ) self.add_llvm_instr( "BINARY", 9, "FAdd", "BinaryOperator", "returns the sum of its two operands", oload_float_arith, oload_binary_params, counters=("floats",), ) self.add_llvm_instr( "BINARY", 10, "Sub", "BinaryOperator", "returns the difference of its two operands", oload_int_arith, oload_binary_params, counters=("ints",), ) self.add_llvm_instr( "BINARY", 11, "FSub", "BinaryOperator", "returns the difference of its two operands", oload_float_arith, oload_binary_params, counters=("floats",), ) self.add_llvm_instr( "BINARY", 12, "Mul", "BinaryOperator", "returns the product of its two operands", oload_int_arith, oload_binary_params, counters=("ints",), ) self.add_llvm_instr( "BINARY", 13, "FMul", "BinaryOperator", "returns the product of its two operands", oload_float_arith, oload_binary_params, counters=("floats",), ) self.add_llvm_instr( "BINARY", 14, "UDiv", "BinaryOperator", "returns the quotient of its two unsigned operands", oload_int_arith, oload_binary_params, counters=("uints",), ) self.add_llvm_instr( "BINARY", 15, "SDiv", "BinaryOperator", "returns the quotient of its two signed operands", oload_int_arith, oload_binary_params, counters=("ints",), ) self.add_llvm_instr( "BINARY", 16, "FDiv", "BinaryOperator", "returns the quotient of its two operands", oload_float_arith, oload_binary_params, counters=("floats",), ) self.add_llvm_instr( "BINARY", 17, "URem", "BinaryOperator", "returns the remainder from the unsigned division of its two operands", oload_int_arith, oload_binary_params, counters=("uints",), ) self.add_llvm_instr( "BINARY", 18, "SRem", "BinaryOperator", "returns the remainder from the signed division of its two operands", oload_int_arith, oload_binary_params, counters=("ints",), ) self.add_llvm_instr( "BINARY", 19, "FRem", "BinaryOperator", "returns the remainder from the division of its two operands", oload_float_arith, oload_binary_params, counters=("floats",), ) self.add_llvm_instr( "BINARY", 20, "Shl", "BinaryOperator", "shifts left (logical)", oload_int_arith, oload_binary_params, counters=("uints",), ) self.add_llvm_instr( "BINARY", 21, "LShr", "BinaryOperator", "shifts right (logical), with zero bit fill", oload_int_arith, oload_binary_params, counters=("uints",), ) self.add_llvm_instr( "BINARY", 22, "AShr", "BinaryOperator", "shifts right (arithmetic), with 'a' operand sign bit fill", oload_int_arith, oload_binary_params, counters=("ints",), ) self.add_llvm_instr( "BINARY", 23, "And", "BinaryOperator", "returns a bitwise logical and of its two operands", oload_int_arith_b, oload_binary_params, counters=("uints",), ) self.add_llvm_instr( "BINARY", 24, "Or", "BinaryOperator", "returns a bitwise logical or of its two operands", oload_int_arith_b, oload_binary_params, counters=("uints",), ) self.add_llvm_instr( "BINARY", 25, "Xor", "BinaryOperator", "returns a bitwise logical xor of its two operands", oload_int_arith_b, oload_binary_params, counters=("uints",), ) self.add_llvm_instr( "MEMORY", 26, "Alloca", "AllocaInst", "allocates memory on the stack frame of the currently executing function", "", [], ) self.add_llvm_instr( "MEMORY", 27, "Load", "LoadInst", "reads from memory", "", [] ) self.add_llvm_instr( "MEMORY", 28, "Store", "StoreInst", "writes to memory", "", [] ) self.add_llvm_instr( "MEMORY", 29, "GetElementPtr", "GetElementPtrInst", "gets the address of a subelement of an aggregate value", "", [], ) self.add_llvm_instr( "MEMORY", 30, "Fence", "FenceInst", "introduces happens-before edges between operations", "", [], counters=("fence",), ) self.add_llvm_instr( "MEMORY", 31, "AtomicCmpXchg", "AtomicCmpXchgInst", "atomically modifies memory", "", [], counters=("atomic",), ) self.add_llvm_instr( "MEMORY", 32, "AtomicRMW", "AtomicRMWInst", "atomically modifies memory", "", [], counters=("atomic",), ) self.add_llvm_instr( "CAST", 33, "Trunc", "TruncInst", "truncates an integer", oload_int_arith_b, oload_cast_params, counters=("ints",), ) self.add_llvm_instr( "CAST", 34, "ZExt", "ZExtInst", "zero extends an integer", oload_int_arith_b, oload_cast_params, counters=("uints",), ) self.add_llvm_instr( "CAST", 35, "SExt", "SExtInst", "sign extends an integer", oload_int_arith_b, oload_cast_params, counters=("ints",), ) self.add_llvm_instr( "CAST", 36, "FPToUI", "FPToUIInst", "converts a floating point to UInt", oload_all_arith, oload_cast_params, counters=("floats",), ) self.add_llvm_instr( "CAST", 37, "FPToSI", "FPToSIInst", "converts a floating point to SInt", oload_all_arith, oload_cast_params, counters=("floats",), ) self.add_llvm_instr( "CAST", 38, "UIToFP", "UIToFPInst", "converts a UInt to floating point", oload_all_arith, oload_cast_params, counters=("floats",), ) self.add_llvm_instr( "CAST", 39, "SIToFP", "SIToFPInst", "converts a SInt to floating point", oload_all_arith, oload_cast_params, counters=("floats",), ) self.add_llvm_instr( "CAST", 40, "FPTrunc", "FPTruncInst", "truncates a floating point", oload_float_arith, oload_cast_params, counters=("floats",), ) self.add_llvm_instr( "CAST", 41, "FPExt", "FPExtInst", "extends a floating point", oload_float_arith, oload_cast_params, counters=("floats",), ) self.add_llvm_instr( "CAST", 42, "PtrToInt", "PtrToIntInst", "converts a pointer to integer", "i", oload_cast_params, ) self.add_llvm_instr( "CAST", 43, "IntToPtr", "IntToPtrInst", "converts an integer to Pointer", "i", oload_cast_params, ) self.add_llvm_instr( "CAST", 44, "BitCast", "BitCastInst", "performs a bit-preserving type cast", oload_all_arith, oload_cast_params, ) self.add_llvm_instr( "CAST", 45, "AddrSpaceCast", "AddrSpaceCastInst", "casts a value addrspace", "", oload_cast_params, ) self.add_llvm_instr( "OTHER", 46, "ICmp", "ICmpInst", "compares integers", oload_int_arith_b, oload_binary_params, counters=("ints",), ) self.add_llvm_instr( "OTHER", 47, "FCmp", "FCmpInst", "compares floating points", oload_float_arith, oload_binary_params, counters=("floats",), ) self.add_llvm_instr( "OTHER", 48, "PHI", "PHINode", "is a PHI node instruction", "", [] ) self.add_llvm_instr("OTHER", 49, "Call", "CallInst", "calls a function", "", []) self.add_llvm_instr( "OTHER", 50, "Select", "SelectInst", "selects an instruction", "", [] ) self.add_llvm_instr( "OTHER", 51, "UserOp1", "Instruction", "may be used internally in a pass", "", [], ) self.add_llvm_instr( "OTHER", 52, "UserOp2", "Instruction", "internal to passes only", "", [] ) self.add_llvm_instr( "OTHER", 53, "VAArg", "VAArgInst", "vaarg instruction", "", [] ) self.add_llvm_instr( "OTHER", 57, "ExtractValue", "ExtractValueInst", "extracts from aggregate", "", [], ) self.add_llvm_instr( "OTHER", 59, "LandingPad", "LandingPadInst", "represents a landing pad", "", [], ) def populate_dxil_operations(self): # $o in a parameter type means the overload type # $r in a parameter type means the resource type # $cb in a parameter type means cbuffer legacy load return type # overload types are a string of (v)oid, (h)alf, (f)loat, (d)ouble, (1)-bit, (8)-bit, (w)ord, (i)nt, (l)ong self.opcode_param = db_dxil_param(1, "i32", "opcode", "DXIL opcode") retvoid_param = db_dxil_param(0, "v", "", "no return value") next_op_idx = 0 self.add_dxil_op( "TempRegLoad", next_op_idx, "TempRegLoad", "helper load operation", "hfwi", "ro", [ db_dxil_param(0, "$o", "", "register value"), db_dxil_param(2, "u32", "index", "linearized register index"), ], ) next_op_idx += 1 self.add_dxil_op( "TempRegStore", next_op_idx, "TempRegStore", "helper store operation", "hfwi", "", [ retvoid_param, db_dxil_param(2, "u32", "index", "linearized register index"), db_dxil_param(3, "$o", "value", "value to store"), ], ) next_op_idx += 1 self.add_dxil_op( "MinPrecXRegLoad", next_op_idx, "MinPrecXRegLoad", "helper load operation for minprecision", "hw", "ro", [ db_dxil_param(0, "$o", "", "register value"), db_dxil_param(2, "pf32", "regIndex", "pointer to indexable register"), db_dxil_param(3, "i32", "index", "index"), db_dxil_param(4, "u8", "component", "component"), ], ) next_op_idx += 1 self.add_dxil_op( "MinPrecXRegStore", next_op_idx, "MinPrecXRegStore", "helper store operation for minprecision", "hw", "", [ retvoid_param, db_dxil_param(2, "pf32", "regIndex", "pointer to indexable register"), db_dxil_param(3, "i32", "index", "index"), db_dxil_param(4, "u8", "component", "component"), db_dxil_param(5, "$o", "value", "value to store"), ], ) next_op_idx += 1 self.add_dxil_op( "LoadInput", next_op_idx, "LoadInput", "loads the value from shader input", "hfwi", "rn", [ db_dxil_param(0, "$o", "", "input value"), db_dxil_param(2, "u32", "inputSigId", "input signature element ID"), db_dxil_param(3, "u32", "rowIndex", "row index relative to element"), db_dxil_param(4, "u8", "colIndex", "column index relative to element"), db_dxil_param(5, "i32", "gsVertexAxis", "gsVertexAxis"), ], counters=("sig_ld",), ) next_op_idx += 1 self.add_dxil_op( "StoreOutput", next_op_idx, "StoreOutput", "stores the value to shader output", "hfwi", "", [ # note, cannot store bit even though load supports it retvoid_param, db_dxil_param(2, "u32", "outputSigId", "output signature element ID"), db_dxil_param(3, "u32", "rowIndex", "row index relative to element"), db_dxil_param(4, "u8", "colIndex", "column index relative to element"), db_dxil_param(5, "$o", "value", "value to store"), ], counters=("sig_st",), ) next_op_idx += 1 def UFI(name, **mappings): name = name.upper() for k, v in mappings.items(): if name.startswith(k): return v if name.upper().startswith("F"): return "floats" elif name.upper().startswith("U"): return "uints" else: return "ints" # Unary float operations are regular. for i in "FAbs,Saturate".split(","): self.add_dxil_op( i, next_op_idx, "Unary", "returns the " + i, "hfd", "rn", [ db_dxil_param(0, "$o", "", "operation result"), db_dxil_param(2, "$o", "value", "input value"), ], counters=("floats",), ) next_op_idx += 1 for i in "IsNaN,IsInf,IsFinite,IsNormal".split(","): self.add_dxil_op( i, next_op_idx, "IsSpecialFloat", "returns the " + i, "hf", "rn", [ db_dxil_param(0, "i1", "", "operation result"), db_dxil_param(2, "$o", "value", "input value"), ], counters=("floats",), ) next_op_idx += 1 for ( i ) in "Cos,Sin,Tan,Acos,Asin,Atan,Hcos,Hsin,Htan,Exp,Frc,Log,Sqrt,Rsqrt,Round_ne,Round_ni,Round_pi,Round_z".split( "," ): self.add_dxil_op( i, next_op_idx, "Unary", "returns the " + i, "hf", "rn", [ db_dxil_param(0, "$o", "", "operation result"), db_dxil_param(2, "$o", "value", "input value"), ], counters=("floats",), ) next_op_idx += 1 # Unary int operations are regular. for i in "Bfrev".split(","): self.add_dxil_op( i, next_op_idx, "Unary", "returns the reverse bit pattern of the input value", "wil", "rn", [ db_dxil_param(0, "$o", "", "operation result"), db_dxil_param(2, "$o", "value", "input value"), ], counters=("uints",), ) next_op_idx += 1 for i in "Countbits,FirstbitLo".split(","): self.add_dxil_op( i, next_op_idx, "UnaryBits", "returns the " + i, "wil", "rn", [ db_dxil_param(0, "i32", "", "operation result"), db_dxil_param(2, "$o", "value", "input value"), ], counters=("uints",), ) next_op_idx += 1 for i in "FirstbitHi,FirstbitSHi".split(","): self.add_dxil_op( i, next_op_idx, "UnaryBits", "returns src != 0? (BitWidth-1 - " + i + ") : -1", "wil", "rn", [ db_dxil_param(0, "i32", "", "operation result"), db_dxil_param(2, "$o", "value", "input value"), ], counters=("uints",), ) next_op_idx += 1 # Binary float operations for i in "FMax,FMin".split(","): self.add_dxil_op( i, next_op_idx, "Binary", "returns the " + i + " of the input values", "hfd", "rn", [ db_dxil_param(0, "$o", "", "operation result"), db_dxil_param(2, "$o", "a", "input value"), db_dxil_param(3, "$o", "b", "input value"), ], counters=("floats",), ) next_op_idx += 1 # Binary int operations for i in "IMax,IMin,UMax,UMin".split(","): self.add_dxil_op( i, next_op_idx, "Binary", "returns the " + i + " of the input values", "wil", "rn", [ db_dxil_param(0, "$o", "", "operation result"), db_dxil_param(2, "$o", "a", "input value"), db_dxil_param(3, "$o", "b", "input value"), ], counters=(UFI(i),), ) next_op_idx += 1 # Binary int operations with two outputs for i in "IMul,UMul,UDiv".split(","): self.add_dxil_op( i, next_op_idx, "BinaryWithTwoOuts", "returns the " + i + " of the input values", "i", "rn", [ db_dxil_param(0, "twoi32", "", "operation result"), db_dxil_param(2, "$o", "a", "input value"), db_dxil_param(3, "$o", "b", "input value"), ], counters=(UFI(i),), ) next_op_idx += 1 # Binary int operations with carry for i in "UAddc,USubb".split(","): self.add_dxil_op( i, next_op_idx, "BinaryWithCarryOrBorrow", "returns the " + i + " of the input values", "i", "rn", [ db_dxil_param( 0, "i32c", "", "operation result with carry/borrow value" ), db_dxil_param(2, "$o", "a", "input value"), db_dxil_param(3, "$o", "b", "input value"), ], counters=("uints",), ) next_op_idx += 1 # Tertiary float. self.add_dxil_op( "FMad", next_op_idx, "Tertiary", "performs a fused multiply add (FMA) of the form a * b + c", "hfd", "rn", [ db_dxil_param( 0, "$o", "", "the fused multiply-addition of parameters a * b + c" ), db_dxil_param(2, "$o", "a", "first value for FMA, the first factor"), db_dxil_param(3, "$o", "b", "second value for FMA, the second factor"), db_dxil_param(4, "$o", "c", "third value for FMA, the addend"), ], ) next_op_idx += 1 self.add_dxil_op( "Fma", next_op_idx, "Tertiary", "performs a fused multiply add (FMA) of the form a * b + c", "d", "rn", [ db_dxil_param( 0, "$o", "", "the double-precision fused multiply-addition of parameters a * b + c, accurate to 0.5 units of least precision (ULP)", ), db_dxil_param(2, "$o", "a", "first value for FMA, the first factor"), db_dxil_param(3, "$o", "b", "second value for FMA, the second factor"), db_dxil_param(4, "$o", "c", "third value for FMA, the addend"), ], counters=("floats",), ) next_op_idx += 1 # Tertiary int. for i in "IMad,UMad".split(","): self.add_dxil_op( i, next_op_idx, "Tertiary", "performs an integral " + i, "wil", "rn", [ db_dxil_param(0, "$o", "", "the operation result"), db_dxil_param( 2, "$o", "a", "first value for FMA, the first factor" ), db_dxil_param( 3, "$o", "b", "second value for FMA, the second factor" ), db_dxil_param(4, "$o", "c", "third value for FMA, the addend"), ], counters=(UFI(i),), ) next_op_idx += 1 for i in "Msad,Ibfe,Ubfe".split(","): self.add_dxil_op( i, next_op_idx, "Tertiary", "performs an integral " + i, "il", "rn", [ db_dxil_param(0, "$o", "", "the operation result"), db_dxil_param( 2, "$o", "a", "first value for FMA, the first factor" ), db_dxil_param( 3, "$o", "b", "second value for FMA, the second factor" ), db_dxil_param(4, "$o", "c", "third value for FMA, the addend"), ], counters=(UFI(i, M="uints"),), ) next_op_idx += 1 # Quaternary self.add_dxil_op( "Bfi", next_op_idx, "Quaternary", "given a bit range from the LSB of a number, places that number of bits in another number at any offset", "i", "rn", [ db_dxil_param(0, "$o", "", "the operation result"), db_dxil_param( 2, "$o", "width", "the bitfield width to take from the value" ), db_dxil_param( 3, "$o", "offset", "the bitfield offset to replace in the value" ), db_dxil_param(4, "$o", "value", "the number the bits are taken from"), db_dxil_param( 5, "$o", "replacedValue", "the number with bits to be replaced" ), ], counters=("uints",), ) next_op_idx += 1 # Dot self.add_dxil_op( "Dot2", next_op_idx, "Dot2", "two-dimensional vector dot-product", "hf", "rn", [ db_dxil_param(0, "$o", "", "the operation result"), db_dxil_param(2, "$o", "ax", "the first component of the first vector"), db_dxil_param( 3, "$o", "ay", "the second component of the first vector" ), db_dxil_param( 4, "$o", "bx", "the first component of the second vector" ), db_dxil_param( 5, "$o", "by", "the second component of the second vector" ), ], counters=("floats",), ) next_op_idx += 1 self.add_dxil_op( "Dot3", next_op_idx, "Dot3", "three-dimensional vector dot-product", "hf", "rn", [ db_dxil_param(0, "$o", "", "the operation result"), db_dxil_param(2, "$o", "ax", "the first component of the first vector"), db_dxil_param( 3, "$o", "ay", "the second component of the first vector" ), db_dxil_param(4, "$o", "az", "the third component of the first vector"), db_dxil_param( 5, "$o", "bx", "the first component of the second vector" ), db_dxil_param( 6, "$o", "by", "the second component of the second vector" ), db_dxil_param( 7, "$o", "bz", "the third component of the second vector" ), ], counters=("floats",), ) next_op_idx += 1 self.add_dxil_op( "Dot4", next_op_idx, "Dot4", "four-dimensional vector dot-product", "hf", "rn", [ db_dxil_param(0, "$o", "", "the operation result"), db_dxil_param(2, "$o", "ax", "the first component of the first vector"), db_dxil_param( 3, "$o", "ay", "the second component of the first vector" ), db_dxil_param(4, "$o", "az", "the third component of the first vector"), db_dxil_param( 5, "$o", "aw", "the fourth component of the first vector" ), db_dxil_param( 6, "$o", "bx", "the first component of the second vector" ), db_dxil_param( 7, "$o", "by", "the second component of the second vector" ), db_dxil_param( 8, "$o", "bz", "the third component of the second vector" ), db_dxil_param( 9, "$o", "bw", "the fourth component of the second vector" ), ], counters=("floats",), ) next_op_idx += 1 # Resources. self.add_dxil_op( "CreateHandle", next_op_idx, "CreateHandle", "creates the handle to a resource", "v", "ro", [ db_dxil_param(0, "res", "", "the handle to the resource"), db_dxil_param( 2, "i8", "resourceClass", "the class of resource to create (SRV, UAV, CBuffer, Sampler)", is_const=True, ), # maps to DxilResourceBase::Class db_dxil_param( 3, "i32", "rangeId", "range identifier for resource", is_const=True ), db_dxil_param(4, "i32", "index", "zero-based index into range"), db_dxil_param( 5, "i1", "nonUniformIndex", "non-uniform resource index", is_const=True, ), ], ) next_op_idx += 1 self.add_dxil_op( "CBufferLoad", next_op_idx, "CBufferLoad", "loads a value from a constant buffer resource", "hfd8wil", "ro", [ db_dxil_param( 0, "$o", "", "the value for the constant buffer variable" ), db_dxil_param(2, "res", "handle", "cbuffer handle"), db_dxil_param(3, "u32", "byteOffset", "linear byte offset of value"), db_dxil_param( 4, "u32", "alignment", "load access alignment", is_const=True ), ], ) next_op_idx += 1 self.add_dxil_op( "CBufferLoadLegacy", next_op_idx, "CBufferLoadLegacy", "loads a value from a constant buffer resource", "hfdwil", "ro", [ db_dxil_param( 0, "$cb", "", "the value for the constant buffer variable" ), db_dxil_param(2, "res", "handle", "cbuffer handle"), db_dxil_param( 3, "u32", "regIndex", "0-based index into cbuffer instance" ), ], ) next_op_idx += 1 self.add_dxil_op( "Sample", next_op_idx, "Sample", "samples a texture", "hfwi", "ro", [ db_dxil_param(0, "$r", "", "the sampled value"), db_dxil_param(2, "res", "srv", "handle of SRV to sample"), db_dxil_param(3, "res", "sampler", "handle of sampler to use"), db_dxil_param(4, "f", "coord0", "coordinate"), db_dxil_param(5, "f", "coord1", "coordinate, undef for Texture1D"), db_dxil_param( 6, "f", "coord2", "coordinate, undef for Texture1D, Texture1DArray or Texture2D", ), db_dxil_param( 7, "f", "coord3", "coordinate, defined only for TextureCubeArray" ), db_dxil_param( 8, "i32", "offset0", "optional offset, applicable to Texture1D, Texture1DArray, and as part of offset1", ), db_dxil_param( 9, "i32", "offset1", "optional offset, applicable to Texture2D, Texture2DArray, and as part of offset2", ), db_dxil_param( 10, "i32", "offset2", "optional offset, applicable to Texture3D" ), db_dxil_param(11, "f", "clamp", "clamp value"), ], counters=("tex_norm",), ) next_op_idx += 1 self.add_dxil_op( "SampleBias", next_op_idx, "SampleBias", "samples a texture after applying the input bias to the mipmap level", "hfwi", "ro", [ db_dxil_param(0, "$r", "", "the sampled value"), db_dxil_param(2, "res", "srv", "handle of SRV to sample"), db_dxil_param(3, "res", "sampler", "handle of sampler to use"), db_dxil_param(4, "f", "coord0", "coordinate"), db_dxil_param(5, "f", "coord1", "coordinate, undef for Texture1D"), db_dxil_param( 6, "f", "coord2", "coordinate, undef for Texture1D, Texture1DArray or Texture2D", ), db_dxil_param( 7, "f", "coord3", "coordinate, defined only for TextureCubeArray" ), db_dxil_param( 8, "i32", "offset0", "optional offset, applicable to Texture1D, Texture1DArray, and as part of offset1", ), db_dxil_param( 9, "i32", "offset1", "optional offset, applicable to Texture2D, Texture2DArray, and as part of offset2", ), db_dxil_param( 10, "i32", "offset2", "optional offset, applicable to Texture3D" ), db_dxil_param(11, "f", "bias", "bias value"), db_dxil_param(12, "f", "clamp", "clamp value"), ], counters=("tex_bias",), ) next_op_idx += 1 self.add_dxil_op( "SampleLevel", next_op_idx, "SampleLevel", "samples a texture using a mipmap-level offset", "hfwi", "ro", [ db_dxil_param(0, "$r", "", "the sampled value"), db_dxil_param(2, "res", "srv", "handle of SRV to sample"), db_dxil_param(3, "res", "sampler", "handle of sampler to use"), db_dxil_param(4, "f", "coord0", "coordinate"), db_dxil_param(5, "f", "coord1", "coordinate, undef for Texture1D"), db_dxil_param( 6, "f", "coord2", "coordinate, undef for Texture1D, Texture1DArray or Texture2D", ), db_dxil_param( 7, "f", "coord3", "coordinate, defined only for TextureCubeArray" ), db_dxil_param( 8, "i32", "offset0", "optional offset, applicable to Texture1D, Texture1DArray, and as part of offset1", ), db_dxil_param( 9, "i32", "offset1", "optional offset, applicable to Texture2D, Texture2DArray, and as part of offset2", ), db_dxil_param( 10, "i32", "offset2", "optional offset, applicable to Texture3D" ), db_dxil_param( 11, "f", "LOD", "level of detail, biggest map if less than or equal to zero; fraction used to interpolate across levels", ), ], counters=("tex_norm",), ) next_op_idx += 1 self.add_dxil_op( "SampleGrad", next_op_idx, "SampleGrad", "samples a texture using a gradient to influence the way the sample location is calculated", "hfwi", "ro", [ db_dxil_param(0, "$r", "", "the sampled value"), db_dxil_param(2, "res", "srv", "handle of SRV to sample"), db_dxil_param(3, "res", "sampler", "handle of sampler to use"), db_dxil_param(4, "f", "coord0", "coordinate"), db_dxil_param(5, "f", "coord1", "coordinate, undef for Texture1D"), db_dxil_param( 6, "f", "coord2", "coordinate, undef for Texture1D, Texture1DArray or Texture2D", ), db_dxil_param( 7, "f", "coord3", "coordinate, defined only for TextureCubeArray" ), db_dxil_param( 8, "i32", "offset0", "optional offset, applicable to Texture1D, Texture1DArray, and as part of offset1", ), db_dxil_param( 9, "i32", "offset1", "optional offset, applicable to Texture2D, Texture2DArray, and as part of offset2", ), db_dxil_param( 10, "i32", "offset2", "optional offset, applicable to Texture3D" ), db_dxil_param( 11, "f", "ddx0", "rate of change of the texture coordinate in the x direction", ), db_dxil_param( 12, "f", "ddx1", "rate of change of the texture coordinate in the x direction", ), db_dxil_param( 13, "f", "ddx2", "rate of change of the texture coordinate in the x direction", ), db_dxil_param( 14, "f", "ddy0", "rate of change of the texture coordinate in the y direction", ), db_dxil_param( 15, "f", "ddy1", "rate of change of the texture coordinate in the y direction", ), db_dxil_param( 16, "f", "ddy2", "rate of change of the texture coordinate in the y direction", ), db_dxil_param(17, "f", "clamp", "clamp value"), ], counters=("tex_grad",), ) next_op_idx += 1 self.add_dxil_op( "SampleCmp", next_op_idx, "SampleCmp", "samples a texture and compares a single component against the specified comparison value", "hf", "ro", [ db_dxil_param( 0, "$r", "", "the value for the constant buffer variable" ), db_dxil_param(2, "res", "srv", "handle of SRV to sample"), db_dxil_param(3, "res", "sampler", "handle of sampler to use"), db_dxil_param(4, "f", "coord0", "coordinate"), db_dxil_param(5, "f", "coord1", "coordinate, undef for Texture1D"), db_dxil_param( 6, "f", "coord2", "coordinate, undef for Texture1D, Texture1DArray or Texture2D", ), db_dxil_param( 7, "f", "coord3", "coordinate, defined only for TextureCubeArray" ), db_dxil_param( 8, "i32", "offset0", "optional offset, applicable to Texture1D, Texture1DArray, and as part of offset1", ), db_dxil_param( 9, "i32", "offset1", "optional offset, applicable to Texture2D, Texture2DArray, and as part of offset2", ), db_dxil_param( 10, "i32", "offset2", "optional offset, applicable to Texture3D" ), db_dxil_param(11, "f", "compareValue", "the value to compare with"), db_dxil_param(12, "f", "clamp", "clamp value"), ], counters=("tex_cmp",), ) next_op_idx += 1 self.add_dxil_op( "SampleCmpLevelZero", next_op_idx, "SampleCmpLevelZero", "samples a texture and compares a single component against the specified comparison value", "hf", "ro", [ db_dxil_param( 0, "$r", "", "the value for the constant buffer variable" ), db_dxil_param(2, "res", "srv", "handle of SRV to sample"), db_dxil_param(3, "res", "sampler", "handle of sampler to use"), db_dxil_param(4, "f", "coord0", "coordinate"), db_dxil_param(5, "f", "coord1", "coordinate, undef for Texture1D"), db_dxil_param( 6, "f", "coord2", "coordinate, undef for Texture1D, Texture1DArray or Texture2D", ), db_dxil_param( 7, "f", "coord3", "coordinate, defined only for TextureCubeArray" ), db_dxil_param( 8, "i32", "offset0", "optional offset, applicable to Texture1D, Texture1DArray, and as part of offset1", ), db_dxil_param( 9, "i32", "offset1", "optional offset, applicable to Texture2D, Texture2DArray, and as part of offset2", ), db_dxil_param( 10, "i32", "offset2", "optional offset, applicable to Texture3D" ), db_dxil_param(11, "f", "compareValue", "the value to compare with"), ], counters=("tex_cmp",), ) next_op_idx += 1 self.add_dxil_op( "TextureLoad", next_op_idx, "TextureLoad", "reads texel data without any filtering or sampling", "hfwi", "ro", [ db_dxil_param(0, "$r", "", "the loaded value"), db_dxil_param(2, "res", "srv", "handle of SRV or UAV to sample"), db_dxil_param( 3, "i32", "mipLevelOrSampleCount", "sample count for Texture2DMS, mip level otherwise", ), db_dxil_param(4, "i32", "coord0", "coordinate"), db_dxil_param(5, "i32", "coord1", "coordinate"), db_dxil_param(6, "i32", "coord2", "coordinate"), db_dxil_param(7, "i32", "offset0", "optional offset"), db_dxil_param(8, "i32", "offset1", "optional offset"), db_dxil_param(9, "i32", "offset2", "optional offset"), ], counters=("tex_load",), ) next_op_idx += 1 self.add_dxil_op( "TextureStore", next_op_idx, "TextureStore", "reads texel data without any filtering or sampling", "hfwi", "", [ db_dxil_param(0, "v", "", ""), db_dxil_param(2, "res", "srv", "handle of UAV to store to"), db_dxil_param(3, "i32", "coord0", "coordinate"), db_dxil_param(4, "i32", "coord1", "coordinate"), db_dxil_param(5, "i32", "coord2", "coordinate"), db_dxil_param(6, "$o", "value0", "value"), db_dxil_param(7, "$o", "value1", "value"), db_dxil_param(8, "$o", "value2", "value"), db_dxil_param(9, "$o", "value3", "value"), db_dxil_param(10, "i8", "mask", "written value mask"), ], counters=("tex_store",), ) next_op_idx += 1 self.add_dxil_op( "BufferLoad", next_op_idx, "BufferLoad", "reads from a TypedBuffer", "hfwi", "ro", [ db_dxil_param(0, "$r", "", "the loaded value"), db_dxil_param(2, "res", "srv", "handle of TypedBuffer SRV to sample"), db_dxil_param(3, "i32", "index", "element index"), db_dxil_param(4, "i32", "wot", "coordinate"), ], counters=("tex_load",), ) next_op_idx += 1 self.add_dxil_op( "BufferStore", next_op_idx, "BufferStore", "writes to a RWTypedBuffer", "hfwi", "", [ db_dxil_param(0, "v", "", ""), db_dxil_param(2, "res", "uav", "handle of UAV to store to"), db_dxil_param(3, "i32", "coord0", "coordinate in elements"), db_dxil_param(4, "i32", "coord1", "coordinate (unused?)"), db_dxil_param(5, "$o", "value0", "value"), db_dxil_param(6, "$o", "value1", "value"), db_dxil_param(7, "$o", "value2", "value"), db_dxil_param(8, "$o", "value3", "value"), db_dxil_param(9, "i8", "mask", "written value mask"), ], counters=("tex_store",), ) next_op_idx += 1 self.add_dxil_op( "BufferUpdateCounter", next_op_idx, "BufferUpdateCounter", "atomically increments/decrements the hidden 32-bit counter stored with a Count or Append UAV", "v", "", [ db_dxil_param(0, "i32", "", "the new value in the buffer"), db_dxil_param( 2, "res", "uav", "handle to a structured buffer UAV with the count or append flag", ), db_dxil_param(3, "i8", "inc", "1 to increase, 0 to decrease"), ], counters=("atomic",), ) next_op_idx += 1 self.add_dxil_op( "CheckAccessFullyMapped", next_op_idx, "CheckAccessFullyMapped", "determines whether all values from a Sample, Gather, or Load operation accessed mapped tiles in a tiled resource", "i", "ro", [ db_dxil_param( 0, "i1", "", "nonzero if all values accessed mapped tiles in a tiled resource", ), db_dxil_param( 2, "u32", "status", "status result from the Sample, Gather or Load operation", ), ], ) next_op_idx += 1 self.add_dxil_op( "GetDimensions", next_op_idx, "GetDimensions", "gets texture size information", "v", "ro", [ db_dxil_param(0, "dims", "", "dimension information for texture"), db_dxil_param(2, "res", "handle", "resource handle to query"), db_dxil_param(3, "i32", "mipLevel", "mip level to query"), ], ) next_op_idx += 1 self.add_dxil_op( "TextureGather", next_op_idx, "TextureGather", "gathers the four texels that would be used in a bi-linear filtering operation", "hfwi", "ro", [ db_dxil_param(0, "$r", "", "dimension information for texture"), db_dxil_param(2, "res", "srv", "handle of SRV to sample"), db_dxil_param(3, "res", "sampler", "handle of sampler to use"), db_dxil_param(4, "f", "coord0", "coordinate"), db_dxil_param(5, "f", "coord1", "coordinate, undef for Texture1D"), db_dxil_param( 6, "f", "coord2", "coordinate, undef for Texture1D, Texture1DArray or Texture2D", ), db_dxil_param( 7, "f", "coord3", "coordinate, defined only for TextureCubeArray" ), db_dxil_param( 8, "i32", "offset0", "optional offset, applicable to Texture1D, Texture1DArray, and as part of offset1", ), db_dxil_param( 9, "i32", "offset1", "optional offset, applicable to Texture2D, Texture2DArray, and as part of offset2", ), db_dxil_param(10, "i32", "channel", "channel to sample"), ], counters=("tex_norm",), ) next_op_idx += 1 self.add_dxil_op( "TextureGatherCmp", next_op_idx, "TextureGatherCmp", "same as TextureGather, except this instrution performs comparison on texels, similar to SampleCmp", "hfwi", "ro", [ db_dxil_param(0, "$r", "", "gathered texels"), db_dxil_param(2, "res", "srv", "handle of SRV to sample"), db_dxil_param(3, "res", "sampler", "handle of sampler to use"), db_dxil_param(4, "f", "coord0", "coordinate"), db_dxil_param(5, "f", "coord1", "coordinate, undef for Texture1D"), db_dxil_param( 6, "f", "coord2", "coordinate, undef for Texture1D, Texture1DArray or Texture2D", ), db_dxil_param( 7, "f", "coord3", "coordinate, defined only for TextureCubeArray" ), db_dxil_param( 8, "i32", "offset0", "optional offset, applicable to Texture1D, Texture1DArray, and as part of offset1", ), db_dxil_param( 9, "i32", "offset1", "optional offset, applicable to Texture2D, Texture2DArray, and as part of offset2", ), db_dxil_param(10, "i32", "channel", "channel to sample"), db_dxil_param(11, "f", "compareValue", "value to compare with"), ], counters=("tex_cmp",), ) next_op_idx += 1 self.add_dxil_op( "Texture2DMSGetSamplePosition", next_op_idx, "Texture2DMSGetSamplePosition", "gets the position of the specified sample", "v", "ro", [ db_dxil_param(0, "SamplePos", "", "sample position"), db_dxil_param(2, "res", "srv", "handle of SRV to sample"), db_dxil_param(3, "i32", "index", "zero-based sample index"), ], ) next_op_idx += 1 self.add_dxil_op( "RenderTargetGetSamplePosition", next_op_idx, "RenderTargetGetSamplePosition", "gets the position of the specified sample", "v", "ro", [ db_dxil_param(0, "SamplePos", "", "sample position"), db_dxil_param(2, "i32", "index", "zero-based sample index"), ], ) next_op_idx += 1 self.add_dxil_op( "RenderTargetGetSampleCount", next_op_idx, "RenderTargetGetSampleCount", "gets the number of samples for a render target", "v", "ro", [ db_dxil_param( 0, "u32", "", "number of sampling locations for a render target" ) ], ) next_op_idx += 1 # Atomics. Note that on TGSM, atomics are performed with LLVM instructions. self.add_dxil_op( "AtomicBinOp", next_op_idx, "AtomicBinOp", "performs an atomic operation on two operands", "li", "", [ db_dxil_param( 0, "$o", "", "the original value in the location updated" ), db_dxil_param(2, "res", "handle", "typed int or uint UAV handle"), db_dxil_param( 3, "i32", "atomicOp", "atomic operation as per DXIL::AtomicBinOpCode", ), db_dxil_param(4, "i32", "offset0", "offset in elements"), db_dxil_param(5, "i32", "offset1", "offset"), db_dxil_param(6, "i32", "offset2", "offset"), db_dxil_param(7, "$o", "newValue", "new value"), ], counters=("atomic",), ) next_op_idx += 1 self.add_dxil_op( "AtomicCompareExchange", next_op_idx, "AtomicCompareExchange", "atomic compare and exchange to memory", "li", "", [ db_dxil_param( 0, "$o", "", "the original value in the location updated" ), db_dxil_param(2, "res", "handle", "typed int or uint UAV handle"), db_dxil_param(3, "i32", "offset0", "offset in elements"), db_dxil_param(4, "i32", "offset1", "offset"), db_dxil_param(5, "i32", "offset2", "offset"), db_dxil_param(6, "$o", "compareValue", "value to compare for exchange"), db_dxil_param(7, "$o", "newValue", "new value"), ], counters=("atomic",), ) next_op_idx += 1 # Synchronization. self.add_dxil_op( "Barrier", next_op_idx, "Barrier", "inserts a memory barrier in the shader", "v", "nd", [ retvoid_param, db_dxil_param( 2, "i32", "barrierMode", "a mask of DXIL::BarrierMode values", is_const=True, ), ], counters=("barrier",), ) next_op_idx += 1 # Pixel shader self.add_dxil_op( "CalculateLOD", next_op_idx, "CalculateLOD", "calculates the level of detail", "f", "ro", [ db_dxil_param(0, "f", "", "level of detail"), db_dxil_param(2, "res", "handle", "resource handle"), db_dxil_param(3, "res", "sampler", "sampler handle"), db_dxil_param(4, "f", "coord0", "coordinate"), db_dxil_param(5, "f", "coord1", "coordinate"), db_dxil_param(6, "f", "coord2", "coordinate"), db_dxil_param( 7, "i1", "clamped", "1 if clampled LOD should be calculated, 0 for unclamped", ), ], ) next_op_idx += 1 self.add_dxil_op( "Discard", next_op_idx, "Discard", "discard the current pixel", "v", "", [ retvoid_param, db_dxil_param( 2, "i1", "condition", "condition for conditional discard" ), ], ) next_op_idx += 1 self.add_dxil_op( "DerivCoarseX", next_op_idx, "Unary", "computes the rate of change of components per stamp", "hf", "rn", [ db_dxil_param( 0, "$o", "", "rate of change in value with regards to RenderTarget x direction", ), db_dxil_param(2, "$o", "value", "input to rate of change"), ], ) next_op_idx += 1 self.add_dxil_op( "DerivCoarseY", next_op_idx, "Unary", "computes the rate of change of components per stamp", "hf", "rn", [ db_dxil_param( 0, "$o", "", "rate of change in value with regards to RenderTarget y direction", ), db_dxil_param(2, "$o", "value", "input to rate of change"), ], ) next_op_idx += 1 self.add_dxil_op( "DerivFineX", next_op_idx, "Unary", "computes the rate of change of components per pixel", "hf", "rn", [ db_dxil_param( 0, "$o", "", "rate of change in value with regards to RenderTarget x direction", ), db_dxil_param(2, "$o", "value", "input to rate of change"), ], ) next_op_idx += 1 self.add_dxil_op( "DerivFineY", next_op_idx, "Unary", "computes the rate of change of components per pixel", "hf", "rn", [ db_dxil_param( 0, "$o", "", "rate of change in value with regards to RenderTarget y direction", ), db_dxil_param(2, "$o", "value", "input to rate of change"), ], ) next_op_idx += 1 self.add_dxil_op( "EvalSnapped", next_op_idx, "EvalSnapped", "evaluates an input attribute at pixel center with an offset", "hf", "rn", [ db_dxil_param(0, "$o", "", "result"), db_dxil_param(2, "i32", "inputSigId", "input signature element ID"), db_dxil_param( 3, "i32", "inputRowIndex", "row index of an input attribute" ), db_dxil_param( 4, "i8", "inputColIndex", "column index of an input attribute" ), db_dxil_param( 5, "i32", "offsetX", "2D offset from the pixel center using a 16x16 grid", ), db_dxil_param( 6, "i32", "offsetY", "2D offset from the pixel center using a 16x16 grid", ), ], ) next_op_idx += 1 self.add_dxil_op( "EvalSampleIndex", next_op_idx, "EvalSampleIndex", "evaluates an input attribute at a sample location", "hf", "rn", [ db_dxil_param(0, "$o", "", "result"), db_dxil_param(2, "i32", "inputSigId", "input signature element ID"), db_dxil_param( 3, "i32", "inputRowIndex", "row index of an input attribute" ), db_dxil_param( 4, "i8", "inputColIndex", "column index of an input attribute" ), db_dxil_param(5, "i32", "sampleIndex", "sample location"), ], ) next_op_idx += 1 self.add_dxil_op( "EvalCentroid", next_op_idx, "EvalCentroid", "evaluates an input attribute at pixel center", "hf", "rn", [ db_dxil_param(0, "$o", "", "result"), db_dxil_param(2, "i32", "inputSigId", "input signature element ID"), db_dxil_param( 3, "i32", "inputRowIndex", "row index of an input attribute" ), db_dxil_param( 4, "i8", "inputColIndex", "column index of an input attribute" ), ], ) next_op_idx += 1 self.add_dxil_op( "SampleIndex", next_op_idx, "SampleIndex", "returns the sample index in a sample-frequency pixel shader", "i", "rn", [db_dxil_param(0, "i32", "", "result")], ) next_op_idx += 1 self.add_dxil_op( "Coverage", next_op_idx, "Coverage", "returns the coverage mask input in a pixel shader", "i", "rn", [db_dxil_param(0, "i32", "", "result")], ) next_op_idx += 1 self.add_dxil_op( "InnerCoverage", next_op_idx, "InnerCoverage", "returns underestimated coverage input from conservative rasterization in a pixel shader", "i", "rn", [db_dxil_param(0, "i32", "", "result")], ) next_op_idx += 1 # Compute shader. self.add_dxil_op( "ThreadId", next_op_idx, "ThreadId", "reads the thread ID", "i", "rn", [ db_dxil_param(0, "i32", "", "thread ID component"), db_dxil_param(2, "i32", "component", "component to read (x,y,z)"), ], ) next_op_idx += 1 self.add_dxil_op( "GroupId", next_op_idx, "GroupId", "reads the group ID (SV_GroupID)", "i", "rn", [ db_dxil_param(0, "i32", "", "group ID component"), db_dxil_param(2, "i32", "component", "component to read"), ], ) next_op_idx += 1 self.add_dxil_op( "ThreadIdInGroup", next_op_idx, "ThreadIdInGroup", "reads the thread ID within the group (SV_GroupThreadID)", "i", "rn", [ db_dxil_param(0, "i32", "", "thread ID in group component"), db_dxil_param(2, "i32", "component", "component to read (x,y,z)"), ], ) next_op_idx += 1 self.add_dxil_op( "FlattenedThreadIdInGroup", next_op_idx, "FlattenedThreadIdInGroup", "provides a flattened index for a given thread within a given group (SV_GroupIndex)", "i", "rn", [db_dxil_param(0, "i32", "", "result")], ) next_op_idx += 1 # Geometry shader self.add_dxil_op( "EmitStream", next_op_idx, "EmitStream", "emits a vertex to a given stream", "v", "", [ retvoid_param, db_dxil_param(2, "i8", "streamId", "target stream ID for operation"), ], counters=("gs_emit",), ) next_op_idx += 1 self.add_dxil_op( "CutStream", next_op_idx, "CutStream", "completes the current primitive topology at the specified stream", "v", "", [ retvoid_param, db_dxil_param(2, "i8", "streamId", "target stream ID for operation"), ], counters=("gs_cut",), ) next_op_idx += 1 self.add_dxil_op( "EmitThenCutStream", next_op_idx, "EmitThenCutStream", "equivalent to an EmitStream followed by a CutStream", "v", "", [ retvoid_param, db_dxil_param(2, "i8", "streamId", "target stream ID for operation"), ], counters=("gs_emit", "gs_cut"), ) next_op_idx += 1 self.add_dxil_op( "GSInstanceID", next_op_idx, "GSInstanceID", "GSInstanceID", "i", "rn", [db_dxil_param(0, "i32", "", "result")], ) next_op_idx += 1 # Double precision self.add_dxil_op( "MakeDouble", next_op_idx, "MakeDouble", "creates a double value", "d", "rn", [ db_dxil_param(0, "d", "", "result"), db_dxil_param(2, "i32", "lo", "low part of double"), db_dxil_param(3, "i32", "hi", "high part of double"), ], ) next_op_idx += 1 self.add_dxil_op( "SplitDouble", next_op_idx, "SplitDouble", "splits a double into low and high parts", "d", "rn", [ db_dxil_param(0, "splitdouble", "", "result"), db_dxil_param(2, "d", "value", "value to split"), ], ) next_op_idx += 1 # Domain & Hull shader. self.add_dxil_op( "LoadOutputControlPoint", next_op_idx, "LoadOutputControlPoint", "LoadOutputControlPoint", "hfwi", "rn", [ db_dxil_param(0, "$o", "", "result"), db_dxil_param(2, "i32", "inputSigId", "input signature element ID"), db_dxil_param(3, "i32", "row", "row, relative to the element"), db_dxil_param(4, "i8", "col", "column, relative to the element"), db_dxil_param(5, "i32", "index", "vertex/point index"), ], counters=("sig_ld",), ) next_op_idx += 1 self.add_dxil_op( "LoadPatchConstant", next_op_idx, "LoadPatchConstant", "LoadPatchConstant", "hfwi", "rn", [ db_dxil_param(0, "$o", "", "result"), db_dxil_param(2, "i32", "inputSigId", "input signature element ID"), db_dxil_param(3, "i32", "row", "row, relative to the element"), db_dxil_param(4, "i8", "col", "column, relative to the element"), ], counters=("sig_ld",), ) next_op_idx += 1 # Domain shader. self.add_dxil_op( "DomainLocation", next_op_idx, "DomainLocation", "DomainLocation", "f", "rn", [ db_dxil_param(0, "f", "", "result"), db_dxil_param(2, "i8", "component", "input", is_const=True), ], ) next_op_idx += 1 # Hull shader. self.add_dxil_op( "StorePatchConstant", next_op_idx, "StorePatchConstant", "StorePatchConstant", "hfwi", "", [ retvoid_param, db_dxil_param(2, "i32", "outputSigID", "output signature element ID"), db_dxil_param(3, "i32", "row", "row, relative to the element"), db_dxil_param(4, "i8", "col", "column, relative to the element"), db_dxil_param(5, "$o", "value", "value to store"), ], counters=("sig_st",), ) next_op_idx += 1 self.add_dxil_op( "OutputControlPointID", next_op_idx, "OutputControlPointID", "OutputControlPointID", "i", "rn", [db_dxil_param(0, "i32", "", "result")], ) next_op_idx += 1 self.add_dxil_op( "PrimitiveID", next_op_idx, "PrimitiveID", "PrimitiveID", "i", "rn", [db_dxil_param(0, "i32", "", "result")], ) next_op_idx += 1 self.add_dxil_op( "CycleCounterLegacy", next_op_idx, "CycleCounterLegacy", "CycleCounterLegacy", "v", "", [db_dxil_param(0, "twoi32", "", "result")], ) next_op_idx += 1 # Add wave intrinsics. self.add_dxil_op( "WaveIsFirstLane", next_op_idx, "WaveIsFirstLane", "returns 1 for the first lane in the wave", "v", "", [db_dxil_param(0, "i1", "", "operation result")], ) next_op_idx += 1 self.add_dxil_op( "WaveGetLaneIndex", next_op_idx, "WaveGetLaneIndex", "returns the index of the current lane in the wave", "v", "ro", [db_dxil_param(0, "i32", "", "operation result")], ) next_op_idx += 1 self.add_dxil_op( "WaveGetLaneCount", next_op_idx, "WaveGetLaneCount", "returns the number of lanes in the wave", "v", "rn", [db_dxil_param(0, "i32", "", "operation result")], ) next_op_idx += 1 self.add_dxil_op( "WaveAnyTrue", next_op_idx, "WaveAnyTrue", "returns 1 if any of the lane evaluates the value to true", "v", "", [ db_dxil_param(0, "i1", "", "operation result"), db_dxil_param(2, "i1", "cond", "condition to test"), ], ) next_op_idx += 1 self.add_dxil_op( "WaveAllTrue", next_op_idx, "WaveAllTrue", "returns 1 if all the lanes evaluate the value to true", "v", "", [ db_dxil_param(0, "i1", "", "operation result"), db_dxil_param(2, "i1", "cond", "condition to test"), ], ) next_op_idx += 1 self.add_dxil_op( "WaveActiveAllEqual", next_op_idx, "WaveActiveAllEqual", "returns 1 if all the lanes have the same value", "hfd18wil", "", [ db_dxil_param(0, "i1", "", "operation result"), db_dxil_param(2, "$o", "value", "value to compare"), ], ) next_op_idx += 1 self.add_dxil_op( "WaveActiveBallot", next_op_idx, "WaveActiveBallot", "returns a struct with a bit set for each lane where the condition is true", "v", "", [ db_dxil_param(0, "fouri32", "", "operation result"), db_dxil_param(2, "i1", "cond", "condition to ballot on"), ], ) next_op_idx += 1 self.add_dxil_op( "WaveReadLaneAt", next_op_idx, "WaveReadLaneAt", "returns the value from the specified lane", "hfd18wil", "", [ db_dxil_param(0, "$o", "", "operation result"), db_dxil_param(2, "$o", "value", "value to read"), db_dxil_param(3, "i32", "lane", "lane index"), ], ) next_op_idx += 1 self.add_dxil_op( "WaveReadLaneFirst", next_op_idx, "WaveReadLaneFirst", "returns the value from the first lane", "hfd18wil", "", [ db_dxil_param(0, "$o", "", "operation result"), db_dxil_param(2, "$o", "value", "value to read"), ], ) next_op_idx += 1 self.add_dxil_op( "WaveActiveOp", next_op_idx, "WaveActiveOp", "returns the result the operation across waves", "hfd18wil", "", [ db_dxil_param(0, "$o", "", "operation result"), db_dxil_param(2, "$o", "value", "input value"), db_dxil_param( 3, "i8", "op", "kind of operation to perform", enum_name="WaveOpKind", is_const=True, ), db_dxil_param( 4, "i8", "sop", "sign of operands", enum_name="SignedOpKind", is_const=True, ), ], ) next_op_idx += 1 self.add_enum_type( "SignedOpKind", "Sign vs. unsigned operands for operation", [ (0, "Signed", "signed integer or floating-point operands"), (1, "Unsigned", "unsigned integer operands"), ], ) self.add_enum_type( "WaveOpKind", "Kind of cross-lane operation", [ (0, "Sum", "sum of values"), (1, "Product", "product of values"), (2, "Min", "minimum value"), (3, "Max", "maximum value"), ], ) self.add_dxil_op( "WaveActiveBit", next_op_idx, "WaveActiveBit", "returns the result of the operation across all lanes", "8wil", "", [ db_dxil_param(0, "$o", "", "operation result"), db_dxil_param(2, "$o", "value", "input value"), db_dxil_param( 3, "i8", "op", "kind of operation to perform", enum_name="WaveBitOpKind", is_const=True, ), ], ) next_op_idx += 1 self.add_enum_type( "WaveBitOpKind", "Kind of bitwise cross-lane operation", [ (0, "And", "bitwise and of values"), (1, "Or", "bitwise or of values"), (2, "Xor", "bitwise xor of values"), ], ) self.add_dxil_op( "WavePrefixOp", next_op_idx, "WavePrefixOp", "returns the result of the operation on prior lanes", "hfd8wil", "", [ db_dxil_param(0, "$o", "", "operation result"), db_dxil_param(2, "$o", "value", "input value"), db_dxil_param( 3, "i8", "op", "0=sum,1=product", enum_name="WaveOpKind", is_const=True, ), db_dxil_param( 4, "i8", "sop", "sign of operands", enum_name="SignedOpKind", is_const=True, ), ], ) next_op_idx += 1 self.add_dxil_op( "QuadReadLaneAt", next_op_idx, "QuadReadLaneAt", "reads from a lane in the quad", "hfd18wil", "", [ db_dxil_param(0, "$o", "", "operation result"), db_dxil_param(2, "$o", "value", "value to read"), db_dxil_param( 3, "u32", "quadLane", "lane to read from (0-4)", max_value=3 ), ], ) next_op_idx += 1 self.add_enum_type( "QuadOpKind", "Kind of quad-level operation", [ ( 0, "ReadAcrossX", "returns the value from the other lane in the quad in the horizontal direction", ), ( 1, "ReadAcrossY", "returns the value from the other lane in the quad in the vertical direction", ), ( 2, "ReadAcrossDiagonal", "returns the value from the lane across the quad in horizontal and vertical direction", ), ], ) self.add_dxil_op( "QuadOp", next_op_idx, "QuadOp", "returns the result of a quad-level operation", "hfd8wil", "", [ db_dxil_param(0, "$o", "", "operation result"), db_dxil_param(2, "$o", "value", "value for operation"), db_dxil_param( 3, "i8", "op", "operation", enum_name="QuadOpKind", is_const=True ), ], ) next_op_idx += 1 # Add bitcasts self.add_dxil_op( "BitcastI16toF16", next_op_idx, "BitcastI16toF16", "bitcast between different sizes", "v", "rn", [ db_dxil_param(0, "h", "", "operation result"), db_dxil_param(2, "i16", "value", "input value"), ], ) next_op_idx += 1 self.add_dxil_op( "BitcastF16toI16", next_op_idx, "BitcastF16toI16", "bitcast between different sizes", "v", "rn", [ db_dxil_param(0, "i16", "", "operation result"), db_dxil_param(2, "h", "value", "input value"), ], ) next_op_idx += 1 self.add_dxil_op( "BitcastI32toF32", next_op_idx, "BitcastI32toF32", "bitcast between different sizes", "v", "rn", [ db_dxil_param(0, "f", "", "operation result"), db_dxil_param(2, "i32", "value", "input value"), ], ) next_op_idx += 1 self.add_dxil_op( "BitcastF32toI32", next_op_idx, "BitcastF32toI32", "bitcast between different sizes", "v", "rn", [ db_dxil_param(0, "i32", "", "operation result"), db_dxil_param(2, "f", "value", "input value"), ], ) next_op_idx += 1 self.add_dxil_op( "BitcastI64toF64", next_op_idx, "BitcastI64toF64", "bitcast between different sizes", "v", "rn", [ db_dxil_param(0, "d", "", "operation result"), db_dxil_param(2, "i64", "value", "input value"), ], ) next_op_idx += 1 self.add_dxil_op( "BitcastF64toI64", next_op_idx, "BitcastF64toI64", "bitcast between different sizes", "v", "rn", [ db_dxil_param(0, "i64", "", "operation result"), db_dxil_param(2, "d", "value", "input value"), ], ) next_op_idx += 1 self.add_dxil_op( "LegacyF32ToF16", next_op_idx, "LegacyF32ToF16", "legacy fuction to convert float (f32) to half (f16) (this is not related to min-precision)", "v", "rn", [ db_dxil_param( 0, "i32", "", "low 16 bits - half value, high 16 bits - zeroes" ), db_dxil_param(2, "f", "value", "float value to convert"), ], ) next_op_idx += 1 self.add_dxil_op( "LegacyF16ToF32", next_op_idx, "LegacyF16ToF32", "legacy fuction to convert half (f16) to float (f32) (this is not related to min-precision)", "v", "rn", [ db_dxil_param(0, "f", "", "converted float value"), db_dxil_param(2, "i32", "value", "half value to convert"), ], ) next_op_idx += 1 self.add_dxil_op( "LegacyDoubleToFloat", next_op_idx, "LegacyDoubleToFloat", "legacy fuction to convert double to float", "v", "rn", [ db_dxil_param(0, "f", "", "float value"), db_dxil_param(2, "d", "value", "double value to convert"), ], ) next_op_idx += 1 self.add_dxil_op( "LegacyDoubleToSInt32", next_op_idx, "LegacyDoubleToSInt32", "legacy fuction to convert double to int32", "v", "rn", [ db_dxil_param(0, "i32", "", "i32 value"), db_dxil_param(2, "d", "value", "double value to convert"), ], ) next_op_idx += 1 self.add_dxil_op( "LegacyDoubleToUInt32", next_op_idx, "LegacyDoubleToUInt32", "legacy fuction to convert double to uint32", "v", "rn", [ db_dxil_param(0, "i32", "", "i32 value"), db_dxil_param(2, "d", "value", "double value to convert"), ], ) next_op_idx += 1 self.add_dxil_op( "WaveAllBitCount", next_op_idx, "WaveAllOp", "returns the count of bits set to 1 across the wave", "v", "", [ db_dxil_param(0, "i32", "", "operation result"), db_dxil_param(2, "i1", "value", "input value"), ], ) next_op_idx += 1 # WavePrefixBitCount has different signature compare to WavePrefixOp, set its opclass to WavePrefixOp is not correct. # It works now because WavePrefixOp and WavePrefixBitCount don't interfere on overload types. # Keep it unchanged for back-compat. self.add_dxil_op( "WavePrefixBitCount", next_op_idx, "WavePrefixOp", "returns the count of bits set to 1 on prior lanes", "v", "", [ db_dxil_param(0, "i32", "", "operation result"), db_dxil_param(2, "i1", "value", "input value"), ], ) next_op_idx += 1 # End of DXIL 1.0 opcodes. self.set_op_count_for_version(1, 0, next_op_idx) self.add_dxil_op( "AttributeAtVertex", next_op_idx, "AttributeAtVertex", "returns the values of the attributes at the vertex.", "hfiw", "rn", [ db_dxil_param(0, "$o", "", "result"), db_dxil_param(2, "i32", "inputSigId", "input signature element ID"), db_dxil_param( 3, "i32", "inputRowIndex", "row index of an input attribute" ), db_dxil_param( 4, "i8", "inputColIndex", "column index of an input attribute" ), db_dxil_param(5, "i8", "VertexID", "Vertex Index"), ], ) next_op_idx += 1 self.add_dxil_op( "ViewID", next_op_idx, "ViewID", "returns the view index", "i", "rn", [db_dxil_param(0, "i32", "", "result")], ) next_op_idx += 1 # End of DXIL 1.1 opcodes. self.set_op_count_for_version(1, 1, next_op_idx) self.add_dxil_op( "RawBufferLoad", next_op_idx, "RawBufferLoad", "reads from a raw buffer and structured buffer", "hfwidl", "ro", [ db_dxil_param(0, "$r", "", "the loaded value"), db_dxil_param(2, "res", "srv", "handle of TypedBuffer SRV to sample"), db_dxil_param( 3, "i32", "index", "element index for StructuredBuffer, or byte offset for ByteAddressBuffer", ), db_dxil_param( 4, "i32", "elementOffset", "offset into element for StructuredBuffer, or undef for ByteAddressBuffer", ), db_dxil_param(5, "i8", "mask", "loading value mask", is_const=True), db_dxil_param( 6, "i32", "alignment", "relative load access alignment", is_const=True, ), ], counters=("tex_load",), ) next_op_idx += 1 self.add_dxil_op( "RawBufferStore", next_op_idx, "RawBufferStore", "writes to a RWByteAddressBuffer or RWStructuredBuffer", "hfwidl", "", [ db_dxil_param(0, "v", "", ""), db_dxil_param(2, "res", "uav", "handle of UAV to store to"), db_dxil_param( 3, "i32", "index", "element index for StructuredBuffer, or byte offset for ByteAddressBuffer", ), db_dxil_param( 4, "i32", "elementOffset", "offset into element for StructuredBuffer, or undef for ByteAddressBuffer", ), db_dxil_param(5, "$o", "value0", "value"), db_dxil_param(6, "$o", "value1", "value"), db_dxil_param(7, "$o", "value2", "value"), db_dxil_param(8, "$o", "value3", "value"), db_dxil_param( 9, "i8", "mask", "mask of contiguous components stored starting at first component (valid: 1, 3, 7, 15)", is_const=True, ), db_dxil_param( 10, "i32", "alignment", "relative store access alignment", is_const=True, ), ], counters=("tex_store",), ) next_op_idx += 1 # End of DXIL 1.2 opcodes. self.set_op_count_for_version(1, 2, next_op_idx) assert next_op_idx == 141, ( "next operation index is %d rather than 141 and thus opcodes are broken" % next_op_idx ) self.add_dxil_op( "InstanceID", next_op_idx, "InstanceID", "The user-provided InstanceID on the bottom-level acceleration structure instance within the top-level structure", "i", "rn", [db_dxil_param(0, "i32", "", "result")], ) next_op_idx += 1 self.add_dxil_op( "InstanceIndex", next_op_idx, "InstanceIndex", "The autogenerated index of the current instance in the top-level structure", "i", "rn", [db_dxil_param(0, "i32", "", "result")], ) next_op_idx += 1 self.add_dxil_op( "HitKind", next_op_idx, "HitKind", "Returns the value passed as HitKind in ReportIntersection(). If intersection was reported by fixed-function triangle intersection, HitKind will be one of HIT_KIND_TRIANGLE_FRONT_FACE or HIT_KIND_TRIANGLE_BACK_FACE.", "i", "rn", [db_dxil_param(0, "i32", "", "result")], ) next_op_idx += 1 self.add_dxil_op( "RayFlags", next_op_idx, "RayFlags", "uint containing the current ray flags.", "i", "rn", [db_dxil_param(0, "i32", "", "result")], ) next_op_idx += 1 self.add_dxil_op( "DispatchRaysIndex", next_op_idx, "DispatchRaysIndex", "The current x and y location within the Width and Height", "i", "rn", [ db_dxil_param(0, "i32", "", "result"), db_dxil_param(2, "i8", "col", "column, relative to the element"), ], ) next_op_idx += 1 self.add_dxil_op( "DispatchRaysDimensions", next_op_idx, "DispatchRaysDimensions", "The Width and Height values from the D3D12_DISPATCH_RAYS_DESC structure provided to the originating DispatchRays() call.", "i", "rn", [ db_dxil_param(0, "i32", "", "result"), db_dxil_param(2, "i8", "col", "column, relative to the element"), ], ) next_op_idx += 1 self.add_dxil_op( "WorldRayOrigin", next_op_idx, "WorldRayOrigin", "The world-space origin for the current ray.", "f", "rn", [ db_dxil_param(0, "f", "", "result"), db_dxil_param(2, "i8", "col", "column, relative to the element"), ], ) next_op_idx += 1 self.add_dxil_op( "WorldRayDirection", next_op_idx, "WorldRayDirection", "The world-space direction for the current ray.", "f", "rn", [ db_dxil_param(0, "f", "", "result"), db_dxil_param(2, "i8", "col", "column, relative to the element"), ], ) next_op_idx += 1 self.add_dxil_op( "ObjectRayOrigin", next_op_idx, "ObjectRayOrigin", "Object-space origin for the current ray.", "f", "rn", [ db_dxil_param(0, "f", "", "result"), db_dxil_param(2, "i8", "col", "column, relative to the element"), ], ) next_op_idx += 1 self.add_dxil_op( "ObjectRayDirection", next_op_idx, "ObjectRayDirection", "Object-space direction for the current ray.", "f", "rn", [ db_dxil_param(0, "f", "", "result"), db_dxil_param(2, "i8", "col", "column, relative to the element"), ], ) next_op_idx += 1 self.add_dxil_op( "ObjectToWorld", next_op_idx, "ObjectToWorld", "Matrix for transforming from object-space to world-space.", "f", "rn", [ db_dxil_param(0, "f", "", "result"), db_dxil_param(2, "i32", "row", "row, relative to the element"), db_dxil_param(3, "i8", "col", "column, relative to the element"), ], ) next_op_idx += 1 self.add_dxil_op( "WorldToObject", next_op_idx, "WorldToObject", "Matrix for transforming from world-space to object-space.", "f", "rn", [ db_dxil_param(0, "f", "", "result"), db_dxil_param(2, "i32", "row", "row, relative to the element"), db_dxil_param(3, "i8", "col", "column, relative to the element"), ], ) next_op_idx += 1 self.add_dxil_op( "RayTMin", next_op_idx, "RayTMin", "float representing the parametric starting point for the ray.", "f", "rn", [db_dxil_param(0, "f", "", "result")], ) next_op_idx += 1 self.add_dxil_op( "RayTCurrent", next_op_idx, "RayTCurrent", "float representing the current parametric ending point for the ray", "f", "ro", [db_dxil_param(0, "f", "", "result")], ) next_op_idx += 1 self.add_dxil_op( "IgnoreHit", next_op_idx, "IgnoreHit", "Used in an any hit shader to reject an intersection and terminate the shader", "v", "nr", [db_dxil_param(0, "v", "", "")], ) next_op_idx += 1 self.add_dxil_op( "AcceptHitAndEndSearch", next_op_idx, "AcceptHitAndEndSearch", "Used in an any hit shader to abort the ray query and the intersection shader (if any). The current hit is committed and execution passes to the closest hit shader with the closest hit recorded so far", "v", "nr", [db_dxil_param(0, "v", "", "")], ) next_op_idx += 1 self.add_dxil_op( "TraceRay", next_op_idx, "TraceRay", "initiates raytrace", "u", "", [ db_dxil_param(0, "v", "", ""), db_dxil_param( 2, "res", "AccelerationStructure", "Top-level acceleration structure to use", ), db_dxil_param(3, "i32", "RayFlags", "Valid combination of Ray_flags"), db_dxil_param( 4, "i32", "InstanceInclusionMask", "Bottom 8 bits of InstanceInclusionMask are used to include/rejectgeometry instances based on the InstanceMask in each instance: if(!((InstanceInclusionMask & InstanceMask) & 0xff)) { ignore intersection }", ), db_dxil_param( 5, "i32", "RayContributionToHitGroupIndex", "Offset to add into Addressing calculations within shader tables for hit group indexing. Only the bottom 4 bits of this value are used", ), db_dxil_param( 6, "i32", "MultiplierForGeometryContributionToShaderIndex", "Stride to multiply by per-geometry GeometryContributionToHitGroupIndex in Addressing calculations within shader tables for hit group indexing. Only the bottom 4 bits of this value are used", ), db_dxil_param( 7, "i32", "MissShaderIndex", "Miss shader index in Addressing calculations within shader tables. Only the bottom 16 bits of this value are used", ), db_dxil_param(8, "f", "Origin_X", "Origin x of the ray"), db_dxil_param(9, "f", "Origin_Y", "Origin y of the ray"), db_dxil_param(10, "f", "Origin_Z", "Origin z of the ray"), db_dxil_param(11, "f", "TMin", "Tmin of the ray"), db_dxil_param(12, "f", "Direction_X", "Direction x of the ray"), db_dxil_param(13, "f", "Direction_Y", "Direction y of the ray"), db_dxil_param(14, "f", "Direction_Z", "Direction z of the ray"), db_dxil_param(15, "f", "TMax", "Tmax of the ray"), db_dxil_param( 16, "udt", "payload", "User-defined intersection attribute structure", ), ], ) next_op_idx += 1 self.add_dxil_op( "ReportHit", next_op_idx, "ReportHit", "returns true if hit was accepted", "u", "", [ db_dxil_param(0, "i1", "", "result"), db_dxil_param( 2, "f", "THit", "parametric distance of the intersection" ), db_dxil_param( 3, "i32", "HitKind", "User-specified value in range of 0-127 to identify the type of hit. Read by any_hit or closes_hit shaders with HitKind()", ), db_dxil_param( 4, "udt", "Attributes", "User-defined intersection attribute structure", ), ], ) next_op_idx += 1 self.add_dxil_op( "CallShader", next_op_idx, "CallShader", "Call a shader in the callable shader table supplied through the DispatchRays() API", "u", "", [ db_dxil_param(0, "v", "", "result"), db_dxil_param( 2, "i32", "ShaderIndex", "Provides index into the callable shader table supplied through the DispatchRays() API", ), db_dxil_param( 3, "udt", "Parameter", "User-defined parameters to pass to the callable shader,This parameter structure must match the parameter structure used in the callable shader pointed to in the shader table", ), ], ) next_op_idx += 1 self.add_dxil_op( "CreateHandleForLib", next_op_idx, "CreateHandleForLib", "create resource handle from resource struct for library", "o", "ro", [ db_dxil_param(0, "res", "", "result"), db_dxil_param(2, "obj", "Resource", "resource to create the handle"), ], ) next_op_idx += 1 # Maps to PrimitiveIndex() intrinsics for raytracing (same meaning as PrimitiveID) self.add_dxil_op( "PrimitiveIndex", next_op_idx, "PrimitiveIndex", "PrimitiveIndex for raytracing shaders", "i", "rn", [db_dxil_param(0, "i32", "", "result")], ) next_op_idx += 1 # End of DXIL 1.3 opcodes. self.set_op_count_for_version(1, 3, next_op_idx) assert next_op_idx == 162, ( "next operation index is %d rather than 162 and thus opcodes are broken" % next_op_idx ) self.add_dxil_op( "Dot2AddHalf", next_op_idx, "Dot2AddHalf", "2D half dot product with accumulate to float", "f", "rn", [ db_dxil_param(0, "$o", "", "accumulated result"), db_dxil_param(2, "$o", "acc", "input accumulator"), db_dxil_param(3, "h", "ax", "the first component of the first vector"), db_dxil_param(4, "h", "ay", "the second component of the first vector"), db_dxil_param(5, "h", "bx", "the first component of the second vector"), db_dxil_param( 6, "h", "by", "the second component of the second vector" ), ], counters=("floats",), ) next_op_idx += 1 self.add_dxil_op( "Dot4AddI8Packed", next_op_idx, "Dot4AddPacked", "signed dot product of 4 x i8 vectors packed into i32, with accumulate to i32", "i", "rn", [ db_dxil_param(0, "i32", "", "accumulated result"), db_dxil_param(2, "i32", "acc", "input accumulator"), db_dxil_param(3, "i32", "a", "first packed 4 x i8 for dot product"), db_dxil_param(4, "i32", "b", "second packed 4 x i8 for dot product"), ], counters=("ints",), ) next_op_idx += 1 self.add_dxil_op( "Dot4AddU8Packed", next_op_idx, "Dot4AddPacked", "unsigned dot product of 4 x u8 vectors packed into i32, with accumulate to i32", "i", "rn", [ db_dxil_param(0, "i32", "", "accumulated result"), db_dxil_param(2, "i32", "acc", "input accumulator"), db_dxil_param(3, "i32", "a", "first packed 4 x u8 for dot product"), db_dxil_param(4, "i32", "b", "second packed 4 x u8 for dot product"), ], counters=("uints",), ) next_op_idx += 1 # End of DXIL 1.4 opcodes. self.set_op_count_for_version(1, 4, next_op_idx) assert next_op_idx == 165, ( "next operation index is %d rather than 165 and thus opcodes are broken" % next_op_idx ) self.add_dxil_op( "WaveMatch", next_op_idx, "WaveMatch", "returns the bitmask of active lanes that have the same value", "hfd8wil", "", [ db_dxil_param(0, "fouri32", "", "operation result"), db_dxil_param(2, "$o", "value", "input value"), ], ) next_op_idx += 1 self.add_dxil_op( "WaveMultiPrefixOp", next_op_idx, "WaveMultiPrefixOp", "returns the result of the operation on groups of lanes identified by a bitmask", "hfd8wil", "", [ db_dxil_param(0, "$o", "", "operation result"), db_dxil_param(2, "$o", "value", "input value"), db_dxil_param(3, "i32", "mask0", "mask 0"), db_dxil_param(4, "i32", "mask1", "mask 1"), db_dxil_param(5, "i32", "mask2", "mask 2"), db_dxil_param(6, "i32", "mask3", "mask 3"), db_dxil_param( 7, "i8", "op", "operation", enum_name="WaveMultiPrefixOpKind", is_const=True, ), db_dxil_param( 8, "i8", "sop", "sign of operands", enum_name="SignedOpKind", is_const=True, ), ], ) next_op_idx += 1 self.add_enum_type( "WaveMultiPrefixOpKind", "Kind of cross-lane for multi-prefix operation", [ (0, "Sum", "sum of values"), (1, "And", "bitwise and of values"), (2, "Or", "bitwise or of values"), (3, "Xor", "bitwise xor of values"), (4, "Product", "product of values"), ], ) self.add_dxil_op( "WaveMultiPrefixBitCount", next_op_idx, "WaveMultiPrefixBitCount", "returns the count of bits set to 1 on groups of lanes identified by a bitmask", "v", "", [ db_dxil_param(0, "i32", "", "operation result"), db_dxil_param(2, "i1", "value", "input value"), db_dxil_param(3, "i32", "mask0", "mask 0"), db_dxil_param(4, "i32", "mask1", "mask 1"), db_dxil_param(5, "i32", "mask2", "mask 2"), db_dxil_param(6, "i32", "mask3", "mask 3"), ], ) next_op_idx += 1 # Mesh Shader self.add_dxil_op( "SetMeshOutputCounts", next_op_idx, "SetMeshOutputCounts", "Mesh shader intrinsic SetMeshOutputCounts", "v", "", [ retvoid_param, db_dxil_param(2, "i32", "numVertices", "number of output vertices"), db_dxil_param(3, "i32", "numPrimitives", "number of output primitives"), ], ) next_op_idx += 1 self.add_dxil_op( "EmitIndices", next_op_idx, "EmitIndices", "emit a primitive's vertex indices in a mesh shader", "v", "", [ retvoid_param, db_dxil_param(2, "u32", "PrimitiveIndex", "a primitive's index"), db_dxil_param( 3, "u32", "VertexIndex0", "a primitive's first vertex index" ), db_dxil_param( 4, "u32", "VertexIndex1", "a primitive's second vertex index" ), db_dxil_param( 5, "u32", "VertexIndex2", "a primitive's third vertex index" ), ], ) next_op_idx += 1 self.add_dxil_op( "GetMeshPayload", next_op_idx, "GetMeshPayload", "get the mesh payload which is from amplification shader", "u", "ro", [db_dxil_param(0, "$o", "", "mesh payload result")], ) next_op_idx += 1 self.add_dxil_op( "StoreVertexOutput", next_op_idx, "StoreVertexOutput", "stores the value to mesh shader vertex output", "hfwi", "", [ retvoid_param, db_dxil_param( 2, "u32", "outputSigId", "vertex output signature element ID" ), db_dxil_param(3, "u32", "rowIndex", "row index relative to element"), db_dxil_param(4, "u8", "colIndex", "column index relative to element"), db_dxil_param(5, "$o", "value", "value to store"), db_dxil_param(6, "u32", "vertexIndex", "vertex index"), ], counters=("sig_st",), ) next_op_idx += 1 self.add_dxil_op( "StorePrimitiveOutput", next_op_idx, "StorePrimitiveOutput", "stores the value to mesh shader primitive output", "hfwi", "", [ retvoid_param, db_dxil_param( 2, "u32", "outputSigId", "primitive output signature element ID" ), db_dxil_param(3, "u32", "rowIndex", "row index relative to element"), db_dxil_param(4, "u8", "colIndex", "column index relative to element"), db_dxil_param(5, "$o", "value", "value to store"), db_dxil_param(6, "u32", "primitiveIndex", "primitive index"), ], counters=("sig_st",), ) next_op_idx += 1 # Amplification Shader self.add_dxil_op( "DispatchMesh", next_op_idx, "DispatchMesh", "Amplification shader intrinsic DispatchMesh", "u", "", [ retvoid_param, db_dxil_param(2, "i32", "threadGroupCountX", "thread group count x"), db_dxil_param(3, "i32", "threadGroupCountY", "thread group count y"), db_dxil_param(4, "i32", "threadGroupCountZ", "thread group count z"), db_dxil_param(5, "$o", "payload", "payload"), ], ) next_op_idx += 1 # Sampler feedback self.add_dxil_op( "WriteSamplerFeedback", next_op_idx, "WriteSamplerFeedback", "updates a feedback texture for a sampling operation", "v", "", [ db_dxil_param(0, "v", "", ""), db_dxil_param( 2, "res", "feedbackTex", "handle of feedback texture UAV" ), db_dxil_param(3, "res", "sampledTex", "handled of sampled texture SRV"), db_dxil_param(4, "res", "sampler", "handle of sampler"), db_dxil_param(5, "f", "c0", "coordinate c0"), db_dxil_param(6, "f", "c1", "coordinate c1"), db_dxil_param(7, "f", "c2", "coordinate c2"), db_dxil_param(8, "f", "c3", "coordinate c3"), db_dxil_param(9, "f", "clamp", "clamp"), ], counters=("tex_store",), ) next_op_idx += 1 self.add_dxil_op( "WriteSamplerFeedbackBias", next_op_idx, "WriteSamplerFeedbackBias", "updates a feedback texture for a sampling operation with a bias on the mipmap level", "v", "", [ db_dxil_param(0, "v", "", ""), db_dxil_param( 2, "res", "feedbackTex", "handle of feedback texture UAV" ), db_dxil_param(3, "res", "sampledTex", "handled of sampled texture SRV"), db_dxil_param(4, "res", "sampler", "handle of sampler"), db_dxil_param(5, "f", "c0", "coordinate c0"), db_dxil_param(6, "f", "c1", "coordinate c1"), db_dxil_param(7, "f", "c2", "coordinate c2"), db_dxil_param(8, "f", "c3", "coordinate c3"), db_dxil_param(9, "f", "bias", "bias in [-16.f,15.99f]"), db_dxil_param(10, "f", "clamp", "clamp"), ], counters=("tex_store",), ) next_op_idx += 1 self.add_dxil_op( "WriteSamplerFeedbackLevel", next_op_idx, "WriteSamplerFeedbackLevel", "updates a feedback texture for a sampling operation with a mipmap-level offset", "v", "", [ db_dxil_param(0, "v", "", ""), db_dxil_param( 2, "res", "feedbackTex", "handle of feedback texture UAV" ), db_dxil_param(3, "res", "sampledTex", "handled of sampled texture SRV"), db_dxil_param(4, "res", "sampler", "handle of sampler"), db_dxil_param(5, "f", "c0", "coordinate c0"), db_dxil_param(6, "f", "c1", "coordinate c1"), db_dxil_param(7, "f", "c2", "coordinate c2"), db_dxil_param(8, "f", "c3", "coordinate c3"), db_dxil_param(9, "f", "lod", "LOD"), ], counters=("tex_store",), ) next_op_idx += 1 self.add_dxil_op( "WriteSamplerFeedbackGrad", next_op_idx, "WriteSamplerFeedbackGrad", "updates a feedback texture for a sampling operation with explicit gradients", "v", "", [ db_dxil_param(0, "v", "", ""), db_dxil_param( 2, "res", "feedbackTex", "handle of feedback texture UAV" ), db_dxil_param(3, "res", "sampledTex", "handled of sampled texture SRV"), db_dxil_param(4, "res", "sampler", "handle of sampler"), db_dxil_param(5, "f", "c0", "coordinate c0"), db_dxil_param(6, "f", "c1", "coordinate c1"), db_dxil_param(7, "f", "c2", "coordinate c2"), db_dxil_param(8, "f", "c3", "coordinate c3"), db_dxil_param( 9, "f", "ddx0", "rate of change of coordinate c0 in the x direction" ), db_dxil_param( 10, "f", "ddx1", "rate of change of coordinate c1 in the x direction", ), db_dxil_param( 11, "f", "ddx2", "rate of change of coordinate c2 in the x direction", ), db_dxil_param( 12, "f", "ddy0", "rate of change of coordinate c0 in the y direction", ), db_dxil_param( 13, "f", "ddy1", "rate of change of coordinate c1 in the y direction", ), db_dxil_param( 14, "f", "ddy2", "rate of change of coordinate c2 in the y direction", ), db_dxil_param(15, "f", "clamp", "clamp"), ], counters=("tex_store",), ) next_op_idx += 1 # RayQuery self.add_dxil_op( "AllocateRayQuery", next_op_idx, "AllocateRayQuery", "allocates space for RayQuery and return handle", "v", "", [ db_dxil_param(0, "i32", "", "handle to RayQuery state"), db_dxil_param( 2, "u32", "constRayFlags", "Valid combination of RAY_FLAGS", is_const=True, ), ], ) next_op_idx += 1 self.add_dxil_op( "RayQuery_TraceRayInline", next_op_idx, "RayQuery_TraceRayInline", "initializes RayQuery for raytrace", "v", "", [ db_dxil_param(0, "v", "", ""), db_dxil_param(2, "i32", "rayQueryHandle", "RayQuery handle"), db_dxil_param( 3, "res", "accelerationStructure", "Top-level acceleration structure to use", ), db_dxil_param( 4, "i32", "rayFlags", "Valid combination of RAY_FLAGS, combined with constRayFlags provided to AllocateRayQuery", ), db_dxil_param( 5, "i32", "instanceInclusionMask", "Bottom 8 bits of InstanceInclusionMask are used to include/rejectgeometry instances based on the InstanceMask in each instance: if(!((InstanceInclusionMask & InstanceMask) & 0xff)) { ignore intersection }", ), db_dxil_param(6, "f", "origin_X", "Origin x of the ray"), db_dxil_param(7, "f", "origin_Y", "Origin y of the ray"), db_dxil_param(8, "f", "origin_Z", "Origin z of the ray"), db_dxil_param(9, "f", "tMin", "Tmin of the ray"), db_dxil_param(10, "f", "direction_X", "Direction x of the ray"), db_dxil_param(11, "f", "direction_Y", "Direction y of the ray"), db_dxil_param(12, "f", "direction_Z", "Direction z of the ray"), db_dxil_param(13, "f", "tMax", "Tmax of the ray"), ], ) next_op_idx += 1 self.add_dxil_op( "RayQuery_Proceed", next_op_idx, "RayQuery_Proceed", "advances a ray query", "1", "", [ db_dxil_param(0, "i1", "", "operation result"), db_dxil_param(2, "i32", "rayQueryHandle", "RayQuery handle"), ], ) next_op_idx += 1 self.add_dxil_op( "RayQuery_Abort", next_op_idx, "RayQuery_Abort", "aborts a ray query", "v", "", [ db_dxil_param(0, "v", "", ""), db_dxil_param(2, "i32", "rayQueryHandle", "RayQuery handle"), ], ) next_op_idx += 1 self.add_dxil_op( "RayQuery_CommitNonOpaqueTriangleHit", next_op_idx, "RayQuery_CommitNonOpaqueTriangleHit", "commits a non opaque triangle hit", "v", "", [ db_dxil_param(0, "v", "", ""), db_dxil_param(2, "i32", "rayQueryHandle", "RayQuery handle"), ], ) next_op_idx += 1 self.add_dxil_op( "RayQuery_CommitProceduralPrimitiveHit", next_op_idx, "RayQuery_CommitProceduralPrimitiveHit", "commits a procedural primitive hit", "v", "", [ db_dxil_param(0, "v", "", ""), db_dxil_param(2, "i32", "rayQueryHandle", "RayQuery handle"), db_dxil_param( 3, "f", "t", "Procedural primitive hit distance (t) to commit." ), ], ) next_op_idx += 1 self.add_dxil_op( "RayQuery_CommittedStatus", next_op_idx, "RayQuery_StateScalar", "returns uint status (COMMITTED_STATUS) of the committed hit in a ray query", "i", "ro", [ db_dxil_param(0, "i32", "", "operation result"), db_dxil_param(2, "i32", "rayQueryHandle", "RayQuery handle"), ], ) next_op_idx += 1 self.add_dxil_op( "RayQuery_CandidateType", next_op_idx, "RayQuery_StateScalar", "returns uint candidate type (CANDIDATE_TYPE) of the current hit candidate in a ray query, after Proceed() has returned true", "i", "ro", [ db_dxil_param(0, "i32", "", "operation result"), db_dxil_param(2, "i32", "rayQueryHandle", "RayQuery handle"), ], ) next_op_idx += 1 self.add_dxil_op( "RayQuery_CandidateObjectToWorld3x4", next_op_idx, "RayQuery_StateMatrix", "returns matrix for transforming from object-space to world-space for a candidate hit.", "f", "ro", [ db_dxil_param(0, "f", "", "operation result"), db_dxil_param(2, "i32", "rayQueryHandle", "RayQuery handle"), db_dxil_param(3, "i32", "row", "row [0..2], relative to the element"), db_dxil_param(4, "i8", "col", "column [0..3], relative to the element"), ], ) next_op_idx += 1 self.add_dxil_op( "RayQuery_CandidateWorldToObject3x4", next_op_idx, "RayQuery_StateMatrix", "returns matrix for transforming from world-space to object-space for a candidate hit.", "f", "ro", [ db_dxil_param(0, "f", "", "operation result"), db_dxil_param(2, "i32", "rayQueryHandle", "RayQuery handle"), db_dxil_param(3, "i32", "row", "row [0..2], relative to the element"), db_dxil_param(4, "i8", "col", "column [0..3], relative to the element"), ], ) next_op_idx += 1 self.add_dxil_op( "RayQuery_CommittedObjectToWorld3x4", next_op_idx, "RayQuery_StateMatrix", "returns matrix for transforming from object-space to world-space for a Committed hit.", "f", "ro", [ db_dxil_param(0, "f", "", "operation result"), db_dxil_param(2, "i32", "rayQueryHandle", "RayQuery handle"), db_dxil_param(3, "i32", "row", "row [0..2], relative to the element"), db_dxil_param(4, "i8", "col", "column [0..3], relative to the element"), ], ) next_op_idx += 1 self.add_dxil_op( "RayQuery_CommittedWorldToObject3x4", next_op_idx, "RayQuery_StateMatrix", "returns matrix for transforming from world-space to object-space for a Committed hit.", "f", "ro", [ db_dxil_param(0, "f", "", "operation result"), db_dxil_param(2, "i32", "rayQueryHandle", "RayQuery handle"), db_dxil_param(3, "i32", "row", "row [0..2], relative to the element"), db_dxil_param(4, "i8", "col", "column [0..3], relative to the element"), ], ) next_op_idx += 1 self.add_dxil_op( "RayQuery_CandidateProceduralPrimitiveNonOpaque", next_op_idx, "RayQuery_StateScalar", "returns if current candidate procedural primitive is non opaque", "1", "ro", [ db_dxil_param(0, "i1", "", "operation result"), db_dxil_param(2, "i32", "rayQueryHandle", "RayQuery handle"), ], ) next_op_idx += 1 self.add_dxil_op( "RayQuery_CandidateTriangleFrontFace", next_op_idx, "RayQuery_StateScalar", "returns if current candidate triangle is front facing", "1", "ro", [ db_dxil_param(0, "i1", "", "operation result"), db_dxil_param(2, "i32", "rayQueryHandle", "RayQuery handle"), ], ) next_op_idx += 1 self.add_dxil_op( "RayQuery_CommittedTriangleFrontFace", next_op_idx, "RayQuery_StateScalar", "returns if current committed triangle is front facing", "1", "ro", [ db_dxil_param(0, "i1", "", "operation result"), db_dxil_param(2, "i32", "rayQueryHandle", "RayQuery handle"), ], ) next_op_idx += 1 self.add_dxil_op( "RayQuery_CandidateTriangleBarycentrics", next_op_idx, "RayQuery_StateVector", "returns candidate triangle hit barycentrics", "f", "ro", [ db_dxil_param(0, "f", "", "operation result"), db_dxil_param(2, "i32", "rayQueryHandle", "RayQuery handle"), db_dxil_param(3, "i8", "component", "component [0..2]", is_const=True), ], ) next_op_idx += 1 self.add_dxil_op( "RayQuery_CommittedTriangleBarycentrics", next_op_idx, "RayQuery_StateVector", "returns committed triangle hit barycentrics", "f", "ro", [ db_dxil_param(0, "f", "", "operation result"), db_dxil_param(2, "i32", "rayQueryHandle", "RayQuery handle"), db_dxil_param(3, "i8", "component", "component [0..2]", is_const=True), ], ) next_op_idx += 1 self.add_dxil_op( "RayQuery_RayFlags", next_op_idx, "RayQuery_StateScalar", "returns ray flags", "i", "ro", [ db_dxil_param(0, "i32", "", "operation result"), db_dxil_param(2, "i32", "rayQueryHandle", "RayQuery handle"), ], ) next_op_idx += 1 self.add_dxil_op( "RayQuery_WorldRayOrigin", next_op_idx, "RayQuery_StateVector", "returns world ray origin", "f", "ro", [ db_dxil_param(0, "f", "", "operation result"), db_dxil_param(2, "i32", "rayQueryHandle", "RayQuery handle"), db_dxil_param(3, "i8", "component", "component [0..2]", is_const=True), ], ) next_op_idx += 1 self.add_dxil_op( "RayQuery_WorldRayDirection", next_op_idx, "RayQuery_StateVector", "returns world ray direction", "f", "ro", [ db_dxil_param(0, "f", "", "operation result"), db_dxil_param(2, "i32", "rayQueryHandle", "RayQuery handle"), db_dxil_param(3, "i8", "component", "component [0..2]", is_const=True), ], ) next_op_idx += 1 self.add_dxil_op( "RayQuery_RayTMin", next_op_idx, "RayQuery_StateScalar", "returns float representing the parametric starting point for the ray.", "f", "ro", [ db_dxil_param(0, "f", "", "operation result"), db_dxil_param(2, "i32", "rayQueryHandle", "RayQuery handle"), ], ) next_op_idx += 1 self.add_dxil_op( "RayQuery_CandidateTriangleRayT", next_op_idx, "RayQuery_StateScalar", "returns float representing the parametric point on the ray for the current candidate triangle hit.", "f", "ro", [ db_dxil_param(0, "f", "", "operation result"), db_dxil_param(2, "i32", "rayQueryHandle", "RayQuery handle"), ], ) next_op_idx += 1 self.add_dxil_op( "RayQuery_CommittedRayT", next_op_idx, "RayQuery_StateScalar", "returns float representing the parametric point on the ray for the current committed hit.", "f", "ro", [ db_dxil_param(0, "f", "", "operation result"), db_dxil_param(2, "i32", "rayQueryHandle", "RayQuery handle"), ], ) next_op_idx += 1 self.add_dxil_op( "RayQuery_CandidateInstanceIndex", next_op_idx, "RayQuery_StateScalar", "returns candidate hit instance index", "i", "ro", [ db_dxil_param(0, "i32", "", "operation result"), db_dxil_param(2, "i32", "rayQueryHandle", "RayQuery handle"), ], ) next_op_idx += 1 self.add_dxil_op( "RayQuery_CandidateInstanceID", next_op_idx, "RayQuery_StateScalar", "returns candidate hit instance ID", "i", "ro", [ db_dxil_param(0, "i32", "", "operation result"), db_dxil_param(2, "i32", "rayQueryHandle", "RayQuery handle"), ], ) next_op_idx += 1 self.add_dxil_op( "RayQuery_CandidateGeometryIndex", next_op_idx, "RayQuery_StateScalar", "returns candidate hit geometry index", "i", "ro", [ db_dxil_param(0, "i32", "", "operation result"), db_dxil_param(2, "i32", "rayQueryHandle", "RayQuery handle"), ], ) next_op_idx += 1 self.add_dxil_op( "RayQuery_CandidatePrimitiveIndex", next_op_idx, "RayQuery_StateScalar", "returns candidate hit geometry index", "i", "ro", [ db_dxil_param(0, "i32", "", "operation result"), db_dxil_param(2, "i32", "rayQueryHandle", "RayQuery handle"), ], ) next_op_idx += 1 self.add_dxil_op( "RayQuery_CandidateObjectRayOrigin", next_op_idx, "RayQuery_StateVector", "returns candidate hit object ray origin", "f", "ro", [ db_dxil_param(0, "f", "", "operation result"), db_dxil_param(2, "i32", "rayQueryHandle", "RayQuery handle"), db_dxil_param(3, "i8", "component", "component [0..2]", is_const=True), ], ) next_op_idx += 1 self.add_dxil_op( "RayQuery_CandidateObjectRayDirection", next_op_idx, "RayQuery_StateVector", "returns candidate object ray direction", "f", "ro", [ db_dxil_param(0, "f", "", "operation result"), db_dxil_param(2, "i32", "rayQueryHandle", "RayQuery handle"), db_dxil_param(3, "i8", "component", "component [0..2]", is_const=True), ], ) next_op_idx += 1 self.add_dxil_op( "RayQuery_CommittedInstanceIndex", next_op_idx, "RayQuery_StateScalar", "returns committed hit instance index", "i", "ro", [ db_dxil_param(0, "i32", "", "operation result"), db_dxil_param(2, "i32", "rayQueryHandle", "RayQuery handle"), ], ) next_op_idx += 1 self.add_dxil_op( "RayQuery_CommittedInstanceID", next_op_idx, "RayQuery_StateScalar", "returns committed hit instance ID", "i", "ro", [ db_dxil_param(0, "i32", "", "operation result"), db_dxil_param(2, "i32", "rayQueryHandle", "RayQuery handle"), ], ) next_op_idx += 1 self.add_dxil_op( "RayQuery_CommittedGeometryIndex", next_op_idx, "RayQuery_StateScalar", "returns committed hit geometry index", "i", "ro", [ db_dxil_param(0, "i32", "", "operation result"), db_dxil_param(2, "i32", "rayQueryHandle", "RayQuery handle"), ], ) next_op_idx += 1 self.add_dxil_op( "RayQuery_CommittedPrimitiveIndex", next_op_idx, "RayQuery_StateScalar", "returns committed hit geometry index", "i", "ro", [ db_dxil_param(0, "i32", "", "operation result"), db_dxil_param(2, "i32", "rayQueryHandle", "RayQuery handle"), ], ) next_op_idx += 1 self.add_dxil_op( "RayQuery_CommittedObjectRayOrigin", next_op_idx, "RayQuery_StateVector", "returns committed hit object ray origin", "f", "ro", [ db_dxil_param(0, "f", "", "operation result"), db_dxil_param(2, "i32", "rayQueryHandle", "RayQuery handle"), db_dxil_param(3, "i8", "component", "component [0..2]", is_const=True), ], ) next_op_idx += 1 self.add_dxil_op( "RayQuery_CommittedObjectRayDirection", next_op_idx, "RayQuery_StateVector", "returns committed object ray direction", "f", "ro", [ db_dxil_param(0, "f", "", "operation result"), db_dxil_param(2, "i32", "rayQueryHandle", "RayQuery handle"), db_dxil_param(3, "i8", "component", "component [0..2]", is_const=True), ], ) next_op_idx += 1 self.add_dxil_op( "GeometryIndex", next_op_idx, "GeometryIndex", "The autogenerated index of the current geometry in the bottom-level structure", "i", "rn", [db_dxil_param(0, "i32", "", "result")], ) next_op_idx += 1 self.add_dxil_op( "RayQuery_CandidateInstanceContributionToHitGroupIndex", next_op_idx, "RayQuery_StateScalar", "returns candidate hit InstanceContributionToHitGroupIndex", "i", "ro", [ db_dxil_param(0, "i32", "", "operation result"), db_dxil_param(2, "i32", "rayQueryHandle", "RayQuery handle"), ], ) next_op_idx += 1 self.add_dxil_op( "RayQuery_CommittedInstanceContributionToHitGroupIndex", next_op_idx, "RayQuery_StateScalar", "returns committed hit InstanceContributionToHitGroupIndex", "i", "ro", [ db_dxil_param(0, "i32", "", "operation result"), db_dxil_param(2, "i32", "rayQueryHandle", "RayQuery handle"), ], ) next_op_idx += 1 # End of DXIL 1.5 opcodes. self.set_op_count_for_version(1, 5, next_op_idx) assert next_op_idx == 216, ( "216 is expected next operation index but encountered %d and thus opcodes are broken" % next_op_idx ) self.add_dxil_op( "AnnotateHandle", next_op_idx, "AnnotateHandle", "annotate handle with resource properties", "v", "rn", [ db_dxil_param(0, "res", "", "annotated handle"), db_dxil_param(2, "res", "res", "input handle"), db_dxil_param( 3, "resproperty", "props", "details like component type, structure stride...", is_const=True, ), ], ) next_op_idx += 1 self.add_dxil_op( "CreateHandleFromBinding", next_op_idx, "CreateHandleFromBinding", "create resource handle from binding", "v", "rn", [ db_dxil_param(0, "res", "", "result"), db_dxil_param( 2, "resbind", "bind", "resource binding", is_const=True ), # { rangeLowerBound, rangeUpperBound, spaceID, resourceClass } db_dxil_param(3, "i32", "index", "index"), db_dxil_param( 4, "i1", "nonUniformIndex", "non-uniform resource index", is_const=True, ), ], ) next_op_idx += 1 self.add_dxil_op( "CreateHandleFromHeap", next_op_idx, "CreateHandleFromHeap", "create resource handle from heap", "v", "rn", [ db_dxil_param(0, "res", "", "result"), db_dxil_param(2, "i32", "index", "heap index"), db_dxil_param( 3, "i1", "samplerHeap", "If samplerHeap is 1, the heap indexed is the sampler descriptor heap, otherwise it is the CBV_SRV_UAV (resource) descriptor heap", is_const=True, ), db_dxil_param( 4, "i1", "nonUniformIndex", "non-uniform resource index", is_const=True, ), ], ) next_op_idx += 1 self.add_dxil_op( "Unpack4x8", next_op_idx, "Unpack4x8", "unpacks 4 8-bit signed or unsigned values into int32 or int16 vector", "iw", "rn", [ db_dxil_param(0, "$vec4", "", "result"), db_dxil_param(2, "i8", "unpackMode", "signed/unsigned"), db_dxil_param(3, "i32", "pk", "packed 4 x i8"), ], ) next_op_idx += 1 self.add_dxil_op( "Pack4x8", next_op_idx, "Pack4x8", "packs vector of 4 signed or unsigned values into a packed datatype, drops or clamps unused bits", "iw", "rn", [ db_dxil_param(0, "i32", "", "result packed 4 x i8"), db_dxil_param(2, "i8", "packMode", "trunc/unsigned clamp/signed clamp"), db_dxil_param(3, "$o", "x", "the first component of the vector"), db_dxil_param(4, "$o", "y", "the second component of the vector"), db_dxil_param(5, "$o", "z", "the third component of the vector"), db_dxil_param(6, "$o", "w", "the fourth component of the vector"), ], ) next_op_idx += 1 self.add_dxil_op( "IsHelperLane", next_op_idx, "IsHelperLane", "returns true on helper lanes in pixel shaders", "1", "ro", [db_dxil_param(0, "i1", "", "result")], ) next_op_idx += 1 # End of DXIL 1.6 opcodes. self.set_op_count_for_version(1, 6, next_op_idx) assert next_op_idx == 222, ( "222 is expected next operation index but encountered %d and thus opcodes are broken" % next_op_idx ) self.add_enum_type( "QuadVoteOpKind", "Kind of cross-quad vote operation", [ (0, "Any", "true if any condition is true in this quad"), (1, "All", "true if all conditions are true in this quad"), ], ) self.add_dxil_op( "QuadVote", next_op_idx, "QuadVote", "compares boolean accross a quad", "1", "", [ db_dxil_param(0, "i1", "", "result - uniform across quad"), db_dxil_param(2, "i1", "cond", "condition"), db_dxil_param( 3, "i8", "op", "QuadVoteOpKind: 0=Any, 1=All", enum_name="QuadVoteOpKind", is_const=True, ), ], ) next_op_idx += 1 self.add_dxil_op( "TextureGatherRaw", next_op_idx, "TextureGatherRaw", "Gather raw elements from 4 texels with no type conversions (SRV type is constrained)", "wil", "ro", [ db_dxil_param(0, "$r", "", "four raw texture elements gathered"), db_dxil_param( 2, "res", "srv", "handle of type-matched SRV to gather from" ), db_dxil_param(3, "res", "sampler", "handle of sampler to use"), db_dxil_param(4, "f", "coord0", "coordinate"), db_dxil_param(5, "f", "coord1", "coordinate, undef for Texture1D"), db_dxil_param( 6, "f", "coord2", "coordinate, undef for Texture1D, Texture1DArray or Texture2D", ), db_dxil_param( 7, "f", "coord3", "coordinate, defined only for TextureCubeArray" ), db_dxil_param( 8, "i32", "offset0", "optional offset, applicable to Texture1D, Texture1DArray, and as part of offset1", ), db_dxil_param( 9, "i32", "offset1", "optional offset, applicable to Texture2D, Texture2DArray", ), ], counters=("tex_norm",), ) next_op_idx += 1 self.add_dxil_op( "SampleCmpLevel", next_op_idx, "SampleCmpLevel", "samples a texture and compares a single component against the specified comparison value", "hf", "ro", [ db_dxil_param(0, "$r", "", "the result of the filtered comparisons"), db_dxil_param(2, "res", "srv", "handle of SRV to sample"), db_dxil_param(3, "res", "sampler", "handle of sampler to use"), db_dxil_param(4, "f", "coord0", "coordinate"), db_dxil_param(5, "f", "coord1", "coordinate, undef for Texture1D"), db_dxil_param( 6, "f", "coord2", "coordinate, undef for Texture1D, Texture1DArray or Texture2D", ), db_dxil_param( 7, "f", "coord3", "coordinate, defined only for TextureCubeArray" ), db_dxil_param( 8, "i32", "offset0", "optional offset, applicable to Texture1D, Texture1DArray, and as part of offset1", ), db_dxil_param( 9, "i32", "offset1", "optional offset, applicable to Texture2D, Texture2DArray, and as part of offset2", ), db_dxil_param( 10, "i32", "offset2", "optional offset, applicable to Texture3D" ), db_dxil_param(11, "f", "compareValue", "the value to compare with"), db_dxil_param( 12, "f", "lod", "level of detail, biggest map if less than or equal to zero; fraction used to interpolate across levels", ), ], counters=("tex_cmp",), ) next_op_idx += 1 self.add_dxil_op( "TextureStoreSample", next_op_idx, "TextureStoreSample", "stores texel data at specified sample index", "hfwi", "", [ db_dxil_param(0, "v", "", ""), db_dxil_param( 2, "res", "srv", "handle of Texture2DMS[Array] UAV to store to" ), db_dxil_param(3, "i32", "coord0", "coordinate"), db_dxil_param(4, "i32", "coord1", "coordinate"), db_dxil_param(5, "i32", "coord2", "coordinate"), db_dxil_param(6, "$o", "value0", "value"), db_dxil_param(7, "$o", "value1", "value"), db_dxil_param(8, "$o", "value2", "value"), db_dxil_param(9, "$o", "value3", "value"), db_dxil_param(10, "i8", "mask", "written value mask", is_const=True), db_dxil_param(11, "i32", "sampleIdx", "sample index"), ], counters=("tex_store",), ) next_op_idx += 1 # End of DXIL 1.7 opcodes. self.set_op_count_for_version(1, 7, next_op_idx) assert next_op_idx == 226, ( "226 is expected next operation index but encountered %d and thus opcodes are broken" % next_op_idx ) # Reserved ops self.add_dxil_op( "Reserved0", next_op_idx, "Reserved", "Reserved", "v", "", [retvoid_param], ) next_op_idx += 1 self.add_dxil_op( "Reserved1", next_op_idx, "Reserved", "Reserved", "v", "", [retvoid_param], ) next_op_idx += 1 self.add_dxil_op( "Reserved2", next_op_idx, "Reserved", "Reserved", "v", "", [retvoid_param], ) next_op_idx += 1 self.add_dxil_op( "Reserved3", next_op_idx, "Reserved", "Reserved", "v", "", [retvoid_param], ) next_op_idx += 1 self.add_dxil_op( "Reserved4", next_op_idx, "Reserved", "Reserved", "v", "", [retvoid_param], ) next_op_idx += 1 self.add_dxil_op( "Reserved5", next_op_idx, "Reserved", "Reserved", "v", "", [retvoid_param], ) next_op_idx += 1 self.add_dxil_op( "Reserved6", next_op_idx, "Reserved", "Reserved", "v", "", [retvoid_param], ) next_op_idx += 1 self.add_dxil_op( "Reserved7", next_op_idx, "Reserved", "Reserved", "v", "", [retvoid_param], ) next_op_idx += 1 self.add_dxil_op( "Reserved8", next_op_idx, "Reserved", "Reserved", "v", "", [retvoid_param], ) next_op_idx += 1 self.add_dxil_op( "Reserved9", next_op_idx, "Reserved", "Reserved", "v", "", [retvoid_param], ) next_op_idx += 1 self.add_dxil_op( "Reserved10", next_op_idx, "Reserved", "Reserved", "v", "", [retvoid_param], ) next_op_idx += 1 self.add_dxil_op( "Reserved11", next_op_idx, "Reserved", "Reserved", "v", "", [retvoid_param], ) next_op_idx += 1 # Work Graph self.add_dxil_op( "AllocateNodeOutputRecords", next_op_idx, "AllocateNodeOutputRecords", "returns a handle for the output records", "v", "", [ db_dxil_param(0, "noderecordhandle", "", "handle of output record"), db_dxil_param(2, "nodehandle", "output", "handle of node output"), db_dxil_param(3, "i32", "numRecords", "number of records"), db_dxil_param(4, "i1", "perThread", "perThread flag", is_const=True), ], ) next_op_idx += 1 self.add_dxil_op( "GetNodeRecordPtr", next_op_idx, "GetNodeRecordPtr", "retrieve node input/output record pointer in address space 6", "u", "rn", [ db_dxil_param(0, "$o", "", "record pointer"), db_dxil_param( 2, "noderecordhandle", "recordhandle", "handle of record" ), db_dxil_param(3, "i32", "arrayIndex", "array index"), ], ) next_op_idx += 1 self.add_dxil_op( "IncrementOutputCount", next_op_idx, "IncrementOutputCount", "Select the next logical output count for an EmptyNodeOutput for the whole group or per thread.", "v", "", [ retvoid_param, db_dxil_param(2, "nodehandle", "output", "handle of node output"), db_dxil_param( 3, "i32", "count", "value by which to increment the count" ), db_dxil_param(4, "i1", "perThread", "perThread flag", is_const=True), ], ) next_op_idx += 1 self.add_dxil_op( "OutputComplete", next_op_idx, "OutputComplete", "indicates all outputs for a given records are complete", "v", "", [ retvoid_param, db_dxil_param(2, "noderecordhandle", "output", "handle of record"), ], ) next_op_idx += 1 self.add_dxil_op( "GetInputRecordCount", next_op_idx, "GetInputRecordCount", "returns the number of records that have been coalesced into the current thread group", "v", "ro", [ db_dxil_param(0, "i32", "", "number of records"), db_dxil_param(2, "noderecordhandle", "input", "handle of input record"), ], ) next_op_idx += 1 self.add_dxil_op( "FinishedCrossGroupSharing", next_op_idx, "FinishedCrossGroupSharing", "returns true if the current thread group is the last to access the input", "v", "", [ db_dxil_param( 0, "i1", "", "true if current thread group is last to access the input ", ), db_dxil_param(2, "noderecordhandle", "input", "handle of input record"), ], ) next_op_idx += 1 self.add_dxil_op( "BarrierByMemoryType", next_op_idx, "BarrierByMemoryType", "Request a barrier for a set of memory types and/or thread group execution sync", "v", "nd", [ retvoid_param, db_dxil_param( 2, "i32", "MemoryTypeFlags", "memory type flags", is_const=True ), db_dxil_param( 3, "i32", "SemanticFlags", "semantic flags", is_const=True ), ], counters=("barrier",), ) next_op_idx += 1 self.add_dxil_op( "BarrierByMemoryHandle", next_op_idx, "BarrierByMemoryHandle", "Request a barrier for just the memory used by the specified object", "v", "nd", [ retvoid_param, db_dxil_param(2, "res", "object", "handle of object"), db_dxil_param( 3, "i32", "SemanticFlags", "semantic flags", is_const=True ), ], counters=("barrier",), ) next_op_idx += 1 self.add_dxil_op( "BarrierByNodeRecordHandle", next_op_idx, "BarrierByNodeRecordHandle", "Request a barrier for just the memory used by the node record", "v", "nd", [ retvoid_param, db_dxil_param(2, "noderecordhandle", "object", "handle of object"), db_dxil_param( 3, "i32", "SemanticFlags", "semantic flags", is_const=True ), ], counters=("barrier",), ) next_op_idx += 1 self.add_dxil_op( "CreateNodeOutputHandle", next_op_idx, "createNodeOutputHandle", "Creates a handle to a NodeOutput", "v", "rn", [ db_dxil_param(0, "nodehandle", "output", "handle of object"), db_dxil_param(2, "i32", "MetadataIdx", "metadata index", is_const=True), ], ) next_op_idx += 1 self.add_dxil_op( "IndexNodeHandle", next_op_idx, "IndexNodeHandle", "returns the handle for the location in the output node array at the indicated index", "v", "rn", [ db_dxil_param(0, "nodehandle", "output", "handle of index"), db_dxil_param( 2, "nodehandle", "NodeOutputHandle", "Handle from CreateNodeOutputHandle", ), db_dxil_param(3, "i32", "ArrayIndex", "array index"), ], ) next_op_idx += 1 self.add_dxil_op( "AnnotateNodeHandle", next_op_idx, "AnnotateNodeHandle", "annotate handle with node properties", "v", "rn", [ db_dxil_param(0, "nodehandle", "", "annotated node handle"), db_dxil_param(2, "nodehandle", "node", "input node handle"), db_dxil_param( 3, "nodeproperty", "props", "details like NodeIOFlags, RecordSize ...", is_const=True, ), ], ) next_op_idx += 1 self.add_dxil_op( "CreateNodeInputRecordHandle", next_op_idx, "CreateNodeInputRecordHandle", "create a handle for an InputRecord", "v", "rn", [ db_dxil_param(0, "noderecordhandle", "output", "output handle"), db_dxil_param(2, "i32", "MetadataIdx", "metadata index", is_const=True), ], ) next_op_idx += 1 self.add_dxil_op( "AnnotateNodeRecordHandle", next_op_idx, "AnnotateNodeRecordHandle", "annotate handle with node record properties", "v", "rn", [ db_dxil_param( 0, "noderecordhandle", "", "annotated node record handle" ), db_dxil_param( 2, "noderecordhandle", "noderecord", "input node record handle" ), db_dxil_param( 3, "noderecordproperty", "props", "details like NodeIOFlags, MaxArraySize ...", is_const=True, ), ], ) next_op_idx += 1 self.add_dxil_op( "NodeOutputIsValid", next_op_idx, "NodeOutputIsValid", "returns true if the specified output node is present in the work graph", "v", "ro", [ db_dxil_param(0, "i1", "", "true if output node present"), db_dxil_param(2, "nodehandle", "output", "handle of output node"), ], ) next_op_idx += 1 self.add_dxil_op( "GetRemainingRecursionLevels", next_op_idx, "GetRemainingRecursionLevels", "returns how many levels of recursion remain", "v", "ro", [db_dxil_param(0, "i32", "", "number of levels of recursion remaining")], ) next_op_idx += 1 # Comparison Sampling self.add_dxil_op( "SampleCmpGrad", next_op_idx, "SampleCmpGrad", "samples a texture using a gradient and compares a single component against the specified comparison value", "hf", "ro", [ db_dxil_param(0, "$r", "", "the result of the filtered comparisons"), db_dxil_param(2, "res", "srv", "handle of SRV to sample"), db_dxil_param(3, "res", "sampler", "handle of sampler to use"), db_dxil_param(4, "f", "coord0", "coordinate"), db_dxil_param(5, "f", "coord1", "coordinate, undef for Texture1D"), db_dxil_param( 6, "f", "coord2", "coordinate, undef for Texture1D, Texture1DArray or Texture2D", ), db_dxil_param( 7, "f", "coord3", "coordinate, defined only for TextureCubeArray" ), db_dxil_param( 8, "i32", "offset0", "optional offset, applicable to Texture1D, Texture1DArray, and as part of offset1", ), db_dxil_param( 9, "i32", "offset1", "optional offset, applicable to Texture2D, Texture2DArray, and as part of offset2", ), db_dxil_param( 10, "i32", "offset2", "optional offset, applicable to Texture3D" ), db_dxil_param(11, "f", "compareValue", "the value to compare with"), db_dxil_param( 12, "f", "ddx0", "rate of change of coordinate c0 in the x direction", ), db_dxil_param( 13, "f", "ddx1", "rate of change of coordinate c1 in the x direction", ), db_dxil_param( 14, "f", "ddx2", "rate of change of coordinate c2 in the x direction", ), db_dxil_param( 15, "f", "ddy0", "rate of change of coordinate c0 in the y direction", ), db_dxil_param( 16, "f", "ddy1", "rate of change of coordinate c1 in the y direction", ), db_dxil_param( 17, "f", "ddy2", "rate of change of coordinate c2 in the y direction", ), db_dxil_param(18, "f", "clamp", "clamp value"), ], counters=("tex_cmp",), ) next_op_idx += 1 self.add_dxil_op( "SampleCmpBias", next_op_idx, "SampleCmpBias", "samples a texture after applying the input bias to the mipmap level and compares a single component against the specified comparison value", "hf", "ro", [ db_dxil_param(0, "$r", "", "the result of the filtered comparisons"), db_dxil_param(2, "res", "srv", "handle of SRV to sample"), db_dxil_param(3, "res", "sampler", "handle of sampler to use"), db_dxil_param(4, "f", "coord0", "coordinate"), db_dxil_param(5, "f", "coord1", "coordinate, undef for Texture1D"), db_dxil_param( 6, "f", "coord2", "coordinate, undef for Texture1D, Texture1DArray or Texture2D", ), db_dxil_param( 7, "f", "coord3", "coordinate, defined only for TextureCubeArray" ), db_dxil_param( 8, "i32", "offset0", "optional offset, applicable to Texture1D, Texture1DArray, and as part of offset1", ), db_dxil_param( 9, "i32", "offset1", "optional offset, applicable to Texture2D, Texture2DArray, and as part of offset2", ), db_dxil_param( 10, "i32", "offset2", "optional offset, applicable to Texture3D" ), db_dxil_param(11, "f", "compareValue", "the value to compare with"), db_dxil_param(12, "f", "bias", "bias value"), db_dxil_param(13, "f", "clamp", "clamp value"), ], counters=("tex_cmp",), ) next_op_idx += 1 self.add_dxil_op( "StartVertexLocation", next_op_idx, "StartVertexLocation", "returns the BaseVertexLocation from DrawIndexedInstanced or StartVertexLocation from DrawInstanced", "i", "rn", [db_dxil_param(0, "i32", "", "result")], ) next_op_idx += 1 self.add_dxil_op( "StartInstanceLocation", next_op_idx, "StartInstanceLocation", "returns the StartInstanceLocation from Draw*Instanced", "i", "rn", [db_dxil_param(0, "i32", "", "result")], ) next_op_idx += 1 # End of DXIL 1.8 opcodes. self.set_op_count_for_version(1, 8, next_op_idx) assert next_op_idx == 258, ( "258 is expected next operation index but encountered %d and thus opcodes are broken" % next_op_idx ) # Set interesting properties. self.build_indices() for ( i ) in "CalculateLOD,DerivCoarseX,DerivCoarseY,DerivFineX,DerivFineY,Sample,SampleBias,SampleCmp,SampleCmpBias".split( "," ): self.name_idx[i].is_gradient = True for i in "DerivCoarseX,DerivCoarseY,DerivFineX,DerivFineY".split(","): assert ( self.name_idx[i].is_gradient == True ), "all derivatives are marked as requiring gradients" self.name_idx[i].is_deriv = True # TODO - some arguments are required to be immediate constants in DXIL, eg resource kinds; add this information # consider - report instructions that are overloaded on a single type, then turn them into non-overloaded version of that type self.verify_dense( self.get_dxil_insts(), lambda x: x.dxil_opid, lambda x: x.name ) for i in self.instr: self.verify_dense(i.ops, lambda x: x.pos, lambda x: i.name) for i in self.instr: if i.is_dxil_op: assert i.oload_types != "", ( "overload for DXIL operation %s should not be empty - use void if n/a" % (i.name) ) assert i.oload_types == "v" or i.oload_types.find("v") < 0, ( "void overload should be exclusive to other types (%s)" % i.name ) assert ( type(i.oload_types) is str ), "overload for %s should be a string - use empty if n/a" % (i.name) # Verify that all operations in each class have the same signature. import itertools class_sort_func = lambda x, y: x < y class_key_func = lambda x: x.dxil_class instr_ordered_by_class = sorted( [i for i in self.instr if i.is_dxil_op], key=class_key_func ) instr_grouped_by_class = itertools.groupby( instr_ordered_by_class, key=class_key_func ) def calc_oload_sig(inst): result = "" for o in inst.ops: result += o.llvm_type return result for k, g in instr_grouped_by_class: group = list(g) if len(group) > 1: first = group[0] first_group = calc_oload_sig(first) for other in group[1:]: other_group = calc_oload_sig(other) # TODO: uncomment assert when opcodes are fixed # assert first_group == other_group, "overload signature %s for instruction %s differs from %s in %s" % (first.name, first_group, other.name, other_group) def populate_extended_docs(self): "Update the documentation with text from external files." inst_starter = "* Inst: " block_starter = "* BLOCK-BEGIN" block_end = "* BLOCK-END" thisdir = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(thisdir, "hctdb_inst_docs.txt")) as ops_file: inst_name = "" inst_doc = "" inst_remarks = "" is_block = False for idx, line in enumerate(ops_file): if line.startswith("#"): continue if line.startswith(block_starter): assert is_block == False, "unexpected block begin at line %i" % ( idx + 1 ) is_block = True continue if line.startswith(block_end): assert is_block == True, "unexpected block end at line %i" % ( idx + 1 ) is_block = False continue if line.startswith(inst_starter): if inst_name: # print(inst_name + " - " + inst_remarks.strip()) self.name_idx[inst_name].doc = inst_doc self.name_idx[inst_name].remarks = inst_remarks.strip() inst_remarks = "" line = line[len(inst_starter) :] sep_idx = line.find("-") inst_name = line[:sep_idx].strip() inst_doc = line[sep_idx + 1 :].strip() else: inst_remarks += line if is_block else "\n" + line.strip() if inst_name: self.name_idx[inst_name].remarks = inst_remarks.strip() def populate_metadata(self): # For now, simply describe the allowed named metadata. m = self.metadata m.append( db_dxil_metadata( "dx.controlflow.hints", "Provides control flow hints to an instruction." ) ) m.append(db_dxil_metadata("dx.entryPoints", "Entry point functions.")) m.append(db_dxil_metadata("dx.precise", "Marks an instruction as precise.")) m.append( db_dxil_metadata( "dx.resources", "Resources used by the entry point shaders." ) ) m.append(db_dxil_metadata("dx.shaderModel", "Shader model for the module.")) m.append( db_dxil_metadata("dx.typeAnnotations", "Provides annotations for types.") ) m.append(db_dxil_metadata("dx.typevar.*", ".")) m.append(db_dxil_metadata("dx.valver", "Optional validator version.")) m.append( db_dxil_metadata("dx.version", "Optional DXIL version for the module.") ) # dx.typevar.* is not the name of metadata, but the prefix for global variables # that will be referenced by structure type annotations. def populate_passes(self): # Populate passes and their options. p = self.passes category_lib = "set this before add_pass" def add_pass(name, type_name, doc, opts): apass = db_dxil_pass( name, type_name=type_name, doc=doc, category_lib=category_lib ) for o in opts: assert "n" in o, "option in %s has no 'n' member" % name apass.args.append( db_dxil_pass_arg( o["n"], ident=o.get("i"), type_name=o.get("t"), is_ctor_param=o.get("c"), doc=o.get("d"), ) ) p.append(apass) category_lib = "llvm" # Add discriminators is a DWARF 4 thing, useful for the profiler. # Consider removing lib\Transforms\Utils\AddDiscriminators.cpp altogether add_pass( "add-discriminators", "AddDiscriminators", "Add DWARF path discriminators", [{"n": "no-discriminators", "i": "NoDiscriminators", "t": "bool"}], ) # Sample profile is part of the sample profiling infrastructure. # Consider removing lib\Transforms\Scalar\SampleProfile.cpp add_pass( "sample-profile", "SampleProfileLoader", "Sample Profile loader", [ {"n": "sample-profile-file", "i": "SampleProfileFile", "t": "string"}, { "n": "sample-profile-max-propagate-iterations", "i": "SampleProfileMaxPropagateIterations", "t": "unsigned", }, ], ) # inline and always-inline share a base class - those are the arguments we document for each of them. inliner_args = [ { "n": "InsertLifetime", "t": "bool", "c": 1, "d": "Insert @llvm.lifetime intrinsics", }, { "n": "InlineThreshold", "t": "unsigned", "c": 1, "d": "Insert @llvm.lifetime intrinsics", }, ] add_pass( "inline", "SimpleInliner", "Function Integration/Inlining", inliner_args ) # {'n':"OptLevel", 't':"unsigned", 'c':1}, # {'n':"SizeOptLevel", 't':'unsigned', 'c':1} add_pass( "always-inline", "AlwaysInliner", "Inliner for always_inline functions", inliner_args, ) # {'n':'InsertLifetime', 't':'bool', 'c':1, 'd':'Insert @llvm.lifetime intrinsics'} # Consider a review of the target-specific wrapper. add_pass( "tti", "TargetTransformInfoWrapperPass", "Target Transform Information", [{"n": "TIRA", "t": "TargetIRAnalysis", "c": 1}], ) add_pass( "verify", "VerifierLegacyPass", "Module Verifier", [ {"n": "FatalErrors", "t": "bool", "c": 1}, {"n": "verify-debug-info", "i": "VerifyDebugInfo", "t": "bool"}, ], ) add_pass( "targetlibinfo", "TargetLibraryInfoWrapperPass", "Target Library Information", [ {"n": "TLIImpl", "t": "TargetLibraryInfoImpl", "c": 1}, { "n": "vector-library", "i": "ClVectorLibrary", "t": "TargetLibraryInfoImpl::VectorLibrary", }, ], ) add_pass("cfl-aa", "CFLAliasAnalysis", "CFL-Based AA implementation", []) add_pass( "tbaa", "TypeBasedAliasAnalysis", "Type-Based Alias Analysis", [ { "n": "enable-tbaa", "i": "EnableTBAA", "t": "bool", "d": "Use to disable TBAA functionality", } ], ) add_pass( "scoped-noalias", "ScopedNoAliasAA", "Scoped NoAlias Alias Analysis", [ { "n": "enable-scoped-noalias", "i": "EnableScopedNoAlias", "t": "bool", "d": "Use to disable scoped no-alias", } ], ) add_pass( "basicaa", "BasicAliasAnalysis", "Basic Alias Analysis (stateless AA impl)", [], ) add_pass( "simplifycfg", "CFGSimplifyPass", "Simplify the CFG", [ {"n": "Threshold", "t": "int", "c": 1}, {"n": "Ftor", "t": "std::function<bool(const Function &)>", "c": 1}, { "n": "bonus-inst-threshold", "i": "UserBonusInstThreshold", "t": "unsigned", "d": "Control the number of bonus instructions (default = 1)", }, ], ) # UseNewSROA is used by PassManagerBuilder::populateFunctionPassManager, not a pass per se. add_pass( "sroa", "SROA", "Scalar Replacement Of Aggregates", [ {"n": "RequiresDomTree", "t": "bool", "c": 1}, {"n": "SkipHLSLMat", "t": "bool", "c": 1}, { "n": "force-ssa-updater", "i": "ForceSSAUpdater", "t": "bool", "d": "Force the pass to not use DomTree and mem2reg, insteadforming SSA values through the SSAUpdater infrastructure.", }, { "n": "sroa-random-shuffle-slices", "i": "SROARandomShuffleSlices", "t": "bool", "d": "Enable randomly shuffling the slices to help uncover instability in their order.", }, { "n": "sroa-strict-inbounds", "i": "SROAStrictInbounds", "t": "bool", "d": "Experiment with completely strict handling of inbounds GEPs.", }, ], ) add_pass( "dxil-cond-mem2reg", "DxilConditionalMem2Reg", "Dxil Conditional Mem2Reg", [ {"n": "NoOpt", "t": "bool", "c": 1}, ], ) add_pass( "scalarrepl", "SROA_DT", "Scalar Replacement of Aggregates (DT)", [ {"n": "Threshold", "t": "int", "c": 1}, {"n": "StructMemberThreshold", "t": "int", "c": 1}, {"n": "ArrayElementThreshold", "t": "int", "c": 1}, {"n": "ScalarLoadThreshold", "t": "int", "c": 1}, ], ) add_pass( "scalarrepl-ssa", "SROA_SSAUp", "Scalar Replacement of Aggregates (SSAUp)", [ {"n": "Threshold", "t": "int", "c": 1}, {"n": "StructMemberThreshold", "t": "int", "c": 1}, {"n": "ArrayElementThreshold", "t": "int", "c": 1}, {"n": "ScalarLoadThreshold", "t": "int", "c": 1}, ], ) add_pass("early-cse", "EarlyCSELegacyPass", "Early CSE", []) # More branch weight support. add_pass( "lower-expect", "LowerExpectIntrinsic", "Lower 'expect' Intrinsics", [ { "n": "likely-branch-weight", "i": "LikelyBranchWeight", "t": "uint32_t", "d": "Weight of the branch likely to be taken (default = 64)", }, { "n": "unlikely-branch-weight", "i": "UnlikelyBranchWeight", "t": "uint32_t", "d": "Weight of the branch unlikely to be taken (default = 4)", }, ], ) # Consider removing lib\Transforms\Utils\SymbolRewriter.cpp add_pass( "rewrite-symbols", "RewriteSymbols", "Rewrite Symbols", [ {"n": "DL", "t": "SymbolRewriter::RewriteDescriptorList", "c": 1}, {"n": "rewrite-map-file", "i": "RewriteMapFiles", "t": "string"}, ], ) add_pass( "mergefunc", "MergeFunctions", "Merge Functions", [ { "n": "mergefunc-sanity", "i": "NumFunctionsForSanityCheck", "t": "unsigned", "d": "How many functions in module could be used for MergeFunctions pass sanity check. '0' disables this check. Works only with '-debug' key.", } ], ) # Consider removing GlobalExtensions globals altogether. add_pass("barrier", "BarrierNoop", "A No-Op Barrier Pass", []) add_pass("dce", "DCE", "Dead Code Elimination", []) add_pass("die", "DeadInstElimination", "Dead Instruction Elimination", []) add_pass("globaldce", "GlobalDCE", "Dead Global Elimination", []) add_pass("mem2reg", "PromotePass", "Promote Memory to Register", []) add_pass("scalarizer", "Scalarizer", "Scalarize vector operations", []) category_lib = "pix" add_pass( "hlsl-dxil-add-pixel-hit-instrmentation", "DxilAddPixelHitInstrumentation", "DXIL Count completed PS invocations and costs", [ {"n": "force-early-z", "t": "int", "c": 1}, {"n": "add-pixel-cost", "t": "int", "c": 1}, {"n": "rt-width", "t": "int", "c": 1}, {"n": "num-pixels", "t": "int", "c": 1}, {"n": "upstream-sv-position-row", "t": "int", "c": 1}, ], ) add_pass( "hlsl-dxil-constantColor", "DxilOutputColorBecomesConstant", "DXIL Constant Color Mod", [ {"n": "mod-mode", "t": "int", "c": 1}, {"n": "constant-red", "t": "float", "c": 1}, {"n": "constant-green", "t": "float", "c": 1}, {"n": "constant-blue", "t": "float", "c": 1}, {"n": "constant-alpha", "t": "float", "c": 1}, ], ) add_pass( "hlsl-dxil-remove-discards", "DxilRemoveDiscards", "HLSL DXIL Remove all discard instructions", [], ) add_pass( "hlsl-dxil-force-early-z", "DxilForceEarlyZ", "HLSL DXIL Force the early Z global flag, if shader has no discard calls", [], ) add_pass( "hlsl-dxil-pix-meshshader-output-instrumentation", "DxilPIXMeshShaderOutputInstrumentation", "DXIL mesh shader output instrumentation for PIX", [ {"n": "expand-payload", "t": "int", "c": 1}, {"n": "UAVSize", "t": "int", "c": 1}, {"n": "dispatchArgY", "t": "int", "c": 1}, {"n": "dispatchArgZ", "t": "int", "c": 1}, ], ) add_pass( "hlsl-dxil-pix-shader-access-instrumentation", "DxilShaderAccessTracking", "HLSL DXIL shader access tracking for PIX", [ {"n": "config", "t": "int", "c": 1}, {"n": "checkForDynamicIndexing", "t": "bool", "c": 1}, ], ) add_pass( "hlsl-dxil-debug-instrumentation", "DxilDebugInstrumentation", "HLSL DXIL debug instrumentation for PIX", [ {"n": "UAVSize", "t": "int", "c": 1}, {"n": "FirstInstruction", "t": "int", "c": 1}, {"n": "LastInstruction", "t": "int", "c": 1}, {"n": "parameter0", "t": "int", "c": 1}, {"n": "parameter1", "t": "int", "c": 1}, {"n": "parameter2", "t": "int", "c": 1}, {"n": "upstreamSVPositionRow", "t": "int", "c": 1}, ], ) add_pass( "dxil-annotate-with-virtual-regs", "DxilAnnotateWithVirtualRegister", "Annotates each instruction in the DXIL module with a virtual register number", [{"n": "startInstruction", "t": "int", "c": 1}], ) add_pass( "dxil-dbg-value-to-dbg-declare", "DxilDbgValueToDbgDeclare", "Converts llvm.dbg.value uses to llvm.dbg.declare.", [], ) add_pass( "hlsl-dxil-reduce-msaa-to-single", "DxilReduceMSAAToSingleSample", "HLSL DXIL Reduce all MSAA reads to single-sample reads", [], ) add_pass( "hlsl-dxil-PIX-add-tid-to-as-payload", "DxilPIXAddTidToAmplificationShaderPayload", "HLSL DXIL Add flat thread id to payload from AS to MS", [ {"n": "dispatchArgY", "t": "int", "c": 1}, {"n": "dispatchArgZ", "t": "int", "c": 1}, ], ) add_pass( "hlsl-dxil-pix-dxr-invocations-log", "DxilPIXDXRInvocationsLog", "HLSL DXIL Logs all non-RayGen DXR 1.0 invocations into a UAV", [{"n": "maxNumEntriesInLog", "t": "int", "c": 1}], ) category_lib = "dxil_gen" add_pass("hlsl-hlemit", "HLEmitMetadata", "HLSL High-Level Metadata Emit.", []) add_pass( "hl-expand-store-intrinsics", "HLExpandStoreIntrinsics", "Expand HLSL store intrinsics", [], ) add_pass( "hl-legalize-parameter", "HLLegalizeParameter", "Legalize parameter", [] ) add_pass( "scalarrepl-param-hlsl", "SROA_Parameter_HLSL", "Scalar Replacement of Aggregates HLSL (parameters)", [], ) add_pass( "static-global-to-alloca", "LowerStaticGlobalIntoAlloca", "Lower static global into Alloca", [], ) add_pass( "hlmatrixlower", "HLMatrixLowerPass", "HLSL High-Level Matrix Lower", [] ) add_pass( "matrixbitcastlower", "MatrixBitcastLowerPass", "Matrix Bitcast lower", [] ) add_pass( "reg2mem_hlsl", "RegToMemHlsl", "Demote values with phi-node usage to stack slots", [], ) add_pass( "dynamic-vector-to-array", "DynamicIndexingVectorToArray", "Replace dynamic indexing vector with array", [{"n": "ReplaceAllVectors", "t": "bool", "c": 1}], ) add_pass( "hlsl-dxil-promote-local-resources", "DxilPromoteLocalResources", "DXIL promote local resource use", [], ) add_pass( "hlsl-dxil-promote-static-resources", "DxilPromoteStaticResources", "DXIL promote static resource use", [], ) add_pass( "hlsl-dxil-legalize-resources", "DxilLegalizeResources", "DXIL legalize resource use", [], ) add_pass( "hlsl-dxil-legalize-eval-operations", "DxilLegalizeEvalOperations", "DXIL legalize eval operations", [], ) add_pass( "dxilgen", "DxilGenerationPass", "HLSL DXIL Generation", [{"n": "NotOptimized", "t": "bool", "c": 1}], ) add_pass( "invalidate-undef-resource", "InvalidateUndefResources", "Invalidate undef resources", [], ) add_pass("simplify-inst", "SimplifyInst", "Simplify Instructions", []) add_pass( "hlsl-dxil-precise", "DxilPrecisePropagatePass", "DXIL precise attribute propagate", [], ) add_pass( "dxil-legalize-sample-offset", "DxilLegalizeSampleOffsetPass", "DXIL legalize sample offset", [], ) add_pass("dxil-gvn-hoist", "DxilSimpleGVNHoist", "DXIL simple gvn hoist", []) add_pass( "dxil-gvn-eliminate-region", "DxilSimpleGVNEliminateRegion", "DXIL simple eliminate region", [], ) add_pass( "hlsl-hlensure", "HLEnsureMetadata", "HLSL High-Level Metadata Ensure", [] ) add_pass( "multi-dim-one-dim", "MultiDimArrayToOneDimArray", "Flatten multi-dim array into one-dim array", [], ) add_pass( "resource-handle", "ResourceToHandle", "Lower resource into handle", [] ) add_pass( "hlsl-passes-nopause", "NoPausePasses", "Clears metadata used for pause and resume", [], ) add_pass("hlsl-passes-pause", "PausePasses", "Prepare to pause passes", []) add_pass("hlsl-passes-resume", "ResumePasses", "Prepare to resume passes", []) add_pass( "hlsl-dxil-lower-handle-for-lib", "DxilLowerCreateHandleForLib", "DXIL Lower createHandleForLib", [], ) add_pass( "hlsl-dxil-cleanup-dynamic-resource-handle", "DxilCleanupDynamicResourceHandle", "DXIL Cleanup dynamic resource handle calls", [], ) add_pass( "hlsl-dxil-allocate-resources-for-lib", "DxilAllocateResourcesForLib", "DXIL Allocate Resources For Library", [], ) add_pass( "hlsl-dxil-convergent-mark", "DxilConvergentMark", "Mark convergent", [] ) add_pass( "hlsl-dxil-convergent-clear", "DxilConvergentClear", "Clear convergent before dxil emit", [], ) add_pass( "hlsl-dxil-eliminate-output-dynamic", "DxilEliminateOutputDynamicIndexing", "DXIL eliminate ouptut dynamic indexing", [], ) add_pass( "dxil-delete-redundant-debug-values", "DxilDeleteRedundantDebugValues", "Dxil Delete Redundant Debug Values", [], ) add_pass( "hlsl-dxilfinalize", "DxilFinalizeModule", "HLSL DXIL Finalize Module", [] ) add_pass("hlsl-dxilemit", "DxilEmitMetadata", "HLSL DXIL Metadata Emit", []) add_pass("hlsl-dxilload", "DxilLoadMetadata", "HLSL DXIL Metadata Load", []) add_pass( "dxil-dfe", "DxilDeadFunctionElimination", "Remove all unused function except entry from DxilModule", [], ) add_pass( "hl-dfe", "HLDeadFunctionElimination", "Remove all unused function except entry from HLModule", [], ) add_pass( "hl-preprocess", "HLPreprocess", "Preprocess HLModule after inline", [] ) add_pass( "hlsl-dxil-expand-trig", "DxilExpandTrigIntrinsics", "DXIL expand trig intrinsics", [], ) add_pass("hlsl-hca", "HoistConstantArray", "HLSL constant array hoisting", []) add_pass( "hlsl-dxil-preserve-all-outputs", "DxilPreserveAllOutputs", "DXIL write to all outputs in signature", [], ) add_pass("red", "ReducibilityAnalysis", "Reducibility Analysis", []) add_pass( "viewid-state", "ComputeViewIdState", "Compute information related to ViewID", [], ) add_pass( "hlsl-translate-dxil-opcode-version", "DxilTranslateRawBuffer", "Translates one version of dxil to another", [], ) add_pass( "hlsl-dxil-cleanup-addrspacecast", "DxilCleanupAddrSpaceCast", "HLSL DXIL Cleanup Address Space Cast (part of hlsl-dxilfinalize)", [], ) add_pass( "dxil-fix-array-init", "DxilFixConstArrayInitializer", "Dxil Fix Array Initializer", [], ) add_pass( "hlsl-validate-wave-sensitivity", "DxilValidateWaveSensitivity", "HLSL DXIL wave sensitiveity validation", [], ) add_pass( "dxil-elim-vector", "DxilEliminateVector", "Dxil Eliminate Vectors", [] ) add_pass( "dxil-rewrite-output-arg-debug-info", "DxilRewriteOutputArgDebugInfo", "Dxil Rewrite Output Arg Debug Info", [], ) add_pass( "dxil-finalize-preserves", "DxilFinalizePreserves", "Dxil Finalize Preserves", [], ) add_pass("dxil-reinsert-nops", "DxilReinsertNops", "Dxil Reinsert Nops", []) add_pass( "dxil-insert-preserves", "DxilInsertPreserves", "Dxil Insert Noops", [ {"n": "AllowPreserves", "t": "bool", "c": 1}, ], ) add_pass( "dxil-preserves-to-select", "DxilPreserveToSelect", "Dxil Preserves To Select", [], ) add_pass("dxil-delete-loop", "DxilLoopDeletion", "Dxil Loop Deletion", []) add_pass("dxil-value-cache", "DxilValueCache", "Dxil Value Cache", []) add_pass( "hlsl-cleanup-dxbreak", "CleanupDxBreak", "HLSL Remove unnecessary dx.break conditions", [], ) add_pass( "dxil-rename-resources", "DxilRenameResources", "Rename resources to prevent merge by name during linking", [ { "n": "prefix", "i": "Prefix", "t": "string", "d": "Prefix to add to resource names", }, { "n": "from-binding", "i": "FromBinding", "t": "bool", "c": 1, "d": "Append binding to name when bound", }, { "n": "keep-name", "i": "KeepName", "t": "bool", "c": 1, "d": "Keep name when appending binding", }, ], ) add_pass( "hlsl-dxil-resources-to-handle", "DxilMutateResourceToHandle", "Mutate resource to handle", [], ) category_lib = "llvm" add_pass( "ipsccp", "IPSCCP", "Interprocedural Sparse Conditional Constant Propagation", [], ) add_pass("globalopt", "GlobalOpt", "Global Variable Optimizer", []) add_pass("deadargelim", "DAE", "Dead Argument Elimination", []) # Should we get rid of this, or invest in bugpoint support? add_pass( "deadarghaX0r", "DAH", "Dead Argument Hacking (BUGPOINT USE ONLY; DO NOT USE)", [], ) add_pass( "instcombine", "InstructionCombiningPass", "Combine redundant instructions", [ {"n": "NoSink", "t": "bool", "c": 1}, ], ) add_pass("prune-eh", "PruneEH", "Remove unused exception handling info", []) add_pass("functionattrs", "FunctionAttrs", "Deduce function attributes", []) # add_pass('argpromotion', 'ArgPromotion', "Promote 'by reference' arguments to scalars", [ # {'n':'maxElements', 't':'unsigned', 'c':1}]) add_pass( "jump-threading", "JumpThreading", "Jump Threading", [ {"n": "Threshold", "t": "int", "c": 1}, { "n": "jump-threading-threshold", "i": "BBDuplicateThreshold", "t": "unsigned", "d": "Max block size to duplicate for jump threading", }, ], ) add_pass( "correlated-propagation", "CorrelatedValuePropagation", "Value Propagation", [], ) # createTailCallEliminationPass is removed - but is this checked before? add_pass( "reassociate", "Reassociate", "Reassociate expressions", [ {"n": "EnableAggressiveReassociation", "t": "bool", "c": 1}, ], ) add_pass( "loop-rotate", "LoopRotate", "Rotate Loops", [ {"n": "MaxHeaderSize", "t": "int", "c": 1}, { "n": "rotation-max-header-size", "i": "DefaultRotationThreshold", "t": "unsigned", "d": "The default maximum header size for automatic loop rotation", }, ], ) add_pass( "licm", "LICM", "Loop Invariant Code Motion", [ { "n": "disable-licm-promotion", "i": "DisablePromotion", "t": "bool", "d": "Disable memory promotion in LICM pass", } ], ) add_pass( "loop-unswitch", "LoopUnswitch", "Unswitch loops", [ {"n": "Os", "t": "bool", "c": 1, "d": "Optimize for size"}, { "n": "loop-unswitch-threshold", "i": "Threshold", "t": "unsigned", "d": "Max loop size to unswitch", }, ], ) # C:\nobackup\work\HLSLonLLVM\lib\Transforms\IPO\PassManagerBuilder.cpp:353 add_pass("indvars", "IndVarSimplify", "Induction Variable Simplification", []) add_pass("loop-idiom", "LoopIdiomRecognize", "Recognize loop idioms", []) add_pass( "dxil-loop-unroll", "DxilLoopUnroll", "DxilLoopUnroll", [ { "n": "MaxIterationAttempt", "t": "unsigned", "c": 1, "d": "Maximum number of iterations to attempt when iteratively unrolling.", }, { "n": "OnlyWarnOnFail", "t": "bool", "c": 1, "d": "Whether to just warn when unrolling fails.", }, { "n": "StructurizeLoopExits", "t": "bool", "c": 1, "d": "Whether the unroller should try to structurize loop exits first.", }, ], ) add_pass( "dxil-erase-dead-region", "DxilEraseDeadRegion", "DxilEraseDeadRegion", [] ) add_pass( "dxil-remove-dead-blocks", "DxilRemoveDeadBlocks", "DxilRemoveDeadBlocks", [], ) add_pass("dxil-o0-legalize", "DxilNoOptLegalize", "DXIL No-Opt Legalize", []) add_pass( "dxil-o0-simplify-inst", "DxilNoOptSimplifyInstructions", "DXIL No-Opt Simplify Inst", [], ) add_pass( "dxil-loop-deletion", "DxilLoopDeletion", "Dxil Delete dead loops", [ {"n": "NoSink", "t": "bool", "c": 1}, ], ) add_pass("loop-deletion", "LoopDeletion", "Delete dead loops", []) add_pass( "loop-interchange", "LoopInterchange", "Interchanges loops for cache reuse", [], ) add_pass( "loop-unroll", "LoopUnroll", "Unroll loops", [ {"n": "Threshold", "t": "int", "c": 1}, {"n": "Count", "t": "int", "c": 1}, {"n": "AllowPartial", "t": "int", "c": 1}, {"n": "Runtime", "t": "int", "c": 1}, { "n": "unroll-threshold", "i": "UnrollThreshold", "t": "unsigned", "d": "The baseline cost threshold for loop unrolling", }, { "n": "unroll-percent-dynamic-cost-saved-threshold", "i": "UnrollPercentDynamicCostSavedThreshold", "t": "unsigned", "d": "The percentage of estimated dynamic cost which must be saved by unrolling to allow unrolling up to the max threshold.", }, { "n": "unroll-dynamic-cost-savings-discount", "i": "UnrollDynamicCostSavingsDiscount", "t": "unsigned", "d": "This is the amount discounted from the total unroll cost when the unrolled form has a high dynamic cost savings (triggered by the '-unroll-perecent-dynamic-cost-saved-threshold' flag).", }, { "n": "unroll-max-iteration-count-to-analyze", "i": "UnrollMaxIterationsCountToAnalyze", "t": "unsigned", "d": "Don't allow loop unrolling to simulate more than this number of iterations when checking full unroll profitability", }, { "n": "unroll-count", "i": "UnrollCount", "t": "unsigned", "d": "Use this unroll count for all loops including those with unroll_count pragma values, for testing purposes", }, { "n": "unroll-allow-partial", "i": "UnrollAllowPartial", "t": "bool", "d": "Allows loops to be partially unrolled until -unroll-threshold loop size is reached.", }, { "n": "unroll-runtime", "i": "UnrollRuntime", "t": "bool", "d": "Unroll loops with run-time trip counts", }, { "n": "pragma-unroll-threshold", "i": "PragmaUnrollThreshold", "t": "unsigned", "d": "Unrolled size limit for loops with an unroll(full) or unroll_count pragma.", }, { "n": "StructurizeLoopExits", "t": "bool", "c": 1, "d": "Whether the unroller should try to structurize loop exits first.", }, ], ) add_pass("mldst-motion", "MergedLoadStoreMotion", "MergedLoadStoreMotion", []) add_pass( "gvn", "GVN", "Global Value Numbering", [ {"n": "noloads", "t": "bool", "c": 1}, {"n": "enable-pre", "i": "EnablePRE", "t": "bool"}, {"n": "enable-load-pre", "i": "EnableLoadPRE", "t": "bool"}, { "n": "max-recurse-depth", "i": "MaxRecurseDepth", "t": "uint32_t", "d": "Max recurse depth", }, ], ) add_pass("sccp", "SCCP", "Sparse Conditional Constant Propagation", []) add_pass("bdce", "BDCE", "Bit-Tracking Dead Code Elimination", []) add_pass("dse", "DSE", "Dead Store Elimination", []) add_pass( "loop-reroll", "LoopReroll", "Reroll loops", [ { "n": "max-reroll-increment", "i": "MaxInc", "t": "unsigned", "d": "The maximum increment for loop rerolling", }, { "n": "reroll-num-tolerated-failed-matches", "i": "NumToleratedFailedMatches", "t": "unsigned", "d": "The maximum number of failures to tolerate during fuzzy matching.", }, ], ) add_pass("load-combine", "LoadCombine", "Combine Adjacent Loads", []) add_pass("adce", "ADCE", "Aggressive Dead Code Elimination", []) add_pass( "float2int", "Float2Int", "Float to int", [ { "n": "float2int-max-integer-bw", "i": "MaxIntegerBW", "t": "unsigned", "d": "Max integer bitwidth to consider in float2int", } ], ) add_pass( "loop-distribute", "LoopDistribute", "Loop Distribition", [ { "n": "loop-distribute-verify", "i": "LDistVerify", "t": "bool", "d": "Turn on DominatorTree and LoopInfo verification after Loop Distribution", }, { "n": "loop-distribute-non-if-convertible", "i": "DistributeNonIfConvertible", "t": "bool", "d": "Whether to distribute into a loop that may not be if-convertible by the loop vectorizer", }, ], ) add_pass( "alignment-from-assumptions", "AlignmentFromAssumptions", "Alignment from assumptions", [], ) add_pass( "strip-dead-prototypes", "StripDeadPrototypesPass", "Strip Unused Function Prototypes", [], ) add_pass( "elim-avail-extern", "EliminateAvailableExternally", "Eliminate Available Externally Globals", [], ) add_pass("constmerge", "ConstantMerge", "Merge Duplicate Global Constants", []) add_pass( "lowerbitsets", "LowerBitSets", "Lower bitset metadata", [ { "n": "lowerbitsets-avoid-reuse", "i": "AvoidReuse", "t": "bool", "d": "Try to avoid reuse of byte array addresses using aliases", } ], ) # TODO: turn STATISTICS macros into ETW events # assert no duplicate names self.pass_idx_args = set() p_names = set() p_ids = set() for ap in p: assert ap.name not in p_names p_names.add(ap.name) for anarg in ap.args: assert ( anarg.is_ctor_param or anarg.name not in p_ids ), "argument %s in %s is not ctor and is duplicate" % ( anarg.name, ap.name, ) if not anarg.is_ctor_param: p_ids.add(anarg.name) self.pass_idx_args.add(anarg.name) def build_semantics(self): SemanticKind = db_dxil_enum( "SemanticKind", "Semantic kind; Arbitrary or specific system value.", [ (0, "Arbitrary", ""), (1, "VertexID", ""), (2, "InstanceID", ""), (3, "Position", ""), (4, "RenderTargetArrayIndex", ""), (5, "ViewPortArrayIndex", ""), (6, "ClipDistance", ""), (7, "CullDistance", ""), (8, "OutputControlPointID", ""), (9, "DomainLocation", ""), (10, "PrimitiveID", ""), (11, "GSInstanceID", ""), (12, "SampleIndex", ""), (13, "IsFrontFace", ""), (14, "Coverage", ""), (15, "InnerCoverage", ""), (16, "Target", ""), (17, "Depth", ""), (18, "DepthLessEqual", ""), (19, "DepthGreaterEqual", ""), (20, "StencilRef", ""), (21, "DispatchThreadID", ""), (22, "GroupID", ""), (23, "GroupIndex", ""), (24, "GroupThreadID", ""), (25, "TessFactor", ""), (26, "InsideTessFactor", ""), (27, "ViewID", ""), (28, "Barycentrics", ""), (29, "ShadingRate", ""), (30, "CullPrimitive", ""), (31, "StartVertexLocation", ""), (32, "StartInstanceLocation", ""), (33, "Invalid", ""), ], ) self.enums.append(SemanticKind) SigPointKind = db_dxil_enum( "SigPointKind", "Signature Point is more specific than shader stage or signature as it is unique in both stage and item dimensionality or frequency.", [ (0, "VSIn", "Ordinary Vertex Shader input from Input Assembler"), (1, "VSOut", "Ordinary Vertex Shader output that may feed Rasterizer"), (2, "PCIn", "Patch Constant function non-patch inputs"), (3, "HSIn", "Hull Shader function non-patch inputs"), (4, "HSCPIn", "Hull Shader patch inputs - Control Points"), (5, "HSCPOut", "Hull Shader function output - Control Point"), ( 6, "PCOut", "Patch Constant function output - Patch Constant data passed to Domain Shader", ), ( 7, "DSIn", "Domain Shader regular input - Patch Constant data plus system values", ), (8, "DSCPIn", "Domain Shader patch input - Control Points"), ( 9, "DSOut", "Domain Shader output - vertex data that may feed Rasterizer", ), ( 10, "GSVIn", "Geometry Shader vertex input - qualified with primitive type", ), (11, "GSIn", "Geometry Shader non-vertex inputs (system values)"), ( 12, "GSOut", "Geometry Shader output - vertex data that may feed Rasterizer", ), (13, "PSIn", "Pixel Shader input"), (14, "PSOut", "Pixel Shader output"), (15, "CSIn", "Compute Shader input"), (16, "MSIn", "Mesh Shader input"), (17, "MSOut", "Mesh Shader vertices output"), (18, "MSPOut", "Mesh Shader primitives output"), (19, "ASIn", "Amplification Shader input"), (21, "Invalid", ""), ], ) self.enums.append(SigPointKind) PackingKind = db_dxil_enum( "PackingKind", "Kind of signature point", [ (0, "None", "No packing should be performed"), (1, "InputAssembler", "Vertex Shader input from Input Assembler"), (2, "Vertex", "Vertex that may feed the Rasterizer"), (3, "PatchConstant", "Patch constant signature"), (4, "Target", "Render Target (Pixel Shader Output)"), (5, "Invalid", ""), ], ) Float32DenormMode = db_dxil_enum( "Float32DenormMode", "float32 denorm behavior", [ (0, "Any", "Undefined behavior for denormal numbers"), (1, "Preserve", "Preserve both input and output"), (2, "FTZ", "Preserve denormal inputs. Flush denorm outputs"), (3, "Reserve3", "Reserved Value. Not used for now"), (4, "Reserve4", "Reserved Value. Not used for now"), (5, "Reserve5", "Reserved Value. Not used for now"), (6, "Reserve6", "Reserved Value. Not used for now"), (7, "Reserve7", "Reserved Value. Not used for now"), ], ) self.enums.append(Float32DenormMode) SigPointCSV = """ SigPoint, Related, ShaderKind, PackingKind, SignatureKind VSIn, Invalid, Vertex, InputAssembler, Input VSOut, Invalid, Vertex, Vertex, Output PCIn, HSCPIn, Hull, None, Invalid HSIn, HSCPIn, Hull, None, Invalid HSCPIn, Invalid, Hull, Vertex, Input HSCPOut, Invalid, Hull, Vertex, Output PCOut, Invalid, Hull, PatchConstant, PatchConstOrPrim DSIn, Invalid, Domain, PatchConstant, PatchConstOrPrim DSCPIn, Invalid, Domain, Vertex, Input DSOut, Invalid, Domain, Vertex, Output GSVIn, Invalid, Geometry, Vertex, Input GSIn, GSVIn, Geometry, None, Invalid GSOut, Invalid, Geometry, Vertex, Output PSIn, Invalid, Pixel, Vertex, Input PSOut, Invalid, Pixel, Target, Output CSIn, Invalid, Compute, None, Invalid MSIn, Invalid, Mesh, None, Invalid MSOut, Invalid, Mesh, Vertex, Output MSPOut, Invalid, Mesh, Vertex, PatchConstOrPrim ASIn, Invalid, Amplification, None, Invalid Invalid, Invalid, Invalid, Invalid, Invalid """ table = [ list(map(str.strip, line.split(","))) for line in SigPointCSV.splitlines() if line.strip() ] for row in table[1:]: assert len(row) == len(table[0]) # Ensure table is rectangular # Make sure labels match enums, otherwise the table isn't aligned or in-sync if not ([row[0] for row in table[1:]] == SigPointKind.value_names()): assert False and "SigPointKind does not align with SigPointCSV row labels" self.sigpoint_table = table self.enums.append(PackingKind) SemanticInterpretationKind = db_dxil_enum( "SemanticInterpretationKind", "Defines how a semantic is interpreted at a particular SignaturePoint", [ (0, "NA", "Not Available"), (1, "SV", "Normal System Value"), (2, "SGV", "System Generated Value (sorted last)"), (3, "Arb", "Treated as Arbitrary"), (4, "NotInSig", "Not included in signature (intrinsic access)"), ( 5, "NotPacked", "Included in signature, but does not contribute to packing", ), (6, "Target", "Special handling for SV_Target"), (7, "TessFactor", "Special handling for tessellation factors"), ( 8, "Shadow", "Shadow element must be added to a signature for compatibility", ), ( 8, "ClipCull", "Special packing rules for SV_ClipDistance or SV_CullDistance", ), (9, "Invalid", ""), ], ) self.enums.append(SemanticInterpretationKind) # The following has SampleIndex, Coverage, and InnerCoverage as loaded with instructions rather than from the signature SemanticInterpretationCSV = """ Semantic,VSIn,VSOut,PCIn,HSIn,HSCPIn,HSCPOut,PCOut,DSIn,DSCPIn,DSOut,GSVIn,GSIn,GSOut,PSIn,PSOut,CSIn,MSIn,MSOut,MSPOut,ASIn Arbitrary,Arb,Arb,NA,NA,Arb,Arb,Arb,Arb,Arb,Arb,Arb,NA,Arb,Arb,NA,NA,NA,Arb,Arb,NA VertexID,SV,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA InstanceID,SV,Arb,NA,NA,Arb,Arb,NA,NA,Arb,Arb,Arb,NA,Arb,Arb,NA,NA,NA,NA,NA,NA Position,Arb,SV,NA,NA,SV,SV,Arb,Arb,SV,SV,SV,NA,SV,SV,NA,NA,NA,SV,NA,NA RenderTargetArrayIndex,Arb,SV,NA,NA,SV,SV,Arb,Arb,SV,SV,SV,NA,SV,SV,NA,NA,NA,NA,SV,NA ViewPortArrayIndex,Arb,SV,NA,NA,SV,SV,Arb,Arb,SV,SV,SV,NA,SV,SV,NA,NA,NA,NA,SV,NA ClipDistance,Arb,ClipCull,NA,NA,ClipCull,ClipCull,Arb,Arb,ClipCull,ClipCull,ClipCull,NA,ClipCull,ClipCull,NA,NA,NA,ClipCull,NA,NA CullDistance,Arb,ClipCull,NA,NA,ClipCull,ClipCull,Arb,Arb,ClipCull,ClipCull,ClipCull,NA,ClipCull,ClipCull,NA,NA,NA,ClipCull,NA,NA OutputControlPointID,NA,NA,NA,NotInSig,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA DomainLocation,NA,NA,NA,NA,NA,NA,NA,NotInSig,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA PrimitiveID,NA,NA,NotInSig,NotInSig,NA,NA,NA,NotInSig,NA,NA,NA,Shadow,SGV,SGV,NA,NA,NA,NA,SV,NA GSInstanceID,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NotInSig,NA,NA,NA,NA,NA,NA,NA,NA SampleIndex,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,Shadow _41,NA,NA,NA,NA,NA,NA IsFrontFace,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,SGV,SGV,NA,NA,NA,NA,NA,NA Coverage,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NotInSig _50,NotPacked _41,NA,NA,NA,NA,NA InnerCoverage,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NotInSig _50,NA,NA,NA,NA,NA,NA Target,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,Target,NA,NA,NA,NA,NA Depth,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NotPacked,NA,NA,NA,NA,NA DepthLessEqual,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NotPacked _50,NA,NA,NA,NA,NA DepthGreaterEqual,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NotPacked _50,NA,NA,NA,NA,NA StencilRef,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NotPacked _50,NA,NA,NA,NA,NA DispatchThreadID,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NotInSig,NotInSig,NA,NA,NotInSig GroupID,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NotInSig,NotInSig,NA,NA,NotInSig GroupIndex,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NotInSig,NotInSig,NA,NA,NotInSig GroupThreadID,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NotInSig,NotInSig,NA,NA,NotInSig TessFactor,NA,NA,NA,NA,NA,NA,TessFactor,TessFactor,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA InsideTessFactor,NA,NA,NA,NA,NA,NA,TessFactor,TessFactor,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA ViewID,NotInSig _61,NA,NotInSig _61,NotInSig _61,NA,NA,NA,NotInSig _61,NA,NA,NA,NotInSig _61,NA,NotInSig _61,NA,NA,NotInSig,NA,NA,NA Barycentrics,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NotPacked _61,NA,NA,NA,NA,NA,NA ShadingRate,NA,SV _64,NA,NA,SV _64,SV _64,NA,NA,SV _64,SV _64,SV _64,NA,SV _64,SV _64,NA,NA,NA,NA,SV,NA CullPrimitive,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NotInSig,NA,NA,NA,NA,NotPacked,NA StartVertexLocation,NotInSig _68,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA StartInstanceLocation,NotInSig _68,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA,NA """ table = [ list(map(str.strip, line.split(","))) for line in SemanticInterpretationCSV.splitlines() if line.strip() ] for row in table[1:]: assert len(row) == len(table[0]) # Ensure table is rectangular # Make sure labels match enums, otherwise the table isn't aligned or in-sync assert table[0][1:] == SigPointKind.value_names()[:-1] # exclude Invalid if not ( [row[0] for row in table[1:]] == SemanticKind.value_names()[:-1] ): # exclude Invalid assert ( False and "SemanticKind does not align with SemanticInterpretationCSV row labels" ) self.interpretation_table = table def build_valrules(self): self.add_valrule_msg( "Bitcode.Valid", "Module must be bitcode-valid", "Module bitcode is invalid.", ) self.add_valrule_msg( "Container.PartMatches", "DXIL Container Parts must match Module", "Container part '%0' does not match expected for module.", ) self.add_valrule_msg( "Container.PartRepeated", "DXIL Container must have only one of each part type", "More than one container part '%0'.", ) self.add_valrule_msg( "Container.PartMissing", "DXIL Container requires certain parts, corresponding to module", "Missing part '%0' required by module.", ) self.add_valrule_msg( "Container.PartInvalid", "DXIL Container must not contain unknown parts", "Unknown part '%0' found in DXIL container.", ) self.add_valrule_msg( "Container.RootSignatureIncompatible", "Root Signature in DXIL Container must be compatible with shader", "Root Signature in DXIL container is not compatible with shader.", ) self.add_valrule("Meta.Required", "Required metadata missing.") self.add_valrule_msg( "Meta.ComputeWithNode", "Compute entry must not have node metadata", "Compute entry '%0' has unexpected node shader metadata", ) self.add_valrule_msg( "Meta.Known", "Named metadata should be known", "Named metadata '%0' is unknown.", ) self.add_valrule("Meta.Used", "All metadata must be used by dxil.") self.add_valrule_msg( "Meta.Target", "Target triple must be 'dxil-ms-dx'", "Unknown target triple '%0'.", ) self.add_valrule( "Meta.WellFormed", "Metadata must be well-formed in operand count and types.", ) # TODO: add string arg for what metadata is malformed (this is emitted from a lot of places and provides no context whatsoever) self.add_valrule_msg( "Meta.VersionSupported", "Version in metadata must be supported.", "%0 version in metadata (%1.%2) is not supported; maximum: (%3.%4).", ) self.add_valrule( "Meta.SemanticLen", "Semantic length must be at least 1 and at most 64." ) self.add_valrule_msg( "Meta.InterpModeValid", "Interpolation mode must be valid", "Invalid interpolation mode for '%0'.", ) self.add_valrule_msg( "Meta.SemaKindValid", "Semantic kind must be valid", "Semantic kind for '%0' is invalid.", ) self.add_valrule_msg( "Meta.NoSemanticOverlap", "Semantics must not overlap", "Semantic '%0' overlap at %1.", ) self.add_valrule_msg( "Meta.SemaKindMatchesName", "Semantic name must match system value, when defined.", "Semantic name %0 does not match System Value kind %1.", ) self.add_valrule_msg( "Meta.DuplicateSysValue", "System value may only appear once in signature", "System value %0 appears more than once in the same signature.", ) self.add_valrule_msg( "Meta.SemanticIndexMax", "System value semantics have a maximum valid semantic index", "%0 semantic index exceeds maximum (%1).", ) self.add_valrule_msg( "Meta.SystemValueRows", "System value may only have 1 row", "rows for system value semantic %0 must be 1.", ) self.add_valrule_msg( "Meta.SemanticShouldBeAllocated", "Semantic should have a valid packing location", "%0 Semantic '%1' should have a valid packing location.", ) self.add_valrule_msg( "Meta.SemanticShouldNotBeAllocated", "Semantic should have a packing location of -1", "%0 Semantic '%1' should have a packing location of -1.", ) self.add_valrule("Meta.ValueRange", "Metadata value must be within range.") self.add_valrule("Meta.FlagsUsage", "Flags must match usage.") self.add_valrule( "Meta.DenseResIDs", "Resource identifiers must be zero-based and dense." ) self.add_valrule_msg( "Meta.SignatureOverlap", "Signature elements may not overlap in packing location.", "signature element %0 at location (%1,%2) size (%3,%4) overlaps another signature element.", ) self.add_valrule_msg( "Meta.SignatureOutOfRange", "Signature elements must fit within maximum signature size", "signature element %0 at location (%1,%2) size (%3,%4) is out of range.", ) self.add_valrule_msg( "Meta.SignatureIndexConflict", "Only elements with compatible indexing rules may be packed together", "signature element %0 at location (%1,%2) size (%3,%4) has an indexing conflict with another signature element packed into the same row.", ) self.add_valrule_msg( "Meta.SignatureIllegalComponentOrder", "Component ordering for packed elements must be: arbitrary < system value < system generated value", "signature element %0 at location (%1,%2) size (%3,%4) violates component ordering rule (arb < sv < sgv).", ) self.add_valrule_msg( "Meta.SignatureDataWidth", "Data width must be identical for all elements packed into the same row.", "signature element %0 at location (%1, %2) size (%3, %4) has data width that differs from another element packed into the same row.", ) self.add_valrule_msg( "Meta.IntegerInterpMode", "Interpolation mode on integer must be Constant", "signature element %0 specifies invalid interpolation mode for integer component type.", ) self.add_valrule_msg( "Meta.InterpModeInOneRow", "Interpolation mode must be identical for all elements packed into the same row.", "signature element %0 at location (%1,%2) size (%3,%4) has interpolation mode that differs from another element packed into the same row.", ) self.add_valrule("Meta.SemanticCompType", "%0 must be %1.") self.add_valrule_msg( "Meta.ClipCullMaxRows", "Combined elements of SV_ClipDistance and SV_CullDistance must fit in two rows.", "ClipDistance and CullDistance occupy more than the maximum of 2 rows combined.", ) self.add_valrule_msg( "Meta.ClipCullMaxComponents", "Combined elements of SV_ClipDistance and SV_CullDistance must fit in 8 components", "ClipDistance and CullDistance use more than the maximum of 8 components combined.", ) self.add_valrule( "Meta.SignatureCompType", "signature %0 specifies unrecognized or invalid component type.", ) self.add_valrule( "Meta.TessellatorPartition", "Invalid Tessellator Partitioning specified. Must be integer, pow2, fractional_odd or fractional_even.", ) self.add_valrule( "Meta.TessellatorOutputPrimitive", "Invalid Tessellator Output Primitive specified. Must be point, line, triangleCW or triangleCCW.", ) self.add_valrule( "Meta.MaxTessFactor", "Hull Shader MaxTessFactor must be [%0..%1]. %2 specified.", ) self.add_valrule("Meta.ValidSamplerMode", "Invalid sampler mode on sampler .") self.add_valrule( "Meta.GlcNotOnAppendConsume", "globallycoherent cannot be used with append/consume buffers: '%0'.", ) self.add_valrule_msg( "Meta.StructBufAlignment", "StructuredBuffer stride not aligned", "structured buffer element size must be a multiple of %0 bytes (actual size %1 bytes).", ) self.add_valrule_msg( "Meta.StructBufAlignmentOutOfBound", "StructuredBuffer stride out of bounds", "structured buffer elements cannot be larger than %0 bytes (actual size %1 bytes).", ) self.add_valrule("Meta.EntryFunction", "entrypoint not found.") self.add_valrule("Meta.InvalidControlFlowHint", "Invalid control flow hint.") self.add_valrule( "Meta.BranchFlatten", "Can't use branch and flatten attributes together." ) self.add_valrule( "Meta.ForceCaseOnSwitch", "Attribute forcecase only works for switch." ) self.add_valrule( "Meta.ControlFlowHintNotOnControlFlow", "Control flow hint only works on control flow inst.", ) self.add_valrule( "Meta.TextureType", "elements of typed buffers and textures must fit in four 32-bit quantities.", ) self.add_valrule( "Meta.BarycentricsInterpolation", "SV_Barycentrics cannot be used with 'nointerpolation' type.", ) self.add_valrule( "Meta.BarycentricsFloat3", "only 'float3' type is allowed for SV_Barycentrics.", ) self.add_valrule( "Meta.BarycentricsTwoPerspectives", "There can only be up to two input attributes of SV_Barycentrics with different perspective interpolation mode.", ) self.add_valrule( "Meta.NoEntryPropsForEntry", "Entry point %0 must have entry properties." ) self.add_valrule("Instr.Oload", "DXIL intrinsic overload must be valid.") self.add_valrule_msg( "Instr.CallOload", "Call to DXIL intrinsic must match overload signature", "Call to DXIL intrinsic '%0' does not match an allowed overload signature.", ) self.add_valrule( "Instr.PtrBitCast", "Pointer type bitcast must be have same size." ) self.add_valrule( "Instr.MinPrecisonBitCast", "Bitcast on minprecison types is not allowed." ) self.add_valrule( "Instr.StructBitCast", "Bitcast on struct types is not allowed." ) self.add_valrule( "Instr.Status", "Resource status should only be used by CheckAccessFullyMapped.", ) self.add_valrule( "Instr.CheckAccessFullyMapped", "CheckAccessFullyMapped should only be used on resource status.", ) self.add_valrule_msg( "Instr.OpConst", "DXIL intrinsic requires an immediate constant operand", "%0 of %1 must be an immediate constant.", ) self.add_valrule("Instr.Allowed", "Instructions must be of an allowed type.") self.add_valrule( "Instr.OpCodeReserved", "Instructions must not reference reserved opcodes." ) self.add_valrule_msg( "Instr.OperandRange", "DXIL intrinsic operand must be within defined range", "expect %0 between %1, got %2.", ) self.add_valrule( "Instr.NoReadingUninitialized", "Instructions should not read uninitialized value.", ) self.add_valrule( "Instr.NoGenericPtrAddrSpaceCast", "Address space cast between pointer types must have one part to be generic address space.", ) self.add_valrule( "Instr.InBoundsAccess", "Access to out-of-bounds memory is disallowed." ) self.add_valrule( "Instr.OpConstRange", "Constant values must be in-range for operation." ) self.add_valrule( "Instr.ImmBiasForSampleB", "bias amount for sample_b must be in the range [%0,%1], but %2 was specified as an immediate.", ) self.add_valrule( "Instr.IllegalDXILOpCode", "DXILOpCode must be [0..%0]. %1 specified." ) self.add_valrule( "Instr.IllegalDXILOpFunction", "'%0' is not a DXILOpFuncition for DXILOpcode '%1'.", ) # If streams have not been declared, you must use cut instead of cut_stream in GS - is there an equivalent rule here? # Need to clean up all error messages and actually implement. # Midlevel self.add_valrule("Instr.NoIndefiniteLog", "No indefinite logarithm.") self.add_valrule("Instr.NoIndefiniteAsin", "No indefinite arcsine.") self.add_valrule("Instr.NoIndefiniteAcos", "No indefinite arccosine.") self.add_valrule("Instr.NoIDivByZero", "No signed integer division by zero.") self.add_valrule("Instr.NoUDivByZero", "No unsigned integer division by zero.") self.add_valrule( "Instr.NoIndefiniteDsxy", "No indefinite derivative calculation." ) self.add_valrule( "Instr.MinPrecisionNotPrecise", "Instructions marked precise may not refer to minprecision values.", ) # Backend self.add_valrule( "Instr.OnlyOneAllocConsume", "RWStructuredBuffers may increment or decrement their counters, but not both.", ) # CCompiler self.add_valrule( "Instr.TextureOffset", "offset texture instructions must take offset which can resolve to integer literal in the range -8 to 7.", ) # D3D12 self.add_valrule_msg( "Instr.CannotPullPosition", "pull-model evaluation of position disallowed", "%0 does not support pull-model evaluation of position.", ) # self.add_valrule("Instr.ERR_GUARANTEED_RACE_CONDITION_UAV", "TODO - race condition writing to shared resource detected, consider making this write conditional.") warning on fxc. # self.add_valrule("Instr.ERR_GUARANTEED_RACE_CONDITION_GSM", "TODO - race condition writing to shared memory detected, consider making this write conditional.") warning on fxc. # self.add_valrule("Instr.ERR_INFINITE_LOOP", "TODO - ERR_INFINITE_LOOP") fxc will report error if it can prove the loop is infinite. self.add_valrule( "Instr.EvalInterpolationMode", "Interpolation mode on %0 used with eval_* instruction must be linear, linear_centroid, linear_noperspective, linear_noperspective_centroid, linear_sample or linear_noperspective_sample.", ) self.add_valrule("Instr.ResourceCoordinateMiss", "coord uninitialized.") self.add_valrule( "Instr.ResourceCoordinateTooMany", "out of bound coord must be undef." ) self.add_valrule("Instr.ResourceOffsetMiss", "offset uninitialized.") self.add_valrule( "Instr.ResourceOffsetTooMany", "out of bound offset must be undef." ) self.add_valrule( "Instr.UndefResultForGetDimension", "GetDimensions used undef dimension %0 on %1.", ) self.add_valrule( "Instr.SamplerModeForLOD", "lod instruction requires sampler declared in default mode.", ) self.add_valrule( "Instr.SamplerModeForSample", "sample/_l/_d/_cl_s/gather instruction requires sampler declared in default mode.", ) self.add_valrule( "Instr.SamplerModeForSampleC", "sample_c_*/gather_c instructions require sampler declared in comparison mode.", ) self.add_valrule( "Instr.SampleCompType", "sample_* instructions require resource to be declared to return UNORM, SNORM or FLOAT.", ) self.add_valrule( "Instr.BarrierModeUselessUGroup", "sync can't specify both _ugroup and _uglobal. If both are needed, just specify _uglobal.", ) self.add_valrule( "Instr.BarrierModeNoMemory", "sync must include some form of memory barrier - _u (UAV) and/or _g (Thread Group Shared Memory). Only _t (thread group sync) is optional.", ) self.add_valrule( "Instr.BarrierModeForNonCS", "sync in a non-Compute/Amplification/Mesh/Node Shader must only sync UAV (sync_uglobal).", ) self.add_valrule( "Instr.BarrierFlagInvalid", "Invalid %0 flags on DXIL operation '%1'" ) self.add_valrule( "Instr.BarrierNonConstantFlagArgument", "Memory type, access, or sync flag is not constant", ) self.add_valrule( "Instr.BarrierRequiresNode", "sync in a non-Node Shader must not sync node record memory.", ) self.add_valrule( "Instr.WriteMaskForTypedUAVStore", "store on typed uav must write to all four components of the UAV.", ) self.add_valrule( "Instr.WriteMaskGapForUAV", "UAV write mask must be contiguous, starting at x: .x, .xy, .xyz, or .xyzw.", ) self.add_valrule( "Instr.ResourceKindForCalcLOD", "lod requires resource declared as texture1D/2D/3D/Cube/CubeArray/1DArray/2DArray.", ) self.add_valrule( "Instr.ResourceKindForSample", "sample/_l/_d requires resource declared as texture1D/2D/3D/Cube/1DArray/2DArray/CubeArray.", ) self.add_valrule( "Instr.ResourceKindForSampleC", "samplec requires resource declared as texture1D/2D/Cube/1DArray/2DArray/CubeArray.", ) self.add_valrule( "Instr.ResourceKindForGather", "gather requires resource declared as texture/2D/Cube/2DArray/CubeArray.", ) self.add_valrule( "Instr.WriteMaskMatchValueForUAVStore", "uav store write mask must match store value mask, write mask is %0 and store value mask is %1.", ) self.add_valrule( "Instr.UndefinedValueForUAVStore", "Assignment of undefined values to UAV." ) self.add_valrule( "Instr.ResourceKindForBufferLoadStore", "buffer load/store only works on Raw/Typed/StructuredBuffer.", ) self.add_valrule( "Instr.ResourceKindForTextureStore", "texture store only works on Texture1D/1DArray/2D/2DArray/3D.", ) self.add_valrule( "Instr.ResourceKindForGetDim", "Invalid resource kind on GetDimensions." ) self.add_valrule( "Instr.ResourceKindForTextureLoad", "texture load only works on Texture1D/1DArray/2D/2DArray/3D/MS2D/MS2DArray.", ) self.add_valrule( "Instr.ResourceClassForSamplerGather", "sample, lod and gather should be on srv resource.", ) self.add_valrule( "Instr.ResourceClassForUAVStore", "store should be on uav resource." ) self.add_valrule( "Instr.ResourceClassForLoad", "load can only run on UAV/SRV resource." ) self.add_valrule( "Instr.ResourceMapToSingleEntry", "Fail to map resource to resource table." ) self.add_valrule( "Instr.ResourceUser", "Resource should only be used by Load/GEP/Call." ) self.add_valrule( "Instr.ResourceKindForTraceRay", "TraceRay should only use RTAccelerationStructure.", ) self.add_valrule("Instr.OffsetOnUAVLoad", "uav load don't support offset.") self.add_valrule( "Instr.MipOnUAVLoad", "uav load don't support mipLevel/sampleIndex." ) self.add_valrule( "Instr.SampleIndexForLoad2DMS", "load on Texture2DMS/2DMSArray require sampleIndex.", ) self.add_valrule( "Instr.CoordinateCountForRawTypedBuf", "raw/typed buffer don't need 2 coordinates.", ) self.add_valrule( "Instr.CoordinateCountForStructBuf", "structured buffer require 2 coordinates.", ) self.add_valrule( "Instr.MipLevelForGetDimension", "Use mip level on buffer when GetDimensions.", ) self.add_valrule( "Instr.DxilStructUser", "Dxil struct types should only be used by ExtractValue.", ) self.add_valrule( "Instr.DxilStructUserOutOfBound", "Index out of bound when extract value from dxil struct types.", ) self.add_valrule( "Instr.HandleNotFromCreateHandle", "Resource handle should returned by createHandle.", ) self.add_valrule( "Instr.BufferUpdateCounterOnUAV", "BufferUpdateCounter valid only on UAV." ) self.add_valrule( "Instr.BufferUpdateCounterOnResHasCounter", "BufferUpdateCounter valid only when HasCounter is true.", ) self.add_valrule("Instr.CBufferOutOfBound", "Cbuffer access out of bound.") self.add_valrule( "Instr.CBufferClassForCBufferHandle", "Expect Cbuffer for CBufferLoad handle.", ) self.add_valrule( "Instr.FailToResloveTGSMPointer", "TGSM pointers must originate from an unambiguous TGSM global variable.", ) self.add_valrule( "Instr.ExtractValue", "ExtractValue should only be used on dxil struct types and cmpxchg.", ) self.add_valrule( "Instr.TGSMRaceCond", "Race condition writing to shared memory detected, consider making this write conditional.", ) self.add_valrule( "Instr.AttributeAtVertexNoInterpolation", "Attribute %0 must have nointerpolation mode in order to use GetAttributeAtVertex function.", ) self.add_valrule( "Instr.CreateHandleImmRangeID", "Local resource must map to global resource.", ) self.add_valrule( "Instr.SignatureOperationNotInEntry", "Dxil operation for input output signature must be in entryPoints.", ) self.add_valrule( "Instr.MultipleSetMeshOutputCounts", "SetMeshOUtputCounts cannot be called multiple times.", ) self.add_valrule( "Instr.MissingSetMeshOutputCounts", "Missing SetMeshOutputCounts call." ) self.add_valrule( "Instr.NonDominatingSetMeshOutputCounts", "Non-Dominating SetMeshOutputCounts call.", ) self.add_valrule( "Instr.MultipleGetMeshPayload", "GetMeshPayload cannot be called multiple times.", ) self.add_valrule( "Instr.NotOnceDispatchMesh", "DispatchMesh must be called exactly once in an Amplification shader.", ) self.add_valrule( "Instr.NonDominatingDispatchMesh", "Non-Dominating DispatchMesh call." ) self.add_valrule( "Instr.AtomicOpNonGroupsharedOrRecord", "Non-groupshared or node record destination to atomic operation.", ) self.add_valrule( "Instr.AtomicIntrinNonUAV", "Non-UAV destination to atomic intrinsic." ) self.add_valrule_msg( "Instr.SVConflictingLaunchMode", "Input system values are compatible with node shader launch mode.", "Call to DXIL intrinsic %0 (%1) is not allowed in node shader launch type %2", ) self.add_valrule("Instr.AtomicConst", "Constant destination to atomic.") # Work-Graphs self.add_valrule( "Instr.NodeRecordHandleUseAfterComplete", "Invalid use of completed record handle.", ) # Some legacy rules: # - space is only supported for shader targets 5.1 and higher # - multiple rules regarding derivatives, which isn't a supported feature for DXIL # - multiple rules regarding library functions, which isn't a supported feature for DXIL (at this time) # - multiple rules regarding interfaces, which isn't a supported feature for DXIL # - rules for DX9-style intrinsics, which aren't supported for DXIL self.add_valrule_msg( "Types.NoVector", "Vector types must not be present", "Vector type '%0' is not allowed.", ) self.add_valrule_msg( "Types.Defined", "Type must be defined based on DXIL primitives", "Type '%0' is not defined on DXIL primitives.", ) self.add_valrule_msg( "Types.IntWidth", "Int type must be of valid width", "Int type '%0' has an invalid width.", ) self.add_valrule( "Types.NoMultiDim", "Only one dimension allowed for array type." ) self.add_valrule( "Types.NoPtrToPtr", "Pointers to pointers, or pointers in structures are not allowed.", ) self.add_valrule( "Types.I8", "I8 can only be used as immediate value for intrinsic or as i8* via bitcast by lifetime intrinsics.", ) self.add_valrule_msg( "Sm.Name", "Target shader model name must be known", "Unknown shader model '%0'.", ) self.add_valrule_msg( "Sm.DxilVersion", "Target shader model requires specific Dxil Version", "Shader model requires Dxil Version %0.%1.", ) self.add_valrule_msg( "Sm.Opcode", "Opcode must be defined in target shader model", "Opcode %0 not valid in shader model %1.", ) self.add_valrule( "Sm.Operand", "Operand must be defined in target shader model." ) self.add_valrule_msg( "Sm.Semantic", "Semantic must be defined in target shader model", "Semantic '%0' is invalid as %1 %2.", ) self.add_valrule_msg( "Sm.NoInterpMode", "Interpolation mode must be undefined for VS input/PS output/patch constant.", "Interpolation mode for '%0' is set but should be undefined.", ) self.add_valrule_msg( "Sm.ConstantInterpMode", "Interpolation mode must be constant for MS primitive output.", "Interpolation mode for '%0' should be constant.", ) self.add_valrule( "Sm.NoPSOutputIdx", "Pixel shader output registers are not indexable." ) # TODO restrict to PS self.add_valrule( "Sm.PSConsistentInterp", "Interpolation mode for PS input position must be linear_noperspective_centroid or linear_noperspective_sample when outputting oDepthGE or oDepthLE and not running at sample frequency (which is forced by inputting SV_SampleIndex or declaring an input linear_sample or linear_noperspective_sample).", ) self.add_valrule( "Sm.ThreadGroupChannelRange", "Declared Thread Group %0 size %1 outside valid range [%2..%3].", ) self.add_valrule( "Sm.MaxTheadGroup", "Declared Thread Group Count %0 (X*Y*Z) is beyond the valid maximum of %1.", ) self.add_valrule( "Sm.MaxTGSMSize", "Total Thread Group Shared Memory storage is %0, exceeded %1.", ) self.add_valrule( "Sm.TGSMUnsupported", "Thread Group Shared Memory not supported %0." ) self.add_valrule_msg( "Sm.WaveSizeValue", "WaveSize value must be a power of 2 in range [4..128]", "WaveSize %0 (%1) outside valid range [%2..%3], or not a power of 2.", ) self.add_valrule_msg( "Sm.WaveSizeAllZeroWhenUndefined", "WaveSize Max and Preferred must be 0 when Min is 0", "WaveSize Max (%0) and Preferred (%1) must be 0 when Min is 0", ) self.add_valrule_msg( "Sm.WaveSizeMaxAndPreferredZeroWhenNoRange", "WaveSize Max and Preferred must be 0 to encode min==max", "WaveSize Max (%0) and Preferred (%1) must be 0 to encode min==max", ) self.add_valrule_msg( "Sm.WaveSizeMaxGreaterThanMin", "WaveSize Max must greater than Min", "WaveSize Max (%0) is less than Min (%1)", ) self.add_valrule_msg( "Sm.WaveSizePreferredInRange", "WaveSize Preferred must be within Min..Max range", "WaveSize Preferred (%0) outside Min..Max range [%1..%2]", ) self.add_valrule( "Sm.WaveSizeOnComputeOrNode", "WaveSize only allowed on compute or node shaders", ) self.add_valrule( "Sm.WaveSizeNeedsSM66or67", "WaveSize is valid only for Shader Model 6.6 and 6.7.", ) self.add_valrule( "Sm.WaveSizeRangeNeedsSM68Plus", "WaveSize Range is valid only for Shader Model 6.8 and higher.", ) self.add_valrule( "Sm.WaveSizeRangeExpectsThreeParams", "WaveSize Range tag expects exactly 3 parameters.", ) self.add_valrule( "Sm.WaveSizeExpectsOneParam", "WaveSize tag expects exactly 1 parameter.", ) self.add_valrule( "Sm.WaveSizeTagDuplicate", "WaveSize or WaveSizeRange tag may only appear once per entry point.", ) self.add_valrule( "Sm.WaveSizeNeedsConstantOperands", "WaveSize metadata operands must be constant values.", ) self.add_valrule( "Sm.ROVOnlyInPS", "RasterizerOrdered objects are only allowed in 5.0+ pixel shaders.", ) self.add_valrule( "Sm.TessFactorForDomain", "Required TessFactor for domain not found declared anywhere in Patch Constant data.", ) self.add_valrule( "Sm.TessFactorSizeMatchDomain", "TessFactor rows, columns (%0, %1) invalid for domain %2. Expected %3 rows and 1 column.", ) self.add_valrule( "Sm.InsideTessFactorSizeMatchDomain", "InsideTessFactor rows, columns (%0, %1) invalid for domain %2. Expected %3 rows and 1 column.", ) self.add_valrule( "Sm.DomainLocationIdxOOB", "DomainLocation component index out of bounds for the domain.", ) self.add_valrule( "Sm.HullPassThruControlPointCountMatch", "For pass thru hull shader, input control point count must match output control point count", ) self.add_valrule( "Sm.OutputControlPointsTotalScalars", "Total number of scalars across all HS output control points must not exceed .", ) self.add_valrule( "Sm.IsoLineOutputPrimitiveMismatch", "Hull Shader declared with IsoLine Domain must specify output primitive point or line. Triangle_cw or triangle_ccw output are not compatible with the IsoLine Domain.", ) self.add_valrule( "Sm.TriOutputPrimitiveMismatch", "Hull Shader declared with Tri Domain must specify output primitive point, triangle_cw or triangle_ccw. Line output is not compatible with the Tri domain.", ) self.add_valrule( "Sm.ValidDomain", "Invalid Tessellator Domain specified. Must be isoline, tri or quad.", ) self.add_valrule( "Sm.PatchConstantOnlyForHSDS", "patch constant signature only valid in HS and DS.", ) self.add_valrule( "Sm.StreamIndexRange", "Stream index (%0) must between 0 and %1." ) self.add_valrule( "Sm.PSOutputSemantic", "Pixel Shader allows output semantics to be SV_Target, SV_Depth, SV_DepthGreaterEqual, SV_DepthLessEqual, SV_Coverage or SV_StencilRef, %0 found.", ) self.add_valrule( "Sm.PSMultipleDepthSemantic", "Pixel Shader only allows one type of depth semantic to be declared.", ) self.add_valrule( "Sm.PSTargetIndexMatchesRow", "SV_Target semantic index must match packed row location.", ) self.add_valrule( "Sm.PSTargetCol0", "SV_Target packed location must start at column 0." ) self.add_valrule( "Sm.PSCoverageAndInnerCoverage", "InnerCoverage and Coverage are mutually exclusive.", ) self.add_valrule( "Sm.GSOutputVertexCountRange", "GS output vertex count must be [0..%0]. %1 specified.", ) self.add_valrule( "Sm.GSInstanceCountRange", "GS instance count must be [1..%0]. %1 specified.", ) self.add_valrule( "Sm.DSInputControlPointCountRange", "DS input control point count must be [0..%0]. %1 specified.", ) self.add_valrule( "Sm.HSInputControlPointCountRange", "HS input control point count must be [0..%0]. %1 specified.", ) self.add_valrule( "Sm.ZeroHSInputControlPointWithInput", "When HS input control point count is 0, no input signature should exist.", ) self.add_valrule( "Sm.OutputControlPointCountRange", "output control point count must be [%0..%1]. %2 specified.", ) self.add_valrule("Sm.GSValidInputPrimitive", "GS input primitive unrecognized.") self.add_valrule( "Sm.GSValidOutputPrimitiveTopology", "GS output primitive topology unrecognized.", ) self.add_valrule( "Sm.AppendAndConsumeOnSameUAV", "BufferUpdateCounter inc and dec on a given UAV (%d) cannot both be in the same shader for shader model less than 5.1.", ) self.add_valrule( "Sm.InvalidTextureKindOnUAV", "TextureCube[Array] resources are not supported with UAVs.", ) self.add_valrule("Sm.InvalidResourceKind", "Invalid resources kind.") self.add_valrule("Sm.InvalidResourceCompType", "Invalid resource return type.") self.add_valrule( "Sm.InvalidSamplerFeedbackType", "Invalid sampler feedback type." ) self.add_valrule( "Sm.SampleCountOnlyOn2DMS", "Only Texture2DMS/2DMSArray could has sample count.", ) self.add_valrule( "Sm.CounterOnlyOnStructBuf", "BufferUpdateCounter valid only on structured buffers.", ) self.add_valrule( "Sm.GSTotalOutputVertexDataRange", "Declared output vertex count (%0) multiplied by the total number of declared scalar components of output data (%1) equals %2. This value cannot be greater than %3.", ) self.add_valrule_msg( "Sm.MultiStreamMustBePoint", "When multiple GS output streams are used they must be pointlists", "Multiple GS output streams are used but '%0' is not pointlist.", ) self.add_valrule( "Sm.CompletePosition", "Not all elements of SV_Position were written." ) self.add_valrule( "Sm.UndefinedOutput", "Not all elements of output %0 were written." ) self.add_valrule( "Sm.CSNoSignatures", "Compute shaders must not have shader signatures." ) self.add_valrule( "Sm.CBufferTemplateTypeMustBeStruct", "D3D12 constant/texture buffer template element can only be a struct.", ) self.add_valrule_msg( "Sm.ResourceRangeOverlap", "Resource ranges must not overlap", "Resource %0 with base %1 size %2 overlap with other resource with base %3 size %4 in space %5.", ) self.add_valrule_msg( "Sm.CBufferSize", "CBuffer size must not exceed 65536 bytes", "CBuffer size is %0 bytes, exceeding maximum of 65536 bytes.", ) self.add_valrule_msg( "Sm.CBufferOffsetOverlap", "CBuffer offsets must not overlap", "CBuffer %0 has offset overlaps at %1.", ) self.add_valrule_msg( "Sm.CBufferElementOverflow", "CBuffer elements must not overflow", "CBuffer %0 size insufficient for element at offset %1.", ) self.add_valrule_msg( "Sm.CBufferArrayOffsetAlignment", "CBuffer array offset must be aligned to 16-bytes", "CBuffer %0 has unaligned array offset at %1.", ) self.add_valrule_msg( "Sm.OpcodeInInvalidFunction", "Invalid DXIL opcode usage like StorePatchConstant in patch constant function", "opcode '%0' should only be used in '%1'.", ) self.add_valrule_msg( "Sm.ViewIDNeedsSlot", "ViewID requires compatible space in pixel shader input signature", "Pixel shader input signature lacks available space for ViewID.", ) self.add_valrule( "Sm.64bitRawBufferLoadStore", "i64/f64 rawBufferLoad/Store overloads are allowed after SM 6.3.", ) self.add_valrule( "Sm.RayShaderSignatures", "Ray tracing shader '%0' should not have any shader signatures.", ) self.add_valrule( "Sm.RayShaderPayloadSize", "For shader '%0', %1 size is smaller than argument's allocation size.", ) self.add_valrule( "Sm.MeshShaderMaxVertexCount", "MS max vertex output count must be [0..%0]. %1 specified.", ) self.add_valrule( "Sm.MeshShaderMaxPrimitiveCount", "MS max primitive output count must be [0..%0]. %1 specified.", ) self.add_valrule( "Sm.MeshShaderPayloadSize", "For mesh shader with entry '%0', payload size %1 is greater than maximum size of %2 bytes.", ) self.add_valrule( "Sm.MeshShaderPayloadSizeDeclared", "For mesh shader with entry '%0', payload size %1 is greater than declared size of %2 bytes.", ) self.add_valrule( "Sm.MeshShaderOutputSize", "For shader '%0', vertex plus primitive output size is greater than %1.", ) self.add_valrule( "Sm.MeshShaderInOutSize", "For shader '%0', payload plus output size is greater than %1.", ) self.add_valrule( "Sm.MeshVSigRowCount", "For shader '%0', vertex output signatures are taking up more than %1 rows.", ) self.add_valrule( "Sm.MeshPSigRowCount", "For shader '%0', primitive output signatures are taking up more than %1 rows.", ) self.add_valrule( "Sm.MeshTotalSigRowCount", "For shader '%0', vertex and primitive output signatures are taking up more than %1 rows.", ) self.add_valrule( "Sm.MaxMSSMSize", "Total Thread Group Shared Memory storage is %0, exceeded %1.", ) self.add_valrule( "Sm.AmplificationShaderPayloadSize", "For amplification shader with entry '%0', payload size %1 is greater than maximum size of %2 bytes.", ) self.add_valrule( "Sm.AmplificationShaderPayloadSizeDeclared", "For amplification shader with entry '%0', payload size %1 is greater than declared size of %2 bytes.", ) # fxc relaxed check of gradient check. # self.add_valrule("Uni.NoUniInDiv", "TODO - No instruction requiring uniform execution can be present in divergent block") # self.add_valrule("Uni.GradientFlow", "TODO - No divergent gradient operations inside flow control") # a bit more specific than the prior rule # self.add_valrule("Uni.ThreadSync", "TODO - Thread sync operation must be in non-varying flow control due to a potential race condition, adding a sync after reading any values controlling shader execution at this point") # self.add_valrule("Uni.NoWaveSensitiveGradient", "Gradient operations are not affected by wave-sensitive data or control flow.") self.add_valrule("Flow.Reducible", "Execution flow must be reducible.") self.add_valrule("Flow.NoRecursion", "Recursion is not permitted.") self.add_valrule("Flow.DeadLoop", "Loop must have break.") self.add_valrule_msg( "Flow.FunctionCall", "Function with parameter is not permitted", "Function %0 with parameter is not permitted, it should be inlined.", ) self.add_valrule_msg( "Decl.DxilNsReserved", "The DXIL reserved prefixes must only be used by built-in functions and types", "Declaration '%0' uses a reserved prefix.", ) self.add_valrule_msg( "Decl.DxilFnExtern", "External function must be a DXIL function", "External function '%0' is not a DXIL function.", ) self.add_valrule_msg( "Decl.UsedInternal", "Internal declaration must be used", "Internal declaration '%0' is unused.", ) self.add_valrule_msg( "Decl.NotUsedExternal", "External declaration should not be used", "External declaration '%0' is unused.", ) self.add_valrule_msg( "Decl.UsedExternalFunction", "External function must be used", "External function '%0' is unused.", ) self.add_valrule_msg( "Decl.FnIsCalled", "Functions can only be used by call instructions", "Function '%0' is used for something other than calling.", ) self.add_valrule_msg( "Decl.FnFlattenParam", "Function parameters must not use struct types", "Type '%0' is a struct type but is used as a parameter in function '%1'.", ) self.add_valrule_msg( "Decl.FnAttribute", "Functions should only contain known function attributes", "Function '%0' contains invalid attribute '%1' with value '%2'.", ) self.add_valrule_msg( "Decl.ResourceInFnSig", "Resources not allowed in function signatures", "Function '%0' uses resource in function signature.", ) self.add_valrule_msg( "Decl.RayQueryInFnSig", "Rayquery objects not allowed in function signatures", "Function '%0' uses rayquery object in function signature.", ) self.add_valrule_msg( "Decl.PayloadStruct", "Payload parameter must be struct type", "Argument '%0' must be a struct type for payload in shader function '%1'.", ) self.add_valrule_msg( "Decl.AttrStruct", "Attributes parameter must be struct type", "Argument '%0' must be a struct type for attributes in shader function '%1'.", ) self.add_valrule_msg( "Decl.ParamStruct", "Callable function parameter must be struct type", "Argument '%0' must be a struct type for callable shader function '%1'.", ) self.add_valrule_msg( "Decl.ExtraArgs", "Extra arguments not allowed for shader functions", "Extra argument '%0' not allowed for shader function '%1'.", ) self.add_valrule_msg( "Decl.ShaderReturnVoid", "Shader functions must return void", "Shader function '%0' must have void return type.", ) self.add_valrule_msg( "Decl.ShaderMissingArg", "payload/params/attributes parameter is required for certain shader types", "%0 shader '%1' missing required %2 parameter.", ) self.add_valrule_msg( "Decl.MultipleNodeInputs", "A node shader may not have more than one input record", "node shader '%0' may not have more than one input record (%1 are declared)", ) self.add_valrule_msg( "Decl.NodeLaunchInputType", "Invalid input record type for node launch type", "%0 node shader '%1' has incompatible input record type (should be %2)", ) # These errors are emitted from ShaderCompatInfo validation. # If a called function is identifiable as a potential source of the # incompatibility, you get Sm.IncompatibleCallInEntry, # otherwise you get Sm.IncompatibleOperation. # You also get the specific incompatibilities found with one function # introducing each problem. # These may be emitted in addition to another specific operation # validation error that identifies the root cause, but is meant to # catch cases currently missed by other validation. self.add_valrule_msg( "Sm.IncompatibleCallInEntry", "Features used in internal function calls must be compatible with entry", "Entry function calls one or more functions using incompatible features. See other errors for details.", ) self.add_valrule_msg( "Sm.IncompatibleOperation", "Operations used in entry function must be compatible with shader stage and other properties", "Entry function performs some operation that is incompatible with the shader stage or other entry properties. See other errors for details.", ) self.add_valrule_msg( "Sm.IncompatibleStage", "Functions may only use features available in the entry function's stage", "Function uses features incompatible with the shader stage (%0) of the entry function.", ) self.add_valrule_msg( "Sm.IncompatibleShaderModel", "Functions may only use features available in the current shader model", "Function uses features incompatible with the shader model.", ) self.add_valrule_msg( "Sm.IncompatibleThreadGroupDim", "When derivatives are used in compute-model shaders, the thread group dimensions must be compatible", "Function uses derivatives in compute-model shader with NumThreads (%0, %1, %2); derivatives require NumThreads to be 1D and a multiple of 4, or 2D/3D with X and Y both being a multiple of 2.", ) self.add_valrule_msg( "Sm.IncompatibleDerivInComputeShaderModel", "Derivatives in compute-model shaders require shader model 6.6 and above", "Function uses derivatives in compute-model shader, which is only supported in shader model 6.6 and above.", ) self.add_valrule_msg( "Sm.IncompatibleRequiresGroup", "Functions requiring groupshared memory must be called from shaders with a visible group", "Function requires a visible group, but is called from a shader without one.", ) self.add_valrule_msg( "Sm.IncompatibleDerivLaunch", "Node shaders only support derivatives in broadcasting launch mode", "Function called from %0 launch node shader uses derivatives; only broadcasting launch supports derivatives.", ) # Assign sensible category names and build up an enumeration description cat_names = { "CONTAINER": "Container", "BITCODE": "Bitcode", "META": "Metadata", "INSTR": "Instruction", "FLOW": "Program flow", "TYPES": "Type system", "SM": "Shader model", "UNI": "Uniform analysis", "DECL": "Declaration", } valrule_enum = db_dxil_enum("ValidationRule", "Known validation rules") valrule_enum.is_internal = True for vr in self.val_rules: vr.category = cat_names[vr.group_name] vrval = db_dxil_enum_value(vr.enum_name, vr.rule_id, vr.doc) vrval.category = vr.category vrval.err_msg = vr.err_msg valrule_enum.values.append(vrval) self.enums.append(valrule_enum) def populate_counters(self): self.llvm_op_counters = set() self.dxil_op_counters = set() for i in self.instr: counters = getattr(i, "props", {}).get("counters", ()) if i.dxil_opid: self.dxil_op_counters.update(counters) else: self.llvm_op_counters.update(counters) counter_set = set(self.counters) counter_set.update(self.llvm_op_counters) counter_set.update(self.dxil_op_counters) self.counters = list(sorted(counter_set)) def add_valrule(self, name, desc): self.val_rules.append( db_dxil_valrule(name, len(self.val_rules), err_msg=desc, doc=desc) ) def add_valrule_msg(self, name, desc, err_msg): self.val_rules.append( db_dxil_valrule(name, len(self.val_rules), err_msg=err_msg, doc=desc) ) def add_llvm_instr( self, kind, llvm_id, name, llvm_name, doc, oload_types, op_params, **props ): i = db_dxil_inst( name, llvm_id=llvm_id, llvm_name=llvm_name, doc=doc, ops=op_params, oload_types=oload_types, ) i.props = props self.instr.append(i) def add_dxil_op( self, name, code_id, code_class, doc, oload_types, fn_attr, op_params, **props ): # The return value is parameter 0, insert the opcode as 1. op_params.insert(1, self.opcode_param) i = db_dxil_inst( name, llvm_id=self.call_instr.llvm_id, llvm_name=self.call_instr.llvm_name, dxil_op=name, dxil_opid=code_id, doc=doc, ops=op_params, dxil_class=code_class, oload_types=oload_types, fn_attr=fn_attr, ) i.props = props self.instr.append(i) def add_dxil_op_reserved(self, name, code_id): # The return value is parameter 0, insert the opcode as 1. op_params = [db_dxil_param(0, "v", "", "reserved"), self.opcode_param] i = db_dxil_inst( name, llvm_id=self.call_instr.llvm_id, llvm_name=self.call_instr.llvm_name, dxil_op=name, dxil_opid=code_id, doc="reserved", ops=op_params, dxil_class="Reserved", oload_types="v", fn_attr="", ) self.instr.append(i) def get_instr_by_llvm_name(self, llvm_name): "Return the instruction with the given LLVM name" return next(i for i in self.instr if i.llvm_name == llvm_name) def get_dxil_insts(self): for i in self.instr: if i.dxil_op != "": yield i def print_stats(self): "Print some basic statistics on the instruction database." print("Instruction count: %d" % len(self.instr)) print( "Max parameter count in instruction: %d" % max(len(i.ops) - 1 for i in self.instr) ) print( "Parameter count: %d" % sum(len(i.ops) - 1 for i in self.instr) ) ############################################################################### # HLSL-specific information. # ############################################################################### class db_hlsl_attribute(object): "An HLSL attribute declaration" def __init__(self, title_name, scope, args, doc): self.name = title_name.lower() # lowercase attribute name self.title_name = title_name # title-case attribute name self.scope = scope # one of l (loop), c (condition), s (switch), f (function) self.args = args # list of arguments self.doc = doc # documentation class db_hlsl_intrinsic(object): "An HLSL intrinsic declaration" def __init__( self, name, idx, opname, params, ns, ns_idx, doc, ro, rn, amo, wv, unsigned_op, overload_idx, hidden, ): self.name = name # Function name self.idx = idx # Unique number within namespace self.opname = opname # D3D-style name self.params = params # List of parameters self.ns = ns # Function namespace self.ns_idx = ns_idx # Namespace index self.doc = doc # Documentation id_prefix = "IOP" if ns == "Intrinsics" else "MOP" # SPIR-V Change Starts if ns == "VkIntrinsics": name = "Vk" + name self.name = "Vk" + self.name id_prefix = "IOP" # SPIR-V Change Ends self.enum_name = "%s_%s" % (id_prefix, name) # enum name self.readonly = ro # Only read memory self.readnone = rn # Not read memory self.argmemonly = amo # Only accesses memory through argument pointers self.wave = wv # Is wave-sensitive self.unsigned_op = unsigned_op # Unsigned opcode if exist if unsigned_op != "": self.unsigned_op = "%s_%s" % (id_prefix, unsigned_op) self.overload_param_index = ( overload_idx # Parameter determines the overload type, -1 means ret type ) self.hidden = hidden # Internal high-level op, not exposed to HLSL self.key = ( ("%3d" % ns_idx) + "!" + name + "!" + ("%2d" % len(params)) + "!" + ("%3d" % idx) ) # Unique key self.vulkanSpecific = ns.startswith( "Vk" ) # Vulkan specific intrinsic - SPIRV change class db_hlsl_namespace(object): "A grouping of HLSL intrinsics" def __init__(self, name): self.name = name self.intrinsics = [] class db_hlsl_intrisic_param(object): "An HLSL parameter declaration for an intrinsic" def __init__( self, name, param_qual, template_id, template_list, component_id, component_list, rows, cols, type_name, idx, template_id_idx, component_id_idx, ): self.name = name # Parameter name self.param_qual = param_qual # Parameter qualifier expressions self.template_id = template_id # Template ID (possibly identifier) self.template_list = template_list # Template list (possibly identifier) self.component_id = component_id # Component ID (possibly identifier) self.component_list = component_list # Component list (possibly identifier) self.rows = rows # Row count for parameter, possibly identifier self.cols = cols # Row count for parameter, possibly identifier self.type_name = type_name # Type name self.idx = idx # Argument index self.template_id_idx = template_id_idx # Template ID numeric value self.component_id_idx = component_id_idx # Component ID numeric value class db_hlsl(object): "A database of HLSL language data" def __init__(self, intrinsic_defs): self.base_types = { "bool": "LICOMPTYPE_BOOL", "int": "LICOMPTYPE_INT", "int32_only": "LICOMPTYPE_INT32_ONLY", "int64_only": "LICOMPTYPE_INT64_ONLY", "int16_t": "LICOMPTYPE_INT16", "uint": "LICOMPTYPE_UINT", "uint16_t": "LICOMPTYPE_UINT16", "u64": "LICOMPTYPE_UINT64", "any_int": "LICOMPTYPE_ANY_INT", "any_int32": "LICOMPTYPE_ANY_INT32", "any_int64": "LICOMPTYPE_ANY_INT64", "uint_only": "LICOMPTYPE_UINT_ONLY", "int8_t4_packed": "LICOMPTYPE_INT8_4PACKED", "uint8_t4_packed": "LICOMPTYPE_UINT8_4PACKED", "float16_t": "LICOMPTYPE_FLOAT16", "float": "LICOMPTYPE_FLOAT", "float32_only": "LICOMPTYPE_FLOAT32_ONLY", "fldbl": "LICOMPTYPE_FLOAT_DOUBLE", "any_float": "LICOMPTYPE_ANY_FLOAT", "float_like": "LICOMPTYPE_FLOAT_LIKE", "double": "LICOMPTYPE_DOUBLE", "double_only": "LICOMPTYPE_DOUBLE_ONLY", "numeric": "LICOMPTYPE_NUMERIC", "numeric16_only": "LICOMPTYPE_NUMERIC16_ONLY", "numeric32": "LICOMPTYPE_NUMERIC32", "numeric32_only": "LICOMPTYPE_NUMERIC32_ONLY", "any": "LICOMPTYPE_ANY", "sampler1d": "LICOMPTYPE_SAMPLER1D", "sampler2d": "LICOMPTYPE_SAMPLER2D", "sampler3d": "LICOMPTYPE_SAMPLER3D", "sampler_cube": "LICOMPTYPE_SAMPLERCUBE", "sampler_cmp": "LICOMPTYPE_SAMPLERCMP", "sampler": "LICOMPTYPE_SAMPLER", "resource": "LICOMPTYPE_RESOURCE", "ray_desc": "LICOMPTYPE_RAYDESC", "acceleration_struct": "LICOMPTYPE_ACCELERATION_STRUCT", "udt": "LICOMPTYPE_USER_DEFINED_TYPE", "void": "LICOMPTYPE_VOID", "string": "LICOMPTYPE_STRING", "Texture2D": "LICOMPTYPE_TEXTURE2D", "Texture2DArray": "LICOMPTYPE_TEXTURE2DARRAY", "wave": "LICOMPTYPE_WAVE", "p32i8": "LICOMPTYPE_INT8_4PACKED", "p32u8": "LICOMPTYPE_UINT8_4PACKED", "any_int16or32": "LICOMPTYPE_ANY_INT16_OR_32", "sint16or32_only": "LICOMPTYPE_SINT16_OR_32_ONLY", "any_sampler": "LICOMPTYPE_ANY_SAMPLER", "ByteAddressBuffer": "LICOMPTYPE_BYTEADDRESSBUFFER", "RWByteAddressBuffer": "LICOMPTYPE_RWBYTEADDRESSBUFFER", "NodeRecordOrUAV": "LICOMPTYPE_NODE_RECORD_OR_UAV", "AnyNodeOutputRecord": "LICOMPTYPE_ANY_NODE_OUTPUT_RECORD", "GroupNodeOutputRecords": "LICOMPTYPE_GROUP_NODE_OUTPUT_RECORDS", "ThreadNodeOutputRecords": "LICOMPTYPE_THREAD_NODE_OUTPUT_RECORDS", } self.trans_rowcol = {"r": "IA_R", "c": "IA_C", "r2": "IA_R2", "c2": "IA_C2"} self.param_qual = { "in": "AR_QUAL_IN", "inout": "AR_QUAL_IN | AR_QUAL_OUT", "ref": "AR_QUAL_REF", "out": "AR_QUAL_OUT", "col_major": "AR_QUAL_COLMAJOR", "row_major": "AR_QUAL_ROWMAJOR", "groupshared": "AR_QUAL_GROUPSHARED", } self.intrinsics = [] self.load_intrinsics(intrinsic_defs) self.create_namespaces() self.populate_attributes() self.opcode_namespace = "hlsl::IntrinsicOp" def create_namespaces(self): last_ns = None self.namespaces = {} for i in sorted(self.intrinsics, key=lambda x: x.key): if last_ns is None or last_ns.name != i.ns: last_ns = db_hlsl_namespace(i.ns) self.namespaces[i.ns] = last_ns last_ns.intrinsics.append(i) def load_intrinsics(self, intrinsic_defs): import re blank_re = re.compile(r"^\s*$") comment_re = re.compile(r"^\s*//") namespace_beg_re = re.compile(r"^namespace\s+(\w+)\s*{\s*$") namespace_end_re = re.compile(r"^}\s*namespace\s*$") intrinsic_re = re.compile( r"^\s*([^(]+)\s+\[\[(\S*)\]\]\s+(\w+)\s*\(\s*([^)]*)\s*\)\s*(:\s*\w+\s*)?;$" ) operand_re = re.compile(r"^:\s*(\w+)\s*$") bracket_cleanup_re = re.compile( r"<\s*(\S+)\s*,\s*(\S+)\s*>" ) # change <a,b> to <a@> to help split params and parse params_split_re = re.compile(r"\s*,\s*") ws_split_re = re.compile(r"\s+") typeref_re = re.compile(r"\$type(\d+)$") type_matrix_re = re.compile(r"(\S+)<(\S+)@(\S+)>$") type_vector_re = re.compile(r"(\S+)<(\S+)>$") type_any_re = re.compile(r"(\S+)<>$") type_array_re = re.compile(r"(\S+)\[\]$") type_object_re = re.compile( r"""( sampler\w* | string | (?:RW)?(?:Texture\w*|ByteAddressBuffer) | acceleration_struct | ray_desc | Node\w* | RWNode\w* | EmptyNode\w* | AnyNodeOutput\w* | NodeOutputRecord\w* | GroupShared\w* $)""", flags=re.VERBOSE, ) digits_re = re.compile(r"^\d+$") opt_param_match_re = re.compile(r"^\$match<(\S+)@(\S+)>$") ns_idx = 0 num_entries = 0 def add_flag(val, new_val): if val == "" or val == "0": return new_val return val + " | " + new_val def translate_rowcol(val): digits_match = digits_re.match(val) if digits_match: return val assert val in self.trans_rowcol, "unknown row/col %s" % val return self.trans_rowcol[val] def process_arg(desc, idx, done_args, intrinsic_name): "Process a single parameter description." opt_list = [] desc = desc.strip() if desc == "...": param_name = "..." type_name = "..." else: opt_list = ws_split_re.split(desc) assert len(opt_list) > 0, "malformed parameter desc %s" % (desc) param_name = opt_list.pop() # last token is name type_name = opt_list.pop() # next-to-last is type specifier param_qual = "0" template_id = str(idx) template_list = "LITEMPLATE_ANY" component_id = str(idx) component_list = "LICOMPTYPE_ANY" rows = "1" cols = "1" if type_name == "$classT": assert idx == 0, "'$classT' can only be used as the return type" # template_id may be -1 in other places other than return type, for example in Stream.Append(). # $unspec is a shorthand for return types only though. template_id = "-1" component_id = "0" type_name = "void" if type_name == "$funcT": template_id = "-3" component_id = "0" type_name = "void" elif type_name == "...": assert idx != 0, "'...' can only be used in the parameter list" template_id = "-2" component_id = "0" type_name = "void" else: typeref_match = typeref_re.match(type_name) if typeref_match: template_id = typeref_match.group(1) component_id = template_id assert idx != 1, "Can't use $type on the first argument" assert template_id != "0", "Can't match an input to the return type" done_idx = int(template_id) - 1 assert ( done_idx <= len(args) + 1 ), "$type must refer to a processed arg" done_arg = done_args[done_idx] type_name = done_arg.type_name # Determine matrix/vector/any/scalar/array/object type names. base_type = type_name def do_matrix(m): base_type, rows, cols = m.groups() template_list = "LITEMPLATE_MATRIX" return base_type, rows, cols, template_list def do_vector(m): base_type, cols = m.groups() template_list = "LITEMPLATE_VECTOR" return base_type, rows, cols, template_list def do_any(m): base_type = m.group(1) rows = "r" cols = "c" template_list = "LITEMPLATE_ANY" return base_type, rows, cols, template_list def do_array(m): base_type = m.group(1) cols = "c" template_list = "LITEMPLATE_ARRAY" return base_type, rows, cols, template_list def do_object(m): template_list = "LITEMPLATE_OBJECT" return base_type, rows, cols, template_list templates = [ (do_matrix, type_matrix_re), (do_vector, type_vector_re), (do_any, type_any_re), (do_array, type_array_re), (do_object, type_object_re), ] for do, type_re in templates: m = type_re.match(type_name) if m: base_type, rows, cols, template_list = do(m) break else: type_vector_match = type_vector_re.match(type_name) if type_vector_match: base_type = type_vector_match.group(1) cols = type_vector_match.group(2) template_list = "LITEMPLATE_VECTOR" else: type_any_match = type_any_re.match(type_name) if type_any_match: base_type = type_any_match.group(1) rows = "r" cols = "c" template_list = "LITEMPLATE_ANY" else: base_type = type_name if ( base_type.startswith("sampler") or base_type.startswith("string") or base_type.startswith("Texture") or base_type.startswith("wave") or base_type.startswith("acceleration_struct") or base_type.startswith("ray_desc") or base_type.startswith("any_sampler") ): template_list = "LITEMPLATE_OBJECT" else: template_list = "LITEMPLATE_SCALAR" assert base_type in self.base_types, "Unknown base type '%s' in '%s'" % ( base_type, desc, ) component_list = self.base_types[base_type] rows = translate_rowcol(rows) cols = translate_rowcol(cols) for opt in opt_list: if opt in self.param_qual: param_qual = add_flag(param_qual, self.param_qual[opt]) else: opt_param_match_match = opt_param_match_re.match(opt) assert opt_param_match_match, "Unknown parameter qualifier '%s'" % ( opt ) template_id = opt_param_match_match.group(1) component_id = opt_param_match_match.group(2) if component_list == "LICOMPTYPE_VOID": if type_name == "void": template_list = "LITEMPLATE_VOID" rows = "0" cols = "0" if template_id == "0": param_qual = "0" # Keep these as numeric values. template_id_idx = int(template_id) component_id_idx = int(component_id) # Verify that references don't point to the right (except for the return value). assert idx == 0 or template_id_idx <= int( idx ), "Argument '%s' has a forward reference" % (param_name) assert idx == 0 or component_id_idx <= int( idx ), "Argument '%s' has a forward reference" % (param_name) if template_id == "-1": template_id = "INTRIN_TEMPLATE_FROM_TYPE" elif template_id == "-2": template_id = "INTRIN_TEMPLATE_VARARGS" elif template_id == "-3": template_id = "INTRIN_TEMPLATE_FROM_FUNCTION" if component_id == "-1": component_id = "INTRIN_COMPTYPE_FROM_TYPE_ELT0" if component_id == "-2": component_id = "INTRIN_COMPTYPE_FROM_NODEOUTPUT" return db_hlsl_intrisic_param( param_name, param_qual, template_id, template_list, component_id, component_list, rows, cols, type_name, idx, template_id_idx, component_id_idx, ) def process_attr(attr): attrs = attr.split(",") readonly = False # Only read memory readnone = False # Not read memory argmemonly = False # Only reads memory through pointer arguments is_wave = False # Is wave-sensitive unsigned_op = "" # Unsigned opcode if exist overload_param_index = ( -1 ) # Parameter determines the overload type, -1 means ret type. hidden = False for a in attrs: if a == "": continue if a == "ro": readonly = True continue if a == "rn": readnone = True continue if a == "amo": argmemonly = True continue if a == "wv": is_wave = True continue if a == "hidden": hidden = True continue assign = a.split("=") if len(assign) != 2: assert False, "invalid attr %s" % (a) continue d = assign[0] v = assign[1] if d == "unsigned_op": unsigned_op = v continue if d == "overload": overload_param_index = int(v) continue assert False, "invalid attr %s" % (a) return ( readonly, readnone, argmemonly, is_wave, unsigned_op, overload_param_index, hidden, ) current_namespace = None for line in intrinsic_defs: if blank_re.match(line): continue if comment_re.match(line): continue match_obj = namespace_beg_re.match(line) if match_obj: assert ( not current_namespace ), "cannot open namespace without closing prior one" current_namespace = match_obj.group(1) num_entries = 0 ns_idx += 1 continue if namespace_end_re.match(line): assert ( current_namespace ), "cannot close namespace without previously opening it" current_namespace = None continue match_obj = intrinsic_re.match(line) if match_obj: assert current_namespace, "instruction missing namespace %s" % (line) # Get a D3D-style operand name for the instruction. # Unused for DXIL. opts = match_obj.group(1) attr = match_obj.group(2) name = match_obj.group(3) params = match_obj.group(4) op = match_obj.group(5) if op: operand_match = operand_re.match(op) if operand_match: op = operand_match.group(1) if not op: op = name ( readonly, readnone, argmemonly, is_wave, unsigned_op, overload_param_index, hidden, ) = process_attr(attr) # Add an entry for this intrinsic. if bracket_cleanup_re.search(opts): opts = bracket_cleanup_re.sub(r"<\1@\2>", opts) if bracket_cleanup_re.search(params): params = bracket_cleanup_re.sub(r"<\g<1>@\2>", params) ret_desc = "out " + opts + " " + name if len(params) > 0: in_args = params_split_re.split(params) else: in_args = [] arg_idx = 1 args = [] for in_arg in in_args: args.append(process_arg(in_arg, arg_idx, args, name)) arg_idx += 1 # We have to process the return type description last # to match the compiler's handling of it and allow # the return type to match an input type. # It needs to be the first entry, so prepend it. args.insert(0, process_arg(ret_desc, 0, args, name)) # TODO: verify a single level of indirection self.intrinsics.append( db_hlsl_intrinsic( name, num_entries, op, args, current_namespace, ns_idx, "pending doc for " + name, readonly, readnone, argmemonly, is_wave, unsigned_op, overload_param_index, hidden, ) ) num_entries += 1 continue assert False, "cannot parse line %s" % (line) def populate_attributes(self): "Populate basic definitions for attributes." attributes = [] def add_attr(title_name, scope, doc): attributes.append(db_hlsl_attribute(title_name, scope, [], doc)) def add_attr_arg(title_name, scope, args, doc): attributes.append(db_hlsl_attribute(title_name, scope, args, doc)) add_attr( "Allow_UAV_Condition", "l", "Allows a compute shader loop termination condition to be based off of a UAV read. The loop must not contain synchronization intrinsics", ) add_attr( "Branch", "c", "Evaluate only one side of the if statement depending on the given condition", ) add_attr( "Call", "s", "The bodies of the individual cases in the switch will be moved into hardware subroutines and the switch will be a series of subroutine calls", ) add_attr( "EarlyDepthStencil", "f", "Forces depth-stencil testing before a shader executes", ) add_attr( "FastOpt", "l", "Reduces the compile time but produces less aggressive optimizations", ) add_attr( "Flatten", "c", "Evaluate both sides of the if statement and choose between the two resulting values", ) add_attr("ForceCase", "s", "Force a switch statement in the hardware") add_attr( "Loop", "l", "Generate code that uses flow control to execute each iteration of the loop", ) add_attr_arg( "ClipPlanes", "f", "Optional list of clip planes", [{"name": "ClipPlane", "type": "int", "count": 6}], ) add_attr_arg( "Domain", "f", "Defines the patch type used in the HS", [{"name": "DomainType", type: "string"}], ) add_attr_arg( "Instance", "f", "Use this attribute to instance a geometry shader", [{"name": "Count", "type": "int"}], ) add_attr_arg( "MaxTessFactor", "f", "Indicates the maximum value that the hull shader would return for any tessellation factor.", [{"name": "Count", "type": "int"}], ) add_attr_arg( "MaxVertexCount", "f", "maxvertexcount doc", [{"name": "Count", "type": "int"}], ) add_attr_arg( "NumThreads", "f", "Defines the number of threads to be executed in a single thread group.", [ {"name": "x", "type": "int"}, {"name": "z", "type": "int"}, {"name": "y", "type": "int"}, ], ) add_attr_arg( "OutputControlPoints", "f", "Defines the number of output control points per thread that will be created in the hull shader", [{"name": "Count", "type": "int"}], ) add_attr_arg( "OutputTopology", "f", "Defines the output primitive type for the tessellator", [{"name": "Topology", "type": "string"}], ) add_attr_arg( "Partitioning", "f", "Defines the tesselation scheme to be used in the hull shader", [{"name": "Scheme", "type": "scheme"}], ) add_attr_arg( "PatchConstantFunc", "f", "Defines the function for computing patch constant data", [{"name": "FunctionName", "type": "string"}], ) add_attr_arg( "RootSignature", "f", "RootSignature doc", [{"name": "SignatureName", "type": "string"}], ) add_attr_arg( "Unroll", "l", "Unroll the loop until it stops executing or a max count", [{"name": "Count", "type": "int"}], ) self.attributes = attributes if __name__ == "__main__": db = db_dxil() print(db) db.print_stats()
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/hct/hcttracei.py
#!/usr/bin/env python2.7 # Copyright (C) Microsoft Corporation. All rights reserved. # This file is distributed under the University of Illinois Open Source License. See LICENSE.TXT for details. """Analyses the ETW dump file fors dxcompiler output as generated by hcttrace.""" import argparse import datetime import xml.etree.ElementTree as ET # Task values. DXCompilerInitialization = 1 DXCompilerShutdown = 2 DXCompilerCreateInstance = 3 DXCompilerIntelliSenseParse = 4 DXCompilerCompile = 5 DXCompilerPreprocess = 6 DXCompilerDisassemble = 7 # Opcode values OpcodeStart = 1 OpcodeStop = 2 # Namespace dictionary. ns = {"e": "http://schemas.microsoft.com/win/2004/08/events/event"} def write_basic_info(node): """Writes computer information""" print("Basic information:") print("CPU Speed: %s" % node.find("e:Data[@Name='CPUSpeed']", ns).text) print( "Processor count: %s" % node.find("e:Data[@Name='NumberOfProcessors']", ns).text ) print("Events lost: %s" % node.find("e:Data[@Name='EventsLost']", ns).text) print("Pointer size: %s" % node.find("e:Data[@Name='PointerSize']", ns).text) def write_compile_times(root): """Prints out compilation times.""" compilations = {} for e in root: system_node = e.find("e:System", ns) if system_node is None: continue channel = system_node.find("e:Channel", ns) if ( channel is None or channel.text != "Microsoft-Windows-DXCompiler-API/Analytic" ): continue task = int(system_node.find("e:Task", ns).text) opcode = int(system_node.find("e:Opcode", ns).text) pid = int(system_node.find("e:Execution", ns).attrib["ProcessID"]) tid = int(system_node.find("e:Execution", ns).attrib["ThreadID"]) time_created = system_node.find("e:TimeCreated", ns).attrib["SystemTime"] # Something like: # 2016-02-02T00:10:51.619434100Z # Unfortunately datetime doesn't have enough precision, so we make do with this: # 2016-02-02T00:10:39.630081 if task == DXCompilerCompile: time_created = time_created[:26] cid = "{0},{1}".format(pid, tid) parsed_time_created = datetime.datetime.strptime( time_created, "%Y-%m-%dT%H:%M:%S.%f" ) if opcode == OpcodeStart: # print("Start at %s" % time_created) compilations[cid] = parsed_time_created else: old_parsed_time_created = compilations[cid] print( "Compilation took %s" % str(parsed_time_created - old_parsed_time_created) ) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "-v", "--verbose", action="store_true", help="Show verbose output" ) parser.add_argument("dumpfiles", nargs="+") args = parser.parse_args() for dumpfile in args.dumpfiles: if args.verbose: print( "Scanning for dxcompiler events in dumpfile: %s" % (dumpfile,), file=sys.stderr, ) tree = ET.parse(dumpfile) root = tree.getroot() write_basic_info(root.find("e:Event/e:EventData", ns)) write_compile_times(root) # Other interesting things: # errors, working set, additional stats if __name__ == "__main__": main()
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/hct/gen_intrin_main.txt
// Copyright (C) Microsoft Corporation. All rights reserved. // This file is distributed under the University of Illinois Open Source License. See LICENSE.TXT for details. // // See hctdb.py for the implementation of intrinsic file processing. // // Intrinsic declarations are grouped into namespaces that // turn into qualifiers for the generated names. This lets // intrinsics be grouped into sets such as base function-style // intrinsics, Texture1D intrinsics, etc. // // Intrinsic declarations are a line of the form: // // <type> \[\[[attr]\]\] <name>([<qual> <type> <name> [, ... ]]) [ : <op>] // // <name> is a C++ identifier for the intrinsic or argument name. // // <op> is the D3DIOP_* (or D3DMOP_* if the namespace has "Method" // in the name) enumerant. By default it's the same as the intrinsic // name, but <op> can be given to set it arbitrarily. // // <qual> is one of "in", "out" or "inout" plus optional qualifiers // "col_major", "row_major". // variadic functions assume <qual> of "in" for any arguments that are not // explicitly specified. // // <type> is where most of the work goes. <type> lets you // specify particular types and layouts for arguments and // also lets you indicate which types must share characteristics // with other types. <type> can be a simple scalar like "bool" // or it can require an N-vector with "bool<N>" or an N-by-M // matrix with "bool<N, M>". You can refer to input columns // and rows with r, c, r2 and c2, so "float<r, r>" means a // float matrix with the same number of rows and columns and // the size comes from the parse input. "<>" means any kind // of layout is acceptable. // // Basic types are bool, int, uint, u64, float, sampler1d, sampler2d, // sampler3d, sampler_cube, sampler_cmp, sampler, wave and void. // There are meta-types too: any_int, uint_only, numeric and any. // // Along with a type and layout you can also give relations // between types in an intrinsic. The types of an intrinsic // are indexed start with 0 at the return type and increasing // left to right (first argument is 1, second is 2, etc.). // $match<X, Y> says that the template type (layout) of // a particular type must match the template type of the X'th // type and that the component type (base type) of a particular // type must match the component type of the Y'th type. // For example, in "float<> acos(in $match<0, 0> float<> x)" the // $match<0, 0> means that both the template and component type // of the argument must match that of the return type (index 0). // The float<> means that any layout (scalar/vector/matrix) of // floats is acceptable, and then the parameter and return // type must match. // // A value of -1 for X in $match is a special marker for // object method intrinsics meaning that the type is taken // from the object's template type. // // A value of -1 for Y in $match is a special marker for // object method intrinsics meaning that the component type // of the type is taken from the first subelement of the // object's template type. // // Certain $match situations are aliased for readability // and conciseness. // // $classT - This equates to $match<-1, 0> void and is // used for method return types that are set from // the object template type. // // $funcT - This equates to $match<-3, 0> void and is // used for method return types that are set from // the function template type. // // $typeN - This equates to $match<N, N> <argtypeN> and is // shorthand for a direct match of another type. // For example, in "$type1 abs(in numeric<> x)" the // $type means that the return type is a direct match // of the argument type ($type cannot be used on the // first argument since there's nothing to match at // that point and can't refer to the return type as // it is matched after the inputs). // namespace Intrinsics { int<4> [[rn]] D3DCOLORtoUBYTE4(in $match<0, 1> float<4> x) : d3dcolortoubyte4; uint [[rn]] GetRenderTargetSampleCount() : rtsampleinfo; float<2> [[rn]] GetRenderTargetSamplePosition(in int s) : rtsamplepos; void [[]] abort(); $type1 [[rn,unsigned_op=uabs]] abs(in numeric<> x); $type1 [[rn]] acos(in float_like<> x); bool [[rn]] all(in any<> x); void [[]] AllMemoryBarrier() : syncallmemory_ug; void [[]] AllMemoryBarrierWithGroupSync() : syncgroupandallmemory_ug; bool [[rn]] any(in any<> x); double<> [[rn]] asdouble(in $match<0, 1> uint<> x, in $match<0, 2> uint<> y) : reinterpret_fuse_double; float<> [[rn]] asfloat(in $match<0, 1> numeric32_only<> x) : reinterpret_float; float16_t<> [[rn]] asfloat16(in $match<0,1> numeric16_only<> x) : reinterpret_float16; int16_t<> [[rn]] asint16(in $match<0,1> numeric16_only<> x) : reinterpret_int16; $type1 [[rn]] asin(in float_like<> x); int<> [[rn]] asint(in $match<0, 1> numeric32_only<> x) : reinterpret_int; void [[]] asuint(in double<> d, out $match<1, 2> uint<> x, out $match<1, 3> uint<> y) : reinterpret_split_double_uint; uint<> [[rn]] asuint(in $match<0, 1> numeric32_only<> x) : reinterpret_uint; uint16_t<> [[rn]] asuint16(in $match<0,1> numeric16_only<> x) : reinterpret_uint16; $type1 [[rn]] atan(in float_like<> x); $type1 [[rn]] atan2(in float_like<> x, in $type1 y); $type1 [[rn]] ceil(in float_like<> x); $type1 [[rn,unsigned_op=uclamp]] clamp(in numeric<> x, in $type1 min, in $type1 max); void [[]] clip(in float<> x); $type1 [[rn]] cos(in float_like<> x); $type1 [[rn]] cosh(in float_like<> x); $match<1, 0> uint<> [[rn]] countbits(in any_int<> x); $type1 [[rn]] cross(in float_like<3> a, in $type1 b); $type1 [[rn]] ddx(in float_like<> x); $type1 [[rn]] ddx_coarse(in float_like<> x); $type1 [[rn]] ddx_fine(in float_like<> x); $type1 [[rn]] ddy(in float_like<> x); $type1 [[rn]] ddy_coarse(in float_like<> x); $type1 [[rn]] ddy_fine(in float_like<> x); $type1 [[rn]] degrees(in float_like<> x); $match<0, 1> float_like [[rn]] determinant(in float_like<r, r> x); void [[]] DeviceMemoryBarrier() : syncdevicememory_ug; void [[]] DeviceMemoryBarrierWithGroupSync() : syncgroupanddevicememory_ug; $match<0, 1> float_like [[rn]] distance(in float_like<c> a, in $type1 b); $match<0, 1> numeric [[rn]] dot(in numeric<c> a, in $type1 b); $type1 [[rn]] dst(in numeric<4> a, in $type1 b); // void errorf(in string Format, ...); $type1 [[rn]] EvaluateAttributeAtSample(in numeric<> value, in uint index); $type1 [[rn]] EvaluateAttributeCentroid(in numeric<> value); $type1 [[rn]] EvaluateAttributeSnapped(in numeric<> value, in int<2> offset); $type1 [[rn]] GetAttributeAtVertex(in numeric<> value, in uint VertexID); $type1 [[rn]] exp(in float_like<> x); $type1 [[rn]] exp2(in float_like<> x); float<> [[rn]] f16tof32(in uint<> x); // Use float for DXIL don't support f16 on f32tof16. uint<> [[rn]] f32tof16(in float<> x); $type1 [[rn]] faceforward(in float_like<c> N, in $type1 I, in $type1 Ng); $match<1, 0> uint<> [[rn,unsigned_op=ufirstbithigh,overload=0]] firstbithigh(in any_int<> x); $match<1, 0> uint<> [[rn]] firstbitlow(in any_int<> x); $type1 [[rn]] floor(in float_like<> x); $type1 [[rn]] fma(in double_only<> a, in $type1 b, in $type1 c); $type1 [[rn]] fmod(in float_like<> a, in $type1 b); $type1 [[rn]] frac(in float_like<> x); $type1 [[]] frexp(in float<> x, out $type1 exp); $type1 [[rn]] fwidth(in float_like<> x); void [[]] GroupMemoryBarrier() : syncsharedmemory; void [[]] GroupMemoryBarrierWithGroupSync() : syncgroupandsharedmemory; // 64-bit integers interlocks void [[]] InterlockedAdd(ref int64_only result, in u64 value); void [[]] InterlockedAdd(ref int64_only result, in u64 value, out any_int64 original) : interlockedadd_immediate; void [[unsigned_op=InterlockedUMin,overload=0]] InterlockedMin(ref int64_only result, in any_int64 value) : interlockedmin; void [[unsigned_op=InterlockedUMin,overload=0]] InterlockedMin(ref int64_only result, in any_int64 value, out any_int64 original) : interlockedmin_immediate; void [[unsigned_op=InterlockedUMax,overload=0]] InterlockedMax(ref int64_only result, in any_int64 value) : interlockedmax; void [[unsigned_op=InterlockedUMax,overload=0]] InterlockedMax(ref int64_only result, in any_int64 value, out any_int64 original) : interlockedmax_immediate; void [[]] InterlockedAnd(ref int64_only result, in u64 value); void [[]] InterlockedAnd(ref int64_only result, in u64 value, out any_int64 original) : interlockedand_immediate; void [[]] InterlockedOr(ref int64_only result, in u64 value); void [[]] InterlockedOr(ref int64_only result, in u64 value, out any_int64 original) : interlockedor_immediate; void [[]] InterlockedXor(ref int64_only result, in u64 value); void [[]] InterlockedXor(ref int64_only result, in u64 value, out any_int64 original) : interlockedxor_immediate; void [[]] InterlockedCompareStore(ref int64_only result, in u64 compare, in u64 value); void [[]] InterlockedExchange(ref int64_only result, in any_int64 value, out any_int64 original); void [[]] InterlockedCompareExchange(ref int64_only result, in u64 compare, in u64 value, out any_int64 original); // floating point interlocks void [[]] InterlockedExchange(ref float32_only result, in float value, out float original); void [[]] InterlockedCompareStoreFloatBitwise(ref float32_only result, in float compare, in float value); void [[]] InterlockedCompareExchangeFloatBitwise(ref float32_only result, in float compare, in float value, out float original); // 32-bit integer interlocks void [[]] InterlockedAdd(ref int32_only result, in uint value); void [[]] InterlockedAdd(ref int32_only result, in uint value, out any_int32 original) : interlockedadd_immediate; void [[unsigned_op=InterlockedUMin,overload=0]] InterlockedMin(ref int32_only result, in any_int32 value) : interlockedmin; void [[unsigned_op=InterlockedUMin,overload=0]] InterlockedMin(ref int32_only result, in any_int32 value, out any_int32 original) : interlockedmin_immediate; void [[unsigned_op=InterlockedUMax,overload=0]] InterlockedMax(ref int32_only result, in any_int32 value) : interlockedmax; void [[unsigned_op=InterlockedUMax,overload=0]] InterlockedMax(ref int32_only result, in any_int32 value, out any_int32 original) : interlockedmax_immediate; void [[]] InterlockedAnd(ref int32_only result, in uint value); void [[]] InterlockedAnd(ref int32_only result, in uint value, out any_int32 original) : interlockedand_immediate; void [[]] InterlockedOr(ref int32_only result, in uint value); void [[]] InterlockedOr(ref int32_only result, in uint value, out any_int32 original) : interlockedor_immediate; void [[]] InterlockedXor(ref int32_only result, in uint value); void [[]] InterlockedXor(ref int32_only result, in uint value, out any_int32 original) : interlockedxor_immediate; void [[]] InterlockedCompareStore(ref int32_only result, in uint compare, in uint value); void [[]] InterlockedExchange(ref int32_only result, in uint value, out any_int32 original); void [[]] InterlockedCompareExchange(ref int32_only result, in uint compare, in uint value, out any_int32 original); $match<1, 0> bool<> [[rn]] isfinite(in float<> x); $match<1, 0> bool<> [[rn]] isinf(in float<> x); $match<1, 0> bool<> [[rn]] isnan(in float<> x); $type1 [[rn]] ldexp(in float_like<> x, in $type1 exp); $match<0, 1> float_like [[rn]] length(in float_like<c> x); $type1 [[rn]] lerp(in float_like<> a, in $type1 b, in $type1 s); $match<0, 1> float_like<4> [[rn]] lit(in float_like l, in $match<2, 1> float_like h, in $match<3, 1> float_like m); $type1 [[rn]] log(in float_like<> x); $type1 [[rn]] log10(in float_like<> x); $type1 [[rn]] log2(in float_like<> x); $type1 [[rn,unsigned_op=umad]] mad(in numeric<> a, in $type1 b, in $type1 c); $type1 [[rn,unsigned_op=umax]] max(in numeric<> a, in $type1 b); $type1 [[rn,unsigned_op=umin]] min(in numeric<> a, in $type1 b); $type1 [[]] modf(in float_like<> x, out $type1 ip); uint<4> [[rn]] msad4(in uint reference, in uint<2> source, in uint<4> accum); numeric [[rn]] mul(in $match<1, 0> numeric a, in $match<2, 0> numeric b) : mul_ss; numeric<c2> [[rn]] mul(in $match<1, 0> numeric a, in $match<2, 0> numeric<c2> b) : mul_sv; numeric<r2, c2> [[rn]] mul(in $match<1, 0> numeric a, in $match<2, 0> numeric<r2, c2> b) : mul_sm; numeric<c> [[rn]] mul(in $match<1, 0> numeric<c> a, in $match<2, 0> numeric b) : mul_vs; numeric [[rn]] mul(in $match<1, 0> numeric<c> a, in $match<2, 0> numeric<c> b) : mul_vv; numeric<c2> [[rn,unsigned_op=umul]] mul(in $match<1, 0> numeric<c> a, in col_major $match<2, 0> numeric<c, c2> b) : mul_vm; numeric<r, c> [[rn]] mul(in $match<1, 0> numeric<r, c> a, in $match<2, 0> numeric b) : mul_ms; numeric<r> [[rn,unsigned_op=umul]] mul(in row_major $match<1, 0> numeric<r, c> a, in $match<2, 0> numeric<c> b) : mul_mv; numeric<r, c2> [[rn,unsigned_op=umul]] mul(in row_major $match<1, 0> numeric<r, c> a, in col_major $match<2, 0> numeric<c, c2> b) : mul_mm; $type1 [[rn]] normalize(in float_like<c> x); $type1 [[rn]] pow(in float_like<> x, in $type1 y); void [[]] printf(in string Format, ...); void [[]] Process2DQuadTessFactorsAvg(in float<4> RawEdgeFactors, in float<2> InsideScale, out float<4> RoundedEdgeFactors, out float<2> RoundedInsideFactors, out float<2> UnroundedInsideFactors) : ptf_2dqavg; void [[]] Process2DQuadTessFactorsMax(in float<4> RawEdgeFactors, in float<2> InsideScale, out float<4> RoundedEdgeFactors, out float<2> RoundedInsideFactors, out float<2> UnroundedInsideFactors) : ptf_2dqmax; void [[]] Process2DQuadTessFactorsMin(in float<4> RawEdgeFactors, in float<2> InsideScale, out float<4> RoundedEdgeFactors, out float<2> RoundedInsideFactors, out float<2> UnroundedInsideFactors) : ptf_2dqmin; void [[]] ProcessIsolineTessFactors(in float<1> RawDetailFactor, in float<1> RawDensityFactor, out float<1> RoundedDetailFactorr, out float<1> RoundedDensityFactor) : ptf_i; void [[]] ProcessQuadTessFactorsAvg(in float<4> RawEdgeFactors, in float<1> InsideScale, out float<4> RoundedEdgeFactors, out float<2> RoundedInsideFactors, out float<2> UnroundedInsideFactors) : ptf_qavg; void [[]] ProcessQuadTessFactorsMax(in float<4> RawEdgeFactors, in float<1> InsideScale, out float<4> RoundedEdgeFactors, out float<2> RoundedInsideFactors, out float<2> UnroundedInsideFactors) : ptf_qmax; void [[]] ProcessQuadTessFactorsMin(in float<4> RawEdgeFactors, in float<1> InsideScale, out float<4> RoundedEdgeFactors, out float<2> RoundedInsideFactors, out float<2> UnroundedInsideFactors) : ptf_qmin; void [[]] ProcessTriTessFactorsAvg(in float<3> RawEdgeFactors, in float<1> InsideScale, out float<3> RoundedEdgeFactors, out float<1> RoundedInsideFactor, out float<1> UnroundedInsideFactor) : ptf_tmin; void [[]] ProcessTriTessFactorsMax(in float<3> RawEdgeFactors, in float<1> InsideScale, out float<3> RoundedEdgeFactors, out float<1> RoundedInsideFactor, out float<1> UnroundedInsideFactor) : ptf_tmax; void [[]] ProcessTriTessFactorsMin(in float<3> RawEdgeFactors, in float<1> InsideScale, out float<3> RoundedEdgeFactors, out float<1> RoundedInsideFactor, out float<1> UnroundedInsideFactor) : ptf_tavg; $type1 [[rn]] radians(in float_like<> x); $type1 [[rn]] rcp(in any_float<> x) : rcp_approx; $type1 [[rn]] reflect(in float_like<c> i, in $type1 n); $type1 [[rn]] refract(in float_like<c> i, in $type1 n, in $match<3, 1> float_like ri); $type1 [[rn]] reversebits(in any_int<> x); $type1 [[rn]] round(in float_like<> x); $type1 [[rn]] rsqrt(in float_like<> x); $type1 [[rn]] saturate(in any_float<> x); $match<1, 0> int<> [[rn,unsigned_op=usign,overload=0]] sign(in numeric<> x); $type1 [[rn]] sin(in float_like<> x); void [[]] sincos(in float_like<> x, out $type1 s, out $type1 c); $type1 [[rn]] sinh(in float_like<> x); $type1 [[rn]] smoothstep(in float_like<> a, in $type1 b, in $type1 x); void [[]] source_mark(); $type1 [[rn]] sqrt(in float_like<> x); $type1 [[rn]] step(in float_like<> a, in $type1 x); $type1 [[rn]] tan(in float_like<> x); $type1 [[rn]] tanh(in float_like<> x); float_like<4> [[ro]] tex1D(in sampler1d s, in float_like x) : tex1d; float_like<4> [[ro]] tex1D(in sampler1d s, in float_like<1> x, in $type2 ddx, in $type2 ddy) : tex1d_dd; float_like<4> [[ro]] tex1Dbias(in sampler1d s, in float_like<4> x) : tex1d_bias; float_like<4> [[ro]] tex1Dgrad(in sampler1d s, in float_like<1> x, in $type2 ddx, in $type2 ddy) : tex1d_dd; float_like<4> [[ro]] tex1Dlod(in sampler1d s, in float_like<4> x) : tex1d_lod; float_like<4> [[ro]] tex1Dproj(in sampler1d s, in float_like<4> x) : tex1d_proj; float_like<4> [[ro]] tex2D(in sampler2d s, in float_like<2> x) : tex2d; float_like<4> [[ro]] tex2D(in sampler2d s, in float_like<2> x, in $type2 ddx, in $type2 ddy) : tex2d_dd; float_like<4> [[ro]] tex2Dbias(in sampler2d s, in float_like<4> x) : tex2d_bias; float_like<4> [[ro]] tex2Dgrad(in sampler2d s, in float_like<2> x, in $type2 ddx, in $type2 ddy) : tex2d_dd; float_like<4> [[ro]] tex2Dlod(in sampler2d s, in float_like<4> x) : tex2d_lod; float_like<4> [[ro]] tex2Dproj(in sampler2d s, in float_like<4> x) : tex2d_proj; float_like<4> [[ro]] tex3D(in sampler3d s, in float_like<3> x) : tex3d; float_like<4> [[ro]] tex3D(in sampler3d s, in float_like<3> x, in $type2 ddx, in $type2 ddy) : tex3d_dd; float_like<4> [[ro]] tex3Dbias(in sampler3d s, in float_like<4> x) : tex3d_bias; float_like<4> [[ro]] tex3Dgrad(in sampler3d s, in float_like<3> x, in $type2 ddx, in $type2 ddy) : tex3d_dd; float_like<4> [[ro]] tex3Dlod(in sampler3d s, in float_like<4> x) : tex3d_lod; float_like<4> [[ro]] tex3Dproj(in sampler3d s, in float_like<4> x) : tex3d_proj; float_like<4> [[ro]] texCUBE(in sampler_cube s, in float_like<3> x) : texcube; float_like<4> [[ro]] texCUBE(in sampler_cube s, in float_like<3> x, in $type2 ddx, in $type2 ddy) : texcube_dd; float_like<4> [[ro]] texCUBEbias(in sampler_cube s, in float_like<4> x) : texcube_bias; float_like<4> [[ro]] texCUBEgrad(in sampler_cube s, in float_like<3> x, in $type2 ddx, in $type2 ddy) : texcube_dd; float_like<4> [[ro]] texCUBElod(in sampler_cube s, in float_like<4> x) : texcube_lod; float_like<4> [[ro]] texCUBEproj(in sampler_cube s, in float_like<4> x) : texcube_proj; $match<1, 1> any<c, r> [[rn]] transpose(in any<r, c> x); $type1 [[rn]] trunc(in float_like<> x); bool [[rn]] CheckAccessFullyMapped(in uint_only status) : check_access_fully_mapped; uint<c> [[rn]] AddUint64(in $match<1, 0> uint<c> a, in $match<2, 0> uint<c> b) : adduint64; $type1 [[rn]] NonUniformResourceIndex(in any<> index) : nonuniform_resource_index; // Wave intrinsics. Only those that depend on the exec mask are marked as wave-sensitive bool [[wv]] WaveIsFirstLane(); uint [[ro]] WaveGetLaneIndex(); uint [[rn]] WaveGetLaneCount(); bool [[wv]] WaveActiveAnyTrue(in bool cond); bool [[wv]] WaveActiveAllTrue(in bool cond); $match<1, 0> bool<> [[wv]] WaveActiveAllEqual(in any<> value); uint<4> [[wv]] WaveActiveBallot(in bool cond); $type1 [[]] WaveReadLaneAt(in any<> value, in uint lane); $type1 [[wv]] WaveReadLaneFirst(in any<> value); uint [[wv]] WaveActiveCountBits(in bool value); $type1 [[unsigned_op=WaveActiveUSum,wv]] WaveActiveSum(in numeric<> value); $type1 [[unsigned_op=WaveActiveUProduct,wv]] WaveActiveProduct(in numeric<> value); $type1 [[wv]] WaveActiveBitAnd(in uint_only<> value); $type1 [[wv]] WaveActiveBitOr(in uint_only<> value); $type1 [[wv]] WaveActiveBitXor(in uint_only<> value); $type1 [[unsigned_op=WaveActiveUMin,wv]] WaveActiveMin(in numeric<> value); $type1 [[unsigned_op=WaveActiveUMax,wv]] WaveActiveMax(in numeric<> value); uint [[wv]] WavePrefixCountBits(in bool value); $type1 [[unsigned_op=WavePrefixUSum,wv]] WavePrefixSum(in numeric<> value); $type1 [[unsigned_op=WavePrefixUProduct,wv]] WavePrefixProduct(in numeric<> value); uint<4> [[wv]] WaveMatch(in numeric<> value); $type1 [[wv]] WaveMultiPrefixBitAnd(in any_int<> value, in uint<4> mask); $type1 [[wv]] WaveMultiPrefixBitOr(in any_int<> value, in uint<4> mask); $type1 [[wv]] WaveMultiPrefixBitXor(in any_int<> value, in uint<4> mask); uint [[wv]] WaveMultiPrefixCountBits(in bool value, in uint<4> mask); $type1 [[unsigned_op=WaveMultiPrefixUProduct,wv]] WaveMultiPrefixProduct(in numeric<> value, in uint<4> mask); $type1 [[unsigned_op=WaveMultiPrefixUSum,wv]] WaveMultiPrefixSum(in numeric<> value, in uint<4> mask); $type1 [[]] QuadReadLaneAt(in numeric<> value, in uint quadLane); $type1 [[]] QuadReadAcrossX(in numeric<> value); $type1 [[]] QuadReadAcrossY(in numeric<> value); $type1 [[]] QuadReadAcrossDiagonal(in numeric<> value); bool [[]] QuadAny(in bool cond); bool [[]] QuadAll(in bool cond); // Raytracing void [[]] TraceRay(in acceleration_struct AccelerationStructure, in uint RayFlags, in uint InstanceInclusionMask, in uint RayContributionToHitGroupIndex, in uint MultiplierForGeometryContributionToHitGroupIndex, in uint MissShaderIndex, in ray_desc Ray, inout udt Payload); bool [[]] ReportHit(in float THit, in uint HitKind, in udt Attributes); void [[]] CallShader(in uint ShaderIndex, inout udt Parameter); void [[]] IgnoreHit(); void [[]] AcceptHitAndEndSearch(); uint<3> [[rn]] DispatchRaysIndex(); uint<3> [[rn]] DispatchRaysDimensions(); // group: Ray Vectors float<3> [[rn]] WorldRayOrigin(); float<3> [[rn]] WorldRayDirection(); float<3> [[rn]] ObjectRayOrigin(); float<3> [[rn]] ObjectRayDirection(); // group: RayT float [[rn]] RayTMin(); float [[rn]] RayTCurrent(); // group: Raytracing uint System Values uint [[rn]] PrimitiveIndex(); uint [[rn]] InstanceID(); uint [[rn]] InstanceIndex(); uint [[rn]] GeometryIndex(); uint [[rn]] HitKind(); uint [[rn]] RayFlags(); // group: Ray Transforms float<3,4> [[rn]] ObjectToWorld(); float<3,4> [[rn]] WorldToObject(); float<3,4> [[rn]] ObjectToWorld3x4(); float<3,4> [[rn]] WorldToObject3x4(); float<4,3> [[rn]] ObjectToWorld4x3(); float<4,3> [[rn]] WorldToObject4x3(); // Packed dot products with accumulate: $type3 [[rn]] dot4add_u8packed(in uint a, in $type1 b, in uint c); $type3 [[rn]] dot4add_i8packed(in uint a, in $type1 b, in int c); $type3 [[rn]] dot2add(in float16_t<2> a, in $type1 b, in float c); // Unpacking intrinsics int16_t<4> [[rn]] unpack_s8s16(in p32i8 pk); uint16_t<4> [[rn]] unpack_u8u16(in p32u8 pk); int<4> [[rn]] unpack_s8s32(in p32i8 pk); uint<4> [[rn]] unpack_u8u32(in p32u8 pk); // Packing intrinsics p32i8 [[rn]] pack_s8(in any_int16or32<4> v); p32u8 [[rn]] pack_u8(in any_int16or32<4> v); p32i8 [[rn]] pack_clamp_s8(in sint16or32_only<4> v); p32u8 [[rn]] pack_clamp_u8(in sint16or32_only<4> v); // Mesh shader intrinsics: void [[]] SetMeshOutputCounts(in uint numVertices, in uint numPrimitives); // Amplification shader intrinsics: void [[]] DispatchMesh(in uint threadGroupCountX, in uint threadGroupCountY, in uint threadGroupCountZ, in udt meshPayload); // Return true if the current lane is a helper lane bool [[ro]] IsHelperLane(); // HL Op for allocating ray query object that default constructor uses uint [[hidden]] AllocateRayQuery(in uint flags); resource [[hidden]] CreateResourceFromHeap(in uint index); // Replacement for vector logical &&, ||, and ternary conditional operators, // For use when HLSL changes to support short-circuiting and only scalar // conditions to maintain clarity. $match<1, 0> bool<> [[rn]] and(in any<> x, in $type1 y); $match<1, 0> bool<> [[rn]] or(in any<> x, in $type1 y); $type2 [[rn]] select(in bool<> cond, in $match<1, 2> any<> t, in $type2 f); $type2 [[rn]] select(in bool cond, in any_sampler t, in $type2 f); // Work Graph intrinsics void [[]] Barrier(in uint MemoryTypeFlags, in uint SemanticFlags); void [[]] Barrier(in NodeRecordOrUAV o, in uint SemanticFlags); uint [[]] GetRemainingRecursionLevels(); } namespace // SPIRV Change Starts namespace VkIntrinsics { u64 [[]] ReadClock(in uint scope); $funcT [[ro]] RawBufferLoad(in u64 addr); $funcT [[ro]] RawBufferLoad(in u64 addr, in uint alignment); void [[]] RawBufferStore(in u64 addr, in $funcT value); void [[]] RawBufferStore(in u64 addr, in $funcT value, in uint alignment); void [[]] ext_execution_mode(in uint mode, ...); void [[]] ext_execution_mode_id(in uint mode, ...); } namespace // SPIRV Change Ends namespace StreamMethods { void [[]] Append(in $match<-1, 1> void x) : stream_append; void [[]] RestartStrip() : stream_restart; } namespace namespace Texture1DMethods { // Use float for DXIL don't support f16 on CalcLOD. float [[ro]] CalculateLevelOfDetail(in any_sampler s, in float<1> x) : tex1d_t_calc_lod; float [[ro]] CalculateLevelOfDetailUnclamped(in any_sampler s, in float<1> x) : tex1d_t_calc_lod_unclamped; void [[]] GetDimensions(in uint x, out uint_only width, out $type2 levels) : resinfo_uint; void [[]] GetDimensions(in uint x, out float_like width, out $type2 levels) : resinfo; void [[]] GetDimensions(out uint_only width) : resinfo_o; void [[]] GetDimensions(out float_like width) : resinfo_o; $classT [[ro]] Load(in int<2> x) : tex1d_t_load; $classT [[ro]] Load(in int<2> x, in int<1> o) : tex1d_t_load_o; $classT [[]] Load(in int<2> x, in int<1> o, out uint_only status) : tex1d_t_load_o_s; $classT [[ro]] Sample(in sampler s, in float<1> x) : tex1d_t; $classT [[ro]] Sample(in sampler s, in float<1> x, in int<1> o) : tex1d_t_o; $classT [[ro]] SampleBias(in sampler s, in float<1> x, in float bias) : tex1d_t_bias; $classT [[ro]] SampleBias(in sampler s, in float<1> x, in float bias, in int<1> o) : tex1d_t_bias_o; float_like [[ro]] SampleCmp(in sampler_cmp s, in float<1> x, in float compareValue) : tex1d_t_comp; float_like [[ro]] SampleCmp(in sampler_cmp s, in float<1> x, in float compareValue, in int<1> o) : tex1d_t_comp_o; float_like [[ro]] SampleCmpBias(in sampler_cmp s, in float<1> x, in float compareValue, in float bias) : tex1d_t_comp_bias; float_like [[ro]] SampleCmpBias(in sampler_cmp s, in float<1> x, in float compareValue, in float bias, in int<1> o) : tex1d_t_comp_bias_o; float_like [[ro]] SampleCmpGrad(in sampler_cmp s, in float<1> x, in float compareValue, in $type2 ddx, in $type2 ddy) : tex1d_t_comp_dd; float_like [[ro]] SampleCmpGrad(in sampler_cmp s, in float<1> x, in float compareValue, in $type2 ddx, in $type2 ddy, in int<1> o) : tex1d_t_comp_dd_o; float_like [[ro]] SampleCmpLevel(in sampler_cmp s, in float<1> x, in float compareValue, in float lod); float_like [[ro]] SampleCmpLevel(in sampler_cmp s, in float<1> x, in float compareValue, in float lod, in int<1> o); float_like [[ro]] SampleCmpLevelZero(in sampler_cmp s, in float<1> x, in float compareValue) : tex1d_t_comp_lz; float_like [[ro]] SampleCmpLevelZero(in sampler_cmp s, in float<1> x, in float compareValue, in int<1> o) : tex1d_t_comp_lz_o; $classT [[ro]] SampleGrad(in sampler s, in float<1> x, in $type2 ddx, in $type2 ddy) : tex1d_t_dd; $classT [[ro]] SampleGrad(in sampler s, in float<1> x, in $type2 ddx, in $type2 ddy, in int<1> o) : tex1d_t_dd_o; $classT [[ro]] SampleLevel(in sampler s, in float<1> x, in float lod) : tex1d_t_lod; $classT [[ro]] SampleLevel(in sampler s, in float<1> x, in float lod, in int<1> o) : tex1d_t_lod_o; $classT [[ro]] Sample(in sampler s, in float<1> x, in int<1> o, in float clamp) : tex1d_t_o_cl; $classT [[]] Sample(in sampler s, in float<1> x, in int<1> o, in float clamp, out uint_only status) : tex1d_t_o_cl_s; float_like [[ro]] SampleCmp(in sampler_cmp s, in float<1> x, in float compareValue, in int<1> o, in float clamp) : tex1d_t_comp_o_cl; float_like [[]] SampleCmp(in sampler_cmp s, in float<1> x, in float compareValue, in int<1> o, in float clamp, out uint_only status) : tex1d_t_comp_o_cl_s; float_like [[ro]] SampleCmpBias(in sampler_cmp s, in float<1> x, in float compareValue, in float bias, in int<1> o, in float clamp) : tex1d_t_comp_bias_o_cl; float_like [[]] SampleCmpBias(in sampler_cmp s, in float<1> x, in float compareValue, in float bias, in int<1> o, in float clamp, out uint_only status) : tex1d_t_comp_bias_o_cl_s; float_like [[ro]] SampleCmpGrad(in sampler_cmp s, in float<1> x, in float compareValue, in $type2 ddx, in $type2 ddy, in int<1> o, in float clamp) : tex1d_t_comp_dd_o_cl; float_like [[]] SampleCmpGrad(in sampler_cmp s, in float<1> x, in float compareValue, in $type2 ddx, in $type2 ddy, in int<1> o, in float clamp, out uint_only status) : tex1d_t_comp_dd_o_cl_s; float_like [[]] SampleCmpLevel(in sampler_cmp s, in float<1> x, in float compareValue, in float lod, in int<1> o, out uint_only status); float_like [[]] SampleCmpLevelZero(in sampler_cmp s, in float<1> x, in float compareValue, in int<1> o, out uint_only status) : tex1d_t_comp_o_s; $classT [[]] SampleLevel(in sampler s, in float<1> x, in float lod, in int<1> o, out uint_only status) : tex1d_t_lod_o_s; $classT [[ro]] SampleBias(in sampler s, in float<1> x, in float bias, in int<1> o, in float clamp) : tex1d_t_bias_o_cl; $classT [[]] SampleBias(in sampler s, in float<1> x, in float bias, in int<1> o, in float clamp, out uint_only status) : tex1d_t_bias_o_cl_s; $classT [[]] SampleGrad(in sampler s, in float<1> x, in $type2 ddx, in $type2 ddy, in int<1> o, in float clamp) : tex1d_t_dd_o_cl; $classT [[]] SampleGrad(in sampler s, in float<1> x, in $type2 ddx, in $type2 ddy, in int<1> o, in float clamp, out uint_only status) : tex1d_t_dd_o_cl_s; } namespace namespace Texture1DArrayMethods { float [[ro]] CalculateLevelOfDetail(in any_sampler s, in float<1> x) : tex1d_t_calc_lod_array; float [[ro]] CalculateLevelOfDetailUnclamped(in any_sampler s, in float<1> x) : tex1d_t_calc_lod_unclamped_array; void [[]] GetDimensions(in uint x, out uint_only width, out $type2 elements, out $type2 levels) : resinfo_uint; void [[]] GetDimensions(in uint x, out float_like width, out $type2 elements, out $type2 levels) : resinfo; void [[]] GetDimensions(out uint_only width, out $type1 elements) : resinfo_uint_o; void [[]] GetDimensions(out float_like width, out $type1 elements) : resinfo_o; $classT [[ro]] Load(in int<3> x) : tex1d_t_load_array; $classT [[ro]] Load(in int<3> x, in int<1> o) : tex1d_t_load_array_o; $classT [[]] Load(in int<3> x, in int<1> o, out uint_only status) : tex1d_t_load_array_o_s; $classT [[ro]] Sample(in sampler s, in float<2> x) : tex1d_t_array; $classT [[ro]] Sample(in sampler s, in float<2> x, in int<1> o) : tex1d_t_array_o; $classT [[ro]] SampleBias(in sampler s, in float<2> x, in float bias) : tex1d_t_bias_array; $classT [[ro]] SampleBias(in sampler s, in float<2> x, in float bias, in int<1> o) : tex1d_t_bias_array_o; float_like [[ro]] SampleCmp(in sampler_cmp s, in float<2> x, in float compareValue) : tex1d_t_comp_array; float_like [[ro]] SampleCmp(in sampler_cmp s, in float<2> x, in float compareValue, in int<1> o) : tex1d_t_comp_array_o; float_like [[ro]] SampleCmpBias(in sampler_cmp s, in float<2> x, in float compareValue, in float bias) : tex1d_t_comp_bias_array; float_like [[ro]] SampleCmpBias(in sampler_cmp s, in float<2> x, in float compareValue, in float bias, in int<1> o) : tex1d_t_comp_bias_array_o; float_like [[ro]] SampleCmpGrad(in sampler_cmp s, in float<2> x, in float compareValue, in $match<2, 2> float<1> ddx, in $match<2, 2> float<1> ddy) : tex1d_t_comp_dd_array; float_like [[ro]] SampleCmpGrad(in sampler_cmp s, in float<2> x, in float compareValue, in $match<2, 2> float<1> ddx, in $match<2, 2> float<1> ddy, in int<1> o) : tex1d_t_comp_dd_array_o; float_like [[ro]] SampleCmpLevel(in sampler_cmp s, in float<2> x, in float compareValue, in float lod); float_like [[ro]] SampleCmpLevel(in sampler_cmp s, in float<2> x, in float compareValue, in float lod, in int<1> o); float_like [[ro]] SampleCmpLevelZero(in sampler_cmp s, in float<2> x, in float compareValue) : tex1d_t_comp_lz_array; float_like [[ro]] SampleCmpLevelZero(in sampler_cmp s, in float<2> x, in float compareValue, in int<1> o) : tex1d_t_comp_lz_array_o; $classT [[ro]] SampleGrad(in sampler s, in float<2> x, in $match<2, 2> float<1> ddx, in $match<2, 2> float<1> ddy) : tex1d_t_dd_array; $classT [[ro]] SampleGrad(in sampler s, in float<2> x, in $match<2, 2> float<1> ddx, in $match<2, 2> float<1> ddy, in int<1> o) : tex1d_t_dd_array_o; $classT [[ro]] SampleLevel(in sampler s, in float<2> x, in float lod) : tex1d_t_lod_array; $classT [[ro]] SampleLevel(in sampler s, in float<2> x, in float lod, in int<1> o) : tex1d_t_lod_array_o; $classT [[ro]] Sample(in sampler s, in float<2> x, in int<1> o, in float clamp) : tex1d_t_array_o_cl; $classT [[]] Sample(in sampler s, in float<2> x, in int<1> o, in float clamp, out uint_only status) : tex1d_t_array_o_cl_s; float_like [[ro]] SampleCmp(in sampler_cmp s, in float<2> x, in float compareValue, in int<1> o, in float clamp) : tex1d_t_comp_array_o_cl; float_like [[]] SampleCmp(in sampler_cmp s, in float<2> x, in float compareValue, in int<1> o, in float clamp, out uint_only status) : tex1d_t_comp_array_o_cl_s; float_like [[ro]] SampleCmpBias(in sampler_cmp s, in float<2> x, in float compareValue, in float bias, in int<1> o, in float clamp) : tex1d_t_comp_bias_array_o_cl; float_like [[]] SampleCmpBias(in sampler_cmp s, in float<2> x, in float compareValue, in float bias, in int<1> o, in float clamp, out uint_only status) : tex1d_t_comp_bias_array_o_cl_s; float_like [[ro]] SampleCmpGrad(in sampler_cmp s, in float<2> x, in float compareValue, in $match<2, 2> float<1> ddx, in $match<2, 2> float<1> ddy, in int<1> o, in float clamp) : tex1d_t_comp_dd_array_o_cl; float_like [[]] SampleCmpGrad(in sampler_cmp s, in float<2> x, in float compareValue, in $match<2, 2> float<1> ddx, in $match<2, 2> float<1> ddy, in int<1> o, in float clamp, out uint_only status) : tex1d_t_comp_dd_array_o_cl_s; float_like [[]] SampleCmpLevel(in sampler_cmp s, in float<2> x, in float compareValue, in float lod, in int<1> o, out uint_only status); float_like [[]] SampleCmpLevelZero(in sampler_cmp s, in float<2> x, in float compareValue, in int<1> o, out uint_only status) : tex1d_t_comp_array_o_s; $classT [[]] SampleLevel(in sampler s, in float<2> x, in float lod, in int<1> o, out uint_only status) : tex1d_t_lod_array_o_s; $classT [[ro]] SampleBias(in sampler s, in float<2> x, in float bias, in int<1> o, in float clamp) : tex1d_t_bias_array_o_cl; $classT [[]] SampleBias(in sampler s, in float<2> x, in float bias, in int<1> o, in float clamp, out uint_only status) : tex1d_t_bias_array_o_cl_s; $classT [[ro]] SampleGrad(in sampler s, in float<2> x, in $match<2, 2> float<1> ddx, in $match<2, 2> float<1> ddy, in int<1> o, in float clamp) : tex1d_t_dd_array_o_cl; $classT [[]] SampleGrad(in sampler s, in float<2> x, in $match<2, 2> float<1> ddx, in $match<2, 2> float<1> ddy, in int<1> o, in float clamp, out uint_only status) : tex1d_t_dd_array_o_cl_s; } namespace namespace Texture2DMethods { float [[ro]] CalculateLevelOfDetail(in any_sampler s, in float<2> x) : tex2d_t_calc_lod; float [[ro]] CalculateLevelOfDetailUnclamped(in any_sampler s, in float<2> x) : tex2d_t_calc_lod_unclamped; $match<0, -1> void<4> [[ro]] Gather(in sampler s, in float<2> x) : tex2d_t_gather; $match<0, -1> void<4> [[ro]] Gather(in sampler s, in float<2> x, in int<2> o) : tex2d_t_gather_o; $match<0, -1> void<4> [[ro]] GatherAlpha(in sampler s, in float<2> x) : tex2d_t_gather_alpha; $match<0, -1> void<4> [[ro]] GatherAlpha(in sampler s, in float<2> x, in int<2> o) : tex2d_t_gather_alpha_o; $match<0, -1> void<4> [[ro]] GatherAlpha(in sampler s, in float<2> x, in int<2> o1, in int<2> o2, in int<2> o3, in int<2> o4) : tex2d_t_gather_alpha_o4; $match<0, -1> void<4> [[ro]] GatherBlue(in sampler s, in float<2> x) : tex2d_t_gather_blue; $match<0, -1> void<4> [[ro]] GatherBlue(in sampler s, in float<2> x, in int<2> o) : tex2d_t_gather_blue_o; $match<0, -1> void<4> [[ro]] GatherBlue(in sampler s, in float<2> x, in int<2> o1, in int<2> o2, in int<2> o3, in int<2> o4) : tex2d_t_gather_blue_o4; $match<0, -1> void<4> [[ro]] GatherCmp(in sampler_cmp s, in float<2> x, in float compareValue) : tex2d_t_gather_comp; $match<0, -1> void<4> [[ro]] GatherCmp(in sampler_cmp s, in float<2> x, in float compareValue, in int<2> o) : tex2d_t_gather_comp_o; $match<0, -1> void<4> [[ro]] GatherCmpAlpha(in sampler_cmp s, in float<2> x, in float compareValue) : tex2d_t_gather_comp_alpha; $match<0, -1> void<4> [[ro]] GatherCmpAlpha(in sampler_cmp s, in float<2> x, in float compareValue, in int<2> o) : tex2d_t_gather_comp_alpha_o; $match<0, -1> void<4> [[ro]] GatherCmpAlpha(in sampler_cmp s, in float<2> x, in float compareValue, in int<2> o1, in int<2> o2, in int<2> o3, in int<2> o4) : tex2d_t_gather_comp_alpha_o4; $match<0, -1> void<4> [[ro]] GatherCmpBlue(in sampler_cmp s, in float<2> x, in float compareValue) : tex2d_t_gather_comp_blue; $match<0, -1> void<4> [[ro]] GatherCmpBlue(in sampler_cmp s, in float<2> x, in float compareValue, in int<2> o) : tex2d_t_gather_comp_blue_o; $match<0, -1> void<4> [[ro]] GatherCmpBlue(in sampler_cmp s, in float<2> x, in float compareValue, in int<2> o1, in int<2> o2, in int<2> o3, in int<2> o4) : tex2d_t_gather_comp_blue_o4; $match<0, -1> void<4> [[ro]] GatherCmpGreen(in sampler_cmp s, in float<2> x, in float compareValue) : tex2d_t_gather_comp_green; $match<0, -1> void<4> [[ro]] GatherCmpGreen(in sampler_cmp s, in float<2> x, in float compareValue, in int<2> o) : tex2d_t_gather_comp_green_o; $match<0, -1> void<4> [[ro]] GatherCmpGreen(in sampler_cmp s, in float<2> x, in float compareValue, in int<2> o1, in int<2> o2, in int<2> o3, in int<2> o4) : tex2d_t_gather_comp_green_o4; $match<0, -1> void<4> [[ro]] GatherCmpRed(in sampler_cmp s, in float<2> x, in float compareValue) : tex2d_t_gather_comp_red; $match<0, -1> void<4> [[ro]] GatherCmpRed(in sampler_cmp s, in float<2> x, in float compareValue, in int<2> o) : tex2d_t_gather_comp_red_o; $match<0, -1> void<4> [[ro]] GatherCmpRed(in sampler_cmp s, in float<2> x, in float compareValue, in int<2> o1, in int<2> o2, in int<2> o3, in int<2> o4) : tex2d_t_gather_comp_red_o4; $match<0, -1> void<4> [[ro]] GatherGreen(in sampler s, in float<2> x) : tex2d_t_gather_green; $match<0, -1> void<4> [[ro]] GatherGreen(in sampler s, in float<2> x, in int<2> o) : tex2d_t_gather_green_o; $match<0, -1> void<4> [[ro]] GatherGreen(in sampler s, in float<2> x, in int<2> o1, in int<2> o2, in int<2> o3, in int<2> o4) : tex2d_t_gather_green_o4; $match<0, -1> void<4> [[ro]] GatherRed(in sampler s, in float<2> x) : tex2d_t_gather_red; $match<0, -1> void<4> [[ro]] GatherRed(in sampler s, in float<2> x, in int<2> o) : tex2d_t_gather_red_o; $match<0, -1> void<4> [[ro]] GatherRed(in sampler s, in float<2> x, in int<2> o1, in int<2> o2, in int<2> o3, in int<2> o4) : tex2d_t_gather_red_o4; void [[]] GetDimensions(in uint x, out uint_only width, out $type2 height, out $type2 levels) : resinfo_uint; void [[]] GetDimensions(in uint x, out float_like width, out $type2 height, out $type2 levels) : resinfo; void [[]] GetDimensions(out uint_only width, out $type1 height) : resinfo_uint_o; void [[]] GetDimensions(out float_like width, out $type1 height) : resinfo_o; $classT [[ro]] Load(in int<3> x) : tex2d_t_load; $classT [[ro]] Load(in int<3> x, in int<2> o) : tex2d_t_load_o; $classT [[]] Load(in int<3> x, in int<2> o, out uint_only status) : tex2d_t_load_o_s; $classT [[ro]] Sample(in sampler s, in float<2> x) : tex2d_t; $classT [[ro]] Sample(in sampler s, in float<2> x, in int<2> o) : tex2d_t_o; $classT [[ro]] SampleBias(in sampler s, in float<2> x, in float bias) : tex2d_t_bias; $classT [[ro]] SampleBias(in sampler s, in float<2> x, in float bias, in int<2> o) : tex2d_t_bias_o; float_like [[ro]] SampleCmp(in sampler_cmp s, in float<2> x, in float compareValue) : tex2d_t_comp; float_like [[ro]] SampleCmp(in sampler_cmp s, in float<2> x, in float compareValue, in int<2> o) : tex2d_t_comp_o; float_like [[ro]] SampleCmpBias(in sampler_cmp s, in float<2> x, in float compareValue, in float bias) : tex2d_t_comp_bias; float_like [[ro]] SampleCmpBias(in sampler_cmp s, in float<2> x, in float compareValue, in float bias, in int<2> o) : tex2d_t_comp_bias_o; float_like [[ro]] SampleCmpGrad(in sampler_cmp s, in float<2> x, in float compareValue, in $type2 ddx, in $type2 ddy) : tex2d_t_comp_dd; float_like [[ro]] SampleCmpGrad(in sampler_cmp s, in float<2> x, in float compareValue, in $type2 ddx, in $type2 ddy, in int<2> o) : tex2d_t_comp_dd_o; float_like [[ro]] SampleCmpLevel(in sampler_cmp s, in float<2> x, in float compareValue, in float lod); float_like [[ro]] SampleCmpLevel(in sampler_cmp s, in float<2> x, in float compareValue, in float lod, in int<2> o); float_like [[ro]] SampleCmpLevelZero(in sampler_cmp s, in float<2> x, in float compareValue) : tex2d_t_comp_lz; float_like [[ro]] SampleCmpLevelZero(in sampler_cmp s, in float<2> x, in float compareValue, in int<2> o) : tex2d_t_comp_lz_o; $classT [[ro]] SampleGrad(in sampler s, in float<2> x, in $type2 ddx, in $type2 ddy) : tex2d_t_dd; $classT [[ro]] SampleGrad(in sampler s, in float<2> x, in $type2 ddx, in $type2 ddy, in int<2> o) : tex2d_t_dd_o; $classT [[ro]] SampleLevel(in sampler s, in float<2> x, in float lod) : tex2d_t_lod; $classT [[ro]] SampleLevel(in sampler s, in float<2> x, in float lod, in int<2> o) : tex2d_t_lod_o; $classT [[ro]] Sample(in sampler s, in float<2> x, in int<2> o, in float clamp) : tex2d_t_o_cl; $classT [[]] Sample(in sampler s, in float<2> x, in int<2> o, in float clamp, out uint_only status) : tex2d_t_o_cl_s; float_like [[ro]] SampleCmp(in sampler_cmp s, in float<2> x, in float compareValue, in int<2> o, in float clamp) : tex2d_t_comp_o_cl; float_like [[]] SampleCmp(in sampler_cmp s, in float<2> x, in float compareValue, in int<2> o, in float clamp, out uint_only status) : tex2d_t_comp_o_cl_s; float_like [[ro]] SampleCmpBias(in sampler_cmp s, in float<2> x, in float compareValue, in float bias, in int<2> o, in float clamp) : tex2d_t_comp_bias_o_cl; float_like [[]] SampleCmpBias(in sampler_cmp s, in float<2> x, in float compareValue, in float bias, in int<2> o, in float clamp, out uint_only status) : tex2d_t_comp_bias_o_cl_s; float_like [[ro]] SampleCmpGrad(in sampler_cmp s, in float<2> x, in float compareValue, in $type2 ddx, in $type2 ddy, in int<2> o, in float clamp) : tex2d_t_comp_dd_o_cl; float_like [[]] SampleCmpGrad(in sampler_cmp s, in float<2> x, in float compareValue, in $type2 ddx, in $type2 ddy, in int<2> o, in float clamp, out uint_only status) : tex2d_t_comp_dd_o_cl_s; float_like [[]] SampleCmpLevel(in sampler_cmp s, in float<2> x, in float compareValue, in float lod, in int<2> o, out uint_only status); float_like [[]] SampleCmpLevelZero(in sampler_cmp s, in float<2> x, in float compareValue, in int<2> o, out uint_only status) : tex2d_t_comp_o_s; $classT [[]] SampleLevel(in sampler s, in float<2> x, in float lod, in int<2> o, out uint_only status) : tex2d_t_lod_o_s; $classT [[ro]] SampleBias(in sampler s, in float<2> x, in float bias, in int<2> o, in float clamp) : tex2d_t_bias_o_cl; $classT [[]] SampleBias(in sampler s, in float<2> x, in float bias, in int<2> o, in float clamp, out uint_only status) : tex2d_t_bias_o_cl_s; $classT [[ro]] SampleGrad(in sampler s, in float<2> x, in $type2 ddx, in $type2 ddy, in int<2> o, in float clamp) : tex2d_t_dd_o_cl; $classT [[]] SampleGrad(in sampler s, in float<2> x, in $type2 ddx, in $type2 ddy, in int<2> o, in float clamp, out uint_only status) : tex2d_t_dd_o_cl_s; $match<0, -1> void<4> [[]] Gather(in sampler s, in float<2> x, in int<2> o, out uint_only status) : tex2d_t_gather_o_s; $match<0, -1> void<4> [[]] GatherRed(in sampler s, in float<2> x, in int<2> o, out uint_only status) : tex2d_t_gather_red_o_s; $match<0, -1> void<4> [[]] GatherRed(in sampler s, in float<2> x, in int<2> o1, in int<2> o2, in int<2> o3, in int<2> o4, out uint_only status) : tex2d_t_gather_red_o4_s; $match<0, -1> void<4> [[]] GatherGreen(in sampler s, in float<2> x, in int<2> o, out uint_only status) : tex2d_t_gather_green_o_s; $match<0, -1> void<4> [[]] GatherGreen(in sampler s, in float<2> x, in int<2> o1, in int<2> o2, in int<2> o3, in int<2> o4, out uint_only status) : tex2d_t_gather_green_o4_s; $match<0, -1> void<4> [[]] GatherBlue(in sampler s, in float<2> x, in int<2> o, out uint_only status) : tex2d_t_gather_blue_o_s; $match<0, -1> void<4> [[]] GatherBlue(in sampler s, in float<2> x, in int<2> o1, in int<2> o2, in int<2> o3, in int<2> o4, out uint_only status) : tex2d_t_gather_blue_o4_s; $match<0, -1> void<4> [[]] GatherAlpha(in sampler s, in float<2> x, in int<2> o, out uint_only status) : tex2d_t_gather_alpha_o_s; $match<0, -1> void<4> [[]] GatherAlpha(in sampler s, in float<2> x, in int<2> o1, in int<2> o2, in int<2> o3, in int<2> o4, out uint_only status) : tex2d_t_gather_alpha_o4_s; $match<0, -1> void<4> [[]] GatherCmp(in sampler_cmp s, in float<2> x, in float compareValue, in int<2> o, out uint_only status) : tex2d_t_gather_comp_o_s; $match<0, -1> void<4> [[]] GatherCmpRed(in sampler_cmp s, in float<2> x, in float compareValue, in int<2> o, out uint_only status) : tex2d_t_gather_comp_red_o_s; $match<0, -1> void<4> [[]] GatherCmpGreen(in sampler_cmp s, in float<2> x, in float compareValue, in int<2> o, out uint_only status) : tex2d_t_gather_comp_green_o_s; $match<0, -1> void<4> [[]] GatherCmpBlue(in sampler_cmp s, in float<2> x, in float compareValue, in int<2> o, out uint_only status) : tex2d_t_gather_comp_blue_o_s; $match<0, -1> void<4> [[]] GatherCmpAlpha(in sampler_cmp s, in float<2> x, in float compareValue, in int<2> o, out uint_only status) : tex2d_t_gather_comp_alpha_o_s; $match<0, -1> void<4> [[]] GatherCmpRed(in sampler_cmp s, in float<2> x, in float compareValue, in int<2> o1, in int<2> o2, in int<2> o3, in int<2> o4, out uint_only status) : tex2d_t_gather_comp_red_o4_s; $match<0, -1> void<4> [[]] GatherCmpGreen(in sampler_cmp s, in float<2> x, in float compareValue, in int<2> o1, in int<2> o2, in int<2> o3, in int<2> o4, out uint_only status) : tex2d_t_gather_comp_green_o4_s; $match<0, -1> void<4> [[]] GatherCmpBlue(in sampler_cmp s, in float<2> x, in float compareValue, in int<2> o1, in int<2> o2, in int<2> o3, in int<2> o4, out uint_only status) : tex2d_t_gather_comp_blue_o4_s; $match<0, -1> void<4> [[]] GatherCmpAlpha(in sampler_cmp s, in float<2> x, in float compareValue, in int<2> o1, in int<2> o2, in int<2> o3, in int<2> o4, out uint_only status) : tex2d_t_gather_comp_alpha_o4_s; $match<0, -1> void<4> [[ro]] GatherRaw(in sampler s, in float<2> x); $match<0, -1> void<4> [[ro]] GatherRaw(in sampler s, in float<2> x, in int<2> o); $match<0, -1> void<4> [[]] GatherRaw(in sampler s, in float<2> x, in int<2> o, out uint_only status); } namespace namespace Texture2DMSMethods { void [[]] GetDimensions(out uint_only width, out $type1 height, out $type2 samples) : resinfo_uint_o; void [[]] GetDimensions(out float_like width, out $type1 height, out $type2 samples) : resinfo_o; float_like<2> [[ro]] GetSamplePosition(in int s) : samplepos; $classT [[]] Load(in int<2> x, in int s) : texture2d_ms; $classT [[]] Load(in int<2> x, in int s, in int<2> o) : texture2d_ms_o; $classT [[]] Load(in int<2> x, in int s, in int<2> o, out uint_only status) : texture2d_ms_o_s; } namespace namespace Texture2DArrayMethods { float [[ro]] CalculateLevelOfDetail(in any_sampler s, in float<2> x) : tex2d_t_calc_lod_array; float [[ro]] CalculateLevelOfDetailUnclamped(in any_sampler s, in float<2> x) : tex2d_t_calc_lod_unclamped_array; $match<0, -1> void<4> [[ro]] Gather(in sampler s, in float<3> x) : tex2d_t_gather_array; $match<0, -1> void<4> [[ro]] Gather(in sampler s, in float<3> x, in int<2> o) : tex2d_t_gather_array_o; $match<0, -1> void<4> [[ro]] GatherAlpha(in sampler s, in float<3> x) : tex2d_t_gather_alpha_array; $match<0, -1> void<4> [[ro]] GatherAlpha(in sampler s, in float<3> x, in int<2> o) : tex2d_t_gather_alpha_array_o; $match<0, -1> void<4> [[ro]] GatherAlpha(in sampler s, in float<3> x, in int<2> o1, in int<2> o2, in int<2> o3, in int<2> o4) : tex2d_t_gather_alpha_array_o4; $match<0, -1> void<4> [[ro]] GatherBlue(in sampler s, in float<3> x) : tex2d_t_gather_blue_array; $match<0, -1> void<4> [[ro]] GatherBlue(in sampler s, in float<3> x, in int<2> o) : tex2d_t_gather_blue_array_o; $match<0, -1> void<4> [[ro]] GatherBlue(in sampler s, in float<3> x, in int<2> o1, in int<2> o2, in int<2> o3, in int<2> o4) : tex2d_t_gather_blue_array_o4; $match<0, -1> void<4> [[ro]] GatherCmp(in sampler_cmp s, in float<3> x, in float compareValue) : tex2d_t_gather_comp_array; $match<0, -1> void<4> [[ro]] GatherCmp(in sampler_cmp s, in float<3> x, in float compareValue, in int<2> o) : tex2d_t_gather_comp_array_o; $match<0, -1> void<4> [[ro]] GatherCmpAlpha(in sampler_cmp s, in float<3> x, in float compareValue) : tex2d_t_gather_comp_alpha_array; $match<0, -1> void<4> [[ro]] GatherCmpAlpha(in sampler_cmp s, in float<3> x, in float compareValue, in int<2> o) : tex2d_t_gather_comp_alpha_array_o; $match<0, -1> void<4> [[ro]] GatherCmpAlpha(in sampler_cmp s, in float<3> x, in float compareValue, in int<2> o1, in int<2> o2, in int<2> o3, in int<2> o4) : tex2d_t_gather_comp_alpha_array_o4; $match<0, -1> void<4> [[ro]] GatherCmpBlue(in sampler_cmp s, in float<3> x, in float compareValue) : tex2d_t_gather_comp_blue_array; $match<0, -1> void<4> [[ro]] GatherCmpBlue(in sampler_cmp s, in float<3> x, in float compareValue, in int<2> o) : tex2d_t_gather_comp_blue_array_o; $match<0, -1> void<4> [[ro]] GatherCmpBlue(in sampler_cmp s, in float<3> x, in float compareValue, in int<2> o1, in int<2> o2, in int<2> o3, in int<2> o4) : tex2d_t_gather_comp_blue_array_o4; $match<0, -1> void<4> [[ro]] GatherCmpGreen(in sampler_cmp s, in float<3> x, in float compareValue) : tex2d_t_gather_comp_green_array; $match<0, -1> void<4> [[ro]] GatherCmpGreen(in sampler_cmp s, in float<3> x, in float compareValue, in int<2> o) : tex2d_t_gather_comp_green_array_o; $match<0, -1> void<4> [[ro]] GatherCmpGreen(in sampler_cmp s, in float<3> x, in float compareValue, in int<2> o1, in int<2> o2, in int<2> o3, in int<2> o4) : tex2d_t_gather_comp_green_array_o4; $match<0, -1> void<4> [[ro]] GatherCmpRed(in sampler_cmp s, in float<3> x, in float compareValue) : tex2d_t_gather_comp_red_array; $match<0, -1> void<4> [[ro]] GatherCmpRed(in sampler_cmp s, in float<3> x, in float compareValue, in int<2> o) : tex2d_t_gather_comp_red_array_o; $match<0, -1> void<4> [[ro]] GatherCmpRed(in sampler_cmp s, in float<3> x, in float compareValue, in int<2> o1, in int<2> o2, in int<2> o3, in int<2> o4) : tex2d_t_gather_comp_red_array_o4; $match<0, -1> void<4> [[ro]] GatherGreen(in sampler s, in float<3> x) : tex2d_t_gather_green_array; $match<0, -1> void<4> [[ro]] GatherGreen(in sampler s, in float<3> x, in int<2> o) : tex2d_t_gather_green_array_o; $match<0, -1> void<4> [[ro]] GatherGreen(in sampler s, in float<3> x, in int<2> o1, in int<2> o2, in int<2> o3, in int<2> o4) : tex2d_t_gather_green_array_o4; $match<0, -1> void<4> [[ro]] GatherRed(in sampler s, in float<3> x) : tex2d_t_gather_red_array; $match<0, -1> void<4> [[ro]] GatherRed(in sampler s, in float<3> x, in int<2> o) : tex2d_t_gather_red_array_o; $match<0, -1> void<4> [[ro]] GatherRed(in sampler s, in float<3> x, in int<2> o1, in int<2> o2, in int<2> o3, in int<2> o4) : tex2d_t_gather_red_array_o4; void [[]] GetDimensions(in uint x, out uint_only width, out $type2 height, out $type2 elements, out $type2 levels) : resinfo_uint; void [[]] GetDimensions(in uint x, out float_like width, out $type2 height, out $type2 elements, out $type2 levels) : resinfo; void [[]] GetDimensions(out uint_only width, out $type1 height, out $type1 elements) : resinfo_uint_o; void [[]] GetDimensions(out float_like width, out $type1 height, out $type1 elements) : resinfo_o; $classT [[ro]] Load(in int<4> x) : tex2d_t_load_array; $classT [[ro]] Load(in int<4> x, in int<2> o) : tex2d_t_load_array_o; $classT [[]] Load(in int<4> x, in int<2> o, out uint_only status) : tex2d_t_load_array_o_s; $classT [[ro]] Sample(in sampler s, in float<3> x) : tex2d_t_array; $classT [[ro]] Sample(in sampler s, in float<3> x, in int<2> o) : tex2d_t_array_o; $classT [[ro]] SampleBias(in sampler s, in float<3> x, in float bias) : tex2d_t_bias_array; $classT [[ro]] SampleBias(in sampler s, in float<3> x, in float bias, in int<2> o) : tex2d_t_bias_array_o; float_like [[ro]] SampleCmp(in sampler_cmp s, in float<3> x, in float compareValue) : tex2d_t_comp_array; float_like [[ro]] SampleCmp(in sampler_cmp s, in float<3> x, in float compareValue, in int<2> o) : tex2d_t_comp_array_o; float_like [[ro]] SampleCmpBias(in sampler_cmp s, in float<3> x, in float compareValue, in float bias) : tex2d_t_comp_bias_array; float_like [[ro]] SampleCmpBias(in sampler_cmp s, in float<3> x, in float compareValue, in float bias, in int<2> o) : tex2d_t_comp_bias_array_o; float_like [[ro]] SampleCmpGrad(in sampler_cmp s, in float<3> x, in float compareValue, in $match<2, 2> float<2> ddx, in $match<2, 2> float<2> ddy) : tex2d_t_comp_dd_array; float_like [[ro]] SampleCmpGrad(in sampler_cmp s, in float<3> x, in float compareValue, in $match<2, 2> float<2> ddx, in $match<2, 2> float<2> ddy, in int<2> o) : tex2d_t_comp_dd_array_o; float_like [[ro]] SampleCmpLevel(in sampler_cmp s, in float<3> x, in float compareValue, in float lod); float_like [[ro]] SampleCmpLevel(in sampler_cmp s, in float<3> x, in float compareValue, in float lod, in int<2> o); float_like [[ro]] SampleCmpLevelZero(in sampler_cmp s, in float<3> x, in float compareValue) : tex2d_t_comp_lz_array; float_like [[ro]] SampleCmpLevelZero(in sampler_cmp s, in float<3> x, in float compareValue, in int<2> o) : tex2d_t_comp_lz_array_o; $classT [[ro]] SampleGrad(in sampler s, in float<3> x, in $match<2, 2> float<2> ddx, in $match<2, 2> float<2> ddy) : tex2d_t_dd_array; $classT [[ro]] SampleGrad(in sampler s, in float<3> x, in $match<2, 2> float<2> ddx, in $match<2, 2> float<2> ddy, in int<2> o) : tex2d_t_dd_array_o; $classT [[ro]] SampleLevel(in sampler s, in float<3> x, in float lod) : tex2d_t_lod_array; $classT [[ro]] SampleLevel(in sampler s, in float<3> x, in float lod, in int<2> o) : tex2d_t_lod_array_o; $classT [[ro]] Sample(in sampler s, in float<3> x, in int<2> o, in float clamp) : tex2d_t_array_o_cl; $classT [[]] Sample(in sampler s, in float<3> x, in int<2> o, in float clamp, out uint_only status) : tex2d_t_array_o_cl_s; float_like [[ro]] SampleCmp(in sampler_cmp s, in float<3> x, in float compareValue, in int<2> o, in float clamp) : tex2d_t_comp_array_o_cl; float_like [[]] SampleCmp(in sampler_cmp s, in float<3> x, in float compareValue, in int<2> o, in float clamp, out uint_only status) : tex2d_t_comp_array_o_cl_s; float_like [[ro]] SampleCmpBias(in sampler_cmp s, in float<3> x, in float compareValue, in float bias, in int<2> o, in float clamp) : tex2d_t_comp_bias_array_o_cl; float_like [[]] SampleCmpBias(in sampler_cmp s, in float<3> x, in float compareValue, in float bias, in int<2> o, in float clamp, out uint_only status) : tex2d_t_comp_bias_array_o_cl_s; float_like [[ro]] SampleCmpGrad(in sampler_cmp s, in float<3> x, in float compareValue, in $match<2, 2> float<2> ddx, in $match<2, 2> float<2> ddy, in int<2> o, in float clamp) : tex2d_t_comp_dd_array_o_cl; float_like [[]] SampleCmpGrad(in sampler_cmp s, in float<3> x, in float compareValue, in $match<2, 2> float<2> ddx, in $match<2, 2> float<2> ddy, in int<2> o, in float clamp, out uint_only status) : tex2d_t_comp_dd_array_o_cl_s; float_like [[]] SampleCmpLevel(in sampler_cmp s, in float<3> x, in float compareValue, in float lod, in int<2> o, out uint_only status); float_like [[]] SampleCmpLevelZero(in sampler_cmp s, in float<3> x, in float compareValue, in int<2> o, out uint_only status) : tex2d_t_comp_array_o_s; $classT [[]] SampleLevel(in sampler s, in float<3> x, in float lod, in int<2> o, out uint_only status) : tex2d_t_lod_array_o_s; $classT [[ro]] SampleBias(in sampler s, in float<3> x, in float bias, in int<2> o, in float clamp) : tex2d_t_bias_array_o_cl; $classT [[]] SampleBias(in sampler s, in float<3> x, in float bias, in int<2> o, in float clamp, out uint_only status) : tex2d_t_bias_array_o_cl_s; $classT [[ro]] SampleGrad(in sampler s, in float<3> x, in $match<2, 2> float<2> ddx, in $match<2, 2> float<2> ddy, in int<2> o, in float clamp) : tex2d_t_dd_array_o_cl; $classT [[]] SampleGrad(in sampler s, in float<3> x, in $match<2, 2> float<2> ddx, in $match<2, 2> float<2> ddy, in int<2> o, in float clamp, out uint_only status) : tex2d_t_dd_array_o_cl_s; $match<0, -1> void<4> [[]] Gather(in sampler s, in float<3> x, in int<2> o, out uint_only status) : tex2d_t_gather_array_o_s; $match<0, -1> void<4> [[]] GatherRed(in sampler s, in float<3> x, in int<2> o, out uint_only status) : tex2d_t_gather_red_array_o_s; $match<0, -1> void<4> [[]] GatherRed(in sampler s, in float<3> x, in int<2> o1, in int<2> o2, in int<2> o3, in int<2> o4, out uint_only status) : tex2d_t_gather_red_array_o4_s; $match<0, -1> void<4> [[]] GatherGreen(in sampler s, in float<3> x, in int<2> o, out uint_only status) : tex2d_t_gather_green_array_o_s; $match<0, -1> void<4> [[]] GatherGreen(in sampler s, in float<3> x, in int<2> o1, in int<2> o2, in int<2> o3, in int<2> o4, out uint_only status) : tex2d_t_gather_green_array_o4_s; $match<0, -1> void<4> [[]] GatherBlue(in sampler s, in float<3> x, in int<2> o, out uint_only status) : tex2d_t_gather_blue_array_o_s; $match<0, -1> void<4> [[]] GatherBlue(in sampler s, in float<3> x, in int<2> o1, in int<2> o2, in int<2> o3, in int<2> o4, out uint_only status) : tex2d_t_gather_blue_array_o4_s; $match<0, -1> void<4> [[]] GatherAlpha(in sampler s, in float<3> x, in int<2> o, out uint_only status) : tex2d_t_gather_alpha_array_o_s; $match<0, -1> void<4> [[]] GatherAlpha(in sampler s, in float<3> x, in int<2> o1, in int<2> o2, in int<2> o3, in int<2> o4, out uint_only status) : tex2d_t_gather_alpha_array_o4_s; $match<0, -1> void<4> [[]] GatherCmp(in sampler_cmp s, in float<3> x, in float compareValue, in int<2> o, out uint_only status) : tex2d_t_gather_comp_array_o_s; $match<0, -1> void<4> [[]] GatherCmpRed(in sampler_cmp s, in float<3> x, in float compareValue, in int<2> o, out uint_only status) : tex2d_t_gather_comp_red_array_o_s; $match<0, -1> void<4> [[]] GatherCmpGreen(in sampler_cmp s, in float<3> x, in float compareValue, in int<2> o, out uint_only status) : tex2d_t_gather_comp_green_array_o_s; $match<0, -1> void<4> [[]] GatherCmpBlue(in sampler_cmp s, in float<3> x, in float compareValue, in int<2> o, out uint_only status) : tex2d_t_gather_comp_blue_array_o_s; $match<0, -1> void<4> [[]] GatherCmpAlpha(in sampler_cmp s, in float<3> x, in float compareValue, in int<2> o, out uint_only status) : tex2d_t_gather_comp_alpha_array_o_s; $match<0, -1> void<4> [[]] GatherCmpRed(in sampler_cmp s, in float<3> x, in float compareValue, in int<2> o1, in int<2> o2, in int<2> o3, in int<2> o4, out uint_only status) : tex2d_t_gather_comp_red_array_o4_s; $match<0, -1> void<4> [[]] GatherCmpGreen(in sampler_cmp s, in float<3> x, in float compareValue, in int<2> o1, in int<2> o2, in int<2> o3, in int<2> o4, out uint_only status) : tex2d_t_gather_comp_green_array_o4_s; $match<0, -1> void<4> [[]] GatherCmpBlue(in sampler_cmp s, in float<3> x, in float compareValue, in int<2> o1, in int<2> o2, in int<2> o3, in int<2> o4, out uint_only status) : tex2d_t_gather_comp_blue_array_o4_s; $match<0, -1> void<4> [[]] GatherCmpAlpha(in sampler_cmp s, in float<3> x, in float compareValue, in int<2> o1, in int<2> o2, in int<2> o3, in int<2> o4, out uint_only status) : tex2d_t_gather_comp_alpha_array_o4_s; $match<0, -1> void<4> [[ro]] GatherRaw(in sampler s, in float<3> x); $match<0, -1> void<4> [[ro]] GatherRaw(in sampler s, in float<3> x, in int<2> o); $match<0, -1> void<4> [[]] GatherRaw(in sampler s, in float<3> x, in int<2> o, out uint_only status); } namespace namespace Texture2DArrayMSMethods { void [[]] GetDimensions(out uint_only width, out $type1 height, out $type1 elements, out $type1 samples) : resinfo_uint_o; void [[]] GetDimensions(out float_like width, out $type1 height, out $type1 elements, out $type1 samples) : resinfo_o; float_like<2> [[ro]] GetSamplePosition(in int s) : samplepos; $classT [[ro]] Load(in int<3> x, in int s) : texture2darray_ms; $classT [[ro]] Load(in int<3> x, in int s, in int<2> o) : texture2darray_ms_o; $classT [[]] Load(in int<3> x, in int s, in int<2> o, out uint_only status) : texture2darray_ms_o_s; } namespace namespace Texture3DMethods { float [[ro]] CalculateLevelOfDetail(in sampler s, in float<3> x) : tex3d_t_calc_lod; float [[ro]] CalculateLevelOfDetailUnclamped(in sampler s, in float<3> x) : tex3d_t_calc_lod_unclamped; void [[]] GetDimensions(in uint x, out uint_only width, out $type2 height, out $type2 depth, out $type2 levels) : resinfo_uint; void [[]] GetDimensions(in uint x, out float_like width, out $type2 height, out $type2 depth, out $type2 levels) : resinfo; void [[]] GetDimensions(out uint_only width, out $type1 height, out $type1 depth) : resinfo_uint_o; void [[]] GetDimensions(out float_like width, out $type1 height, out $type1 depth) : resinfo_o; $classT [[ro]] Load(in int<4> x) : tex3d_t_load; $classT [[ro]] Load(in int<4> x, in int<3> o) : tex3d_t_load_o; $classT [[]] Load(in int<4> x, in int<3> o, out uint_only status) : tex3d_t_load_o_s; $classT [[ro]] Sample(in sampler s, in float<3> x) : tex3d_t; $classT [[ro]] Sample(in sampler s, in float<3> x, in int<3> o) : tex3d_t_o; $classT [[ro]] SampleBias(in sampler s, in float<3> x, in float bias) : tex3d_t_bias; $classT [[ro]] SampleBias(in sampler s, in float<3> x, in float bias, in int<3> o) : tex3d_t_bias_o; $classT [[ro]] SampleGrad(in sampler s, in float<3> x, in $type2 ddx, in $type2 ddy) : tex3d_t_dd; $classT [[ro]] SampleGrad(in sampler s, in float<3> x, in $type2 ddx, in $type2 ddy, in int<3> o) : tex3d_t_dd_o; $classT [[ro]] SampleLevel(in sampler s, in float<3> x, in float lod) : tex3d_t_lod; $classT [[ro]] SampleLevel(in sampler s, in float<3> x, in float lod, in int<3> o) : tex3d_t_lod_o; $classT [[ro]] Sample(in sampler s, in float<3> x, in int<3> o, in float clamp) : tex3d_t_o_cl; $classT [[]] Sample(in sampler s, in float<3> x, in int<3> o, in float clamp, out uint_only status) : tex3d_t_o_cl_s; $classT [[]] SampleLevel(in sampler s, in float<3> x, in float lod, in int<3> o, out uint_only status) : tex3d_t_lod_o_s; $classT [[ro]] SampleBias(in sampler s, in float<3> x, in float bias, in int<3> o, in float clamp) : tex3d_t_bias_o_cl; $classT [[]] SampleBias(in sampler s, in float<3> x, in float bias, in int<3> o, in float clamp, out uint_only status) : tex3d_t_bias_o_cl_s; $classT [[ro]] SampleGrad(in sampler s, in float<3> x, in $type2 ddx, in $type2 ddy, in int<3> o, in float clamp) : tex3d_t_dd_o_cl; $classT [[]] SampleGrad(in sampler s, in float<3> x, in $type2 ddx, in $type2 ddy, in int<3> o, in float clamp, out uint_only status) : tex3d_t_dd_o_cl_s; } namespace namespace TextureCUBEMethods { float [[ro]] CalculateLevelOfDetail(in any_sampler s, in float<3> x) : texcube_t_calc_lod; float [[ro]] CalculateLevelOfDetailUnclamped(in any_sampler s, in float<3> x) : texcube_t_calc_lod_unclamped; $match<0, -1> void<4> [[ro]] Gather(in sampler s, in float<3> x) : texcube_t_gather; $match<0, -1> void<4> [[ro]] GatherAlpha(in sampler s, in float<3> x) : texcube_t_gather_alpha; $match<0, -1> void<4> [[ro]] GatherBlue(in sampler s, in float<3> x) : texcube_t_gather_blue; $match<0, -1> void<4> [[ro]] GatherCmp(in sampler_cmp s, in float<3> x, in float compareValue) : texcube_t_gather_comp; $match<0, -1> void<4> [[ro]] GatherCmpAlpha(in sampler_cmp s, in float<3> x, in float compareValue) : texcube_t_gather_comp_alpha; $match<0, -1> void<4> [[ro]] GatherCmpBlue(in sampler_cmp s, in float<3> x, in float compareValue) : texcube_t_gather_comp_blue; $match<0, -1> void<4> [[ro]] GatherCmpGreen(in sampler_cmp s, in float<3> x, in float compareValue) : texcube_t_gather_comp_green; $match<0, -1> void<4> [[ro]] GatherCmpRed(in sampler_cmp s, in float<3> x, in float compareValue) : texcube_t_gather_comp_red; $match<0, -1> void<4> [[ro]] GatherGreen(in sampler s, in float<3> x) : texcube_t_gather_green; $match<0, -1> void<4> [[ro]] GatherRed(in sampler s, in float<3> x) : texcube_t_gather_red; void [[]] GetDimensions(in uint x, out uint_only width, out $type2 height, out $type2 levels) : resinfo_uint; void [[]] GetDimensions(in uint x, out float_like width, out $type2 height, out $type2 levels) : resinfo; void [[]] GetDimensions(out uint_only width, out $type1 height) : resinfo_uint_o; void [[]] GetDimensions(out float_like width, out $type1 height) : resinfo_o; $classT [[ro]] Sample(in sampler s, in float<3> x) : texcube_t; $classT [[ro]] SampleBias(in sampler s, in float<3> x, in float bias) : texcube_t_bias; float_like [[ro]] SampleCmp(in sampler_cmp s, in float<3> x, in float c) : texcube_t_comp; float_like [[ro]] SampleCmpBias(in sampler_cmp s, in float<3> x, in float compareValue, in float bias) : texcube_t_comp_bias; float_like [[ro]] SampleCmpGrad(in sampler_cmp s, in float<3> x, in float compareValue, in $type2 ddx, in $type2 ddy) : texcube_t_comp_dd; float_like [[ro]] SampleCmpLevel(in sampler_cmp s, in float<3> x, in float c, in float lod); float_like [[ro]] SampleCmpLevelZero(in sampler_cmp s, in float<3> x, in float c) : texcube_t_comp_lz; $classT [[ro]] SampleGrad(in sampler s, in float<3> x, in $type2 ddx, in $type2 ddy) : texcube_t_dd; $classT [[ro]] SampleLevel(in sampler s, in float<3> x, in float lod) : texcube_t_lod; $classT [[ro]] Sample(in sampler s, in float<3> x, in float clamp) : texcube_t_cl; $classT [[]] Sample(in sampler s, in float<3> x, in float clamp, out uint_only status) : texcube_t_cl_s; float_like [[ro]] SampleCmp(in sampler_cmp s, in float<3> x, in float compareValue, in float clamp) : texcube_t_comp_cl; float_like [[]] SampleCmp(in sampler_cmp s, in float<3> x, in float compareValue, in float clamp, out uint_only status) : texcube_t_comp_cl_s; float_like [[ro]] SampleCmpBias(in sampler_cmp s, in float<3> x, in float compareValue, in float bias, in float clamp) : texcube_t_comp_bias_cl; float_like [[]] SampleCmpBias(in sampler_cmp s, in float<3> x, in float compareValue, in float bias, in float clamp, out uint_only status) : texcube_t_comp_bias_cl_s; float_like [[ro]] SampleCmpGrad(in sampler_cmp s, in float<3> x, in float compareValue, in $type2 ddx, in $type2 ddy, in float clamp) : texcube_t_comp_dd_o_cl; float_like [[]] SampleCmpGrad(in sampler_cmp s, in float<3> x, in float compareValue, in $type2 ddx, in $type2 ddy, in float clamp, out uint_only status) : texcube_t_comp_dd_o_cl_s; float_like [[]] SampleCmpLevel(in sampler_cmp s, in float<3> x, in float compareValue, in float lod, out uint_only status); float_like [[]] SampleCmpLevelZero(in sampler_cmp s, in float<3> x, in float compareValue, out uint_only status) : texcube_t_comp_s; $classT [[]] SampleLevel(in sampler s, in float<3> x, in float lod, out uint_only status) : texcube_t_lod_s; $classT [[ro]] SampleBias(in sampler s, in float<3> x, in float bias, in float clamp) : texcube_t_bias_cl; $classT [[]] SampleBias(in sampler s, in float<3> x, in float bias, in float clamp, out uint_only status) : texcube_t_bias_cl_s; $classT [[ro]] SampleGrad(in sampler s, in float<3> x, in $type2 ddx, in $type2 ddy, in float clamp) : texcube_t_dd_cl; $classT [[]] SampleGrad(in sampler s, in float<3> x, in $type2 ddx, in $type2 ddy, in float clamp, out uint_only status) : texcube_t_dd_cl_s; $match<0, -1> void<4> [[]] Gather(in sampler s, in float<3> x, out uint_only status) : texcube_t_gather_s; $match<0, -1> void<4> [[]] GatherRed(in sampler s, in float<3> x, out uint_only status) : texcube_t_gather_red_s; $match<0, -1> void<4> [[]] GatherGreen(in sampler s, in float<3> x, out uint_only status) : texcube_t_gather_green_s; $match<0, -1> void<4> [[]] GatherBlue(in sampler s, in float<3> x, out uint_only status) : texcube_t_gather_blue_s; $match<0, -1> void<4> [[]] GatherAlpha(in sampler s, in float<3> x, out uint_only status) : texcube_t_gather_alpha_s; $match<0, -1> void<4> [[]] GatherCmp(in sampler_cmp s, in float<3> x, in float compareValue, out uint_only status) : texcube_t_gather_comp_s; $match<0, -1> void<4> [[]] GatherCmpRed(in sampler_cmp s, in float<3> x, in float compareValue, out uint_only status) : texcube_t_gather_comp_red_s; $match<0, -1> void<4> [[]] GatherCmpGreen(in sampler_cmp s, in float<3> x, in float compareValue, out uint_only status) : texcube_t_gather_comp_green_s; $match<0, -1> void<4> [[]] GatherCmpBlue(in sampler_cmp s, in float<3> x, in float compareValue, out uint_only status) : texcube_t_gather_comp_blue_s; $match<0, -1> void<4> [[]] GatherCmpAlpha(in sampler_cmp s, in float<3> x, in float compareValue, out uint_only status) : texcube_t_gather_comp_alpha_s; } namespace namespace TextureCUBEArrayMethods { float [[ro]] CalculateLevelOfDetail(in any_sampler s, in float<3> x) : texcube_t_calc_lod_array; float [[ro]] CalculateLevelOfDetailUnclamped(in any_sampler s, in float<3> x) : texcube_t_calc_lod_unclamped_array; $match<0, -1> void<4> [[ro]] Gather(in sampler s, in float<4> x) : texcube_t_gather_array; $match<0, -1> void<4> [[ro]] GatherAlpha(in sampler s, in float<4> x) : texcube_t_gather_alpha_array; $match<0, -1> void<4> [[ro]] GatherBlue(in sampler s, in float<4> x) : texcube_t_gather_blue_array; $match<0, -1> void<4> [[ro]] GatherCmp(in sampler_cmp s, in float<4> x, in float compareValue) : texcube_t_gather_comp_array; $match<0, -1> void<4> [[ro]] GatherCmpAlpha(in sampler_cmp s, in float<4> x, in float compareValue) : texcube_t_gather_comp_alpha_array; $match<0, -1> void<4> [[ro]] GatherCmpBlue(in sampler_cmp s, in float<4> x, in float compareValue) : texcube_t_gather_comp_blue_array; $match<0, -1> void<4> [[ro]] GatherCmpGreen(in sampler_cmp s, in float<4> x, in float compareValue) : texcube_t_gather_comp_green_array; $match<0, -1> void<4> [[ro]] GatherCmpRed(in sampler_cmp s, in float<4> x, in float compareValue) : texcube_t_gather_comp_red_array; $match<0, -1> void<4> [[ro]] GatherGreen(in sampler s, in float<4> x) : texcube_t_gather_green_array; $match<0, -1> void<4> [[ro]] GatherRed(in sampler s, in float<4> x) : texcube_t_gather_red_array; void [[]] GetDimensions(in uint x, out uint_only width, out $type2 height, out $type2 elements, out $type2 levels) : resinfo_uint; void [[]] GetDimensions(in uint x, out float_like width, out $type2 height, out $type2 elements, out $type2 levels) : resinfo; void [[]] GetDimensions(out uint_only width, out $type1 height, out $type1 elements) : resinfo_uint_o; void [[]] GetDimensions(out float_like width, out $type1 height, out $type1 elements) : resinfo_o; $classT [[ro]] Sample(in sampler s, in float<4> x) : texcube_t_array; $classT [[ro]] SampleBias(in sampler s, in float<4> x, in float bias) : texcube_t_bias_array; float_like [[ro]] SampleCmp(in sampler_cmp s, in float<4> x, in float c) : texcube_t_comp_array; float_like [[ro]] SampleCmpBias(in sampler_cmp s, in float<4> x, in float compareValue, in float bias) : texcube_t_comp_bias_array; float_like [[ro]] SampleCmpGrad(in sampler_cmp s, in float<4> x, in float compareValue, in $match<2, 2> float<3> ddx, in $match<2, 2> float<3> ddy) : texcube_t_comp_dd_array; float_like [[ro]] SampleCmpLevel(in sampler_cmp s, in float<4> x, in float c, in float lod); float_like [[ro]] SampleCmpLevelZero(in sampler_cmp s, in float<4> x, in float c) : texcube_t_comp_lz_array; $classT [[ro]] SampleGrad(in sampler s, in float<4> x, in $match<2, 2> float<3> ddx, in $match<2, 2> float<3> ddy) : texcube_t_dd_array; $classT [[ro]] SampleLevel(in sampler s, in float<4> x, in float lod) : texcube_t_lod_array; $classT [[ro]] Sample(in sampler s, in float<4> x, in float clamp) : texcube_t_array_cl; $classT [[]] Sample(in sampler s, in float<4> x, in float clamp, out uint_only status) : texcube_t_array_cl_s; float_like [[ro]] SampleCmp(in sampler_cmp s, in float<4> x, in float compareValue, in float clamp) : texcube_t_comp_array_cl; float_like [[]] SampleCmp(in sampler_cmp s, in float<4> x, in float compareValue, in float clamp, out uint_only status) : texcube_t_comp_array_cl_s; float_like [[ro]] SampleCmpBias(in sampler_cmp s, in float<4> x, in float compareValue, in float bias, in float clamp) : texcube_t_comp_bias_array_cl; float_like [[]] SampleCmpBias(in sampler_cmp s, in float<4> x, in float compareValue, in float bias, in float clamp, out uint_only status) : texcube_t_comp_bias_array_cl_s; float_like [[ro]] SampleCmpGrad(in sampler_cmp s, in float<4> x, in float compareValue, in $match<2, 2> float<3> ddx, in $match<2, 2> float<3> ddy, in float clamp) : texcube_t_comp_dd_array_cl; float_like [[]] SampleCmpGrad(in sampler_cmp s, in float<4> x, in float compareValue, in $match<2, 2> float<3> ddx, in $match<2, 2> float<3> ddy, in float clamp, out uint_only status) : texcube_t_comp_dd_array_cl_s; float_like [[]] SampleCmpLevel(in sampler_cmp s, in float<4> x, in float compareValue, in float lod, out uint_only status); float_like [[]] SampleCmpLevelZero(in sampler_cmp s, in float<4> x, in float compareValue, out uint_only status) : texcube_t_comp_array_s; $classT [[]] SampleLevel(in sampler s, in float<4> x, in float lod, out uint_only status) : texcube_t_lod_array_s; $classT [[ro]] SampleBias(in sampler s, in float<4> x, in float bias, in float clamp) : texcube_t_bias_array_cl; $classT [[]] SampleBias(in sampler s, in float<4> x, in float bias, in float clamp, out uint_only status) : texcube_t_bias_array_cl_s; $classT [[ro]] SampleGrad(in sampler s, in float<4> x, in $match<2, 2> float<3> ddx, in $match<2, 2> float<3> ddy, in float clamp) : texcube_t_dd_array_cl; $classT [[]] SampleGrad(in sampler s, in float<4> x, in $match<2, 2> float<3> ddx, in $match<2, 2> float<3> ddy, in float clamp, out uint_only status) : texcube_t_dd_array_cl_s; $match<0, -1> void<4> [[]] Gather(in sampler s, in float<4> x, out uint_only status) : texcube_t_gather_array_s; $match<0, -1> void<4> [[]] GatherRed(in sampler s, in float<4> x, out uint_only status) : texcube_t_gather_red_array_s; $match<0, -1> void<4> [[]] GatherGreen(in sampler s, in float<4> x, out uint_only status) : texcube_t_gather_green_array_s; $match<0, -1> void<4> [[]] GatherBlue(in sampler s, in float<4> x, out uint_only status) : texcube_t_gather_blue_array_s; $match<0, -1> void<4> [[]] GatherAlpha(in sampler s, in float<4> x, out uint_only status) : texcube_t_gather_alpha_array_s; $match<0, -1> void<4> [[]] GatherCmp(in sampler_cmp s, in float<4> x, in float compareValue, out uint_only status) : texcube_t_gather_comp_array_s; $match<0, -1> void<4> [[]] GatherCmpRed(in sampler_cmp s, in float<4> x, in float compareValue, out uint_only status) : texcube_t_gather_comp_red_array_s; $match<0, -1> void<4> [[]] GatherCmpGreen(in sampler_cmp s, in float<4> x, in float compareValue, out uint_only status) : texcube_t_gather_comp_green_array_s; $match<0, -1> void<4> [[]] GatherCmpBlue(in sampler_cmp s, in float<4> x, in float compareValue, out uint_only status) : texcube_t_gather_comp_blue_array_s; $match<0, -1> void<4> [[]] GatherCmpAlpha(in sampler_cmp s, in float<4> x, in float compareValue, out uint_only status) : texcube_t_gather_comp_alpha_array_s; } namespace namespace BufferMethods { void [[]] GetDimensions(out uint_only width) : bufinfo; $classT [[ro]] Load(in int<1> x) : buffer_load; $classT [[]] Load(in int<1> x, out uint_only status) : buffer_load_s; } namespace namespace RWTexture1DMethods { void [[]] GetDimensions(out uint_only width) : resinfo_o; void [[]] GetDimensions(out float_like width) : resinfo_o; $classT [[ro]] Load(in int<1> x) : rwtex1d_load; $classT [[]] Load(in int<1> x, out uint_only status) : rwtex1d_load_s; } namespace namespace RWTexture1DArrayMethods { void [[]] GetDimensions(out uint_only width, out $type1 elements) : resinfo_uint_o; void [[]] GetDimensions(out float_like width, out $type1 elements) : resinfo_o; $classT [[ro]] Load(in int<2> x) : rwtex1d_load_array; $classT [[]] Load(in int<2> x, out uint_only status) : rwtex1d_load_array_s; } namespace namespace RWTexture2DMethods { void [[]] GetDimensions(out uint_only width, out $type1 height) : resinfo_uint_o; void [[]] GetDimensions(out float_like width, out $type1 height) : resinfo_o; $classT [[ro]] Load(in int<2> x) : rwtex2d_load; $classT [[]] Load(in int<2> x, out uint_only status) : rwtex2d_load_s; } namespace namespace RWTexture2DArrayMethods { void [[]] GetDimensions(out uint_only width, out $type1 height, out $type1 elements) : resinfo_uint_o; void [[]] GetDimensions(out float_like width, out $type1 height, out $type1 elements) : resinfo_o; $classT [[ro]] Load(in int<3> x) : rwtex2d_load_array; $classT [[]] Load(in int<3> x, out uint_only status) : rwtex2d_load_array_s; } namespace namespace RWTexture2DMSMethods { void [[]] GetDimensions(out uint_only width, out $type1 height, out $type2 samples); void [[]] GetDimensions(out float_like width, out $type1 height, out $type2 samples); float_like<2> [[ro]] GetSamplePosition(in int s); $classT [[ro]] Load(in int<2> x, in int s); $classT [[]] Load(in int<2> x, in int s, out uint_only status); } namespace namespace RWTexture2DMSArrayMethods { void [[]] GetDimensions(out uint_only width, out $type1 height, out $type1 elements, out $type1 samples); void [[]] GetDimensions(out float_like width, out $type1 height, out $type1 elements, out $type1 samples); float_like<2> [[ro]] GetSamplePosition(in int s); $classT [[ro]] Load(in int<3> x, in int s); $classT [[]] Load(in int<3> x, in int s, out uint_only status); } namespace namespace RWTexture3DMethods { void [[]] GetDimensions(out uint_only width, out $type1 height, out $type1 depth) : resinfo_uint_o; void [[]] GetDimensions(out float_like width, out $type1 height, out $type1 depth) : resinfo_o; $classT [[ro]] Load(in int<3> x) : rwtex3d_load; $classT [[]] Load(in int<3> x, out uint_only status) : rwtex3d_load_s; } namespace namespace RWBufferMethods { void [[]] GetDimensions(out uint_only width) : bufinfo; $classT [[ro]] Load(in int x) : rwbuffer_load; $classT [[]] Load(in int x, out uint_only status) : rwbuffer_load_s; } namespace namespace ByteAddressBufferMethods { void [[]] GetDimensions(out uint_only width) : bufinfo; $funcT [[ro]] Load(in uint byteOffset) : byteaddress_load; uint<2> [[ro]] Load2(in uint byteOffset) : byteaddress_load; uint<3> [[ro]] Load3(in uint byteOffset) : byteaddress_load; uint<4> [[ro]] Load4(in uint byteOffset) : byteaddress_load; $funcT [[]] Load(in uint byteOffset, out uint_only status) : byteaddress_load_s; uint<2> [[]] Load2(in uint byteOffset, out uint_only status) : byteaddress_load_s; uint<3> [[]] Load3(in uint byteOffset, out uint_only status) : byteaddress_load_s; uint<4> [[]] Load4(in uint byteOffset, out uint_only status) : byteaddress_load_s; } namespace namespace RWByteAddressBufferMethods { void [[]] GetDimensions(out uint_only width) : bufinfo; $funcT [[ro]] Load(in uint byteOffset) : byteaddress_load; uint<2> [[ro]] Load2(in uint byteOffset) : byteaddress_load; uint<3> [[ro]] Load3(in uint byteOffset) : byteaddress_load; uint<4> [[ro]] Load4(in uint byteOffset) : byteaddress_load; $funcT [[]] Load(in uint byteOffset, out uint_only status) : byteaddress_load_s; uint<2> [[]] Load2(in uint byteOffset, out uint_only status) : byteaddress_load_s; uint<3> [[]] Load3(in uint byteOffset, out uint_only status) : byteaddress_load_s; uint<4> [[]] Load4(in uint byteOffset, out uint_only status) : byteaddress_load_s; void [[]] Store(in uint byteOffset, in $funcT value) : byteaddress_store; void [[]] Store2(in uint byteOffset, in uint<2> value) : byteaddress_store; void [[]] Store3(in uint byteOffset, in uint<3> value) : byteaddress_store; void [[]] Store4(in uint byteOffset, in uint<4> value) : byteaddress_store; // 64-bit integer interlocks void [[]] InterlockedAdd64(in uint byteOffset, in u64 value); void [[]] InterlockedAdd64(in uint byteOffset, in u64 value, out any_int64 original) : interlockedadd_immediate; void [[unsigned_op=InterlockedUMin,overload=1]] InterlockedMin64(in uint byteOffset, in any_int64 value) : interlockedmin; void [[unsigned_op=InterlockedUMin,overload=1]] InterlockedMin64(in uint byteOffset, in any_int64 value, out any_int64 original) : interlockedmin_immediate; void [[unsigned_op=InterlockedUMax,overload=1]] InterlockedMax64(in uint byteOffset, in any_int64 value) : interlockedmax; void [[unsigned_op=InterlockedUMax,overload=1]] InterlockedMax64(in uint byteOffset, in any_int64 value, out any_int64 original) : interlockedmax_immediate; void [[]] InterlockedAnd64(in uint byteOffset, in u64 value); void [[]] InterlockedAnd64(in uint byteOffset, in u64 value, out any_int64 original) : interlockedand_immediate; void [[]] InterlockedOr64(in uint byteOffset, in u64 value); void [[]] InterlockedOr64(in uint byteOffset, in u64 value, out any_int64 original) : interlockedor_immediate; void [[]] InterlockedXor64(in uint byteOffset, in u64 value); void [[]] InterlockedXor64(in uint byteOffset, in u64 value, out any_int64 original) : interlockedxor_immediate; void [[]] InterlockedCompareStore64(in uint byteOffset, in u64 compare, in u64 value); void [[]] InterlockedExchange64(in uint byteOffset, in any_int64 value, out any_int64 original); void [[]] InterlockedCompareExchange64(in uint byteOffset, in u64 compare, in u64 value, out any_int64 original); // floating point interlocks void [[]] InterlockedExchangeFloat(in uint byteOffest, in float value, out float original); void [[]] InterlockedCompareStoreFloatBitwise(in uint byteOffest, in float compare, in float value); void [[]] InterlockedCompareExchangeFloatBitwise(in uint byteOffest, in float compare, in float value, out float original); // 32-bit integer interlocks void [[]] InterlockedAdd(in uint byteOffset, in uint value); void [[]] InterlockedAdd(in uint byteOffset, in uint value, out uint original) : interlockedadd_immediate; void [[unsigned_op=InterlockedUMin,overload=1]] InterlockedMin(in uint byteOffset, in any_int32 value) : interlockedmin; void [[unsigned_op=InterlockedUMin,overload=1]] InterlockedMin(in uint byteOffset, in any_int32 value, out uint original) : interlockedmin_immediate; void [[unsigned_op=InterlockedUMax,overload=1]] InterlockedMax(in uint byteOffset, in any_int32 value) : interlockedmax; void [[unsigned_op=InterlockedUMax,overload=1]] InterlockedMax(in uint byteOffset, in any_int32 value, out uint original) : interlockedmax_immediate; void [[]] InterlockedAnd(in uint byteOffset, in uint value); void [[]] InterlockedAnd(in uint byteOffset, in uint value, out uint original) : interlockedand_immediate; void [[]] InterlockedOr(in uint byteOffset, in uint value); void [[]] InterlockedOr(in uint byteOffset, in uint value, out uint original) : interlockedor_immediate; void [[]] InterlockedXor(in uint byteOffset, in uint value); void [[]] InterlockedXor(in uint byteOffset, in uint value, out uint original) : interlockedxor_immediate; void [[]] InterlockedCompareStore(in uint byteOffset, in uint compare, in uint value); void [[]] InterlockedExchange(in uint byteOffset, in uint value, out uint original); void [[]] InterlockedCompareExchange(in uint byteOffset, in uint compare, in uint value, out uint original); } namespace namespace StructuredBufferMethods { void [[]] GetDimensions(out uint_only count, out uint_only stride) : bufinfo; $classT [[ro]] Load(in int x) : structured_buffer_load; $classT [[]] Load(in int x, out uint_only status) : structured_buffer_load_s; } namespace namespace RWStructuredBufferMethods { void [[]] GetDimensions(out uint_only count, out uint_only stride) : bufinfo; uint [[]] IncrementCounter() : structuredbuffer_inc; uint [[]] DecrementCounter() : structuredbuffer_dec; $classT [[ro]] Load(in int x) : rwstructured_buffer_load; $classT [[]] Load(in int x, out uint_only status) : rwstructured_buffer_load_s; } namespace namespace AppendStructuredBufferMethods { void [[]] GetDimensions(out uint_only count, out uint_only stride) : bufinfo; void [[]] Append(in $match<-1,0> void value ) : structuredbuffer_append; } namespace namespace ConsumeStructuredBufferMethods { void [[]] GetDimensions(out uint_only count, out uint_only stride) : bufinfo; $classT [[]] Consume() : structuredbuffer_consume; } namespace namespace FeedbackTexture2DMethods { void [[]] WriteSamplerFeedback(in Texture2D t, in sampler s, in float<2> x); void [[]] WriteSamplerFeedback(in Texture2D t, in sampler s, in float<2> x, in float clamp); void [[]] WriteSamplerFeedbackBias(in Texture2D t, in sampler s, in float<2> x, in float bias); void [[]] WriteSamplerFeedbackBias(in Texture2D t, in sampler s, in float<2> x, in float bias, in float clamp); void [[]] WriteSamplerFeedbackGrad(in Texture2D t, in sampler s, in float<2> x, in float<2> ddx, in float<2> ddy); void [[]] WriteSamplerFeedbackGrad(in Texture2D t, in sampler s, in float<2> x, in float<2> ddx, in float<2> ddy, in float clamp); void [[]] WriteSamplerFeedbackLevel(in Texture2D t, in sampler s, in float<2> x, in float lod); } namespace namespace FeedbackTexture2DArrayMethods { void [[]] WriteSamplerFeedback(in Texture2DArray t, in sampler s, in float<3> x); void [[]] WriteSamplerFeedback(in Texture2DArray t, in sampler s, in float<3> x, in float clamp); void [[]] WriteSamplerFeedbackBias(in Texture2DArray t, in sampler s, in float<3> x, in float bias); void [[]] WriteSamplerFeedbackBias(in Texture2DArray t, in sampler s, in float<3> x, in float bias, in float clamp); void [[]] WriteSamplerFeedbackGrad(in Texture2DArray t, in sampler s, in float<3> x, in float<2> ddx, in float<2> ddy); void [[]] WriteSamplerFeedbackGrad(in Texture2DArray t, in sampler s, in float<3> x, in float<2> ddx, in float<2> ddy, in float clamp); void [[]] WriteSamplerFeedbackLevel(in Texture2DArray t, in sampler s, in float<3> x, in float lod); } namespace namespace RayQueryMethods { void [[]] TraceRayInline(in acceleration_struct AccelerationStructure, in uint RayFlags, in uint InstanceInclusionMask, in ray_desc Ray); bool [[]] Proceed(); void [[]] Abort(); void [[]] CommitNonOpaqueTriangleHit(); void [[]] CommitProceduralPrimitiveHit(in float t); uint [[ro]] CommittedStatus(); uint [[ro]] CandidateType(); float<3,4> [[ro]] CandidateObjectToWorld3x4(); float<4,3> [[ro]] CandidateObjectToWorld4x3(); float<3,4> [[ro]] CandidateWorldToObject3x4(); float<4,3> [[ro]] CandidateWorldToObject4x3(); float<3,4> [[ro]] CommittedObjectToWorld3x4(); float<4,3> [[ro]] CommittedObjectToWorld4x3(); float<3,4> [[ro]] CommittedWorldToObject3x4(); float<4,3> [[ro]] CommittedWorldToObject4x3(); bool [[ro]] CandidateProceduralPrimitiveNonOpaque(); bool [[ro]] CandidateTriangleFrontFace(); bool [[ro]] CommittedTriangleFrontFace(); float<2> [[ro]] CandidateTriangleBarycentrics(); float<2> [[ro]] CommittedTriangleBarycentrics(); uint [[ro]] RayFlags(); float<3> [[ro]] WorldRayOrigin(); float<3> [[ro]] WorldRayDirection(); float [[ro]] RayTMin(); float [[ro]] CandidateTriangleRayT(); float [[ro]] CommittedRayT(); uint [[ro]] CandidateInstanceIndex(); uint [[ro]] CandidateInstanceID(); uint [[ro]] CandidateGeometryIndex(); uint [[ro]] CandidatePrimitiveIndex(); float<3> [[ro]] CandidateObjectRayOrigin(); float<3> [[ro]] CandidateObjectRayDirection(); uint [[ro]] CommittedInstanceIndex(); uint [[ro]] CommittedInstanceID(); uint [[ro]] CommittedGeometryIndex(); uint [[ro]] CommittedPrimitiveIndex(); float<3> [[ro]] CommittedObjectRayOrigin(); float<3> [[ro]] CommittedObjectRayDirection(); uint [[ro]] CandidateInstanceContributionToHitGroupIndex(); uint [[ro]] CommittedInstanceContributionToHitGroupIndex(); } namespace // Work Graphs objects and methods // EmptyNodeInput namespace EmptyNodeInputMethods { uint [[ro]] Count(); } namespace // RWDispatchNodeInputRecord methods (in addition to Get) namespace RWDispatchNodeInputRecordMethods { bool [[]] FinishedCrossGroupSharing(); } namespace // GroupNodeInputRecords methods (in addition to Get and array access subscript) namespace GroupNodeInputRecordsMethods { uint [[ro]] Count(); } namespace // NodeOutput namespace NodeOutputMethods { $match<0,-2> ThreadNodeOutputRecords [[]] GetThreadNodeOutputRecords(in uint numRecords); $match<0,-2> GroupNodeOutputRecords [[]] GetGroupNodeOutputRecords(in uint numRecords); bool [[]] IsValid(); } namespace // EmptyNodeOutput namespace EmptyNodeOutputMethods { void [[]] GroupIncrementOutputCount(in uint count); void [[]] ThreadIncrementOutputCount(in uint count); bool [[]] IsValid(); } namespace // ThreadNodeOutputRecords, GroupNodeOutputRecords namespace GroupOrThreadNodeOutputRecordsMethods { void [[]] OutputComplete(); } namespace // SPIRV Change Starts namespace VkSubpassInputMethods { $classT [[]] SubpassLoad() : subpassinput_load; } namespace namespace VkSubpassInputMSMethods { $classT [[]] SubpassLoad(in int sample) : subpassinputms_load; } namespace // SPIRV Change Ends
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/hct/CodeTags.py
# Copyright (C) Microsoft Corporation. All rights reserved. # This file is distributed under the University of Illinois Open Source License. See LICENSE.TXT for details. """CodeTags.py - Support code tags and auto-generated/manipulated regions Example 1: /* <py> import System random = System.Random() </py> */ // <py>ints=10</py> // <py::lines('GENERATED')>'int MyInts[] = { %s };' % [random.Next() for n in range(ints)]</py> // GENERATED:BEGIN // GENERATED:END Example 2: Sort lines (case-insensitive) // <py::lines('SORTED')>sorted(lines, key=str.lower)</py> // SORTED:BEGIN These are some lines to be sorted // SORTED:END For .rst files, use this syntax: .. <py::lines('SORTED')>sorted(lines, key=str.lower)</py::lines> .. SORTED:BEGIN The text .. SORTED:END TODO: - Handle doc/location thing better (not dependent on app.current_doc and selection) Would be easier with some exposed anchor point system """ import sys is_py3 = sys.version_info[0] == 3 if is_py3: basestring = (str, bytes) import re import hctdb_instrhelp def SelectTaggedLines(tag, start, doc=None): "Select lines between tag:BEGIN and tag:END" if doc is None: doc = app.current_doc text = doc.text begin = text.find(tag + ":BEGIN", doc.get_selection_range()[1]) if begin == -1: raise StandardError("Could not find tag %s:BEGIN" % tag) begin = text.find(native_endl, begin) end = text.find(tag + ":END", begin) if end == -1: raise StandardError("Could not find tag %s:END" % tag) end = text.rfind(native_endl, begin, end) + len(native_endl) doc.select(begin, end) rxWhitespace = re.compile(r"\s+") def GetIndent(text, pos): "Get indent for line in text at pos" end = text.find(native_endl, pos) begin = text.rfind(native_endl, 0, end) if begin == -1: begin = 0 else: begin += len(native_endl) m = rxWhitespace.match(text, begin, end) if m: return m.group(0) return "" def ReplaceTaggedLines(text_or_lines, tag="GENERATED_CODE", doc=None, tagrange=None): "Replace lines between tag:BEGIN and tag:END with text_or_lines, start searching forward from selection or end of tagrange" if doc is None: doc = app.current_doc if tagrange is None: tagrange = doc.get_selection_range() SelectTaggedLines(tag, tagrange[1], doc) text = doc.text begin, end = doc.get_selection_range() indent = GetIndent(text, begin) if isinstance(text_or_lines, basestring): text_or_lines = text_or_lines.splitlines() text_or_lines = [indent + line for line in text_or_lines] delta = ReplaceSelection(text_or_lines) doc.select(begin, end + delta) # reselect replacement so search may continue def StripIndent(lines, indent): "Remove indent from lines of text" def strip_indent(line): if line.startswith(indent): return line[len(indent) :] return line if isinstance(lines, basestring): lines = lines.splitlines() return map(strip_indent, lines) def UpdateTaggedLines(fn, tag="GENERATED_CODE", doc=None, tagrange=None): "Call supplied function with list of lines found between tag:BEGIN and tag:END. Replace with result." if doc is None: doc = app.current_doc if tagrange is None: tagrange = doc.get_selection_range() SelectTaggedLines(tag, tagrange[1], doc) begin, end = doc.get_selection_range() indent = GetIndent(doc.text, begin) lines = NormalizeForPython(doc.selected_text).splitlines()[1:] lines = StripIndent(lines, indent) lines = WrapFunctionForExceptionHandling(fn)(lines) if isinstance(lines, basestring): lines = lines.splitlines() lines = [indent + line for line in lines] delta = ReplaceSelection(lines) doc.select(begin, end + delta) # reselect replacement so search may continue def UpdateEachTaggedLine(fn, tag="GENERATED_CODE", doc=None, begin=None): "Call fn for each line of text between tag:BEGIN and tag:END" UpdateTaggedLines(lambda lines: map(fn, lines), tag, doc, begin) def _make_transform_lines(tag): """Makes an operation for tag processing The 'lines' operation will select lines with your tag and execute your code with a local variable 'lines', the result of which is joined back together into text to replace the current selection: <example_py::lines('COMMENT_THIS')>['// %s' % line for line in lines]</example_py> """ def _transform(code, doc=app.current_doc): def _transformer(lines): return eval(code) return UpdateTaggedLines(_transformer, tag, doc=doc) return _transform def _make_output(arg): def _print_fn(expression_text, doc=app.current_doc): print("%s = %s" % (expression_text, arg)) return _print_fn def _make_eval(arg): def _eval(expression_text, doc=app.current_doc): print(arg) return _eval PyOperations = { "lines": _make_transform_lines, "output": _make_output, "eval": _make_eval, } rxPyTag = re.compile(r"\<py(::(\w+)(\((.*?)\))?(/)?)?\>") def FindPyTag(doc, begin=0): text = doc.text _operation_function_ = None tag_code = "" end = -1 while begin != -1: begin = text.find("<py", begin) if begin != -1: m = rxPyTag.match(text, begin) if m: end = m.end() tag_code = tag = m.group(2) if tag: try: _operation_function_ = PyOperations[tag] except KeyError: print('Unknown tag "%s"' % tag) raise if m.group(3): tag_code = "(_operation_function_)%s" % m.group(3) try: _operation_function_ = eval( tag_code, globals(), {"_operation_function_": _operation_function_}, ) except: print( '%s(%d): Exception during eval("%s")' % ( doc.name, text.count(native_endl, 0, begin) + 1, tag_code, ) ) raise tag_code = tag_code.replace("(_operation_function_)", tag) else: tag = "" if m.group( 5 ): # we have form: <example_py[...]/> # whole tag selected currently if m.group(4): # we have <example_py::something(...)/> begin, end = m.span(4) # Select the arguments to 'something' break begin = end end = text.find("</py>", end) if end == -1: print( "%s(%d): Error: Could not find matching </py>" % (doc.name, text.count(native_endl, 0, begin) + 1) ) begin = -1 break else: # "<py" was the beginning of something else, keep searching: begin += 3 return begin, end, _operation_function_, tag_code def ExecuteNextPyTag(doc, begin=0): begin, end, op, tag_code = FindPyTag(doc, begin) if begin != -1 and end != -1: indent = GetIndent(doc.text, begin) code = doc.text[begin:end] code = NormalizeForPython(code) code = "\n".join(StripIndent(code, indent)) doc.select(begin, end) if op: result = None try: result = op(code, doc=doc) except: print( '%s(%d): Exception during eval("%s")' % (doc.name, doc.text.count(native_endl, 0, begin) + 1, code) ) raise if result is not None: print(result) else: try: exec(code, globals()) except: print( "%s(%d): Exception executing code" % (doc.name, doc.text.count(native_endl, 0, begin) + 1) ) raise return end def ExecutePyTags(doc=None): if doc is None: doc = app.current_doc begin = 0 while begin != -1: begin = ExecuteNextPyTag(doc, begin) ################################################ ################################################ # Testing Section class Test(object): "Provides testing functionality, emulating dependencies" class TestApp(object): pass class TestDoc(object): def __repr__(self): return "<TestDoc: %s=%s, %s>" % ( repr(self._selection), repr(self.text[self._selection[0] : self._selection[1]]), repr(self.text), ) def __init__(self, text, selection=None): self.name = "TestDoc" self.text = text self._selection = (0, 0) def get_selected_text(self): return self.text[self._selection[0] : self._selection[1]] def select(self, start, end): self._selection = start, end def get_selection_range(self): return self._selection def set_selected_text(self, text): begin, end = self.get_selection_range() self.text = self.text[:begin] + text + self.text[end:] # self._selection = (0,0) selected_text = property(get_selected_text, set_selected_text) def __init__(self, before, expected): self.before, self.expected = before, expected self.after = "" def test(self, selection=None): doc = Test.TestDoc(self.before, selection) app.current_doc = doc try: ExecutePyTags(doc) self.after = doc.text return 0 except: import sys _stderr = sys.stderr sys.stderr = self sys.excepthook(*sys.exc_info()) sys.stderr = _stderr return 1 def write(self, text): self.after += text def verify(self): "Returns nothing if passed, or failure message if failed." if self.after == self.expected: return return ( "==================== Verify failed!\n--- Before:%s+++ After:%s=== Expected:%s====================\n" % (self.before, self.after, self.expected) ) @staticmethod def NormalizeForVSText(text_or_lines): if isinstance(text_or_lines, basestring): text = str(text_or_lines).replace(native_endl, "\n") else: text = "\n".join( [str(item).replace(native_endl, "\n") for item in text_or_lines] ) return text.replace("\n", native_endl) @staticmethod def NormalizeForPython(text): return str(text).replace(native_endl, "\n").replace("\r", "\n") @staticmethod def TerminateTextForVS(text): if text.endswith(native_endl): return text return text + native_endl @staticmethod def WrapFunctionForExceptionHandling(fn): import sys def wrapperfn(*args, **kwargs): try: return fn(*args, **kwargs) except: sys.excepthook(*sys.exc_info()) sys.stderr.write("\n") raise return wrapperfn @staticmethod def ReplaceSelection(text_or_lines, doc=None): if doc is None: doc = app.current_doc original = doc.selected_text result = TerminateTextForVS(NormalizeForVSText(text_or_lines)) if original.startswith(native_endl) and not result.startswith(native_endl): result = native_endl + result doc.selected_text = result return len(result) - len(original) @staticmethod def SetDependencies(): global app global NormalizeForVSText, NormalizeForPython, TerminateTextForVS, WrapFunctionForExceptionHandling, ReplaceSelection if not hasattr(globals(), "app"): ( NormalizeForVSText, NormalizeForPython, TerminateTextForVS, WrapFunctionForExceptionHandling, ReplaceSelection, ) = ( Test.NormalizeForVSText, Test.NormalizeForPython, Test.TerminateTextForVS, Test.WrapFunctionForExceptionHandling, Test.ReplaceSelection, ) app = Test.TestApp() _tests = r""" <py>app.current_doc.text = '\nfoo\n'</py> -------------------- foo ==================== not indented // <py::lines('COMMENT_THIS')>['// %s' % line for line in lines]</py> before section // COMMENT_THIS:BEGIN lines to comment // COMMENT_THIS:END after comment -------------------- not indented // <py::lines('COMMENT_THIS')>['// %s' % line for line in lines]</py> before section // COMMENT_THIS:BEGIN // lines to comment // COMMENT_THIS:END after comment ==================== -------------------- ==================== -------------------- """.split( "====================" ) _tests = [text.split("--------------------") for text in _tests] if not is_py3: del text def test_module(tests=_tests): global native_endl Test.SetDependencies() native_endl = "\n" failed = 0 print("Testing CodeTags.py") for before, expected in tests: test = Test(before, expected) test.test() result = test.verify() if result: print(result) failed += 1 if failed: print("%d Test(s) Failed!" % failed) else: print("All Tests Passed!") return failed def _TraceFunctions(): global _tablevel _tablevel = 0 def _trace(fn): def _wrapper(*args, **kwargs): global _tablevel _tablevel += 1 _args = map(repr, args) _args += ["%s=%s" % (key, repr(value)) for key, value in kwargs.items()] print("%s%s(%s)" % (_tablevel * " ", fn.__name__, ", ".join(_args))) result = fn(*args, **kwargs) if result: print("%s= %s" % (_tablevel * " ", repr(result))) _tablevel -= 1 return result return _wrapper import types for key, value in globals().items(): if key[:1] != "_": if type(value) == types.FunctionType: globals()[key] = _trace(value) elif type(value) == types.ClassType: for key in dir(value): member = getattr(value, key) if type(member) == types.MethodType: setattr(value, key, _trace(member)) ################################################ ################################################ # For running from the command-line def usage(): print( """CodeTags.py - Templatize and generate code with python tags. Usage: CodeTags.py <input file> [<output file>] <input file> - file with tags to expand <output file> - optional output file (expand in place if unspecified) """ ) return 1 def main(argv, newline=None): trace = False test = False args = [] for arg in argv: if arg[0] in "/-": opt = arg[1:].lower() if opt == "trace": trace = True continue elif opt == "test": test = True continue args.append(arg) if trace: _TraceFunctions() if test: return test_module() if len(args) == 1: # do in-place expansion of code tags args.append(args[0]) result = 0 if len(args) == 2: global native_endl Test.SetDependencies() native_endl = "\n" with open(args[0], "rt") as f: # Use test harness to do work, but we don't care about the comparison # with expected, since we're not actually in testing mode: test = Test(f.read(), "expected not used.") result = test.test() if result == 0: with open(args[1], "wt", newline=newline) as f: f.write(test.after) else: sys.stderr.write(test.after) else: result = usage() return result if __name__ == "__main__": import sys exit(main(sys.argv[1:]))
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/git/code-format-helper.py
#!/usr/bin/env python3 # # ====- code-format-helper, runs code formatters from the ci --*- python -*--==# # # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # # ==-------------------------------------------------------------------------==# import argparse import os import subprocess import sys from functools import cached_property import github from github import IssueComment, PullRequest class FormatHelper: COMMENT_TAG = "<!--LLVM CODE FORMAT COMMENT: {fmt}-->" name = "unknown" @property def comment_tag(self) -> str: return self.COMMENT_TAG.replace("fmt", self.name) def format_run(self, changed_files: [str], args: argparse.Namespace) -> str | None: pass def pr_comment_text(self, diff: str) -> str: return f""" {self.comment_tag} :warning: {self.friendly_name}, {self.name} found issues in your code. :warning: <details> <summary> You can test this locally with the following command: </summary> ``````````bash {self.instructions} `````````` </details> <details> <summary> View the diff from {self.name} here. </summary> ``````````diff {diff} `````````` </details> - [ ] Check this box to apply formatting changes to this branch.""" def find_comment( self, pr: PullRequest.PullRequest ) -> IssueComment.IssueComment | None: for comment in pr.as_issue().get_comments(): if self.comment_tag in comment.body: return comment return None def update_pr(self, diff: str, args: argparse.Namespace): repo = github.Github(args.token).get_repo(args.repo) pr = repo.get_issue(args.issue_number).as_pull_request() existing_comment = self.find_comment(pr) pr_text = self.pr_comment_text(diff) if existing_comment: existing_comment.edit(pr_text) else: pr.as_issue().create_comment(pr_text) def update_pr_success(self, args: argparse.Namespace): repo = github.Github(args.token).get_repo(args.repo) pr = repo.get_issue(args.issue_number).as_pull_request() existing_comment = self.find_comment(pr) if existing_comment: existing_comment.edit( f""" {self.comment_tag} :white_check_mark: With the latest revision this PR passed the {self.friendly_name}. """ ) def run(self, changed_files: [str], args: argparse.Namespace): diff = self.format_run(changed_files, args) if diff: self.update_pr(diff, args) return False else: self.update_pr_success(args) return True class ClangFormatHelper(FormatHelper): name = "clang-format" friendly_name = "C/C++ code formatter" @property def instructions(self): return " ".join(self.cf_cmd) @cached_property def libcxx_excluded_files(self): return [] # HLSL Change - libcxx is not in DXC's repo #with open("libcxx/utils/data/ignore_format.txt", "r") as ifd: # return [excl.strip() for excl in ifd.readlines()] def should_be_excluded(self, path: str) -> bool: if path in self.libcxx_excluded_files: print(f"Excluding file {path}") return True return False def filter_changed_files(self, changed_files: [str]) -> [str]: filtered_files = [] for path in changed_files: _, ext = os.path.splitext(path) if ext in (".cpp", ".c", ".h", ".hpp", ".hxx", ".cxx"): if not self.should_be_excluded(path): filtered_files.append(path) return filtered_files def format_run(self, changed_files: [str], args: argparse.Namespace) -> str | None: cpp_files = self.filter_changed_files(changed_files) if not cpp_files: return cf_cmd = [ "git-clang-format", "--diff", args.start_rev, args.end_rev, "--", ] + cpp_files print(f"Running: {' '.join(cf_cmd)}") self.cf_cmd = cf_cmd proc = subprocess.run(cf_cmd, capture_output=True) # formatting needed if proc.returncode == 1: return proc.stdout.decode("utf-8") return None class DarkerFormatHelper(FormatHelper): name = "darker" friendly_name = "Python code formatter" @property def instructions(self): return " ".join(self.darker_cmd) def filter_changed_files(self, changed_files: [str]) -> [str]: filtered_files = [] for path in changed_files: name, ext = os.path.splitext(path) if ext == ".py": filtered_files.append(path) return filtered_files def format_run(self, changed_files: [str], args: argparse.Namespace) -> str | None: py_files = self.filter_changed_files(changed_files) if not py_files: return darker_cmd = [ "darker", "--check", "--diff", "-r", f"{args.start_rev}..{args.end_rev}", ] + py_files print(f"Running: {' '.join(darker_cmd)}") self.darker_cmd = darker_cmd proc = subprocess.run(darker_cmd, capture_output=True) # formatting needed if proc.returncode == 1: return proc.stdout.decode("utf-8") return None ALL_FORMATTERS = (DarkerFormatHelper(), ClangFormatHelper()) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "--token", type=str, required=True, help="GitHub authentiation token" ) parser.add_argument( "--repo", type=str, default=os.getenv("GITHUB_REPOSITORY", "llvm/llvm-project"), help="The GitHub repository that we are working with in the form of <owner>/<repo> (e.g. llvm/llvm-project)", ) parser.add_argument("--issue-number", type=int, required=True) parser.add_argument( "--start-rev", type=str, required=True, help="Compute changes from this revision.", ) parser.add_argument( "--end-rev", type=str, required=True, help="Compute changes to this revision" ) parser.add_argument( "--changed-files", type=str, help="Comma separated list of files that has been changed", ) args = parser.parse_args() changed_files = [] if args.changed_files: changed_files = args.changed_files.split(",") exit_code = 0 for fmt in ALL_FORMATTERS: if not fmt.run(changed_files, args): exit_code = 1 sys.exit(exit_code)
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/git/code-format-save-diff.py
#!/usr/bin/env python3 # # ====- code-format-save-diff, save diff from comment --*- python -*---------==# # # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # # ==-------------------------------------------------------------------------==# import argparse import os import re import subprocess import sys import tempfile from functools import cached_property import github from github import IssueComment, PullRequest LF = '\n' CRLF = '\r\n' CR = '\r' def get_diff_from_comment(comment: IssueComment.IssueComment) -> str: diff_pat = re.compile(r"``````````diff(?P<DIFF>.+)``````````", re.DOTALL) m = re.search(diff_pat, comment.body) if m is None: raise Exception(f"Could not find diff in comment {comment.id}") diff = m.group("DIFF") # force to linux line endings diff = diff.replace(CRLF, LF).replace(CR, LF) return diff def run_cmd(cmd: [str]) -> None: print(f"Running: {' '.join(cmd)}") proc = subprocess.run(cmd, capture_output=True, text=True) if proc.returncode != 0: print(proc.stdout) print(proc.stderr) raise Exception(f"Failed to run {' '.join(cmd)}") def apply_patches(args: argparse.Namespace) -> None: repo = github.Github(args.token).get_repo(args.repo) pr = repo.get_issue(args.issue_number).as_pull_request() comment = pr.get_issue_comment(args.comment_id) if comment is None: raise Exception(f"Comment {args.comment_id} does not exist") # get the diff from the comment diff = get_diff_from_comment(comment) # write diff to temporary file and apply if os.path.exists(args.tmp_diff_file): os.remove(args.tmp_diff_file) with open(args.tmp_diff_file, 'w+') as tmp: tmp.write(diff) tmp.flush() tmp.close() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "--token", type=str, required=True, help="GitHub authentiation token" ) parser.add_argument( "--repo", type=str, default=os.getenv("GITHUB_REPOSITORY", "llvm/llvm-project"), help="The GitHub repository that we are working with in the form of <owner>/<repo> (e.g. llvm/llvm-project)", ) parser.add_argument("--issue-number", type=int, required=True) parser.add_argument("--comment-id", type=int, required=True) parser.add_argument( "--tmp-diff-file", type=str, required=True, help="Temporary file to write diff to", ) args = parser.parse_args() apply_patches(args)
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/git/requirements_formatting.txt.in
black~=24.3 darker==1.7.2 PyGithub==1.59.1
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/git/requirements_formatting.txt
# # This file is autogenerated by pip-compile with Python 3.11 # by the following command: # # pip-compile --output-file=llvm/utils/git/requirements_formatting.txt llvm/utils/git/requirements_formatting.txt.in # black==24.3.0 # via # -r llvm/utils/git/requirements_formatting.txt.in # darker certifi==2024.7.4 # via requests cffi==1.15.1 # via # cryptography # pynacl charset-normalizer==3.2.0 # via requests click==8.1.7 # via black cryptography==42.0.4 # via pyjwt darker==1.7.2 # via -r llvm/utils/git/requirements_formatting.txt.in deprecated==1.2.14 # via pygithub idna==3.7 # via requests mypy-extensions==1.0.0 # via black packaging==23.1 # via black pathspec==0.11.2 # via black platformdirs==3.10.0 # via black pycparser==2.21 # via cffi pygithub==1.59.1 # via -r llvm/utils/git/requirements_formatting.txt.in pyjwt[crypto]==2.8.0 # via pygithub pynacl==1.5.0 # via pygithub requests==2.32.0 # via pygithub toml==0.10.2 # via darker urllib3==2.2.2 # via requests wrapt==1.15.0 # via deprecated
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/TableGen/CTagsEmitter.cpp
//===- CTagsEmitter.cpp - Generate ctags-compatible index ------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This tablegen backend emits an index of definitions in ctags(1) format. // A helper script, utils/TableGen/tdtags, provides an easier-to-use // interface; run 'tdtags -H' for documentation. // //===----------------------------------------------------------------------===// #include "llvm/Support/SourceMgr.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/TableGen/Error.h" #include "llvm/TableGen/Record.h" #include <algorithm> #include <string> #include <vector> using namespace llvm; #define DEBUG_TYPE "ctags-emitter" namespace { class Tag { private: const std::string *Id; SMLoc Loc; public: Tag(const std::string &Name, const SMLoc Location) : Id(&Name), Loc(Location) {} int operator<(const Tag &B) const { return *Id < *B.Id; } void emit(raw_ostream &OS) const { const MemoryBuffer *CurMB = SrcMgr.getMemoryBuffer(SrcMgr.FindBufferContainingLoc(Loc)); const char *BufferName = CurMB->getBufferIdentifier(); std::pair<unsigned, unsigned> LineAndColumn = SrcMgr.getLineAndColumn(Loc); OS << *Id << "\t" << BufferName << "\t" << LineAndColumn.first << "\n"; } }; class CTagsEmitter { private: RecordKeeper &Records; public: CTagsEmitter(RecordKeeper &R) : Records(R) {} void run(raw_ostream &OS); private: static SMLoc locate(const Record *R); }; } // End anonymous namespace. SMLoc CTagsEmitter::locate(const Record *R) { ArrayRef<SMLoc> Locs = R->getLoc(); return !Locs.empty() ? Locs.front() : SMLoc(); } void CTagsEmitter::run(raw_ostream &OS) { const auto &Classes = Records.getClasses(); const auto &Defs = Records.getDefs(); std::vector<Tag> Tags; // Collect tags. Tags.reserve(Classes.size() + Defs.size()); for (const auto &C : Classes) Tags.push_back(Tag(C.first, locate(C.second.get()))); for (const auto &D : Defs) Tags.push_back(Tag(D.first, locate(D.second.get()))); // Emit tags. std::sort(Tags.begin(), Tags.end()); OS << "!_TAG_FILE_FORMAT\t1\t/original ctags format/\n"; OS << "!_TAG_FILE_SORTED\t1\t/0=unsorted, 1=sorted, 2=foldcase/\n"; for (const Tag &T : Tags) T.emit(OS); } namespace llvm { void EmitCTags(RecordKeeper &RK, raw_ostream &OS) { CTagsEmitter(RK).run(OS); } } // End llvm namespace.
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/TableGen/CodeGenDAGPatterns.h
//===- CodeGenDAGPatterns.h - Read DAG patterns from .td file ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file declares the CodeGenDAGPatterns class, which is used to read and // represent the patterns present in a .td file for instructions. // //===----------------------------------------------------------------------===// #ifndef LLVM_UTILS_TABLEGEN_CODEGENDAGPATTERNS_H #define LLVM_UTILS_TABLEGEN_CODEGENDAGPATTERNS_H #include "CodeGenIntrinsics.h" #include "CodeGenTarget.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringMap.h" #include "llvm/Support/ErrorHandling.h" #include <algorithm> #include <map> #include <set> #include <vector> namespace llvm { class Record; class Init; class ListInit; class DagInit; class SDNodeInfo; class TreePattern; class TreePatternNode; class CodeGenDAGPatterns; class ComplexPattern; /// EEVT::DAGISelGenValueType - These are some extended forms of /// MVT::SimpleValueType that we use as lattice values during type inference. /// The existing MVT iAny, fAny and vAny types suffice to represent /// arbitrary integer, floating-point, and vector types, so only an unknown /// value is needed. namespace EEVT { /// TypeSet - This is either empty if it's completely unknown, or holds a set /// of types. It is used during type inference because register classes can /// have multiple possible types and we don't know which one they get until /// type inference is complete. /// /// TypeSet can have three states: /// Vector is empty: The type is completely unknown, it can be any valid /// target type. /// Vector has multiple constrained types: (e.g. v4i32 + v4f32) it is one /// of those types only. /// Vector has one concrete type: The type is completely known. /// class TypeSet { SmallVector<MVT::SimpleValueType, 4> TypeVec; public: TypeSet() {} TypeSet(MVT::SimpleValueType VT, TreePattern &TP); TypeSet(ArrayRef<MVT::SimpleValueType> VTList); bool isCompletelyUnknown() const { return TypeVec.empty(); } bool isConcrete() const { if (TypeVec.size() != 1) return false; unsigned char T = TypeVec[0]; (void)T; assert(T < MVT::LAST_VALUETYPE || T == MVT::iPTR || T == MVT::iPTRAny); return true; } MVT::SimpleValueType getConcrete() const { assert(isConcrete() && "Type isn't concrete yet"); return (MVT::SimpleValueType)TypeVec[0]; } bool isDynamicallyResolved() const { return getConcrete() == MVT::iPTR || getConcrete() == MVT::iPTRAny; } const SmallVectorImpl<MVT::SimpleValueType> &getTypeList() const { assert(!TypeVec.empty() && "Not a type list!"); return TypeVec; } bool isVoid() const { return TypeVec.size() == 1 && TypeVec[0] == MVT::isVoid; } /// hasIntegerTypes - Return true if this TypeSet contains any integer value /// types. bool hasIntegerTypes() const; /// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or /// a floating point value type. bool hasFloatingPointTypes() const; /// hasScalarTypes - Return true if this TypeSet contains a scalar value /// type. bool hasScalarTypes() const; /// hasVectorTypes - Return true if this TypeSet contains a vector value /// type. bool hasVectorTypes() const; /// getName() - Return this TypeSet as a string. std::string getName() const; /// MergeInTypeInfo - This merges in type information from the specified /// argument. If 'this' changes, it returns true. If the two types are /// contradictory (e.g. merge f32 into i32) then this flags an error. bool MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP); bool MergeInTypeInfo(MVT::SimpleValueType InVT, TreePattern &TP) { return MergeInTypeInfo(EEVT::TypeSet(InVT, TP), TP); } /// Force this type list to only contain integer types. bool EnforceInteger(TreePattern &TP); /// Force this type list to only contain floating point types. bool EnforceFloatingPoint(TreePattern &TP); /// EnforceScalar - Remove all vector types from this type list. bool EnforceScalar(TreePattern &TP); /// EnforceVector - Remove all non-vector types from this type list. bool EnforceVector(TreePattern &TP); /// EnforceSmallerThan - 'this' must be a smaller VT than Other. Update /// this an other based on this information. bool EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP); /// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type /// whose element is VT. bool EnforceVectorEltTypeIs(EEVT::TypeSet &VT, TreePattern &TP); /// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type /// whose element is VT. bool EnforceVectorEltTypeIs(MVT::SimpleValueType VT, TreePattern &TP); /// EnforceVectorSubVectorTypeIs - 'this' is now constrainted to /// be a vector type VT. bool EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VT, TreePattern &TP); /// EnforceVectorSameNumElts - 'this' is now constrainted to /// be a vector with same num elements as VT. bool EnforceVectorSameNumElts(EEVT::TypeSet &VT, TreePattern &TP); bool operator!=(const TypeSet &RHS) const { return TypeVec != RHS.TypeVec; } bool operator==(const TypeSet &RHS) const { return TypeVec == RHS.TypeVec; } private: /// FillWithPossibleTypes - Set to all legal types and return true, only /// valid on completely unknown type sets. If Pred is non-null, only MVTs /// that pass the predicate are added. bool FillWithPossibleTypes(TreePattern &TP, bool (*Pred)(MVT::SimpleValueType) = nullptr, const char *PredicateName = nullptr); }; } /// Set type used to track multiply used variables in patterns typedef std::set<std::string> MultipleUseVarSet; /// SDTypeConstraint - This is a discriminated union of constraints, /// corresponding to the SDTypeConstraint tablegen class in Target.td. struct SDTypeConstraint { SDTypeConstraint(Record *R); unsigned OperandNo; // The operand # this constraint applies to. enum { SDTCisVT, SDTCisPtrTy, SDTCisInt, SDTCisFP, SDTCisVec, SDTCisSameAs, SDTCisVTSmallerThanOp, SDTCisOpSmallerThanOp, SDTCisEltOfVec, SDTCisSubVecOfVec, SDTCVecEltisVT, SDTCisSameNumEltsAs } ConstraintType; union { // The discriminated union. struct { MVT::SimpleValueType VT; } SDTCisVT_Info; struct { unsigned OtherOperandNum; } SDTCisSameAs_Info; struct { unsigned OtherOperandNum; } SDTCisVTSmallerThanOp_Info; struct { unsigned BigOperandNum; } SDTCisOpSmallerThanOp_Info; struct { unsigned OtherOperandNum; } SDTCisEltOfVec_Info; struct { unsigned OtherOperandNum; } SDTCisSubVecOfVec_Info; struct { MVT::SimpleValueType VT; } SDTCVecEltisVT_Info; struct { unsigned OtherOperandNum; } SDTCisSameNumEltsAs_Info; } x; /// ApplyTypeConstraint - Given a node in a pattern, apply this type /// constraint to the nodes operands. This returns true if it makes a /// change, false otherwise. If a type contradiction is found, an error /// is flagged. bool ApplyTypeConstraint(TreePatternNode *N, const SDNodeInfo &NodeInfo, TreePattern &TP) const; }; /// SDNodeInfo - One of these records is created for each SDNode instance in /// the target .td file. This represents the various dag nodes we will be /// processing. class SDNodeInfo { Record *Def; std::string EnumName; std::string SDClassName; unsigned Properties; unsigned NumResults; int NumOperands; std::vector<SDTypeConstraint> TypeConstraints; public: SDNodeInfo(Record *R); // Parse the specified record. unsigned getNumResults() const { return NumResults; } /// getNumOperands - This is the number of operands required or -1 if /// variadic. int getNumOperands() const { return NumOperands; } Record *getRecord() const { return Def; } const std::string &getEnumName() const { return EnumName; } const std::string &getSDClassName() const { return SDClassName; } const std::vector<SDTypeConstraint> &getTypeConstraints() const { return TypeConstraints; } /// getKnownType - If the type constraints on this node imply a fixed type /// (e.g. all stores return void, etc), then return it as an /// MVT::SimpleValueType. Otherwise, return MVT::Other. MVT::SimpleValueType getKnownType(unsigned ResNo) const; /// hasProperty - Return true if this node has the specified property. /// bool hasProperty(enum SDNP Prop) const { return Properties & (1 << Prop); } /// ApplyTypeConstraints - Given a node in a pattern, apply the type /// constraints for this node to the operands of the node. This returns /// true if it makes a change, false otherwise. If a type contradiction is /// found, an error is flagged. bool ApplyTypeConstraints(TreePatternNode *N, TreePattern &TP) const { bool MadeChange = false; for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) MadeChange |= TypeConstraints[i].ApplyTypeConstraint(N, *this, TP); return MadeChange; } }; /// TreePredicateFn - This is an abstraction that represents the predicates on /// a PatFrag node. This is a simple one-word wrapper around a pointer to /// provide nice accessors. class TreePredicateFn { /// PatFragRec - This is the TreePattern for the PatFrag that we /// originally came from. TreePattern *PatFragRec; public: /// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag. TreePredicateFn(TreePattern *N); TreePattern *getOrigPatFragRecord() const { return PatFragRec; } /// isAlwaysTrue - Return true if this is a noop predicate. bool isAlwaysTrue() const; bool isImmediatePattern() const { return !getImmCode().empty(); } /// getImmediatePredicateCode - Return the code that evaluates this pattern if /// this is an immediate predicate. It is an error to call this on a /// non-immediate pattern. std::string getImmediatePredicateCode() const { std::string Result = getImmCode(); assert(!Result.empty() && "Isn't an immediate pattern!"); return Result; } bool operator==(const TreePredicateFn &RHS) const { return PatFragRec == RHS.PatFragRec; } bool operator!=(const TreePredicateFn &RHS) const { return !(*this == RHS); } /// Return the name to use in the generated code to reference this, this is /// "Predicate_foo" if from a pattern fragment "foo". std::string getFnName() const; /// getCodeToRunOnSDNode - Return the code for the function body that /// evaluates this predicate. The argument is expected to be in "Node", /// not N. This handles casting and conversion to a concrete node type as /// appropriate. std::string getCodeToRunOnSDNode() const; private: std::string getPredCode() const; std::string getImmCode() const; }; /// FIXME: TreePatternNode's can be shared in some cases (due to dag-shaped /// patterns), and as such should be ref counted. We currently just leak all /// TreePatternNode objects! class TreePatternNode { /// The type of each node result. Before and during type inference, each /// result may be a set of possible types. After (successful) type inference, /// each is a single concrete type. SmallVector<EEVT::TypeSet, 1> Types; /// Operator - The Record for the operator if this is an interior node (not /// a leaf). Record *Operator; /// Val - The init value (e.g. the "GPRC" record, or "7") for a leaf. /// Init *Val; /// Name - The name given to this node with the :$foo notation. /// std::string Name; /// PredicateFns - The predicate functions to execute on this node to check /// for a match. If this list is empty, no predicate is involved. std::vector<TreePredicateFn> PredicateFns; /// TransformFn - The transformation function to execute on this node before /// it can be substituted into the resulting instruction on a pattern match. Record *TransformFn; std::vector<TreePatternNode*> Children; public: TreePatternNode(Record *Op, const std::vector<TreePatternNode*> &Ch, unsigned NumResults) : Operator(Op), Val(nullptr), TransformFn(nullptr), Children(Ch) { Types.resize(NumResults); } TreePatternNode(Init *val, unsigned NumResults) // leaf ctor : Operator(nullptr), Val(val), TransformFn(nullptr) { Types.resize(NumResults); } ~TreePatternNode(); bool hasName() const { return !Name.empty(); } const std::string &getName() const { return Name; } void setName(StringRef N) { Name.assign(N.begin(), N.end()); } bool isLeaf() const { return Val != nullptr; } // Type accessors. unsigned getNumTypes() const { return Types.size(); } MVT::SimpleValueType getType(unsigned ResNo) const { return Types[ResNo].getConcrete(); } const SmallVectorImpl<EEVT::TypeSet> &getExtTypes() const { return Types; } const EEVT::TypeSet &getExtType(unsigned ResNo) const { return Types[ResNo]; } EEVT::TypeSet &getExtType(unsigned ResNo) { return Types[ResNo]; } void setType(unsigned ResNo, const EEVT::TypeSet &T) { Types[ResNo] = T; } bool hasTypeSet(unsigned ResNo) const { return Types[ResNo].isConcrete(); } bool isTypeCompletelyUnknown(unsigned ResNo) const { return Types[ResNo].isCompletelyUnknown(); } bool isTypeDynamicallyResolved(unsigned ResNo) const { return Types[ResNo].isDynamicallyResolved(); } Init *getLeafValue() const { assert(isLeaf()); return Val; } Record *getOperator() const { assert(!isLeaf()); return Operator; } unsigned getNumChildren() const { return Children.size(); } TreePatternNode *getChild(unsigned N) const { return Children[N]; } void setChild(unsigned i, TreePatternNode *N) { Children[i] = N; } /// hasChild - Return true if N is any of our children. bool hasChild(const TreePatternNode *N) const { for (unsigned i = 0, e = Children.size(); i != e; ++i) if (Children[i] == N) return true; return false; } bool hasAnyPredicate() const { return !PredicateFns.empty(); } const std::vector<TreePredicateFn> &getPredicateFns() const { return PredicateFns; } void clearPredicateFns() { PredicateFns.clear(); } void setPredicateFns(const std::vector<TreePredicateFn> &Fns) { assert(PredicateFns.empty() && "Overwriting non-empty predicate list!"); PredicateFns = Fns; } void addPredicateFn(const TreePredicateFn &Fn) { assert(!Fn.isAlwaysTrue() && "Empty predicate string!"); if (std::find(PredicateFns.begin(), PredicateFns.end(), Fn) == PredicateFns.end()) PredicateFns.push_back(Fn); } Record *getTransformFn() const { return TransformFn; } void setTransformFn(Record *Fn) { TransformFn = Fn; } /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the /// CodeGenIntrinsic information for it, otherwise return a null pointer. const CodeGenIntrinsic *getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const; /// getComplexPatternInfo - If this node corresponds to a ComplexPattern, /// return the ComplexPattern information, otherwise return null. const ComplexPattern * getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const; /// Returns the number of MachineInstr operands that would be produced by this /// node if it mapped directly to an output Instruction's /// operand. ComplexPattern specifies this explicitly; MIOperandInfo gives it /// for Operands; otherwise 1. unsigned getNumMIResults(const CodeGenDAGPatterns &CGP) const; /// NodeHasProperty - Return true if this node has the specified property. bool NodeHasProperty(SDNP Property, const CodeGenDAGPatterns &CGP) const; /// TreeHasProperty - Return true if any node in this tree has the specified /// property. bool TreeHasProperty(SDNP Property, const CodeGenDAGPatterns &CGP) const; /// isCommutativeIntrinsic - Return true if the node is an intrinsic which is /// marked isCommutative. bool isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const; void print(raw_ostream &OS) const; void dump() const; public: // Higher level manipulation routines. /// clone - Return a new copy of this tree. /// TreePatternNode *clone() const; /// RemoveAllTypes - Recursively strip all the types of this tree. void RemoveAllTypes(); /// isIsomorphicTo - Return true if this node is recursively isomorphic to /// the specified node. For this comparison, all of the state of the node /// is considered, except for the assigned name. Nodes with differing names /// that are otherwise identical are considered isomorphic. bool isIsomorphicTo(const TreePatternNode *N, const MultipleUseVarSet &DepVars) const; /// SubstituteFormalArguments - Replace the formal arguments in this tree /// with actual values specified by ArgMap. void SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap); /// InlinePatternFragments - If this pattern refers to any pattern /// fragments, inline them into place, giving us a pattern without any /// PatFrag references. TreePatternNode *InlinePatternFragments(TreePattern &TP); /// ApplyTypeConstraints - Apply all of the type constraints relevant to /// this node and its children in the tree. This returns true if it makes a /// change, false otherwise. If a type contradiction is found, flag an error. bool ApplyTypeConstraints(TreePattern &TP, bool NotRegisters); /// UpdateNodeType - Set the node type of N to VT if VT contains /// information. If N already contains a conflicting type, then flag an /// error. This returns true if any information was updated. /// bool UpdateNodeType(unsigned ResNo, const EEVT::TypeSet &InTy, TreePattern &TP) { return Types[ResNo].MergeInTypeInfo(InTy, TP); } bool UpdateNodeType(unsigned ResNo, MVT::SimpleValueType InTy, TreePattern &TP) { return Types[ResNo].MergeInTypeInfo(EEVT::TypeSet(InTy, TP), TP); } // Update node type with types inferred from an instruction operand or result // def from the ins/outs lists. // Return true if the type changed. bool UpdateNodeTypeFromInst(unsigned ResNo, Record *Operand, TreePattern &TP); /// ContainsUnresolvedType - Return true if this tree contains any /// unresolved types. bool ContainsUnresolvedType() const { for (unsigned i = 0, e = Types.size(); i != e; ++i) if (!Types[i].isConcrete()) return true; for (unsigned i = 0, e = getNumChildren(); i != e; ++i) if (getChild(i)->ContainsUnresolvedType()) return true; return false; } /// canPatternMatch - If it is impossible for this pattern to match on this /// target, fill in Reason and return false. Otherwise, return true. bool canPatternMatch(std::string &Reason, const CodeGenDAGPatterns &CDP); }; inline raw_ostream &operator<<(raw_ostream &OS, const TreePatternNode &TPN) { TPN.print(OS); return OS; } /// TreePattern - Represent a pattern, used for instructions, pattern /// fragments, etc. /// class TreePattern { /// Trees - The list of pattern trees which corresponds to this pattern. /// Note that PatFrag's only have a single tree. /// std::vector<TreePatternNode*> Trees; /// NamedNodes - This is all of the nodes that have names in the trees in this /// pattern. StringMap<SmallVector<TreePatternNode*,1> > NamedNodes; /// TheRecord - The actual TableGen record corresponding to this pattern. /// Record *TheRecord; /// Args - This is a list of all of the arguments to this pattern (for /// PatFrag patterns), which are the 'node' markers in this pattern. std::vector<std::string> Args; /// CDP - the top-level object coordinating this madness. /// CodeGenDAGPatterns &CDP; /// isInputPattern - True if this is an input pattern, something to match. /// False if this is an output pattern, something to emit. bool isInputPattern; /// hasError - True if the currently processed nodes have unresolvable types /// or other non-fatal errors bool HasError; /// It's important that the usage of operands in ComplexPatterns is /// consistent: each named operand can be defined by at most one /// ComplexPattern. This records the ComplexPattern instance and the operand /// number for each operand encountered in a ComplexPattern to aid in that /// check. StringMap<std::pair<Record *, unsigned>> ComplexPatternOperands; public: /// TreePattern constructor - Parse the specified DagInits into the /// current record. TreePattern(Record *TheRec, ListInit *RawPat, bool isInput, CodeGenDAGPatterns &ise); TreePattern(Record *TheRec, DagInit *Pat, bool isInput, CodeGenDAGPatterns &ise); TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput, CodeGenDAGPatterns &ise); /// getTrees - Return the tree patterns which corresponds to this pattern. /// const std::vector<TreePatternNode*> &getTrees() const { return Trees; } unsigned getNumTrees() const { return Trees.size(); } TreePatternNode *getTree(unsigned i) const { return Trees[i]; } TreePatternNode *getOnlyTree() const { assert(Trees.size() == 1 && "Doesn't have exactly one pattern!"); return Trees[0]; } const StringMap<SmallVector<TreePatternNode*,1> > &getNamedNodesMap() { if (NamedNodes.empty()) ComputeNamedNodes(); return NamedNodes; } /// getRecord - Return the actual TableGen record corresponding to this /// pattern. /// Record *getRecord() const { return TheRecord; } unsigned getNumArgs() const { return Args.size(); } const std::string &getArgName(unsigned i) const { assert(i < Args.size() && "Argument reference out of range!"); return Args[i]; } std::vector<std::string> &getArgList() { return Args; } CodeGenDAGPatterns &getDAGPatterns() const { return CDP; } /// InlinePatternFragments - If this pattern refers to any pattern /// fragments, inline them into place, giving us a pattern without any /// PatFrag references. void InlinePatternFragments() { for (unsigned i = 0, e = Trees.size(); i != e; ++i) Trees[i] = Trees[i]->InlinePatternFragments(*this); } /// InferAllTypes - Infer/propagate as many types throughout the expression /// patterns as possible. Return true if all types are inferred, false /// otherwise. Bail out if a type contradiction is found. bool InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *NamedTypes=nullptr); /// error - If this is the first error in the current resolution step, /// print it and set the error flag. Otherwise, continue silently. void error(const Twine &Msg); bool hasError() const { return HasError; } void resetError() { HasError = false; } void print(raw_ostream &OS) const; void dump() const; private: TreePatternNode *ParseTreePattern(Init *DI, StringRef OpName); void ComputeNamedNodes(); void ComputeNamedNodes(TreePatternNode *N); }; /// DAGDefaultOperand - One of these is created for each OperandWithDefaultOps /// that has a set ExecuteAlways / DefaultOps field. struct DAGDefaultOperand { std::vector<TreePatternNode*> DefaultOps; }; class DAGInstruction { TreePattern *Pattern; std::vector<Record*> Results; std::vector<Record*> Operands; std::vector<Record*> ImpResults; TreePatternNode *ResultPattern; public: DAGInstruction(TreePattern *TP, const std::vector<Record*> &results, const std::vector<Record*> &operands, const std::vector<Record*> &impresults) : Pattern(TP), Results(results), Operands(operands), ImpResults(impresults), ResultPattern(nullptr) {} TreePattern *getPattern() const { return Pattern; } unsigned getNumResults() const { return Results.size(); } unsigned getNumOperands() const { return Operands.size(); } unsigned getNumImpResults() const { return ImpResults.size(); } const std::vector<Record*>& getImpResults() const { return ImpResults; } void setResultPattern(TreePatternNode *R) { ResultPattern = R; } Record *getResult(unsigned RN) const { assert(RN < Results.size()); return Results[RN]; } Record *getOperand(unsigned ON) const { assert(ON < Operands.size()); return Operands[ON]; } Record *getImpResult(unsigned RN) const { assert(RN < ImpResults.size()); return ImpResults[RN]; } TreePatternNode *getResultPattern() const { return ResultPattern; } }; /// PatternToMatch - Used by CodeGenDAGPatterns to keep tab of patterns /// processed to produce isel. class PatternToMatch { public: PatternToMatch(Record *srcrecord, ListInit *preds, TreePatternNode *src, TreePatternNode *dst, const std::vector<Record*> &dstregs, int complexity, unsigned uid) : SrcRecord(srcrecord), Predicates(preds), SrcPattern(src), DstPattern(dst), Dstregs(dstregs), AddedComplexity(complexity), ID(uid) {} Record *SrcRecord; // Originating Record for the pattern. ListInit *Predicates; // Top level predicate conditions to match. TreePatternNode *SrcPattern; // Source pattern to match. TreePatternNode *DstPattern; // Resulting pattern. std::vector<Record*> Dstregs; // Physical register defs being matched. int AddedComplexity; // Add to matching pattern complexity. unsigned ID; // Unique ID for the record. Record *getSrcRecord() const { return SrcRecord; } ListInit *getPredicates() const { return Predicates; } TreePatternNode *getSrcPattern() const { return SrcPattern; } TreePatternNode *getDstPattern() const { return DstPattern; } const std::vector<Record*> &getDstRegs() const { return Dstregs; } int getAddedComplexity() const { return AddedComplexity; } std::string getPredicateCheck() const; /// Compute the complexity metric for the input pattern. This roughly /// corresponds to the number of nodes that are covered. int getPatternComplexity(const CodeGenDAGPatterns &CGP) const; }; class CodeGenDAGPatterns { RecordKeeper &Records; CodeGenTarget Target; std::vector<CodeGenIntrinsic> Intrinsics; std::vector<CodeGenIntrinsic> TgtIntrinsics; std::map<Record*, SDNodeInfo, LessRecordByID> SDNodes; std::map<Record*, std::pair<Record*, std::string>, LessRecordByID> SDNodeXForms; std::map<Record*, ComplexPattern, LessRecordByID> ComplexPatterns; std::map<Record *, std::unique_ptr<TreePattern>, LessRecordByID> PatternFragments; std::map<Record*, DAGDefaultOperand, LessRecordByID> DefaultOperands; std::map<Record*, DAGInstruction, LessRecordByID> Instructions; // Specific SDNode definitions: Record *intrinsic_void_sdnode; Record *intrinsic_w_chain_sdnode, *intrinsic_wo_chain_sdnode; /// PatternsToMatch - All of the things we are matching on the DAG. The first /// value is the pattern to match, the second pattern is the result to /// emit. std::vector<PatternToMatch> PatternsToMatch; public: CodeGenDAGPatterns(RecordKeeper &R); CodeGenTarget &getTargetInfo() { return Target; } const CodeGenTarget &getTargetInfo() const { return Target; } Record *getSDNodeNamed(const std::string &Name) const; const SDNodeInfo &getSDNodeInfo(Record *R) const { assert(SDNodes.count(R) && "Unknown node!"); return SDNodes.find(R)->second; } // Node transformation lookups. typedef std::pair<Record*, std::string> NodeXForm; const NodeXForm &getSDNodeTransform(Record *R) const { assert(SDNodeXForms.count(R) && "Invalid transform!"); return SDNodeXForms.find(R)->second; } typedef std::map<Record*, NodeXForm, LessRecordByID>::const_iterator nx_iterator; nx_iterator nx_begin() const { return SDNodeXForms.begin(); } nx_iterator nx_end() const { return SDNodeXForms.end(); } const ComplexPattern &getComplexPattern(Record *R) const { assert(ComplexPatterns.count(R) && "Unknown addressing mode!"); return ComplexPatterns.find(R)->second; } const CodeGenIntrinsic &getIntrinsic(Record *R) const { for (unsigned i = 0, e = Intrinsics.size(); i != e; ++i) if (Intrinsics[i].TheDef == R) return Intrinsics[i]; for (unsigned i = 0, e = TgtIntrinsics.size(); i != e; ++i) if (TgtIntrinsics[i].TheDef == R) return TgtIntrinsics[i]; llvm_unreachable("Unknown intrinsic!"); } const CodeGenIntrinsic &getIntrinsicInfo(unsigned IID) const { if (IID-1 < Intrinsics.size()) return Intrinsics[IID-1]; if (IID-Intrinsics.size()-1 < TgtIntrinsics.size()) return TgtIntrinsics[IID-Intrinsics.size()-1]; llvm_unreachable("Bad intrinsic ID!"); } unsigned getIntrinsicID(Record *R) const { for (unsigned i = 0, e = Intrinsics.size(); i != e; ++i) if (Intrinsics[i].TheDef == R) return i; for (unsigned i = 0, e = TgtIntrinsics.size(); i != e; ++i) if (TgtIntrinsics[i].TheDef == R) return i + Intrinsics.size(); llvm_unreachable("Unknown intrinsic!"); } const DAGDefaultOperand &getDefaultOperand(Record *R) const { assert(DefaultOperands.count(R) &&"Isn't an analyzed default operand!"); return DefaultOperands.find(R)->second; } // Pattern Fragment information. TreePattern *getPatternFragment(Record *R) const { assert(PatternFragments.count(R) && "Invalid pattern fragment request!"); return PatternFragments.find(R)->second.get(); } TreePattern *getPatternFragmentIfRead(Record *R) const { if (!PatternFragments.count(R)) return nullptr; return PatternFragments.find(R)->second.get(); } typedef std::map<Record *, std::unique_ptr<TreePattern>, LessRecordByID>::const_iterator pf_iterator; pf_iterator pf_begin() const { return PatternFragments.begin(); } pf_iterator pf_end() const { return PatternFragments.end(); } // Patterns to match information. typedef std::vector<PatternToMatch>::const_iterator ptm_iterator; ptm_iterator ptm_begin() const { return PatternsToMatch.begin(); } ptm_iterator ptm_end() const { return PatternsToMatch.end(); } /// Parse the Pattern for an instruction, and insert the result in DAGInsts. typedef std::map<Record*, DAGInstruction, LessRecordByID> DAGInstMap; const DAGInstruction &parseInstructionPattern( CodeGenInstruction &CGI, ListInit *Pattern, DAGInstMap &DAGInsts); const DAGInstruction &getInstruction(Record *R) const { assert(Instructions.count(R) && "Unknown instruction!"); return Instructions.find(R)->second; } Record *get_intrinsic_void_sdnode() const { return intrinsic_void_sdnode; } Record *get_intrinsic_w_chain_sdnode() const { return intrinsic_w_chain_sdnode; } Record *get_intrinsic_wo_chain_sdnode() const { return intrinsic_wo_chain_sdnode; } bool hasTargetIntrinsics() { return !TgtIntrinsics.empty(); } private: void ParseNodeInfo(); void ParseNodeTransforms(); void ParseComplexPatterns(); void ParsePatternFragments(bool OutFrags = false); void ParseDefaultOperands(); void ParseInstructions(); void ParsePatterns(); void InferInstructionFlags(); void GenerateVariants(); void VerifyInstructionFlags(); void AddPatternToMatch(TreePattern *Pattern, const PatternToMatch &PTM); void FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat, std::map<std::string, TreePatternNode*> &InstInputs, std::map<std::string, TreePatternNode*> &InstResults, std::vector<Record*> &InstImpResults); }; } // end namespace llvm #endif
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/TableGen/X86DisassemblerShared.h
//===- X86DisassemblerShared.h - Emitter shared header ----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_UTILS_TABLEGEN_X86DISASSEMBLERSHARED_H #define LLVM_UTILS_TABLEGEN_X86DISASSEMBLERSHARED_H #include "llvm/Support/X86DisassemblerDecoderCommon.h" #include "../../lib/Target/X86/Disassembler/X86DisassemblerDecoderCommon.h" #include <cstring> #include <string> struct InstructionSpecifier { llvm::X86Disassembler::OperandSpecifier operands[llvm::X86Disassembler::X86_MAX_OPERANDS]; llvm::X86Disassembler::InstructionContext insnContext; std::string name; InstructionSpecifier() { insnContext = llvm::X86Disassembler::IC; name = ""; memset(operands, 0, sizeof(operands)); } }; /// Specifies whether a ModR/M byte is needed and (if so) which /// instruction each possible value of the ModR/M byte corresponds to. Once /// this information is known, we have narrowed down to a single instruction. struct ModRMDecision { uint8_t modrm_type; llvm::X86Disassembler::InstrUID instructionIDs[256]; }; /// Specifies which set of ModR/M->instruction tables to look at /// given a particular opcode. struct OpcodeDecision { ModRMDecision modRMDecisions[256]; }; /// Specifies which opcode->instruction tables to look at given /// a particular context (set of attributes). Since there are many possible /// contexts, the decoder first uses CONTEXTS_SYM to determine which context /// applies given a specific set of attributes. Hence there are only IC_max /// entries in this table, rather than 2^(ATTR_max). struct ContextDecision { OpcodeDecision opcodeDecisions[llvm::X86Disassembler::IC_max]; }; #endif
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/TableGen/CodeEmitterGen.cpp
//===- CodeEmitterGen.cpp - Code Emitter Generator ------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // CodeEmitterGen uses the descriptions of instructions and their fields to // construct an automated code emitter: a function that, given a MachineInstr, // returns the (currently, 32-bit unsigned) value of the instruction. // //===----------------------------------------------------------------------===// #include "CodeGenTarget.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/TableGen/Record.h" #include "llvm/TableGen/TableGenBackend.h" #include <map> #include <string> #include <vector> using namespace llvm; namespace { class CodeEmitterGen { RecordKeeper &Records; public: CodeEmitterGen(RecordKeeper &R) : Records(R) {} void run(raw_ostream &o); private: int getVariableBit(const std::string &VarName, BitsInit *BI, int bit); std::string getInstructionCase(Record *R, CodeGenTarget &Target); void AddCodeToMergeInOperand(Record *R, BitsInit *BI, const std::string &VarName, unsigned &NumberedOp, std::set<unsigned> &NamedOpIndices, std::string &Case, CodeGenTarget &Target); }; // If the VarBitInit at position 'bit' matches the specified variable then // return the variable bit position. Otherwise return -1. int CodeEmitterGen::getVariableBit(const std::string &VarName, BitsInit *BI, int bit) { if (VarBitInit *VBI = dyn_cast<VarBitInit>(BI->getBit(bit))) { if (VarInit *VI = dyn_cast<VarInit>(VBI->getBitVar())) if (VI->getName() == VarName) return VBI->getBitNum(); } else if (VarInit *VI = dyn_cast<VarInit>(BI->getBit(bit))) { if (VI->getName() == VarName) return 0; } return -1; } void CodeEmitterGen:: AddCodeToMergeInOperand(Record *R, BitsInit *BI, const std::string &VarName, unsigned &NumberedOp, std::set<unsigned> &NamedOpIndices, std::string &Case, CodeGenTarget &Target) { CodeGenInstruction &CGI = Target.getInstruction(R); // Determine if VarName actually contributes to the Inst encoding. int bit = BI->getNumBits()-1; // Scan for a bit that this contributed to. for (; bit >= 0; ) { if (getVariableBit(VarName, BI, bit) != -1) break; --bit; } // If we found no bits, ignore this value, otherwise emit the call to get the // operand encoding. if (bit < 0) return; // If the operand matches by name, reference according to that // operand number. Non-matching operands are assumed to be in // order. unsigned OpIdx; if (CGI.Operands.hasOperandNamed(VarName, OpIdx)) { // Get the machine operand number for the indicated operand. OpIdx = CGI.Operands[OpIdx].MIOperandNo; assert(!CGI.Operands.isFlatOperandNotEmitted(OpIdx) && "Explicitly used operand also marked as not emitted!"); } else { unsigned NumberOps = CGI.Operands.size(); /// If this operand is not supposed to be emitted by the /// generated emitter, skip it. while (NumberedOp < NumberOps && (CGI.Operands.isFlatOperandNotEmitted(NumberedOp) || (!NamedOpIndices.empty() && NamedOpIndices.count( CGI.Operands.getSubOperandNumber(NumberedOp).first)))) { ++NumberedOp; if (NumberedOp >= CGI.Operands.back().MIOperandNo + CGI.Operands.back().MINumOperands) { errs() << "Too few operands in record " << R->getName() << " (no match for variable " << VarName << "):\n"; errs() << *R; errs() << '\n'; return; } } OpIdx = NumberedOp++; } std::pair<unsigned, unsigned> SO = CGI.Operands.getSubOperandNumber(OpIdx); std::string &EncoderMethodName = CGI.Operands[SO.first].EncoderMethodName; // If the source operand has a custom encoder, use it. This will // get the encoding for all of the suboperands. if (!EncoderMethodName.empty()) { // A custom encoder has all of the information for the // sub-operands, if there are more than one, so only // query the encoder once per source operand. if (SO.second == 0) { Case += " // op: " + VarName + "\n" + " op = " + EncoderMethodName + "(MI, " + utostr(OpIdx); Case += ", Fixups, STI"; Case += ");\n"; } } else { Case += " // op: " + VarName + "\n" + " op = getMachineOpValue(MI, MI.getOperand(" + utostr(OpIdx) + ")"; Case += ", Fixups, STI"; Case += ");\n"; } for (; bit >= 0; ) { int varBit = getVariableBit(VarName, BI, bit); // If this bit isn't from a variable, skip it. if (varBit == -1) { --bit; continue; } // Figure out the consecutive range of bits covered by this operand, in // order to generate better encoding code. int beginInstBit = bit; int beginVarBit = varBit; int N = 1; for (--bit; bit >= 0;) { varBit = getVariableBit(VarName, BI, bit); if (varBit == -1 || varBit != (beginVarBit - N)) break; ++N; --bit; } uint64_t opMask = ~(uint64_t)0 >> (64-N); int opShift = beginVarBit - N + 1; opMask <<= opShift; opShift = beginInstBit - beginVarBit; if (opShift > 0) { Case += " Value |= (op & UINT64_C(" + utostr(opMask) + ")) << " + itostr(opShift) + ";\n"; } else if (opShift < 0) { Case += " Value |= (op & UINT64_C(" + utostr(opMask) + ")) >> " + itostr(-opShift) + ";\n"; } else { Case += " Value |= op & UINT64_C(" + utostr(opMask) + ");\n"; } } } std::string CodeEmitterGen::getInstructionCase(Record *R, CodeGenTarget &Target) { std::string Case; BitsInit *BI = R->getValueAsBitsInit("Inst"); const std::vector<RecordVal> &Vals = R->getValues(); unsigned NumberedOp = 0; std::set<unsigned> NamedOpIndices; // Collect the set of operand indices that might correspond to named // operand, and skip these when assigning operands based on position. if (Target.getInstructionSet()-> getValueAsBit("noNamedPositionallyEncodedOperands")) { CodeGenInstruction &CGI = Target.getInstruction(R); for (unsigned i = 0, e = Vals.size(); i != e; ++i) { unsigned OpIdx; if (!CGI.Operands.hasOperandNamed(Vals[i].getName(), OpIdx)) continue; NamedOpIndices.insert(OpIdx); } } // Loop over all of the fields in the instruction, determining which are the // operands to the instruction. for (unsigned i = 0, e = Vals.size(); i != e; ++i) { // Ignore fixed fields in the record, we're looking for values like: // bits<5> RST = { ?, ?, ?, ?, ? }; if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete()) continue; AddCodeToMergeInOperand(R, BI, Vals[i].getName(), NumberedOp, NamedOpIndices, Case, Target); } std::string PostEmitter = R->getValueAsString("PostEncoderMethod"); if (!PostEmitter.empty()) { Case += " Value = " + PostEmitter + "(MI, Value"; Case += ", STI"; Case += ");\n"; } return Case; } void CodeEmitterGen::run(raw_ostream &o) { CodeGenTarget Target(Records); std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction"); // For little-endian instruction bit encodings, reverse the bit order Target.reverseBitsForLittleEndianEncoding(); const std::vector<const CodeGenInstruction*> &NumberedInstructions = Target.getInstructionsByEnumValue(); // Emit function declaration o << "uint64_t " << Target.getName(); o << "MCCodeEmitter::getBinaryCodeForInstr(const MCInst &MI,\n" << " SmallVectorImpl<MCFixup> &Fixups,\n" << " const MCSubtargetInfo &STI) const {\n"; // Emit instruction base values o << " static const uint64_t InstBits[] = {\n"; for (std::vector<const CodeGenInstruction*>::const_iterator IN = NumberedInstructions.begin(), EN = NumberedInstructions.end(); IN != EN; ++IN) { const CodeGenInstruction *CGI = *IN; Record *R = CGI->TheDef; if (R->getValueAsString("Namespace") == "TargetOpcode" || R->getValueAsBit("isPseudo")) { o << " UINT64_C(0),\n"; continue; } BitsInit *BI = R->getValueAsBitsInit("Inst"); // Start by filling in fixed values. uint64_t Value = 0; for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) { if (BitInit *B = dyn_cast<BitInit>(BI->getBit(e-i-1))) Value |= (uint64_t)B->getValue() << (e-i-1); } o << " UINT64_C(" << Value << ")," << '\t' << "// " << R->getName() << "\n"; } o << " UINT64_C(0)\n };\n"; // Map to accumulate all the cases. std::map<std::string, std::vector<std::string> > CaseMap; // Construct all cases statement for each opcode for (std::vector<Record*>::iterator IC = Insts.begin(), EC = Insts.end(); IC != EC; ++IC) { Record *R = *IC; if (R->getValueAsString("Namespace") == "TargetOpcode" || R->getValueAsBit("isPseudo")) continue; const std::string &InstName = R->getValueAsString("Namespace") + "::" + R->getName(); std::string Case = getInstructionCase(R, Target); CaseMap[Case].push_back(InstName); } // Emit initial function code o << " const unsigned opcode = MI.getOpcode();\n" << " uint64_t Value = InstBits[opcode];\n" << " uint64_t op = 0;\n" << " (void)op; // suppress warning\n" << " switch (opcode) {\n"; // Emit each case statement std::map<std::string, std::vector<std::string> >::iterator IE, EE; for (IE = CaseMap.begin(), EE = CaseMap.end(); IE != EE; ++IE) { const std::string &Case = IE->first; std::vector<std::string> &InstList = IE->second; for (int i = 0, N = InstList.size(); i < N; i++) { if (i) o << "\n"; o << " case " << InstList[i] << ":"; } o << " {\n"; o << Case; o << " break;\n" << " }\n"; } // Default case: unhandled opcode o << " default:\n" << " std::string msg;\n" << " raw_string_ostream Msg(msg);\n" << " Msg << \"Not supported instr: \" << MI;\n" << " report_fatal_error(Msg.str());\n" << " }\n" << " return Value;\n" << "}\n\n"; } } // End anonymous namespace namespace llvm { void EmitCodeEmitter(RecordKeeper &RK, raw_ostream &OS) { emitSourceFileHeader("Machine Code Emitter", OS); CodeEmitterGen(RK).run(OS); } } // End llvm namespace
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/TableGen/IntrinsicEmitter.cpp
//===- IntrinsicEmitter.cpp - Generate intrinsic information --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This tablegen backend emits information about intrinsic functions. // //===----------------------------------------------------------------------===// #include "CodeGenIntrinsics.h" #include "CodeGenTarget.h" #include "SequenceToOffsetTable.h" #include "TableGenBackends.h" #include "llvm/ADT/StringExtras.h" #include "llvm/TableGen/Error.h" #include "llvm/TableGen/Record.h" #include "llvm/TableGen/StringMatcher.h" #include "llvm/TableGen/TableGenBackend.h" #include <algorithm> using namespace llvm; namespace { class IntrinsicEmitter { RecordKeeper &Records; bool TargetOnly; std::string TargetPrefix; public: IntrinsicEmitter(RecordKeeper &R, bool T) : Records(R), TargetOnly(T) {} void run(raw_ostream &OS); void EmitPrefix(raw_ostream &OS); void EmitEnumInfo(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS); void EmitFnNameRecognizer(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS); void EmitIntrinsicToNameTable(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS); void EmitIntrinsicToOverloadTable(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS); void EmitGenerator(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS); void EmitAttributes(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS); void EmitModRefBehavior(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS); void EmitIntrinsicToGCCBuiltinMap(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS); void EmitIntrinsicToMSBuiltinMap(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS); void EmitSuffix(raw_ostream &OS); }; } // End anonymous namespace //===----------------------------------------------------------------------===// // IntrinsicEmitter Implementation //===----------------------------------------------------------------------===// void IntrinsicEmitter::run(raw_ostream &OS) { emitSourceFileHeader("Intrinsic Function Source Fragment", OS); std::vector<CodeGenIntrinsic> Ints = LoadIntrinsics(Records, TargetOnly); if (TargetOnly && !Ints.empty()) TargetPrefix = Ints[0].TargetPrefix; EmitPrefix(OS); // Emit the enum information. EmitEnumInfo(Ints, OS); // Emit the intrinsic ID -> name table. EmitIntrinsicToNameTable(Ints, OS); // Emit the intrinsic ID -> overload table. EmitIntrinsicToOverloadTable(Ints, OS); // Emit the function name recognizer. EmitFnNameRecognizer(Ints, OS); // Emit the intrinsic declaration generator. EmitGenerator(Ints, OS); // Emit the intrinsic parameter attributes. EmitAttributes(Ints, OS); // Emit intrinsic alias analysis mod/ref behavior. EmitModRefBehavior(Ints, OS); // Emit code to translate GCC builtins into LLVM intrinsics. EmitIntrinsicToGCCBuiltinMap(Ints, OS); // Emit code to translate MS builtins into LLVM intrinsics. EmitIntrinsicToMSBuiltinMap(Ints, OS); EmitSuffix(OS); } void IntrinsicEmitter::EmitPrefix(raw_ostream &OS) { OS << "// VisualStudio defines setjmp as _setjmp\n" "#if defined(_MSC_VER) && defined(setjmp) && \\\n" " !defined(setjmp_undefined_for_msvc)\n" "# pragma push_macro(\"setjmp\")\n" "# undef setjmp\n" "# define setjmp_undefined_for_msvc\n" "#endif\n\n"; } void IntrinsicEmitter::EmitSuffix(raw_ostream &OS) { OS << "#if defined(_MSC_VER) && defined(setjmp_undefined_for_msvc)\n" "// let's return it to _setjmp state\n" "# pragma pop_macro(\"setjmp\")\n" "# undef setjmp_undefined_for_msvc\n" "#endif\n\n"; } void IntrinsicEmitter::EmitEnumInfo(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS) { OS << "// Enum values for Intrinsics.h\n"; OS << "#ifdef GET_INTRINSIC_ENUM_VALUES\n"; for (unsigned i = 0, e = Ints.size(); i != e; ++i) { OS << " " << Ints[i].EnumName; OS << ((i != e-1) ? ", " : " "); if (Ints[i].EnumName.size() < 40) OS << std::string(40-Ints[i].EnumName.size(), ' '); OS << " // " << Ints[i].Name << "\n"; } OS << "#endif\n\n"; } void IntrinsicEmitter:: EmitFnNameRecognizer(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS) { // Build a 'first character of function name' -> intrinsic # mapping. std::map<char, std::vector<unsigned> > IntMapping; for (unsigned i = 0, e = Ints.size(); i != e; ++i) IntMapping[Ints[i].Name[5]].push_back(i); OS << "// Function name -> enum value recognizer code.\n"; OS << "#ifdef GET_FUNCTION_RECOGNIZER\n"; OS << " StringRef NameR(Name+6, Len-6); // Skip over 'llvm.'\n"; OS << " switch (Name[5]) { // Dispatch on first letter.\n"; OS << " default: break;\n"; // Emit the intrinsic matching stuff by first letter. for (std::map<char, std::vector<unsigned> >::iterator I = IntMapping.begin(), E = IntMapping.end(); I != E; ++I) { OS << " case '" << I->first << "':\n"; std::vector<unsigned> &IntList = I->second; // Sort in reverse order of intrinsic name so "abc.def" appears after // "abd.def.ghi" in the overridden name matcher std::sort(IntList.begin(), IntList.end(), [&](unsigned i, unsigned j) { return Ints[i].Name > Ints[j].Name; }); // Emit all the overloaded intrinsics first, build a table of the // non-overloaded ones. std::vector<StringMatcher::StringPair> MatchTable; for (unsigned i = 0, e = IntList.size(); i != e; ++i) { unsigned IntNo = IntList[i]; std::string Result = "return " + TargetPrefix + "Intrinsic::" + Ints[IntNo].EnumName + ";"; if (!Ints[IntNo].isOverloaded) { MatchTable.push_back(std::make_pair(Ints[IntNo].Name.substr(6),Result)); continue; } // For overloaded intrinsics, only the prefix needs to match std::string TheStr = Ints[IntNo].Name.substr(6); TheStr += '.'; // Require "bswap." instead of bswap. OS << " if (NameR.startswith(\"" << TheStr << "\")) " << Result << '\n'; } // Emit the matcher logic for the fixed length strings. StringMatcher("NameR", MatchTable, OS).Emit(1); OS << " break; // end of '" << I->first << "' case.\n"; } OS << " }\n"; OS << "#endif\n\n"; } void IntrinsicEmitter:: EmitIntrinsicToNameTable(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS) { OS << "// Intrinsic ID to name table\n"; OS << "#ifdef GET_INTRINSIC_NAME_TABLE\n"; OS << " // Note that entry #0 is the invalid intrinsic!\n"; for (unsigned i = 0, e = Ints.size(); i != e; ++i) OS << " \"" << Ints[i].Name << "\",\n"; OS << "#endif\n\n"; } void IntrinsicEmitter:: EmitIntrinsicToOverloadTable(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS) { OS << "// Intrinsic ID to overload bitset\n"; OS << "#ifdef GET_INTRINSIC_OVERLOAD_TABLE\n"; OS << "static const uint8_t OTable[] = {\n"; OS << " 0"; for (unsigned i = 0, e = Ints.size(); i != e; ++i) { // Add one to the index so we emit a null bit for the invalid #0 intrinsic. if ((i+1)%8 == 0) OS << ",\n 0"; if (Ints[i].isOverloaded) OS << " | (1<<" << (i+1)%8 << ')'; } OS << "\n};\n\n"; // OTable contains a true bit at the position if the intrinsic is overloaded. OS << "return (OTable[id/8] & (1 << (id%8))) != 0;\n"; OS << "#endif\n\n"; } // NOTE: This must be kept in synch with the copy in lib/VMCore/Function.cpp! enum IIT_Info { // Common values should be encoded with 0-15. IIT_Done = 0, IIT_I1 = 1, IIT_I8 = 2, IIT_I16 = 3, IIT_I32 = 4, IIT_I64 = 5, IIT_F16 = 6, IIT_F32 = 7, IIT_F64 = 8, IIT_V2 = 9, IIT_V4 = 10, IIT_V8 = 11, IIT_V16 = 12, IIT_V32 = 13, IIT_PTR = 14, IIT_ARG = 15, // Values from 16+ are only encodable with the inefficient encoding. IIT_V64 = 16, IIT_MMX = 17, IIT_METADATA = 18, IIT_EMPTYSTRUCT = 19, IIT_STRUCT2 = 20, IIT_STRUCT3 = 21, IIT_STRUCT4 = 22, IIT_STRUCT5 = 23, IIT_EXTEND_ARG = 24, IIT_TRUNC_ARG = 25, IIT_ANYPTR = 26, IIT_V1 = 27, IIT_VARARG = 28, IIT_HALF_VEC_ARG = 29, IIT_SAME_VEC_WIDTH_ARG = 30, IIT_PTR_TO_ARG = 31, IIT_VEC_OF_PTRS_TO_ELT = 32, IIT_I128 = 33 }; static void EncodeFixedValueType(MVT::SimpleValueType VT, std::vector<unsigned char> &Sig) { if (MVT(VT).isInteger()) { unsigned BitWidth = MVT(VT).getSizeInBits(); switch (BitWidth) { default: PrintFatalError("unhandled integer type width in intrinsic!"); case 1: return Sig.push_back(IIT_I1); case 8: return Sig.push_back(IIT_I8); case 16: return Sig.push_back(IIT_I16); case 32: return Sig.push_back(IIT_I32); case 64: return Sig.push_back(IIT_I64); case 128: return Sig.push_back(IIT_I128); } } switch (VT) { default: PrintFatalError("unhandled MVT in intrinsic!"); case MVT::f16: return Sig.push_back(IIT_F16); case MVT::f32: return Sig.push_back(IIT_F32); case MVT::f64: return Sig.push_back(IIT_F64); case MVT::Metadata: return Sig.push_back(IIT_METADATA); case MVT::x86mmx: return Sig.push_back(IIT_MMX); // MVT::OtherVT is used to mean the empty struct type here. case MVT::Other: return Sig.push_back(IIT_EMPTYSTRUCT); // MVT::isVoid is used to represent varargs here. case MVT::isVoid: return Sig.push_back(IIT_VARARG); } } #if defined(_MSC_VER) && !defined(__clang__) // HLSL Comment - still a problem with more recent versions #pragma optimize("",off) // MSVC 2010 optimizer can't deal with this function. #endif static void EncodeFixedType(Record *R, std::vector<unsigned char> &ArgCodes, std::vector<unsigned char> &Sig) { if (R->isSubClassOf("LLVMMatchType")) { unsigned Number = R->getValueAsInt("Number"); assert(Number < ArgCodes.size() && "Invalid matching number!"); if (R->isSubClassOf("LLVMExtendedType")) Sig.push_back(IIT_EXTEND_ARG); else if (R->isSubClassOf("LLVMTruncatedType")) Sig.push_back(IIT_TRUNC_ARG); else if (R->isSubClassOf("LLVMHalfElementsVectorType")) Sig.push_back(IIT_HALF_VEC_ARG); else if (R->isSubClassOf("LLVMVectorSameWidth")) { Sig.push_back(IIT_SAME_VEC_WIDTH_ARG); Sig.push_back((Number << 3) | ArgCodes[Number]); MVT::SimpleValueType VT = getValueType(R->getValueAsDef("ElTy")); EncodeFixedValueType(VT, Sig); return; } else if (R->isSubClassOf("LLVMPointerTo")) Sig.push_back(IIT_PTR_TO_ARG); else if (R->isSubClassOf("LLVMVectorOfPointersToElt")) Sig.push_back(IIT_VEC_OF_PTRS_TO_ELT); else Sig.push_back(IIT_ARG); return Sig.push_back((Number << 3) | ArgCodes[Number]); } MVT::SimpleValueType VT = getValueType(R->getValueAsDef("VT")); unsigned Tmp = 0; switch (VT) { default: break; case MVT::iPTRAny: ++Tmp; LLVM_FALLTHROUGH; // HLSL Change case MVT::vAny: ++Tmp; LLVM_FALLTHROUGH; // HLSL Change case MVT::fAny: ++Tmp; LLVM_FALLTHROUGH; // HLSL Change case MVT::iAny: ++Tmp; LLVM_FALLTHROUGH; // HLSL Change case MVT::Any: { // If this is an "any" valuetype, then the type is the type of the next // type in the list specified to getIntrinsic(). Sig.push_back(IIT_ARG); // Figure out what arg # this is consuming, and remember what kind it was. unsigned ArgNo = ArgCodes.size(); ArgCodes.push_back(Tmp); // Encode what sort of argument it must be in the low 3 bits of the ArgNo. return Sig.push_back((ArgNo << 3) | Tmp); } case MVT::iPTR: { unsigned AddrSpace = 0; if (R->isSubClassOf("LLVMQualPointerType")) { AddrSpace = R->getValueAsInt("AddrSpace"); assert(AddrSpace < 256 && "Address space exceeds 255"); } if (AddrSpace) { Sig.push_back(IIT_ANYPTR); Sig.push_back(AddrSpace); } else { Sig.push_back(IIT_PTR); } return EncodeFixedType(R->getValueAsDef("ElTy"), ArgCodes, Sig); } } if (MVT(VT).isVector()) { MVT VVT = VT; switch (VVT.getVectorNumElements()) { default: PrintFatalError("unhandled vector type width in intrinsic!"); case 1: Sig.push_back(IIT_V1); break; case 2: Sig.push_back(IIT_V2); break; case 4: Sig.push_back(IIT_V4); break; case 8: Sig.push_back(IIT_V8); break; case 16: Sig.push_back(IIT_V16); break; case 32: Sig.push_back(IIT_V32); break; case 64: Sig.push_back(IIT_V64); break; } return EncodeFixedValueType(VVT.getVectorElementType().SimpleTy, Sig); } EncodeFixedValueType(VT, Sig); } #if defined(_MSC_VER) && !defined(__clang__) #pragma optimize("",on) #endif /// ComputeFixedEncoding - If we can encode the type signature for this /// intrinsic into 32 bits, return it. If not, return ~0U. static void ComputeFixedEncoding(const CodeGenIntrinsic &Int, std::vector<unsigned char> &TypeSig) { std::vector<unsigned char> ArgCodes; if (Int.IS.RetVTs.empty()) TypeSig.push_back(IIT_Done); else if (Int.IS.RetVTs.size() == 1 && Int.IS.RetVTs[0] == MVT::isVoid) TypeSig.push_back(IIT_Done); else { switch (Int.IS.RetVTs.size()) { case 1: break; case 2: TypeSig.push_back(IIT_STRUCT2); break; case 3: TypeSig.push_back(IIT_STRUCT3); break; case 4: TypeSig.push_back(IIT_STRUCT4); break; case 5: TypeSig.push_back(IIT_STRUCT5); break; default: llvm_unreachable("Unhandled case in struct"); } for (unsigned i = 0, e = Int.IS.RetVTs.size(); i != e; ++i) EncodeFixedType(Int.IS.RetTypeDefs[i], ArgCodes, TypeSig); } for (unsigned i = 0, e = Int.IS.ParamTypeDefs.size(); i != e; ++i) EncodeFixedType(Int.IS.ParamTypeDefs[i], ArgCodes, TypeSig); } static void printIITEntry(raw_ostream &OS, unsigned char X) { OS << (unsigned)X; } void IntrinsicEmitter::EmitGenerator(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS) { // If we can compute a 32-bit fixed encoding for this intrinsic, do so and // capture it in this vector, otherwise store a ~0U. std::vector<unsigned> FixedEncodings; SequenceToOffsetTable<std::vector<unsigned char> > LongEncodingTable; std::vector<unsigned char> TypeSig; // Compute the unique argument type info. for (unsigned i = 0, e = Ints.size(); i != e; ++i) { // Get the signature for the intrinsic. TypeSig.clear(); ComputeFixedEncoding(Ints[i], TypeSig); // Check to see if we can encode it into a 32-bit word. We can only encode // 8 nibbles into a 32-bit word. if (TypeSig.size() <= 8) { bool Failed = false; unsigned Result = 0; for (unsigned i = 0, e = TypeSig.size(); i != e; ++i) { // If we had an unencodable argument, bail out. if (TypeSig[i] > 15) { Failed = true; break; } Result = (Result << 4) | TypeSig[e-i-1]; } // If this could be encoded into a 31-bit word, return it. if (!Failed && (Result >> 31) == 0) { FixedEncodings.push_back(Result); continue; } } // Otherwise, we're going to unique the sequence into the // LongEncodingTable, and use its offset in the 32-bit table instead. LongEncodingTable.add(TypeSig); // This is a placehold that we'll replace after the table is laid out. FixedEncodings.push_back(~0U); } LongEncodingTable.layout(); OS << "// Global intrinsic function declaration type table.\n"; OS << "#ifdef GET_INTRINSIC_GENERATOR_GLOBAL\n"; OS << "static const unsigned IIT_Table[] = {\n "; for (unsigned i = 0, e = FixedEncodings.size(); i != e; ++i) { if ((i & 7) == 7) OS << "\n "; // If the entry fit in the table, just emit it. if (FixedEncodings[i] != ~0U) { OS << "0x" << utohexstr(FixedEncodings[i]) << ", "; continue; } TypeSig.clear(); ComputeFixedEncoding(Ints[i], TypeSig); // Otherwise, emit the offset into the long encoding table. We emit it this // way so that it is easier to read the offset in the .def file. OS << "(1U<<31) | " << LongEncodingTable.get(TypeSig) << ", "; } OS << "0\n};\n\n"; // Emit the shared table of register lists. OS << "static const unsigned char IIT_LongEncodingTable[] = {\n"; if (!LongEncodingTable.empty()) LongEncodingTable.emit(OS, printIITEntry); OS << " 255\n};\n\n"; OS << "#endif\n\n"; // End of GET_INTRINSIC_GENERATOR_GLOBAL } namespace { enum ModRefKind { MRK_none, MRK_readonly, MRK_readnone }; } static ModRefKind getModRefKind(const CodeGenIntrinsic &intrinsic) { switch (intrinsic.ModRef) { case CodeGenIntrinsic::NoMem: return MRK_readnone; case CodeGenIntrinsic::ReadArgMem: case CodeGenIntrinsic::ReadMem: return MRK_readonly; case CodeGenIntrinsic::ReadWriteArgMem: case CodeGenIntrinsic::ReadWriteMem: return MRK_none; } llvm_unreachable("bad mod-ref kind"); } namespace { struct AttributeComparator { bool operator()(const CodeGenIntrinsic *L, const CodeGenIntrinsic *R) const { // Sort throwing intrinsics after non-throwing intrinsics. if (L->canThrow != R->canThrow) return R->canThrow; if (L->isNoDuplicate != R->isNoDuplicate) return R->isNoDuplicate; if (L->isNoReturn != R->isNoReturn) return R->isNoReturn; if (L->isConvergent != R->isConvergent) return R->isConvergent; // Try to order by readonly/readnone attribute. ModRefKind LK = getModRefKind(*L); ModRefKind RK = getModRefKind(*R); if (LK != RK) return (LK > RK); // Order by argument attributes. // This is reliable because each side is already sorted internally. return (L->ArgumentAttributes < R->ArgumentAttributes); } }; } // End anonymous namespace /// EmitAttributes - This emits the Intrinsic::getAttributes method. void IntrinsicEmitter:: EmitAttributes(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS) { OS << "// Add parameter attributes that are not common to all intrinsics.\n"; OS << "#ifdef GET_INTRINSIC_ATTRIBUTES\n"; if (TargetOnly) OS << "static AttributeSet getAttributes(LLVMContext &C, " << TargetPrefix << "Intrinsic::ID id) {\n"; else OS << "AttributeSet Intrinsic::getAttributes(LLVMContext &C, ID id) {\n"; // Compute the maximum number of attribute arguments and the map typedef std::map<const CodeGenIntrinsic*, unsigned, AttributeComparator> UniqAttrMapTy; UniqAttrMapTy UniqAttributes; unsigned maxArgAttrs = 0; unsigned AttrNum = 0; for (unsigned i = 0, e = Ints.size(); i != e; ++i) { const CodeGenIntrinsic &intrinsic = Ints[i]; maxArgAttrs = std::max(maxArgAttrs, unsigned(intrinsic.ArgumentAttributes.size())); unsigned &N = UniqAttributes[&intrinsic]; if (N) continue; assert(AttrNum < 256 && "Too many unique attributes for table!"); N = ++AttrNum; } // Emit an array of AttributeSet. Most intrinsics will have at least one // entry, for the function itself (index ~1), which is usually nounwind. OS << " static const uint8_t IntrinsicsToAttributesMap[] = {\n"; for (unsigned i = 0, e = Ints.size(); i != e; ++i) { const CodeGenIntrinsic &intrinsic = Ints[i]; OS << " " << UniqAttributes[&intrinsic] << ", // " << intrinsic.Name << "\n"; } OS << " };\n\n"; OS << " AttributeSet AS[" << maxArgAttrs+1 << "];\n"; OS << " unsigned NumAttrs = 0;\n"; OS << " if (id != 0) {\n"; OS << " switch(IntrinsicsToAttributesMap[id - "; if (TargetOnly) OS << "Intrinsic::num_intrinsics"; else OS << "1"; OS << "]) {\n"; OS << " default: llvm_unreachable(\"Invalid attribute number\");\n"; for (UniqAttrMapTy::const_iterator I = UniqAttributes.begin(), E = UniqAttributes.end(); I != E; ++I) { OS << " case " << I->second << ": {\n"; const CodeGenIntrinsic &intrinsic = *(I->first); // Keep track of the number of attributes we're writing out. unsigned numAttrs = 0; // The argument attributes are alreadys sorted by argument index. unsigned ai = 0, ae = intrinsic.ArgumentAttributes.size(); if (ae) { while (ai != ae) { unsigned argNo = intrinsic.ArgumentAttributes[ai].first; OS << " const Attribute::AttrKind AttrParam" << argNo + 1 <<"[]= {"; bool addComma = false; do { switch (intrinsic.ArgumentAttributes[ai].second) { case CodeGenIntrinsic::NoCapture: if (addComma) OS << ","; OS << "Attribute::NoCapture"; addComma = true; break; case CodeGenIntrinsic::ReadOnly: if (addComma) OS << ","; OS << "Attribute::ReadOnly"; addComma = true; break; case CodeGenIntrinsic::ReadNone: if (addComma) OS << ","; OS << "Attributes::ReadNone"; addComma = true; break; } ++ai; } while (ai != ae && intrinsic.ArgumentAttributes[ai].first == argNo); OS << "};\n"; OS << " AS[" << numAttrs++ << "] = AttributeSet::get(C, " << argNo+1 << ", AttrParam" << argNo +1 << ");\n"; } } ModRefKind modRef = getModRefKind(intrinsic); if (!intrinsic.canThrow || modRef || intrinsic.isNoReturn || intrinsic.isNoDuplicate || intrinsic.isConvergent) { OS << " const Attribute::AttrKind Atts[] = {"; bool addComma = false; if (!intrinsic.canThrow) { OS << "Attribute::NoUnwind"; addComma = true; } if (intrinsic.isNoReturn) { if (addComma) OS << ","; OS << "Attribute::NoReturn"; addComma = true; } if (intrinsic.isNoDuplicate) { if (addComma) OS << ","; OS << "Attribute::NoDuplicate"; addComma = true; } if (intrinsic.isConvergent) { if (addComma) OS << ","; OS << "Attribute::Convergent"; addComma = true; } switch (modRef) { case MRK_none: break; case MRK_readonly: if (addComma) OS << ","; OS << "Attribute::ReadOnly"; break; case MRK_readnone: if (addComma) OS << ","; OS << "Attribute::ReadNone"; break; } OS << "};\n"; OS << " AS[" << numAttrs++ << "] = AttributeSet::get(C, " << "AttributeSet::FunctionIndex, Atts);\n"; } if (numAttrs) { OS << " NumAttrs = " << numAttrs << ";\n"; OS << " break;\n"; OS << " }\n"; } else { OS << " return AttributeSet();\n"; OS << " }\n"; } } OS << " }\n"; OS << " }\n"; OS << " return AttributeSet::get(C, makeArrayRef(AS, NumAttrs));\n"; OS << "}\n"; OS << "#endif // GET_INTRINSIC_ATTRIBUTES\n\n"; } /// EmitModRefBehavior - Determine intrinsic alias analysis mod/ref behavior. void IntrinsicEmitter:: EmitModRefBehavior(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS){ OS << "// Determine intrinsic alias analysis mod/ref behavior.\n" << "#ifdef GET_INTRINSIC_MODREF_BEHAVIOR\n" << "assert(iid <= Intrinsic::" << Ints.back().EnumName << " && " << "\"Unknown intrinsic.\");\n\n"; OS << "static const uint8_t IntrinsicModRefBehavior[] = {\n" << " /* invalid */ UnknownModRefBehavior,\n"; for (unsigned i = 0, e = Ints.size(); i != e; ++i) { OS << " /* " << TargetPrefix << Ints[i].EnumName << " */ "; switch (Ints[i].ModRef) { case CodeGenIntrinsic::NoMem: OS << "DoesNotAccessMemory,\n"; break; case CodeGenIntrinsic::ReadArgMem: OS << "OnlyReadsArgumentPointees,\n"; break; case CodeGenIntrinsic::ReadMem: OS << "OnlyReadsMemory,\n"; break; case CodeGenIntrinsic::ReadWriteArgMem: OS << "OnlyAccessesArgumentPointees,\n"; break; case CodeGenIntrinsic::ReadWriteMem: OS << "UnknownModRefBehavior,\n"; break; } } OS << "};\n\n" << "return static_cast<ModRefBehavior>(IntrinsicModRefBehavior[iid]);\n" << "#endif // GET_INTRINSIC_MODREF_BEHAVIOR\n\n"; } /// EmitTargetBuiltins - All of the builtins in the specified map are for the /// same target, and we already checked it. static void EmitTargetBuiltins(const std::map<std::string, std::string> &BIM, const std::string &TargetPrefix, raw_ostream &OS) { std::vector<StringMatcher::StringPair> Results; for (std::map<std::string, std::string>::const_iterator I = BIM.begin(), E = BIM.end(); I != E; ++I) { std::string ResultCode = "return " + TargetPrefix + "Intrinsic::" + I->second + ";"; Results.emplace_back(I->first, ResultCode); } StringMatcher("BuiltinName", Results, OS).Emit(); } void IntrinsicEmitter:: EmitIntrinsicToGCCBuiltinMap(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS) { typedef std::map<std::string, std::map<std::string, std::string> > BIMTy; BIMTy BuiltinMap; for (unsigned i = 0, e = Ints.size(); i != e; ++i) { if (!Ints[i].GCCBuiltinName.empty()) { // Get the map for this target prefix. std::map<std::string, std::string> &BIM =BuiltinMap[Ints[i].TargetPrefix]; if (!BIM.insert(std::make_pair(Ints[i].GCCBuiltinName, Ints[i].EnumName)).second) PrintFatalError("Intrinsic '" + Ints[i].TheDef->getName() + "': duplicate GCC builtin name!"); } } OS << "// Get the LLVM intrinsic that corresponds to a GCC builtin.\n"; OS << "// This is used by the C front-end. The GCC builtin name is passed\n"; OS << "// in as BuiltinName, and a target prefix (e.g. 'ppc') is passed\n"; OS << "// in as TargetPrefix. The result is assigned to 'IntrinsicID'.\n"; OS << "#ifdef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN\n"; if (TargetOnly) { OS << "static " << TargetPrefix << "Intrinsic::ID " << "getIntrinsicForGCCBuiltin(const char " << "*TargetPrefixStr, const char *BuiltinNameStr) {\n"; } else { OS << "Intrinsic::ID Intrinsic::getIntrinsicForGCCBuiltin(const char " << "*TargetPrefixStr, const char *BuiltinNameStr) {\n"; } OS << " StringRef BuiltinName(BuiltinNameStr);\n"; OS << " StringRef TargetPrefix(TargetPrefixStr);\n\n"; // Note: this could emit significantly better code if we cared. for (BIMTy::iterator I = BuiltinMap.begin(), E = BuiltinMap.end();I != E;++I){ OS << " "; if (!I->first.empty()) OS << "if (TargetPrefix == \"" << I->first << "\") "; else OS << "/* Target Independent Builtins */ "; OS << "{\n"; // Emit the comparisons for this target prefix. EmitTargetBuiltins(I->second, TargetPrefix, OS); OS << " }\n"; } OS << " return "; if (!TargetPrefix.empty()) OS << "(" << TargetPrefix << "Intrinsic::ID)"; OS << "Intrinsic::not_intrinsic;\n"; OS << "}\n"; OS << "#endif\n\n"; } void IntrinsicEmitter:: EmitIntrinsicToMSBuiltinMap(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS) { std::map<std::string, std::map<std::string, std::string>> TargetBuiltins; for (const auto &Intrinsic : Ints) { if (Intrinsic.MSBuiltinName.empty()) continue; auto &Builtins = TargetBuiltins[Intrinsic.TargetPrefix]; if (!Builtins.insert(std::make_pair(Intrinsic.MSBuiltinName, Intrinsic.EnumName)).second) PrintFatalError("Intrinsic '" + Intrinsic.TheDef->getName() + "': " "duplicate MS builtin name!"); } OS << "// Get the LLVM intrinsic that corresponds to a MS builtin.\n" "// This is used by the C front-end. The MS builtin name is passed\n" "// in as a BuiltinName, and a target prefix (e.g. 'arm') is passed\n" "// in as a TargetPrefix. The result is assigned to 'IntrinsicID'.\n" "#ifdef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN\n"; OS << (TargetOnly ? "static " + TargetPrefix : "") << "Intrinsic::ID " << (TargetOnly ? "" : "Intrinsic::") << "getIntrinsicForMSBuiltin(const char *TP, const char *BN) {\n"; OS << " StringRef BuiltinName(BN);\n" " StringRef TargetPrefix(TP);\n" "\n"; for (const auto &Builtins : TargetBuiltins) { OS << " "; if (Builtins.first.empty()) OS << "/* Target Independent Builtins */ "; else OS << "if (TargetPrefix == \"" << Builtins.first << "\") "; OS << "{\n"; EmitTargetBuiltins(Builtins.second, TargetPrefix, OS); OS << "}"; } OS << " return "; if (!TargetPrefix.empty()) OS << "(" << TargetPrefix << "Intrinsic::ID)"; OS << "Intrinsic::not_intrinsic;\n"; OS << "}\n"; OS << "#endif\n\n"; } void llvm::EmitIntrinsics(RecordKeeper &RK, raw_ostream &OS, bool TargetOnly) { IntrinsicEmitter(RK, TargetOnly).run(OS); }
0
repos/DirectXShaderCompiler/utils
repos/DirectXShaderCompiler/utils/TableGen/CodeGenInstruction.h
//===- CodeGenInstruction.h - Instruction Class Wrapper ---------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines a wrapper class for the 'Instruction' TableGen class. // //===----------------------------------------------------------------------===// #ifndef LLVM_UTILS_TABLEGEN_CODEGENINSTRUCTION_H #define LLVM_UTILS_TABLEGEN_CODEGENINSTRUCTION_H #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/StringRef.h" #include "llvm/CodeGen/MachineValueType.h" #include "llvm/Support/SMLoc.h" #include <string> #include <utility> #include <vector> namespace llvm { class Record; class DagInit; class CodeGenTarget; class StringRef; class CGIOperandList { public: class ConstraintInfo { enum { None, EarlyClobber, Tied } Kind; unsigned OtherTiedOperand; public: ConstraintInfo() : Kind(None) {} static ConstraintInfo getEarlyClobber() { ConstraintInfo I; I.Kind = EarlyClobber; I.OtherTiedOperand = 0; return I; } static ConstraintInfo getTied(unsigned Op) { ConstraintInfo I; I.Kind = Tied; I.OtherTiedOperand = Op; return I; } bool isNone() const { return Kind == None; } bool isEarlyClobber() const { return Kind == EarlyClobber; } bool isTied() const { return Kind == Tied; } unsigned getTiedOperand() const { assert(isTied()); return OtherTiedOperand; } }; /// OperandInfo - The information we keep track of for each operand in the /// operand list for a tablegen instruction. struct OperandInfo { /// Rec - The definition this operand is declared as. /// Record *Rec; /// Name - If this operand was assigned a symbolic name, this is it, /// otherwise, it's empty. std::string Name; /// PrinterMethodName - The method used to print operands of this type in /// the asmprinter. std::string PrinterMethodName; /// EncoderMethodName - The method used to get the machine operand value /// for binary encoding. "getMachineOpValue" by default. std::string EncoderMethodName; /// OperandType - A value from MCOI::OperandType representing the type of /// the operand. std::string OperandType; /// MIOperandNo - Currently (this is meant to be phased out), some logical /// operands correspond to multiple MachineInstr operands. In the X86 /// target for example, one address operand is represented as 4 /// MachineOperands. Because of this, the operand number in the /// OperandList may not match the MachineInstr operand num. Until it /// does, this contains the MI operand index of this operand. unsigned MIOperandNo; unsigned MINumOperands; // The number of operands. /// DoNotEncode - Bools are set to true in this vector for each operand in /// the DisableEncoding list. These should not be emitted by the code /// emitter. std::vector<bool> DoNotEncode; /// MIOperandInfo - Default MI operand type. Note an operand may be made /// up of multiple MI operands. DagInit *MIOperandInfo; /// Constraint info for this operand. This operand can have pieces, so we /// track constraint info for each. std::vector<ConstraintInfo> Constraints; OperandInfo(Record *R, const std::string &N, const std::string &PMN, const std::string &EMN, const std::string &OT, unsigned MION, unsigned MINO, DagInit *MIOI) : Rec(R), Name(N), PrinterMethodName(PMN), EncoderMethodName(EMN), OperandType(OT), MIOperandNo(MION), MINumOperands(MINO), MIOperandInfo(MIOI) {} /// getTiedOperand - If this operand is tied to another one, return the /// other operand number. Otherwise, return -1. int getTiedRegister() const { for (unsigned j = 0, e = Constraints.size(); j != e; ++j) { const CGIOperandList::ConstraintInfo &CI = Constraints[j]; if (CI.isTied()) return CI.getTiedOperand(); } return -1; } }; CGIOperandList(Record *D); Record *TheDef; // The actual record containing this OperandList. /// NumDefs - Number of def operands declared, this is the number of /// elements in the instruction's (outs) list. /// unsigned NumDefs; /// OperandList - The list of declared operands, along with their declared /// type (which is a record). std::vector<OperandInfo> OperandList; // Information gleaned from the operand list. bool isPredicable; bool hasOptionalDef; bool isVariadic; // Provide transparent accessors to the operand list. bool empty() const { return OperandList.empty(); } unsigned size() const { return OperandList.size(); } const OperandInfo &operator[](unsigned i) const { return OperandList[i]; } OperandInfo &operator[](unsigned i) { return OperandList[i]; } OperandInfo &back() { return OperandList.back(); } const OperandInfo &back() const { return OperandList.back(); } typedef std::vector<OperandInfo>::iterator iterator; typedef std::vector<OperandInfo>::const_iterator const_iterator; iterator begin() { return OperandList.begin(); } const_iterator begin() const { return OperandList.begin(); } iterator end() { return OperandList.end(); } const_iterator end() const { return OperandList.end(); } /// getOperandNamed - Return the index of the operand with the specified /// non-empty name. If the instruction does not have an operand with the /// specified name, abort. unsigned getOperandNamed(StringRef Name) const; /// hasOperandNamed - Query whether the instruction has an operand of the /// given name. If so, return true and set OpIdx to the index of the /// operand. Otherwise, return false. bool hasOperandNamed(StringRef Name, unsigned &OpIdx) const; /// ParseOperandName - Parse an operand name like "$foo" or "$foo.bar", /// where $foo is a whole operand and $foo.bar refers to a suboperand. /// This aborts if the name is invalid. If AllowWholeOp is true, references /// to operands with suboperands are allowed, otherwise not. std::pair<unsigned,unsigned> ParseOperandName(const std::string &Op, bool AllowWholeOp = true); /// getFlattenedOperandNumber - Flatten a operand/suboperand pair into a /// flat machineinstr operand #. unsigned getFlattenedOperandNumber(std::pair<unsigned,unsigned> Op) const { return OperandList[Op.first].MIOperandNo + Op.second; } /// getSubOperandNumber - Unflatten a operand number into an /// operand/suboperand pair. std::pair<unsigned,unsigned> getSubOperandNumber(unsigned Op) const { for (unsigned i = 0; ; ++i) { assert(i < OperandList.size() && "Invalid flat operand #"); if (OperandList[i].MIOperandNo+OperandList[i].MINumOperands > Op) return std::make_pair(i, Op-OperandList[i].MIOperandNo); } } /// isFlatOperandNotEmitted - Return true if the specified flat operand # /// should not be emitted with the code emitter. bool isFlatOperandNotEmitted(unsigned FlatOpNo) const { std::pair<unsigned,unsigned> Op = getSubOperandNumber(FlatOpNo); if (OperandList[Op.first].DoNotEncode.size() > Op.second) return OperandList[Op.first].DoNotEncode[Op.second]; return false; } void ProcessDisableEncoding(std::string Value); }; class CodeGenInstruction { public: Record *TheDef; // The actual record defining this instruction. std::string Namespace; // The namespace the instruction is in. /// AsmString - The format string used to emit a .s file for the /// instruction. std::string AsmString; /// Operands - This is information about the (ins) and (outs) list specified /// to the instruction. CGIOperandList Operands; /// ImplicitDefs/ImplicitUses - These are lists of registers that are /// implicitly defined and used by the instruction. std::vector<Record*> ImplicitDefs, ImplicitUses; // Various boolean values we track for the instruction. bool isReturn : 1; bool isBranch : 1; bool isIndirectBranch : 1; bool isCompare : 1; bool isMoveImm : 1; bool isBitcast : 1; bool isSelect : 1; bool isBarrier : 1; bool isCall : 1; bool canFoldAsLoad : 1; bool mayLoad : 1; bool mayLoad_Unset : 1; bool mayStore : 1; bool mayStore_Unset : 1; bool isPredicable : 1; bool isConvertibleToThreeAddress : 1; bool isCommutable : 1; bool isTerminator : 1; bool isReMaterializable : 1; bool hasDelaySlot : 1; bool usesCustomInserter : 1; bool hasPostISelHook : 1; bool hasCtrlDep : 1; bool isNotDuplicable : 1; bool hasSideEffects : 1; bool hasSideEffects_Unset : 1; bool isAsCheapAsAMove : 1; bool hasExtraSrcRegAllocReq : 1; bool hasExtraDefRegAllocReq : 1; bool isCodeGenOnly : 1; bool isPseudo : 1; bool isRegSequence : 1; bool isExtractSubreg : 1; bool isInsertSubreg : 1; bool isConvergent : 1; std::string DeprecatedReason; bool HasComplexDeprecationPredicate; /// Are there any undefined flags? bool hasUndefFlags() const { return mayLoad_Unset || mayStore_Unset || hasSideEffects_Unset; } // The record used to infer instruction flags, or NULL if no flag values // have been inferred. Record *InferredFrom; CodeGenInstruction(Record *R); /// HasOneImplicitDefWithKnownVT - If the instruction has at least one /// implicit def and it has a known VT, return the VT, otherwise return /// MVT::Other. MVT::SimpleValueType HasOneImplicitDefWithKnownVT(const CodeGenTarget &TargetInfo) const; /// FlattenAsmStringVariants - Flatten the specified AsmString to only /// include text from the specified variant, returning the new string. static std::string FlattenAsmStringVariants(StringRef AsmString, unsigned Variant); }; /// CodeGenInstAlias - This represents an InstAlias definition. class CodeGenInstAlias { public: Record *TheDef; // The actual record defining this InstAlias. /// AsmString - The format string used to emit a .s file for the /// instruction. std::string AsmString; /// Result - The result instruction. DagInit *Result; /// ResultInst - The instruction generated by the alias (decoded from /// Result). CodeGenInstruction *ResultInst; struct ResultOperand { private: std::string Name; Record *R; int64_t Imm; public: enum { K_Record, K_Imm, K_Reg } Kind; ResultOperand(std::string N, Record *r) : Name(N), R(r), Kind(K_Record) {} ResultOperand(int64_t I) : Imm(I), Kind(K_Imm) {} ResultOperand(Record *r) : R(r), Kind(K_Reg) {} bool isRecord() const { return Kind == K_Record; } bool isImm() const { return Kind == K_Imm; } bool isReg() const { return Kind == K_Reg; } StringRef getName() const { assert(isRecord()); return Name; } Record *getRecord() const { assert(isRecord()); return R; } int64_t getImm() const { assert(isImm()); return Imm; } Record *getRegister() const { assert(isReg()); return R; } unsigned getMINumOperands() const; }; /// ResultOperands - The decoded operands for the result instruction. std::vector<ResultOperand> ResultOperands; /// ResultInstOperandIndex - For each operand, this vector holds a pair of /// indices to identify the corresponding operand in the result /// instruction. The first index specifies the operand and the second /// index specifies the suboperand. If there are no suboperands or if all /// of them are matched by the operand, the second value should be -1. std::vector<std::pair<unsigned, int> > ResultInstOperandIndex; CodeGenInstAlias(Record *R, unsigned Variant, CodeGenTarget &T); bool tryAliasOpMatch(DagInit *Result, unsigned AliasOpNo, Record *InstOpRec, bool hasSubOps, ArrayRef<SMLoc> Loc, CodeGenTarget &T, ResultOperand &ResOp); }; } #endif