diff --git a/Dockerfile b/Dockerfile
index dbe5194..5db2460 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -74,10 +74,6 @@ run locale-gen
# expand libc sources
run cd /usr/src/glibc ; tar xvf glibc-*.tar.xz
-# build rtags
-copy rtags.zip /externals/
-run cd /externals/ && unzip rtags.zip && cd rtags && cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=1 && make -j$(nproc) install && rm -rf /externals
-
# build cgdb (the version shipped with ubuntu is too old)
copy cgdb-0.7.0.tar.gz /externals/
run cd /externals/ && tar -xvzf cgdb-0.7.0.tar.gz && cd cgdb-0.7.0 && ./configure && make -j$(nproc) && make install
@@ -112,4 +108,8 @@ RUN curl -SL $DOTNET_SDK_DOWNLOAD_URL --output dotnet.tar.gz \
&& rm dotnet.tar.gz \
&& ln -s /usr/share/dotnet/dotnet /usr/bin/dotnet
+# build rtags
+copy rtags /rtags/
+run cd /rtags && cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=1 && make -j$(nproc) install
+run rm -rf /rtags
diff --git a/rtags.zip b/rtags.zip
deleted file mode 100644
index 04c84c5..0000000
Binary files a/rtags.zip and /dev/null differ
diff --git a/rtags/.dir-locals.el b/rtags/.dir-locals.el
new file mode 100644
index 0000000..98c6493
--- /dev/null
+++ b/rtags/.dir-locals.el
@@ -0,0 +1,15 @@
+;;; Directory Local Variables
+;;; For more information see (info "(emacs) Directory Variables")
+
+((nil
+ (indent-tabs-mode))
+ (c++-mode
+ (c-basic-offset . 4)
+ (indent-tabs-mode))
+ (cmake-mode
+ (cmake-tab-width . 4)
+ (indent-tabs-mode))
+ (python-mode
+ (python-indent-offset . 4)
+ (tab-width . 4)
+ (indent-tabs-mode)))
diff --git a/rtags/.github/ISSUE_TEMPLATE/bug_report.md b/rtags/.github/ISSUE_TEMPLATE/bug_report.md
new file mode 100644
index 0000000..0c32fb5
--- /dev/null
+++ b/rtags/.github/ISSUE_TEMPLATE/bug_report.md
@@ -0,0 +1,30 @@
+---
+name: Bug report
+about: Create a report to help us improve
+
+---
+
+**Describe the bug**
+A clear and concise description of what the bug is.
+
+**To Reproduce**
+Steps to reproduce the behavior:
+1. Go to '...'
+2. Click on '....'
+3. Scroll down to '....'
+4. See error
+
+**Expected behavior**
+A clear and concise description of what you expected to happen.
+
+**Screenshots/Backtrace**
+If applicable, add screenshots or/and a backtrace.
+
+**Environment (please complete the following information):**
+ - OS/Version: [e.g. iOS; Fedora 26; Ubuntu]
+ - RTags(rdm,rc): [e.g. 2.18 or/and revision]
+ - Emacs: [e.g. 24.5]
+ - LLVM/Clang: [e.g. 4.3]
+
+**Additional context**
+Add any other context about the problem here.
diff --git a/rtags/.github/ISSUE_TEMPLATE/feature_request.md b/rtags/.github/ISSUE_TEMPLATE/feature_request.md
new file mode 100644
index 0000000..066b2d9
--- /dev/null
+++ b/rtags/.github/ISSUE_TEMPLATE/feature_request.md
@@ -0,0 +1,17 @@
+---
+name: Feature request
+about: Suggest an idea for this project
+
+---
+
+**Is your feature request related to a problem? Please describe.**
+A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
+
+**Describe the solution you'd like**
+A clear and concise description of what you want to happen.
+
+**Describe alternatives you've considered**
+A clear and concise description of any alternative solutions or features you've considered.
+
+**Additional context**
+Add any other context or screenshots about the feature request here.
diff --git a/rtags/.gitignore b/rtags/.gitignore
new file mode 100644
index 0000000..0b7c235
--- /dev/null
+++ b/rtags/.gitignore
@@ -0,0 +1,60 @@
+*.o
+*.a
+Makefile
+core
+CMakeFiles/
+cmake_install.cmake
+CMakeCache.txt
+rc
+rdm
+js
+clangtest
+gr
+.gdb_history
+.ninja_log
+build.ninja
+rules.ninja
+/.gdb_brestore
+/.gdb_brestore.txt
+/src/include/rct/rct-config.h
+/src/librtags.dylib
+/src/librtags.so
+.ninja_deps
+compile_commands.json
+/tests/dtlcpptest/dtlcpptest
+/bin/.gdb_brestore
+/bin/.gdb_brestore.txt
+/bin/rp
+/bin/librtagsclang.dylib
+/src/libshared.so
+/src/libshared.dylib
+/src/.gdb_brestore
+/src/.gdb_brestore.txt
+/src/*.elc
+/.lsdev_default
+/tests/186/
+/install_manifest.txt
+/build/marker
+/Uninstall.cmake
+/automated_tests/test_runner.pyc
+/src/*_cotire.cmake
+/src/cotire/
+/build/
+/CPackConfig.cmake
+/CPackSourceConfig.cmake
+/source/VERSION
+/src/include/RTagsVersion.h
+/bin/rlex
+/src/llvmclang-prefix/
+/emake.xml
+/emake.data.bak
+/emake.data
+/.emake/sched/Linux/emake.sched
+/src/lua-prefix
+/CTestTestfile.cmake
+/DartConfiguration.tcl
+/Testing
+/src/CTestTestfile.cmake
+/testfile.txt
+/empty.txt
+/src/CTestTestfile.cmake
diff --git a/rtags/.gitmodules b/rtags/.gitmodules
new file mode 100644
index 0000000..1e89c9e
--- /dev/null
+++ b/rtags/.gitmodules
@@ -0,0 +1,12 @@
+[submodule "src/rct"]
+ path = src/rct
+ url = https://github.com/Andersbakken/rct
+ branch = master
+[submodule "src/selene"]
+ path = src/selene
+ url = https://github.com/jeremyong/Selene.git
+ branch = master
+[submodule "src/lua"]
+ path = src/lua
+ url = https://github.com/LuaDist/lua.git
+ branch = master
diff --git a/rtags/.travis.yml b/rtags/.travis.yml
new file mode 100644
index 0000000..f81822f
--- /dev/null
+++ b/rtags/.travis.yml
@@ -0,0 +1,36 @@
+#
+# Available repositories are listed here:
+# https://github.com/travis-ci/apt-source-whitelist/blob/master/ubuntu.json
+#
+
+language: cpp
+sudo: required
+
+addons:
+ apt:
+ sources:
+ - ubuntu-toolchain-r-test
+ packages:
+ - g++-4.9
+ - python3-pip
+ - libcppunit-dev
+
+git:
+ depth: 3
+
+matrix:
+ include:
+ - os: linux
+ compiler: g++
+ dist: trusty
+ env: T=g++-linux COMPILER_VERSION=-4.9
+ - os: osx
+ compiler: clang
+ env: T=clang-osx
+
+branches:
+ only:
+ - master
+ - develop
+
+script: ./scripts/travis.sh
diff --git a/rtags/CMakeLists.txt b/rtags/CMakeLists.txt
new file mode 100644
index 0000000..ae18077
--- /dev/null
+++ b/rtags/CMakeLists.txt
@@ -0,0 +1,106 @@
+cmake_minimum_required(VERSION 2.8.6)
+project(rtags)
+set(RTAGS_VERSION_MAJOR 2)
+set(RTAGS_VERSION_MINOR 18)
+set(RTAGS_VERSION_DATABASE 125)
+set(RTAGS_VERSION_SOURCES_FILE 14)
+set(RTAGS_VERSION ${RTAGS_VERSION_MAJOR}.${RTAGS_VERSION_MINOR}.${RTAGS_VERSION_DATABASE})
+
+set(RCT_WITH_TESTS ${BUILD_TESTING})
+
+set(CMAKE_LEGACY_CYGWIN_WIN32 0)
+
+if (APPLE)
+ set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -g")
+else ()
+ set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -ggdb")
+endif ()
+
+if (ASAN)
+ string(REPLACE "," ";" ASANS ${ASAN})
+ foreach (SANITIZE ${ASANS})
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=${SANITIZE}")
+ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fsanitize=${SANITIZE}")
+ endforeach ()
+endif ()
+
+if (NOT CMAKE_BUILD_TYPE)
+ set(CMAKE_BUILD_TYPE Release CACHE STRING
+ "Choose the type of build, options are: Debug Release RelWithDebInfo MinSizeRel." FORCE)
+endif()
+
+if ("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang")
+ set(CMAKE_COMPILER_IS_CLANGCXX TRUE)
+endif()
+
+set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake/")
+
+include(FeatureSummary)
+add_subdirectory(src)
+
+add_custom_target(man
+ COMMAND "${CMAKE_CURRENT_SOURCE_DIR}/scripts/gen-man-pages.sh" "${PROJECT_BINARY_DIR}/bin"
+ DEPENDS man/man7/rdm.7 man/man7/rc.7)
+add_dependencies(man rdm rc)
+
+if (EXISTS "rules.ninja")
+ add_custom_target(release COMMAND ${CMAKE_COMMAND} -GNinja -DCMAKE_BUILD_TYPE=Release . WORKING_DIRECTORY .)
+ add_custom_target(debug COMMAND ${CMAKE_COMMAND} -GNinja -DCMAKE_BUILD_TYPE=Debug . WORKING_DIRECTORY .)
+else()
+ add_custom_target(release COMMAND ${CMAKE_COMMAND} -DCMAKE_BUILD_TYPE=Release . WORKING_DIRECTORY .)
+ add_custom_target(debug COMMAND ${CMAKE_COMMAND} -DCMAKE_BUILD_TYPE=Debug . WORKING_DIRECTORY .)
+endif()
+
+# Create uninstall script and target
+configure_file("${CMAKE_MODULE_PATH}/Uninstall.cmake.in" "${CMAKE_BINARY_DIR}/Uninstall.cmake" IMMEDIATE @ONLY)
+add_custom_target(uninstall ${CMAKE_COMMAND} -P "${CMAKE_BINARY_DIR}/Uninstall.cmake")
+
+if (RTAGS_ENABLE_DEV_OPTIONS)
+ set(CPACK_PACKAGE_INSTALL_DIRECTORY "RTAGS")
+ set(CPACK_PACKAGE_VENDOR "RTags")
+ set(CPACK_PACKAGE_CONTACT "http://rtags.net")
+ set(CPACK_PACKAGE_VERSION_MAJOR ${RTAGS_VERSION_MAJOR})
+ set(CPACK_PACKAGE_VERSION_MINOR ${RTAGS_VERSION_MINOR})
+ set(CPACK_PACKAGE_VERSION_DATABASE ${RTAGS_VERSION_DATABASE})
+ set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE.txt")
+ set(CPACK_PACKAGE_VERSION "${RTAGS_VERSION}")
+
+ if (NOT CPACK_GENERATOR)
+ set(CPACK_GENERATOR TGZ)
+ endif ()
+ set(CPACK_SOURCE_PACKAGE_FILE_NAME "rtags-${RTAGS_VERSION_MAJOR}.${RTAGS_VERSION_MINOR}"
+ CACHE INTERNAL "tarball basename")
+ set(CPACK_SOURCE_GENERATOR ${CPACK_GENERATOR})
+
+ set(CPACK_SOURCE_IGNORE_FILES
+ "~$"
+ "\\\\.gitignore$"
+ "\\\\.gitmodules$"
+ "^${PROJECT_SOURCE_DIR}/.git/"
+ "^${PROJECT_SOURCE_DIR}/build/"
+ )
+
+ include(CPack)
+endif ()
+
+include(CTest)
+
+if (BUILD_TESTING)
+ find_package(Perl QUIET)
+ if(PERL_FOUND)
+ add_test(NAME SBRootTest COMMAND perl "${CMAKE_SOURCE_DIR}/tests/sbroot/sbroot_test.pl")
+ set_property(TEST SBRootTest PROPERTY ENVIRONMENT "RTAGS_BINARY_DIR=${CMAKE_BINARY_DIR}/bin")
+ else()
+ message(WARNING "Perl not found! Excluding sbroot test from tests.")
+ endif()
+
+ find_program(NOSETEST NAMES nosetests nosetests-2.7 PATHS "$ENV{HOME}/.local/bin")
+ if (NOSETEST)
+ add_test(NAME nosetests COMMAND ${NOSETEST} -w ${CMAKE_SOURCE_DIR}/tests/automated --no-byte-compile -v)
+ set_property(TEST nosetests PROPERTY ENVIRONMENT "RTAGS_BINARY_DIR=${CMAKE_BINARY_DIR}/bin")
+ else()
+ message(WARNING "Nosetests executable not found! Excluding automated_tests from tests.")
+ endif ()
+endif ()
+
+feature_summary(INCLUDE_QUIET_PACKAGES WHAT ALL)
diff --git a/rtags/LICENSE.txt b/rtags/LICENSE.txt
new file mode 100644
index 0000000..a73e010
--- /dev/null
+++ b/rtags/LICENSE.txt
@@ -0,0 +1,14 @@
+Copyright (C) 2011-2016 Jan Erik Hanssen and Anders Bakken
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see .
diff --git a/rtags/README.org b/rtags/README.org
new file mode 100644
index 0000000..c2c329d
--- /dev/null
+++ b/rtags/README.org
@@ -0,0 +1,1220 @@
+#+OPTIONS: ^:nil
+
+#+html:

+#+html: | rtags | ac-rtags | company-rtags | flycheck-rtags | helm-rtags | ivy-rtags |
|---|
 |  |  |  |  |  |
+
+* Introduction
+RTags is a client/server application that indexes C/C++ code and keeps a
+persistent file-based database of references, declarations, definitions,
+symbolnames etc. There's also limited support for ObjC/ObjC++. It allows you
+to find symbols by name (including nested class and namespace scope). Most
+importantly we give you proper follow-symbol and find-references support. We
+also have neat little things like rename-symbol, integration with clang's
+"fixits" (http://clang.llvm.org/diagnostics.html). We also integrate with
+flymake using clang's vastly superior errors and warnings. Since RTags
+constantly will reindex "dirty" files you get live updates of compiler errors
+and warnings. Since we already know how to compile your sources we have a way
+to quickly bring up the preprocessed output of the current source file in a
+buffer.
+
+While existing taggers like gnu global, cscope, etags, ctags etc do a decent
+job for C they often fall a little bit short for C++. With its incredible
+lexical complexity, parsing C++ is an incredibly hard task and we make no
+bones about the fact that the only reason we are able to improve on the
+current tools is because of clang (http://clang.llvm.org/). RTags is named
+RTags in recognition of Roberto Raggi on whose C++ parser we intended to base
+this project but he assured us clang was the way to go. The name stuck though.
+
+* TLDR Quickstart
+Build RTags
+
+#+BEGIN_SRC sh
+git clone --recursive https://github.com/Andersbakken/rtags.git
+cd rtags
+cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=1 .
+make
+#+END_SRC
+
+Start the RTags daemon (=rdm=)
+
+#+BEGIN_SRC sh
+./bin/rdm &
+#+END_SRC
+
+Index the RTags project, and wait until =rdm= is silent
+
+#+BEGIN_SRC sh
+./bin/rc -J .
+#+END_SRC
+
+Open source file in =emacs=
+
+#+BEGIN_SRC sh
+emacs +73:34 src/rdm.cpp
+#+END_SRC
+
+Load =rtags.el=
+
+#+BEGIN_EXAMPLE
+M-: (load-file "rtags.el") RET
+#+END_EXAMPLE
+
+Insure =rc= can be found
+
+#+BEGIN_EXAMPLE
+M-x set-variable RET rtags-path RET "../bin" RET
+#+END_EXAMPLE
+
+Call =rtags-find-symbol-at-point=
+
+#+BEGIN_EXAMPLE
+M-x rtags-find-symbol-at-point RET
+#+END_EXAMPLE
+
+Your location is now on the definition of =Server::instance()=
+
+* Installing RTags
+** Prerequisites
+There are a few prerequisites you need to have in order to build RTags
+
+- =LLVM/Clang= >= 3.3
+
+ On Linux you may be able to use your distribution package manager to install
+ this. On OS X you can use Homebrew or possibly other package managers,
+ though see below for details if you plan to tag projects that use C++11
+ features (such as RTags itself). Alternatively you can grab the sources from
+ [[http://llvm.org/releases/download.html][llvm.org]] and build it yourself.
+
+- =GCC/Clang= >= 4.9/3.3
+
+ A modern compiler to build RTags. RTags makes extensive use of C++11
+ features such as variadic templates and threading utility classes from the
+ C++ standard library.
+
+- =cmake= >= 2.8
+
+ The meta-built system used by RTags.
+-----
+- =emacs= >= 24.3 is recommended
+
+ RTags might very well work with much older =emacs= versions but the oldest
+ version we have tested with is 24.3. There's no particular effort made to
+ support older versions, but patches that make it work are welcome. Having
+ said that, completion ([[https://github.com/auto-complete/auto-complete][ac]], [[https://github.com/company-mode/company-mode][company]]) as well as [[https://github.com/flycheck/flycheck][Flycheck]] integration only
+ works, and has been tested with =emacs= >= 24.3.
+
+ *NOTE:* Emacs is no real prerequisite. That implies you can compile RTags
+ without =emacs= installed. This may be of interest to you, if you want use
+ RTags as back-end for a different editor like vim, see section [[#support-for-other-editors][Support for
+ other editors]]. You explicitly can tell =cmake= to ignore the elisp files by
+ passing =-DRTAGS_NO_ELISP_FILES=1= to =cmake=.
+
+*** Optional
+- =pkg-config= and =bash-completion=
+
+ RTags comes with bash completion support. If you want the bash completion
+ files to be installed, you either have to make sure that =pkg-config= and
+ =bash-completion= package is installed or you can manually force the
+ installation by setting the variable =FORCE_BASH_COMPLETION_INSTALLATION=
+ to =TRUE= or =ON=.
+
+ The default installation path is
+ =CMAKE_INSTALL_PREFIX/share/bash-completion/completions=. You can adjust the
+ path with the =cmake= variable =BASH_COMPLETION_COMPLETIONSDIR=
+ variable. However, if the bash completions files are not installed in the
+ default completion path, i.e. =/usr/share/bash-completion/completions= on
+ GNU/Linux, you have to make sure the RTags bash completion file gets
+ sourced to get completion support.
+
+- =lua= version >= 5.3
+
+ TODO(Andersbakken): Add some notes why we optionally require Lua, whats the
+ purpose of it.
+
+ If your system does not provide a suitable version you can download Lua from
+ [[https://www.lua.org/download.html][here]]. We recommend downloading the pre-built binaries. If you have compiled
+ Lua from scratch (the build will only create an archive =liblua.a= and no
+ shared library) or you have installed the headers/library to a non standard
+ place you need to tell =cmake= where the headers/library is located.
+
+ E.g.
+ #+BEGIN_SRC sh
+ cmake -DLUA_INCLUDE_DIR=/opt/lua/include -DLUA_LIBRARY=/opt/lua/lib/liblua.a
+ # or liblua53.so or liblua53.a if you have downloaded, e.g. lua-5.3.2 binaries
+ cmake -DLUA_INCLUDE_DIR=/opt/lua/include -DLUA_LIBRARY=/opt/lua/lib/liblua53.so
+ #+END_SRC
+
+- =ZLIB=
+
+- =OpenSSL=
+
+** C++11 on OS X
+
+If you plan to tag projects using C++11 features on OS X then you'll
+need a libclang linked with LLVM's [[http://libcxx.llvm.org/][libc++]].
+For LLVM 3.9 the following works:
+
+#+BEGIN_SRC sh
+brew install llvm --with-libcxx --with-clang --without-assertions --with-rtti
+#+END_SRC
+
+Note that unless you link llvm
+#+BEGIN_SRC sh
+brew link llvm
+#+END_SRC
+
+You'll likely have to tell cmake where to find llvm-config.
+
+E.g.
+
+#+BEGIN_SRC sh
+$ PATH=/usr/local/Cellar/llvm/3.9.1/bin/:$PATH cmake /path/to/rtags
+$ make
+#+END_SRC
+
+or you can install clang and llvm from mac ports
+
+#+BEGIN_SRC sh
+sudo port install clang-3.5
+#+END_SRC
+
+** Building RTags
+- Get the code
+
+ To build RTags, you need to checkout RTags and the repository's sub-modules,
+ this can be done in one step. After that, you need to run =cmake=, =make= and
+ =make install=, in that order.
+
+ #+BEGIN_SRC sh
+ git clone --recursive https://github.com/Andersbakken/rtags.git
+ #+END_SRC
+
+ You can also download the sources from here:
+
+ https://andersbakken.github.io/rtags-releases/rtags-2.18.tar.bz2
+
+ or
+
+ https://andersbakken.github.io/rtags-releases/rtags-2.18.tar.gz
+
+- Building RTags
+
+ We recommend building in a separate directory to keep the build files separate
+ from the source, but you can run =cmake= in the source tree if you prefer.
+
+ #+BEGIN_SRC sh
+ cd rtags
+ mkdir build
+ cd build
+ cmake ..
+ make
+ make install
+ #+END_SRC
+
+ *TIP:* You can run =ccmake= (CMake with an ncurses UI) instead of =cmake= to
+ interactively configure the RTags build.
+
+ Note that if you're trying to test RTags by indexing RTags' own
+ source code you shouldn't build it in /tmp/ since RTags will refuse
+ to index files in /tmp/
+
+ "make install" runs ctest by default. If you want to skip ctest during install,
+ you can pass -DSKIP_CTEST=True to cmake.
+
+ #+BEGIN_SRC sh
+ cmake .. -DSKIP_CTEST=True
+ make
+ make install
+ #+END_SRC
+
+- Elpa
+
+ You can install the elisp part of RTags using package.el if you add
+ melpa to your sources list.
+
+ Once you have emacs installed from melpa you can use the elisp to
+ build the c++ parts of RTags. You still need to have a working
+ compiler, libclang and cmake installed.
+
+ To use:
+ #+BEGIN_SRC elisp
+ M-x rtags-install
+ #+END_SRC
+
+ You may have to set additional arguments to cmake for this
+ work. E.g.
+
+ #+BEGIN_SRC elisp
+ M-: (rtags-install nil "-DLIBCLANG_LLVM_CONFIG_EXECUTABLE=/usr/local//Cellar/llvm/4.0.0/bin/llvm-config")
+ #+END_SRC
+
+* Finding clang
+** Use Your System's version
+Unless you define RTAGS_BUILD_CLANG in cmake (or configure), the build system will try to
+locate the required llvm/clang libraries and options automatically from what is
+installed on your system.
+
+RTags needs three pieces of information about =libclang=. All of these can be
+provided to =cmake= by way of an environment variable or a =cmake= variable. If
+not provided we will try to find =llvm-config= and interrogate it for the
+information. You can tell RTags which =llvm-config= to use like this:
+
+#+BEGIN_SRC sh
+LIBCLANG_LLVM_CONFIG_EXECUTABLE=/path/to/llvm-config cmake .
+#+END_SRC
+
+or
+
+#+BEGIN_SRC sh
+cmake -DLIBCLANG_LLVM_CONFIG_EXECUTABLE=/path/to/llvm-config .
+#+END_SRC
+
+If you don't, we will look for variations of the =llvm-config= executable name
+in your =$PATH=. If llvm is installed at a different place, you could set the
+cmake variable =CMAKE_PREFIX_PATH= to the install prefix path of llvm.
+
+The three things we need are:
+
+1. =LIBCLANG_CXXFLAGS=
+
+ Usually something like this:
+
+ #+BEGIN_SRC sh
+ $ llvm-config --cxxflags
+ # Max OS X
+ -I/usr/local/Cellar/llvm36/3.6.0/lib/llvm-3.6/include -DNDEBUG -D_GNU_SOURCE -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS -O3 -std=c++11 -fvisibility-inlines-hidden -fno-exceptions -fno-common -Woverloaded-virtual -Wcast-qual
+ # Fedora 23 64 bit
+ -I/usr/include -DNDEBUG -D_GNU_SOURCE -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS -O3 -std=c++11 -fvisibility-inlines-hidden -fno-exceptions -fno-common -Woverloaded-virtual -Wcast-qual
+ #+END_SRC
+
+2. =LIBCLANG_LIBDIR=
+
+ Usually something like this:
+
+ #+BEGIN_SRC sh
+ $ llvm-config --libdir
+ # Mac OS X
+ /usr/local/Cellar/llvm36/3.6.0/lib/llvm-3.6/lib
+ # Fedora 23 64 bit
+ /usr/lib64/llvm
+ #+END_SRC
+
+ We need this to locate clang's system headers, and we will assume that they
+ are located in: =${LIBCLANG_LIBDIR}/clang/CLANG_VERSION_STRING/include
+ (/usr/local/Cellar/llvm36/3.6.0/lib/llvm-3.6/lib/clang/3.6.0/include)=. There
+ should be headers like stdarg.h and limits.h in this directory.
+
+3. =LIBCLANG_LIBRARIES=
+
+ Usually something like this:
+
+ #+BEGIN_EXAMPLE
+ # Mac OS X
+ /usr/local/Cellar/llvm36/3.6.0/lib/llvm-3.6/lib/libclang.so
+ # Fedora 23 64 bit
+ /usr/lib64/llvm/libclang.so
+ #+END_EXAMPLE
+
+ Unless otherwise specified, we will try to find the clang library using
+ =cmake='s =find_library= feature and/or assuming that they there will be a
+ libclang.(so|dylib) in =${LIBCLANG_LIBDIR}=
+
+Like with =LIBCLANG_LLVM_CONFIG_EXECUTABLE= these variables can be overwritten
+as a =cmake= variable =(cmake -DLIBCLANG_LIBDIR =...)= or an environment variable
+=(LIBCLANG_LIBDIR =... cmake)=
+
+** Let the Build System Download and Compile LLVM/Clang
+By default, cmake searches for a system libclang. If you want it to
+download and build the required llvm/clang libraries, either call
+cmake with -DRTAGS_BUILD_CLANG=1 or configure with --build-clang
+
+Note that if you use ninja to build RTags you might run into the
+following error:
+
+#+BEGIN_SRC sh
+ninja: error: '/usr/local/rtags-llvmclang/lib/libclang.dylib', needed by 'bin/rdm', missing and no known rule to make it
+#+END_SRC
+
+In that case you need to do this:
+
+#+BEGIN_SRC sh
+ninja llvmclang && ninja && ninja install
+#+END_SRC
+
+* Setup
+
+=rdm= runs in the background and monitors all your indexed files for changes,
+and reindexes when a source file or one of its dependencies is modified. Since
+clang is a fully compliant compiler it needs specific information about how
+your sources are compiled to be able to properly index them. This is done
+through telling =rdm= about the compile line like this:
+
+#+BEGIN_SRC sh
+rc -c gcc -I... -fsomeflag -c foobar.c
+rc -J /path/to/a/directory/containing/compile_commands.json
+#+END_SRC sh
+
+You can generate a compile_commands.json with various different tools, one
+might fit better than the other, depending on your project build system.
+
+- [[https://ninja-build.org/manual.html][ninja]]
+
+ #+begin_src sh
+ ninja -t compdb cxx cc > compile_commands.json
+ rc -J
+ #+end_src
+
+ With =ninja= it's also possible to pipe the commands directly to =rc=.
+
+ #+BEGIN_SRC sh
+ ninja -t commands | rc -c -
+ # Parse commands for a specific target only
+ ninja -t commands rdm | rc -c -
+ #+END_SRC
+
+- =cmake=
+
+ =cmake= can generate a compile_commands.json file as well.
+
+ #+BEGIN_SRC sh
+ cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=1 .
+ rc -J
+ #+END_SRC
+
+- [[https://github.com/rizsotto/Bear][Bear]]
+
+ For other projects you can use =bear= to generate a compile_commands.json
+ file. However, if you are cross-compiling you probably need to adjust the
+ command entries in the compile_commands.json file to match the correct
+ compiler. Furthermore, make sure you clean your project before invoking
+ =bear=.
+
+ #+BEGIN_SRC sh
+ make clean
+ bear make
+ rc -J
+ # Parse commands for a specific target only
+ make clean
+ bear make rdm
+ rc -J
+ #+END_SRC
+
+- =make=
+
+ You can ask =make= to only print the recipes without actually doing something.
+ This way may be perfectly fine for not too complex Makefiles.
+
+ #+BEGIN_SRC sh
+ make clean
+ make -nk | rc -c -
+ #+END_SRC
+
+ There are very likely similar things you can do with other build systems that
+ we're unfamiliar with, please let us know if you do.
+
+- A different approach to get your files indexed is the man-in-the-middle
+
+ This can be done like this:
+
+ #+BEGIN_SRC sh
+ ln -s /path/to/rtags/bin/gcc-rtags-wrapper.sh /somewhere/that/is/in/your/path/before/usr/bin/gcc
+ ln -s /path/to/rtags/bin/gcc-rtags-wrapper.sh /somewhere/that/is/in/your/path/before/usr/bin/c++
+ ln -s /path/to/rtags/bin/gcc-rtags-wrapper.sh /somewhere/that/is/in/your/path/before/usr/bin/cc
+ ln -s /path/to/rtags/bin/gcc-rtags-wrapper.sh /somewhere/that/is/in/your/path/before/usr/bin/g++
+#+END_SRC
+
+ E.g.
+
+ #+BEGIN_EXAMPLE
+ $ which -a gcc | xargs file
+ /home/abakken/bin/gcc: symbolic link to `/home/abakken/dev/rtags/bin/gcc-rtags-wrapper.sh'
+ /usr/bin/gcc: symbolic link to `gcc-4.7'
+ #+END_EXAMPLE
+
+ Now every time you compile a file with =which gcc= =rc= will get its grubby
+ hands all over your command line and make sure RTags knows about it.
+
+RTags will group source files into projects based on some heuristics.
+
+Essentially it will look for certain files/dirs (like
+configure/CMakeLists.txt/scons.1/.git) etc to try to determine the likely
+project root for each source file. For generated source files that end up in
+the build directory we try to find the source root based on similar heuristics
+around config.status/CMakeCache.txt etc. Usually this works out reasonably
+well. If it doesn't for you, you can pass =--project-root
+/path/to/the/project/root= to =rc=.
+
+RTags only gives you information about current project when you ask
+for things by name. You can explicitly change the current project using:
+
+#+BEGIN_SRC sh
+rc -w foobar
+#+END_SRC
+
+We try to do it automatically for you by passing along information about the
+current buffer when we call =rc= from elisp so that =rdm= can update its
+current project on demand.
+
+RTags keeps a cache of indexed data so you don't have to reindex everything if
+you restart it.
+
+The location of this data is by default =~/.rtags= but can be overridden by
+passing =--data-dir /other/dir= to =rdm= or putting something like this in
+your ~/.rdmrc:
+
+#+BEGIN_EXAMPLE
+$ cat ~/.rdmrc
+--data-dir=/other/dir
+#+END_EXAMPLE
+
+** Integration with =launchd= /(Mac OS X)/
+
+On Mac OS X, you can set =rdm= can be run on demand, on your behalf, by
+=launchd=, and have it exit cleanly after a period of inactivity. The easiest
+way to do this is with Homebrew:
+
+#+BEGIN_SRC
+brew services start rtags
+#+END_SRC
+
+You can also do it manually using the following steps:
+
+1. Create a file, e.g., in emacs, with the following contents:
+
+ #+BEGIN_SRC xml
+
+
+
+
+ Label
+ com.andersbakken.rtags.agent
+ ProgramArguments
+
+ sh
+ -c
+ $RDM -v --launchd --inactivity-timeout 300 --log-file ~/Library/Logs/rtags.launchd.log
+
+ Sockets
+
+ Listener
+
+ SockPathName
+ $HOME/.rdm
+
+
+
+
+ #+END_SRC
+
+2. Replace =$HOME= with the absolute path to your home folder. Replace
+ =$RDM= with the path to your copy of =rdm=, and add any command line
+ parameters you might usually use.
+
+ (The =SockPathName= entry relates to the name of the domain socket that
+ =rdm= uses. The settings above are for the default value; if your command
+ line options direct it to use some other name, please modify it to
+ suit. Unfortunately =launchd='s configuration files are a bit naff, so
+ you'll have to repeat yourself.)
+
+3. Save the result as
+ =~/Library/LaunchAgents/com.andersbakken.rtags.agent.plist=.
+
+4. Run the following command from the terminal:
+
+ : launchctl load ~/Library/LaunchAgents/com.andersbakken.rtags.agent.plist
+
+ (This will happen automatically next time you log back in.)
+
+5. Try using RTags, and you should find =rdm= will spring into life!
+
+*** Notes
+
+- =rdm= will automatically quit after 5 minutes of inactivity (this is
+ what the =--inactivity-timeout 300= command line option is for), so
+ it won't stick around hogging memory. But =launchd= will still be
+ watching its socket for activity, and will relaunch it if necessary.
+
+- You can watch =launchd='s logging by tailing
+ =~/Library/Logs/rtags.launchd.log=.
+
+** Integration with =systemd= /(GNU Linux)/
+
+On GNU/Linux distributions based on the =systemd= service manager, =rdm= can
+also be socket acivated.
+
+ 1. Add the following to =~/.config/systemd/user/rdm.socket=
+
+ #+BEGIN_EXAMPLE
+ [Unit]
+ Description=RTags daemon socket
+
+ [Socket]
+ ListenStream=%t/rdm.socket
+
+ [Install]
+ WantedBy=default.target
+ #+END_EXAMPLE
+
+ 2. Add the following to =~/.config/systemd/user/rdm.service=
+
+ #+BEGIN_EXAMPLE
+ [Unit]
+ Description=RTags daemon
+
+ Requires=rdm.socket
+
+ [Service]
+ Type=simple
+ ExecStart=$RDM -v --inactivity-timeout 300 --log-flush
+ ExecStartPost=/bin/sh -c "echo +19 > /proc/$MAINPID/autogroup"
+ Nice=19
+ CPUSchedulingPolicy=idle
+ #+END_EXAMPLE
+
+ 3. Replace =$RDM= with the path to your copy of =rdm=, and add any command
+ line parameters you might usually use.
+
+ You have to use absolute paths here. =%h= is expanded to your home
+ directory. Environment variables are not expanded inside strings.
+
+ 4. Run the following command from the terminal:
+
+ #+BEGIN_SRC sh
+ systemctl --user enable rdm.socket
+ systemctl --user start rdm.socket
+ #+END_SRC
+
+ =Systemd= will create the =rdm= socket automatically.
+
+ Note that user level systemd does not work on RHEL
+ derivatives. See here for more info: https://bugs.centos.org/view.php?id=8767
+
+If you prefer using SystemV something like this could be used:
+
+#+BEGIN_EXAMPLE
+
+#!/bin/bash
+#
+# chkconfig: 35 90 12
+# description: Foo server
+#
+
+# Get function from functions library
+. /etc/init.d/functions
+
+# Start the service FOO
+start() {
+ initlog -c "echo -n Starting FOO server: "
+ /path/to/FOO &
+ ### Create the lock file ###
+ touch /var/lock/subsys/FOO
+ success $"FOO server startup"
+ echo
+}
+
+# Restart the service FOO
+stop() {
+ initlog -c "echo -n Stopping FOO server: "
+ killproc FOO
+ ### Now, delete the lock file ###
+ rm -f /var/lock/subsys/FOO
+ echo
+}
+
+### main logic ###
+case "$1" in
+ start)
+ start
+ ;;
+ stop)
+ stop
+ ;;
+ status)
+ status FOO
+ ;;
+ restart|reload|condrestart)
+ stop
+ start
+ ;;
+ *)
+ echo $"Usage: $0 {start|stop|restart|reload|status}"
+ exit 1
+esac
+
+exit 0
+
+#+END_EXAMPLE
+
+* Usage
+
+Now that your files are indexed you can start using RTags. Normally you
+would do this from your editor but the way to extract this information from
+=rdm= is to use the command line tool =rc=.
+
+E.g.
+
+#+BEGIN_EXAMPLE
+$ rdm &
+$ ninja -t commands | rc -c
+$ rc --follow-location Job.cpp:20:10
+/home/abakken/dev/rtags/src/Job.h:10:18 List *mPathFiltersRegExp;
+#+END_EXAMPLE
+
+A location has the format of file:line:column.
+
+For Emacs we maintain a set of elisp bindings that allows you to control RTags
+from your editor. There are projects that provide integration for other
+editors out there.
+
+Vim: https://github.com/lyuts/vim-rtags and https://github.com/shaneharper/vim-rtags
+
+Neovim: https://github.com/marxin/neo-rtags
+
+Sublime Text: https://github.com/rampage644/sublime-rtags
+
+Atom: https://github.com/artagnon/atomic-rtags, https://github.com/rajendrant/atom-rtags and https://github.com/sphaerophoria/atom-rtags-plus
+
+=rc= has a vast number of commands and options and we have written a
+man page for it. Most users will have limited interest in ever calling them
+manually and would rather just use the interactive elisp functions.
+
+* Elisp
+** Functions
+
+#+BEGIN_SRC emacs-lisp
+(rtags-start-process-unless-running)
+#+END_SRC
+
+Start the =rdm= process unless the process is already running. You may create
+hook to automatically call this function upon entering, e.g. c-mode or
+c++mode.
+
+E.g.
+
+#+BEGIN_SRC emacs-lisp
+(add-hook 'c-mode-hook 'rtags-start-process-unless-running)
+(add-hook 'c++-mode-hook 'rtags-start-process-unless-running)
+(add-hook 'objc-mode-hook 'rtags-start-process-unless-running)
+#+END_SRC
+
+#+begin_src emacs-lisp
+(rtags-restart-process)
+#+end_src
+
+Restart the =rdm= process.
+
+#+BEGIN_SRC emacs-lisp
+(rtags-find-symbol-at-point)
+#+END_SRC
+
+Follow symbol under cursor. For references this goes to the definition (or
+declaration if no definition is known of the symbol. For declarations it goes
+to the definition and vice versa. For definitions of variables/parameters with
+constructors it goes to the constructor in question. If you pass a prefix
+argument, limit to current source file, if you pass a prefix argument and have
+narrowed the current file, limit to the narrowed region. This prefix argument
+is the same for: =rtags-find-references-at-point=, =rtags-find-symbol=,
+=rtags-find-references=
+
+#+BEGIN_SRC emacs-lisp
+(rtags-find-references-at-point)
+#+END_SRC
+
+Find all references to symbol under cursor. If symbol is itself a reference it
+will find all references to the referenced symbol
+
+#+BEGIN_SRC emacs-lisp
+(rtags-find-symbol)
+#+END_SRC
+
+Prompt for name of symbol to go to. Imagine the following code:
+
+#+BEGIN_SRC C++
+
+namespace N
+{
+class C
+{
+public:
+ int func(int);
+};
+};
+
+using namespace N;
+int C::func(int val)
+{
+ return val * 2;
+}
+#+END_SRC
+int N::C::func(int) will now be accessible by the following names:
+- func
+- func(int)
+- C::func(int)
+- C::func
+- N::C::func(int)
+- N::C::func
+
+#+BEGIN_SRC emacs-lisp
+(rtags-find-references)
+#+END_SRC
+
+Prompt for name of symbol to find references to. Same as above but find
+references to symbol rather than declarations and definitions.
+
+#+BEGIN_SRC emacs-lisp
+(rtags-diagnostics)
+#+END_SRC
+
+Start an async process in a buffer to receive warnings/errors from clang
+whenever a file gets reindexed. It integrates with flymake to put highlighting
+on code with warnings and errors
+
+#+BEGIN_SRC emacs-lisp
+(rtags-enable-standard-keybindings)
+#+END_SRC
+Sets up a ton of standard keybindings under C-c r. If you pass a mode to the
+function it will set it up on that mode, otherwise it will use
+c-mode-base-map). You can choose a different prefix than C-c r like this:
+
+#+BEGIN_SRC emacs-lisp
+(rtags-enable-standard-keybindings c-mode-base-map "\C-xr")
+#+END_SRC
+
+#+BEGIN_SRC emacs-lisp
+(rtags-find-file)
+#+END_SRC
+
+Lets you jump to file by name (partial or full, concept kinda stolen from
+gtags.el) with completion in the project. This includes all files under what
+we determine to be the root of the project, not just source files.
+
+#+BEGIN_SRC emacs-lisp
+(rtags-find-virtuals-at-point)
+#+END_SRC
+For virtual functions, show the various reimplementations of the function at
+point
+
+#+BEGIN_SRC emacs-lisp
+(rtags-fixit)
+#+END_SRC
+Apply clang's automatic fixits in current file. If you pass a prefix arg use
+ediff to apply it. See (http://clang.llvm.org/diagnostics.html) for more info.
+
+#+BEGIN_SRC emacs-lisp
+(rtags-imenu)
+#+END_SRC
+Provides an ido-based imenu like interface to a subset of the symbols in the
+current file. Note that it does not actually use imenu infrastructure.
+
+#+BEGIN_SRC emacs-lisp
+(rtags-location-stack-back)
+(rtags-location-stack-forward)
+#+END_SRC
+
+Whenever RTags jumps somewhere it pushes a location onto its stack. Jump back
+and forward in this stack
+
+#+BEGIN_SRC emacs-lisp
+(rtags-next-match)
+(rtags-previous-match)
+#+END_SRC
+
+For functions that return more than one match, jump to the next/previous one.
+
+#+BEGIN_SRC emacs-lisp
+(rtags-preprocess-file)
+#+END_SRC
+
+Preprocess current file according to known C(XX)Flags and show the result in a
+buffer. If region is active only display the preprocessed output for that
+region.
+
+#+BEGIN_SRC emacs-lisp
+(rtags-print-symbol-info)
+#+END_SRC
+
+Print some info about symbol under cursor
+
+#+BEGIN_SRC emacs-lisp
+(rtags-symbol-type)
+#+END_SRC
+
+Print the type of the symbol under cursor.
+
+#+BEGIN_SRC emacs-lisp
+(rtags-print-dependencies)
+#+END_SRC
+
+Open a buffer showing files that depend on current file/files that current
+file depends on.
+
+#+BEGIN_SRC emacs-lisp
+(rtags-print-enum-value-at-point)
+#+END_SRC
+
+Print integral value of enum value at point
+
+#+BEGIN_SRC emacs-lisp
+(rtags-quit-rdm)
+#+END_SRC
+
+Shut down =rdm=
+
+#+BEGIN_SRC emacs-lisp
+(rtags-rename-symbol)
+#+END_SRC
+
+Rename symbol under cursor. Make sure all files are saved and fully indexed
+before using.
+
+#+BEGIN_SRC emacs-lisp
+(rtags-reparse-file)
+#+END_SRC
+
+Explicitly trigger a reparse of current file. Mostly for debugging. Unless we
+have bugs it should not be necessary.
+
+#+BEGIN_SRC emacs-lisp
+(rtags-show-rtags-buffer)
+#+END_SRC
+
+Switch to =*RTags*= buffer. This is the buffer where a number of functions
+display their alternatives when they have more than one match.
+
+#+BEGIN_SRC emacs-lisp
+(rtags-include-file)
+#+END_SRC
+
+Insert selected or entered include, e.g. "string.h"/ in current
+buffer, either at the top, after the first include statement or with prefix
+argument (=C-u=) at current point.
+
+#+BEGIN_SRC emacs-lisp
+(rtags-get-include-file-for-symbol)
+#+END_SRC
+
+Insert include for entered symbol or symbol under courser in current buffer,
+either at the top, after the first include statement or with prefix argument
+(=C-u=) at current point.
+
+** Variables
+
+#+BEGIN_SRC emacs-lisp
+rtags-path
+#+END_SRC
+
+Path to =rc/rdm= if they're not in =$PATH=.
+
+#+BEGIN_SRC emacs-lisp
+rtags-jump-to-first-match
+#+END_SRC
+
+Similar to =compilation-auto-jump-to-first-error=. Whether to jump to the
+first match automatically when there's more than one.
+
+#+BEGIN_SRC emacs-lisp
+rtags-find-file-case-insensitive
+#+END_SRC
+
+Whether to match files case-insensitively
+
+#+BEGIN_SRC emacs-lisp
+rtags-find-file-prefer-exact-match
+#+END_SRC
+
+Whether to exclude partial matches for file names when an exact match is
+found. E.g. =/foobar.cpp= =/bar.cpp= If =rtags-find-file-prefer-exact-match=
+is =t= a query for =bar.cpp= would only return =/bar.cpp=, otherwise both
+=foobar.cpp= and =bar.cpp= would be returned.
+
+** Fall back to other taggers
+You can do something like the following to fall back to e.g. gtags
+if RTags doesn't have a certain project indexed:
+
+#+BEGIN_SRC emacs-lisp
+(defun use-rtags (&optional useFileManager)
+ (and (rtags-executable-find "rc")
+ (cond ((not (gtags-get-rootpath)) t)
+ ((and (not (eq major-mode 'c++-mode))
+ (not (eq major-mode 'c-mode))) (rtags-has-filemanager))
+ (useFileManager (rtags-has-filemanager))
+ (t (rtags-is-indexed)))))
+
+(defun tags-find-symbol-at-point (&optional prefix)
+ (interactive "P")
+ (if (and (not (rtags-find-symbol-at-point prefix)) rtags-last-request-not-indexed)
+ (gtags-find-tag)))
+(defun tags-find-references-at-point (&optional prefix)
+ (interactive "P")
+ (if (and (not (rtags-find-references-at-point prefix)) rtags-last-request-not-indexed)
+ (gtags-find-rtag)))
+(defun tags-find-symbol ()
+ (interactive)
+ (call-interactively (if (use-rtags) 'rtags-find-symbol 'gtags-find-symbol)))
+(defun tags-find-references ()
+ (interactive)
+ (call-interactively (if (use-rtags) 'rtags-find-references 'gtags-find-rtag)))
+(defun tags-find-file ()
+ (interactive)
+ (call-interactively (if (use-rtags t) 'rtags-find-file 'gtags-find-file)))
+(defun tags-imenu ()
+ (interactive)
+ (call-interactively (if (use-rtags t) 'rtags-imenu 'idomenu)))
+
+(define-key c-mode-base-map (kbd "M-.") (function tags-find-symbol-at-point))
+(define-key c-mode-base-map (kbd "M-,") (function tags-find-references-at-point))
+(define-key c-mode-base-map (kbd "M-;") (function tags-find-file))
+(define-key c-mode-base-map (kbd "C-.") (function tags-find-symbol))
+(define-key c-mode-base-map (kbd "C-,") (function tags-find-references))
+(define-key c-mode-base-map (kbd "C-<") (function rtags-find-virtuals-at-point))
+(define-key c-mode-base-map (kbd "M-i") (function tags-imenu))
+
+(define-key global-map (kbd "M-.") (function tags-find-symbol-at-point))
+(define-key global-map (kbd "M-,") (function tags-find-references-at-point))
+(define-key global-map (kbd "M-;") (function tags-find-file))
+(define-key global-map (kbd "C-.") (function tags-find-symbol))
+(define-key global-map (kbd "C-,") (function tags-find-references))
+(define-key global-map (kbd "C-<") (function rtags-find-virtuals-at-point))
+(define-key global-map (kbd "M-i") (function tags-imenu))
+
+#+END_SRC
+
+* Code Completion in Emacs:
+To enable code completion in Emacs with company mode do the following:
+
+- Enable rtags-diagnostics. The easiest way is to:
+
+#+BEGIN_SRC emacs-lisp
+(setq rtags-autostart-diagnostics t)
+#+END_SRC
+
+but you can also explicitly start it with
+
+#+BEGIN_EXAMPLE
+M-x rtags-diagnostics
+#+END_EXAMPLE
+
+- Enable completions in RTags:
+
+#+BEGIN_SRC emacs-lisp
+(setq rtags-completions-enabled t)
+#+END_SRC
+
+- Enable company-mode
+
+#+BEGIN_SRC emacs-lisp
+(require 'company)
+(global-company-mode)
+#+END_SRC
+
+- Add company-rtags to company-backends:
+
+#+BEGIN_SRC emacs-lisp
+(push 'company-rtags company-backends)
+#+END_SRC
+
+This minimal init.el configuration should be enough to get completion to work.
+
+#+BEGIN_SRC emacs-lisp
+(require 'package)
+(package-initialize)
+(require 'rtags)
+(require 'company)
+
+(setq rtags-autostart-diagnostics t)
+(rtags-diagnostics)
+(setq rtags-completions-enabled t)
+(push 'company-rtags company-backends)
+(global-company-mode)
+(define-key c-mode-base-map (kbd "") (function company-complete))
+#+END_SRC
+
+To enable completion in Emacs with auto-complete-mode do the following:
+...TODO...
+* RTags Flycheck integration
+To turn on RTags Flycheck support you need to load the =flycheck-rtags=
+package.
+
+#+BEGIN_SRC emacs-lisp
+(require 'flycheck-rtags)
+#+END_SRC
+
+** Optional
+You may explicitly select the RTags Flycheck checker for some major modes for
+better experience.
+
+At the moment there is no customize option available to choose between
+=rtags-diagnostics= overlays or Flycheck overlays, nor is it planned right
+now.
+We recommend setting =flycheck-highlighting-mode= locally to =nil= as the
+RTags overlays are more accurate.
+
+Further, Flycheck will trigger automatically, based on events, the syntax
+checker for the current buffer, this is however, pretty useless in conjunction
+with RTags. We trigger it manually because we find it gives you a better
+experience.
+To turn off the automatic Flycheck syntax checking, set the variable
+=flycheck-check-syntax-automatically= locally to =nil=.
+
+#+BEGIN_SRC emacs-lisp
+(defun my-flycheck-rtags-setup ()
+ (flycheck-select-checker 'rtags)
+ (setq-local flycheck-highlighting-mode nil) ;; RTags creates more accurate overlays.
+ (setq-local flycheck-check-syntax-automatically nil))
+(add-hook 'c-mode-hook #'my-flycheck-rtags-setup)
+(add-hook 'c++-mode-hook #'my-flycheck-rtags-setup)
+(add-hook 'objc-mode-hook #'my-flycheck-rtags-setup)
+#+END_SRC
+
+* Helm integration
+You can use Helm to view the result, to do so, set
+=rtags-display-result-backend= to =helm=. You don't need to load =helm-rtags=,
+we do it. If you have installed *RTags* through MELPA you need to install
+=helm-rtags=.
+
+#+BEGIN_SRC emacs-lisp
+(setq rtags-display-result-backend 'helm)
+#+END_SRC
+
+* Ivy integration
+You can use Ivy to view the result, to do so, set
+=rtags-display-result-backend= to =ivy=. You don't need to load =ivy-rtags=,
+we do it. If you have installed *RTags* through MELPA you need to install
+=ivy-rtags=.
+
+#+BEGIN_SRC emacs-lisp
+(setq rtags-display-result-backend 'ivy)
+#+END_SRC
+
+* Videos
+Here are some videos demonstrating how to use RTags with Emacs though some of
+these may be outdated:
+
+[[http://www.youtube.com/watch?v=Z4g05SjkQzM&list=PLAL6K6Ycnt4IwjIjWcYV9bFgcTG_4T1Y_&index=10][Set up RTags]]
+
+[[http://www.youtube.com/watch?v=J2B-z0LBL_s&list=PLAL6K6Ycnt4IwjIjWcYV9bFgcTG_4T1Y_&index=6][Set up symlinks and run the daemon]]
+
+[[http://www.youtube.com/watch?v=bD6Rlycn1RU&list=PLAL6K6Ycnt4IwjIjWcYV9bFgcTG_4T1Y_&index=5][Project setup using make]]
+
+[[http://www.youtube.com/watch?v=Zivoc5DH_II&list=PLAL6K6Ycnt4IwjIjWcYV9bFgcTG_4T1Y_&index=9][Project setup using ninja]]
+
+[[http://www.youtube.com/watch?v=IfenCEuOqOs&list=PLAL6K6Ycnt4IwjIjWcYV9bFgcTG_4T1Y_&index=2][Navigation/references]]
+
+[[http://www.youtube.com/watch?v=wVoaE3Pj4oU&list=PLAL6K6Ycnt4IwjIjWcYV9bFgcTG_4T1Y_&index=1][Fixits]]
+
+[[http://www.youtube.com/watch?v=mnQPz5J7gN0&list=PLAL6K6Ycnt4IwjIjWcYV9bFgcTG_4T1Y_&index=3]["IMenu" / virtuals / filenames]]
+
+[[http://www.youtube.com/watch?v=p6JHriYmVuY&list=PLAL6K6Ycnt4IwjIjWcYV9bFgcTG_4T1Y_&index=4][Rename symbol]]
+
+[[http://www.youtube.com/watch?v=9CsoJTs58q8&list=PLAL6K6Ycnt4IwjIjWcYV9bFgcTG_4T1Y_&index=8][Enums and cursor info]]
+
+* Debugging RTags
+If you find that =rp= is crashing (leading to output like this: "job crashed
+191 9698036154370 0x331e7e30"). You should be able to do the following:
+
+#+BEGIN_SRC sh
+rdm --suspend-rp-on-crash
+#+END_SRC
+
+When =rp= crashes the =rp= process will stay alive, enabling you to debug it
+with something like this:
+
+#+BEGIN_SRC sh
+gdb -p `pidof rp`
+#+END_SRC
+
+* Support for other editors
+There are several other projects integrating RTags with other editors.
+
+Sublime Text:
+https://github.com/rampage644/sublime-rtags
+
+Vim:
+https://github.com/lyuts/vim-rtags
+https://github.com/shaneharper/vim-rtags
+https://github.com/mattn/vim-rtags
+
+Neovim:
+https://github.com/marxin/neo-rtags
+
+Note to those maintainers. If you need RTags to behave differently or add
+features to make these other integration's easier (like produce output in
+other formats etc), just drop us a note.
+* Coding style
+ We are always excited to accept bug fixes, improvements and features
+ through code contributions. Feel free to send a pull request for
+ anything you think could be improved upon.
+
+ We'd like contributions to adhere to our coding style.
+
+ The coding style can kinda be deduced from this:
+ #+begin_src cpp
+ if (foo) {
+ while (!done) {
+ switch (value) {
+ case 1:
+ break;
+ case 2: {
+ int variable = 12;
+ break; }
+ case 3:
+ break;
+ }
+ }
+ for (auto foo : vars) {
+
+ }
+ }
+
+ void test(const std::string &bar);
+
+ class Foo
+ {
+ private:
+ int mPrivateMember;
+ };
+
+ struct Bar
+ {
+ int publicMember;
+ };
+
+ class A
+ {
+ public:
+ A(int val);
+ private:
+ int mValue;
+ };
+
+ A::A(int val)
+ : mValue(val)
+ {
+ }
+
+ conn->setErrorHandler([](const SocketClient::SharedPtr &, Message::MessageError &&error) {
+ if (error.type == Message::Message_VersionError) {
+ ::error("Wrong version marker. You're probably using mismatched versions of rc and rdm");
+ } else {
+ logDirect(LogLevel::Error, error.text);
+ }
+ });
+
+#+end_src
+
+* Unit tests
+ There are some tests available in ~tests~, and in
+ ~src/rct/tests~. The test target will be generated by default. You
+ can disable the generation of the test target by calling cmake like this:
+
+ #+begin_src sh
+ cmake -DBUILD_TESTING=0
+ #+end_src
+
+ To run the tests, call =make= with the target =test=.
+ #+begin_src sh
+ make all test # Build the binaries first
+ #+end_src
+* Disclaimer
+RTags is still under development and is not the most stable piece of software
+you'll ever find. We're constantly working to improve on it.
diff --git a/rtags/bin/cc_prefix.sh b/rtags/bin/cc_prefix.sh
new file mode 100755
index 0000000..8172dd8
--- /dev/null
+++ b/rtags/bin/cc_prefix.sh
@@ -0,0 +1,8 @@
+#!/bin/bash
+
+[ -z "$RTAGS_DISABLED" ] && [ -x "$(which rc)" ] && rc --silent --compile "$@" &
+[ "$RTAGS_RMAKE" ] && exit 1
+compiler="$1"
+shift
+$compiler "$@"
+exit $?
diff --git a/rtags/bin/gcc-rtags-hook.sh b/rtags/bin/gcc-rtags-hook.sh
new file mode 100755
index 0000000..337d410
--- /dev/null
+++ b/rtags/bin/gcc-rtags-hook.sh
@@ -0,0 +1,8 @@
+#!/bin/bash
+
+if [ -z "$RTAGS_DISABLED" ] && [ -x "$(which rc)" ]; then
+ rc --silent --compile "$ICECC_CXX" "$@" &
+fi
+
+[ "$RTAGS_RMAKE" ] && exit 1
+exit 0
diff --git a/rtags/bin/gcc-rtags-wrapper.sh b/rtags/bin/gcc-rtags-wrapper.sh
new file mode 100755
index 0000000..60ec868
--- /dev/null
+++ b/rtags/bin/gcc-rtags-wrapper.sh
@@ -0,0 +1,85 @@
+#!/bin/bash
+
+if [ "$RTAGS_GCC_WRAPPER" = "1" ]; then
+ echo 1>&2 "Recursive invocation of gcc-rtags-wrapper.sh detected"
+ exit 1
+fi
+
+# tup support
+
+function eliminateTupVariant
+{
+ topDir="$PWD"
+ while [ "$PWD" != / -a ! -e ../.tup -a ! -e .tup ]; do
+ cd ..
+ done
+
+ if [ -e tup.config ]; then
+ configDir=$PWD
+ cd ..
+ echo "$PWD${topDir#$configDir}"
+ else
+ echo "$topDir"
+ fi
+}
+
+pushd . >/dev/null
+if pwd | grep --quiet /.tup/mnt/@tupjob-; then
+ # get out from the tup virtual filesystem
+ cd "/${PWD#*/.tup/mnt/@tupjob-*/}"
+
+ # get out from the tup variant directory (if any)
+ cd "$(eliminateTupVariant)"
+fi
+
+# tup support end
+
+rc=$(which rc)
+for i in $(which -a "$(basename "$0")"); do
+ filename="$i"
+ max=10
+ while [ $max -gt 0 -a -L "$filename" ]; do
+ max=$((max - 1))
+ link=$(readlink "$filename")
+ if echo "$link" | grep --quiet "^/"; then
+ filename="$link"
+ else
+ filename="$(dirname $filename)/$link"
+ fi
+ done
+
+ filename=$(basename "$filename")
+ if [ "$filename" != "gcc-rtags-wrapper.sh" ] && [ -z "$PLAST" -o "$filename" != "plastc" ]; then
+ [ -n "$RTAGS_SERVER_FILE" ] && RTAGS_ARGS="$RTAGS_ARGS -n$RTAGS_SERVER_FILE"
+ [ -n "$RTAGS_PROJECT" ] && RTAGS_ARGS="$RTAGS_ARGS --project-root=$RTAGS_PROJECT"
+ [ -z "$RTAGS_COMPILE_TIMEOUT" ] && RTAGS_COMPILE_TIMEOUT=3000
+
+ if [ -z "$RTAGS_DISABLED" ] && [ -x "$rc" ]; then
+ case $(basename "$i") in
+ mpicc)
+ cc=cc
+ flags="$(mpicc -show|cut -d ' ' -f 2-) -DMPICH_NO_ATTR_TYPE_TAGS"
+ ;;
+ mpicxx)
+ cc=c++
+ flags="$(mpicxx -show|cut -d ' ' -f 2-) -DMPICH_NO_ATTR_TYPE_TAGS"
+ ;;
+ *)
+ cc="$i"
+ flags=""
+ ;;
+ esac
+ $rc --timeout=$RTAGS_COMPILE_TIMEOUT $RTAGS_ARGS --silent --compile "$cc" $flags "$@" &
+ disown &>/dev/null # rc might be finished by now and if so disown will yell at us
+ fi
+ [ "$RTAGS_RMAKE" ] && exit 0
+
+ export RTAGS_GCC_WRAPPER=1
+ popd >/dev/null
+ "$i" "$@"
+ exit $?
+ else
+ PATH="$(echo "$PATH" | sed -e "s,$(dirname "$i")/*:*,,g")"
+ fi
+done
+exit 1 ### no compiler found?
diff --git a/rtags/bin/rtags-gcc-prefix.sh b/rtags/bin/rtags-gcc-prefix.sh
new file mode 100755
index 0000000..aea57c0
--- /dev/null
+++ b/rtags/bin/rtags-gcc-prefix.sh
@@ -0,0 +1,8 @@
+#!/bin/bash
+
+[ -z "$RTAGS_DISABLED" ] && [ -x "$(which rc)" ] && rc --silent --compile "$@" &
+[ -n "$RTAGS_RMAKE" ] && exit 0
+compiler="$1"
+shift
+$compiler "$@"
+exit $?
diff --git a/rtags/clang.sup b/rtags/clang.sup
new file mode 100644
index 0000000..90b8415
--- /dev/null
+++ b/rtags/clang.sup
@@ -0,0 +1,19 @@
+{
+ 1
+ Memcheck:Cond
+ fun:_ZNK5clang4Expr21refersToVectorElementEv
+ obj:*
+}
+
+
+{
+ 2
+ Memcheck:Cond
+ fun:_ZNK5clang4Expr21refersToVectorElementEv
+}
+{
+ 3
+ Memcheck:Cond
+ fun:_ZNK5clang4Expr17isTemporaryObjectERNS_10ASTContextEPKNS_13CXXRecordDeclE
+}
+
diff --git a/rtags/cmake/BashCompletion.cmake b/rtags/cmake/BashCompletion.cmake
new file mode 100644
index 0000000..a38dabd
--- /dev/null
+++ b/rtags/cmake/BashCompletion.cmake
@@ -0,0 +1,34 @@
+set(FORCE_BASH_COMPLETION_INSTALLATION FALSE CACHE BOOL "Force bash completion installation")
+
+if(FORCE_BASH_COMPLETION_INSTALLATION AND "${BASH_COMPLETION_COMPLETIONSDIR}" STREQUAL "")
+ set(BASH_COMPLETION_COMPLETIONSDIR "/share/bash-completion/completions")
+endif()
+
+find_package(PkgConfig QUIET)
+set_package_properties(PkgConfig
+ PROPERTIES
+ URL "https://www.freedesktop.org/wiki/Software/pkg-config/"
+ DESCRIPTION "helper tool"
+ TYPE OPTIONAL
+ PURPOSE "We use it to get the bash completion installation path, and replace the prefix with the value of CMAKE_INSTALL_PREFIX.")
+if(PKG_CONFIG_FOUND OR FORCE_BASH_COMPLETION_INSTALLATION)
+ if(PKG_CONFIG_FOUND AND NOT FORCE_BASH_COMPLETION_INSTALLATION)
+ execute_process(COMMAND ${PKG_CONFIG_EXECUTABLE} --variable=completionsdir bash-completion
+ RESULT_VARIABLE BASH_COMPLETION_UNAVAILABLE
+ OUTPUT_VARIABLE BASH_COMPLETION_COMPLETIONSDIR
+ ERROR_QUIET
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ if(NOT BASH_COMPLETION_UNAVAILABLE)
+ execute_process(COMMAND ${PKG_CONFIG_EXECUTABLE} --variable=prefix bash-completion
+ OUTPUT_VARIABLE BASH_COMPLETION_COMPLETIONSDIR_PREFIX
+ ERROR_QUIET
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ string(REPLACE "${BASH_COMPLETION_COMPLETIONSDIR_PREFIX}" "" BASH_COMPLETION_COMPLETIONSDIR ${BASH_COMPLETION_COMPLETIONSDIR})
+ endif()
+ endif()
+ if(NOT BASH_COMPLETION_UNAVAILABLE OR FORCE_BASH_COMPLETION_INSTALLATION)
+ set(BASH_COMPLETION_COMPLETIONSDIR "${CMAKE_INSTALL_PREFIX}${BASH_COMPLETION_COMPLETIONSDIR}" CACHE PATH "Bash completion installation directory" FORCE)
+ mark_as_advanced(BASH_COMPLETION_COMPLETIONSDIR)
+ set(BASH_COMPLETION_FOUND TRUE)
+ endif()
+endif()
diff --git a/rtags/cmake/ClangVersion.cmake b/rtags/cmake/ClangVersion.cmake
new file mode 100644
index 0000000..c311f1b
--- /dev/null
+++ b/rtags/cmake/ClangVersion.cmake
@@ -0,0 +1,23 @@
+macro(ClangVersion path version_major version_minor)
+ if(EXISTS "${path}/clang/Basic/Version.inc")
+ file(READ "${path}/clang/Basic/Version.inc" CLANG_VERSION_DATA)
+ string(REGEX REPLACE ";" "\\\\;" CLANG_VERSION_DATA ${CLANG_VERSION_DATA})
+ string(REGEX REPLACE "\n" ";" CLANG_VERSION_DATA ${CLANG_VERSION_DATA})
+ foreach(line ${CLANG_VERSION_DATA})
+ string(REGEX REPLACE "^#define CLANG_VERSION ([0-9]+\\.[0-9]+)$" "\\1" CLANG_VERSION_STRING ${line})
+ if(DEFINED CLANG_VERSION_STRING)
+ string(REGEX REPLACE "^([0-9]+)\\.[0-9]+$" "\\1" CLANG_VERSION_MAJOR ${CLANG_VERSION_STRING})
+ string(REGEX REPLACE "^[0-9]+\\.([0-9]+)$" "\\1" CLANG_VERSION_MINOR ${CLANG_VERSION_STRING})
+ if(NOT ${CLANG_VERSION_MAJOR} STREQUAL "" AND NOT ${CLANG_VERSION_MINOR} STREQUAL "")
+ break()
+ endif()
+ endif()
+ endforeach()
+ endif()
+ if(NOT ${CLANG_VERSION_MAJOR} STREQUAL "" AND NOT ${CLANG_VERSION_MINOR} STREQUAL "")
+ set(${version_major} ${CLANG_VERSION_MAJOR})
+ set(${version_minor} ${CLANG_VERSION_MINOR})
+ else()
+ message(FATAL_ERROR "Unable to parse ClangVersion from ${path}/clang/Basic/Version.inc")
+ endif()
+endmacro()
diff --git a/rtags/cmake/EnsureLibraries.cmake b/rtags/cmake/EnsureLibraries.cmake
new file mode 100644
index 0000000..65594a4
--- /dev/null
+++ b/rtags/cmake/EnsureLibraries.cmake
@@ -0,0 +1,46 @@
+#### EnsureLibraries
+
+# Macro for copying needed libraries to target directory
+MACRO(EnsureLibraries EXE_NAME LIBRARY_NAMES )
+
+ FOREACH ( LIBRARY_NAME IN ITEMS ${LIBRARY_NAMES} )
+ GET_TARGET_PROPERTY ( libLocation "${LIBRARY_NAME}" LOCATION )
+
+ IF ( NOT "${libLocation}" STREQUAL "libLocation-NOTFOUND" )
+
+ GET_TARGET_PROPERTY ( exeLocation "${EXE_NAME}" LOCATION )
+
+ IF ( CMAKE_COMPILER_IS_GNUCC )
+ ADD_CUSTOM_COMMAND ( TARGET ${EXE_NAME}
+ POST_BUILD
+ COMMAND ${CMAKE_COMMAND} -D LIBRARY="${libLocation}" -D TARGET="${exeLocation}" -P "${CMAKE_SOURCE_DIR}/cmake/EnsureLibrariesRunner.cmake"
+ COMMENT "Copy lib ${LIBRARY_NAME} to ${EXE_NAME} build ..."
+ DEPENDS ${LIBRARY_NAME}
+ )
+ ELSE ( CMAKE_COMPILER_IS_GNUCC )
+
+ INCLUDE(GenerateExportHeader)
+
+ IF ( NOT CYGWIN )
+ GENERATE_EXPORT_HEADER( ${LIBRARY_NAME}
+ BASE_NAME ${LIBRARY_NAME}
+ EXPORT_MACRO_NAME ${LIBRARY_NAME}_EXPORT
+ EXPORT_FILE_NAME ${LIBRARY_NAME}_Export.h
+ STATIC_DEFINE ${LIBRARY_NAME}_BUILT_AS_STATIC
+ )
+ ENDIF ( NOT CYGWIN )
+
+ ADD_CUSTOM_COMMAND ( TARGET ${EXE_NAME}
+ POST_BUILD
+ COMMAND ${CMAKE_COMMAND} -E copy "${libLocation}" "$"
+ COMMENT "Copy lib ${LIBRARY_NAME} to ${EXE_NAME} build ..."
+ DEPENDS ${LIBRARY_NAME}
+ DEPENDS osswin
+ )
+ ENDIF ( CMAKE_COMPILER_IS_GNUCC )
+
+ ENDIF ( NOT "${libLocation}" STREQUAL "libLocation-NOTFOUND" )
+
+ ENDFOREACH ( LIBRARY_NAME IN ITEMS ${LIBRARY_NAMES} )
+
+ENDMACRO(EnsureLibraries)
diff --git a/rtags/cmake/EnsureLibrariesRunner.cmake b/rtags/cmake/EnsureLibrariesRunner.cmake
new file mode 100644
index 0000000..5f5efe3
--- /dev/null
+++ b/rtags/cmake/EnsureLibrariesRunner.cmake
@@ -0,0 +1,28 @@
+
+IF ( NOT EXISTS ${LIBRARY} )
+ MESSAGE ( FATAL_ERROR "The provided file ${LIBRARY} does not exist" )
+ RETURN ()
+ENDIF ( NOT EXISTS ${LIBRARY} )
+
+SET ( TARGET_PATH "${TARGET}" )
+
+IF ( EXISTS ${TARGET} AND NOT IS_DIRECTORY ${TARGET} )
+ FILE ( TO_NATIVE_PATH "${TARGET}" TARGET_PATH )
+ IF ( EXISTS ${TARGET_PATH} )
+ GET_FILENAME_COMPONENT ( TARGET_PATH ${TARGET} PATH )
+ ENDIF ( EXISTS ${TARGET_PATH} )
+ENDIF ( EXISTS ${TARGET} AND NOT IS_DIRECTORY ${TARGET} )
+
+IF ( NOT EXISTS ${TARGET_PATH} AND NOT IS_DIRECTORY ${TARGET_PATH} )
+ MESSAGE ( FATAL_ERROR "The provided target ${TARGET_PATH} does not exist, and is not a directory" )
+ RETURN ()
+ENDIF ( NOT EXISTS ${TARGET_PATH} AND NOT IS_DIRECTORY ${TARGET_PATH} )
+SET ( OUTPUT_TARGET ${TARGET_PATH} )
+
+FILE ( TO_NATIVE_PATH "${LIBRARY}" NATIVE_LIBRARY_PATH )
+FILE ( TO_NATIVE_PATH "${OUTPUT_TARGET}/" NATIVE_TARGET_PATH )
+
+#MESSAGE ( STATUS "Copying ${NATIVE_LIBRARY_PATH} => ${NATIVE_TARGET_PATH}" )
+
+FILE ( COPY ${NATIVE_LIBRARY_PATH} DESTINATION ${NATIVE_TARGET_PATH} )
+
diff --git a/rtags/cmake/FindLibClang.cmake b/rtags/cmake/FindLibClang.cmake
new file mode 100644
index 0000000..1e95cb7
--- /dev/null
+++ b/rtags/cmake/FindLibClang.cmake
@@ -0,0 +1,141 @@
+# FindLibClang
+#
+# This module searches libclang and llvm-config, the llvm-config tool is used to
+# get information about the installed llvm/clang package to compile LLVM based
+# programs.
+#
+# It defines the following variables
+#
+# ``LIBCLANG_LLVM_CONFIG_EXECUTABLE``
+# the llvm-config tool to get various information.
+# ``LIBCLANG_LIBRARIES``
+# the clang libraries to link against to use Clang/LLVM.
+# ``LIBCLANG_LIBDIR``
+# the directory where the clang libraries are located.
+# ``LIBCLANG_FOUND``
+# true if libclang was found
+# ``LIBCLANG_VERSION_STRING``
+# version number as a string
+# ``LIBCLANG_CXXFLAGS``
+# the compiler flags for files that include LLVM headers
+#
+#=============================================================================
+# Copyright (C) 2011, 2012, 2013 Jan Erik Hanssen and Anders Bakken
+# Copyright (C) 2015 Christian Schwarzgruber
+#
+# This file is part of RTags (http://rtags.net).
+#
+# RTags is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# RTags is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with RTags. If not, see .
+
+if (NOT LIBCLANG_ROOT_DIR)
+ set(LIBCLANG_ROOT_DIR $ENV{LIBCLANG_ROOT_DIR})
+endif ()
+
+if (NOT LIBCLANG_LLVM_CONFIG_EXECUTABLE)
+ set(LIBCLANG_LLVM_CONFIG_EXECUTABLE $ENV{LIBCLANG_LLVM_CONFIG_EXECUTABLE})
+ if (NOT LIBCLANG_LLVM_CONFIG_EXECUTABLE)
+ if (APPLE)
+ foreach(major RANGE 9 3)
+ foreach(minor RANGE 9 0)
+ foreach(patch RANGE 9 0)
+ message(STATUS "trying llvm-config llvm-config${major}${minor} in /usr/local/Cellar/llvm/${major}.${minor}.${patch}/bin")
+ find_program(LIBCLANG_LLVM_CONFIG_EXECUTABLE NAMES llvm-config llvm-config${major}${minor} llvm-config-${major}${minor} llvm-config-${major} llvm-config${major} PATHS /usr/local/Cellar/llvm/${major}.${minor}.${patch}/bin)
+ if (LIBCLANG_LLVM_CONFIG_EXECUTABLE)
+ break()
+ endif ()
+ endforeach ()
+ if (LIBCLANG_LLVM_CONFIG_EXECUTABLE)
+ break()
+ endif ()
+ endforeach ()
+ if (LIBCLANG_LLVM_CONFIG_EXECUTABLE)
+ break()
+ endif ()
+ endforeach ()
+ else ()
+ set(llvm_config_names llvm-config)
+ foreach(major RANGE 9 3)
+ list(APPEND llvm_config_names "llvm-config${major}" "llvm-config-${major}")
+ foreach(minor RANGE 9 0)
+ list(APPEND llvm_config_names "llvm-config${major}${minor}" "llvm-config-${major}.${minor}" "llvm-config-mp-${major}.${minor}")
+ endforeach ()
+ endforeach ()
+ find_program(LIBCLANG_LLVM_CONFIG_EXECUTABLE NAMES ${llvm_config_names})
+ endif ()
+ endif ()
+ if (LIBCLANG_LLVM_CONFIG_EXECUTABLE)
+ message(STATUS "llvm-config executable found: ${LIBCLANG_LLVM_CONFIG_EXECUTABLE}")
+ endif ()
+endif ()
+
+if (NOT LIBCLANG_CXXFLAGS)
+ if (NOT LIBCLANG_LLVM_CONFIG_EXECUTABLE)
+ message(FATAL_ERROR "Could NOT find llvm-config executable and LIBCLANG_CXXFLAGS is not set ")
+ endif ()
+ execute_process(COMMAND ${LIBCLANG_LLVM_CONFIG_EXECUTABLE} --cxxflags OUTPUT_VARIABLE LIBCLANG_CXXFLAGS OUTPUT_STRIP_TRAILING_WHITESPACE)
+ if (NOT LIBCLANG_CXXFLAGS)
+ find_path(LIBCLANG_CXXFLAGS_HACK_CMAKECACHE_DOT_TEXT_BULLSHIT clang-c/Index.h HINTS ${LIBCLANG_ROOT_DIR}/include NO_DEFAULT_PATH)
+ if (NOT EXISTS ${LIBCLANG_CXXFLAGS_HACK_CMAKECACHE_DOT_TEXT_BULLSHIT})
+ find_path(LIBCLANG_CXXFLAGS clang-c/Index.h)
+ if (NOT EXISTS ${LIBCLANG_CXXFLAGS})
+ message(FATAL_ERROR "Could NOT find clang include path. You can fix this by setting LIBCLANG_CXXFLAGS in your shell or as a cmake variable.")
+ endif ()
+ else ()
+ set(LIBCLANG_CXXFLAGS ${LIBCLANG_CXXFLAGS_HACK_CMAKECACHE_DOT_TEXT_BULLSHIT})
+ endif ()
+ set(LIBCLANG_CXXFLAGS "-I${LIBCLANG_CXXFLAGS}")
+ endif ()
+ string(REGEX MATCHALL "-(D__?[a-zA-Z_]*|I([^\" ]+|\"[^\"]+\"))" LIBCLANG_CXXFLAGS "${LIBCLANG_CXXFLAGS}")
+ string(REGEX REPLACE ";" " " LIBCLANG_CXXFLAGS "${LIBCLANG_CXXFLAGS}")
+ set(LIBCLANG_CXXFLAGS ${LIBCLANG_CXXFLAGS} CACHE STRING "The LLVM C++ compiler flags needed to compile LLVM based applications.")
+ unset(LIBCLANG_CXXFLAGS_HACK_CMAKECACHE_DOT_TEXT_BULLSHIT CACHE)
+endif ()
+
+if (NOT EXISTS ${LIBCLANG_LIBDIR})
+ if (NOT LIBCLANG_LLVM_CONFIG_EXECUTABLE)
+ message(FATAL_ERROR "Could NOT find llvm-config executable and LIBCLANG_LIBDIR is not set ")
+ endif ()
+ execute_process(COMMAND ${LIBCLANG_LLVM_CONFIG_EXECUTABLE} --libdir OUTPUT_VARIABLE LIBCLANG_LIBDIR OUTPUT_STRIP_TRAILING_WHITESPACE)
+ if (NOT EXISTS ${LIBCLANG_LIBDIR})
+ message(FATAL_ERROR "Could NOT find clang libdir. You can fix this by setting LIBCLANG_LIBDIR in your shell or as a cmake variable.")
+ endif ()
+ set(LIBCLANG_LIBDIR ${LIBCLANG_LIBDIR} CACHE STRING "Path to the clang library.")
+endif ()
+
+if (NOT LIBCLANG_LIBRARIES)
+ find_library(LIBCLANG_LIB_HACK_CMAKECACHE_DOT_TEXT_BULLSHIT NAMES clang libclang HINTS ${LIBCLANG_LIBDIR} ${LIBCLANG_ROOT_DIR}/lib NO_DEFAULT_PATH)
+ if (LIBCLANG_LIB_HACK_CMAKECACHE_DOT_TEXT_BULLSHIT)
+ set(LIBCLANG_LIBRARIES "${LIBCLANG_LIB_HACK_CMAKECACHE_DOT_TEXT_BULLSHIT}")
+ else ()
+ find_library(LIBCLANG_LIBRARIES NAMES clang libclang)
+ if (NOT EXISTS ${LIBCLANG_LIBRARIES})
+ set (LIBCLANG_LIBRARIES "-L${LIBCLANG_LIBDIR}" "-lclang" "-Wl,-rpath,${LIBCLANG_LIBDIR}")
+ endif ()
+ endif ()
+ unset(LIBCLANG_LIB_HACK_CMAKECACHE_DOT_TEXT_BULLSHIT CACHE)
+endif ()
+
+set(LIBCLANG_LIBRARY ${LIBCLANG_LIBRARIES} CACHE FILEPATH "Path to the libclang library")
+
+if (LIBCLANG_LLVM_CONFIG_EXECUTABLE)
+ execute_process(COMMAND ${LIBCLANG_LLVM_CONFIG_EXECUTABLE} --version OUTPUT_VARIABLE LIBCLANG_VERSION_STRING OUTPUT_STRIP_TRAILING_WHITESPACE)
+else ()
+ set(LIBCLANG_VERSION_STRING "Unknown")
+endif ()
+message("-- Using Clang version ${LIBCLANG_VERSION_STRING} from ${LIBCLANG_LIBDIR} with CXXFLAGS ${LIBCLANG_CXXFLAGS}")
+
+# Handly the QUIETLY and REQUIRED arguments and set LIBCLANG_FOUND to TRUE if all listed variables are TRUE
+include(FindPackageHandleStandardArgs)
+find_package_handle_standard_args(LibClang DEFAULT_MSG LIBCLANG_LIBRARY LIBCLANG_CXXFLAGS LIBCLANG_LIBDIR)
+mark_as_advanced(LIBCLANG_CXXFLAGS LIBCLANG_LIBRARY LIBCLANG_LLVM_CONFIG_EXECUTABLE LIBCLANG_LIBDIR)
diff --git a/rtags/cmake/PkgInfo.cmake b/rtags/cmake/PkgInfo.cmake
new file mode 100644
index 0000000..a0c125f
--- /dev/null
+++ b/rtags/cmake/PkgInfo.cmake
@@ -0,0 +1,70 @@
+find_package(Git)
+if(GIT_FOUND)
+ set(USE_GIT 1)
+else()
+ set(USE_GIT 0)
+endif()
+
+if(${USE_GIT} EQUAL 1)
+ execute_process(
+ COMMAND ${GIT_EXECUTABLE} describe --tags --dirty
+ WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
+ OUTPUT_VARIABLE GIT_DESCRIBE_VERSION
+ RESULT_VARIABLE GIT_DESCRIBE_RESULT
+ ERROR_VARIABLE GIT_DESCRIBE_ERROR
+ OUTPUT_STRIP_TRAILING_WHITESPACE
+ )
+ execute_process(
+ COMMAND ${GIT_EXECUTABLE} config --get user.name
+ WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
+ OUTPUT_VARIABLE GIT_CONFIG_USERNAME
+ RESULT_VARIABLE GIT_CONFIG_RESULT
+ ERROR_VARIABLE GIT_CONFIG_ERROR
+ OUTPUT_STRIP_TRAILING_WHITESPACE
+ )
+else()
+ set(GIT_DESCRIBE_RESULT -1)
+ set(GIT_CONFIG_RESULT -1)
+endif()
+
+#
+# Deal with version first
+#
+if(GIT_DESCRIBE_RESULT EQUAL 0)
+ file(WRITE ${CMAKE_BINARY_DIR}/source/VERSION "${GIT_DESCRIBE_VERSION}")
+else()
+ file(READ ${CMAKE_SOURCE_DIR}/VERSION GIT_DESCRIBE_VERSION)
+endif()
+
+string(REGEX REPLACE "v([0-9]*)\\.([0-9]*)(-(.*))?"
+ "\\1;\\2;\\4" VLIST "${GIT_DESCRIBE_VERSION}")
+#message(INFO " vlist ${VLIST}")
+
+list(GET VLIST 0 VERSION_MAJOR)
+list(GET VLIST 1 VERSION_MINOR)
+list(LENGTH VLIST VLISTLEN)
+if(VLISTLEN EQUAL 3)
+ list(GET VLIST 2 VERSION_EXTRA)
+endif()
+set(VERSION "${VERSION_MAJOR}.${VERSION_MINOR}-${VERSION_EXTRA}")
+
+#
+# Deal with username
+#
+string(LENGTH "${GIT_CONFIG_USERNAME}" GIT_CONFIG_USERNAME_LENGTH)
+#message(INFO "uname <${GIT_CONFIG_USERNAME}>")
+#message(INFO "length ${GIT_CONFIG_USERNAME_LENGTH}")
+if(GIT_CONFIG_USERNAME_LENGTH EQUAL 0)
+ set(GIT_CONFIG_RESULT -1)
+endif()
+
+if(GIT_CONFIG_RESULT EQUAL -1)
+ if(WIN32)
+ set(PKG_USERNAME "$ENV{USERNAME}")
+ else()
+ set(PKG_USERNAME "$ENV{USER}")
+ endif()
+else()
+ set(PKG_USERNAME "${GIT_CONFIG_USERNAME}")
+endif()
+#message(INFO "user ${PKG_USERNAME}")
\ No newline at end of file
diff --git a/rtags/cmake/Uninstall.cmake.in b/rtags/cmake/Uninstall.cmake.in
new file mode 100644
index 0000000..1f17834
--- /dev/null
+++ b/rtags/cmake/Uninstall.cmake.in
@@ -0,0 +1,39 @@
+set(MANIFEST "${CMAKE_CURRENT_BINARY_DIR}/install_manifest.txt")
+
+if(NOT EXISTS ${MANIFEST})
+ message(FATAL_ERROR "Cannot find install manifest: '${MANIFEST}'")
+endif()
+
+file(STRINGS ${MANIFEST} files)
+foreach(file ${files})
+ if(IS_SYMLINK ${file} OR EXISTS ${file})
+ message(STATUS "Removing file: '${file}'.")
+ exec_program(${CMAKE_COMMAND} ARGS "-E remove ${file}" OUTPUT_VARIABLE stdout RETURN_VALUE result)
+ if(NOT "${result}" STREQUAL 0)
+ message(FATAL_ERROR "Failed to remove file: '${file}'.")
+ endif()
+ else()
+ message(STATUS "File '${file}' does not exist.")
+ endif()
+endforeach()
+
+# We will not traverse back and delete "arbitrary" folders.
+# An exception are directories which are rtags specific directories like,
+# "rtags" under "INSTALL_PREFIX/usr/emacs/site-lisp/".
+set(directories "@CMAKE_INSTALL_PREFIX@/share/emacs/site-lisp/rtags")
+foreach(dir ${directories})
+ if(IS_DIRECTORY ${dir} AND EXISTS ${dir})
+ file(GLOB files "${dir}/*")
+ if(NOT files)
+ message(STATUS "Removing directory: '${dir}'.")
+ exec_program(${CMAKE_COMMAND} ARGS "-E remove_directory ${dir}" OUTPUT_VARIABLE stdout RETURN_VALUE result)
+ if(NOT "${result}" STREQUAL 0)
+ message(FATAL_ERROR "Failed to remove directory: '${dir}'.")
+ endif()
+ else()
+ message(STATUS "Directory '${dir}' not empty.")
+ endif()
+ else()
+ message(STATUS "Directory '${dir}' does not exist.")
+ endif()
+endforeach()
diff --git a/rtags/cmake/cotire.cmake b/rtags/cmake/cotire.cmake
new file mode 100644
index 0000000..a4fb533
--- /dev/null
+++ b/rtags/cmake/cotire.cmake
@@ -0,0 +1,3827 @@
+# - cotire (compile time reducer)
+#
+# See the cotire manual for usage hints.
+#
+#=============================================================================
+# Copyright 2012-2015 Sascha Kratky
+#
+# Permission is hereby granted, free of charge, to any person
+# obtaining a copy of this software and associated documentation
+# files (the "Software"), to deal in the Software without
+# restriction, including without limitation the rights to use,
+# copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the
+# Software is furnished to do so, subject to the following
+# conditions:
+#
+# The above copyright notice and this permission notice shall be
+# included in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+# OTHER DEALINGS IN THE SOFTWARE.
+#=============================================================================
+
+if(__COTIRE_INCLUDED)
+ return()
+endif()
+set(__COTIRE_INCLUDED TRUE)
+
+# call cmake_minimum_required, but prevent modification of the CMake policy stack in include mode
+# cmake_minimum_required also sets the policy version as a side effect, which we have to avoid
+if (NOT CMAKE_SCRIPT_MODE_FILE)
+ cmake_policy(PUSH)
+endif()
+cmake_minimum_required(VERSION 2.8.12)
+if (NOT CMAKE_SCRIPT_MODE_FILE)
+ cmake_policy(POP)
+endif()
+
+set (COTIRE_CMAKE_MODULE_FILE "${CMAKE_CURRENT_LIST_FILE}")
+set (COTIRE_CMAKE_MODULE_VERSION "1.7.6")
+
+# activate select policies
+if (POLICY CMP0025)
+ # Compiler id for Apple Clang is now AppleClang
+ cmake_policy(SET CMP0025 NEW)
+endif()
+
+if (POLICY CMP0026)
+ # disallow use of the LOCATION target property
+ cmake_policy(SET CMP0026 NEW)
+endif()
+
+if (POLICY CMP0038)
+ # targets may not link directly to themselves
+ cmake_policy(SET CMP0038 NEW)
+endif()
+
+if (POLICY CMP0039)
+ # utility targets may not have link dependencies
+ cmake_policy(SET CMP0039 NEW)
+endif()
+
+if (POLICY CMP0040)
+ # target in the TARGET signature of add_custom_command() must exist
+ cmake_policy(SET CMP0040 NEW)
+endif()
+
+if (POLICY CMP0045)
+ # error on non-existent target in get_target_property
+ cmake_policy(SET CMP0045 NEW)
+endif()
+
+if (POLICY CMP0046)
+ # error on non-existent dependency in add_dependencies
+ cmake_policy(SET CMP0046 NEW)
+endif()
+
+if (POLICY CMP0049)
+ # do not expand variables in target source entries
+ cmake_policy(SET CMP0049 NEW)
+endif()
+
+if (POLICY CMP0050)
+ # disallow add_custom_command SOURCE signatures
+ cmake_policy(SET CMP0050 NEW)
+endif()
+
+if (POLICY CMP0051)
+ # include TARGET_OBJECTS expressions in a target's SOURCES property
+ cmake_policy(SET CMP0051 NEW)
+endif()
+
+if (POLICY CMP0053)
+ # simplify variable reference and escape sequence evaluation
+ cmake_policy(SET CMP0053 NEW)
+endif()
+
+if (POLICY CMP0054)
+ # only interpret if() arguments as variables or keywords when unquoted
+ cmake_policy(SET CMP0054 NEW)
+endif()
+
+include(CMakeParseArguments)
+include(ProcessorCount)
+
+function (cotire_get_configuration_types _configsVar)
+ set (_configs "")
+ if (CMAKE_CONFIGURATION_TYPES)
+ list (APPEND _configs ${CMAKE_CONFIGURATION_TYPES})
+ endif()
+ if (CMAKE_BUILD_TYPE)
+ list (APPEND _configs "${CMAKE_BUILD_TYPE}")
+ endif()
+ if (_configs)
+ list (REMOVE_DUPLICATES _configs)
+ set (${_configsVar} ${_configs} PARENT_SCOPE)
+ else()
+ set (${_configsVar} "None" PARENT_SCOPE)
+ endif()
+endfunction()
+
+function (cotire_get_source_file_extension _sourceFile _extVar)
+ # get_filename_component returns extension from first occurrence of . in file name
+ # this function computes the extension from last occurrence of . in file name
+ string (FIND "${_sourceFile}" "." _index REVERSE)
+ if (_index GREATER -1)
+ math (EXPR _index "${_index} + 1")
+ string (SUBSTRING "${_sourceFile}" ${_index} -1 _sourceExt)
+ else()
+ set (_sourceExt "")
+ endif()
+ set (${_extVar} "${_sourceExt}" PARENT_SCOPE)
+endfunction()
+
+macro (cotire_check_is_path_relative_to _path _isRelativeVar)
+ set (${_isRelativeVar} FALSE)
+ if (IS_ABSOLUTE "${_path}")
+ foreach (_dir ${ARGN})
+ file (RELATIVE_PATH _relPath "${_dir}" "${_path}")
+ if (NOT _relPath OR (NOT IS_ABSOLUTE "${_relPath}" AND NOT "${_relPath}" MATCHES "^\\.\\."))
+ set (${_isRelativeVar} TRUE)
+ break()
+ endif()
+ endforeach()
+ endif()
+endmacro()
+
+function (cotire_filter_language_source_files _language _target _sourceFilesVar _excludedSourceFilesVar _cotiredSourceFilesVar)
+ if (CMAKE_${_language}_SOURCE_FILE_EXTENSIONS)
+ set (_languageExtensions "${CMAKE_${_language}_SOURCE_FILE_EXTENSIONS}")
+ else()
+ set (_languageExtensions "")
+ endif()
+ if (CMAKE_${_language}_IGNORE_EXTENSIONS)
+ set (_ignoreExtensions "${CMAKE_${_language}_IGNORE_EXTENSIONS}")
+ else()
+ set (_ignoreExtensions "")
+ endif()
+ if (COTIRE_UNITY_SOURCE_EXCLUDE_EXTENSIONS)
+ set (_excludeExtensions "${COTIRE_UNITY_SOURCE_EXCLUDE_EXTENSIONS}")
+ else()
+ set (_excludeExtensions "")
+ endif()
+ if (COTIRE_DEBUG AND _languageExtensions)
+ message (STATUS "${_language} source file extensions: ${_languageExtensions}")
+ endif()
+ if (COTIRE_DEBUG AND _ignoreExtensions)
+ message (STATUS "${_language} ignore extensions: ${_ignoreExtensions}")
+ endif()
+ if (COTIRE_DEBUG AND _excludeExtensions)
+ message (STATUS "${_language} exclude extensions: ${_excludeExtensions}")
+ endif()
+ if (CMAKE_VERSION VERSION_LESS "3.1.0")
+ set (_allSourceFiles ${ARGN})
+ else()
+ # as of CMake 3.1 target sources may contain generator expressions
+ # since we cannot obtain required property information about source files added
+ # through generator expressions at configure time, we filter them out
+ string (GENEX_STRIP "${ARGN}" _allSourceFiles)
+ endif()
+ set (_filteredSourceFiles "")
+ set (_excludedSourceFiles "")
+ foreach (_sourceFile ${_allSourceFiles})
+ get_source_file_property(_sourceIsHeaderOnly "${_sourceFile}" HEADER_FILE_ONLY)
+ get_source_file_property(_sourceIsExternal "${_sourceFile}" EXTERNAL_OBJECT)
+ get_source_file_property(_sourceIsSymbolic "${_sourceFile}" SYMBOLIC)
+ if (NOT _sourceIsHeaderOnly AND NOT _sourceIsExternal AND NOT _sourceIsSymbolic)
+ cotire_get_source_file_extension("${_sourceFile}" _sourceExt)
+ if (_sourceExt)
+ list (FIND _ignoreExtensions "${_sourceExt}" _ignoreIndex)
+ if (_ignoreIndex LESS 0)
+ list (FIND _excludeExtensions "${_sourceExt}" _excludeIndex)
+ if (_excludeIndex GREATER -1)
+ list (APPEND _excludedSourceFiles "${_sourceFile}")
+ else()
+ list (FIND _languageExtensions "${_sourceExt}" _sourceIndex)
+ if (_sourceIndex GREATER -1)
+ # consider source file unless it is excluded explicitly
+ get_source_file_property(_sourceIsExcluded "${_sourceFile}" COTIRE_EXCLUDED)
+ if (_sourceIsExcluded)
+ list (APPEND _excludedSourceFiles "${_sourceFile}")
+ else()
+ list (APPEND _filteredSourceFiles "${_sourceFile}")
+ endif()
+ else()
+ get_source_file_property(_sourceLanguage "${_sourceFile}" LANGUAGE)
+ if ("${_sourceLanguage}" STREQUAL "${_language}")
+ # add to excluded sources, if file is not ignored and has correct language without having the correct extension
+ list (APPEND _excludedSourceFiles "${_sourceFile}")
+ endif()
+ endif()
+ endif()
+ endif()
+ endif()
+ endif()
+ endforeach()
+ # separate filtered source files from already cotired ones
+ # the COTIRE_TARGET property of a source file may be set while a target is being processed by cotire
+ set (_sourceFiles "")
+ set (_cotiredSourceFiles "")
+ foreach (_sourceFile ${_filteredSourceFiles})
+ get_source_file_property(_sourceIsCotired "${_sourceFile}" COTIRE_TARGET)
+ if (_sourceIsCotired)
+ list (APPEND _cotiredSourceFiles "${_sourceFile}")
+ else()
+ get_source_file_property(_sourceCompileFlags "${_sourceFile}" COMPILE_FLAGS)
+ if (_sourceCompileFlags)
+ # add to excluded sources, if file has custom compile flags
+ list (APPEND _excludedSourceFiles "${_sourceFile}")
+ else()
+ list (APPEND _sourceFiles "${_sourceFile}")
+ endif()
+ endif()
+ endforeach()
+ if (COTIRE_DEBUG)
+ if (_sourceFiles)
+ message (STATUS "Filtered ${_target} ${_language} sources: ${_sourceFiles}")
+ endif()
+ if (_excludedSourceFiles)
+ message (STATUS "Excluded ${_target} ${_language} sources: ${_excludedSourceFiles}")
+ endif()
+ if (_cotiredSourceFiles)
+ message (STATUS "Cotired ${_target} ${_language} sources: ${_cotiredSourceFiles}")
+ endif()
+ endif()
+ set (${_sourceFilesVar} ${_sourceFiles} PARENT_SCOPE)
+ set (${_excludedSourceFilesVar} ${_excludedSourceFiles} PARENT_SCOPE)
+ set (${_cotiredSourceFilesVar} ${_cotiredSourceFiles} PARENT_SCOPE)
+endfunction()
+
+function (cotire_get_objects_with_property_on _filteredObjectsVar _property _type)
+ set (_filteredObjects "")
+ foreach (_object ${ARGN})
+ get_property(_isSet ${_type} "${_object}" PROPERTY ${_property} SET)
+ if (_isSet)
+ get_property(_propertyValue ${_type} "${_object}" PROPERTY ${_property})
+ if (_propertyValue)
+ list (APPEND _filteredObjects "${_object}")
+ endif()
+ endif()
+ endforeach()
+ set (${_filteredObjectsVar} ${_filteredObjects} PARENT_SCOPE)
+endfunction()
+
+function (cotire_get_objects_with_property_off _filteredObjectsVar _property _type)
+ set (_filteredObjects "")
+ foreach (_object ${ARGN})
+ get_property(_isSet ${_type} "${_object}" PROPERTY ${_property} SET)
+ if (_isSet)
+ get_property(_propertyValue ${_type} "${_object}" PROPERTY ${_property})
+ if (NOT _propertyValue)
+ list (APPEND _filteredObjects "${_object}")
+ endif()
+ endif()
+ endforeach()
+ set (${_filteredObjectsVar} ${_filteredObjects} PARENT_SCOPE)
+endfunction()
+
+function (cotire_get_source_file_property_values _valuesVar _property)
+ set (_values "")
+ foreach (_sourceFile ${ARGN})
+ get_source_file_property(_propertyValue "${_sourceFile}" ${_property})
+ if (_propertyValue)
+ list (APPEND _values "${_propertyValue}")
+ endif()
+ endforeach()
+ set (${_valuesVar} ${_values} PARENT_SCOPE)
+endfunction()
+
+function (cotire_resolve_config_properites _configurations _propertiesVar)
+ set (_properties "")
+ foreach (_property ${ARGN})
+ if ("${_property}" MATCHES "")
+ foreach (_config ${_configurations})
+ string (TOUPPER "${_config}" _upperConfig)
+ string (REPLACE "" "${_upperConfig}" _configProperty "${_property}")
+ list (APPEND _properties ${_configProperty})
+ endforeach()
+ else()
+ list (APPEND _properties ${_property})
+ endif()
+ endforeach()
+ set (${_propertiesVar} ${_properties} PARENT_SCOPE)
+endfunction()
+
+function (cotire_copy_set_properites _configurations _type _source _target)
+ cotire_resolve_config_properites("${_configurations}" _properties ${ARGN})
+ foreach (_property ${_properties})
+ get_property(_isSet ${_type} ${_source} PROPERTY ${_property} SET)
+ if (_isSet)
+ get_property(_propertyValue ${_type} ${_source} PROPERTY ${_property})
+ set_property(${_type} ${_target} PROPERTY ${_property} "${_propertyValue}")
+ endif()
+ endforeach()
+endfunction()
+
+function (cotire_get_target_usage_requirements _target _targetRequirementsVar)
+ set (_targetRequirements "")
+ get_target_property(_librariesToProcess ${_target} LINK_LIBRARIES)
+ while (_librariesToProcess)
+ # remove from head
+ list (GET _librariesToProcess 0 _library)
+ list (REMOVE_AT _librariesToProcess 0)
+ if (TARGET ${_library})
+ list (FIND _targetRequirements ${_library} _index)
+ if (_index LESS 0)
+ list (APPEND _targetRequirements ${_library})
+ # process transitive libraries
+ get_target_property(_libraries ${_library} INTERFACE_LINK_LIBRARIES)
+ if (_libraries)
+ list (APPEND _librariesToProcess ${_libraries})
+ list (REMOVE_DUPLICATES _librariesToProcess)
+ endif()
+ endif()
+ endif()
+ endwhile()
+ set (${_targetRequirementsVar} ${_targetRequirements} PARENT_SCOPE)
+endfunction()
+
+function (cotire_filter_compile_flags _language _flagFilter _matchedOptionsVar _unmatchedOptionsVar)
+ if (WIN32 AND CMAKE_${_language}_COMPILER_ID MATCHES "MSVC|Intel")
+ set (_flagPrefix "[/-]")
+ else()
+ set (_flagPrefix "--?")
+ endif()
+ set (_optionFlag "")
+ set (_matchedOptions "")
+ set (_unmatchedOptions "")
+ foreach (_compileFlag ${ARGN})
+ if (_compileFlag)
+ if (_optionFlag AND NOT "${_compileFlag}" MATCHES "^${_flagPrefix}")
+ # option with separate argument
+ list (APPEND _matchedOptions "${_compileFlag}")
+ set (_optionFlag "")
+ elseif ("${_compileFlag}" MATCHES "^(${_flagPrefix})(${_flagFilter})$")
+ # remember option
+ set (_optionFlag "${CMAKE_MATCH_2}")
+ elseif ("${_compileFlag}" MATCHES "^(${_flagPrefix})(${_flagFilter})(.+)$")
+ # option with joined argument
+ list (APPEND _matchedOptions "${CMAKE_MATCH_3}")
+ set (_optionFlag "")
+ else()
+ # flush remembered option
+ if (_optionFlag)
+ list (APPEND _matchedOptions "${_optionFlag}")
+ set (_optionFlag "")
+ endif()
+ # add to unfiltered options
+ list (APPEND _unmatchedOptions "${_compileFlag}")
+ endif()
+ endif()
+ endforeach()
+ if (_optionFlag)
+ list (APPEND _matchedOptions "${_optionFlag}")
+ endif()
+ if (COTIRE_DEBUG AND _matchedOptions)
+ message (STATUS "Filter ${_flagFilter} matched: ${_matchedOptions}")
+ endif()
+ if (COTIRE_DEBUG AND _unmatchedOptions)
+ message (STATUS "Filter ${_flagFilter} unmatched: ${_unmatchedOptions}")
+ endif()
+ set (${_matchedOptionsVar} ${_matchedOptions} PARENT_SCOPE)
+ set (${_unmatchedOptionsVar} ${_unmatchedOptions} PARENT_SCOPE)
+endfunction()
+
+function (cotire_get_target_compile_flags _config _language _target _flagsVar)
+ string (TOUPPER "${_config}" _upperConfig)
+ # collect options from CMake language variables
+ set (_compileFlags "")
+ if (CMAKE_${_language}_FLAGS)
+ set (_compileFlags "${_compileFlags} ${CMAKE_${_language}_FLAGS}")
+ endif()
+ if (CMAKE_${_language}_FLAGS_${_upperConfig})
+ set (_compileFlags "${_compileFlags} ${CMAKE_${_language}_FLAGS_${_upperConfig}}")
+ endif()
+ if (_target)
+ # add target compile flags
+ get_target_property(_targetflags ${_target} COMPILE_FLAGS)
+ if (_targetflags)
+ set (_compileFlags "${_compileFlags} ${_targetflags}")
+ endif()
+ endif()
+ if (UNIX)
+ separate_arguments(_compileFlags UNIX_COMMAND "${_compileFlags}")
+ elseif(WIN32)
+ separate_arguments(_compileFlags WINDOWS_COMMAND "${_compileFlags}")
+ else()
+ separate_arguments(_compileFlags)
+ endif()
+ # target compile options
+ if (_target)
+ get_target_property(_targetOptions ${_target} COMPILE_OPTIONS)
+ if (_targetOptions)
+ list (APPEND _compileFlags ${_targetOptions})
+ endif()
+ endif()
+ # interface compile options from linked library targets
+ if (_target)
+ set (_linkedTargets "")
+ cotire_get_target_usage_requirements(${_target} _linkedTargets)
+ foreach (_linkedTarget ${_linkedTargets})
+ get_target_property(_targetOptions ${_linkedTarget} INTERFACE_COMPILE_OPTIONS)
+ if (_targetOptions)
+ list (APPEND _compileFlags ${_targetOptions})
+ endif()
+ endforeach()
+ endif()
+ # handle language standard properties
+ if (_target)
+ get_target_property(_targetLanguageStandard ${_target} ${_language}_STANDARD)
+ get_target_property(_targetLanguageExtensions ${_target} ${_language}_EXTENSIONS)
+ get_target_property(_targetLanguageStandardRequired ${_target} ${_language}_STANDARD_REQUIRED)
+ if (_targetLanguageExtensions)
+ if (CMAKE_${_language}${_targetLanguageExtensions}_EXTENSION_COMPILE_OPTION)
+ list (APPEND _compileFlags "${CMAKE_${_language}${_targetLanguageExtensions}_EXTENSION_COMPILE_OPTION}")
+ endif()
+ elseif (_targetLanguageStandard)
+ if (_targetLanguageStandardRequired)
+ if (CMAKE_${_language}${_targetLanguageStandard}_STANDARD_COMPILE_OPTION)
+ list (APPEND _compileFlags "${CMAKE_${_language}${_targetLanguageStandard}_STANDARD_COMPILE_OPTION}")
+ endif()
+ else()
+ if (CMAKE_${_language}${_targetLanguageStandard}_EXTENSION_COMPILE_OPTION)
+ list (APPEND _compileFlags "${CMAKE_${_language}${_targetLanguageStandard}_EXTENSION_COMPILE_OPTION}")
+ endif()
+ endif()
+ endif()
+ endif()
+ # handle the POSITION_INDEPENDENT_CODE target property
+ if (_target)
+ get_target_property(_targetPIC ${_target} POSITION_INDEPENDENT_CODE)
+ if (_targetPIC)
+ get_target_property(_targetType ${_target} TYPE)
+ if (_targetType STREQUAL "EXECUTABLE" AND CMAKE_${_language}_COMPILE_OPTIONS_PIE)
+ list (APPEND _compileFlags "${CMAKE_${_language}_COMPILE_OPTIONS_PIE}")
+ elseif (CMAKE_${_language}_COMPILE_OPTIONS_PIC)
+ list (APPEND _compileFlags "${CMAKE_${_language}_COMPILE_OPTIONS_PIC}")
+ endif()
+ endif()
+ endif()
+ # handle visibility target properties
+ if (_target)
+ get_target_property(_targetVisibility ${_target} ${_language}_VISIBILITY_PRESET)
+ if (_targetVisibility AND CMAKE_${_language}_COMPILE_OPTIONS_VISIBILITY)
+ list (APPEND _compileFlags "${CMAKE_${_language}_COMPILE_OPTIONS_VISIBILITY}${_targetVisibility}")
+ endif()
+ get_target_property(_targetVisibilityInlines ${_target} VISIBILITY_INLINES_HIDDEN)
+ if (_targetVisibilityInlines AND CMAKE_${_language}_COMPILE_OPTIONS_VISIBILITY_INLINES_HIDDEN)
+ list (APPEND _compileFlags "${CMAKE_${_language}_COMPILE_OPTIONS_VISIBILITY_INLINES_HIDDEN}")
+ endif()
+ endif()
+ # platform specific flags
+ if (APPLE)
+ get_target_property(_architectures ${_target} OSX_ARCHITECTURES_${_upperConfig})
+ if (NOT _architectures)
+ get_target_property(_architectures ${_target} OSX_ARCHITECTURES)
+ endif()
+ if (_architectures)
+ foreach (_arch ${_architectures})
+ list (APPEND _compileFlags "-arch" "${_arch}")
+ endforeach()
+ endif()
+ if (CMAKE_OSX_SYSROOT)
+ if (CMAKE_${_language}_SYSROOT_FLAG)
+ list (APPEND _compileFlags "${CMAKE_${_language}_SYSROOT_FLAG}" "${CMAKE_OSX_SYSROOT}")
+ else()
+ list (APPEND _compileFlags "-isysroot" "${CMAKE_OSX_SYSROOT}")
+ endif()
+ endif()
+ if (CMAKE_OSX_DEPLOYMENT_TARGET)
+ if (CMAKE_${_language}_OSX_DEPLOYMENT_TARGET_FLAG)
+ list (APPEND _compileFlags "${CMAKE_${_language}_OSX_DEPLOYMENT_TARGET_FLAG}${CMAKE_OSX_DEPLOYMENT_TARGET}")
+ else()
+ list (APPEND _compileFlags "-mmacosx-version-min=${CMAKE_OSX_DEPLOYMENT_TARGET}")
+ endif()
+ endif()
+ endif()
+ if (COTIRE_DEBUG AND _compileFlags)
+ message (STATUS "Target ${_target} compile flags: ${_compileFlags}")
+ endif()
+ set (${_flagsVar} ${_compileFlags} PARENT_SCOPE)
+endfunction()
+
+function (cotire_get_target_include_directories _config _language _target _includeDirsVar _systemIncludeDirsVar)
+ set (_includeDirs "")
+ set (_systemIncludeDirs "")
+ # default include dirs
+ if (CMAKE_INCLUDE_CURRENT_DIR)
+ list (APPEND _includeDirs "${CMAKE_CURRENT_BINARY_DIR}")
+ list (APPEND _includeDirs "${CMAKE_CURRENT_SOURCE_DIR}")
+ endif()
+ set (_targetFlags "")
+ cotire_get_target_compile_flags("${_config}" "${_language}" "${_target}" _targetFlags)
+ # parse additional include directories from target compile flags
+ if (CMAKE_INCLUDE_FLAG_${_language})
+ string (STRIP "${CMAKE_INCLUDE_FLAG_${_language}}" _includeFlag)
+ string (REGEX REPLACE "^[-/]+" "" _includeFlag "${_includeFlag}")
+ if (_includeFlag)
+ set (_dirs "")
+ cotire_filter_compile_flags("${_language}" "${_includeFlag}" _dirs _ignore ${_targetFlags})
+ if (_dirs)
+ list (APPEND _includeDirs ${_dirs})
+ endif()
+ endif()
+ endif()
+ # parse additional system include directories from target compile flags
+ if (CMAKE_INCLUDE_SYSTEM_FLAG_${_language})
+ string (STRIP "${CMAKE_INCLUDE_SYSTEM_FLAG_${_language}}" _includeFlag)
+ string (REGEX REPLACE "^[-/]+" "" _includeFlag "${_includeFlag}")
+ if (_includeFlag)
+ set (_dirs "")
+ cotire_filter_compile_flags("${_language}" "${_includeFlag}" _dirs _ignore ${_targetFlags})
+ if (_dirs)
+ list (APPEND _systemIncludeDirs ${_dirs})
+ endif()
+ endif()
+ endif()
+ # target include directories
+ get_directory_property(_dirs DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" INCLUDE_DIRECTORIES)
+ if (_target)
+ get_target_property(_targetDirs ${_target} INCLUDE_DIRECTORIES)
+ if (_targetDirs)
+ list (APPEND _dirs ${_targetDirs})
+ endif()
+ get_target_property(_targetDirs ${_target} INTERFACE_SYSTEM_INCLUDE_DIRECTORIES)
+ if (_targetDirs)
+ list (APPEND _systemIncludeDirs ${_targetDirs})
+ endif()
+ endif()
+ # interface include directories from linked library targets
+ if (_target)
+ set (_linkedTargets "")
+ cotire_get_target_usage_requirements(${_target} _linkedTargets)
+ foreach (_linkedTarget ${_linkedTargets})
+ get_target_property(_targetDirs ${_linkedTarget} INTERFACE_INCLUDE_DIRECTORIES)
+ if (_targetDirs)
+ list (APPEND _dirs ${_targetDirs})
+ endif()
+ get_target_property(_targetDirs ${_linkedTarget} INTERFACE_SYSTEM_INCLUDE_DIRECTORIES)
+ if (_targetDirs)
+ list (APPEND _systemIncludeDirs ${_targetDirs})
+ endif()
+ endforeach()
+ endif()
+ if (dirs)
+ list (REMOVE_DUPLICATES _dirs)
+ endif()
+ list (LENGTH _includeDirs _projectInsertIndex)
+ foreach (_dir ${_dirs})
+ if (CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE)
+ cotire_check_is_path_relative_to("${_dir}" _isRelative "${CMAKE_SOURCE_DIR}" "${CMAKE_BINARY_DIR}")
+ if (_isRelative)
+ list (LENGTH _includeDirs _len)
+ if (_len EQUAL _projectInsertIndex)
+ list (APPEND _includeDirs "${_dir}")
+ else()
+ list (INSERT _includeDirs _projectInsertIndex "${_dir}")
+ endif()
+ math (EXPR _projectInsertIndex "${_projectInsertIndex} + 1")
+ else()
+ list (APPEND _includeDirs "${_dir}")
+ endif()
+ else()
+ list (APPEND _includeDirs "${_dir}")
+ endif()
+ endforeach()
+ list (REMOVE_DUPLICATES _includeDirs)
+ list (REMOVE_DUPLICATES _systemIncludeDirs)
+ if (CMAKE_${_language}_IMPLICIT_INCLUDE_DIRECTORIES)
+ list (REMOVE_ITEM _includeDirs ${CMAKE_${_language}_IMPLICIT_INCLUDE_DIRECTORIES})
+ endif()
+ if (COTIRE_DEBUG AND _includeDirs)
+ message (STATUS "Target ${_target} include dirs: ${_includeDirs}")
+ endif()
+ set (${_includeDirsVar} ${_includeDirs} PARENT_SCOPE)
+ if (COTIRE_DEBUG AND _systemIncludeDirs)
+ message (STATUS "Target ${_target} system include dirs: ${_systemIncludeDirs}")
+ endif()
+ set (${_systemIncludeDirsVar} ${_systemIncludeDirs} PARENT_SCOPE)
+endfunction()
+
+function (cotire_get_target_export_symbol _target _exportSymbolVar)
+ set (_exportSymbol "")
+ get_target_property(_targetType ${_target} TYPE)
+ get_target_property(_enableExports ${_target} ENABLE_EXPORTS)
+ if (_targetType MATCHES "(SHARED|MODULE)_LIBRARY" OR
+ (_targetType STREQUAL "EXECUTABLE" AND _enableExports))
+ get_target_property(_exportSymbol ${_target} DEFINE_SYMBOL)
+ if (NOT _exportSymbol)
+ set (_exportSymbol "${_target}_EXPORTS")
+ endif()
+ string (MAKE_C_IDENTIFIER "${_exportSymbol}" _exportSymbol)
+ endif()
+ set (${_exportSymbolVar} ${_exportSymbol} PARENT_SCOPE)
+endfunction()
+
+function (cotire_get_target_compile_definitions _config _language _target _definitionsVar)
+ string (TOUPPER "${_config}" _upperConfig)
+ set (_configDefinitions "")
+ # CMAKE_INTDIR for multi-configuration build systems
+ if (NOT "${CMAKE_CFG_INTDIR}" STREQUAL ".")
+ list (APPEND _configDefinitions "CMAKE_INTDIR=\"${_config}\"")
+ endif()
+ # target export define symbol
+ cotire_get_target_export_symbol("${_target}" _defineSymbol)
+ if (_defineSymbol)
+ list (APPEND _configDefinitions "${_defineSymbol}")
+ endif()
+ # directory compile definitions
+ get_directory_property(_definitions DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" COMPILE_DEFINITIONS)
+ if (_definitions)
+ list (APPEND _configDefinitions ${_definitions})
+ endif()
+ get_directory_property(_definitions DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" COMPILE_DEFINITIONS_${_upperConfig})
+ if (_definitions)
+ list (APPEND _configDefinitions ${_definitions})
+ endif()
+ # target compile definitions
+ get_target_property(_definitions ${_target} COMPILE_DEFINITIONS)
+ if (_definitions)
+ list (APPEND _configDefinitions ${_definitions})
+ endif()
+ get_target_property(_definitions ${_target} COMPILE_DEFINITIONS_${_upperConfig})
+ if (_definitions)
+ list (APPEND _configDefinitions ${_definitions})
+ endif()
+ # interface compile definitions from linked library targets
+ set (_linkedTargets "")
+ cotire_get_target_usage_requirements(${_target} _linkedTargets)
+ foreach (_linkedTarget ${_linkedTargets})
+ get_target_property(_definitions ${_linkedTarget} INTERFACE_COMPILE_DEFINITIONS)
+ if (_definitions)
+ list (APPEND _configDefinitions ${_definitions})
+ endif()
+ endforeach()
+ # parse additional compile definitions from target compile flags
+ # and don't look at directory compile definitions, which we already handled
+ set (_targetFlags "")
+ cotire_get_target_compile_flags("${_config}" "${_language}" "${_target}" _targetFlags)
+ cotire_filter_compile_flags("${_language}" "D" _definitions _ignore ${_targetFlags})
+ if (_definitions)
+ list (APPEND _configDefinitions ${_definitions})
+ endif()
+ list (REMOVE_DUPLICATES _configDefinitions)
+ if (COTIRE_DEBUG AND _configDefinitions)
+ message (STATUS "Target ${_target} compile definitions: ${_configDefinitions}")
+ endif()
+ set (${_definitionsVar} ${_configDefinitions} PARENT_SCOPE)
+endfunction()
+
+function (cotire_get_target_compiler_flags _config _language _target _compilerFlagsVar)
+ # parse target compile flags omitting compile definitions and include directives
+ set (_targetFlags "")
+ cotire_get_target_compile_flags("${_config}" "${_language}" "${_target}" _targetFlags)
+ set (_flagFilter "D")
+ if (CMAKE_INCLUDE_FLAG_${_language})
+ string (STRIP "${CMAKE_INCLUDE_FLAG_${_language}}" _includeFlag)
+ string (REGEX REPLACE "^[-/]+" "" _includeFlag "${_includeFlag}")
+ if (_includeFlag)
+ set (_flagFilter "${_flagFilter}|${_includeFlag}")
+ endif()
+ endif()
+ if (CMAKE_INCLUDE_SYSTEM_FLAG_${_language})
+ string (STRIP "${CMAKE_INCLUDE_SYSTEM_FLAG_${_language}}" _includeFlag)
+ string (REGEX REPLACE "^[-/]+" "" _includeFlag "${_includeFlag}")
+ if (_includeFlag)
+ set (_flagFilter "${_flagFilter}|${_includeFlag}")
+ endif()
+ endif()
+ set (_compilerFlags "")
+ cotire_filter_compile_flags("${_language}" "${_flagFilter}" _ignore _compilerFlags ${_targetFlags})
+ if (COTIRE_DEBUG AND _compilerFlags)
+ message (STATUS "Target ${_target} compiler flags: ${_compilerFlags}")
+ endif()
+ set (${_compilerFlagsVar} ${_compilerFlags} PARENT_SCOPE)
+endfunction()
+
+function (cotire_add_sys_root_paths _pathsVar)
+ if (APPLE)
+ if (CMAKE_OSX_SYSROOT AND CMAKE_${_language}_HAS_ISYSROOT)
+ foreach (_path IN LISTS ${_pathsVar})
+ if (IS_ABSOLUTE "${_path}")
+ get_filename_component(_path "${CMAKE_OSX_SYSROOT}/${_path}" ABSOLUTE)
+ if (EXISTS "${_path}")
+ list (APPEND ${_pathsVar} "${_path}")
+ endif()
+ endif()
+ endforeach()
+ endif()
+ endif()
+ set (${_pathsVar} ${${_pathsVar}} PARENT_SCOPE)
+endfunction()
+
+function (cotire_get_source_extra_properties _sourceFile _pattern _resultVar)
+ set (_extraProperties ${ARGN})
+ set (_result "")
+ if (_extraProperties)
+ list (FIND _extraProperties "${_sourceFile}" _index)
+ if (_index GREATER -1)
+ math (EXPR _index "${_index} + 1")
+ list (LENGTH _extraProperties _len)
+ math (EXPR _len "${_len} - 1")
+ foreach (_index RANGE ${_index} ${_len})
+ list (GET _extraProperties ${_index} _value)
+ if (_value MATCHES "${_pattern}")
+ list (APPEND _result "${_value}")
+ else()
+ break()
+ endif()
+ endforeach()
+ endif()
+ endif()
+ set (${_resultVar} ${_result} PARENT_SCOPE)
+endfunction()
+
+function (cotire_get_source_compile_definitions _config _language _sourceFile _definitionsVar)
+ set (_compileDefinitions "")
+ if (NOT CMAKE_SCRIPT_MODE_FILE)
+ string (TOUPPER "${_config}" _upperConfig)
+ get_source_file_property(_definitions "${_sourceFile}" COMPILE_DEFINITIONS)
+ if (_definitions)
+ list (APPEND _compileDefinitions ${_definitions})
+ endif()
+ get_source_file_property(_definitions "${_sourceFile}" COMPILE_DEFINITIONS_${_upperConfig})
+ if (_definitions)
+ list (APPEND _compileDefinitions ${_definitions})
+ endif()
+ endif()
+ cotire_get_source_extra_properties("${_sourceFile}" "^[a-zA-Z0-9_]+(=.*)?$" _definitions ${ARGN})
+ if (_definitions)
+ list (APPEND _compileDefinitions ${_definitions})
+ endif()
+ if (COTIRE_DEBUG AND _compileDefinitions)
+ message (STATUS "Source ${_sourceFile} compile definitions: ${_compileDefinitions}")
+ endif()
+ set (${_definitionsVar} ${_compileDefinitions} PARENT_SCOPE)
+endfunction()
+
+function (cotire_get_source_files_compile_definitions _config _language _definitionsVar)
+ set (_configDefinitions "")
+ foreach (_sourceFile ${ARGN})
+ cotire_get_source_compile_definitions("${_config}" "${_language}" "${_sourceFile}" _sourceDefinitions)
+ if (_sourceDefinitions)
+ list (APPEND _configDefinitions "${_sourceFile}" ${_sourceDefinitions} "-")
+ endif()
+ endforeach()
+ set (${_definitionsVar} ${_configDefinitions} PARENT_SCOPE)
+endfunction()
+
+function (cotire_get_source_undefs _sourceFile _property _sourceUndefsVar)
+ set (_sourceUndefs "")
+ if (NOT CMAKE_SCRIPT_MODE_FILE)
+ get_source_file_property(_undefs "${_sourceFile}" ${_property})
+ if (_undefs)
+ list (APPEND _sourceUndefs ${_undefs})
+ endif()
+ endif()
+ cotire_get_source_extra_properties("${_sourceFile}" "^[a-zA-Z0-9_]+$" _undefs ${ARGN})
+ if (_undefs)
+ list (APPEND _sourceUndefs ${_undefs})
+ endif()
+ if (COTIRE_DEBUG AND _sourceUndefs)
+ message (STATUS "Source ${_sourceFile} ${_property} undefs: ${_sourceUndefs}")
+ endif()
+ set (${_sourceUndefsVar} ${_sourceUndefs} PARENT_SCOPE)
+endfunction()
+
+function (cotire_get_source_files_undefs _property _sourceUndefsVar)
+ set (_sourceUndefs "")
+ foreach (_sourceFile ${ARGN})
+ cotire_get_source_undefs("${_sourceFile}" ${_property} _undefs)
+ if (_undefs)
+ list (APPEND _sourceUndefs "${_sourceFile}" ${_undefs} "-")
+ endif()
+ endforeach()
+ set (${_sourceUndefsVar} ${_sourceUndefs} PARENT_SCOPE)
+endfunction()
+
+macro (cotire_set_cmd_to_prologue _cmdVar)
+ set (${_cmdVar} "${CMAKE_COMMAND}")
+ if (COTIRE_DEBUG)
+ list (APPEND ${_cmdVar} "--warn-uninitialized")
+ endif()
+ list (APPEND ${_cmdVar} "-DCOTIRE_BUILD_TYPE:STRING=$")
+ if (COTIRE_VERBOSE)
+ list (APPEND ${_cmdVar} "-DCOTIRE_VERBOSE:BOOL=ON")
+ elseif("${CMAKE_GENERATOR}" MATCHES "Makefiles")
+ list (APPEND ${_cmdVar} "-DCOTIRE_VERBOSE:BOOL=$(VERBOSE)")
+ endif()
+endmacro()
+
+function (cotire_init_compile_cmd _cmdVar _language _compilerExe _compilerArg1)
+ if (NOT _compilerExe)
+ set (_compilerExe "${CMAKE_${_language}_COMPILER}")
+ endif()
+ if (NOT _compilerArg1)
+ set (_compilerArg1 ${CMAKE_${_language}_COMPILER_ARG1})
+ endif()
+ string (STRIP "${_compilerArg1}" _compilerArg1)
+ set (${_cmdVar} "${_compilerExe}" ${_compilerArg1} PARENT_SCOPE)
+endfunction()
+
+macro (cotire_add_definitions_to_cmd _cmdVar _language)
+ foreach (_definition ${ARGN})
+ if (WIN32 AND CMAKE_${_language}_COMPILER_ID MATCHES "MSVC|Intel")
+ list (APPEND ${_cmdVar} "/D${_definition}")
+ else()
+ list (APPEND ${_cmdVar} "-D${_definition}")
+ endif()
+ endforeach()
+endmacro()
+
+function (cotire_add_includes_to_cmd _cmdVar _language _includesVar _systemIncludesVar)
+ set (_includeDirs ${${_includesVar}} ${${_systemIncludesVar}})
+ if (_includeDirs)
+ list (REMOVE_DUPLICATES _includeDirs)
+ foreach (_include ${_includeDirs})
+ if (WIN32 AND CMAKE_${_language}_COMPILER_ID MATCHES "MSVC|Intel")
+ file (TO_NATIVE_PATH "${_include}" _include)
+ list (APPEND ${_cmdVar} "${CMAKE_INCLUDE_FLAG_${_language}}${CMAKE_INCLUDE_FLAG_${_language}_SEP}${_include}")
+ else()
+ set (_index -1)
+ if ("${CMAKE_INCLUDE_SYSTEM_FLAG_${_language}}" MATCHES ".+")
+ list (FIND ${_systemIncludesVar} "${_include}" _index)
+ endif()
+ if (_index GREATER -1)
+ list (APPEND ${_cmdVar} "${CMAKE_INCLUDE_SYSTEM_FLAG_${_language}}${_include}")
+ else()
+ list (APPEND ${_cmdVar} "${CMAKE_INCLUDE_FLAG_${_language}}${CMAKE_INCLUDE_FLAG_${_language}_SEP}${_include}")
+ endif()
+ endif()
+ endforeach()
+ endif()
+ set (${_cmdVar} ${${_cmdVar}} PARENT_SCOPE)
+endfunction()
+
+function (cotire_add_frameworks_to_cmd _cmdVar _language _includesVar _systemIncludesVar)
+ if (APPLE)
+ set (_frameworkDirs "")
+ foreach (_include ${${_includesVar}})
+ if (IS_ABSOLUTE "${_include}" AND _include MATCHES "\\.framework$")
+ get_filename_component(_frameworkDir "${_include}" DIRECTORY)
+ list (APPEND _frameworkDirs "${_frameworkDir}")
+ endif()
+ endforeach()
+ set (_systemFrameworkDirs "")
+ foreach (_include ${${_systemIncludesVar}})
+ if (IS_ABSOLUTE "${_include}" AND _include MATCHES "\\.framework$")
+ get_filename_component(_frameworkDir "${_include}" DIRECTORY)
+ list (APPEND _systemFrameworkDirs "${_frameworkDir}")
+ endif()
+ endforeach()
+ if (_systemFrameworkDirs)
+ list (APPEND _frameworkDirs ${_systemFrameworkDirs})
+ endif()
+ if (_frameworkDirs)
+ list (REMOVE_DUPLICATES _frameworkDirs)
+ foreach (_frameworkDir ${_frameworkDirs})
+ set (_index -1)
+ if ("${CMAKE_${_language}_SYSTEM_FRAMEWORK_SEARCH_FLAG}" MATCHES ".+")
+ list (FIND _systemFrameworkDirs "${_frameworkDir}" _index)
+ endif()
+ if (_index GREATER -1)
+ list (APPEND ${_cmdVar} "${CMAKE_${_language}_SYSTEM_FRAMEWORK_SEARCH_FLAG}${_frameworkDir}")
+ else()
+ list (APPEND ${_cmdVar} "${CMAKE_${_language}_FRAMEWORK_SEARCH_FLAG}${_frameworkDir}")
+ endif()
+ endforeach()
+ endif()
+ endif()
+ set (${_cmdVar} ${${_cmdVar}} PARENT_SCOPE)
+endfunction()
+
+macro (cotire_add_compile_flags_to_cmd _cmdVar)
+ foreach (_flag ${ARGN})
+ list (APPEND ${_cmdVar} "${_flag}")
+ endforeach()
+endmacro()
+
+function (cotire_check_file_up_to_date _fileIsUpToDateVar _file)
+ if (EXISTS "${_file}")
+ set (_triggerFile "")
+ foreach (_dependencyFile ${ARGN})
+ if (EXISTS "${_dependencyFile}")
+ # IS_NEWER_THAN returns TRUE if both files have the same timestamp
+ # thus we do the comparison in both directions to exclude ties
+ if ("${_dependencyFile}" IS_NEWER_THAN "${_file}" AND
+ NOT "${_file}" IS_NEWER_THAN "${_dependencyFile}")
+ set (_triggerFile "${_dependencyFile}")
+ break()
+ endif()
+ endif()
+ endforeach()
+ if (_triggerFile)
+ if (COTIRE_VERBOSE)
+ get_filename_component(_fileName "${_file}" NAME)
+ message (STATUS "${_fileName} update triggered by ${_triggerFile} change.")
+ endif()
+ set (${_fileIsUpToDateVar} FALSE PARENT_SCOPE)
+ else()
+ if (COTIRE_VERBOSE)
+ get_filename_component(_fileName "${_file}" NAME)
+ message (STATUS "${_fileName} is up-to-date.")
+ endif()
+ set (${_fileIsUpToDateVar} TRUE PARENT_SCOPE)
+ endif()
+ else()
+ if (COTIRE_VERBOSE)
+ get_filename_component(_fileName "${_file}" NAME)
+ message (STATUS "${_fileName} does not exist yet.")
+ endif()
+ set (${_fileIsUpToDateVar} FALSE PARENT_SCOPE)
+ endif()
+endfunction()
+
+macro (cotire_find_closest_relative_path _headerFile _includeDirs _relPathVar)
+ set (${_relPathVar} "")
+ foreach (_includeDir ${_includeDirs})
+ if (IS_DIRECTORY "${_includeDir}")
+ file (RELATIVE_PATH _relPath "${_includeDir}" "${_headerFile}")
+ if (NOT IS_ABSOLUTE "${_relPath}" AND NOT "${_relPath}" MATCHES "^\\.\\.")
+ string (LENGTH "${${_relPathVar}}" _closestLen)
+ string (LENGTH "${_relPath}" _relLen)
+ if (_closestLen EQUAL 0 OR _relLen LESS _closestLen)
+ set (${_relPathVar} "${_relPath}")
+ endif()
+ endif()
+ elseif ("${_includeDir}" STREQUAL "${_headerFile}")
+ # if path matches exactly, return short non-empty string
+ set (${_relPathVar} "1")
+ break()
+ endif()
+ endforeach()
+endmacro()
+
+macro (cotire_check_header_file_location _headerFile _insideIncludeDirs _outsideIncludeDirs _headerIsInside)
+ # check header path against ignored and honored include directories
+ cotire_find_closest_relative_path("${_headerFile}" "${_insideIncludeDirs}" _insideRelPath)
+ if (_insideRelPath)
+ # header is inside, but could be become outside if there is a shorter outside match
+ cotire_find_closest_relative_path("${_headerFile}" "${_outsideIncludeDirs}" _outsideRelPath)
+ if (_outsideRelPath)
+ string (LENGTH "${_insideRelPath}" _insideRelPathLen)
+ string (LENGTH "${_outsideRelPath}" _outsideRelPathLen)
+ if (_outsideRelPathLen LESS _insideRelPathLen)
+ set (${_headerIsInside} FALSE)
+ else()
+ set (${_headerIsInside} TRUE)
+ endif()
+ else()
+ set (${_headerIsInside} TRUE)
+ endif()
+ else()
+ # header is outside
+ set (${_headerIsInside} FALSE)
+ endif()
+endmacro()
+
+macro (cotire_check_ignore_header_file_path _headerFile _headerIsIgnoredVar)
+ if (NOT EXISTS "${_headerFile}")
+ set (${_headerIsIgnoredVar} TRUE)
+ elseif (IS_DIRECTORY "${_headerFile}")
+ set (${_headerIsIgnoredVar} TRUE)
+ elseif ("${_headerFile}" MATCHES "\\.\\.|[_-]fixed" AND "${_headerFile}" MATCHES "\\.h$")
+ # heuristic: ignore C headers with embedded parent directory references or "-fixed" or "_fixed" in path
+ # these often stem from using GCC #include_next tricks, which may break the precompiled header compilation
+ # with the error message "error: no include path in which to search for header.h"
+ set (${_headerIsIgnoredVar} TRUE)
+ else()
+ set (${_headerIsIgnoredVar} FALSE)
+ endif()
+endmacro()
+
+macro (cotire_check_ignore_header_file_ext _headerFile _ignoreExtensionsVar _headerIsIgnoredVar)
+ # check header file extension
+ cotire_get_source_file_extension("${_headerFile}" _headerFileExt)
+ set (${_headerIsIgnoredVar} FALSE)
+ if (_headerFileExt)
+ list (FIND ${_ignoreExtensionsVar} "${_headerFileExt}" _index)
+ if (_index GREATER -1)
+ set (${_headerIsIgnoredVar} TRUE)
+ endif()
+ endif()
+endmacro()
+
+macro (cotire_parse_line _line _headerFileVar _headerDepthVar)
+ if (MSVC)
+ # cl.exe /showIncludes output looks different depending on the language pack used, e.g.:
+ # English: "Note: including file: C:\directory\file"
+ # German: "Hinweis: Einlesen der Datei: C:\directory\file"
+ # We use a very general regular expression, relying on the presence of the : characters
+ if (_line MATCHES "( +)([a-zA-Z]:[^:]+)$")
+ # Visual Studio compiler output
+ string (LENGTH "${CMAKE_MATCH_1}" ${_headerDepthVar})
+ get_filename_component(${_headerFileVar} "${CMAKE_MATCH_2}" ABSOLUTE)
+ else()
+ set (${_headerFileVar} "")
+ set (${_headerDepthVar} 0)
+ endif()
+ else()
+ if (_line MATCHES "^(\\.+) (.*)$")
+ # GCC like output
+ string (LENGTH "${CMAKE_MATCH_1}" ${_headerDepthVar})
+ if (IS_ABSOLUTE "${CMAKE_MATCH_2}")
+ set (${_headerFileVar} "${CMAKE_MATCH_2}")
+ else()
+ get_filename_component(${_headerFileVar} "${CMAKE_MATCH_2}" REALPATH)
+ endif()
+ else()
+ set (${_headerFileVar} "")
+ set (${_headerDepthVar} 0)
+ endif()
+ endif()
+endmacro()
+
+function (cotire_parse_includes _language _scanOutput _ignoredIncludeDirs _honoredIncludeDirs _ignoredExtensions _selectedIncludesVar _unparsedLinesVar)
+ if (WIN32)
+ # prevent CMake macro invocation errors due to backslash characters in Windows paths
+ string (REPLACE "\\" "/" _scanOutput "${_scanOutput}")
+ endif()
+ # canonize slashes
+ string (REPLACE "//" "/" _scanOutput "${_scanOutput}")
+ # prevent semicolon from being interpreted as a line separator
+ string (REPLACE ";" "\\;" _scanOutput "${_scanOutput}")
+ # then separate lines
+ string (REGEX REPLACE "\n" ";" _scanOutput "${_scanOutput}")
+ list (LENGTH _scanOutput _len)
+ # remove duplicate lines to speed up parsing
+ list (REMOVE_DUPLICATES _scanOutput)
+ list (LENGTH _scanOutput _uniqueLen)
+ if (COTIRE_VERBOSE OR COTIRE_DEBUG)
+ message (STATUS "Scanning ${_uniqueLen} unique lines of ${_len} for includes")
+ if (_ignoredExtensions)
+ message (STATUS "Ignored extensions: ${_ignoredExtensions}")
+ endif()
+ if (_ignoredIncludeDirs)
+ message (STATUS "Ignored paths: ${_ignoredIncludeDirs}")
+ endif()
+ if (_honoredIncludeDirs)
+ message (STATUS "Included paths: ${_honoredIncludeDirs}")
+ endif()
+ endif()
+ set (_sourceFiles ${ARGN})
+ set (_selectedIncludes "")
+ set (_unparsedLines "")
+ # stack keeps track of inside/outside project status of processed header files
+ set (_headerIsInsideStack "")
+ foreach (_line IN LISTS _scanOutput)
+ if (_line)
+ cotire_parse_line("${_line}" _headerFile _headerDepth)
+ if (_headerFile)
+ cotire_check_header_file_location("${_headerFile}" "${_ignoredIncludeDirs}" "${_honoredIncludeDirs}" _headerIsInside)
+ if (COTIRE_DEBUG)
+ message (STATUS "${_headerDepth}: ${_headerFile} ${_headerIsInside}")
+ endif()
+ # update stack
+ list (LENGTH _headerIsInsideStack _stackLen)
+ if (_headerDepth GREATER _stackLen)
+ math (EXPR _stackLen "${_stackLen} + 1")
+ foreach (_index RANGE ${_stackLen} ${_headerDepth})
+ list (APPEND _headerIsInsideStack ${_headerIsInside})
+ endforeach()
+ else()
+ foreach (_index RANGE ${_headerDepth} ${_stackLen})
+ list (REMOVE_AT _headerIsInsideStack -1)
+ endforeach()
+ list (APPEND _headerIsInsideStack ${_headerIsInside})
+ endif()
+ if (COTIRE_DEBUG)
+ message (STATUS "${_headerIsInsideStack}")
+ endif()
+ # header is a candidate if it is outside project
+ if (NOT _headerIsInside)
+ # get parent header file's inside/outside status
+ if (_headerDepth GREATER 1)
+ math (EXPR _index "${_headerDepth} - 2")
+ list (GET _headerIsInsideStack ${_index} _parentHeaderIsInside)
+ else()
+ set (_parentHeaderIsInside TRUE)
+ endif()
+ # select header file if parent header file is inside project
+ # (e.g., a project header file that includes a standard header file)
+ if (_parentHeaderIsInside)
+ cotire_check_ignore_header_file_path("${_headerFile}" _headerIsIgnored)
+ if (NOT _headerIsIgnored)
+ cotire_check_ignore_header_file_ext("${_headerFile}" _ignoredExtensions _headerIsIgnored)
+ if (NOT _headerIsIgnored)
+ list (APPEND _selectedIncludes "${_headerFile}")
+ else()
+ # fix header's inside status on stack, it is ignored by extension now
+ list (REMOVE_AT _headerIsInsideStack -1)
+ list (APPEND _headerIsInsideStack TRUE)
+ endif()
+ endif()
+ if (COTIRE_DEBUG)
+ message (STATUS "${_headerFile} ${_ignoredExtensions} ${_headerIsIgnored}")
+ endif()
+ endif()
+ endif()
+ else()
+ if (MSVC)
+ # for cl.exe do not keep unparsed lines which solely consist of a source file name
+ string (FIND "${_sourceFiles}" "${_line}" _index)
+ if (_index LESS 0)
+ list (APPEND _unparsedLines "${_line}")
+ endif()
+ else()
+ list (APPEND _unparsedLines "${_line}")
+ endif()
+ endif()
+ endif()
+ endforeach()
+ list (REMOVE_DUPLICATES _selectedIncludes)
+ set (${_selectedIncludesVar} ${_selectedIncludes} PARENT_SCOPE)
+ set (${_unparsedLinesVar} ${_unparsedLines} PARENT_SCOPE)
+endfunction()
+
+function (cotire_scan_includes _includesVar)
+ set(_options "")
+ set(_oneValueArgs COMPILER_ID COMPILER_EXECUTABLE COMPILER_VERSION LANGUAGE UNPARSED_LINES)
+ set(_multiValueArgs COMPILE_DEFINITIONS COMPILE_FLAGS INCLUDE_DIRECTORIES SYSTEM_INCLUDE_DIRECTORIES
+ IGNORE_PATH INCLUDE_PATH IGNORE_EXTENSIONS INCLUDE_PRIORITY_PATH)
+ cmake_parse_arguments(_option "${_options}" "${_oneValueArgs}" "${_multiValueArgs}" ${ARGN})
+ set (_sourceFiles ${_option_UNPARSED_ARGUMENTS})
+ if (NOT _option_LANGUAGE)
+ set (_option_LANGUAGE "CXX")
+ endif()
+ if (NOT _option_COMPILER_ID)
+ set (_option_COMPILER_ID "${CMAKE_${_option_LANGUAGE}_ID}")
+ endif()
+ if (NOT _option_COMPILER_VERSION)
+ set (_option_COMPILER_VERSION "${CMAKE_${_option_LANGUAGE}_COMPILER_VERSION}")
+ endif()
+ cotire_init_compile_cmd(_cmd "${_option_LANGUAGE}" "${_option_COMPILER_EXECUTABLE}" "${_option_COMPILER_ARG1}")
+ cotire_add_definitions_to_cmd(_cmd "${_option_LANGUAGE}" ${_option_COMPILE_DEFINITIONS})
+ cotire_add_compile_flags_to_cmd(_cmd ${_option_COMPILE_FLAGS})
+ cotire_add_includes_to_cmd(_cmd "${_option_LANGUAGE}" _option_INCLUDE_DIRECTORIES _option_SYSTEM_INCLUDE_DIRECTORIES)
+ cotire_add_frameworks_to_cmd(_cmd "${_option_LANGUAGE}" _option_INCLUDE_DIRECTORIES _option_SYSTEM_INCLUDE_DIRECTORIES)
+ cotire_add_makedep_flags("${_option_LANGUAGE}" "${_option_COMPILER_ID}" "${_option_COMPILER_VERSION}" _cmd)
+ # only consider existing source files for scanning
+ set (_existingSourceFiles "")
+ foreach (_sourceFile ${_sourceFiles})
+ if (EXISTS "${_sourceFile}")
+ list (APPEND _existingSourceFiles "${_sourceFile}")
+ endif()
+ endforeach()
+ if (NOT _existingSourceFiles)
+ set (${_includesVar} "" PARENT_SCOPE)
+ return()
+ endif()
+ list (APPEND _cmd ${_existingSourceFiles})
+ if (COTIRE_VERBOSE)
+ message (STATUS "execute_process: ${_cmd}")
+ endif()
+ if (_option_COMPILER_ID MATCHES "MSVC")
+ # cl.exe messes with the output streams unless the environment variable VS_UNICODE_OUTPUT is cleared
+ unset (ENV{VS_UNICODE_OUTPUT})
+ endif()
+ execute_process(
+ COMMAND ${_cmd}
+ WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
+ RESULT_VARIABLE _result
+ OUTPUT_QUIET
+ ERROR_VARIABLE _output)
+ if (_result)
+ message (STATUS "Result ${_result} scanning includes of ${_existingSourceFiles}.")
+ endif()
+ cotire_parse_includes(
+ "${_option_LANGUAGE}" "${_output}"
+ "${_option_IGNORE_PATH}" "${_option_INCLUDE_PATH}"
+ "${_option_IGNORE_EXTENSIONS}"
+ _includes _unparsedLines
+ ${_sourceFiles})
+ if (_option_INCLUDE_PRIORITY_PATH)
+ set (_sortedIncludes "")
+ foreach (_priorityPath ${_option_INCLUDE_PRIORITY_PATH})
+ foreach (_include ${_includes})
+ string (FIND ${_include} ${_priorityPath} _position)
+ if (_position GREATER -1)
+ list (APPEND _sortedIncludes ${_include})
+ endif()
+ endforeach()
+ endforeach()
+ if (_sortedIncludes)
+ list (INSERT _includes 0 ${_sortedIncludes})
+ list (REMOVE_DUPLICATES _includes)
+ endif()
+ endif()
+ set (${_includesVar} ${_includes} PARENT_SCOPE)
+ if (_option_UNPARSED_LINES)
+ set (${_option_UNPARSED_LINES} ${_unparsedLines} PARENT_SCOPE)
+ endif()
+endfunction()
+
+macro (cotire_append_undefs _contentsVar)
+ set (_undefs ${ARGN})
+ if (_undefs)
+ list (REMOVE_DUPLICATES _undefs)
+ foreach (_definition ${_undefs})
+ list (APPEND ${_contentsVar} "#undef ${_definition}")
+ endforeach()
+ endif()
+endmacro()
+
+macro (cotire_comment_str _language _commentText _commentVar)
+ if ("${_language}" STREQUAL "CMAKE")
+ set (${_commentVar} "# ${_commentText}")
+ else()
+ set (${_commentVar} "/* ${_commentText} */")
+ endif()
+endmacro()
+
+function (cotire_write_file _language _file _contents _force)
+ get_filename_component(_moduleName "${COTIRE_CMAKE_MODULE_FILE}" NAME)
+ cotire_comment_str("${_language}" "${_moduleName} ${COTIRE_CMAKE_MODULE_VERSION} generated file" _header1)
+ cotire_comment_str("${_language}" "${_file}" _header2)
+ set (_contents "${_header1}\n${_header2}\n${_contents}")
+ if (COTIRE_DEBUG)
+ message (STATUS "${_contents}")
+ endif()
+ if (_force OR NOT EXISTS "${_file}")
+ file (WRITE "${_file}" "${_contents}")
+ else()
+ file (READ "${_file}" _oldContents)
+ if (NOT "${_oldContents}" STREQUAL "${_contents}")
+ file (WRITE "${_file}" "${_contents}")
+ else()
+ if (COTIRE_DEBUG)
+ message (STATUS "${_file} unchanged")
+ endif()
+ endif()
+ endif()
+endfunction()
+
+function (cotire_generate_unity_source _unityFile)
+ set(_options "")
+ set(_oneValueArgs LANGUAGE)
+ set(_multiValueArgs
+ DEPENDS SOURCES_COMPILE_DEFINITIONS
+ PRE_UNDEFS SOURCES_PRE_UNDEFS POST_UNDEFS SOURCES_POST_UNDEFS PROLOGUE EPILOGUE)
+ cmake_parse_arguments(_option "${_options}" "${_oneValueArgs}" "${_multiValueArgs}" ${ARGN})
+ if (_option_DEPENDS)
+ cotire_check_file_up_to_date(_unityFileIsUpToDate "${_unityFile}" ${_option_DEPENDS})
+ if (_unityFileIsUpToDate)
+ return()
+ endif()
+ endif()
+ set (_sourceFiles ${_option_UNPARSED_ARGUMENTS})
+ if (NOT _option_PRE_UNDEFS)
+ set (_option_PRE_UNDEFS "")
+ endif()
+ if (NOT _option_SOURCES_PRE_UNDEFS)
+ set (_option_SOURCES_PRE_UNDEFS "")
+ endif()
+ if (NOT _option_POST_UNDEFS)
+ set (_option_POST_UNDEFS "")
+ endif()
+ if (NOT _option_SOURCES_POST_UNDEFS)
+ set (_option_SOURCES_POST_UNDEFS "")
+ endif()
+ set (_contents "")
+ if (_option_PROLOGUE)
+ list (APPEND _contents ${_option_PROLOGUE})
+ endif()
+ if (_option_LANGUAGE AND _sourceFiles)
+ if ("${_option_LANGUAGE}" STREQUAL "CXX")
+ list (APPEND _contents "#ifdef __cplusplus")
+ elseif ("${_option_LANGUAGE}" STREQUAL "C")
+ list (APPEND _contents "#ifndef __cplusplus")
+ endif()
+ endif()
+ set (_compileUndefinitions "")
+ foreach (_sourceFile ${_sourceFiles})
+ cotire_get_source_compile_definitions(
+ "${_option_CONFIGURATION}" "${_option_LANGUAGE}" "${_sourceFile}" _compileDefinitions
+ ${_option_SOURCES_COMPILE_DEFINITIONS})
+ cotire_get_source_undefs("${_sourceFile}" COTIRE_UNITY_SOURCE_PRE_UNDEFS _sourcePreUndefs ${_option_SOURCES_PRE_UNDEFS})
+ cotire_get_source_undefs("${_sourceFile}" COTIRE_UNITY_SOURCE_POST_UNDEFS _sourcePostUndefs ${_option_SOURCES_POST_UNDEFS})
+ if (_option_PRE_UNDEFS)
+ list (APPEND _compileUndefinitions ${_option_PRE_UNDEFS})
+ endif()
+ if (_sourcePreUndefs)
+ list (APPEND _compileUndefinitions ${_sourcePreUndefs})
+ endif()
+ if (_compileUndefinitions)
+ cotire_append_undefs(_contents ${_compileUndefinitions})
+ set (_compileUndefinitions "")
+ endif()
+ if (_sourcePostUndefs)
+ list (APPEND _compileUndefinitions ${_sourcePostUndefs})
+ endif()
+ if (_option_POST_UNDEFS)
+ list (APPEND _compileUndefinitions ${_option_POST_UNDEFS})
+ endif()
+ foreach (_definition ${_compileDefinitions})
+ if (_definition MATCHES "^([a-zA-Z0-9_]+)=(.+)$")
+ list (APPEND _contents "#define ${CMAKE_MATCH_1} ${CMAKE_MATCH_2}")
+ list (INSERT _compileUndefinitions 0 "${CMAKE_MATCH_1}")
+ else()
+ list (APPEND _contents "#define ${_definition}")
+ list (INSERT _compileUndefinitions 0 "${_definition}")
+ endif()
+ endforeach()
+ # use absolute path as source file location
+ get_filename_component(_sourceFileLocation "${_sourceFile}" ABSOLUTE)
+ if (WIN32)
+ file (TO_NATIVE_PATH "${_sourceFileLocation}" _sourceFileLocation)
+ endif()
+ list (APPEND _contents "#include \"${_sourceFileLocation}\"")
+ endforeach()
+ if (_compileUndefinitions)
+ cotire_append_undefs(_contents ${_compileUndefinitions})
+ set (_compileUndefinitions "")
+ endif()
+ if (_option_LANGUAGE AND _sourceFiles)
+ list (APPEND _contents "#endif")
+ endif()
+ if (_option_EPILOGUE)
+ list (APPEND _contents ${_option_EPILOGUE})
+ endif()
+ list (APPEND _contents "")
+ string (REPLACE ";" "\n" _contents "${_contents}")
+ if (COTIRE_VERBOSE)
+ message ("${_contents}")
+ endif()
+ cotire_write_file("${_option_LANGUAGE}" "${_unityFile}" "${_contents}" TRUE)
+endfunction()
+
+function (cotire_generate_prefix_header _prefixFile)
+ set(_options "")
+ set(_oneValueArgs LANGUAGE COMPILER_EXECUTABLE COMPILER_ID COMPILER_VERSION)
+ set(_multiValueArgs DEPENDS COMPILE_DEFINITIONS COMPILE_FLAGS
+ INCLUDE_DIRECTORIES SYSTEM_INCLUDE_DIRECTORIES IGNORE_PATH INCLUDE_PATH
+ IGNORE_EXTENSIONS INCLUDE_PRIORITY_PATH)
+ cmake_parse_arguments(_option "${_options}" "${_oneValueArgs}" "${_multiValueArgs}" ${ARGN})
+ if (NOT _option_COMPILER_ID)
+ set (_option_COMPILER_ID "${CMAKE_${_option_LANGUAGE}_ID}")
+ endif()
+ if (NOT _option_COMPILER_VERSION)
+ set (_option_COMPILER_VERSION "${CMAKE_${_option_LANGUAGE}_COMPILER_VERSION}")
+ endif()
+ if (_option_DEPENDS)
+ cotire_check_file_up_to_date(_prefixFileIsUpToDate "${_prefixFile}" ${_option_DEPENDS})
+ if (_prefixFileIsUpToDate)
+ # create empty log file
+ set (_unparsedLinesFile "${_prefixFile}.log")
+ file (WRITE "${_unparsedLinesFile}" "")
+ return()
+ endif()
+ endif()
+ set (_prologue "")
+ set (_epilogue "")
+ if (_option_COMPILER_ID MATCHES "Clang")
+ set (_prologue "#pragma clang system_header")
+ elseif (_option_COMPILER_ID MATCHES "GNU")
+ set (_prologue "#pragma GCC system_header")
+ elseif (_option_COMPILER_ID MATCHES "MSVC")
+ set (_prologue "#pragma warning(push, 0)")
+ set (_epilogue "#pragma warning(pop)")
+ elseif (_option_COMPILER_ID MATCHES "Intel")
+ # Intel compiler requires hdrstop pragma to stop generating PCH file
+ set (_epilogue "#pragma hdrstop")
+ endif()
+ set (_sourceFiles ${_option_UNPARSED_ARGUMENTS})
+ cotire_scan_includes(_selectedHeaders ${_sourceFiles}
+ LANGUAGE "${_option_LANGUAGE}"
+ COMPILER_EXECUTABLE "${_option_COMPILER_EXECUTABLE}"
+ COMPILER_ID "${_option_COMPILER_ID}"
+ COMPILER_VERSION "${_option_COMPILER_VERSION}"
+ COMPILE_DEFINITIONS ${_option_COMPILE_DEFINITIONS}
+ COMPILE_FLAGS ${_option_COMPILE_FLAGS}
+ INCLUDE_DIRECTORIES ${_option_INCLUDE_DIRECTORIES}
+ SYSTEM_INCLUDE_DIRECTORIES ${_option_SYSTEM_INCLUDE_DIRECTORIES}
+ IGNORE_PATH ${_option_IGNORE_PATH}
+ INCLUDE_PATH ${_option_INCLUDE_PATH}
+ IGNORE_EXTENSIONS ${_option_IGNORE_EXTENSIONS}
+ INCLUDE_PRIORITY_PATH ${_option_INCLUDE_PRIORITY_PATH}
+ UNPARSED_LINES _unparsedLines)
+ cotire_generate_unity_source("${_prefixFile}"
+ PROLOGUE ${_prologue} EPILOGUE ${_epilogue} LANGUAGE "${_option_LANGUAGE}" ${_selectedHeaders})
+ set (_unparsedLinesFile "${_prefixFile}.log")
+ if (_unparsedLines)
+ if (COTIRE_VERBOSE OR NOT _selectedHeaders)
+ list (LENGTH _unparsedLines _skippedLineCount)
+ message (STATUS "${_skippedLineCount} line(s) skipped, see ${_unparsedLinesFile}")
+ endif()
+ string (REPLACE ";" "\n" _unparsedLines "${_unparsedLines}")
+ endif()
+ file (WRITE "${_unparsedLinesFile}" "${_unparsedLines}")
+endfunction()
+
+function (cotire_add_makedep_flags _language _compilerID _compilerVersion _flagsVar)
+ set (_flags ${${_flagsVar}})
+ if (_compilerID MATCHES "MSVC")
+ # cl.exe options used
+ # /nologo suppresses display of sign-on banner
+ # /TC treat all files named on the command line as C source files
+ # /TP treat all files named on the command line as C++ source files
+ # /EP preprocess to stdout without #line directives
+ # /showIncludes list include files
+ set (_sourceFileTypeC "/TC")
+ set (_sourceFileTypeCXX "/TP")
+ if (_flags)
+ # append to list
+ list (APPEND _flags /nologo "${_sourceFileType${_language}}" /EP /showIncludes)
+ else()
+ # return as a flag string
+ set (_flags "${_sourceFileType${_language}} /EP /showIncludes")
+ endif()
+ elseif (_compilerID MATCHES "GNU")
+ # GCC options used
+ # -H print the name of each header file used
+ # -E invoke preprocessor
+ # -fdirectives-only do not expand macros, requires GCC >= 4.3
+ if (_flags)
+ # append to list
+ list (APPEND _flags -H -E)
+ if (NOT "${_compilerVersion}" VERSION_LESS "4.3.0")
+ list (APPEND _flags "-fdirectives-only")
+ endif()
+ else()
+ # return as a flag string
+ set (_flags "-H -E")
+ if (NOT "${_compilerVersion}" VERSION_LESS "4.3.0")
+ set (_flags "${_flags} -fdirectives-only")
+ endif()
+ endif()
+ elseif (_compilerID MATCHES "Clang")
+ # Clang options used
+ # -H print the name of each header file used
+ # -E invoke preprocessor
+ # -fno-color-diagnostics don't prints diagnostics in color
+ if (_flags)
+ # append to list
+ list (APPEND _flags -H -E -fno-color-diagnostics)
+ else()
+ # return as a flag string
+ set (_flags "-H -E -fno-color-diagnostics")
+ endif()
+ elseif (_compilerID MATCHES "Intel")
+ if (WIN32)
+ # Windows Intel options used
+ # /nologo do not display compiler version information
+ # /QH display the include file order
+ # /EP preprocess to stdout, omitting #line directives
+ # /TC process all source or unrecognized file types as C source files
+ # /TP process all source or unrecognized file types as C++ source files
+ set (_sourceFileTypeC "/TC")
+ set (_sourceFileTypeCXX "/TP")
+ if (_flags)
+ # append to list
+ list (APPEND _flags /nologo "${_sourceFileType${_language}}" /EP /QH)
+ else()
+ # return as a flag string
+ set (_flags "${_sourceFileType${_language}} /EP /QH")
+ endif()
+ else()
+ # Linux / Mac OS X Intel options used
+ # -H print the name of each header file used
+ # -EP preprocess to stdout, omitting #line directives
+ # -Kc++ process all source or unrecognized file types as C++ source files
+ if (_flags)
+ # append to list
+ if ("${_language}" STREQUAL "CXX")
+ list (APPEND _flags -Kc++)
+ endif()
+ list (APPEND _flags -H -EP)
+ else()
+ # return as a flag string
+ if ("${_language}" STREQUAL "CXX")
+ set (_flags "-Kc++ ")
+ endif()
+ set (_flags "${_flags}-H -EP")
+ endif()
+ endif()
+ else()
+ message (FATAL_ERROR "cotire: unsupported ${_language} compiler ${_compilerID} version ${_compilerVersion}.")
+ endif()
+ set (${_flagsVar} ${_flags} PARENT_SCOPE)
+endfunction()
+
+function (cotire_add_pch_compilation_flags _language _compilerID _compilerVersion _prefixFile _pchFile _hostFile _flagsVar)
+ set (_flags ${${_flagsVar}})
+ if (_compilerID MATCHES "MSVC")
+ file (TO_NATIVE_PATH "${_prefixFile}" _prefixFileNative)
+ file (TO_NATIVE_PATH "${_pchFile}" _pchFileNative)
+ file (TO_NATIVE_PATH "${_hostFile}" _hostFileNative)
+ # cl.exe options used
+ # /Yc creates a precompiled header file
+ # /Fp specifies precompiled header binary file name
+ # /FI forces inclusion of file
+ # /TC treat all files named on the command line as C source files
+ # /TP treat all files named on the command line as C++ source files
+ # /Zs syntax check only
+ # /Zm precompiled header memory allocation scaling factor
+ set (_sourceFileTypeC "/TC")
+ set (_sourceFileTypeCXX "/TP")
+ if (_flags)
+ # append to list
+ list (APPEND _flags /nologo "${_sourceFileType${_language}}"
+ "/Yc${_prefixFileNative}" "/Fp${_pchFileNative}" "/FI${_prefixFileNative}" /Zs "${_hostFileNative}")
+ if (COTIRE_PCH_MEMORY_SCALING_FACTOR)
+ list (APPEND _flags "/Zm${COTIRE_PCH_MEMORY_SCALING_FACTOR}")
+ endif()
+ else()
+ # return as a flag string
+ set (_flags "/Yc\"${_prefixFileNative}\" /Fp\"${_pchFileNative}\" /FI\"${_prefixFileNative}\"")
+ if (COTIRE_PCH_MEMORY_SCALING_FACTOR)
+ set (_flags "${_flags} /Zm${COTIRE_PCH_MEMORY_SCALING_FACTOR}")
+ endif()
+ endif()
+ elseif (_compilerID MATCHES "GNU|Clang")
+ # GCC / Clang options used
+ # -x specify the source language
+ # -c compile but do not link
+ # -o place output in file
+ # note that we cannot use -w to suppress all warnings upon pre-compiling, because turning off a warning may
+ # alter compile flags as a side effect (e.g., -Wwrite-string implies -fconst-strings)
+ set (_xLanguage_C "c-header")
+ set (_xLanguage_CXX "c++-header")
+ if (_flags)
+ # append to list
+ list (APPEND _flags "-x" "${_xLanguage_${_language}}" "-c" "${_prefixFile}" -o "${_pchFile}")
+ else()
+ # return as a flag string
+ set (_flags "-x ${_xLanguage_${_language}} -c \"${_prefixFile}\" -o \"${_pchFile}\"")
+ endif()
+ elseif (_compilerID MATCHES "Intel")
+ if (WIN32)
+ file (TO_NATIVE_PATH "${_prefixFile}" _prefixFileNative)
+ file (TO_NATIVE_PATH "${_pchFile}" _pchFileNative)
+ file (TO_NATIVE_PATH "${_hostFile}" _hostFileNative)
+ # Windows Intel options used
+ # /nologo do not display compiler version information
+ # /Yc create a precompiled header (PCH) file
+ # /Fp specify a path or file name for precompiled header files
+ # /FI tells the preprocessor to include a specified file name as the header file
+ # /TC process all source or unrecognized file types as C source files
+ # /TP process all source or unrecognized file types as C++ source files
+ # /Zs syntax check only
+ # /Wpch-messages enable diagnostics related to pre-compiled headers (requires Intel XE 2013 Update 2)
+ set (_sourceFileTypeC "/TC")
+ set (_sourceFileTypeCXX "/TP")
+ if (_flags)
+ # append to list
+ list (APPEND _flags /nologo "${_sourceFileType${_language}}"
+ "/Yc" "/Fp${_pchFileNative}" "/FI${_prefixFileNative}" /Zs "${_hostFileNative}")
+ if (NOT "${_compilerVersion}" VERSION_LESS "13.1.0")
+ list (APPEND _flags "/Wpch-messages")
+ endif()
+ else()
+ # return as a flag string
+ set (_flags "/Yc /Fp\"${_pchFileNative}\" /FI\"${_prefixFileNative}\"")
+ if (NOT "${_compilerVersion}" VERSION_LESS "13.1.0")
+ set (_flags "${_flags} /Wpch-messages")
+ endif()
+ endif()
+ else()
+ # Linux / Mac OS X Intel options used
+ # -pch-dir location for precompiled header files
+ # -pch-create name of the precompiled header (PCH) to create
+ # -Kc++ process all source or unrecognized file types as C++ source files
+ # -fsyntax-only check only for correct syntax
+ # -Wpch-messages enable diagnostics related to pre-compiled headers (requires Intel XE 2013 Update 2)
+ get_filename_component(_pchDir "${_pchFile}" DIRECTORY)
+ get_filename_component(_pchName "${_pchFile}" NAME)
+ set (_xLanguage_C "c-header")
+ set (_xLanguage_CXX "c++-header")
+ if (_flags)
+ # append to list
+ if ("${_language}" STREQUAL "CXX")
+ list (APPEND _flags -Kc++)
+ endif()
+ list (APPEND _flags "-include" "${_prefixFile}" "-pch-dir" "${_pchDir}" "-pch-create" "${_pchName}" "-fsyntax-only" "${_hostFile}")
+ if (NOT "${_compilerVersion}" VERSION_LESS "13.1.0")
+ list (APPEND _flags "-Wpch-messages")
+ endif()
+ else()
+ # return as a flag string
+ set (_flags "-include \"${_prefixFile}\" -pch-dir \"${_pchDir}\" -pch-create \"${_pchName}\"")
+ if (NOT "${_compilerVersion}" VERSION_LESS "13.1.0")
+ set (_flags "${_flags} -Wpch-messages")
+ endif()
+ endif()
+ endif()
+ else()
+ message (FATAL_ERROR "cotire: unsupported ${_language} compiler ${_compilerID} version ${_compilerVersion}.")
+ endif()
+ set (${_flagsVar} ${_flags} PARENT_SCOPE)
+endfunction()
+
+function (cotire_add_prefix_pch_inclusion_flags _language _compilerID _compilerVersion _prefixFile _pchFile _flagsVar)
+ set (_flags ${${_flagsVar}})
+ if (_compilerID MATCHES "MSVC")
+ file (TO_NATIVE_PATH "${_prefixFile}" _prefixFileNative)
+ # cl.exe options used
+ # /Yu uses a precompiled header file during build
+ # /Fp specifies precompiled header binary file name
+ # /FI forces inclusion of file
+ # /Zm precompiled header memory allocation scaling factor
+ if (_pchFile)
+ file (TO_NATIVE_PATH "${_pchFile}" _pchFileNative)
+ if (_flags)
+ # append to list
+ list (APPEND _flags "/Yu${_prefixFileNative}" "/Fp${_pchFileNative}" "/FI${_prefixFileNative}")
+ if (COTIRE_PCH_MEMORY_SCALING_FACTOR)
+ list (APPEND _flags "/Zm${COTIRE_PCH_MEMORY_SCALING_FACTOR}")
+ endif()
+ else()
+ # return as a flag string
+ set (_flags "/Yu\"${_prefixFileNative}\" /Fp\"${_pchFileNative}\" /FI\"${_prefixFileNative}\"")
+ if (COTIRE_PCH_MEMORY_SCALING_FACTOR)
+ set (_flags "${_flags} /Zm${COTIRE_PCH_MEMORY_SCALING_FACTOR}")
+ endif()
+ endif()
+ else()
+ # no precompiled header, force inclusion of prefix header
+ if (_flags)
+ # append to list
+ list (APPEND _flags "/FI${_prefixFileNative}")
+ else()
+ # return as a flag string
+ set (_flags "/FI\"${_prefixFileNative}\"")
+ endif()
+ endif()
+ elseif (_compilerID MATCHES "GNU")
+ # GCC options used
+ # -include process include file as the first line of the primary source file
+ # -Winvalid-pch warns if precompiled header is found but cannot be used
+ # note: ccache requires the -include flag to be used in order to process precompiled header correctly
+ if (_flags)
+ # append to list
+ list (APPEND _flags "-Winvalid-pch" "-include" "${_prefixFile}")
+ else()
+ # return as a flag string
+ set (_flags "-Winvalid-pch -include \"${_prefixFile}\"")
+ endif()
+ elseif (_compilerID MATCHES "Clang")
+ # Clang options used
+ # -include process include file as the first line of the primary source file
+ # -include-pch include precompiled header file
+ # -Qunused-arguments don't emit warning for unused driver arguments
+ # note: ccache requires the -include flag to be used in order to process precompiled header correctly
+ if (_flags)
+ # append to list
+ list (APPEND _flags "-Qunused-arguments" "-include" "${_prefixFile}")
+ else()
+ # return as a flag string
+ set (_flags "-Qunused-arguments -include \"${_prefixFile}\"")
+ endif()
+ elseif (_compilerID MATCHES "Intel")
+ if (WIN32)
+ file (TO_NATIVE_PATH "${_prefixFile}" _prefixFileNative)
+ # Windows Intel options used
+ # /Yu use a precompiled header (PCH) file
+ # /Fp specify a path or file name for precompiled header files
+ # /FI tells the preprocessor to include a specified file name as the header file
+ # /Wpch-messages enable diagnostics related to pre-compiled headers (requires Intel XE 2013 Update 2)
+ if (_pchFile)
+ file (TO_NATIVE_PATH "${_pchFile}" _pchFileNative)
+ if (_flags)
+ # append to list
+ list (APPEND _flags "/Yu" "/Fp${_pchFileNative}" "/FI${_prefixFileNative}")
+ if (NOT "${_compilerVersion}" VERSION_LESS "13.1.0")
+ list (APPEND _flags "/Wpch-messages")
+ endif()
+ else()
+ # return as a flag string
+ set (_flags "/Yu /Fp\"${_pchFileNative}\" /FI\"${_prefixFileNative}\"")
+ if (NOT "${_compilerVersion}" VERSION_LESS "13.1.0")
+ set (_flags "${_flags} /Wpch-messages")
+ endif()
+ endif()
+ else()
+ # no precompiled header, force inclusion of prefix header
+ if (_flags)
+ # append to list
+ list (APPEND _flags "/FI${_prefixFileNative}")
+ else()
+ # return as a flag string
+ set (_flags "/FI\"${_prefixFileNative}\"")
+ endif()
+ endif()
+ else()
+ # Linux / Mac OS X Intel options used
+ # -pch-dir location for precompiled header files
+ # -pch-use name of the precompiled header (PCH) to use
+ # -include process include file as the first line of the primary source file
+ # -Wpch-messages enable diagnostics related to pre-compiled headers (requires Intel XE 2013 Update 2)
+ if (_pchFile)
+ get_filename_component(_pchDir "${_pchFile}" DIRECTORY)
+ get_filename_component(_pchName "${_pchFile}" NAME)
+ if (_flags)
+ # append to list
+ list (APPEND _flags "-include" "${_prefixFile}" "-pch-dir" "${_pchDir}" "-pch-use" "${_pchName}")
+ if (NOT "${_compilerVersion}" VERSION_LESS "13.1.0")
+ list (APPEND _flags "-Wpch-messages")
+ endif()
+ else()
+ # return as a flag string
+ set (_flags "-include \"${_prefixFile}\" -pch-dir \"${_pchDir}\" -pch-use \"${_pchName}\"")
+ if (NOT "${_compilerVersion}" VERSION_LESS "13.1.0")
+ set (_flags "${_flags} -Wpch-messages")
+ endif()
+ endif()
+ else()
+ # no precompiled header, force inclusion of prefix header
+ if (_flags)
+ # append to list
+ list (APPEND _flags "-include" "${_prefixFile}")
+ else()
+ # return as a flag string
+ set (_flags "-include \"${_prefixFile}\"")
+ endif()
+ endif()
+ endif()
+ else()
+ message (FATAL_ERROR "cotire: unsupported ${_language} compiler ${_compilerID} version ${_compilerVersion}.")
+ endif()
+ set (${_flagsVar} ${_flags} PARENT_SCOPE)
+endfunction()
+
+function (cotire_precompile_prefix_header _prefixFile _pchFile _hostFile)
+ set(_options "")
+ set(_oneValueArgs COMPILER_EXECUTABLE COMPILER_ID COMPILER_VERSION LANGUAGE)
+ set(_multiValueArgs COMPILE_DEFINITIONS COMPILE_FLAGS INCLUDE_DIRECTORIES SYSTEM_INCLUDE_DIRECTORIES SYS)
+ cmake_parse_arguments(_option "${_options}" "${_oneValueArgs}" "${_multiValueArgs}" ${ARGN})
+ if (NOT _option_LANGUAGE)
+ set (_option_LANGUAGE "CXX")
+ endif()
+ if (NOT _option_COMPILER_ID)
+ set (_option_COMPILER_ID "${CMAKE_${_option_LANGUAGE}_ID}")
+ endif()
+ if (NOT _option_COMPILER_VERSION)
+ set (_option_COMPILER_VERSION "${CMAKE_${_option_LANGUAGE}_COMPILER_VERSION}")
+ endif()
+ cotire_init_compile_cmd(_cmd "${_option_LANGUAGE}" "${_option_COMPILER_EXECUTABLE}" "${_option_COMPILER_ARG1}")
+ cotire_add_definitions_to_cmd(_cmd "${_option_LANGUAGE}" ${_option_COMPILE_DEFINITIONS})
+ cotire_add_compile_flags_to_cmd(_cmd ${_option_COMPILE_FLAGS})
+ cotire_add_includes_to_cmd(_cmd "${_option_LANGUAGE}" _option_INCLUDE_DIRECTORIES _option_SYSTEM_INCLUDE_DIRECTORIES)
+ cotire_add_frameworks_to_cmd(_cmd "${_option_LANGUAGE}" _option_INCLUDE_DIRECTORIES _option_SYSTEM_INCLUDE_DIRECTORIES)
+ cotire_add_pch_compilation_flags(
+ "${_option_LANGUAGE}" "${_option_COMPILER_ID}" "${_option_COMPILER_VERSION}"
+ "${_prefixFile}" "${_pchFile}" "${_hostFile}" _cmd)
+ if (COTIRE_VERBOSE)
+ message (STATUS "execute_process: ${_cmd}")
+ endif()
+ if (_option_COMPILER_ID MATCHES "MSVC")
+ # cl.exe messes with the output streams unless the environment variable VS_UNICODE_OUTPUT is cleared
+ unset (ENV{VS_UNICODE_OUTPUT})
+ endif()
+ execute_process(
+ COMMAND ${_cmd}
+ WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
+ RESULT_VARIABLE _result)
+ if (_result)
+ message (FATAL_ERROR "cotire: error ${_result} precompiling ${_prefixFile}.")
+ endif()
+endfunction()
+
+function (cotire_check_precompiled_header_support _language _target _msgVar)
+ set (_unsupportedCompiler
+ "Precompiled headers not supported for ${_language} compiler ${CMAKE_${_language}_COMPILER_ID}")
+ if (CMAKE_${_language}_COMPILER_ID MATCHES "MSVC")
+ # supported since Visual Studio C++ 6.0
+ # and CMake does not support an earlier version
+ set (${_msgVar} "" PARENT_SCOPE)
+ elseif (CMAKE_${_language}_COMPILER_ID MATCHES "GNU")
+ # GCC PCH support requires version >= 3.4
+ if ("${CMAKE_${_language}_COMPILER_VERSION}" VERSION_LESS "3.4.0")
+ set (${_msgVar} "${_unsupportedCompiler} version ${CMAKE_${_language}_COMPILER_VERSION}." PARENT_SCOPE)
+ else()
+ set (${_msgVar} "" PARENT_SCOPE)
+ endif()
+ elseif (CMAKE_${_language}_COMPILER_ID MATCHES "Clang")
+ # all Clang versions have PCH support
+ set (${_msgVar} "" PARENT_SCOPE)
+ elseif (CMAKE_${_language}_COMPILER_ID MATCHES "Intel")
+ # Intel PCH support requires version >= 8.0.0
+ if ("${CMAKE_${_language}_COMPILER_VERSION}" VERSION_LESS "8.0.0")
+ set (${_msgVar} "${_unsupportedCompiler} version ${CMAKE_${_language}_COMPILER_VERSION}." PARENT_SCOPE)
+ else()
+ set (${_msgVar} "" PARENT_SCOPE)
+ endif()
+ else()
+ set (${_msgVar} "${_unsupportedCompiler}." PARENT_SCOPE)
+ endif()
+ if (CMAKE_${_language}_COMPILER MATCHES "ccache")
+ if (NOT "$ENV{CCACHE_SLOPPINESS}" MATCHES "time_macros|pch_defines")
+ set (${_msgVar}
+ "ccache requires the environment variable CCACHE_SLOPPINESS to be set to \"pch_defines,time_macros\"."
+ PARENT_SCOPE)
+ endif()
+ endif()
+ if (APPLE)
+ # PCH compilation not supported by GCC / Clang for multi-architecture builds (e.g., i386, x86_64)
+ cotire_get_configuration_types(_configs)
+ foreach (_config ${_configs})
+ set (_targetFlags "")
+ cotire_get_target_compile_flags("${_config}" "${_language}" "${_target}" _targetFlags)
+ cotire_filter_compile_flags("${_language}" "arch" _architectures _ignore ${_targetFlags})
+ list (LENGTH _architectures _numberOfArchitectures)
+ if (_numberOfArchitectures GREATER 1)
+ string (REPLACE ";" ", " _architectureStr "${_architectures}")
+ set (${_msgVar}
+ "Precompiled headers not supported on Darwin for multi-architecture builds (${_architectureStr})."
+ PARENT_SCOPE)
+ break()
+ endif()
+ endforeach()
+ endif()
+endfunction()
+
+macro (cotire_get_intermediate_dir _cotireDir)
+ # ${CMAKE_CFG_INTDIR} may reference a build-time variable when using a generator which supports configuration types
+ get_filename_component(${_cotireDir} "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}/${COTIRE_INTDIR}" ABSOLUTE)
+endmacro()
+
+macro (cotire_setup_file_extension_variables)
+ set (_unityFileExt_C ".c")
+ set (_unityFileExt_CXX ".cxx")
+ set (_prefixFileExt_C ".h")
+ set (_prefixFileExt_CXX ".hxx")
+ set (_prefixSourceFileExt_C ".c")
+ set (_prefixSourceFileExt_CXX ".cxx")
+endmacro()
+
+function (cotire_make_single_unity_source_file_path _language _target _unityFileVar)
+ cotire_setup_file_extension_variables()
+ if (NOT DEFINED _unityFileExt_${_language})
+ set (${_unityFileVar} "" PARENT_SCOPE)
+ return()
+ endif()
+ set (_unityFileBaseName "${_target}_${_language}${COTIRE_UNITY_SOURCE_FILENAME_SUFFIX}")
+ set (_unityFileName "${_unityFileBaseName}${_unityFileExt_${_language}}")
+ cotire_get_intermediate_dir(_baseDir)
+ set (_unityFile "${_baseDir}/${_unityFileName}")
+ set (${_unityFileVar} "${_unityFile}" PARENT_SCOPE)
+endfunction()
+
+function (cotire_make_unity_source_file_paths _language _target _maxIncludes _unityFilesVar)
+ cotire_setup_file_extension_variables()
+ if (NOT DEFINED _unityFileExt_${_language})
+ set (${_unityFileVar} "" PARENT_SCOPE)
+ return()
+ endif()
+ set (_unityFileBaseName "${_target}_${_language}${COTIRE_UNITY_SOURCE_FILENAME_SUFFIX}")
+ cotire_get_intermediate_dir(_baseDir)
+ set (_startIndex 0)
+ set (_index 0)
+ set (_unityFiles "")
+ set (_sourceFiles ${ARGN})
+ foreach (_sourceFile ${_sourceFiles})
+ get_source_file_property(_startNew "${_sourceFile}" COTIRE_START_NEW_UNITY_SOURCE)
+ math (EXPR _unityFileCount "${_index} - ${_startIndex}")
+ if (_startNew OR (_maxIncludes GREATER 0 AND NOT _unityFileCount LESS _maxIncludes))
+ if (_index GREATER 0)
+ # start new unity file segment
+ math (EXPR _endIndex "${_index} - 1")
+ set (_unityFileName "${_unityFileBaseName}_${_startIndex}_${_endIndex}${_unityFileExt_${_language}}")
+ list (APPEND _unityFiles "${_baseDir}/${_unityFileName}")
+ endif()
+ set (_startIndex ${_index})
+ endif()
+ math (EXPR _index "${_index} + 1")
+ endforeach()
+ list (LENGTH _sourceFiles _numberOfSources)
+ if (_startIndex EQUAL 0)
+ # there is only a single unity file
+ cotire_make_single_unity_source_file_path(${_language} ${_target} _unityFiles)
+ elseif (_startIndex LESS _numberOfSources)
+ # end with final unity file segment
+ math (EXPR _endIndex "${_index} - 1")
+ set (_unityFileName "${_unityFileBaseName}_${_startIndex}_${_endIndex}${_unityFileExt_${_language}}")
+ list (APPEND _unityFiles "${_baseDir}/${_unityFileName}")
+ endif()
+ set (${_unityFilesVar} ${_unityFiles} PARENT_SCOPE)
+ if (COTIRE_DEBUG AND _unityFiles)
+ message (STATUS "unity files: ${_unityFiles}")
+ endif()
+endfunction()
+
+function (cotire_unity_to_prefix_file_path _language _target _unityFile _prefixFileVar)
+ cotire_setup_file_extension_variables()
+ if (NOT DEFINED _unityFileExt_${_language})
+ set (${_prefixFileVar} "" PARENT_SCOPE)
+ return()
+ endif()
+ set (_unityFileBaseName "${_target}_${_language}${COTIRE_UNITY_SOURCE_FILENAME_SUFFIX}")
+ set (_prefixFileBaseName "${_target}_${_language}${COTIRE_PREFIX_HEADER_FILENAME_SUFFIX}")
+ string (REPLACE "${_unityFileBaseName}" "${_prefixFileBaseName}" _prefixFile "${_unityFile}")
+ string (REGEX REPLACE "${_unityFileExt_${_language}}$" "${_prefixFileExt_${_language}}" _prefixFile "${_prefixFile}")
+ set (${_prefixFileVar} "${_prefixFile}" PARENT_SCOPE)
+endfunction()
+
+function (cotire_prefix_header_to_source_file_path _language _prefixHeaderFile _prefixSourceFileVar)
+ cotire_setup_file_extension_variables()
+ if (NOT DEFINED _prefixSourceFileExt_${_language})
+ set (${_prefixSourceFileVar} "" PARENT_SCOPE)
+ return()
+ endif()
+ string (REGEX REPLACE "${_prefixFileExt_${_language}}$" "${_prefixSourceFileExt_${_language}}" _prefixSourceFile "${_prefixHeaderFile}")
+ set (${_prefixSourceFileVar} "${_prefixSourceFile}" PARENT_SCOPE)
+endfunction()
+
+function (cotire_make_prefix_file_name _language _target _prefixFileBaseNameVar _prefixFileNameVar)
+ cotire_setup_file_extension_variables()
+ if (NOT _language)
+ set (_prefixFileBaseName "${_target}${COTIRE_PREFIX_HEADER_FILENAME_SUFFIX}")
+ set (_prefixFileName "${_prefixFileBaseName}${_prefixFileExt_C}")
+ elseif (DEFINED _prefixFileExt_${_language})
+ set (_prefixFileBaseName "${_target}_${_language}${COTIRE_PREFIX_HEADER_FILENAME_SUFFIX}")
+ set (_prefixFileName "${_prefixFileBaseName}${_prefixFileExt_${_language}}")
+ else()
+ set (_prefixFileBaseName "")
+ set (_prefixFileName "")
+ endif()
+ set (${_prefixFileBaseNameVar} "${_prefixFileBaseName}" PARENT_SCOPE)
+ set (${_prefixFileNameVar} "${_prefixFileName}" PARENT_SCOPE)
+endfunction()
+
+function (cotire_make_prefix_file_path _language _target _prefixFileVar)
+ cotire_make_prefix_file_name("${_language}" "${_target}" _prefixFileBaseName _prefixFileName)
+ set (${_prefixFileVar} "" PARENT_SCOPE)
+ if (_prefixFileName)
+ if (NOT _language)
+ set (_language "C")
+ endif()
+ if (CMAKE_${_language}_COMPILER_ID MATCHES "GNU|Clang|Intel|MSVC")
+ cotire_get_intermediate_dir(_baseDir)
+ set (${_prefixFileVar} "${_baseDir}/${_prefixFileName}" PARENT_SCOPE)
+ endif()
+ endif()
+endfunction()
+
+function (cotire_make_pch_file_path _language _target _pchFileVar)
+ cotire_make_prefix_file_name("${_language}" "${_target}" _prefixFileBaseName _prefixFileName)
+ set (${_pchFileVar} "" PARENT_SCOPE)
+ if (_prefixFileBaseName AND _prefixFileName)
+ cotire_check_precompiled_header_support("${_language}" "${_target}" _msg)
+ if (NOT _msg)
+ if (XCODE)
+ # For Xcode, we completely hand off the compilation of the prefix header to the IDE
+ return()
+ endif()
+ cotire_get_intermediate_dir(_baseDir)
+ if (CMAKE_${_language}_COMPILER_ID MATCHES "MSVC")
+ # MSVC uses the extension .pch added to the prefix header base name
+ set (${_pchFileVar} "${_baseDir}/${_prefixFileBaseName}.pch" PARENT_SCOPE)
+ elseif (CMAKE_${_language}_COMPILER_ID MATCHES "Clang")
+ # Clang looks for a precompiled header corresponding to the prefix header with the extension .pch appended
+ set (${_pchFileVar} "${_baseDir}/${_prefixFileName}.pch" PARENT_SCOPE)
+ elseif (CMAKE_${_language}_COMPILER_ID MATCHES "GNU")
+ # GCC looks for a precompiled header corresponding to the prefix header with the extension .gch appended
+ set (${_pchFileVar} "${_baseDir}/${_prefixFileName}.gch" PARENT_SCOPE)
+ elseif (CMAKE_${_language}_COMPILER_ID MATCHES "Intel")
+ # Intel uses the extension .pchi added to the prefix header base name
+ set (${_pchFileVar} "${_baseDir}/${_prefixFileBaseName}.pchi" PARENT_SCOPE)
+ endif()
+ endif()
+ endif()
+endfunction()
+
+function (cotire_select_unity_source_files _unityFile _sourcesVar)
+ set (_sourceFiles ${ARGN})
+ if (_sourceFiles AND "${_unityFile}" MATCHES "${COTIRE_UNITY_SOURCE_FILENAME_SUFFIX}_([0-9]+)_([0-9]+)")
+ set (_startIndex ${CMAKE_MATCH_1})
+ set (_endIndex ${CMAKE_MATCH_2})
+ list (LENGTH _sourceFiles _numberOfSources)
+ if (NOT _startIndex LESS _numberOfSources)
+ math (EXPR _startIndex "${_numberOfSources} - 1")
+ endif()
+ if (NOT _endIndex LESS _numberOfSources)
+ math (EXPR _endIndex "${_numberOfSources} - 1")
+ endif()
+ set (_files "")
+ foreach (_index RANGE ${_startIndex} ${_endIndex})
+ list (GET _sourceFiles ${_index} _file)
+ list (APPEND _files "${_file}")
+ endforeach()
+ else()
+ set (_files ${_sourceFiles})
+ endif()
+ set (${_sourcesVar} ${_files} PARENT_SCOPE)
+endfunction()
+
+function (cotire_get_unity_source_dependencies _language _target _dependencySourcesVar)
+ set (_dependencySources "")
+ # depend on target's generated source files
+ get_target_property(_targetSourceFiles ${_target} SOURCES)
+ cotire_get_objects_with_property_on(_generatedSources GENERATED SOURCE ${_targetSourceFiles})
+ if (_generatedSources)
+ # but omit all generated source files that have the COTIRE_EXCLUDED property set to true
+ cotire_get_objects_with_property_on(_excludedGeneratedSources COTIRE_EXCLUDED SOURCE ${_generatedSources})
+ if (_excludedGeneratedSources)
+ list (REMOVE_ITEM _generatedSources ${_excludedGeneratedSources})
+ endif()
+ # and omit all generated source files that have the COTIRE_DEPENDENCY property set to false explicitly
+ cotire_get_objects_with_property_off(_excludedNonDependencySources COTIRE_DEPENDENCY SOURCE ${_generatedSources})
+ if (_excludedNonDependencySources)
+ list (REMOVE_ITEM _generatedSources ${_excludedNonDependencySources})
+ endif()
+ if (_generatedSources)
+ list (APPEND _dependencySources ${_generatedSources})
+ endif()
+ endif()
+ if (COTIRE_DEBUG AND _dependencySources)
+ message (STATUS "${_language} ${_target} unity source dependencies: ${_dependencySources}")
+ endif()
+ set (${_dependencySourcesVar} ${_dependencySources} PARENT_SCOPE)
+endfunction()
+
+function (cotire_get_prefix_header_dependencies _language _target _dependencySourcesVar)
+ set (_dependencySources "")
+ # depend on target source files marked with custom COTIRE_DEPENDENCY property
+ get_target_property(_targetSourceFiles ${_target} SOURCES)
+ cotire_get_objects_with_property_on(_dependencySources COTIRE_DEPENDENCY SOURCE ${_targetSourceFiles})
+ if (COTIRE_DEBUG AND _dependencySources)
+ message (STATUS "${_language} ${_target} prefix header dependencies: ${_dependencySources}")
+ endif()
+ set (${_dependencySourcesVar} ${_dependencySources} PARENT_SCOPE)
+endfunction()
+
+function (cotire_generate_target_script _language _configurations _target _targetScriptVar _targetConfigScriptVar)
+ set (_targetSources ${ARGN})
+ cotire_get_prefix_header_dependencies(${_language} ${_target} COTIRE_TARGET_PREFIX_DEPENDS ${_targetSources})
+ cotire_get_unity_source_dependencies(${_language} ${_target} COTIRE_TARGET_UNITY_DEPENDS ${_targetSources})
+ # set up variables to be configured
+ set (COTIRE_TARGET_LANGUAGE "${_language}")
+ get_target_property(COTIRE_TARGET_IGNORE_PATH ${_target} COTIRE_PREFIX_HEADER_IGNORE_PATH)
+ cotire_add_sys_root_paths(COTIRE_TARGET_IGNORE_PATH)
+ get_target_property(COTIRE_TARGET_INCLUDE_PATH ${_target} COTIRE_PREFIX_HEADER_INCLUDE_PATH)
+ cotire_add_sys_root_paths(COTIRE_TARGET_INCLUDE_PATH)
+ get_target_property(COTIRE_TARGET_PRE_UNDEFS ${_target} COTIRE_UNITY_SOURCE_PRE_UNDEFS)
+ get_target_property(COTIRE_TARGET_POST_UNDEFS ${_target} COTIRE_UNITY_SOURCE_POST_UNDEFS)
+ get_target_property(COTIRE_TARGET_MAXIMUM_NUMBER_OF_INCLUDES ${_target} COTIRE_UNITY_SOURCE_MAXIMUM_NUMBER_OF_INCLUDES)
+ get_target_property(COTIRE_TARGET_INCLUDE_PRIORITY_PATH ${_target} COTIRE_PREFIX_HEADER_INCLUDE_PRIORITY_PATH)
+ cotire_get_source_files_undefs(COTIRE_UNITY_SOURCE_PRE_UNDEFS COTIRE_TARGET_SOURCES_PRE_UNDEFS ${_targetSources})
+ cotire_get_source_files_undefs(COTIRE_UNITY_SOURCE_POST_UNDEFS COTIRE_TARGET_SOURCES_POST_UNDEFS ${_targetSources})
+ set (COTIRE_TARGET_CONFIGURATION_TYPES "${_configurations}")
+ foreach (_config ${_configurations})
+ string (TOUPPER "${_config}" _upperConfig)
+ cotire_get_target_include_directories(
+ "${_config}" "${_language}" "${_target}" COTIRE_TARGET_INCLUDE_DIRECTORIES_${_upperConfig} COTIRE_TARGET_SYSTEM_INCLUDE_DIRECTORIES_${_upperConfig})
+ cotire_get_target_compile_definitions(
+ "${_config}" "${_language}" "${_target}" COTIRE_TARGET_COMPILE_DEFINITIONS_${_upperConfig})
+ cotire_get_target_compiler_flags(
+ "${_config}" "${_language}" "${_target}" COTIRE_TARGET_COMPILE_FLAGS_${_upperConfig})
+ cotire_get_source_files_compile_definitions(
+ "${_config}" "${_language}" COTIRE_TARGET_SOURCES_COMPILE_DEFINITIONS_${_upperConfig} ${_targetSources})
+ endforeach()
+ # set up COTIRE_TARGET_SOURCES
+ set (COTIRE_TARGET_SOURCES "")
+ foreach (_sourceFile ${_targetSources})
+ get_source_file_property(_generated "${_sourceFile}" GENERATED)
+ if (_generated)
+ # use absolute paths for generated files only, retrieving the LOCATION property is an expensive operation
+ get_source_file_property(_sourceLocation "${_sourceFile}" LOCATION)
+ list (APPEND COTIRE_TARGET_SOURCES "${_sourceLocation}")
+ else()
+ list (APPEND COTIRE_TARGET_SOURCES "${_sourceFile}")
+ endif()
+ endforeach()
+ # copy variable definitions to cotire target script
+ get_cmake_property(_vars VARIABLES)
+ string (REGEX MATCHALL "COTIRE_[A-Za-z0-9_]+" _matchVars "${_vars}")
+ # omit COTIRE_*_INIT variables
+ string (REGEX MATCHALL "COTIRE_[A-Za-z0-9_]+_INIT" _initVars "${_matchVars}")
+ if (_initVars)
+ list (REMOVE_ITEM _matchVars ${_initVars})
+ endif()
+ # omit COTIRE_VERBOSE which is passed as a CMake define on command line
+ list (REMOVE_ITEM _matchVars COTIRE_VERBOSE)
+ set (_contents "")
+ set (_contentsHasGeneratorExpressions FALSE)
+ foreach (_var IN LISTS _matchVars ITEMS
+ XCODE MSVC CMAKE_GENERATOR CMAKE_BUILD_TYPE CMAKE_CONFIGURATION_TYPES
+ CMAKE_${_language}_COMPILER_ID CMAKE_${_language}_COMPILER_VERSION
+ CMAKE_${_language}_COMPILER CMAKE_${_language}_COMPILER_ARG1
+ CMAKE_INCLUDE_FLAG_${_language} CMAKE_INCLUDE_FLAG_${_language}_SEP
+ CMAKE_INCLUDE_SYSTEM_FLAG_${_language}
+ CMAKE_${_language}_FRAMEWORK_SEARCH_FLAG
+ CMAKE_${_language}_SYSTEM_FRAMEWORK_SEARCH_FLAG
+ CMAKE_${_language}_SOURCE_FILE_EXTENSIONS)
+ if (DEFINED ${_var})
+ string (REPLACE "\"" "\\\"" _value "${${_var}}")
+ set (_contents "${_contents}set (${_var} \"${_value}\")\n")
+ if (NOT _contentsHasGeneratorExpressions)
+ if ("${_value}" MATCHES "\\$<.*>")
+ set (_contentsHasGeneratorExpressions TRUE)
+ endif()
+ endif()
+ endif()
+ endforeach()
+ # generate target script file
+ get_filename_component(_moduleName "${COTIRE_CMAKE_MODULE_FILE}" NAME)
+ set (_targetCotireScript "${CMAKE_CURRENT_BINARY_DIR}/${_target}_${_language}_${_moduleName}")
+ cotire_write_file("CMAKE" "${_targetCotireScript}" "${_contents}" FALSE)
+ if (_contentsHasGeneratorExpressions)
+ # use file(GENERATE ...) to expand generator expressions in the target script at CMake generate-time
+ set (_configNameOrNoneGeneratorExpression "$<$:None>$<$>:$>")
+ set (_targetCotireConfigScript "${CMAKE_CURRENT_BINARY_DIR}/${_target}_${_language}_${_configNameOrNoneGeneratorExpression}_${_moduleName}")
+ file (GENERATE OUTPUT "${_targetCotireConfigScript}" INPUT "${_targetCotireScript}")
+ else()
+ set (_targetCotireConfigScript "${_targetCotireScript}")
+ endif()
+ set (${_targetScriptVar} "${_targetCotireScript}" PARENT_SCOPE)
+ set (${_targetConfigScriptVar} "${_targetCotireConfigScript}" PARENT_SCOPE)
+endfunction()
+
+function (cotire_setup_pch_file_compilation _language _target _targetScript _prefixFile _pchFile _hostFile)
+ set (_sourceFiles ${ARGN})
+ if (CMAKE_${_language}_COMPILER_ID MATCHES "MSVC|Intel")
+ # for Visual Studio and Intel, we attach the precompiled header compilation to the host file
+ # the remaining files include the precompiled header, see cotire_setup_pch_file_inclusion
+ if (_sourceFiles)
+ set (_flags "")
+ cotire_add_pch_compilation_flags(
+ "${_language}" "${CMAKE_${_language}_COMPILER_ID}" "${CMAKE_${_language}_COMPILER_VERSION}"
+ "${_prefixFile}" "${_pchFile}" "${_hostFile}" _flags)
+ set_property (SOURCE ${_hostFile} APPEND_STRING PROPERTY COMPILE_FLAGS " ${_flags} ")
+ set_property (SOURCE ${_hostFile} APPEND PROPERTY OBJECT_OUTPUTS "${_pchFile}")
+ # make object file generated from host file depend on prefix header
+ set_property (SOURCE ${_hostFile} APPEND PROPERTY OBJECT_DEPENDS "${_prefixFile}")
+ # mark host file as cotired to prevent it from being used in another cotired target
+ set_property (SOURCE ${_hostFile} PROPERTY COTIRE_TARGET "${_target}")
+ endif()
+ elseif ("${CMAKE_GENERATOR}" MATCHES "Make|Ninja")
+ # for makefile based generator, we add a custom command to precompile the prefix header
+ if (_targetScript)
+ cotire_set_cmd_to_prologue(_cmds)
+ list (APPEND _cmds -P "${COTIRE_CMAKE_MODULE_FILE}" "precompile" "${_targetScript}" "${_prefixFile}" "${_pchFile}" "${_hostFile}")
+ file (RELATIVE_PATH _pchFileRelPath "${CMAKE_BINARY_DIR}" "${_pchFile}")
+ if (COTIRE_DEBUG)
+ message (STATUS "add_custom_command: OUTPUT ${_pchFile} ${_cmds} DEPENDS ${_prefixFile} IMPLICIT_DEPENDS ${_language} ${_prefixFile}")
+ endif()
+ set_property (SOURCE "${_pchFile}" PROPERTY GENERATED TRUE)
+ add_custom_command(
+ OUTPUT "${_pchFile}"
+ COMMAND ${_cmds}
+ DEPENDS "${_prefixFile}"
+ IMPLICIT_DEPENDS ${_language} "${_prefixFile}"
+ WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
+ COMMENT "Building ${_language} precompiled header ${_pchFileRelPath}"
+ VERBATIM)
+ endif()
+ endif()
+endfunction()
+
+function (cotire_setup_pch_file_inclusion _language _target _wholeTarget _prefixFile _pchFile _hostFile)
+ if (CMAKE_${_language}_COMPILER_ID MATCHES "MSVC|Intel")
+ # for Visual Studio and Intel, we include the precompiled header in all but the host file
+ # the host file does the precompiled header compilation, see cotire_setup_pch_file_compilation
+ set (_sourceFiles ${ARGN})
+ list (LENGTH _sourceFiles _numberOfSourceFiles)
+ if (_numberOfSourceFiles GREATER 0)
+ # mark sources as cotired to prevent them from being used in another cotired target
+ set_source_files_properties(${_sourceFiles} PROPERTIES COTIRE_TARGET "${_target}")
+ set (_flags "")
+ cotire_add_prefix_pch_inclusion_flags(
+ "${_language}" "${CMAKE_${_language}_COMPILER_ID}" "${CMAKE_${_language}_COMPILER_VERSION}"
+ "${_prefixFile}" "${_pchFile}" _flags)
+ set_property (SOURCE ${_sourceFiles} APPEND_STRING PROPERTY COMPILE_FLAGS " ${_flags} ")
+ # make object files generated from source files depend on precompiled header
+ set_property (SOURCE ${_sourceFiles} APPEND PROPERTY OBJECT_DEPENDS "${_pchFile}")
+ endif()
+ elseif ("${CMAKE_GENERATOR}" MATCHES "Make|Ninja")
+ set (_sourceFiles ${_hostFile} ${ARGN})
+ if (NOT _wholeTarget)
+ # for makefile based generator, we force the inclusion of the prefix header for a subset
+ # of the source files, if this is a multi-language target or has excluded files
+ set (_flags "")
+ cotire_add_prefix_pch_inclusion_flags(
+ "${_language}" "${CMAKE_${_language}_COMPILER_ID}" "${CMAKE_${_language}_COMPILER_VERSION}"
+ "${_prefixFile}" "${_pchFile}" _flags)
+ set_property (SOURCE ${_sourceFiles} APPEND_STRING PROPERTY COMPILE_FLAGS " ${_flags} ")
+ # mark sources as cotired to prevent them from being used in another cotired target
+ set_source_files_properties(${_sourceFiles} PROPERTIES COTIRE_TARGET "${_target}")
+ endif()
+ # make object files generated from source files depend on precompiled header
+ set_property (SOURCE ${_sourceFiles} APPEND PROPERTY OBJECT_DEPENDS "${_pchFile}")
+ endif()
+endfunction()
+
+function (cotire_setup_prefix_file_inclusion _language _target _prefixFile)
+ set (_sourceFiles ${ARGN})
+ # force the inclusion of the prefix header for the given source files
+ set (_flags "")
+ set (_pchFile "")
+ cotire_add_prefix_pch_inclusion_flags(
+ "${_language}" "${CMAKE_${_language}_COMPILER_ID}" "${CMAKE_${_language}_COMPILER_VERSION}"
+ "${_prefixFile}" "${_pchFile}" _flags)
+ set_property (SOURCE ${_sourceFiles} APPEND_STRING PROPERTY COMPILE_FLAGS " ${_flags} ")
+ # mark sources as cotired to prevent them from being used in another cotired target
+ set_source_files_properties(${_sourceFiles} PROPERTIES COTIRE_TARGET "${_target}")
+ # make object files generated from source files depend on prefix header
+ set_property (SOURCE ${_sourceFiles} APPEND PROPERTY OBJECT_DEPENDS "${_prefixFile}")
+endfunction()
+
+function (cotire_get_first_set_property_value _propertyValueVar _type _object)
+ set (_properties ${ARGN})
+ foreach (_property ${_properties})
+ get_property(_propertyValue ${_type} "${_object}" PROPERTY ${_property})
+ if (_propertyValue)
+ set (${_propertyValueVar} ${_propertyValue} PARENT_SCOPE)
+ return()
+ endif()
+ endforeach()
+ set (${_propertyValueVar} "" PARENT_SCOPE)
+endfunction()
+
+function (cotire_setup_combine_command _language _targetScript _joinedFile _cmdsVar)
+ set (_files ${ARGN})
+ set (_filesPaths "")
+ foreach (_file ${_files})
+ get_filename_component(_filePath "${_file}" ABSOLUTE)
+ list (APPEND _filesPaths "${_filePath}")
+ endforeach()
+ cotire_set_cmd_to_prologue(_prefixCmd)
+ list (APPEND _prefixCmd -P "${COTIRE_CMAKE_MODULE_FILE}" "combine")
+ if (_targetScript)
+ list (APPEND _prefixCmd "${_targetScript}")
+ endif()
+ list (APPEND _prefixCmd "${_joinedFile}" ${_filesPaths})
+ if (COTIRE_DEBUG)
+ message (STATUS "add_custom_command: OUTPUT ${_joinedFile} COMMAND ${_prefixCmd} DEPENDS ${_files}")
+ endif()
+ set_property (SOURCE "${_joinedFile}" PROPERTY GENERATED TRUE)
+ file (RELATIVE_PATH _joinedFileRelPath "${CMAKE_BINARY_DIR}" "${_joinedFile}")
+ get_filename_component(_joinedFileBaseName "${_joinedFile}" NAME_WE)
+ get_filename_component(_joinedFileExt "${_joinedFile}" EXT)
+ if (_language AND _joinedFileBaseName MATCHES "${COTIRE_UNITY_SOURCE_FILENAME_SUFFIX}$")
+ set (_comment "Generating ${_language} unity source ${_joinedFileRelPath}")
+ elseif (_language AND _joinedFileBaseName MATCHES "${COTIRE_PREFIX_HEADER_FILENAME_SUFFIX}$")
+ if (_joinedFileExt MATCHES "^\\.c")
+ set (_comment "Generating ${_language} prefix source ${_joinedFileRelPath}")
+ else()
+ set (_comment "Generating ${_language} prefix header ${_joinedFileRelPath}")
+ endif()
+ else()
+ set (_comment "Generating ${_joinedFileRelPath}")
+ endif()
+ add_custom_command(
+ OUTPUT "${_joinedFile}"
+ COMMAND ${_prefixCmd}
+ DEPENDS ${_files}
+ COMMENT "${_comment}"
+ WORKING_DIRECTORY "${CMAKE_BINARY_DIR}"
+ VERBATIM)
+ list (APPEND ${_cmdsVar} COMMAND ${_prefixCmd})
+ set (${_cmdsVar} ${${_cmdsVar}} PARENT_SCOPE)
+endfunction()
+
+function (cotire_setup_target_pch_usage _languages _target _wholeTarget)
+ if (XCODE)
+ # for Xcode, we attach a pre-build action to generate the unity sources and prefix headers
+ set (_prefixFiles "")
+ foreach (_language ${_languages})
+ get_property(_prefixFile TARGET ${_target} PROPERTY COTIRE_${_language}_PREFIX_HEADER)
+ if (_prefixFile)
+ list (APPEND _prefixFiles "${_prefixFile}")
+ endif()
+ endforeach()
+ set (_cmds ${ARGN})
+ list (LENGTH _prefixFiles _numberOfPrefixFiles)
+ if (_numberOfPrefixFiles GREATER 1)
+ # we also generate a generic, single prefix header which includes all language specific prefix headers
+ set (_language "")
+ set (_targetScript "")
+ cotire_make_prefix_file_path("${_language}" ${_target} _prefixHeader)
+ cotire_setup_combine_command("${_language}" "${_targetScript}" "${_prefixHeader}" _cmds ${_prefixFiles})
+ else()
+ set (_prefixHeader "${_prefixFiles}")
+ endif()
+ if (COTIRE_DEBUG)
+ message (STATUS "add_custom_command: TARGET ${_target} PRE_BUILD ${_cmds}")
+ endif()
+ # because CMake PRE_BUILD command does not support dependencies,
+ # we check dependencies explicity in cotire script mode when the pre-build action is run
+ add_custom_command(
+ TARGET "${_target}"
+ PRE_BUILD ${_cmds}
+ WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
+ COMMENT "Updating target ${_target} prefix headers"
+ VERBATIM)
+ # make Xcode precompile the generated prefix header with ProcessPCH and ProcessPCH++
+ set_target_properties(${_target} PROPERTIES XCODE_ATTRIBUTE_GCC_PRECOMPILE_PREFIX_HEADER "YES")
+ set_target_properties(${_target} PROPERTIES XCODE_ATTRIBUTE_GCC_PREFIX_HEADER "${_prefixHeader}")
+ elseif ("${CMAKE_GENERATOR}" MATCHES "Make|Ninja")
+ # for makefile based generator, we force inclusion of the prefix header for all target source files
+ # if this is a single-language target without any excluded files
+ if (_wholeTarget)
+ set (_language "${_languages}")
+ # for Visual Studio and Intel, precompiled header inclusion is always done on the source file level
+ # see cotire_setup_pch_file_inclusion
+ if (NOT CMAKE_${_language}_COMPILER_ID MATCHES "MSVC|Intel")
+ get_property(_prefixFile TARGET ${_target} PROPERTY COTIRE_${_language}_PREFIX_HEADER)
+ if (_prefixFile)
+ get_property(_pchFile TARGET ${_target} PROPERTY COTIRE_${_language}_PRECOMPILED_HEADER)
+ set (_options COMPILE_OPTIONS)
+ cotire_add_prefix_pch_inclusion_flags(
+ "${_language}" "${CMAKE_${_language}_COMPILER_ID}" "${CMAKE_${_language}_COMPILER_VERSION}"
+ "${_prefixFile}" "${_pchFile}" _options)
+ set_property(TARGET ${_target} APPEND PROPERTY ${_options})
+ endif()
+ endif()
+ endif()
+ endif()
+endfunction()
+
+function (cotire_setup_unity_generation_commands _language _target _targetScript _targetConfigScript _unityFiles _cmdsVar)
+ set (_dependencySources "")
+ cotire_get_unity_source_dependencies(${_language} ${_target} _dependencySources ${ARGN})
+ foreach (_unityFile ${_unityFiles})
+ set_property (SOURCE "${_unityFile}" PROPERTY GENERATED TRUE)
+ # set up compiled unity source dependencies via OBJECT_DEPENDS
+ # this ensures that missing source files are generated before the unity file is compiled
+ if (COTIRE_DEBUG AND _dependencySources)
+ message (STATUS "${_unityFile} OBJECT_DEPENDS ${_dependencySources}")
+ endif()
+ if (_dependencySources)
+ # the OBJECT_DEPENDS property requires a list of full paths
+ set (_objectDependsPaths "")
+ foreach (_sourceFile ${_dependencySources})
+ get_source_file_property(_sourceLocation "${_sourceFile}" LOCATION)
+ list (APPEND _objectDependsPaths "${_sourceLocation}")
+ endforeach()
+ set_property (SOURCE "${_unityFile}" PROPERTY OBJECT_DEPENDS ${_objectDependsPaths})
+ endif()
+ if (WIN32 AND CMAKE_${_language}_COMPILER_ID MATCHES "MSVC|Intel")
+ # unity file compilation results in potentially huge object file, thus use /bigobj by default unter MSVC and Windows Intel
+ set_property (SOURCE "${_unityFile}" APPEND_STRING PROPERTY COMPILE_FLAGS "/bigobj")
+ endif()
+ cotire_set_cmd_to_prologue(_unityCmd)
+ list (APPEND _unityCmd -P "${COTIRE_CMAKE_MODULE_FILE}" "unity" "${_targetConfigScript}" "${_unityFile}")
+ if (CMAKE_VERSION VERSION_LESS "3.1.0")
+ set (_unityCmdDepends "${_targetScript}")
+ else()
+ # CMake 3.1.0 supports generator expressions in arguments to DEPENDS
+ set (_unityCmdDepends "${_targetConfigScript}")
+ endif()
+ file (RELATIVE_PATH _unityFileRelPath "${CMAKE_BINARY_DIR}" "${_unityFile}")
+ if (COTIRE_DEBUG)
+ message (STATUS "add_custom_command: OUTPUT ${_unityFile} COMMAND ${_unityCmd} DEPENDS ${_unityCmdDepends}")
+ endif()
+ add_custom_command(
+ OUTPUT "${_unityFile}"
+ COMMAND ${_unityCmd}
+ DEPENDS ${_unityCmdDepends}
+ COMMENT "Generating ${_language} unity source ${_unityFileRelPath}"
+ WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
+ VERBATIM)
+ list (APPEND ${_cmdsVar} COMMAND ${_unityCmd})
+ endforeach()
+ set (${_cmdsVar} ${${_cmdsVar}} PARENT_SCOPE)
+endfunction()
+
+function (cotire_setup_prefix_generation_command _language _target _targetScript _prefixFile _unityFiles _cmdsVar)
+ set (_sourceFiles ${ARGN})
+ set (_dependencySources "")
+ cotire_get_prefix_header_dependencies(${_language} ${_target} _dependencySources ${_sourceFiles})
+ cotire_set_cmd_to_prologue(_prefixCmd)
+ list (APPEND _prefixCmd -P "${COTIRE_CMAKE_MODULE_FILE}" "prefix" "${_targetScript}" "${_prefixFile}" ${_unityFiles})
+ set_property (SOURCE "${_prefixFile}" PROPERTY GENERATED TRUE)
+ if (COTIRE_DEBUG)
+ message (STATUS "add_custom_command: OUTPUT ${_prefixFile} COMMAND ${_prefixCmd} DEPENDS ${_unityFile} ${_dependencySources}")
+ endif()
+ file (RELATIVE_PATH _prefixFileRelPath "${CMAKE_BINARY_DIR}" "${_prefixFile}")
+ get_filename_component(_prefixFileExt "${_prefixFile}" EXT)
+ if (_prefixFileExt MATCHES "^\\.c")
+ set (_comment "Generating ${_language} prefix source ${_prefixFileRelPath}")
+ else()
+ set (_comment "Generating ${_language} prefix header ${_prefixFileRelPath}")
+ endif()
+ # prevent pre-processing errors upon generating the prefix header when a target's generated include file does not yet exist
+ # we do not add a file-level dependency for the target's generated files though, because we only want to depend on their existence
+ # thus we make the prefix header generation depend on a custom helper target which triggers the generation of the files
+ set (_preTargetName "${_target}${COTIRE_PCH_TARGET_SUFFIX}_pre")
+ if (TARGET ${_preTargetName})
+ # custom helper target has already been generated while processing a different language
+ list (APPEND _dependencySources ${_preTargetName})
+ else()
+ get_target_property(_targetSourceFiles ${_target} SOURCES)
+ cotire_get_objects_with_property_on(_generatedSources GENERATED SOURCE ${_targetSourceFiles})
+ if (_generatedSources)
+ add_custom_target("${_preTargetName}" DEPENDS ${_generatedSources})
+ cotire_init_target("${_preTargetName}")
+ list (APPEND _dependencySources ${_preTargetName})
+ endif()
+ endif()
+ add_custom_command(
+ OUTPUT "${_prefixFile}" "${_prefixFile}.log"
+ COMMAND ${_prefixCmd}
+ DEPENDS ${_unityFiles} ${_dependencySources}
+ COMMENT "${_comment}"
+ WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
+ VERBATIM)
+ list (APPEND ${_cmdsVar} COMMAND ${_prefixCmd})
+ set (${_cmdsVar} ${${_cmdsVar}} PARENT_SCOPE)
+endfunction()
+
+function (cotire_setup_prefix_generation_from_unity_command _language _target _targetScript _prefixFile _unityFiles _cmdsVar)
+ set (_sourceFiles ${ARGN})
+ if (CMAKE_${_language}_COMPILER_ID MATCHES "GNU|Clang")
+ # GNU and Clang require indirect compilation of the prefix header to make them honor the system_header pragma
+ cotire_prefix_header_to_source_file_path(${_language} "${_prefixFile}" _prefixSourceFile)
+ else()
+ set (_prefixSourceFile "${_prefixFile}")
+ endif()
+ cotire_setup_prefix_generation_command(
+ ${_language} ${_target} "${_targetScript}"
+ "${_prefixSourceFile}" "${_unityFiles}" ${_cmdsVar} ${_sourceFiles})
+ if (CMAKE_${_language}_COMPILER_ID MATCHES "GNU|Clang")
+ # set up generation of a prefix source file which includes the prefix header
+ cotire_setup_combine_command(${_language} "${_targetScript}" "${_prefixFile}" _cmds ${_prefixSourceFile})
+ endif()
+ set (${_cmdsVar} ${${_cmdsVar}} PARENT_SCOPE)
+endfunction()
+
+function (cotire_setup_prefix_generation_from_provided_command _language _target _targetScript _prefixFile _cmdsVar)
+ set (_prefixHeaderFiles ${ARGN})
+ if (CMAKE_${_language}_COMPILER_ID MATCHES "GNU|Clang")
+ # GNU and Clang require indirect compilation of the prefix header to make them honor the system_header pragma
+ cotire_prefix_header_to_source_file_path(${_language} "${_prefixFile}" _prefixSourceFile)
+ else()
+ set (_prefixSourceFile "${_prefixFile}")
+ endif()
+ cotire_setup_combine_command(${_language} "${_targetScript}" "${_prefixSourceFile}" _cmds ${_prefixHeaderFiles})
+ if (CMAKE_${_language}_COMPILER_ID MATCHES "GNU|Clang")
+ # set up generation of a prefix source file which includes the prefix header
+ cotire_setup_combine_command(${_language} "${_targetScript}" "${_prefixFile}" _cmds ${_prefixSourceFile})
+ endif()
+ set (${_cmdsVar} ${${_cmdsVar}} PARENT_SCOPE)
+endfunction()
+
+function (cotire_init_cotire_target_properties _target)
+ get_property(_isSet TARGET ${_target} PROPERTY COTIRE_ENABLE_PRECOMPILED_HEADER SET)
+ if (NOT _isSet)
+ set_property(TARGET ${_target} PROPERTY COTIRE_ENABLE_PRECOMPILED_HEADER TRUE)
+ endif()
+ get_property(_isSet TARGET ${_target} PROPERTY COTIRE_ADD_UNITY_BUILD SET)
+ if (NOT _isSet)
+ set_property(TARGET ${_target} PROPERTY COTIRE_ADD_UNITY_BUILD TRUE)
+ endif()
+ get_property(_isSet TARGET ${_target} PROPERTY COTIRE_ADD_CLEAN SET)
+ if (NOT _isSet)
+ set_property(TARGET ${_target} PROPERTY COTIRE_ADD_CLEAN FALSE)
+ endif()
+ get_property(_isSet TARGET ${_target} PROPERTY COTIRE_PREFIX_HEADER_IGNORE_PATH SET)
+ if (NOT _isSet)
+ set_property(TARGET ${_target} PROPERTY COTIRE_PREFIX_HEADER_IGNORE_PATH "${CMAKE_SOURCE_DIR}")
+ cotire_check_is_path_relative_to("${CMAKE_BINARY_DIR}" _isRelative "${CMAKE_SOURCE_DIR}")
+ if (NOT _isRelative)
+ set_property(TARGET ${_target} APPEND PROPERTY COTIRE_PREFIX_HEADER_IGNORE_PATH "${CMAKE_BINARY_DIR}")
+ endif()
+ endif()
+ get_property(_isSet TARGET ${_target} PROPERTY COTIRE_PREFIX_HEADER_INCLUDE_PATH SET)
+ if (NOT _isSet)
+ set_property(TARGET ${_target} PROPERTY COTIRE_PREFIX_HEADER_INCLUDE_PATH "")
+ endif()
+ get_property(_isSet TARGET ${_target} PROPERTY COTIRE_PREFIX_HEADER_INCLUDE_PRIORITY_PATH SET)
+ if (NOT _isSet)
+ set_property(TARGET ${_target} PROPERTY COTIRE_PREFIX_HEADER_INCLUDE_PRIORITY_PATH "")
+ endif()
+ get_property(_isSet TARGET ${_target} PROPERTY COTIRE_UNITY_SOURCE_PRE_UNDEFS SET)
+ if (NOT _isSet)
+ set_property(TARGET ${_target} PROPERTY COTIRE_UNITY_SOURCE_PRE_UNDEFS "")
+ endif()
+ get_property(_isSet TARGET ${_target} PROPERTY COTIRE_UNITY_SOURCE_POST_UNDEFS SET)
+ if (NOT _isSet)
+ set_property(TARGET ${_target} PROPERTY COTIRE_UNITY_SOURCE_POST_UNDEFS "")
+ endif()
+ get_property(_isSet TARGET ${_target} PROPERTY COTIRE_UNITY_LINK_LIBRARIES_INIT SET)
+ if (NOT _isSet)
+ set_property(TARGET ${_target} PROPERTY COTIRE_UNITY_LINK_LIBRARIES_INIT "COPY_UNITY")
+ endif()
+ get_property(_isSet TARGET ${_target} PROPERTY COTIRE_UNITY_SOURCE_MAXIMUM_NUMBER_OF_INCLUDES SET)
+ if (NOT _isSet)
+ if (COTIRE_MAXIMUM_NUMBER_OF_UNITY_INCLUDES)
+ set_property(TARGET ${_target} PROPERTY COTIRE_UNITY_SOURCE_MAXIMUM_NUMBER_OF_INCLUDES "${COTIRE_MAXIMUM_NUMBER_OF_UNITY_INCLUDES}")
+ else()
+ set_property(TARGET ${_target} PROPERTY COTIRE_UNITY_SOURCE_MAXIMUM_NUMBER_OF_INCLUDES "")
+ endif()
+ endif()
+endfunction()
+
+function (cotire_make_target_message _target _languages _disableMsg _targetMsgVar)
+ get_target_property(_targetUsePCH ${_target} COTIRE_ENABLE_PRECOMPILED_HEADER)
+ get_target_property(_targetAddSCU ${_target} COTIRE_ADD_UNITY_BUILD)
+ string (REPLACE ";" " " _languagesStr "${_languages}")
+ math (EXPR _numberOfExcludedFiles "${ARGC} - 4")
+ if (_numberOfExcludedFiles EQUAL 0)
+ set (_excludedStr "")
+ elseif (COTIRE_VERBOSE OR _numberOfExcludedFiles LESS 4)
+ string (REPLACE ";" ", " _excludedStr "excluding ${ARGN}")
+ else()
+ set (_excludedStr "excluding ${_numberOfExcludedFiles} files")
+ endif()
+ set (_targetMsg "")
+ if (NOT _languages)
+ set (_targetMsg "Target ${_target} cannot be cotired.")
+ if (_disableMsg)
+ set (_targetMsg "${_targetMsg} ${_disableMsg}")
+ endif()
+ elseif (NOT _targetUsePCH AND NOT _targetAddSCU)
+ set (_targetMsg "${_languagesStr} target ${_target} cotired without unity build and precompiled header.")
+ if (_disableMsg)
+ set (_targetMsg "${_targetMsg} ${_disableMsg}")
+ endif()
+ elseif (NOT _targetUsePCH)
+ if (_excludedStr)
+ set (_targetMsg "${_languagesStr} target ${_target} cotired without precompiled header ${_excludedStr}.")
+ else()
+ set (_targetMsg "${_languagesStr} target ${_target} cotired without precompiled header.")
+ endif()
+ if (_disableMsg)
+ set (_targetMsg "${_targetMsg} ${_disableMsg}")
+ endif()
+ elseif (NOT _targetAddSCU)
+ if (_excludedStr)
+ set (_targetMsg "${_languagesStr} target ${_target} cotired without unity build ${_excludedStr}.")
+ else()
+ set (_targetMsg "${_languagesStr} target ${_target} cotired without unity build.")
+ endif()
+ else()
+ if (_excludedStr)
+ set (_targetMsg "${_languagesStr} target ${_target} cotired ${_excludedStr}.")
+ else()
+ set (_targetMsg "${_languagesStr} target ${_target} cotired.")
+ endif()
+ endif()
+ set (${_targetMsgVar} "${_targetMsg}" PARENT_SCOPE)
+endfunction()
+
+function (cotire_choose_target_languages _target _targetLanguagesVar _wholeTargetVar)
+ set (_languages ${ARGN})
+ set (_allSourceFiles "")
+ set (_allExcludedSourceFiles "")
+ set (_allCotiredSourceFiles "")
+ set (_targetLanguages "")
+ set (_pchEligibleTargetLanguages "")
+ get_target_property(_targetType ${_target} TYPE)
+ get_target_property(_targetSourceFiles ${_target} SOURCES)
+ get_target_property(_targetUsePCH ${_target} COTIRE_ENABLE_PRECOMPILED_HEADER)
+ get_target_property(_targetAddSCU ${_target} COTIRE_ADD_UNITY_BUILD)
+ set (_disableMsg "")
+ foreach (_language ${_languages})
+ get_target_property(_prefixHeader ${_target} COTIRE_${_language}_PREFIX_HEADER)
+ get_target_property(_unityBuildFile ${_target} COTIRE_${_language}_UNITY_SOURCE)
+ if (_prefixHeader OR _unityBuildFile)
+ message (STATUS "cotire: target ${_target} has already been cotired.")
+ set (${_targetLanguagesVar} "" PARENT_SCOPE)
+ return()
+ endif()
+ if (_targetUsePCH AND "${_language}" MATCHES "^C|CXX$")
+ cotire_check_precompiled_header_support("${_language}" "${_target}" _disableMsg)
+ if (_disableMsg)
+ set (_targetUsePCH FALSE)
+ endif()
+ endif()
+ set (_sourceFiles "")
+ set (_excludedSources "")
+ set (_cotiredSources "")
+ cotire_filter_language_source_files(${_language} ${_target} _sourceFiles _excludedSources _cotiredSources ${_targetSourceFiles})
+ if (_sourceFiles OR _excludedSources OR _cotiredSources)
+ list (APPEND _targetLanguages ${_language})
+ endif()
+ if (_sourceFiles)
+ list (APPEND _allSourceFiles ${_sourceFiles})
+ endif()
+ list (LENGTH _sourceFiles _numberOfSources)
+ if (NOT _numberOfSources LESS ${COTIRE_MINIMUM_NUMBER_OF_TARGET_SOURCES})
+ list (APPEND _pchEligibleTargetLanguages ${_language})
+ endif()
+ if (_excludedSources)
+ list (APPEND _allExcludedSourceFiles ${_excludedSources})
+ endif()
+ if (_cotiredSources)
+ list (APPEND _allCotiredSourceFiles ${_cotiredSources})
+ endif()
+ endforeach()
+ set (_targetMsgLevel STATUS)
+ if (NOT _targetLanguages)
+ string (REPLACE ";" " or " _languagesStr "${_languages}")
+ set (_disableMsg "No ${_languagesStr} source files.")
+ set (_targetUsePCH FALSE)
+ set (_targetAddSCU FALSE)
+ endif()
+ if (_targetUsePCH)
+ if (_allCotiredSourceFiles)
+ cotire_get_source_file_property_values(_cotireTargets COTIRE_TARGET ${_allCotiredSourceFiles})
+ list (REMOVE_DUPLICATES _cotireTargets)
+ string (REPLACE ";" ", " _cotireTargetsStr "${_cotireTargets}")
+ set (_disableMsg "Target sources already include a precompiled header for target(s) ${_cotireTargets}.")
+ set (_disableMsg "${_disableMsg} Set target property COTIRE_ENABLE_PRECOMPILED_HEADER to FALSE for targets ${_target},")
+ set (_disableMsg "${_disableMsg} ${_cotireTargetsStr} to get a workable build system.")
+ set (_targetMsgLevel SEND_ERROR)
+ set (_targetUsePCH FALSE)
+ elseif (NOT _pchEligibleTargetLanguages)
+ set (_disableMsg "Too few applicable sources.")
+ set (_targetUsePCH FALSE)
+ elseif (XCODE AND _allExcludedSourceFiles)
+ # for Xcode, we cannot apply the precompiled header to individual sources, only to the whole target
+ set (_disableMsg "Exclusion of source files not supported for generator Xcode.")
+ set (_targetUsePCH FALSE)
+ elseif (XCODE AND "${_targetType}" STREQUAL "OBJECT_LIBRARY")
+ # for Xcode, we cannot apply the required PRE_BUILD action to generate the prefix header to an OBJECT_LIBRARY target
+ set (_disableMsg "Required PRE_BUILD action not supported for OBJECT_LIBRARY targets for generator Xcode.")
+ set (_targetUsePCH FALSE)
+ endif()
+ endif()
+ set_property(TARGET ${_target} PROPERTY COTIRE_ENABLE_PRECOMPILED_HEADER ${_targetUsePCH})
+ set_property(TARGET ${_target} PROPERTY COTIRE_ADD_UNITY_BUILD ${_targetAddSCU})
+ cotire_make_target_message(${_target} "${_targetLanguages}" "${_disableMsg}" _targetMsg ${_allExcludedSourceFiles})
+ if (_targetMsg)
+ if (NOT DEFINED COTIREMSG_${_target})
+ set (COTIREMSG_${_target} "")
+ endif()
+ if (COTIRE_VERBOSE OR NOT "${_targetMsgLevel}" STREQUAL "STATUS" OR
+ NOT "${COTIREMSG_${_target}}" STREQUAL "${_targetMsg}")
+ # cache message to avoid redundant messages on re-configure
+ set (COTIREMSG_${_target} "${_targetMsg}" CACHE INTERNAL "${_target} cotire message.")
+ message (${_targetMsgLevel} "${_targetMsg}")
+ endif()
+ endif()
+ list (LENGTH _targetLanguages _numberOfLanguages)
+ if (_numberOfLanguages GREATER 1 OR _allExcludedSourceFiles)
+ set (${_wholeTargetVar} FALSE PARENT_SCOPE)
+ else()
+ set (${_wholeTargetVar} TRUE PARENT_SCOPE)
+ endif()
+ set (${_targetLanguagesVar} ${_targetLanguages} PARENT_SCOPE)
+endfunction()
+
+function (cotire_compute_unity_max_number_of_includes _target _maxIncludesVar)
+ set (_sourceFiles ${ARGN})
+ get_target_property(_maxIncludes ${_target} COTIRE_UNITY_SOURCE_MAXIMUM_NUMBER_OF_INCLUDES)
+ if (_maxIncludes MATCHES "(-j|--parallel|--jobs) ?([0-9]*)")
+ set (_numberOfThreads "${CMAKE_MATCH_2}")
+ if (NOT _numberOfThreads)
+ # use all available cores
+ ProcessorCount(_numberOfThreads)
+ endif()
+ list (LENGTH _sourceFiles _numberOfSources)
+ math (EXPR _maxIncludes "(${_numberOfSources} + ${_numberOfThreads} - 1) / ${_numberOfThreads}")
+ elseif (NOT _maxIncludes MATCHES "[0-9]+")
+ set (_maxIncludes 0)
+ endif()
+ if (COTIRE_DEBUG)
+ message (STATUS "${_target} unity source max includes: ${_maxIncludes}")
+ endif()
+ set (${_maxIncludesVar} ${_maxIncludes} PARENT_SCOPE)
+endfunction()
+
+function (cotire_process_target_language _language _configurations _target _wholeTarget _cmdsVar)
+ set (${_cmdsVar} "" PARENT_SCOPE)
+ get_target_property(_targetSourceFiles ${_target} SOURCES)
+ set (_sourceFiles "")
+ set (_excludedSources "")
+ set (_cotiredSources "")
+ cotire_filter_language_source_files(${_language} ${_target} _sourceFiles _excludedSources _cotiredSources ${_targetSourceFiles})
+ if (NOT _sourceFiles AND NOT _cotiredSources)
+ return()
+ endif()
+ set (_cmds "")
+ # check for user provided unity source file list
+ get_property(_unitySourceFiles TARGET ${_target} PROPERTY COTIRE_${_language}_UNITY_SOURCE_INIT)
+ if (NOT _unitySourceFiles)
+ set (_unitySourceFiles ${_sourceFiles} ${_cotiredSources})
+ endif()
+ cotire_generate_target_script(
+ ${_language} "${_configurations}" ${_target} _targetScript _targetConfigScript ${_unitySourceFiles})
+ # set up unity files for parallel compilation
+ cotire_compute_unity_max_number_of_includes(${_target} _maxIncludes ${_unitySourceFiles})
+ cotire_make_unity_source_file_paths(${_language} ${_target} ${_maxIncludes} _unityFiles ${_unitySourceFiles})
+ list (LENGTH _unityFiles _numberOfUnityFiles)
+ if (_numberOfUnityFiles EQUAL 0)
+ return()
+ elseif (_numberOfUnityFiles GREATER 1)
+ cotire_setup_unity_generation_commands(
+ ${_language} ${_target} "${_targetScript}" "${_targetConfigScript}" "${_unityFiles}" _cmds ${_unitySourceFiles})
+ endif()
+ # set up single unity file for prefix header generation
+ cotire_make_single_unity_source_file_path(${_language} ${_target} _unityFile)
+ cotire_setup_unity_generation_commands(
+ ${_language} ${_target} "${_targetScript}" "${_targetConfigScript}" "${_unityFile}" _cmds ${_unitySourceFiles})
+ cotire_make_prefix_file_path(${_language} ${_target} _prefixFile)
+ # set up prefix header
+ if (_prefixFile)
+ # check for user provided prefix header files
+ get_property(_prefixHeaderFiles TARGET ${_target} PROPERTY COTIRE_${_language}_PREFIX_HEADER_INIT)
+ if (_prefixHeaderFiles)
+ cotire_setup_prefix_generation_from_provided_command(
+ ${_language} ${_target} "${_targetConfigScript}" "${_prefixFile}" _cmds ${_prefixHeaderFiles})
+ else()
+ cotire_setup_prefix_generation_from_unity_command(
+ ${_language} ${_target} "${_targetConfigScript}" "${_prefixFile}" "${_unityFile}" _cmds ${_unitySourceFiles})
+ endif()
+ # check if selected language has enough sources at all
+ list (LENGTH _sourceFiles _numberOfSources)
+ if (_numberOfSources LESS ${COTIRE_MINIMUM_NUMBER_OF_TARGET_SOURCES})
+ set (_targetUsePCH FALSE)
+ else()
+ get_target_property(_targetUsePCH ${_target} COTIRE_ENABLE_PRECOMPILED_HEADER)
+ endif()
+ if (_targetUsePCH)
+ cotire_make_pch_file_path(${_language} ${_target} _pchFile)
+ if (_pchFile)
+ # first file in _sourceFiles is passed as the host file
+ cotire_setup_pch_file_compilation(
+ ${_language} ${_target} "${_targetConfigScript}" "${_prefixFile}" "${_pchFile}" ${_sourceFiles})
+ cotire_setup_pch_file_inclusion(
+ ${_language} ${_target} ${_wholeTarget} "${_prefixFile}" "${_pchFile}" ${_sourceFiles})
+ endif()
+ elseif (_prefixHeaderFiles)
+ # user provided prefix header must be included unconditionally
+ cotire_setup_prefix_file_inclusion(${_language} ${_target} "${_prefixFile}" ${_sourceFiles})
+ endif()
+ endif()
+ # mark target as cotired for language
+ set_property(TARGET ${_target} PROPERTY COTIRE_${_language}_UNITY_SOURCE "${_unityFiles}")
+ if (_prefixFile)
+ set_property(TARGET ${_target} PROPERTY COTIRE_${_language}_PREFIX_HEADER "${_prefixFile}")
+ if (_targetUsePCH AND _pchFile)
+ set_property(TARGET ${_target} PROPERTY COTIRE_${_language}_PRECOMPILED_HEADER "${_pchFile}")
+ endif()
+ endif()
+ set (${_cmdsVar} ${_cmds} PARENT_SCOPE)
+endfunction()
+
+function (cotire_setup_clean_target _target)
+ set (_cleanTargetName "${_target}${COTIRE_CLEAN_TARGET_SUFFIX}")
+ if (NOT TARGET "${_cleanTargetName}")
+ cotire_set_cmd_to_prologue(_cmds)
+ get_filename_component(_outputDir "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}" ABSOLUTE)
+ list (APPEND _cmds -P "${COTIRE_CMAKE_MODULE_FILE}" "cleanup" "${_outputDir}" "${COTIRE_INTDIR}" "${_target}")
+ add_custom_target(${_cleanTargetName}
+ COMMAND ${_cmds}
+ WORKING_DIRECTORY "${CMAKE_BINARY_DIR}"
+ COMMENT "Cleaning up target ${_target} cotire generated files"
+ VERBATIM)
+ cotire_init_target("${_cleanTargetName}")
+ endif()
+endfunction()
+
+function (cotire_setup_pch_target _languages _configurations _target)
+ if ("${CMAKE_GENERATOR}" MATCHES "Make|Ninja")
+ # for makefile based generators, we add a custom target to trigger the generation of the cotire related files
+ set (_dependsFiles "")
+ foreach (_language ${_languages})
+ set (_props COTIRE_${_language}_PREFIX_HEADER COTIRE_${_language}_UNITY_SOURCE)
+ if (NOT CMAKE_${_language}_COMPILER_ID MATCHES "MSVC|Intel")
+ # Visual Studio and Intel only create precompiled header as a side effect
+ list (INSERT _props 0 COTIRE_${_language}_PRECOMPILED_HEADER)
+ endif()
+ cotire_get_first_set_property_value(_dependsFile TARGET ${_target} ${_props})
+ if (_dependsFile)
+ list (APPEND _dependsFiles "${_dependsFile}")
+ endif()
+ endforeach()
+ if (_dependsFiles)
+ set (_pchTargetName "${_target}${COTIRE_PCH_TARGET_SUFFIX}")
+ add_custom_target("${_pchTargetName}" DEPENDS ${_dependsFiles})
+ cotire_init_target("${_pchTargetName}")
+ cotire_add_to_pch_all_target(${_pchTargetName})
+ endif()
+ else()
+ # for other generators, we add the "clean all" target to clean up the precompiled header
+ cotire_setup_clean_all_target()
+ endif()
+endfunction()
+
+function (cotire_collect_unity_target_sources _target _languages _unityTargetSourcesVar)
+ get_target_property(_targetSourceFiles ${_target} SOURCES)
+ set (_unityTargetSources ${_targetSourceFiles})
+ foreach (_language ${_languages})
+ get_property(_unityFiles TARGET ${_target} PROPERTY COTIRE_${_language}_UNITY_SOURCE)
+ if (_unityFiles)
+ # remove source files that are included in the unity source
+ set (_sourceFiles "")
+ set (_excludedSources "")
+ set (_cotiredSources "")
+ cotire_filter_language_source_files(${_language} ${_target} _sourceFiles _excludedSources _cotiredSources ${_targetSourceFiles})
+ if (_sourceFiles OR _cotiredSources)
+ list (REMOVE_ITEM _unityTargetSources ${_sourceFiles} ${_cotiredSources})
+ endif()
+ # add unity source files instead
+ list (APPEND _unityTargetSources ${_unityFiles})
+ endif()
+ endforeach()
+ set (${_unityTargetSourcesVar} ${_unityTargetSources} PARENT_SCOPE)
+endfunction()
+
+function (cotire_setup_unity_target_pch_usage _languages _target)
+ foreach (_language ${_languages})
+ get_property(_unityFiles TARGET ${_target} PROPERTY COTIRE_${_language}_UNITY_SOURCE)
+ if (_unityFiles)
+ get_property(_userPrefixFile TARGET ${_target} PROPERTY COTIRE_${_language}_PREFIX_HEADER_INIT)
+ get_property(_prefixFile TARGET ${_target} PROPERTY COTIRE_${_language}_PREFIX_HEADER)
+ if (_userPrefixFile AND _prefixFile)
+ # user provided prefix header must be included unconditionally by unity sources
+ cotire_setup_prefix_file_inclusion(${_language} ${_target} "${_prefixFile}" ${_unityFiles})
+ endif()
+ endif()
+ endforeach()
+endfunction()
+
+function (cotire_setup_unity_build_target _languages _configurations _target)
+ get_target_property(_unityTargetName ${_target} COTIRE_UNITY_TARGET_NAME)
+ if (NOT _unityTargetName)
+ set (_unityTargetName "${_target}${COTIRE_UNITY_BUILD_TARGET_SUFFIX}")
+ endif()
+ # determine unity target sub type
+ get_target_property(_targetType ${_target} TYPE)
+ if ("${_targetType}" STREQUAL "EXECUTABLE")
+ set (_unityTargetSubType "")
+ elseif (_targetType MATCHES "(STATIC|SHARED|MODULE|OBJECT)_LIBRARY")
+ set (_unityTargetSubType "${CMAKE_MATCH_1}")
+ else()
+ message (WARNING "cotire: target ${_target} has unknown target type ${_targetType}.")
+ return()
+ endif()
+ # determine unity target sources
+ set (_unityTargetSources "")
+ cotire_collect_unity_target_sources(${_target} "${_languages}" _unityTargetSources)
+ # handle automatic Qt processing
+ get_target_property(_targetAutoMoc ${_target} AUTOMOC)
+ get_target_property(_targetAutoUic ${_target} AUTOUIC)
+ get_target_property(_targetAutoRcc ${_target} AUTORCC)
+ if (_targetAutoMoc OR _targetAutoUic OR _targetAutoRcc)
+ # if the original target sources are subject to CMake's automatic Qt processing,
+ # also include implicitly generated _automoc.cpp file
+ list (APPEND _unityTargetSources "${_target}_automoc.cpp")
+ set_property (SOURCE "${_target}_automoc.cpp" PROPERTY GENERATED TRUE)
+ endif()
+ # prevent AUTOMOC, AUTOUIC and AUTORCC properties from being set when the unity target is created
+ set (CMAKE_AUTOMOC OFF)
+ set (CMAKE_AUTOUIC OFF)
+ set (CMAKE_AUTORCC OFF)
+ if (COTIRE_DEBUG)
+ message (STATUS "add target ${_targetType} ${_unityTargetName} ${_unityTargetSubType} EXCLUDE_FROM_ALL ${_unityTargetSources}")
+ endif()
+ # generate unity target
+ if ("${_targetType}" STREQUAL "EXECUTABLE")
+ add_executable(${_unityTargetName} ${_unityTargetSubType} EXCLUDE_FROM_ALL ${_unityTargetSources})
+ else()
+ add_library(${_unityTargetName} ${_unityTargetSubType} EXCLUDE_FROM_ALL ${_unityTargetSources})
+ endif()
+ if (_targetAutoMoc OR _targetAutoUic OR _targetAutoRcc)
+ # depend on the original target's implicity generated _automoc target
+ add_dependencies(${_unityTargetName} ${_target}_automoc)
+ endif()
+ # copy output location properties
+ set (_outputDirProperties
+ ARCHIVE_OUTPUT_DIRECTORY ARCHIVE_OUTPUT_DIRECTORY_
+ LIBRARY_OUTPUT_DIRECTORY LIBRARY_OUTPUT_DIRECTORY_
+ RUNTIME_OUTPUT_DIRECTORY RUNTIME_OUTPUT_DIRECTORY_)
+ if (COTIRE_UNITY_OUTPUT_DIRECTORY)
+ set (_setDefaultOutputDir TRUE)
+ if (IS_ABSOLUTE "${COTIRE_UNITY_OUTPUT_DIRECTORY}")
+ set (_outputDir "${COTIRE_UNITY_OUTPUT_DIRECTORY}")
+ else()
+ # append relative COTIRE_UNITY_OUTPUT_DIRECTORY to target's actual output directory
+ cotire_copy_set_properites("${_configurations}" TARGET ${_target} ${_unityTargetName} ${_outputDirProperties})
+ cotire_resolve_config_properites("${_configurations}" _properties ${_outputDirProperties})
+ foreach (_property ${_properties})
+ get_property(_outputDir TARGET ${_target} PROPERTY ${_property})
+ if (_outputDir)
+ get_filename_component(_outputDir "${_outputDir}/${COTIRE_UNITY_OUTPUT_DIRECTORY}" ABSOLUTE)
+ set_property(TARGET ${_unityTargetName} PROPERTY ${_property} "${_outputDir}")
+ set (_setDefaultOutputDir FALSE)
+ endif()
+ endforeach()
+ if (_setDefaultOutputDir)
+ get_filename_component(_outputDir "${CMAKE_CURRENT_BINARY_DIR}/${COTIRE_UNITY_OUTPUT_DIRECTORY}" ABSOLUTE)
+ endif()
+ endif()
+ if (_setDefaultOutputDir)
+ set_target_properties(${_unityTargetName} PROPERTIES
+ ARCHIVE_OUTPUT_DIRECTORY "${_outputDir}"
+ LIBRARY_OUTPUT_DIRECTORY "${_outputDir}"
+ RUNTIME_OUTPUT_DIRECTORY "${_outputDir}")
+ endif()
+ else()
+ cotire_copy_set_properites("${_configurations}" TARGET ${_target} ${_unityTargetName}
+ ${_outputDirProperties})
+ endif()
+ # copy output name
+ cotire_copy_set_properites("${_configurations}" TARGET ${_target} ${_unityTargetName}
+ ARCHIVE_OUTPUT_NAME ARCHIVE_OUTPUT_NAME_
+ LIBRARY_OUTPUT_NAME LIBRARY_OUTPUT_NAME_
+ OUTPUT_NAME OUTPUT_NAME_
+ RUNTIME_OUTPUT_NAME RUNTIME_OUTPUT_NAME_
+ PREFIX _POSTFIX SUFFIX
+ IMPORT_PREFIX IMPORT_SUFFIX)
+ # copy compile stuff
+ cotire_copy_set_properites("${_configurations}" TARGET ${_target} ${_unityTargetName}
+ COMPILE_DEFINITIONS COMPILE_DEFINITIONS_
+ COMPILE_FLAGS COMPILE_OPTIONS
+ Fortran_FORMAT Fortran_MODULE_DIRECTORY
+ INCLUDE_DIRECTORIES
+ INTERPROCEDURAL_OPTIMIZATION INTERPROCEDURAL_OPTIMIZATION_
+ POSITION_INDEPENDENT_CODE
+ C_COMPILER_LAUNCHER CXX_COMPILER_LAUNCHER
+ C_INCLUDE_WHAT_YOU_USE CXX_INCLUDE_WHAT_YOU_USE
+ C_VISIBILITY_PRESET CXX_VISIBILITY_PRESET VISIBILITY_INLINES_HIDDEN)
+ # copy compile features
+ cotire_copy_set_properites("${_configurations}" TARGET ${_target} ${_unityTargetName}
+ C_EXTENSIONS C_STANDARD C_STANDARD_REQUIRED
+ CXX_EXTENSIONS CXX_STANDARD CXX_STANDARD_REQUIRED
+ COMPILE_FEATURES)
+ # copy interface stuff
+ cotire_copy_set_properites("${_configurations}" TARGET ${_target} ${_unityTargetName}
+ COMPATIBLE_INTERFACE_BOOL COMPATIBLE_INTERFACE_NUMBER_MAX COMPATIBLE_INTERFACE_NUMBER_MIN
+ COMPATIBLE_INTERFACE_STRING
+ INTERFACE_COMPILE_DEFINITIONS INTERFACE_COMPILE_FEATURES INTERFACE_COMPILE_OPTIONS
+ INTERFACE_INCLUDE_DIRECTORIES INTERFACE_SOURCES
+ INTERFACE_POSITION_INDEPENDENT_CODE INTERFACE_SYSTEM_INCLUDE_DIRECTORIES
+ INTERFACE_AUTOUIC_OPTIONS NO_SYSTEM_FROM_IMPORTED)
+ # copy link stuff
+ cotire_copy_set_properites("${_configurations}" TARGET ${_target} ${_unityTargetName}
+ BUILD_WITH_INSTALL_RPATH INSTALL_RPATH INSTALL_RPATH_USE_LINK_PATH SKIP_BUILD_RPATH
+ LINKER_LANGUAGE LINK_DEPENDS LINK_DEPENDS_NO_SHARED
+ LINK_FLAGS LINK_FLAGS_
+ LINK_INTERFACE_LIBRARIES LINK_INTERFACE_LIBRARIES_
+ LINK_INTERFACE_MULTIPLICITY LINK_INTERFACE_MULTIPLICITY_
+ LINK_SEARCH_START_STATIC LINK_SEARCH_END_STATIC
+ STATIC_LIBRARY_FLAGS STATIC_LIBRARY_FLAGS_
+ NO_SONAME SOVERSION VERSION)
+ # copy cmake stuff
+ cotire_copy_set_properites("${_configurations}" TARGET ${_target} ${_unityTargetName}
+ IMPLICIT_DEPENDS_INCLUDE_TRANSFORM RULE_LAUNCH_COMPILE RULE_LAUNCH_CUSTOM RULE_LAUNCH_LINK)
+ # copy Apple platform specific stuff
+ cotire_copy_set_properites("${_configurations}" TARGET ${_target} ${_unityTargetName}
+ BUNDLE BUNDLE_EXTENSION FRAMEWORK FRAMEWORK_VERSION INSTALL_NAME_DIR
+ MACOSX_BUNDLE MACOSX_BUNDLE_INFO_PLIST MACOSX_FRAMEWORK_INFO_PLIST MACOSX_RPATH
+ OSX_ARCHITECTURES OSX_ARCHITECTURES_ PRIVATE_HEADER PUBLIC_HEADER RESOURCE XCTEST)
+ # copy Windows platform specific stuff
+ cotire_copy_set_properites("${_configurations}" TARGET ${_target} ${_unityTargetName}
+ GNUtoMS
+ COMPILE_PDB_NAME COMPILE_PDB_NAME_
+ COMPILE_PDB_OUTPUT_DIRECTORY COMPILE_PDB_OUTPUT_DIRECTORY_
+ PDB_NAME PDB_NAME_ PDB_OUTPUT_DIRECTORY PDB_OUTPUT_DIRECTORY_
+ VS_DESKTOP_EXTENSIONS_VERSION VS_DOTNET_REFERENCES VS_DOTNET_TARGET_FRAMEWORK_VERSION
+ VS_GLOBAL_KEYWORD VS_GLOBAL_PROJECT_TYPES VS_GLOBAL_ROOTNAMESPACE
+ VS_IOT_EXTENSIONS_VERSION VS_IOT_STARTUP_TASK
+ VS_KEYWORD VS_MOBILE_EXTENSIONS_VERSION
+ VS_SCC_AUXPATH VS_SCC_LOCALPATH VS_SCC_PROJECTNAME VS_SCC_PROVIDER
+ VS_WINDOWS_TARGET_PLATFORM_MIN_VERSION
+ VS_WINRT_COMPONENT VS_WINRT_EXTENSIONS VS_WINRT_REFERENCES
+ WIN32_EXECUTABLE WINDOWS_EXPORT_ALL_SYMBOLS)
+ # copy Android platform specific stuff
+ cotire_copy_set_properites("${_configurations}" TARGET ${_target} ${_unityTargetName}
+ ANDROID_API ANDROID_API_MIN ANDROID_GUI
+ ANDROID_ANT_ADDITIONAL_OPTIONS ANDROID_ARCH ANDROID_ASSETS_DIRECTORIES
+ ANDROID_JAR_DEPENDENCIES ANDROID_JAR_DIRECTORIES ANDROID_JAVA_SOURCE_DIR
+ ANDROID_NATIVE_LIB_DEPENDENCIES ANDROID_NATIVE_LIB_DIRECTORIES
+ ANDROID_PROCESS_MAX ANDROID_PROGUARD ANDROID_PROGUARD_CONFIG_PATH
+ ANDROID_SECURE_PROPS_PATH ANDROID_SKIP_ANT_STEP ANDROID_STL_TYPE)
+ # use output name from original target
+ get_target_property(_targetOutputName ${_unityTargetName} OUTPUT_NAME)
+ if (NOT _targetOutputName)
+ set_property(TARGET ${_unityTargetName} PROPERTY OUTPUT_NAME "${_target}")
+ endif()
+ # use export symbol from original target
+ cotire_get_target_export_symbol("${_target}" _defineSymbol)
+ if (_defineSymbol)
+ set_property(TARGET ${_unityTargetName} PROPERTY DEFINE_SYMBOL "${_defineSymbol}")
+ if ("${_targetType}" STREQUAL "EXECUTABLE")
+ set_property(TARGET ${_unityTargetName} PROPERTY ENABLE_EXPORTS TRUE)
+ endif()
+ endif()
+ cotire_init_target(${_unityTargetName})
+ cotire_add_to_unity_all_target(${_unityTargetName})
+ set_property(TARGET ${_target} PROPERTY COTIRE_UNITY_TARGET_NAME "${_unityTargetName}")
+endfunction(cotire_setup_unity_build_target)
+
+function (cotire_target _target)
+ set(_options "")
+ set(_oneValueArgs "")
+ set(_multiValueArgs LANGUAGES CONFIGURATIONS)
+ cmake_parse_arguments(_option "${_options}" "${_oneValueArgs}" "${_multiValueArgs}" ${ARGN})
+ if (NOT _option_LANGUAGES)
+ get_property (_option_LANGUAGES GLOBAL PROPERTY ENABLED_LANGUAGES)
+ endif()
+ if (NOT _option_CONFIGURATIONS)
+ cotire_get_configuration_types(_option_CONFIGURATIONS)
+ endif()
+ # trivial checks
+ get_target_property(_imported ${_target} IMPORTED)
+ if (_imported)
+ message (WARNING "cotire: imported target ${_target} cannot be cotired.")
+ return()
+ endif()
+ # resolve alias
+ get_target_property(_aliasName ${_target} ALIASED_TARGET)
+ if (_aliasName)
+ if (COTIRE_DEBUG)
+ message (STATUS "${_target} is an alias. Applying cotire to aliased target ${_aliasName} instead.")
+ endif()
+ set (_target ${_aliasName})
+ endif()
+ # check if target needs to be cotired for build type
+ # when using configuration types, the test is performed at build time
+ cotire_init_cotire_target_properties(${_target})
+ if (NOT CMAKE_CONFIGURATION_TYPES)
+ if (CMAKE_BUILD_TYPE)
+ list (FIND _option_CONFIGURATIONS "${CMAKE_BUILD_TYPE}" _index)
+ else()
+ list (FIND _option_CONFIGURATIONS "None" _index)
+ endif()
+ if (_index EQUAL -1)
+ if (COTIRE_DEBUG)
+ message (STATUS "CMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE} not cotired (${_option_CONFIGURATIONS})")
+ endif()
+ return()
+ endif()
+ endif()
+ # when not using configuration types, immediately create cotire intermediate dir
+ if (NOT CMAKE_CONFIGURATION_TYPES)
+ cotire_get_intermediate_dir(_baseDir)
+ file (MAKE_DIRECTORY "${_baseDir}")
+ endif()
+ # choose languages that apply to the target
+ cotire_choose_target_languages("${_target}" _targetLanguages _wholeTarget ${_option_LANGUAGES})
+ if (NOT _targetLanguages)
+ return()
+ endif()
+ set (_cmds "")
+ foreach (_language ${_targetLanguages})
+ cotire_process_target_language("${_language}" "${_option_CONFIGURATIONS}" ${_target} ${_wholeTarget} _cmd)
+ if (_cmd)
+ list (APPEND _cmds ${_cmd})
+ endif()
+ endforeach()
+ get_target_property(_targetAddSCU ${_target} COTIRE_ADD_UNITY_BUILD)
+ if (_targetAddSCU)
+ cotire_setup_unity_build_target("${_targetLanguages}" "${_option_CONFIGURATIONS}" ${_target})
+ endif()
+ get_target_property(_targetUsePCH ${_target} COTIRE_ENABLE_PRECOMPILED_HEADER)
+ if (_targetUsePCH)
+ cotire_setup_target_pch_usage("${_targetLanguages}" ${_target} ${_wholeTarget} ${_cmds})
+ cotire_setup_pch_target("${_targetLanguages}" "${_option_CONFIGURATIONS}" ${_target})
+ if (_targetAddSCU)
+ cotire_setup_unity_target_pch_usage("${_targetLanguages}" ${_target})
+ endif()
+ endif()
+ get_target_property(_targetAddCleanTarget ${_target} COTIRE_ADD_CLEAN)
+ if (_targetAddCleanTarget)
+ cotire_setup_clean_target(${_target})
+ endif()
+endfunction(cotire_target)
+
+function (cotire_map_libraries _strategy _mappedLibrariesVar)
+ set (_mappedLibraries "")
+ foreach (_library ${ARGN})
+ if (TARGET "${_library}" AND "${_strategy}" MATCHES "COPY_UNITY")
+ # use target's corresponding unity target, if available
+ get_target_property(_libraryUnityTargetName ${_library} COTIRE_UNITY_TARGET_NAME)
+ if (TARGET "${_libraryUnityTargetName}")
+ list (APPEND _mappedLibraries "${_libraryUnityTargetName}")
+ else()
+ list (APPEND _mappedLibraries "${_library}")
+ endif()
+ else()
+ list (APPEND _mappedLibraries "${_library}")
+ endif()
+ endforeach()
+ list (REMOVE_DUPLICATES _mappedLibraries)
+ set (${_mappedLibrariesVar} ${_mappedLibraries} PARENT_SCOPE)
+endfunction()
+
+function (cotire_target_link_libraries _target)
+ get_target_property(_unityTargetName ${_target} COTIRE_UNITY_TARGET_NAME)
+ if (TARGET "${_unityTargetName}")
+ get_target_property(_linkLibrariesStrategy ${_target} COTIRE_UNITY_LINK_LIBRARIES_INIT)
+ if (COTIRE_DEBUG)
+ message (STATUS "unity target ${_unityTargetName} link strategy: ${_linkLibrariesStrategy}")
+ endif()
+ if ("${_linkLibrariesStrategy}" MATCHES "^(COPY|COPY_UNITY)$")
+ set (_unityLinkLibraries "")
+ get_target_property(_linkLibraries ${_target} LINK_LIBRARIES)
+ if (_linkLibraries)
+ list (APPEND _unityLinkLibraries ${_linkLibraries})
+ endif()
+ get_target_property(_interfaceLinkLibraries ${_target} INTERFACE_LINK_LIBRARIES)
+ if (_interfaceLinkLibraries)
+ list (APPEND _unityLinkLibraries ${_interfaceLinkLibraries})
+ endif()
+ cotire_map_libraries("${_linkLibrariesStrategy}" _unityLinkLibraries ${_unityLinkLibraries})
+ if (COTIRE_DEBUG)
+ message (STATUS "unity target ${_unityTargetName} libraries: ${_unityLinkLibraries}")
+ endif()
+ if (_unityLinkLibraries)
+ target_link_libraries(${_unityTargetName} ${_unityLinkLibraries})
+ endif()
+ endif()
+ endif()
+endfunction(cotire_target_link_libraries)
+
+function (cotire_cleanup _binaryDir _cotireIntermediateDirName _targetName)
+ if (_targetName)
+ file (GLOB_RECURSE _cotireFiles "${_binaryDir}/${_targetName}*.*")
+ else()
+ file (GLOB_RECURSE _cotireFiles "${_binaryDir}/*.*")
+ endif()
+ # filter files in intermediate directory
+ set (_filesToRemove "")
+ foreach (_file ${_cotireFiles})
+ get_filename_component(_dir "${_file}" DIRECTORY)
+ get_filename_component(_dirName "${_dir}" NAME)
+ if ("${_dirName}" STREQUAL "${_cotireIntermediateDirName}")
+ list (APPEND _filesToRemove "${_file}")
+ endif()
+ endforeach()
+ if (_filesToRemove)
+ if (COTIRE_VERBOSE)
+ message (STATUS "cleaning up ${_filesToRemove}")
+ endif()
+ file (REMOVE ${_filesToRemove})
+ endif()
+endfunction()
+
+function (cotire_init_target _targetName)
+ if (COTIRE_TARGETS_FOLDER)
+ set_target_properties(${_targetName} PROPERTIES FOLDER "${COTIRE_TARGETS_FOLDER}")
+ endif()
+ set_target_properties(${_targetName} PROPERTIES EXCLUDE_FROM_ALL TRUE)
+ if (MSVC_IDE)
+ set_target_properties(${_targetName} PROPERTIES EXCLUDE_FROM_DEFAULT_BUILD TRUE)
+ endif()
+endfunction()
+
+function (cotire_add_to_pch_all_target _pchTargetName)
+ set (_targetName "${COTIRE_PCH_ALL_TARGET_NAME}")
+ if (NOT TARGET "${_targetName}")
+ add_custom_target("${_targetName}"
+ WORKING_DIRECTORY "${CMAKE_BINARY_DIR}"
+ VERBATIM)
+ cotire_init_target("${_targetName}")
+ endif()
+ cotire_setup_clean_all_target()
+ add_dependencies(${_targetName} ${_pchTargetName})
+endfunction()
+
+function (cotire_add_to_unity_all_target _unityTargetName)
+ set (_targetName "${COTIRE_UNITY_BUILD_ALL_TARGET_NAME}")
+ if (NOT TARGET "${_targetName}")
+ add_custom_target("${_targetName}"
+ WORKING_DIRECTORY "${CMAKE_BINARY_DIR}"
+ VERBATIM)
+ cotire_init_target("${_targetName}")
+ endif()
+ cotire_setup_clean_all_target()
+ add_dependencies(${_targetName} ${_unityTargetName})
+endfunction()
+
+function (cotire_setup_clean_all_target)
+ set (_targetName "${COTIRE_CLEAN_ALL_TARGET_NAME}")
+ if (NOT TARGET "${_targetName}")
+ cotire_set_cmd_to_prologue(_cmds)
+ list (APPEND _cmds -P "${COTIRE_CMAKE_MODULE_FILE}" "cleanup" "${CMAKE_BINARY_DIR}" "${COTIRE_INTDIR}")
+ add_custom_target(${_targetName}
+ COMMAND ${_cmds}
+ WORKING_DIRECTORY "${CMAKE_BINARY_DIR}"
+ COMMENT "Cleaning up all cotire generated files"
+ VERBATIM)
+ cotire_init_target("${_targetName}")
+ endif()
+endfunction()
+
+function (cotire)
+ set(_options "")
+ set(_oneValueArgs "")
+ set(_multiValueArgs LANGUAGES CONFIGURATIONS)
+ cmake_parse_arguments(_option "${_options}" "${_oneValueArgs}" "${_multiValueArgs}" ${ARGN})
+ set (_targets ${_option_UNPARSED_ARGUMENTS})
+ foreach (_target ${_targets})
+ if (TARGET ${_target})
+ cotire_target(${_target} LANGUAGES ${_option_LANGUAGES} CONFIGURATIONS ${_option_CONFIGURATIONS})
+ else()
+ message (WARNING "cotire: ${_target} is not a target.")
+ endif()
+ endforeach()
+ foreach (_target ${_targets})
+ if (TARGET ${_target})
+ cotire_target_link_libraries(${_target})
+ endif()
+ endforeach()
+endfunction()
+
+if (CMAKE_SCRIPT_MODE_FILE)
+
+ # cotire is being run in script mode
+ # locate -P on command args
+ set (COTIRE_ARGC -1)
+ foreach (_index RANGE ${CMAKE_ARGC})
+ if (COTIRE_ARGC GREATER -1)
+ set (COTIRE_ARGV${COTIRE_ARGC} "${CMAKE_ARGV${_index}}")
+ math (EXPR COTIRE_ARGC "${COTIRE_ARGC} + 1")
+ elseif ("${CMAKE_ARGV${_index}}" STREQUAL "-P")
+ set (COTIRE_ARGC 0)
+ endif()
+ endforeach()
+
+ # include target script if available
+ if ("${COTIRE_ARGV2}" MATCHES "\\.cmake$")
+ # the included target scripts sets up additional variables relating to the target (e.g., COTIRE_TARGET_SOURCES)
+ include("${COTIRE_ARGV2}")
+ endif()
+
+ if (COTIRE_DEBUG)
+ message (STATUS "${COTIRE_ARGV0} ${COTIRE_ARGV1} ${COTIRE_ARGV2} ${COTIRE_ARGV3} ${COTIRE_ARGV4} ${COTIRE_ARGV5}")
+ endif()
+
+ if (NOT COTIRE_BUILD_TYPE)
+ set (COTIRE_BUILD_TYPE "None")
+ endif()
+ string (TOUPPER "${COTIRE_BUILD_TYPE}" _upperConfig)
+ set (_includeDirs ${COTIRE_TARGET_INCLUDE_DIRECTORIES_${_upperConfig}})
+ set (_systemIncludeDirs ${COTIRE_TARGET_SYSTEM_INCLUDE_DIRECTORIES_${_upperConfig}})
+ set (_compileDefinitions ${COTIRE_TARGET_COMPILE_DEFINITIONS_${_upperConfig}})
+ set (_compileFlags ${COTIRE_TARGET_COMPILE_FLAGS_${_upperConfig}})
+ # check if target has been cotired for actual build type COTIRE_BUILD_TYPE
+ list (FIND COTIRE_TARGET_CONFIGURATION_TYPES "${COTIRE_BUILD_TYPE}" _index)
+ if (_index GREATER -1)
+ set (_sources ${COTIRE_TARGET_SOURCES})
+ set (_sourcesDefinitions ${COTIRE_TARGET_SOURCES_COMPILE_DEFINITIONS_${_upperConfig}})
+ else()
+ if (COTIRE_DEBUG)
+ message (STATUS "COTIRE_BUILD_TYPE=${COTIRE_BUILD_TYPE} not cotired (${COTIRE_TARGET_CONFIGURATION_TYPES})")
+ endif()
+ set (_sources "")
+ set (_sourcesDefinitions "")
+ endif()
+ set (_targetPreUndefs ${COTIRE_TARGET_PRE_UNDEFS})
+ set (_targetPostUndefs ${COTIRE_TARGET_POST_UNDEFS})
+ set (_sourcesPreUndefs ${COTIRE_TARGET_SOURCES_PRE_UNDEFS})
+ set (_sourcesPostUndefs ${COTIRE_TARGET_SOURCES_POST_UNDEFS})
+
+ if ("${COTIRE_ARGV1}" STREQUAL "unity")
+
+ if (XCODE)
+ # executing pre-build action under Xcode, check dependency on target script
+ set (_dependsOption DEPENDS "${COTIRE_ARGV2}")
+ else()
+ # executing custom command, no need to re-check for dependencies
+ set (_dependsOption "")
+ endif()
+
+ cotire_select_unity_source_files("${COTIRE_ARGV3}" _sources ${_sources})
+
+ cotire_generate_unity_source(
+ "${COTIRE_ARGV3}" ${_sources}
+ LANGUAGE "${COTIRE_TARGET_LANGUAGE}"
+ SOURCES_COMPILE_DEFINITIONS ${_sourcesDefinitions}
+ PRE_UNDEFS ${_targetPreUndefs}
+ POST_UNDEFS ${_targetPostUndefs}
+ SOURCES_PRE_UNDEFS ${_sourcesPreUndefs}
+ SOURCES_POST_UNDEFS ${_sourcesPostUndefs}
+ ${_dependsOption})
+
+ elseif ("${COTIRE_ARGV1}" STREQUAL "prefix")
+
+ if (XCODE)
+ # executing pre-build action under Xcode, check dependency on unity file and prefix dependencies
+ set (_dependsOption DEPENDS "${COTIRE_ARGV4}" ${COTIRE_TARGET_PREFIX_DEPENDS})
+ else()
+ # executing custom command, no need to re-check for dependencies
+ set (_dependsOption "")
+ endif()
+
+ set (_files "")
+ foreach (_index RANGE 4 ${COTIRE_ARGC})
+ if (COTIRE_ARGV${_index})
+ list (APPEND _files "${COTIRE_ARGV${_index}}")
+ endif()
+ endforeach()
+
+ cotire_generate_prefix_header(
+ "${COTIRE_ARGV3}" ${_files}
+ COMPILER_EXECUTABLE "${CMAKE_${COTIRE_TARGET_LANGUAGE}_COMPILER}"
+ COMPILER_ARG1 ${CMAKE_${COTIRE_TARGET_LANGUAGE}_COMPILER_ARG1}
+ COMPILER_ID "${CMAKE_${COTIRE_TARGET_LANGUAGE}_COMPILER_ID}"
+ COMPILER_VERSION "${CMAKE_${COTIRE_TARGET_LANGUAGE}_COMPILER_VERSION}"
+ LANGUAGE "${COTIRE_TARGET_LANGUAGE}"
+ IGNORE_PATH "${COTIRE_TARGET_IGNORE_PATH};${COTIRE_ADDITIONAL_PREFIX_HEADER_IGNORE_PATH}"
+ INCLUDE_PATH ${COTIRE_TARGET_INCLUDE_PATH}
+ IGNORE_EXTENSIONS "${CMAKE_${COTIRE_TARGET_LANGUAGE}_SOURCE_FILE_EXTENSIONS};${COTIRE_ADDITIONAL_PREFIX_HEADER_IGNORE_EXTENSIONS}"
+ INCLUDE_PRIORITY_PATH ${COTIRE_TARGET_INCLUDE_PRIORITY_PATH}
+ INCLUDE_DIRECTORIES ${_includeDirs}
+ SYSTEM_INCLUDE_DIRECTORIES ${_systemIncludeDirs}
+ COMPILE_DEFINITIONS ${_compileDefinitions}
+ COMPILE_FLAGS ${_compileFlags}
+ ${_dependsOption})
+
+ elseif ("${COTIRE_ARGV1}" STREQUAL "precompile")
+
+ set (_files "")
+ foreach (_index RANGE 5 ${COTIRE_ARGC})
+ if (COTIRE_ARGV${_index})
+ list (APPEND _files "${COTIRE_ARGV${_index}}")
+ endif()
+ endforeach()
+
+ cotire_precompile_prefix_header(
+ "${COTIRE_ARGV3}" "${COTIRE_ARGV4}" "${COTIRE_ARGV5}"
+ COMPILER_EXECUTABLE "${CMAKE_${COTIRE_TARGET_LANGUAGE}_COMPILER}"
+ COMPILER_ARG1 ${CMAKE_${COTIRE_TARGET_LANGUAGE}_COMPILER_ARG1}
+ COMPILER_ID "${CMAKE_${COTIRE_TARGET_LANGUAGE}_COMPILER_ID}"
+ COMPILER_VERSION "${CMAKE_${COTIRE_TARGET_LANGUAGE}_COMPILER_VERSION}"
+ LANGUAGE "${COTIRE_TARGET_LANGUAGE}"
+ INCLUDE_DIRECTORIES ${_includeDirs}
+ SYSTEM_INCLUDE_DIRECTORIES ${_systemIncludeDirs}
+ COMPILE_DEFINITIONS ${_compileDefinitions}
+ COMPILE_FLAGS ${_compileFlags})
+
+ elseif ("${COTIRE_ARGV1}" STREQUAL "combine")
+
+ if (COTIRE_TARGET_LANGUAGE)
+ set (_combinedFile "${COTIRE_ARGV3}")
+ set (_startIndex 4)
+ else()
+ set (_combinedFile "${COTIRE_ARGV2}")
+ set (_startIndex 3)
+ endif()
+ set (_files "")
+ foreach (_index RANGE ${_startIndex} ${COTIRE_ARGC})
+ if (COTIRE_ARGV${_index})
+ list (APPEND _files "${COTIRE_ARGV${_index}}")
+ endif()
+ endforeach()
+
+ if (XCODE)
+ # executing pre-build action under Xcode, check dependency on files to be combined
+ set (_dependsOption DEPENDS ${_files})
+ else()
+ # executing custom command, no need to re-check for dependencies
+ set (_dependsOption "")
+ endif()
+
+ if (COTIRE_TARGET_LANGUAGE)
+ cotire_generate_unity_source(
+ "${_combinedFile}" ${_files}
+ LANGUAGE "${COTIRE_TARGET_LANGUAGE}"
+ ${_dependsOption})
+ else()
+ cotire_generate_unity_source("${_combinedFile}" ${_files} ${_dependsOption})
+ endif()
+
+ elseif ("${COTIRE_ARGV1}" STREQUAL "cleanup")
+
+ cotire_cleanup("${COTIRE_ARGV2}" "${COTIRE_ARGV3}" "${COTIRE_ARGV4}")
+
+ else()
+ message (FATAL_ERROR "cotire: unknown command \"${COTIRE_ARGV1}\".")
+ endif()
+
+else()
+
+ # cotire is being run in include mode
+ # set up all variable and property definitions
+
+ if (NOT DEFINED COTIRE_DEBUG_INIT)
+ if (DEFINED COTIRE_DEBUG)
+ set (COTIRE_DEBUG_INIT ${COTIRE_DEBUG})
+ else()
+ set (COTIRE_DEBUG_INIT FALSE)
+ endif()
+ endif()
+ option (COTIRE_DEBUG "Enable cotire debugging output?" ${COTIRE_DEBUG_INIT})
+
+ if (NOT DEFINED COTIRE_VERBOSE_INIT)
+ if (DEFINED COTIRE_VERBOSE)
+ set (COTIRE_VERBOSE_INIT ${COTIRE_VERBOSE})
+ else()
+ set (COTIRE_VERBOSE_INIT FALSE)
+ endif()
+ endif()
+ option (COTIRE_VERBOSE "Enable cotire verbose output?" ${COTIRE_VERBOSE_INIT})
+
+ set (COTIRE_ADDITIONAL_PREFIX_HEADER_IGNORE_EXTENSIONS "inc;inl;ipp" CACHE STRING
+ "Ignore headers with the listed file extensions from the generated prefix header.")
+
+ set (COTIRE_ADDITIONAL_PREFIX_HEADER_IGNORE_PATH "" CACHE STRING
+ "Ignore headers from these directories when generating the prefix header.")
+
+ set (COTIRE_UNITY_SOURCE_EXCLUDE_EXTENSIONS "m;mm" CACHE STRING
+ "Ignore sources with the listed file extensions from the generated unity source.")
+
+ set (COTIRE_MINIMUM_NUMBER_OF_TARGET_SOURCES "3" CACHE STRING
+ "Minimum number of sources in target required to enable use of precompiled header.")
+
+ if (NOT DEFINED COTIRE_MAXIMUM_NUMBER_OF_UNITY_INCLUDES_INIT)
+ if (DEFINED COTIRE_MAXIMUM_NUMBER_OF_UNITY_INCLUDES)
+ set (COTIRE_MAXIMUM_NUMBER_OF_UNITY_INCLUDES_INIT ${COTIRE_MAXIMUM_NUMBER_OF_UNITY_INCLUDES})
+ elseif ("${CMAKE_GENERATOR}" MATCHES "JOM|Ninja|Visual Studio")
+ # enable parallelization for generators that run multiple jobs by default
+ set (COTIRE_MAXIMUM_NUMBER_OF_UNITY_INCLUDES_INIT "-j")
+ else()
+ set (COTIRE_MAXIMUM_NUMBER_OF_UNITY_INCLUDES_INIT "0")
+ endif()
+ endif()
+ set (COTIRE_MAXIMUM_NUMBER_OF_UNITY_INCLUDES "${COTIRE_MAXIMUM_NUMBER_OF_UNITY_INCLUDES_INIT}" CACHE STRING
+ "Maximum number of source files to include in a single unity source file.")
+
+ if (NOT COTIRE_PREFIX_HEADER_FILENAME_SUFFIX)
+ set (COTIRE_PREFIX_HEADER_FILENAME_SUFFIX "_prefix")
+ endif()
+ if (NOT COTIRE_UNITY_SOURCE_FILENAME_SUFFIX)
+ set (COTIRE_UNITY_SOURCE_FILENAME_SUFFIX "_unity")
+ endif()
+ if (NOT COTIRE_INTDIR)
+ set (COTIRE_INTDIR "cotire")
+ endif()
+ if (NOT COTIRE_PCH_ALL_TARGET_NAME)
+ set (COTIRE_PCH_ALL_TARGET_NAME "all_pch")
+ endif()
+ if (NOT COTIRE_UNITY_BUILD_ALL_TARGET_NAME)
+ set (COTIRE_UNITY_BUILD_ALL_TARGET_NAME "all_unity")
+ endif()
+ if (NOT COTIRE_CLEAN_ALL_TARGET_NAME)
+ set (COTIRE_CLEAN_ALL_TARGET_NAME "clean_cotire")
+ endif()
+ if (NOT COTIRE_CLEAN_TARGET_SUFFIX)
+ set (COTIRE_CLEAN_TARGET_SUFFIX "_clean_cotire")
+ endif()
+ if (NOT COTIRE_PCH_TARGET_SUFFIX)
+ set (COTIRE_PCH_TARGET_SUFFIX "_pch")
+ endif()
+ if (MSVC)
+ # MSVC default PCH memory scaling factor of 100 percent (75 MB) is too small for template heavy C++ code
+ # use a bigger default factor of 170 percent (128 MB)
+ if (NOT DEFINED COTIRE_PCH_MEMORY_SCALING_FACTOR)
+ set (COTIRE_PCH_MEMORY_SCALING_FACTOR "170")
+ endif()
+ endif()
+ if (NOT COTIRE_UNITY_BUILD_TARGET_SUFFIX)
+ set (COTIRE_UNITY_BUILD_TARGET_SUFFIX "_unity")
+ endif()
+ if (NOT DEFINED COTIRE_TARGETS_FOLDER)
+ set (COTIRE_TARGETS_FOLDER "cotire")
+ endif()
+ if (NOT DEFINED COTIRE_UNITY_OUTPUT_DIRECTORY)
+ if ("${CMAKE_GENERATOR}" MATCHES "Ninja")
+ # generated Ninja build files do not work if the unity target produces the same output file as the cotired target
+ set (COTIRE_UNITY_OUTPUT_DIRECTORY "unity")
+ else()
+ set (COTIRE_UNITY_OUTPUT_DIRECTORY "")
+ endif()
+ endif()
+
+ # define cotire cache variables
+
+ define_property(
+ CACHED_VARIABLE PROPERTY "COTIRE_ADDITIONAL_PREFIX_HEADER_IGNORE_PATH"
+ BRIEF_DOCS "Ignore headers from these directories when generating the prefix header."
+ FULL_DOCS
+ "The variable can be set to a semicolon separated list of include directories."
+ "If a header file is found in one of these directories or sub-directories, it will be excluded from the generated prefix header."
+ "If not defined, defaults to empty list."
+ )
+
+ define_property(
+ CACHED_VARIABLE PROPERTY "COTIRE_ADDITIONAL_PREFIX_HEADER_IGNORE_EXTENSIONS"
+ BRIEF_DOCS "Ignore includes with the listed file extensions from the generated prefix header."
+ FULL_DOCS
+ "The variable can be set to a semicolon separated list of file extensions."
+ "If a header file extension matches one in the list, it will be excluded from the generated prefix header."
+ "Includes with an extension in CMAKE__SOURCE_FILE_EXTENSIONS are always ignored."
+ "If not defined, defaults to inc;inl;ipp."
+ )
+
+ define_property(
+ CACHED_VARIABLE PROPERTY "COTIRE_UNITY_SOURCE_EXCLUDE_EXTENSIONS"
+ BRIEF_DOCS "Exclude sources with the listed file extensions from the generated unity source."
+ FULL_DOCS
+ "The variable can be set to a semicolon separated list of file extensions."
+ "If a source file extension matches one in the list, it will be excluded from the generated unity source file."
+ "Source files with an extension in CMAKE__IGNORE_EXTENSIONS are always excluded."
+ "If not defined, defaults to m;mm."
+ )
+
+ define_property(
+ CACHED_VARIABLE PROPERTY "COTIRE_MINIMUM_NUMBER_OF_TARGET_SOURCES"
+ BRIEF_DOCS "Minimum number of sources in target required to enable use of precompiled header."
+ FULL_DOCS
+ "The variable can be set to an integer > 0."
+ "If a target contains less than that number of source files, cotire will not enable the use of the precompiled header for the target."
+ "If not defined, defaults to 3."
+ )
+
+ define_property(
+ CACHED_VARIABLE PROPERTY "COTIRE_MAXIMUM_NUMBER_OF_UNITY_INCLUDES"
+ BRIEF_DOCS "Maximum number of source files to include in a single unity source file."
+ FULL_DOCS
+ "This may be set to an integer >= 0."
+ "If 0, cotire will only create a single unity source file."
+ "If a target contains more than that number of source files, cotire will create multiple unity source files for it."
+ "Can be set to \"-j\" to optimize the count of unity source files for the number of available processor cores."
+ "Can be set to \"-j jobs\" to optimize the number of unity source files for the given number of simultaneous jobs."
+ "Is used to initialize the target property COTIRE_UNITY_SOURCE_MAXIMUM_NUMBER_OF_INCLUDES."
+ "Defaults to \"-j\" for the generators Visual Studio, JOM or Ninja. Defaults to 0 otherwise."
+ )
+
+ # define cotire directory properties
+
+ define_property(
+ DIRECTORY PROPERTY "COTIRE_ENABLE_PRECOMPILED_HEADER"
+ BRIEF_DOCS "Modify build command of cotired targets added in this directory to make use of the generated precompiled header."
+ FULL_DOCS
+ "See target property COTIRE_ENABLE_PRECOMPILED_HEADER."
+ )
+
+ define_property(
+ DIRECTORY PROPERTY "COTIRE_ADD_UNITY_BUILD"
+ BRIEF_DOCS "Add a new target that performs a unity build for cotired targets added in this directory."
+ FULL_DOCS
+ "See target property COTIRE_ADD_UNITY_BUILD."
+ )
+
+ define_property(
+ DIRECTORY PROPERTY "COTIRE_ADD_CLEAN"
+ BRIEF_DOCS "Add a new target that cleans all cotire generated files for cotired targets added in this directory."
+ FULL_DOCS
+ "See target property COTIRE_ADD_CLEAN."
+ )
+
+ define_property(
+ DIRECTORY PROPERTY "COTIRE_PREFIX_HEADER_IGNORE_PATH"
+ BRIEF_DOCS "Ignore headers from these directories when generating the prefix header."
+ FULL_DOCS
+ "See target property COTIRE_PREFIX_HEADER_IGNORE_PATH."
+ )
+
+ define_property(
+ DIRECTORY PROPERTY "COTIRE_PREFIX_HEADER_INCLUDE_PATH"
+ BRIEF_DOCS "Honor headers from these directories when generating the prefix header."
+ FULL_DOCS
+ "See target property COTIRE_PREFIX_HEADER_INCLUDE_PATH."
+ )
+
+ define_property(
+ DIRECTORY PROPERTY "COTIRE_PREFIX_HEADER_INCLUDE_PRIORITY_PATH"
+ BRIEF_DOCS "Header paths matching one of these directories are put at the top of the prefix header."
+ FULL_DOCS
+ "See target property COTIRE_PREFIX_HEADER_INCLUDE_PRIORITY_PATH."
+ )
+
+ define_property(
+ DIRECTORY PROPERTY "COTIRE_UNITY_SOURCE_PRE_UNDEFS"
+ BRIEF_DOCS "Preprocessor undefs to place in the generated unity source file before the inclusion of each source file."
+ FULL_DOCS
+ "See target property COTIRE_UNITY_SOURCE_PRE_UNDEFS."
+ )
+
+ define_property(
+ DIRECTORY PROPERTY "COTIRE_UNITY_SOURCE_POST_UNDEFS"
+ BRIEF_DOCS "Preprocessor undefs to place in the generated unity source file after the inclusion of each source file."
+ FULL_DOCS
+ "See target property COTIRE_UNITY_SOURCE_POST_UNDEFS."
+ )
+
+ define_property(
+ DIRECTORY PROPERTY "COTIRE_UNITY_SOURCE_MAXIMUM_NUMBER_OF_INCLUDES"
+ BRIEF_DOCS "Maximum number of source files to include in a single unity source file."
+ FULL_DOCS
+ "See target property COTIRE_UNITY_SOURCE_MAXIMUM_NUMBER_OF_INCLUDES."
+ )
+
+ define_property(
+ DIRECTORY PROPERTY "COTIRE_UNITY_LINK_LIBRARIES_INIT"
+ BRIEF_DOCS "Define strategy for setting up the unity target's link libraries."
+ FULL_DOCS
+ "See target property COTIRE_UNITY_LINK_LIBRARIES_INIT."
+ )
+
+ # define cotire target properties
+
+ define_property(
+ TARGET PROPERTY "COTIRE_ENABLE_PRECOMPILED_HEADER" INHERITED
+ BRIEF_DOCS "Modify this target's build command to make use of the generated precompiled header."
+ FULL_DOCS
+ "If this property is set to TRUE, cotire will modify the build command to make use of the generated precompiled header."
+ "Irrespective of the value of this property, cotire will setup custom commands to generate the unity source and prefix header for the target."
+ "For makefile based generators cotire will also set up a custom target to manually invoke the generation of the precompiled header."
+ "The target name will be set to this target's name with the suffix _pch appended."
+ "Inherited from directory."
+ "Defaults to TRUE."
+ )
+
+ define_property(
+ TARGET PROPERTY "COTIRE_ADD_UNITY_BUILD" INHERITED
+ BRIEF_DOCS "Add a new target that performs a unity build for this target."
+ FULL_DOCS
+ "If this property is set to TRUE, cotire creates a new target of the same type that uses the generated unity source file instead of the target sources."
+ "Most of the relevant target properties will be copied from this target to the new unity build target."
+ "Target dependencies and linked libraries have to be manually set up for the new unity build target."
+ "The unity target name will be set to this target's name with the suffix _unity appended."
+ "Inherited from directory."
+ "Defaults to TRUE."
+ )
+
+ define_property(
+ TARGET PROPERTY "COTIRE_ADD_CLEAN" INHERITED
+ BRIEF_DOCS "Add a new target that cleans all cotire generated files for this target."
+ FULL_DOCS
+ "If this property is set to TRUE, cotire creates a new target that clean all files (unity source, prefix header, precompiled header)."
+ "The clean target name will be set to this target's name with the suffix _clean_cotire appended."
+ "Inherited from directory."
+ "Defaults to FALSE."
+ )
+
+ define_property(
+ TARGET PROPERTY "COTIRE_PREFIX_HEADER_IGNORE_PATH" INHERITED
+ BRIEF_DOCS "Ignore headers from these directories when generating the prefix header."
+ FULL_DOCS
+ "The property can be set to a list of directories."
+ "If a header file is found in one of these directories or sub-directories, it will be excluded from the generated prefix header."
+ "Inherited from directory."
+ "If not set, this property is initialized to \${CMAKE_SOURCE_DIR};\${CMAKE_BINARY_DIR}."
+ )
+
+ define_property(
+ TARGET PROPERTY "COTIRE_PREFIX_HEADER_INCLUDE_PATH" INHERITED
+ BRIEF_DOCS "Honor headers from these directories when generating the prefix header."
+ FULL_DOCS
+ "The property can be set to a list of directories."
+ "If a header file is found in one of these directories or sub-directories, it will be included in the generated prefix header."
+ "If a header file is both selected by COTIRE_PREFIX_HEADER_IGNORE_PATH and COTIRE_PREFIX_HEADER_INCLUDE_PATH,"
+ "the option which yields the closer relative path match wins."
+ "Inherited from directory."
+ "If not set, this property is initialized to the empty list."
+ )
+
+ define_property(
+ TARGET PROPERTY "COTIRE_PREFIX_HEADER_INCLUDE_PRIORITY_PATH" INHERITED
+ BRIEF_DOCS "Header paths matching one of these directories are put at the top of prefix header."
+ FULL_DOCS
+ "The property can be set to a list of directories."
+ "Header file paths matching one of these directories will be inserted at the beginning of the generated prefix header."
+ "Header files are sorted according to the order of the directories in the property."
+ "If not set, this property is initialized to the empty list."
+ )
+
+ define_property(
+ TARGET PROPERTY "COTIRE_UNITY_SOURCE_PRE_UNDEFS" INHERITED
+ BRIEF_DOCS "Preprocessor undefs to place in the generated unity source file before the inclusion of each target source file."
+ FULL_DOCS
+ "This may be set to a semicolon-separated list of preprocessor symbols."
+ "cotire will add corresponding #undef directives to the generated unit source file before each target source file."
+ "Inherited from directory."
+ "Defaults to empty string."
+ )
+
+ define_property(
+ TARGET PROPERTY "COTIRE_UNITY_SOURCE_POST_UNDEFS" INHERITED
+ BRIEF_DOCS "Preprocessor undefs to place in the generated unity source file after the inclusion of each target source file."
+ FULL_DOCS
+ "This may be set to a semicolon-separated list of preprocessor symbols."
+ "cotire will add corresponding #undef directives to the generated unit source file after each target source file."
+ "Inherited from directory."
+ "Defaults to empty string."
+ )
+
+ define_property(
+ TARGET PROPERTY "COTIRE_UNITY_SOURCE_MAXIMUM_NUMBER_OF_INCLUDES" INHERITED
+ BRIEF_DOCS "Maximum number of source files to include in a single unity source file."
+ FULL_DOCS
+ "This may be set to an integer > 0."
+ "If a target contains more than that number of source files, cotire will create multiple unity build files for it."
+ "If not set, cotire will only create a single unity source file."
+ "Inherited from directory."
+ "Defaults to empty."
+ )
+
+ define_property(
+ TARGET PROPERTY "COTIRE__UNITY_SOURCE_INIT"
+ BRIEF_DOCS "User provided unity source file to be used instead of the automatically generated one."
+ FULL_DOCS
+ "If set, cotire will only add the given file(s) to the generated unity source file."
+ "If not set, cotire will add all the target source files to the generated unity source file."
+ "The property can be set to a user provided unity source file."
+ "Defaults to empty."
+ )
+
+ define_property(
+ TARGET PROPERTY "COTIRE__PREFIX_HEADER_INIT"
+ BRIEF_DOCS "User provided prefix header file to be used instead of the automatically generated one."
+ FULL_DOCS
+ "If set, cotire will add the given header file(s) to the generated prefix header file."
+ "If not set, cotire will generate a prefix header by tracking the header files included by the unity source file."
+ "The property can be set to a user provided prefix header file (e.g., stdafx.h)."
+ "Defaults to empty."
+ )
+
+ define_property(
+ TARGET PROPERTY "COTIRE_UNITY_LINK_LIBRARIES_INIT" INHERITED
+ BRIEF_DOCS "Define strategy for setting up unity target's link libraries."
+ FULL_DOCS
+ "If this property is empty or set to NONE, the generated unity target's link libraries have to be set up manually."
+ "If this property is set to COPY, the unity target's link libraries will be copied from this target."
+ "If this property is set to COPY_UNITY, the unity target's link libraries will be copied from this target with considering existing unity targets."
+ "Inherited from directory."
+ "Defaults to empty."
+ )
+
+ define_property(
+ TARGET PROPERTY "COTIRE__UNITY_SOURCE"
+ BRIEF_DOCS "Read-only property. The generated unity source file(s)."
+ FULL_DOCS
+ "cotire sets this property to the path of the generated single computation unit source file for the target."
+ "Defaults to empty string."
+ )
+
+ define_property(
+ TARGET PROPERTY "COTIRE__PREFIX_HEADER"
+ BRIEF_DOCS "Read-only property. The generated prefix header file."
+ FULL_DOCS
+ "cotire sets this property to the full path of the generated language prefix header for the target."
+ "Defaults to empty string."
+ )
+
+ define_property(
+ TARGET PROPERTY "COTIRE__PRECOMPILED_HEADER"
+ BRIEF_DOCS "Read-only property. The generated precompiled header file."
+ FULL_DOCS
+ "cotire sets this property to the full path of the generated language precompiled header binary for the target."
+ "Defaults to empty string."
+ )
+
+ define_property(
+ TARGET PROPERTY "COTIRE_UNITY_TARGET_NAME"
+ BRIEF_DOCS "The name of the generated unity build target corresponding to this target."
+ FULL_DOCS
+ "This property can be set to the desired name of the unity target that will be created by cotire."
+ "If not set, the unity target name will be set to this target's name with the suffix _unity appended."
+ "After this target has been processed by cotire, the property is set to the actual name of the generated unity target."
+ "Defaults to empty string."
+ )
+
+ # define cotire source properties
+
+ define_property(
+ SOURCE PROPERTY "COTIRE_EXCLUDED"
+ BRIEF_DOCS "Do not modify source file's build command."
+ FULL_DOCS
+ "If this property is set to TRUE, the source file's build command will not be modified to make use of the precompiled header."
+ "The source file will also be excluded from the generated unity source file."
+ "Source files that have their COMPILE_FLAGS property set will be excluded by default."
+ "Defaults to FALSE."
+ )
+
+ define_property(
+ SOURCE PROPERTY "COTIRE_DEPENDENCY"
+ BRIEF_DOCS "Add this source file to dependencies of the automatically generated prefix header file."
+ FULL_DOCS
+ "If this property is set to TRUE, the source file is added to dependencies of the generated prefix header file."
+ "If the file is modified, cotire will re-generate the prefix header source upon build."
+ "Defaults to FALSE."
+ )
+
+ define_property(
+ SOURCE PROPERTY "COTIRE_UNITY_SOURCE_PRE_UNDEFS"
+ BRIEF_DOCS "Preprocessor undefs to place in the generated unity source file before the inclusion of this source file."
+ FULL_DOCS
+ "This may be set to a semicolon-separated list of preprocessor symbols."
+ "cotire will add corresponding #undef directives to the generated unit source file before this file is included."
+ "Defaults to empty string."
+ )
+
+ define_property(
+ SOURCE PROPERTY "COTIRE_UNITY_SOURCE_POST_UNDEFS"
+ BRIEF_DOCS "Preprocessor undefs to place in the generated unity source file after the inclusion of this source file."
+ FULL_DOCS
+ "This may be set to a semicolon-separated list of preprocessor symbols."
+ "cotire will add corresponding #undef directives to the generated unit source file after this file is included."
+ "Defaults to empty string."
+ )
+
+ define_property(
+ SOURCE PROPERTY "COTIRE_START_NEW_UNITY_SOURCE"
+ BRIEF_DOCS "Start a new unity source file which includes this source file as the first one."
+ FULL_DOCS
+ "If this property is set to TRUE, cotire will complete the current unity file and start a new one."
+ "The new unity source file will include this source file as the first one."
+ "This property essentially works as a separator for unity source files."
+ "Defaults to FALSE."
+ )
+
+ define_property(
+ SOURCE PROPERTY "COTIRE_TARGET"
+ BRIEF_DOCS "Read-only property. Mark this source file as cotired for the given target."
+ FULL_DOCS
+ "cotire sets this property to the name of target, that the source file's build command has been altered for."
+ "Defaults to empty string."
+ )
+
+ message (STATUS "cotire ${COTIRE_CMAKE_MODULE_VERSION} loaded.")
+
+endif()
diff --git a/rtags/configure b/rtags/configure
new file mode 100755
index 0000000..1503f8e
--- /dev/null
+++ b/rtags/configure
@@ -0,0 +1,132 @@
+#!/bin/bash
+
+function usage ()
+{
+ echo "configure [OPTIONS...]"
+ echo " --help|-h Display this help"
+ echo " --cmake [arg] Use arg instead of \"cmake\""
+ echo " --cmake-argument [arg] Pass additional arguments to cmake"
+ echo " --cmake-generator [arg] Use this generator for cmake (e.g. Ninja)"
+ echo " --enable-dev-options Set certain development options (cpack)"
+ echo " --asan Enable -fsanitize=address and -fsanitize=undefined"
+ echo " --debug Compile RTags in debug mode"
+ echo " --release Compile RTags in release mode (default)"
+ echo " --system-clang Don't build llvm/clang as part of RTags' build process (default)"
+ echo " --build-tests Build tests"
+ echo " --build-clang Download and build llvm/clang as part of RTags' build process"
+ echo " --no-install Generate a build that isn't going to be installed"
+ echo " --prefix [arg] Set install prefix to arg"
+ echo " --clang-libraries [arg] Override what libraries RTags will use to link against clang/llvm"
+ echo " --clang-cxxflags [arg] Override what cxxflags RTags will use for compilation to be able to include clang headers."
+ echo " --clang-libdir [arg] Sets the libdir RTags will use for clang."
+ echo " --cotire Enable cotire when building RTags"
+ echo " --emacs Use arg instead of \"emacs\" when byte-compiling elisp"
+ echo " --lua-enabled Enable LUA AST scripting"
+ echo " --no-lua-files-install Don't install RTags lua files"
+ echo " --no-elisp-files-install Don't install RTags elisp files"
+ echo " --no-elisp-bytecompile Don't bytecompile RTags elisp files"
+ echo " --elisp-install-location [arg] Install elisp files to this location"
+}
+
+CMAKE=cmake
+CMAKE_ARGS="-DCMAKE_EXPORT_COMPILE_COMMANDS=1"
+BUILD=
+while [ -n "$1" ]; do
+ case "$1" in
+ --help|-h)
+ usage > /dev/stdout
+ exit 0
+ ;;
+ --cmake)
+ shift
+ CMAKE="$1"
+ ;;
+ --cmake-argument)
+ shift
+ CMAKE_ARGS="${CMAKE_ARGS} \"$1\""
+ ;;
+ --cmake-generator)
+ shift
+ CMAKE_GENERATOR="$1"
+ ;;
+ --enable-dev-options)
+ CMAKE_ARGS="${CMAKE_ARGS} -DRTAGS_ENABLE_DEV_OPTIONS=1"
+ ;;
+ --debug)
+ CMAKE_ARGS="${CMAKE_ARGS} -DCMAKE_BUILD_TYPE=Debug"
+ ;;
+ --release)
+ CMAKE_ARGS="${CMAKE_ARGS} -DCMAKE_BUILD_TYPE=Release"
+ ;;
+ --system-clang)
+ BUILD=
+ ;;
+ --build-clang)
+ BUILD=1
+ ;;
+ --without-tests)
+ CMAKE_ARGS="${CMAKE_ARGS} -DBUILD_TESTING=0"
+ ;;
+ --no-install)
+ CMAKE_ARGS="${CMAKE_ARGS} -DRTAGS_NO_INSTALL=1"
+ ;;
+ --prefix)
+ shift
+ CMAKE_ARGS="${CMAKE_ARGS} -DCMAKE_INSTALL_PREFIX=\"$1\""
+ ;;
+ --lua-enabled)
+ CMAKE_ARGS="${CMAKE_ARGS} -DLUA_ENABLED=1"
+ ;;
+ --clang-libraries)
+ shift
+ CMAKE_ARGS="${CMAKE_ARGS} -DLIBCLANG_LIBRARIES=\"$1\""
+ ;;
+ --clang-cxxflags)
+ shift
+ CMAKE_ARGS="${CMAKE_ARGS} -DLIBCLANG_CXXFLAGS=\"$1\""
+ ;;
+ --clang-libdir)
+ shift
+ CMAKE_ARGS="${CMAKE_ARGS} -DLIBCLANG_LIBDIR=\"$1\""
+ ;;
+ --cotire)
+ CMAKE_ARGS="${CMAKE_ARGS} -DRTAGS_COTIRE=1"
+ ;;
+ --emacs)
+ shift
+ CMAKE_ARGS="${CMAKE_ARGS} -DEMACS=\"$1\""
+ ;;
+ --no-lua-files-install)
+ CMAKE_ARGS="${CMAKE_ARGS} -DRTAGS_NO_LUA_FILES=1"
+ ;;
+ --no-elisp-files-install)
+ CMAKE_ARGS="${CMAKE_ARGS} -DRTAGS_NO_ELISP_FILES=1"
+ ;;
+ --no-elisp-bytecompile)
+ CMAKE_ARGS="${CMAKE_ARGS} -DRTAGS_NO_ELISP_BYTECOMPILE=1"
+ ;;
+ --asan)
+ CMAKE_ARGS="${CMAKE_ARGS} -DASAN=address,undefined"
+ ;;
+ --asan=*)
+ CMAKE_ARGS="${CMAKE_ARGS} -DASAN=`echo $1 | sed -e 's,--asan=,,'`"
+ ;;
+ --elisp-install-location)
+ shift
+ CMAKE_ARGS="${CMAKE_ARGS} -DRTAGS_ELISP_INSTALL_LOCATION=\"$1\""
+ ;;
+ *)
+ usage > /dev/stderr
+ echo "Unknown option $1"
+ exit 1
+ ;;
+ esac
+ shift
+done
+
+[ -n "$CMAKE_GENERATOR" ] && CMAKE_ARGS="${CMAKE_ARGS} -G \"$CMAKE_GENERATOR\""
+[ -n "$BUILD" ] && CMAKE_ARGS="${CMAKE_ARGS} -DRTAGS_BUILD_CLANG=1"
+
+echo -e "Running cmake:\n\"$CMAKE\" \"$(dirname ${BASH_SOURCE[0]})\" ${CMAKE_ARGS}\n"
+rm -f CMakeCache.txt
+eval "$CMAKE" "$(dirname ${BASH_SOURCE[0]})" ${CMAKE_ARGS}
diff --git a/rtags/man/man7/rc.7 b/rtags/man/man7/rc.7
new file mode 100644
index 0000000..3625fbc
--- /dev/null
+++ b/rtags/man/man7/rc.7
@@ -0,0 +1,386 @@
+.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.6.
+.TH RC "7" "June 2018" "rc 2.18.125" "User Commands"
+.SH NAME
+rc \- manual page for rc 2.18.125
+.SH SYNOPSIS
+rc [OPTION]...
+.SH DESCRIPTION
+rc is the RTags client application.
+.PP
+.SH OPTIONS
+.TP
+\fB\-\-verbose\fR|\-v
+Be more verbose.
+.TP
+\fB\-\-version\fR
+Print current version.
+.TP
+\fB\-\-verify\-version\fR [arg]
+Verify that the correct protocol version is used.
+.TP
+\fB\-\-silent\fR|\-Q
+Be silent.
+.TP
+\fB\-\-help\fR|\-h
+Display this help.
+.TP
+\fB\-\-config\fR [arg]
+Use this file (instead of ~/.rcrc).
+.TP
+\fB\-\-no\-rc\fR
+Don't load any rc files.
+.SS "Rdm:"
+.TP
+\fB\-\-quit\-rdm\fR|\-q
+Tell server to shut down with optional exit code as argument.
+.TP
+\fB\-\-connect\-timeout\fR [arg]
+Timeout for connecting to rdm in ms (default 1000).
+.SS "Project management:"
+.TP
+\fB\-\-clear\fR|\-C
+Clear projects.
+.TP
+\fB\-\-project\fR|\-w [optional]
+With arg, select project matching that if unique, otherwise list all projects.
+.TP
+\fB\-\-delete\-project\fR|\-W [arg]
+Delete all projects matching regex.
+.TP
+\fB\-\-job\-count\fR|\-j [optional]
+Set or query current job count. (Prefix with l to set low\-priority\-job\-count).
+.SS "Indexing commands:"
+.TP
+\fB\-\-compile\fR|\-c [optional]
+Pass compilation arguments to rdm.
+.TP
+\fB\-\-guess\-flags\fR
+Guess compile flags (used with \fB\-c\fR).
+.TP
+\fB\-\-load\-compile\-commands\fR|\-J [optional]
+Load compile_commands.json from directory
+.TP
+\fB\-\-suspend\fR|\-X [optional]
+Dump suspended files (don't track changes in these files) with no arg. Otherwise toggle suspension for arg.
+.SS "Query commands:"
+.TP
+\fB\-\-follow\-location\fR|\-f [arg]
+Follow this location.
+.TP
+\fB\-\-references\-name\fR|\-R [arg]
+Find references matching arg.
+.TP
+\fB\-\-references\fR|\-r [arg]
+Find references matching this location.
+.TP
+\fB\-\-list\-symbols\fR|\-S [optional]
+List symbol names matching arg.
+.TP
+\fB\-\-find\-symbols\fR|\-F [optional]
+Find symbols matching arg.
+.TP
+\fB\-\-symbol\-info\fR|\-U [arg]
+Get cursor info for this location.
+.TP
+\fB\-\-status\fR|\-s [optional]
+Dump status of rdm. Arg can be symbols or symbolNames.
+.TP
+\fB\-\-diagnose\fR [arg]
+Resend diagnostics for file.
+.TP
+\fB\-\-diagnose\-all\fR
+Resend diagnostics for all files.
+.TP
+\fB\-\-last\-indexed\fR
+Get timestamp of the last time indexing completed for the current project.
+.TP
+\fB\-\-is\-indexed\fR|\-T [arg]
+Check if rtags knows about, and is ready to return information about, this source file.
+.TP
+\fB\-\-is\-indexing\fR
+Check if rtags is currently indexing files.
+.TP
+\fB\-\-has\-filemanager\fR [optional]
+Check if rtags has info about files in this directory.
+.TP
+\fB\-\-preprocess\fR|\-E [arg]
+Preprocess file.
+.TP
+\fB\-\-reindex\fR|\-V [optional]
+Reindex all files or all files matching pattern.
+.TP
+\fB\-\-check\-reindex\fR|\-x [optional]
+Check if reindexing is necessary for all files matching pattern.
+.TP
+\fB\-\-path\fR|\-P [optional]
+Print files matching pattern.
+.TP
+\fB\-\-current\-project\fR
+Print path for current project.
+.TP
+\fB\-\-dump\-file\fR|\-d [arg]
+Dump source file.
+.TP
+\fB\-\-check\-includes\fR [arg]
+Check includes for source file.
+.TP
+\fB\-\-dump\-file\-maps\fR [arg]
+Dump file maps for file.
+.TP
+\fB\-\-generate\-test\fR [arg]
+Generate a test for a given source file.
+.TP
+\fB\-\-rdm\-log\fR|\-g
+Receive logs from rdm.
+.TP
+\fB\-\-fixits\fR [arg]
+Get fixits for file.
+.TP
+\fB\-\-remove\fR|\-D [arg]
+Remove file from project.
+.TP
+\fB\-\-find\-project\-root\fR [arg]
+Use to check behavior of find\-project\-root.
+.TP
+\fB\-\-find\-project\-build\-root\fR [arg]
+Use to check behavior of find\-project\-root for builds.
+.TP
+\fB\-\-include\-file\fR [arg]
+Use to generate include statement for symbol.
+.TP
+\fB\-\-sources\fR [optional]
+Dump sources for source file.
+.TP
+\fB\-\-dependencies\fR [arg]
+Dump dependencies for source file [(includes, included\-by, depends\-on, depended\-on, tree\-depends\-on, raw)].
+.TP
+\fB\-\-all\-dependencies\fR
+Dump dependencies for all source files [(includes, included\-by, depends\-on, depended\-on, tree\-depends\-on, raw)].
+.TP
+\fB\-\-reload\-file\-manager\fR|\-B
+Reload file manager.
+.TP
+\fB\-\-man\fR
+Output XML for xmltoman to generate man page for rc :\-)
+.TP
+\fB\-\-code\-complete\-at\fR|\-l [arg]
+Code complete at location: arg is file:line:col.
+.TP
+\fB\-\-send\-diagnostics\fR [arg]
+Only for debugging. Send data to all \fB\-G\fR connections.
+.TP
+\fB\-\-dump\-completions\fR
+Dump cached completions.
+.TP
+\fB\-\-dump\-compile\-commands\fR
+Dump compilation database for project.
+.TP
+\fB\-\-set\-buffers\fR [optional]
+Set active buffers (list of filenames for active buffers in editor).
+.TP
+\fB\-\-list\-buffers\fR
+List active buffers.
+.TP
+\fB\-\-add\-buffers\fR [arg]
+Add additional buffers.
+.TP
+\fB\-\-remove\-buffers\fR [arg]
+Remove buffers.
+.TP
+\fB\-\-list\-cursor\-kinds\fR
+List spelling for known cursor kinds.
+.TP
+\fB\-\-class\-hierarchy\fR [arg]
+Dump class hierarcy for struct/class at location.
+.TP
+\fB\-\-debug\-locations\fR [optional]
+Manipulate debug locations.
+.TP
+\fB\-\-validate\fR
+Validate database files for current project.
+.TP
+\fB\-\-tokens\fR [arg]
+Dump tokens for file. \fB\-\-tokens\fR file.cpp:123\-321 for range.
+.SS "Command flags:"
+.TP
+\fB\-\-strip\-paren\fR|\-p
+Strip parens in various contexts.
+.TP
+\fB\-\-max\fR|\-M [arg]
+Max lines of output for queries.
+.TP
+\fB\-\-reverse\-sort\fR|\-O
+Sort output reversed.
+.TP
+\fB\-\-rename\fR
+Used for \fB\-\-references\fR to indicate that we're using the results to rename symbols.
+.TP
+\fB\-\-unsaved\-file\fR [arg]
+Pass unsaved file on command line. E.g. \fB\-\-unsaved\-file\fR=\fI\,main\/\fR.cpp:1200 then write 1200 bytes on stdin.
+.TP
+\fB\-\-log\-file\fR|\-L [arg]
+Log to this file.
+.TP
+\fB\-\-no\-context\fR|\-N
+Don't print context for locations.
+.TP
+\fB\-\-path\-filter\fR|\-i [arg]
+Filter out results not matching with arg.
+.TP
+\fB\-\-dependency\-filter\fR [arg]
+Filter out results unless argument depends on them.
+.TP
+\fB\-\-range\-filter\fR [arg]
+Filter out results not in the specified range.
+.TP
+\fB\-\-filter\-system\-headers\fR|\-H
+Don't exempt system headers from path filters.
+.TP
+\fB\-\-all\-references\fR|\-e
+Include definitions/declarations/constructors/destructors for references. Used for rename symbol.
+.TP
+\fB\-\-target\-usrs\fR
+Print all matching usr targets for \fB\-f\fR. Used for debugging.
+.TP
+\fB\-\-all\-targets\fR
+Print multiple targets for \fB\-f\fR. Sorted by best match.
+.TP
+\fB\-\-elisp\fR|\-Y
+Output elisp: (list "one" "two" ...).
+.TP
+\fB\-\-json\fR
+Output json.
+.TP
+\fB\-\-diagnostics\fR|\-m
+Receive async formatted diagnostics from rdm.
+.TP
+\fB\-\-match\-regexp\fR|\-Z
+Treat various text patterns as regexps (\fB\-P\fR, \fB\-i\fR, \fB\-V\fR, \fB\-F\fR).
+.TP
+\fB\-\-match\-icase\fR|\-I
+Match case insensitively
+.TP
+\fB\-\-absolute\-path\fR|\-K
+Print files with absolute path.
+.TP
+\fB\-\-socket\-file\fR|\-n [arg]
+Use this socket file (default ~/.rdm).
+.TP
+\fB\-\-socket\-address\fR [arg]
+Use this host:port combination (instead of \fB\-\-socket\-file\fR).
+.TP
+\fB\-\-timeout\fR|\-y [arg]
+Max time in ms to wait for job to finish (default no timeout).
+.TP
+\fB\-\-find\-virtuals\fR|\-k
+Use in combinations with \fB\-R\fR or \fB\-r\fR to show other implementations of this function.
+.TP
+\fB\-\-find\-file\-prefer\-exact\fR|\-A
+Use to make \fB\-\-find\-file\fR prefer exact matches over partial matches.
+.TP
+\fB\-\-symbol\-info\-include\-parents\fR
+Use to make \fB\-\-symbol\-info\fR include parent symbols.
+.TP
+\fB\-\-symbol\-info\-include\-targets\fR
+Use to make \fB\-\-symbol\-info\fR include target symbols.
+.TP
+\fB\-\-symbol\-info\-include\-references\fR
+Use to make \fB\-\-symbol\-info\fR include reference symbols.
+.TP
+\fB\-\-symbol\-info\-include\-base\-classes\fR
+Use to make \fB\-\-symbol\-info\fR include baseclasses' symbols.
+.TP
+\fB\-\-cursor\-kind\fR
+Include cursor kind in \fB\-\-find\-symbols\fR output.
+.TP
+\fB\-\-display\-name\fR
+Include display name in \fB\-\-find\-symbols\fR output.
+.TP
+\fB\-\-current\-file\fR [arg]
+Pass along which file is being edited to give rdm a better chance at picking the right project.
+.TP
+\fB\-\-declaration\-only\fR|\-G
+Filter out definitions (unless inline).
+.TP
+\fB\-\-definition\-only\fR
+Filter out declarations (unless inline).
+.TP
+\fB\-\-kind\-filter\fR [arg]
+Only return results matching this kind.
+.TP
+\fB\-\-containing\-function\fR|\-o
+Include name of containing function in output.
+.TP
+\fB\-\-containing\-function\-location\fR
+Include location of containing function in output.
+.TP
+\fB\-\-build\-index\fR [arg]
+For sources with multiple builds, use the arg'th.
+.TP
+\fB\-\-compilation\-flags\-only\fR
+For \fB\-\-source\fR, only print compilation flags.
+.TP
+\fB\-\-compilation\-flags\-split\-line\fR
+For \fB\-\-source\fR, print one compilation flag per line.
+.TP
+\fB\-\-compilation\-flags\-pwd\fR
+For \fB\-\-source\fR, print pwd for compile command on the first line.
+.TP
+\fB\-\-dump\-include\-headers\fR
+For \fB\-\-dump\-file\fR, also dump dependencies.
+.TP
+\fB\-\-silent\-query\fR
+Don't log this request in rdm.
+.TP
+\fB\-\-synchronous\-completions\fR
+Wait for completion results and print them to stdout.
+.TP
+\fB\-\-synchronous\-diagnostics\fR
+Wait for diagnostics and print them to stdout.
+.TP
+\fB\-\-xml\fR
+Output XML
+.TP
+\fB\-\-no\-sort\-references\-by\-input\fR
+Don't sort references by input position.
+.TP
+\fB\-\-project\-root\fR [arg]
+Override project root for compile commands.
+.TP
+\fB\-\-rtags\-config\fR [arg]
+Print out .rtags\-config for argument.
+.TP
+\fB\-\-wildcard\-symbol\-names\fR|\-a
+Expand * like wildcards in \fB\-\-list\-symbols\fR and \fB\-\-find\-symbols\fR.
+.TP
+\fB\-\-no\-color\fR|\-z
+Don't colorize context.
+.TP
+\fB\-\-wait\fR
+Wait for reindexing to finish.
+.TP
+\fB\-\-code\-complete\-include\-macros\fR
+Include macros in code completion results.
+.TP
+\fB\-\-code\-complete\-includes\fR
+Give includes in completion results.
+.TP
+\fB\-\-code\-complete\-no\-wait\fR
+Don't wait for synchronous completion if the translation unit has to be created.
+.TP
+\fB\-\-code\-complete\-prefix\fR [arg]
+Filter out code completion results that don't start with this prefix.
+.TP
+\fB\-\-code\-completion\-enabled\fR|\-b
+Inform rdm that we're code\-completing. Use with \fB\-\-diagnose\fR
+.TP
+\fB\-\-no\-spell\-checking\fR
+Don't produce spell check info in diagnostics.
+.TP
+\fB\-\-tokens\-include\-symbols\fR
+Include symbols for tokens.
+.TP
+\fB\-\-no\-realpath\fR
+Don't resolve paths using realpath(3).
+.SH "SEE ALSO"
+rdm(7)
diff --git a/rtags/man/man7/rdm.7 b/rtags/man/man7/rdm.7
new file mode 100644
index 0000000..b351d85
--- /dev/null
+++ b/rtags/man/man7/rdm.7
@@ -0,0 +1,272 @@
+.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.6.
+.TH RDM "7" "June 2018" "rdm 2.18.125" "User Commands"
+.SH NAME
+rdm \- manual page for rdm 2.18.125
+.SH SYNOPSIS
+rdm [OPTION]...
+.SH DESCRIPTION
+RTags is a client/server application that indexes C/C++ code and keeps
+a persistent file\-based database of references, declarations,
+definitions, symbolnames etc. There's also limited support for
+ObjC/ObjC++. It allows you to find symbols by name (including nested
+class and namespace scope). Most importantly we give you proper
+follow\-symbol and find\-references support. We also have neat little
+things like rename\-symbol, integration with clang's "fixits"
+(http://clang.llvm.org/diagnostics.html). We also integrate with
+flymake using clang's vastly superior errors and warnings. Since
+RTags constantly will reindex "dirty" files you get live updates of
+compiler errors and warnings. Since we already know how to compile
+your sources we have a way to quickly bring up the preprocessed output
+of the current source file in a buffer.
+
+While existing taggers like gnu global, cscope, etags, ctags etc do a
+decent job for C they often fall a little bit short for C++. With its
+incredible lexical complexity, parsing C++ is an incredibly hard task
+and we make no bones about the fact that the only reason we are able
+to improve on the current tools is because of clang
+(http://clang.llvm.org/). RTags is named RTags in recognition of
+Roberto Raggi on whose C++ parser we intended to base this project but
+he assured us clang was the way to go. The name stuck though.
+.PP
+.SH OPTIONS
+.TP
+\fB\-\-help\fR|\-h
+Display this page.
+.TP
+\fB\-\-version\fR
+Display version.
+.TP
+\fB\-\-include\-path\fR|\-I [arg]
+Add additional include path to clang.
+.TP
+\fB\-\-no\-libclang\-include\-path\fR
+Don't use the include path from libclang.
+.TP
+\fB\-\-isystem\fR|\-s [arg]
+Add additional system include path to clang.
+.TP
+\fB\-\-define\fR|\-D [arg]
+Add additional define directive to clang.
+.TP
+\fB\-\-default\-argument\fR [arg]
+Add additional argument to clang.
+.TP
+\fB\-\-log\-file\fR|\-L [arg]
+Log to this file.
+.TP
+\fB\-\-crash\-dump\-file\fR [arg]
+File to dump crash log to (default is /crash.dump).
+.TP
+\fB\-\-setenv\fR|\-e [arg]
+Set this environment variable (\fB\-\-setenv\fR "foobar=1").
+.TP
+\fB\-\-no\-Wall\fR|\-W
+Don't use \fB\-Wall\fR.
+.TP
+\fB\-\-Weverything\fR|\-u
+Use \fB\-Weverything\fR.
+.TP
+\fB\-\-verbose\fR|\-v
+Change verbosity, multiple \fB\-v\fR's are allowed.
+.TP
+\fB\-\-job\-count\fR|\-j [arg]
+Spawn this many concurrent processes for indexing.
+.TP
+\fB\-\-header\-error\-job\-count\fR|\-H [arg]
+Allow this many concurrent header error jobs (default std::max(1, \fB\-\-job\-count\fR / 2)).
+.TP
+\fB\-\-test\fR|\-t [arg]
+Run this test.
+.TP
+\fB\-\-test\-timeout\fR|\-z [arg]
+Timeout for test to complete.
+.TP
+\fB\-\-clean\-slate\fR|\-C
+Clear out all data.
+.TP
+\fB\-\-disable\-sighandler\fR|\-x
+Disable signal handler to dump stack for crashes.
+.TP
+\fB\-\-silent\fR|\-S
+No logging to stdout/stderr.
+.TP
+\fB\-\-exclude\-filter\fR|\-X [arg]
+Files to exclude from rdm, default "*/CMakeFiles/*;*/cmake*/Modules/*;*/conftest.c*;/tmp/*;/private/tmp/*;/private/var/*".
+.TP
+\fB\-\-socket\-file\fR|\-n [arg]
+Use this file for the server socket (default ~/.rdm).
+.TP
+\fB\-\-data\-dir\fR|\-d [arg]
+Use this directory to store persistent data (default \fI\,$XDG_CACHE_HOME/rtags\/\fP otherwise ~/.cache/rtags).
+.TP
+\fB\-\-ignore\-printf\-fixits\fR|\-F
+Disregard any clang fixit that looks like it's trying to fix format for printf and friends.
+.TP
+\fB\-\-error\-limit\fR|\-f [arg]
+Set error limit to argument (\fB\-ferror\-limit=\fR{arg} (default 50).
+.TP
+\fB\-\-block\-argument\fR|\-G [arg]
+Block this argument from being passed to clang. E.g. rdm \fB\-\-block\-argument\fR \fB\-fno\-inline\fR
+.TP
+\fB\-\-no\-spell\-checking\fR|\-l
+Don't pass \fB\-fspell\-checking\fR.
+.TP
+\fB\-\-large\-by\-value\-copy\fR|\-r [arg]
+Use \fB\-Wlarge\-by\-value\-copy\fR=\fI\,[arg]\/\fR when invoking clang.
+.TP
+\fB\-\-allow\-multiple\-sources\fR|\-m
+Don't merge source files added with \fB\-c\fR.
+.TP
+\fB\-\-no\-startup\-project\fR|\-o
+Don't restore the last current project on startup.
+.TP
+\fB\-\-no\-no\-unknown\-warnings\-option\fR|\-Y
+Don't pass \fB\-Wno\-unknown\-warning\-option\fR.
+.TP
+\fB\-\-ignore\-compiler\fR|\-b [arg]
+Ignore this compiler.
+.TP
+\fB\-\-compiler\-wrappers\fR [arg]
+Consider these filenames compiler wrappers (split on ;), default ccache".
+.TP
+\fB\-\-watch\-system\-paths\fR|\-w
+Watch system paths for changes.
+.TP
+\fB\-\-rp\-visit\-file\-timeout\fR|\-Z [arg]
+Timeout for rp visitfile commands in ms (0 means no timeout) (default 60000).
+.TP
+\fB\-\-rp\-indexer\-message\-timeout\fR|\-T [arg]
+Timeout for rp indexer\-message in ms (0 means no timeout) (default 60000).
+.TP
+\fB\-\-rp\-connect\-timeout\fR|\-O [arg]
+Timeout for connection from rp to rdm in ms (0 means no timeout) (default 0).
+.TP
+\fB\-\-rp\-connect\-attempts\fR [arg]
+Number of times rp attempts to connect to rdm before giving up. (default 3).
+.TP
+\fB\-\-rp\-nice\-value\fR|\-a [arg]
+Nice value to use for rp (nice(2)) (default is no nicing).
+.TP
+\fB\-\-suspend\-rp\-on\-crash\fR|\-q
+Suspend rp in SIGSEGV handler (default off).
+.TP
+\fB\-\-rp\-log\-to\-syslog\fR
+Make rp log to syslog.
+.TP
+\fB\-\-start\-suspended\fR|\-Q
+Start out suspended (no reindexing enabled).
+.TP
+\fB\-\-separate\-debug\-and\-release\fR|\-E
+Normally rdm doesn't consider release and debug as different builds. Pass this if you want it to.
+.TP
+\fB\-\-separate\-32\-bit\-and\-64\-bit\fR
+Normally rdm doesn't consider \fB\-m32\fR and \fB\-m64\fR as different builds. Pass this if you want it to.
+.HP
+\fB\-\-ignore\-include\-path\-differences\-in\-usr\fR Don't consider sources that only differ in includepaths within \fI\,/usr\/\fP (not including /usr/home/) as different builds.
+.TP
+\fB\-\-max\-crash\-count\fR|\-K [arg]
+Max number of crashes before giving up a sourcefile (default 5).
+.TP
+\fB\-\-max\-socket\-write\-buffer\-size\fR [arg]
+Max number of bytes buffered after EAGAIN.
+.TP
+\fB\-\-completion\-cache\-size\fR|\-i [arg]
+Number of translation units to cache (default 10).
+.TP
+\fB\-\-completion\-no\-filter\fR
+Don't filter private members and destructors from completions.
+.TP
+\fB\-\-completion\-logs\fR
+Log more info about completions.
+.TP
+\fB\-\-max\-include\-completion\-depth\fR [arg]
+Max recursion depth for header completion (default 3).
+.TP
+\fB\-\-allow\-Wpedantic\fR|\-P
+Don't strip out \fB\-Wpedantic\fR. This can cause problems in certain projects.
+.TP
+\fB\-\-allow\-Werror\fR
+Don't strip out \fB\-Werror\fR and \fB\-Wfatal\-errors\fR. By default these are stripped out.
+.TP
+\fB\-\-enable\-compiler\-manager\fR|\-R
+Query compilers for their actual include paths instead of letting clang use its own.
+.TP
+\fB\-\-enable\-NDEBUG\fR|\-g
+Don't remove \fB\-DNDEBUG\fR from compile lines.
+.TP
+\fB\-\-progress\fR|\-p
+Report compilation progress in diagnostics output.
+.TP
+\fB\-\-max\-file\-map\-cache\-size\fR|\-y [arg]
+Max files to cache per query (Should not exceed maximum number of open file descriptors allowed per process) (default 500).
+.TP
+\fB\-\-no\-filemanager\-watch\fR|\-M
+Don't use a file system watcher for filemanager.
+.TP
+\fB\-\-no\-filemanager\fR
+Don't scan project directory for files. (rc \fB\-P\fR won't work).
+.TP
+\fB\-\-no\-file\-lock\fR
+Disable file locking. Not entirely safe but might improve performance on certain systems.
+.TP
+\fB\-\-pch\-enabled\fR
+Enable PCH (experimental).
+.TP
+\fB\-\-no\-filesystem\-watcher\fR|\-B
+Disable file system watching altogether. Reindexing has to be triggered manually.
+.TP
+\fB\-\-arg\-transform\fR|\-V [arg]
+Use arg to transform arguments. [arg] should be executable with (execv(3)).
+.TP
+\fB\-\-no\-comments\fR
+Don't parse/store doxygen comments.
+.TP
+\fB\-\-inactivity\-timeout\fR [arg]
+Time in seconds after which rdm will quit if there's been no activity (N.B., once rdm has quit, something will need to re\-run it!).
+.TP
+\fB\-\-daemon\fR
+Run as daemon (detach from terminal).
+.TP
+\fB\-\-log\-file\-log\-level\fR [arg]
+Log level for log file (default is error), options are: error, warning, debug or verbose\-debug.
+.TP
+\fB\-\-watch\-sources\-only\fR
+Only watch source files (not dependencies).
+.TP
+\fB\-\-debug\-locations\fR
+Set debug locations.
+.TP
+\fB\-\-validate\-file\-maps\fR
+Spend some time validating project data on startup.
+.TP
+\fB\-\-tcp\-port\fR [arg]
+Listen on this tcp socket (default none).
+.TP
+\fB\-\-rp\-path\fR [arg]
+Path to rp.
+.TP
+\fB\-\-log\-timestamp\fR
+Add timestamp to logs.
+.TP
+\fB\-\-log\-flush\fR
+Flush stderr/stdout after each log.
+.TP
+\fB\-\-sandbox\-root\fR [arg]
+Create index using relative paths by stripping dir (enables copying of tag index db files without need to reindex).
+.TP
+\fB\-\-poll\-timer\fR [arg]
+Poll the database of the current project every seconds.
+.TP
+\fB\-\-no\-realpath\fR
+Don't use realpath(3) for files
+.TP
+\fB\-\-translation\-unit\-cache\fR
+Cache translation units. Not working yet.
+.TP
+\fB\-\-config\fR|\-c [arg]
+Use this file (instead of ~/.rdmrc).
+.TP
+\fB\-\-no\-rc\fR|\-N
+Don't load any rc files.
+.SH "SEE ALSO"
+rc(7)
diff --git a/rtags/scripts/bump-version.sh b/rtags/scripts/bump-version.sh
new file mode 100755
index 0000000..098559e
--- /dev/null
+++ b/rtags/scripts/bump-version.sh
@@ -0,0 +1,25 @@
+#!/bin/bash
+
+SCRIPT="$(readlink -f ${BASH_SOURCE[0]})"
+DIR="$(dirname $SCRIPT)"
+
+# echo "$SCRIPT $DIR"
+
+MAJOR=`echo $1 | awk -F. '{print $1}'`
+MINOR=`echo $1 | awk -F. '{print $2}'`
+
+if ! echo "$1" | grep -q "^[0-9]\+\.[0-9]\+$"; then
+ echo "Bad argument: \"$1\""
+ echo "Usage bump-version.sh 3.22"
+ exit 1
+fi
+
+SED=sed
+[ -n "`which gsed`" ] && SED=gsed
+
+$SED -i"" -e "s,^set(RTAGS_VERSION_MAJOR [0-9]\+),set(RTAGS_VERSION_MAJOR $MAJOR)," -e "s,^set(RTAGS_VERSION_MINOR [0-9]\+),set(RTAGS_VERSION_MINOR $MINOR)," "$DIR/../CMakeLists.txt"
+$SED -i"" -e "s,^(defconst rtags-package-version \"[0-9]\+\.[0-9]\+\"),(defconst rtags-package-version \"${MAJOR}.${MINOR}\")," "$DIR/../src/rtags.el"
+$SED -i"" -e "s,https://andersbakken\.github\.io/rtags-releases/rtags-[0-9]\+\.[0-9]\+\.tar\.,https://andersbakken.github.io/rtags-releases/rtags-$MAJOR.$MINOR.tar.,g" "$DIR/../README.org"
+
+git commit -m "Bump version to ${MAJOR}.${MINOR}" $DIR/../README.org $DIR/../CMakeLists.txt $DIR/../src/rtags.el
+git tag "v${MAJOR}.${MINOR}"
diff --git a/rtags/scripts/fix-dylib.sh b/rtags/scripts/fix-dylib.sh
new file mode 100755
index 0000000..83f4fe0
--- /dev/null
+++ b/rtags/scripts/fix-dylib.sh
@@ -0,0 +1,6 @@
+#!/bin/sh
+
+#nstall_name_tool -change "@executable_path/../lib/libclang.3.2.dylib" "@executable_path/../3rdparty/clang_install/lib/libclang.3.2.dylib" rdm
+
+REAL=$(readlink "$1"/3rdparty/clang_install/lib/libclang.dylib)
+install_name_tool -change "@executable_path/../lib/$(basename \"$REAL\")" "@executable_path/../3rdparty/clang_install/lib/$(basename \"$REAL\")" $2
diff --git a/rtags/scripts/gen-man-pages.sh b/rtags/scripts/gen-man-pages.sh
new file mode 100755
index 0000000..8a394c6
--- /dev/null
+++ b/rtags/scripts/gen-man-pages.sh
@@ -0,0 +1,93 @@
+#!/bin/bash -e
+# gen-man-pages.sh --- generate man pages
+#
+# Copyright (c) Christian Schwarzgruber
+#
+# This file is part of RTags (http://rtags.net).
+#
+# RTags is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or (at
+# your option) any later version.
+#
+# RTags is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with GNU Emacs. If not, see . */
+#
+# Description: rc, rdm and help2man need to be in the PATH environment variable.
+BASE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+
+if [ $# -lt 1 ]; then
+ echo "Usage: $(basename $0) RDM_RC_BIN_DIR"
+ exit 1
+fi
+
+MAN_BASE="$BASE_DIR/man/man7"
+
+# Force simply locale `C`
+LC_TIME=C
+
+# Generate the rc manual page.
+echo 'Generating manual page for "rc"'
+help2man --no-info -s 7 \
+ -i <(echo "
+[SYNOPSIS]
+rc [OPTION]...
+
+[DESCRIPTION]
+rc is the RTags client application.
+
+[SEE ALSO]
+rdm(7)
+") "$1/rc" > "$MAN_BASE/rc.7"
+
+# Generate the rdm manual page.
+echo 'Generating manual page for "rdm"'
+help2man --no-info -s 7 \
+ -i <(echo "
+[SYNOPSIS]
+rdm [OPTION]...
+
+[DESCRIPTION]
+RTags is a client/server application that indexes C/C++ code and keeps
+a persistent file\-based database of references, declarations,
+definitions, symbolnames etc. There's also limited support for
+ObjC/ObjC++. It allows you to find symbols by name (including nested
+class and namespace scope). Most importantly we give you proper
+follow\-symbol and find\-references support. We also have neat little
+things like rename\-symbol, integration with clang's \"fixits\"
+(http://clang.llvm.org/diagnostics.html). We also integrate with
+flymake using clang's vastly superior errors and warnings. Since
+RTags constantly will reindex \"dirty\" files you get live updates of
+compiler errors and warnings. Since we already know how to compile
+your sources we have a way to quickly bring up the preprocessed output
+of the current source file in a buffer.
+
+While existing taggers like gnu global, cscope, etags, ctags etc do a
+decent job for C they often fall a little bit short for C++. With its
+incredible lexical complexity, parsing C++ is an incredibly hard task
+and we make no bones about the fact that the only reason we are able
+to improve on the current tools is because of clang
+(http://clang.llvm.org/). RTags is named RTags in recognition of
+Roberto Raggi on whose C++ parser we intended to base this project but
+he assured us clang was the way to go. The name stuck though.
+
+[SEE ALSO]
+rc(7)
+") "$1/rdm" > "$MAN_BASE/rdm.7"
+
+# Fix-ups
+sed -ri \
+ -e '/^(rdm|rc) options...$/d' \
+ -e 's/^Options:$/.SH OPTIONS/' \
+ -e 's/^(Path to rp) \(default.*\).$/\1./' \
+ -e '/job\\-count/{
+ n
+ s/(.*indexing) \(default [0-9]+\).$/\1./
+ }' \
+ "$MAN_BASE/rc.7" "$MAN_BASE/rdm.7"
+exit 0
diff --git a/rtags/scripts/getclang.sh b/rtags/scripts/getclang.sh
new file mode 100755
index 0000000..136f32d
--- /dev/null
+++ b/rtags/scripts/getclang.sh
@@ -0,0 +1,38 @@
+#!/bin/bash
+
+VERSION="$1"
+[ -z "${VERSION}" ] && VERSION="3.8.1"
+
+CHECKSUMDIR=`dirname "${BASH_SOURCE[0]}"`/../llvm-checksums/
+
+LLVM=llvm-${VERSION}.src
+LLVM_FILE=${LLVM}.tar.xz
+CLANG=cfe-${VERSION}.src
+CLANG_FILE=${CLANG}.tar.xz
+LIBCXX=libcxx-${VERSION}.src
+LIBCXX_FILE=${LIBCXX}.tar.xz
+
+function dnload()
+{
+ local FILE=$1-${VERSION}.src.tar.xz
+ local URL=http://llvm.org/releases/${VERSION}/${FILE}
+ STATUS=`curl -L -w "%{http_code}" -z ${FILE} https://releases.llvm.org/${VERSION}/${FILE} -o ${FILE} 2>/dev/null`
+ echo ${STATUS}
+}
+
+STATUS=`dnload llvm`
+if [ "${STATUS}" == 200 ] || [ ! -d llvm ]; then
+ tar xf ${LLVM_FILE}
+ rm -rf llvm
+ mv ${LLVM} llvm
+ dnload cfe >/dev/null
+ tar xf ${CLANG_FILE}
+ rm -f llvm/tools/clang
+ mv ${CLANG} llvm/tools/clang
+
+ if [ `uname -s` = Darwin ]; then
+ dnload libcxx >/dev/null
+ tar xf ${LIBCXX_FILE}
+ mv ${LIBCXX} llvm/projects/libcxx
+ fi
+fi
diff --git a/rtags/scripts/git-archive-all b/rtags/scripts/git-archive-all
new file mode 100755
index 0000000..0f96f00
--- /dev/null
+++ b/rtags/scripts/git-archive-all
@@ -0,0 +1,292 @@
+#!/bin/bash -
+#
+# File: git-archive-all.sh
+#
+# Description: A utility script that builds an archive file(s) of all
+# git repositories and submodules in the current path.
+# Useful for creating a single tarfile of a git super-
+# project that contains other submodules.
+#
+# Examples: Use git-archive-all.sh to create archive distributions
+# from git repositories. To use, simply do:
+#
+# cd $GIT_DIR; git-archive-all.sh
+#
+# where $GIT_DIR is the root of your git superproject.
+#
+# License: GPL3
+#
+###############################################################################
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+#
+###############################################################################
+
+# DEBUGGING
+set -e
+set -C # noclobber
+
+# TRAP SIGNALS
+trap 'cleanup' QUIT EXIT
+
+# For security reasons, explicitly set the internal field separator
+# to newline, space, tab
+OLD_IFS=$IFS
+IFS='
+ '
+
+function cleanup () {
+ rm -f $TMPFILE
+ rm -f $TOARCHIVE
+ IFS="$OLD_IFS"
+}
+
+function usage () {
+ echo "Usage is as follows:"
+ echo
+ echo "$PROGRAM <--version>"
+ echo " Prints the program version number on a line by itself and exits."
+ echo
+ echo "$PROGRAM <--usage|--help|-?>"
+ echo " Prints this usage output and exits."
+ echo
+ echo "$PROGRAM [--format ] [--prefix ] [--verbose|-v] [--separate|-s]"
+ echo " [--tree-ish|-t ] [output_file]"
+ echo " Creates an archive for the entire git superproject, and its submodules"
+ echo " using the passed parameters, described below."
+ echo
+ echo " If '--format' is specified, the archive is created with the named"
+ echo " git archiver backend. Obviously, this must be a backend that git archive"
+ echo " understands. The format defaults to 'tar' if not specified."
+ echo
+ echo " If '--prefix' is specified, the archive's superproject and all submodules"
+ echo " are created with the prefix named. The default is to not use one."
+ echo
+ echo " If '--separate' or '-s' is specified, individual archives will be created"
+ echo " for each of the superproject itself and its submodules. The default is to"
+ echo " concatenate individual archives into one larger archive."
+ echo
+ echo " If '--tree-ish' is specified, the archive will be created based on whatever"
+ echo " you define the tree-ish to be. Branch names, commit hash, etc. are acceptable."
+ echo " Defaults to HEAD if not specified. See git archive's documentation for more"
+ echo " information on what a tree-ish is."
+ echo
+ echo " If 'output_file' is specified, the resulting archive is created as the"
+ echo " file named. This parameter is essentially a path that must be writeable."
+ echo " When combined with '--separate' ('-s') this path must refer to a directory."
+ echo " Without this parameter or when combined with '--separate' the resulting"
+ echo " archive(s) are named with a dot-separated path of the archived directory and"
+ echo " a file extension equal to their format (e.g., 'superdir.submodule1dir.tar')."
+ echo
+ echo " The special value '-' (single dash) is treated as STDOUT and, when used, the"
+ echo " --separate option is ignored. Use a double-dash to separate the outfile from"
+ echo " the value of previous options. For example, to write a .zip file to STDOUT:"
+ echo
+ echo " ./$PROGRAM --format zip -- -"
+ echo
+ echo " If '--verbose' or '-v' is specified, progress will be printed."
+}
+
+function version () {
+ echo "$PROGRAM version $VERSION"
+}
+
+# Internal variables and initializations.
+readonly PROGRAM=$(basename "$0")
+readonly VERSION=0.3
+
+SEPARATE=0
+VERBOSE=0
+
+TARCMD=$(command -v gnutar || command -v gtar || command -v tar)
+FORMAT=tar
+PREFIX=
+TREEISH=HEAD
+
+# RETURN VALUES/EXIT STATUS CODES
+readonly E_BAD_OPTION=254
+readonly E_UNKNOWN=255
+
+# Process command-line arguments.
+while test $# -gt 0; do
+ if [ x"$1" == x"--" ]; then
+ # detect argument termination
+ shift
+ break
+ fi
+ case $1 in
+ --format )
+ shift
+ FORMAT="$1"
+ shift
+ ;;
+
+ --prefix )
+ shift
+ PREFIX="$1"
+ shift
+ ;;
+
+ --separate | -s )
+ shift
+ SEPARATE=1
+ ;;
+
+ --tree-ish | -t )
+ shift
+ TREEISH="$1"
+ shift
+ ;;
+
+ --version )
+ version
+ exit
+ ;;
+
+ --verbose | -v )
+ shift
+ VERBOSE=1
+ ;;
+
+ -? | --usage | --help )
+ usage
+ exit
+ ;;
+
+ -* )
+ echo "Unrecognized option: $1" >&2
+ usage
+ exit $E_BAD_OPTION
+ ;;
+
+ * )
+ break
+ ;;
+ esac
+done
+
+OLD_PWD=$(pwd)
+TMPDIR=${TMPDIR:-/tmp}
+TMPFILE=$(mktemp "$TMPDIR/$PROGRAM.XXXXXX") # Create a place to store our work's progress
+TOARCHIVE=$(mktemp "$TMPDIR/$PROGRAM.toarchive.XXXXXX")
+OUT_FILE=$OLD_PWD # assume "this directory" without a name change by default
+
+if [ ! -z "$1" ]; then
+ OUT_FILE="$1"
+ if [ "-" == $OUT_FILE ]; then
+ SEPARATE=0
+ fi
+ shift
+fi
+
+# Validate parameters; error early, error often.
+if [ "-" == $OUT_FILE -o $SEPARATE -ne 1 ] && [ "$FORMAT" == "tar" -a $($TARCMD --help | grep -q -- "--concatenate"; echo $?) -ne 0 ]; then
+ echo "Your 'tar' does not support the '--concatenate' option, which we need"
+ echo "to produce a single tarfile. Either install a compatible tar (such as"
+ echo "gnutar), or invoke $PROGRAM with the '--separate' option."
+ exit
+elif [ $SEPARATE -eq 1 -a ! -d $OUT_FILE ]; then
+ echo "When creating multiple archives, your destination must be a directory."
+ echo "If it's not, you risk being surprised when your files are overwritten."
+ exit
+elif [ $(git config -l | grep -q '^core\.bare=false'; echo $?) -ne 0 ]; then
+ echo "$PROGRAM must be run from a git working copy (i.e., not a bare repository)."
+ exit
+fi
+
+# Create the superproject's git-archive
+if [ $VERBOSE -eq 1 ]; then
+ echo -n "creating superproject archive..."
+fi
+git archive --format=$FORMAT --prefix="$PREFIX" $TREEISH > "$TMPDIR/$(basename "$(pwd)").$FORMAT"
+if [ $VERBOSE -eq 1 ]; then
+ echo "done"
+fi
+echo "$TMPDIR/$(basename "$(pwd)").$FORMAT" >| $TMPFILE # clobber on purpose
+superfile=$(head -n 1 $TMPFILE)
+
+if [ $VERBOSE -eq 1 ]; then
+ echo -n "looking for subprojects..."
+fi
+# find all '.git' dirs, these show us the remaining to-be-archived dirs
+# we only want directories that are below the current directory
+find . -mindepth 2 -name '.git' -type d -print | sed -e 's/^\.\///' -e 's/\.git$//' >> $TOARCHIVE
+# as of version 1.7.8, git places the submodule .git directories under the superprojects .git dir
+# the submodules get a .git file that points to their .git dir. we need to find all of these too
+find . -mindepth 2 -name '.git' -type f -print0 | xargs -0 grep -l "gitdir" | sed -e 's/^\.\///' -e 's/\.git$//' >> $TOARCHIVE
+if [ $VERBOSE -eq 1 ]; then
+ echo "done"
+ echo " found:"
+ while read arch
+ do
+ echo " $arch"
+ done < $TOARCHIVE
+fi
+
+if [ $VERBOSE -eq 1 ]; then
+ echo -n "archiving submodules..."
+fi
+while read path; do
+ TREEISH=$(git submodule | grep "^ .*${path%/} " | cut -d ' ' -f 2) # git submodule does not list trailing slashes in $path
+ cd "$path"
+ git archive --format=$FORMAT --prefix="${PREFIX}$path" ${TREEISH:-HEAD} > "$TMPDIR"/"$(echo "$path" | sed -e 's/\//./g')"$FORMAT
+ if [ $FORMAT == 'zip' ]; then
+ # delete the empty directory entry; zipped submodules won't unzip if we don't do this
+ zip -d "$(tail -n 1 $TMPFILE)" "${PREFIX}${path%/}" >/dev/null # remove trailing '/'
+ fi
+ echo "$TMPDIR"/"$(echo "$path" | sed -e 's/\//./g')"$FORMAT >> $TMPFILE
+ cd "$OLD_PWD"
+done < $TOARCHIVE
+if [ $VERBOSE -eq 1 ]; then
+ echo "done"
+fi
+
+if [ $VERBOSE -eq 1 ]; then
+ echo -n "concatenating archives into single archive..."
+fi
+# Concatenate archives into a super-archive.
+if [ $SEPARATE -eq 0 -o "-" == $OUT_FILE ]; then
+ if [ $FORMAT == 'tar' ]; then
+ sed -e '1d' $TMPFILE | while read file; do
+ $TARCMD --concatenate -f "$superfile" "$file" && rm -f "$file"
+ done
+ elif [ $FORMAT == 'zip' ]; then
+ sed -e '1d' $TMPFILE | while read file; do
+ # zip incorrectly stores the full path, so cd and then grow
+ cd "$(dirname $file)"
+ zip -g "$superfile" "$(basename $file)" && rm -f "$file"
+ done
+ cd "$OLD_PWD"
+ fi
+
+ echo "$superfile" >| $TMPFILE # clobber on purpose
+fi
+if [ $VERBOSE -eq 1 ]; then
+ echo "done"
+fi
+
+if [ $VERBOSE -eq 1 ]; then
+ echo -n "moving archive to $OUT_FILE..."
+fi
+while read file; do
+ if [ "-" == $OUT_FILE ]; then
+ cat "$file" && rm -f "$file"
+ else
+ mv "$file" "$OUT_FILE"
+ fi
+done < $TMPFILE
+if [ $VERBOSE -eq 1 ]; then
+ echo "done"
+fi
diff --git a/rtags/scripts/llvm-osx/build.sh b/rtags/scripts/llvm-osx/build.sh
new file mode 100755
index 0000000..107ad5b
--- /dev/null
+++ b/rtags/scripts/llvm-osx/build.sh
@@ -0,0 +1,3 @@
+#!/bin/bash
+brew tap homebrew/versions
+brew install llvm38 --with-libcxx --with-clang --without-assertions --rtti $@
diff --git a/rtags/scripts/rtags-release.sh b/rtags/scripts/rtags-release.sh
new file mode 100755
index 0000000..0a1ff52
--- /dev/null
+++ b/rtags/scripts/rtags-release.sh
@@ -0,0 +1,69 @@
+#!/bin/bash
+
+### TO RUN
+### curl https://raw.githubusercontent.com/Andersbakken/rtags/master/scripts/rtags-release.sh | bash
+
+REPO=`mktemp -d`
+RELEASES_REPO=`mktemp -d`
+CMAKE_ARGS="-DRTAGS_ENABLE_DEV_OPTIONS=1"
+FORCE=
+
+while [ -n "$1" ]; do
+ case "$1" in
+ --repo|-r)
+ shift
+ REPO="$1"
+ ;;
+ --releases-repo|-R)
+ shift
+ RELEASES_REPO="$1"
+ ;;
+ --force|-f)
+ FORCE=1
+ ;;
+ --cmake-args|-C)
+ shift
+ CMAKE_ARGS="$CMAKE_ARGS $1"
+ ;;
+ *)
+ echo "Unknown option $1"
+ exit 1
+ ;;
+ esac
+ shift
+done
+
+git clone git@github.com:Andersbakken/rtags.git "$REPO" --recursive --depth 1 || exit 1
+cd "$REPO"
+
+branch_name="$(git symbolic-ref HEAD 2>/dev/null)" || branch_name="(unnamed branch)" # detached HEAD
+branch_name=${branch_name##refs/heads/}
+if [ "$branch_name" != "master" ]; then
+ echo wrong branch $branch_name
+ exit 1
+fi
+
+commit=$(git show --oneline --no-patch)
+current=`curl --silent http://andersbakken.github.io/rtags-releases/commit | cut -d' ' -f1`
+if [ "`echo "$commit" | cut -d' ' -f1`" = "$current" -a -z "$FORCE" ]; then
+ exit 0
+fi
+
+git clone git@github.com:Andersbakken/rtags-releases.git "$RELEASES_REPO" --recursive --depth 1 || exit 1
+cd "$RELEASES_REPO"
+if ! git branch | grep --quiet "^\* *gh-pages$"; then
+ echo "wrong branch"
+ exit 1
+fi
+
+rm -rf .git/hooks/*
+
+cmake "$REPO" $CMAKE_ARGS >/dev/null || exit 1
+make package_source >/dev/null || exit 1
+cmake "$REPO" $CMAKE_ARGS -DCPACK_GENERATOR=TBZ2 >/dev/null 2>&1 || exit 1
+make package_source >/dev/null || exit 1
+echo "$commit" > commit
+git add *.tar.gz *.tar.bz2 commit >/dev/null
+git commit --amend -m "Release for $commit" >/dev/null
+git push -f git@github.com:Andersbakken/rtags-releases.git gh-pages >/dev/null
+rm -rf "$REPO" "$RELEASES_REPO"
diff --git a/rtags/scripts/travis.sh b/rtags/scripts/travis.sh
new file mode 100755
index 0000000..12948bc
--- /dev/null
+++ b/rtags/scripts/travis.sh
@@ -0,0 +1,94 @@
+#!/bin/bash -e
+# travis.sh --- setup and compile script for travis
+#
+# Copyright (c) Christian Schwarzgruber
+# Author: Christian Schwarzgruber
+# Created: Tue May 10 22:28:28 2016 (+0200)
+#
+# This file is part of RTags (http://rtags.net).
+#
+# RTags is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# RTags is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with RTags. If not, see . */
+#
+# Description: The following variables can be changed from the build matrix:
+# - ASAN (default value is "1")
+# - LUA_VERSION (default value is "5.3.2")
+# - LUA_DISABLE (default value is "", set it to anything to disable lua
+# extension for that matrix)
+declare -a CMAKE_PARAMS=("-DCMAKE_CXX_COMPILER=$CXX$COMPILER_VERSION"
+ "-DBUILD_TESTING=1"
+ "-DCMAKE_C_COMPILER=$CC$COMPILER_VERSION")
+
+if [ "$ASAN" ]; then
+ CMAKE_PARAMS+=("-DASAN=address,undefined")
+fi
+
+LUA_DISABLE=${LUA_DISABLE:-""}
+if [ ! $LUA_DISABLE ]; then
+ CMAKE_PARAMS+=("-DLUA_ENABLED=1")
+ echo "Running build with Lua extension."
+else
+ echo "Running build without Lua extension."
+fi # end ! $LUA_DISABLE
+
+function build()
+{
+ mkdir build && pushd build > /dev/null
+ cmake "${CMAKE_PARAMS[@]}" .. || cat CMakeFiles/CMakeError.log
+ make VERBOSE=1 -j2
+}
+
+# All arguments will be passed on to ctest
+function run_tests()
+{
+ PATH=$(pwd)/bin:$PATH
+ ctest --output-on-failure --verbose $@
+}
+
+function osx()
+{
+ ## Step -- Setup
+ brew update
+ brew install llvm yarn cppunit
+ brew upgrade python3
+ python3 -m pip install --upgrade pip
+ pip3 install --user --upgrade nose PyHamcrest
+ # Add nosetest bin dir to the env path var
+ PATH=$PATH:/Users/travis/Library/Python/3.6/bin
+
+ ## Step -- Build
+ build
+
+ ## Step -- Test
+ run_tests
+}
+
+function gnu_linux()
+{
+ ## Step -- Setup
+ pip3 install --user --upgrade nose PyHamcrest
+
+ ## Step -- Build
+ build
+
+ ## Step -- Test
+ run_tests
+}
+
+if [ $TRAVIS_OS_NAME = osx ]; then
+ osx
+else
+ gnu_linux
+fi
+
+exit 0
diff --git a/rtags/share/etc/init.d/rtags b/rtags/share/etc/init.d/rtags
new file mode 100755
index 0000000..2bd5be6
--- /dev/null
+++ b/rtags/share/etc/init.d/rtags
@@ -0,0 +1,49 @@
+#!/bin/bash
+#
+# chkconfig: 35 90 12
+# description: Foo server
+#
+
+# Get function from functions library
+. /etc/init.d/functions
+
+# Start the service FOO
+start() {
+ initlog -c "echo -n Starting FOO server: "
+ /path/to/FOO &
+ ### Create the lock file ###
+ touch /var/lock/subsys/FOO
+ success $"FOO server startup"
+ echo
+}
+
+# Restart the service FOO
+stop() {
+ initlog -c "echo -n Stopping FOO server: "
+ killproc FOO
+ ### Now, delete the lock file ###
+ rm -f /var/lock/subsys/FOO
+ echo
+}
+
+### main logic ###
+case "$1" in
+ start)
+ start
+ ;;
+ stop)
+ stop
+ ;;
+ status)
+ status FOO
+ ;;
+ restart|reload|condrestart)
+ stop
+ start
+ ;;
+ *)
+ echo $"Usage: $0 {start|stop|restart|reload|status}"
+ exit 1
+esac
+
+exit 0
diff --git a/rtags/share/etc/services/system/rdm.service b/rtags/share/etc/services/system/rdm.service
new file mode 100644
index 0000000..c0f6fd6
--- /dev/null
+++ b/rtags/share/etc/services/system/rdm.service
@@ -0,0 +1,11 @@
+[Unit]
+Description=RTags daemon
+
+Requires=rdm.socket
+
+[Service]
+Type=simple
+ExecStart=$RDM -v --inactivity-timeout 300 --log-flush
+ExecStartPost=/bin/sh -c "echo +19 > /proc/$MAINPID/autogroup"
+Nice=19
+CPUSchedulingPolicy=idle
diff --git a/rtags/share/etc/services/system/rdm.socket b/rtags/share/etc/services/system/rdm.socket
new file mode 100644
index 0000000..68363b6
--- /dev/null
+++ b/rtags/share/etc/services/system/rdm.socket
@@ -0,0 +1,8 @@
+[Unit]
+Description=RTags daemon socket
+
+[Socket]
+ListenStream=%t/rdm.socket
+
+[Install]
+WantedBy=default.target
diff --git a/rtags/src/AST.cpp b/rtags/src/AST.cpp
new file mode 100644
index 0000000..49a5057
--- /dev/null
+++ b/rtags/src/AST.cpp
@@ -0,0 +1,177 @@
+/* This file is part of RTags (http://rtags.net).
+
+ RTags is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ RTags is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with RTags. If not, see . */
+
+#include "AST.h"
+#include "ClangThread.h"
+#include "selene.h"
+
+#define TO_STR1(x) #x
+#define TO_STR(x) TO_STR1(x)
+
+struct UserData {
+ List parents;
+ AST *ast;
+};
+CXChildVisitResult AST::visitor(CXCursor cursor, CXCursor, CXClientData u)
+{
+ UserData *userData = reinterpret_cast(u);
+ assert(userData);
+ Cursor::Data *p = userData->parents.isEmpty() ? 0 : userData->parents.back().data.get();
+ Cursor c = userData->ast->construct(cursor, p);
+ userData->parents.push_back(Cursor { c.data } );
+ clang_visitChildren(cursor, visitor, u);
+ if (userData->parents.size() > 1)
+ userData->parents.pop_back();
+ return CXChildVisit_Continue;
+}
+
+template static void assign(sel::Selector selector, const T &t) { selector = t; }
+void assign(sel::Selector selector, const String &str) { selector = str.ref(); }
+
+template
+static void exposeArray(sel::Selector selector, const std::vector &array)
+{
+ int i = 0;
+ for (const T &t : array) {
+ assign(selector[i++], t);
+ }
+}
+
+static void registerClasses(sel::State &state)
+{
+ state["SourceLocation"].SetClass("line", &AST::SourceLocation::line,
+ "column", &AST::SourceLocation::column,
+ "file", &AST::SourceLocation::file,
+ "offset", &AST::SourceLocation::offset,
+ "toString", &AST::SourceLocation::toString);
+ state["SourceRange"].SetClass("start", &AST::SourceRange::start,
+ "end", &AST::SourceRange::end,
+ "length", &AST::SourceRange::length,
+ "toString", &AST::SourceRange::toString);
+
+ auto cursors = state["Cursors"];
+ cursors.SetClass("size", &AST::Cursors::size,
+ "at", &AST::Cursors::at);
+ auto cursor = state["Cursor"];
+ cursor.SetClass("location", &AST::Cursor::location,
+ "usr", &AST::Cursor::usr,
+ "kind", &AST::Cursor::kind,
+ "linkage", &AST::Cursor::linkage,
+ "availability", &AST::Cursor::availability,
+ "language", &AST::Cursor::language,
+ "spelling", &AST::Cursor::spelling,
+ "displayName", &AST::Cursor::displayName,
+ "rawComment", &AST::Cursor::rawComment,
+ "briefComment", &AST::Cursor::briefComment,
+ "mangledName", &AST::Cursor::mangledName,
+ "templateKind", &AST::Cursor::templateKind,
+ "range", &AST::Cursor::range,
+ "children", &AST::Cursor::children,
+ "query", &AST::Cursor::query,
+ "None", &AST::Cursor::none,
+ "Add", &AST::Cursor::add,
+ "Recurse", &AST::Cursor::recurse,
+ "overriddenCount", &AST::Cursor::overriddenCount,
+ "overriddenCursors", &AST::Cursor::overriddenCursors,
+ "argumentCount", &AST::Cursor::argumentCount,
+ "arguments", &AST::Cursor::arguments,
+ "fieldBitWidth", &AST::Cursor::fieldBitWidth,
+ "typedefUnderlyingType", &AST::Cursor::typedefUnderlyingType,
+ "enumIntegerType", &AST::Cursor::enumIntegerType,
+ "enumConstantValue", &AST::Cursor::enumConstantValue,
+ "includedFile", &AST::Cursor::includedFile,
+ "templateArgumentCount", &AST::Cursor::templateArgumentCount,
+ "templateArgumentType", &AST::Cursor::templateArgumentType,
+ "templateArgumentValue", &AST::Cursor::templateArgumentValue,
+ "templateArgumentKind", &AST::Cursor::templateArgumentKind,
+ "referenced", &AST::Cursor::referenced,
+ "canonical", &AST::Cursor::canonical,
+ "lexicalParent", &AST::Cursor::lexicalParent,
+ "semanticParent", &AST::Cursor::semanticParent,
+ "definitionCursor", &AST::Cursor::definitionCursor,
+ "specializedCursorTemplate", &AST::Cursor::specializedCursorTemplate,
+ "childCount", &AST::Cursor::childCount,
+ "child", &AST::Cursor::child,
+ "isBitField", &AST::Cursor::isBitField,
+ "isVirtualBase", &AST::Cursor::isVirtualBase,
+ "isStatic", &AST::Cursor::isStatic,
+ "isVirtual", &AST::Cursor::isVirtual,
+ "isPureVirtual", &AST::Cursor::isPureVirtual,
+ "isConst", &AST::Cursor::isConst,
+ "isDefinition", &AST::Cursor::isDefinition,
+ "isDynamicCall", &AST::Cursor::isDynamicCall);
+}
+
+std::shared_ptr AST::create(const Source &source, const String &sourceCode, CXTranslationUnit unit)
+{
+ std::shared_ptr ast(new AST);
+ ast->mState.reset(new sel::State {true});
+ sel::State &state = *ast->mState;
+ registerClasses(state);
+ ast->mSourceCode = sourceCode;
+ state["sourceFile"] = source.sourceFile().ref();
+ state["sourceCode"] = sourceCode.ref();
+ state["write"] = [ast](const std::string &str) {
+ // error() << "writing" << str;
+ ast->mReturnValues.append(str);
+ };
+
+ exposeArray(state["commandLine"], source.toCommandLine(Source::Default|Source::IncludeCompiler|Source::IncludeSourceFile));
+
+ if (unit) {
+ UserData userData;
+ userData.ast = ast.get();
+ visitor(clang_getTranslationUnitCursor(unit), clang_getNullCursor(), &userData);
+
+ const Cursor root = userData.parents.front();
+ state["root"] = [root]() { return root; };
+ state["findByUsr"] = [ast](const std::string &usr) {
+ return ast->mByUsr.value(usr);
+ };
+
+ state["findByOffset"] = [ast](const std::string &str) {
+ // int offset = atoi(str.c_str());
+ // if (offset) {
+
+ // } else
+ // sscanf
+ // return mByUsr.value(usr);
+ };
+ const String script = Path(TO_STR(RTAGS_SOURCE_DIR) "/rtags.lua").readAll();
+ state(script.constData());
+ }
+ return ast;
+}
+
+List AST::diagnostics() const
+{
+ return List();
+}
+
+List AST::skippedRanges() const
+{
+ return List();
+}
+
+List AST::evaluate(const String &script)
+{
+ assert(mReturnValues.isEmpty());
+ try {
+ mState->operator()(script.constData());
+ } catch (...) {
+ error() << "Got exception";
+ }
+ return std::move(mReturnValues);
+}
diff --git a/rtags/src/AST.h b/rtags/src/AST.h
new file mode 100644
index 0000000..faddefe
--- /dev/null
+++ b/rtags/src/AST.h
@@ -0,0 +1,460 @@
+#ifndef AST_h
+#define AST_h
+
+/* This file is part of RTags (http://rtags.net).
+
+ RTags is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ RTags is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with RTags. If not, see . */
+
+#include
+#include "Source.h"
+#include "Location.h"
+#include "RTags.h"
+#include "rct/String.h"
+#include "rct/List.h"
+
+namespace sel {
+class State;
+};
+class AST
+{
+public:
+ template
+ static std::string toString(T t)
+ {
+ String str;
+ Log(&str) << t;
+ return str.ref();
+ }
+ static std::string toString(CXString str)
+ {
+ return RTags::eatString(str).ref();
+ }
+ struct SourceLocation {
+ SourceLocation()
+ : offset(-1)
+ {}
+
+ bool operator<(const SourceLocation &other) const { return location < other.location; }
+
+ bool isNull() const { return location.isNull(); }
+ Location location;
+ int offset;
+
+ int line() const { return location.line(); }
+ int column() const { return location.column(); }
+ std::string file() const { return location.path(); }
+ std::string toString() const
+ {
+ return String::format<256>("%s,%d",
+ location.toString(Location::AbsolutePath|Location::NoColor).constData(),
+ offset);
+ }
+
+ };
+
+ struct SourceRange {
+ SourceRange(const CXSourceRange &r = clang_getNullRange())
+ : range(r)
+ {}
+ CXSourceRange range;
+
+ SourceLocation start() const { return AST::createLocation(clang_getRangeStart(range)); }
+ SourceLocation end() const { return AST::createLocation(clang_getRangeEnd(range)); }
+ int length() const { return end().offset - start().offset; }
+ std::string toString() const { return start().toString() + " - " + end().toString(); }
+ };
+ struct CursorType;
+ struct Cursors;
+ struct Cursor {
+ struct Data : public std::enable_shared_from_this {
+ Data(AST *a, Data *p, const CXCursor &c, const SourceLocation &loc, const std::string &u = std::string())
+ : ast(a), parent(p), cursor(c), location(loc), usr(u)
+ {
+ }
+ ~Data()
+ {
+ for (Data *child : children)
+ delete child;
+ }
+
+ AST *ast;
+ Data *parent;
+ List children;
+ CXCursor cursor;
+ SourceLocation location;
+ std::string usr;
+ };
+
+ SourceLocation location() const { return data ? data->location : SourceLocation(); }
+ std::string usr() const { return data ? data->usr : std::string(); }
+ std::string kind() const { return stringProperty(&clang_getCursorKind); }
+ std::string linkage() const { return stringProperty(&clang_getCursorLinkage); }
+ std::string availability() const { return stringProperty(&clang_getCursorAvailability); }
+ std::string language() const { return stringProperty(&clang_getCursorAvailability); }
+ std::string spelling() const { return stringProperty(&clang_getCursorSpelling); }
+ std::string displayName() const { return stringProperty(&clang_getCursorDisplayName); }
+ std::string rawComment() const { return stringProperty(&clang_Cursor_getRawCommentText); }
+ std::string briefComment() const { return stringProperty(&clang_Cursor_getBriefCommentText); }
+
+ std::string mangledName() const
+ {
+#if CINDEX_VERSION > CINDEX_VERSION_ENCODE(0, 28)
+ return stringProperty(&clang_Cursor_getMangling);
+#else
+ return std::string();
+#endif
+ }
+ std::string templateKind() const { return stringProperty(&clang_getTemplateCursorKind); }
+ SourceRange range() const { return data ? SourceRange { clang_getCursorExtent(data->cursor) } : SourceRange(); }
+ unsigned overriddenCount() const
+ {
+ unsigned count = 0;
+ if (data) {
+ CXCursor *overridden = 0;
+ clang_getOverriddenCursors(data->cursor, &overridden, &count);
+ if (overridden)
+ clang_disposeOverriddenCursors(overridden);
+ }
+ return count;
+ }
+ Cursors overriddenCursors() const
+ {
+ Cursors ret;
+ if (data) {
+ CXCursor *overridden = 0;
+ unsigned count;
+ clang_getOverriddenCursors(data->cursor, &overridden, &count);
+ ret.resize(count);
+ for (unsigned i=0; iast->create(overridden[i]);
+ clang_disposeOverriddenCursors(overridden);
+ }
+ return ret;
+ }
+
+ unsigned argumentCount() const { return data ? RTags::cursorArguments(data->cursor) : 0; }
+ inline Cursors arguments() const;
+
+ int fieldBitWidth() const { return intProperty(&clang_getFieldDeclBitWidth); }
+ CursorType typedefUnderlyingType() const { return cursorTypeProperty(&clang_getTypedefDeclUnderlyingType); }
+ CursorType enumIntegerType() const { return cursorTypeProperty(&clang_getEnumDeclIntegerType); }
+ long long enumConstantValue() const { return intProperty(&clang_getEnumConstantDeclValue); }
+ std::string includedFile() const
+ {
+ if (data && clang_getCursorKind(data->cursor) == CXCursor_InclusionDirective) {
+ CXFile includedFile = clang_getIncludedFile(data->cursor);
+ if (includedFile) {
+ CXStringScope fn = clang_getFileName(includedFile);
+ const char *cstr = clang_getCString(fn);
+ if (cstr)
+ return Path::resolved(cstr).ref();
+ }
+ }
+ return std::string();
+ }
+
+ unsigned templateArgumentCount() const
+ {
+#if CINDEX_VERSION > CINDEX_VERSION_ENCODE(0, 28)
+ return data ? clang_Cursor_getNumTemplateArguments(data->cursor) : 0;
+#else
+ return 0;
+#endif
+ }
+ CursorType templateArgumentType(unsigned idx) const
+ {
+#if CINDEX_VERSION > CINDEX_VERSION_ENCODE(0, 28)
+ return data ? CursorType(data->ast, clang_Cursor_getTemplateArgumentType(data->cursor, idx)) : CursorType();
+#else
+ (void)idx;
+ return CursorType();
+#endif
+ }
+ long long templateArgumentValue(unsigned idx) const
+ {
+#if CINDEX_VERSION > CINDEX_VERSION_ENCODE(0, 28)
+ return data ? clang_Cursor_getTemplateArgumentValue(data->cursor, idx) : -1;
+#else
+ (void)idx;
+ return -1;
+#endif
+ }
+ std::string templateArgumentKind(unsigned idx) const
+ {
+ std::string ret;
+#if CINDEX_VERSION > CINDEX_VERSION_ENCODE(0, 28)
+ if (data)
+ ret = toString(clang_Cursor_getTemplateArgumentKind(data->cursor, idx));
+#else
+ (void)idx;
+#endif
+ return ret;
+ }
+
+ Cursor referenced() const { return cursorProperty(&clang_getCursorReferenced); }
+ Cursor canonical() const { return cursorProperty(&clang_getCanonicalCursor); }
+ Cursor lexicalParent() const { return cursorProperty(&clang_getCursorLexicalParent); }
+ Cursor semanticParent() const { return cursorProperty(&clang_getCursorSemanticParent); }
+ Cursor definitionCursor() const { return cursorProperty(& clang_getCursorDefinition); }
+ Cursor specializedCursorTemplate() const { return cursorProperty(&clang_getSpecializedCursorTemplate); }
+ int childCount() const { return data ? data->children.size() : 0; }
+ Cursor child(int idx) const { return data ? Cursor{ data->children.value(idx)->shared_from_this() } : Cursor(); }
+ Cursors children() const;
+ enum QueryResult {
+ None = 0x0,
+ Add = 0x1,
+ Recurse = 0x2
+ };
+ unsigned none() const { return None; };
+ unsigned add() const { return Add; };
+ unsigned recurse() const { return Recurse; };
+ Cursors query(const std::function callback, int depth = INT_MAX) const
+ {
+ Cursors ret;
+ if (data) {
+ const unsigned result = callback(*this);
+ if (result & Add)
+ ret.append(*this);
+ if (result & Recurse && depth > 0) {
+ for (Data *childData : data->children) {
+ const Cursor child = { childData->shared_from_this() };
+ ret.append(child.query(callback, depth - 1));
+ }
+ }
+ }
+ return ret;
+ }
+
+ bool isBitField() const { return intProperty(&clang_Cursor_isBitField); }
+ bool isVirtualBase() const { return intProperty(&clang_isVirtualBase); }
+ bool isStatic() const { return intProperty(&clang_CXXMethod_isStatic); }
+ bool isVirtual() const { return intProperty(&clang_CXXMethod_isVirtual); }
+ bool isPureVirtual() const
+ {
+#if CINDEX_VERSION >= CINDEX_VERSION_ENCODE(0, 20)
+ return intProperty(&clang_CXXMethod_isPureVirtual);
+#else
+ return false;
+#endif
+ }
+ bool isConst() const
+ {
+#if CINDEX_VERSION > CINDEX_VERSION_ENCODE(0, 20)
+ return intProperty(&clang_CXXMethod_isConst);
+#else
+ return false;
+#endif
+ }
+ bool isDefinition() const { return intProperty(&clang_isCursorDefinition); }
+ bool isDynamicCall() const { return intProperty(&clang_Cursor_isDynamicCall); }
+
+ template std::string stringProperty(Func func) const { return data ? toString(func(data->cursor)) : std::string(); }
+ template Ret intProperty(Type (*func)(CXCursor), Type defaultValue = Type()) const { return data ? func(data->cursor) : defaultValue; }
+ template Cursor cursorProperty(Func func) const { return data ? data->ast->create(func(data->cursor)) : Cursor(); }
+ template CursorType cursorTypeProperty(Func func) const { return data ? CursorType(data->ast, func(data->cursor)) : CursorType(); }
+
+ std::shared_ptr data;
+ };
+
+ struct Cursors : public List
+ {
+ int size() const { return List::size(); }
+ Cursor at(int idx) const { return value(idx); }
+ };
+
+ struct CursorType {
+ CursorType(const AST *a, const CXType &t) : ast(a), type(t) {}
+ CursorType(const AST *a = 0) : ast(a) { memset(&type, 0, sizeof(type)); }
+
+ std::string spelling() const { return toString(clang_getTypeSpelling(type)); }
+ Cursor declaration() const { return ast ? ast->create(clang_getTypeDeclaration(type)) : Cursor(); }
+ std::string callingConvention() const { return toString(clang_getFunctionTypeCallingConv(type)); }
+ std::string referenceType() const
+ {
+#if CINDEX_VERSION >= CINDEX_VERSION_ENCODE(0, 20)
+ return toString(clang_Type_getCXXRefQualifier(type));
+#else
+ return std::string();
+#endif
+ }
+ unsigned argumentCount() const { return clang_getNumArgTypes(type); }
+ CursorType argument(unsigned idx) const { return CursorType(ast, clang_getArgType(type, idx)); }
+ unsigned templateArgumentCount() const
+ {
+#if CINDEX_VERSION > CINDEX_VERSION_ENCODE(0, 20)
+ return clang_Type_getNumTemplateArguments(type);
+#else
+ return 0;
+#endif
+ }
+ CursorType templateArgument(unsigned idx) const
+ {
+#if CINDEX_VERSION > CINDEX_VERSION_ENCODE(0, 20)
+ return CursorType(ast, clang_Type_getTemplateArgumentAsType(type, idx));
+#else
+ (void)idx;
+ return CursorType();
+#endif
+ }
+ CursorType canonicalType() const { return CursorType(ast, clang_getCanonicalType(type)); }
+ CursorType pointeeType() const { return CursorType(ast, clang_getPointeeType(type)); }
+ CursorType resultType() const { return CursorType(ast, clang_getResultType(type)); }
+ CursorType elementType() const { return CursorType(ast, clang_getElementType(type)); }
+ CursorType arrayElementType() const { return CursorType(ast, clang_getElementType(type)); }
+ CursorType classType() const
+ {
+#if CINDEX_VERSION >= CINDEX_VERSION_ENCODE(0, 20)
+ return CursorType(ast, clang_Type_getClassType(type));
+#else
+ return CursorType();
+#endif
+ }
+
+ bool isConstQualified() const { return clang_isConstQualifiedType(type); }
+ bool isEstrictQualified() const { return clang_isRestrictQualifiedType(type); }
+ bool isVolatileQualified() const { return clang_isVolatileQualifiedType(type); }
+ bool isVariadic() const { return clang_isFunctionTypeVariadic(type); }
+ bool isPod() const { return clang_isPODType(type); }
+ long long numElements() const { return clang_getNumElements(type); }
+ long long arraySize() const { return clang_getArraySize(type); }
+ long long alignOf() const { return clang_Type_getAlignOf(type); }
+ long long sizeOf() const { return clang_Type_getSizeOf(type); }
+
+ const AST *ast;
+ CXType type;
+ };
+
+ struct Diagnostic {
+
+
+ };
+
+ struct SkippedRange {
+
+
+ };
+
+ static std::shared_ptr create(const Source &source, const String &sourceCode, CXTranslationUnit unit);
+ List evaluate(const String &script);
+ Cursor *root() const { return mRoot; }
+ List diagnostics() const;
+ List skippedRanges() const;
+ static SourceLocation createLocation(const CXCursor &cursor) { return createLocation(clang_getCursorLocation(cursor)); }
+ static SourceLocation createLocation(const CXSourceLocation &location)
+ {
+ SourceLocation loc;
+ loc.location = RTags::createLocation(location, &loc.offset);
+ return loc;
+ }
+
+ Cursor create(const CXCursor &cursor) const
+ {
+ if (clang_isInvalid(clang_getCursorKind(cursor)))
+ return Cursor();
+
+ auto match = [&cursor](const Cursors &cursors) -> Cursor {
+ for (const Cursor &c : cursors) {
+ assert(c.data);
+ if (clang_equalCursors(c.data->cursor, cursor)) {
+ return c;
+ }
+ }
+ // The explicit const cast is here to satisfy travis clang matrix.
+ // clang 3.4 does not allow to use two different return types
+ return Cursor();
+ };
+
+ const std::string usr = toString(clang_getCursorUSR(cursor));
+ if (!usr.empty()) {
+ auto it = mByUsr.find(usr);
+ if (it != mByUsr.end()) {
+ const Cursor ret = match(it->second);
+ if (ret.data)
+ return ret;
+ }
+ }
+
+ const SourceLocation loc = createLocation(cursor);
+ if (!loc.isNull()) {
+ auto it = mByLocation.find(loc);
+ if (it != mByLocation.end()) {
+ const Cursor ret = match(it->second);
+ if (ret.data)
+ return ret;
+ }
+ }
+ return construct(cursor, 0, loc, usr);
+ }
+private:
+ static CXChildVisitResult visitor(CXCursor cursor, CXCursor, CXClientData u);
+ Cursor construct(const CXCursor &cursor,
+ Cursor::Data *parent = 0,
+ SourceLocation loc = SourceLocation(),
+ std::string usr = std::string()) const
+ {
+ Cursor ret;
+ if (loc.isNull())
+ loc = createLocation(cursor);
+ if (usr.empty())
+ usr = toString(clang_getCursorUSR(cursor));
+ ret.data.reset(new Cursor::Data(const_cast(this), parent, cursor, loc, usr));
+ if (!loc.isNull())
+ mByLocation[loc].append(ret);
+ if (!ret.data->usr.empty())
+ mByUsr[usr].append(ret);
+ if (parent)
+ parent->children.append(ret.data.get());
+ return ret;
+ }
+ AST()
+ : mRoot(0)
+ {}
+ mutable Hash mByUsr;
+ mutable Map mByLocation;
+ String mSourceCode;
+ List mReturnValues;
+ Cursor *mRoot;
+ std::shared_ptr mState;
+};
+
+
+inline AST::Cursors AST::Cursor::children() const
+{
+ Cursors ret;
+ if (data) {
+ ret.resize(data->children.size());
+ int i = 0;
+ for (Data *child : data->children) {
+ ret[i++] = Cursor { child->shared_from_this() };
+ }
+ }
+ return ret;
+}
+
+inline AST::Cursors AST::Cursor::arguments() const
+{
+ AST::Cursors ret;
+ if (data) {
+ List args;
+ const unsigned size = RTags::cursorArguments(data->cursor, &args);
+ if (size) {
+ ret.resize(size);
+ for (unsigned i=0; iast->create(args[i]);
+ }
+ }
+ }
+ return ret;
+}
+#endif
diff --git a/rtags/src/CMakeLists.txt b/rtags/src/CMakeLists.txt
new file mode 100644
index 0000000..2ee7f4d
--- /dev/null
+++ b/rtags/src/CMakeLists.txt
@@ -0,0 +1,364 @@
+set(CMAKE_SKIP_BUILD_RPATH FALSE)
+set(CMAKE_BUILD_WITH_INSTALL_RPATH FALSE)
+set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
+
+include(ExternalProject)
+
+if (RTAGS_BUILD_CLANG)
+ set(LIBCLANG_VERSION_STRING "5.0.0")
+ if (RTAGS_NO_INSTALL)
+ set(CLANG_INSTALL_PATH ${CMAKE_CURRENT_BINARY_DIR}/llvmclang-prefix/install)
+ else ()
+ set(CLANG_INSTALL_PATH ${CMAKE_INSTALL_PREFIX}/rtags-llvmclang)
+ endif ()
+ ExternalProject_Add(llvmclang
+ DOWNLOAD_COMMAND ${PROJECT_SOURCE_DIR}/scripts/getclang.sh "${LIBCLANG_VERSION_STRING}"
+ SOURCE_DIR llvmclang-prefix/src/llvm
+ CMAKE_ARGS -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=${CLANG_INSTALL_PATH} -DLLVM_BUILD_TOOLS=1
+ LOG_DOWNLOAD 1 # Wrap download in script to log output
+ LOG_UPDATE 1 # Wrap update in script to log output
+ LOG_CONFIGURE 1 # Wrap configure in script to log output
+ LOG_BUILD 1 # Wrap build in script to log output
+ LOG_TEST 1 # Wrap test in script to log output
+ LOG_INSTALL 1 # Wrap install in script to log output
+ )
+ if (CMAKE_SYSTEM_NAME MATCHES "Darwin")
+ set(CLANG_LIBRARY_NAME "libclang.dylib")
+ add_definitions("-DCLANG_INCLUDE=${CLANG_INSTALL_PATH}/include/c++/v1") # add libcxx include
+ else ()
+ set(CLANG_LIBRARY_NAME "libclang.so")
+ endif ()
+ set(LIBCLANG_LIBRARIES ${CLANG_INSTALL_PATH}/lib/${CLANG_LIBRARY_NAME})
+ set(LIBCLANG_LIBDIR ${CLANG_INSTALL_PATH}/lib)
+ set(LIBCLANG_CXXFLAGS "-I${CLANG_INSTALL_PATH}/include")
+endif ()
+
+
+configure_file("${CMAKE_CURRENT_SOURCE_DIR}/RTagsVersion.h.in" "${CMAKE_CURRENT_BINARY_DIR}/include/RTagsVersion.h")
+
+# Treat MSYS as Cygwin
+if (MSYS)
+ set(CYGWIN 1)
+ set(CMAKE_SYSTEM_NAME "CYGWIN")
+endif ()
+
+# Set RPATH when installing to a custom (non-system) directory
+list(FIND CMAKE_PLATFORM_IMPLICIT_LINK_DIRECTORIES "${CMAKE_INSTALL_PREFIX}/lib" isSystemDir)
+if ("${isSystemDir}" STREQUAL "-1")
+ list(APPEND CMAKE_INSTALL_RPATH ${CMAKE_INSTALL_PREFIX}/lib)
+endif ()
+
+include(${CMAKE_SOURCE_DIR}/cmake/EnsureLibraries.cmake)
+
+if (NOT DEFINED LIBCLANG_LIBRARIES)
+ set(LIBCLANG_LIBRARIES $ENV{LIBCLANG_LIBRARIES})
+endif ()
+
+if (NOT DEFINED LIBCLANG_CXXFLAGS)
+ set(LIBCLANG_CXXFLAGS $ENV{LIBCLANG_CXXFLAGS})
+endif ()
+
+if (NOT DEFINED LIBCLANG_LIBDIR)
+ set(LIBCLANG_LIBDIR $ENV{LIBCLANG_LIBDIR})
+endif()
+
+if (NOT DEFINED LIBCLANG_LIBRARIES OR NOT DEFINED LIBCLANG_CXXFLAGS OR NOT DEFINED LIBCLANG_LIBDIR)
+ find_package(LibClang REQUIRED)
+endif ()
+set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${LIBCLANG_CXXFLAGS}")
+
+if (NOT RTAGS_BUILD_CLANG)
+ set(LIBCLANG_COMPILE_TEST "
+#include
+
+int main()
+{
+ CXIndex index = clang_createIndex(0, true);
+ CXTranslationUnit unit = clang_parseTranslationUnit(index, 0, 0, 0, 0, 0, 0);
+ clang_disposeTranslationUnit(unit);
+ clang_disposeIndex(index);
+ return 0;
+}
+")
+ include(CheckCXXSourceCompiles)
+ set(CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS} ${CMAKE_CXX_FLAGS} ${LIBCLANG_CXXFLAGS})
+ set(CMAKE_REQUIRED_LIBRARIES ${CMAKE_REQUIRED_LIBRARIES} ${LIBCLANG_LIBRARIES})
+ check_cxx_source_compiles("${LIBCLANG_COMPILE_TEST}" LIBCLANG_COMPILES)
+ if (NOT LIBCLANG_COMPILES)
+ message(FATAL_ERROR "Failed to compile small clang test app.\nIt's likely that the include file could not be found!\nMaybe you need to install the clang development package?\nSee CMakeFiles/CMakeError.log for more info.")
+ endif ()
+ unset(CMAKE_REQUIRED_FLAGS)
+ unset(CMAKE_REQUIRED_LIBRARIES)
+ unset(LIBCLANG_COMPILES)
+endif ()
+
+set(CXX_11_EXTENDED_REGEX_TEST "
+#include
+
+int main()
+{
+ try {
+ std::regex rx(\"^(.*):([0-9]+):([0-9]+):?-:?([0-9]+):([0-9]+):?(@[A-Za-z,]+)?\", std::regex_constants::extended);
+ } catch (std::regex_error& e) {
+ return -1;
+ }
+
+ return 0;
+}
+")
+include(CheckCXXSourceRuns)
+set(CMAKE_REQUIRED_FLAGS ${CMAKE_REQUIRED_FLAGS} "-std=c++11" ${CMAKE_CXX_FLAGS} ${LIBCLANG_CXXFLAGS})
+check_cxx_source_runs("${CXX_11_EXTENDED_REGEX_TEST}" CXX_11_EXTENDED_REGEX_SUPPORT)
+if (NOT CXX_11_EXTENDED_REGEX_SUPPORT)
+ message(FATAL_ERROR "Compiler with complete C++11 support required ( >= GCC 4.9 or >= Clang 3.3)")
+endif ()
+unset(CMAKE_REQUIRED_FLAGS)
+unset(CMAKE_REQUIRED_LIBRARIES)
+unset(CXX_11_EXTENDED_REGEX_SUPPORT)
+
+if (EXISTS ${CLANG_COMPILATION_INCLUDE})
+ add_definitions(-DHAVE_CXCOMPILATIONDATABASE)
+endif ()
+
+if (LUA_ENABLED)
+ ExternalProject_Add(lua
+ DOWNLOAD_COMMAND ""
+ SOURCE_DIR ${CMAKE_CURRENT_LIST_DIR}/lua
+ INSTALL_COMMAND ""
+ CMAKE_ARGS -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=0 -DCMAKE_GENERATOR=${CMAKE_GENERATOR})
+endif ()
+
+set(RCT_RTTI_ENABLED 1)
+set(RCT_NO_INSTALL 1)
+set(RCT_NO_LIBRARY 1)
+# Everyting which as been set either in rct/rct.cmake or rct/compiler.cmake
+# doesn't need to be set in this file again.
+include(rct/rct.cmake)
+
+set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wstrict-aliasing=2 -Wcast-qual -fPIC")
+set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wstrict-aliasing=2 -Wcast-qual -fPIC")
+if (NOT CYGWIN)
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fstack-protector-all -Wstack-protector")
+ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fstack-protector-all -Wstack-protector")
+endif ()
+
+if (CMAKE_BUILD_TYPE MATCHES "Debug")
+ add_compile_options("-Og")
+ add_definitions("-DRTAGS_DEBUG")
+ set(RCT_EVENTLOOP_CALLBACK_TIME_THRESHOLD 2000)
+endif ()
+
+add_definitions(
+ "-DRTAGS_SOURCE_DIR=${CMAKE_CURRENT_SOURCE_DIR}"
+ "-DCLANG_LIBDIR=${LIBCLANG_LIBDIR}"
+ "-DCLANG_VERSION=${LIBCLANG_VERSION_STRING}"
+ "-DOS_${CMAKE_SYSTEM_NAME}"
+ ${RCT_DEFINITIONS})
+
+if (CMAKE_SYSTEM_NAME MATCHES "FreeBSD")
+ add_definitions(-D__LONG_LONG_SUPPORTED)
+endif ()
+
+set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/bin)
+
+set(RTAGS_SOURCES
+ ClangIndexer.cpp
+ ClangThread.cpp
+ ClassHierarchyJob.cpp
+ CompilerManager.cpp
+ CompletionThread.cpp
+ DependenciesJob.cpp
+ FileManager.cpp
+ FindFileJob.cpp
+ FindSymbolsJob.cpp
+ FollowLocationJob.cpp
+ IncludeFileJob.cpp
+ IndexMessage.cpp
+ IndexParseData.cpp
+ IndexerJob.cpp
+ JobScheduler.cpp
+ ListSymbolsJob.cpp
+ Location.cpp
+ Preprocessor.cpp
+ ProcThread.cpp
+ Project.cpp
+ QueryJob.cpp
+ QueryMessage.cpp
+ RClient.cpp
+ RTags.cpp
+ ReferencesJob.cpp
+ Sandbox.cpp
+ ScanThread.cpp
+ Server.cpp
+ Source.cpp
+ StatusJob.cpp
+ Symbol.cpp
+ Symbol.cpp
+ SymbolInfoJob.cpp
+ Token.cpp
+ TokensJob.cpp
+ ${RCT_SOURCES})
+
+if (LUA_ENABLED)
+ list(APPEND RTAGS_SOURCES AST.cpp)
+endif ()
+
+add_library(rtags STATIC ${RTAGS_SOURCES})
+if (RTAGS_BUILD_CLANG)
+ add_dependencies(rtags llvmclang)
+endif ()
+if (LUA_ENABLED)
+ add_dependencies(rtags lua)
+endif ()
+
+if (RTAGS_COTIRE)
+ include(cotire)
+ set_target_properties(rtags PROPERTIES COTIRE_ADD_UNITY_BUILD FALSE)
+ cotire(rtags)
+endif ()
+
+include_directories(
+ ${CMAKE_CURRENT_LIST_DIR}
+ ${RCT_INCLUDE_DIRS}
+ ${CMAKE_CURRENT_LIST_DIR}/selene/include
+ ${CMAKE_CURRENT_BINARY_DIR}/lua-prefix/src/lua-build
+ ${CMAKE_CURRENT_LIST_DIR}/lua/src)
+
+if (CMAKE_SYSTEM_NAME MATCHES "Darwin")
+ set(START_GROUP "")
+ set(END_GROUP "")
+else ()
+ set(START_GROUP "-Wl,--start-group")
+ set(END_GROUP "-Wl,--end-group")
+endif ()
+
+set(RTAGS_LIBRARIES rtags ${START_GROUP} ${LIBCLANG_LIBRARIES} ${END_GROUP})
+if (LUA_ENABLED)
+ list(APPEND RTAGS_LIBRARIES -L${CMAKE_CURRENT_BINARY_DIR}/lua-prefix/src/lua-build/ liblua.a)
+ add_definitions(-DRTAGS_HAS_LUA)
+endif ()
+
+if ("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang")
+ set_source_files_properties(AST.cpp PROPERTIES
+ COMPILE_FLAGS "-Wno-unused-parameter -Wno-unused-variable -ftemplate-depth=2000 -Wno-cast-qual -Wno-shadow")
+else ()
+ set_source_files_properties(AST.cpp PROPERTIES
+ COMPILE_FLAGS "-Wno-unused-but-set-parameter -Wno-unused-parameter -Wno-unused-variable -ftemplate-depth=2000 -Wno-cast-qual -Wno-shadow")
+endif()
+
+# RCT_LIBRARIES and stdc++ library must be at the end
+set(RTAGS_LIBRARIES ${RTAGS_LIBRARIES} -lstdc++ ${RCT_LIBRARIES})
+add_executable(rc rc.cpp)
+target_link_libraries(rc ${RTAGS_LIBRARIES})
+
+add_executable(rdm rdm.cpp)
+target_link_libraries(rdm ${RTAGS_LIBRARIES})
+
+set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/bin)
+
+add_executable(rp rp.cpp)
+target_link_libraries(rp ${RTAGS_LIBRARIES})
+
+if (CYGWIN)
+ EnsureLibraries(rdm rct)
+endif ()
+
+if (EMACS)
+ set(EMACS_EXECUTABLE ${EMACS})
+else ()
+ find_program(EMACS_EXECUTABLE emacs)
+endif ()
+
+if (EMACS_EXECUTABLE)
+ execute_process(COMMAND ${EMACS_EXECUTABLE} --version
+ RESULT_VARIABLE EMACS_ERROR
+ OUTPUT_VARIABLE EMACS_VERSION_INFORMATION
+ ERROR_QUIET)
+ if (NOT EMACS_ERROR)
+ string(REGEX MATCH "[0-9]+(\\.[0-9]+)*" EMACS_VERSION ${EMACS_VERSION_INFORMATION})
+ if ("${EMACS_VERSION}" LESS "24.3")
+ message(WARNING "Installed emacs version is to old, elisp files are not going to be installed, minimum required version is >=24.3!")
+ set(RTAGS_NO_ELISP_FILES TRUE)
+ else()
+ message(STATUS "Found emacs version ${EMACS_VERSION}")
+ endif ()
+ else ()
+ message(STATUS "Could not get emacs version (\"emacs --version\"), elisp files are not going to be installed")
+ set(RTAGS_NO_ELISP_FILES TRUE)
+ endif ()
+else ()
+ set(RTAGS_NO_ELISP_FILES TRUE)
+ message(STATUS "Emacs was not found, elisp files are not going to be installed!")
+endif ()
+
+set(RTAGS_ELISP_FILES
+ rtags.el
+ ac-rtags.el
+ helm-rtags.el
+ ivy-rtags.el
+ company-rtags.el
+ flycheck-rtags.el)
+
+if (LUA_ENABLED AND NOT RTAGS_NO_LUA_FILES AND LUA_FOUND AND NOT ${CMAKE_CURRENT_BINARY_DIR} STREQUAL ${CMAKE_CURRENT_SOURCE_DIR})
+ add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/rtags.lua
+ COMMAND ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_CURRENT_SOURCE_DIR}/rtags.lua ${CMAKE_CURRENT_BINARY_DIR}/rtags.lua
+ DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/rtags.lua
+ COMMENT "Copying ${CMAKE_CURRENT_SOURCE_DIR}/rtags.lua -> ${CMAKE_CURRENT_BINARY_DIR}/rtags.lua")
+endif ()
+
+if (NOT RTAGS_NO_ELISP_FILES)
+ if (NOT RTAGS_ELISP_INSTALL_LOCATION)
+ set(RTAGS_ELISP_INSTALL_LOCATION ${CMAKE_INSTALL_PREFIX}/share/emacs/site-lisp/rtags/)
+ endif ()
+ set(RTAGS_ELISP_SOURCES "")
+ foreach(el ${RTAGS_ELISP_FILES})
+ if (NOT ${CMAKE_CURRENT_BINARY_DIR} STREQUAL ${CMAKE_CURRENT_SOURCE_DIR})
+ add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${el}
+ COMMAND ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_CURRENT_SOURCE_DIR}/${el} ${CMAKE_CURRENT_BINARY_DIR}/${el}
+ DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${el}
+ COMMENT "Copying ${CMAKE_CURRENT_SOURCE_DIR}/${el} -> ${CMAKE_CURRENT_BINARY_DIR}/${el}")
+ endif ()
+ list(APPEND RTAGS_ELISP_SOURCES ${CMAKE_CURRENT_BINARY_DIR}/${el})
+ if (NOT RTAGS_NO_ELISP_BYTECOMPILE)
+ list(APPEND RTAGS_ELISP_SOURCES ${CMAKE_CURRENT_BINARY_DIR}/${el}c)
+ add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${el}c
+ COMMAND ${EMACS_EXECUTABLE} -batch -l ${CMAKE_CURRENT_SOURCE_DIR}/compile-shim.elisp -l ${CMAKE_CURRENT_SOURCE_DIR}/rtags.el -f batch-byte-compile
+ ${CMAKE_CURRENT_BINARY_DIR}/${el}
+ DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/${el}
+ WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
+ COMMENT "Creating byte-compiled Emacs lisp ${CMAKE_CURRENT_BINARY_DIR}/${el}c")
+ add_custom_target(emacs_byte_compile_${el} ALL DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/${el}c)
+ endif ()
+ endforeach()
+endif ()
+
+install(CODE "message(\"Installing rtags...\")")
+include(BashCompletion)
+if (BASH_COMPLETION_FOUND)
+ file (MAKE_DIRECTORY "${PROJECT_BINARY_DIR}/completions")
+ execute_process(COMMAND ${CMAKE_COMMAND} -E create_symlink rtags rc
+ COMMAND ${CMAKE_COMMAND} -E create_symlink rtags rdm
+ WORKING_DIRECTORY "${PROJECT_BINARY_DIR}/completions")
+ install(FILES rtags-bash-completion.bash DESTINATION ${BASH_COMPLETION_COMPLETIONSDIR}
+ PERMISSIONS OWNER_WRITE OWNER_READ GROUP_READ WORLD_READ
+ RENAME rtags)
+ install(FILES "${PROJECT_BINARY_DIR}/completions/rc" "${PROJECT_BINARY_DIR}/completions/rdm"
+ DESTINATION ${BASH_COMPLETION_COMPLETIONSDIR})
+endif ()
+install(TARGETS rdm rc rp RUNTIME DESTINATION bin COMPONENT rtags)
+install(FILES ../bin/gcc-rtags-wrapper.sh DESTINATION bin
+ PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE)
+install(FILES ../man/man7/rc.7 ../man/man7/rdm.7 DESTINATION share/man/man7/)
+
+if (UNIX AND NOT ${SKIP_CTEST})
+ install(CODE "execute_process(COMMAND ctest)")
+endif ()
+
+if (NOT RTAGS_NO_ELISP_FILES)
+ install(FILES ${RTAGS_ELISP_SOURCES} DESTINATION ${RTAGS_ELISP_INSTALL_LOCATION})
+endif ()
+
+if (CLANGTEST_ENABLED)
+ add_executable(clangtest clangtest.cpp)
+ target_link_libraries(clangtest ${LIBCLANG_LIBRARIES})
+endif ()
diff --git a/rtags/src/ClangIndexer.cpp b/rtags/src/ClangIndexer.cpp
new file mode 100644
index 0000000..7cbab3d
--- /dev/null
+++ b/rtags/src/ClangIndexer.cpp
@@ -0,0 +1,2413 @@
+/* This file is part of RTags (http://rtags.net).
+
+ RTags is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ RTags is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with RTags. If not, see . */
+
+#define RTAGS_SINGLE_THREAD
+#include "ClangIndexer.h"
+
+#include
+#if CINDEX_VERSION >= CINDEX_VERSION_ENCODE(0, 25)
+#include
+#endif
+
+#include "Diagnostic.h"
+#include "FileMap.h"
+#include "QueryMessage.h"
+#include "RClient.h"
+#include "rct/Connection.h"
+#include "rct/EventLoop.h"
+#include "rct/SHA256.h"
+#include "RTags.h"
+#include "RTagsVersion.h"
+#include "VisitFileMessage.h"
+#include "VisitFileResponseMessage.h"
+#include "Location.h"
+
+static inline String usr(const CXCursor &cursor)
+{
+ return RTags::eatString(clang_getCursorUSR(clang_getCanonicalCursor(cursor)));
+}
+
+static inline void setType(Symbol &symbol, const CXType &type)
+{
+ symbol.type = type.kind;
+ symbol.typeName = RTags::eatString(clang_getTypeSpelling(type));
+ const CXType canonical = clang_getCanonicalType(type);
+ if (!clang_equalTypes(type, canonical)
+#if CINDEX_VERSION >= CINDEX_VERSION_ENCODE(0, 32)
+ && (symbol.typeName == "auto" || type.kind != CXType_Auto)
+#endif
+ ) {
+ symbol.typeName += " => " + RTags::eatString(clang_getTypeSpelling(canonical));
+ }
+}
+
+static inline void setRange(Symbol &symbol, const CXSourceRange &range, uint16_t *length = 0)
+{
+ CXSourceLocation rangeStart = clang_getRangeStart(range);
+ CXSourceLocation rangeEnd = clang_getRangeEnd(range);
+ unsigned int startLine, startColumn, endLine, endColumn, startOffset, endOffset;
+ clang_getSpellingLocation(rangeStart, 0, &startLine, &startColumn, &startOffset);
+ clang_getSpellingLocation(rangeEnd, 0, &endLine, &endColumn, &endOffset);
+ symbol.startLine = startLine;
+ symbol.endLine = endLine;
+ symbol.startColumn = startColumn;
+ symbol.endColumn = endColumn;
+ if (length)
+ *length = static_cast(endOffset - startOffset);
+}
+
+struct VerboseVisitorUserData {
+ int indent;
+ String out;
+ ClangIndexer *indexer;
+};
+
+Flags ClangIndexer::sServerOpts;
+Path ClangIndexer::sServerSandboxRoot;
+ClangIndexer::ClangIndexer()
+ : mCurrentTranslationUnit(String::npos), mLastCursor(clang_getNullCursor()),
+ mLastCallExprSymbol(0), mVisitFileResponseMessageFileId(0),
+ mVisitFileResponseMessageVisit(0), mParseDuration(0), mVisitDuration(0), mBlocked(0),
+ mAllowed(0), mIndexed(1), mVisitFileTimeout(0), mIndexDataMessageTimeout(0),
+ mFileIdsQueried(0), mFileIdsQueriedTime(0), mCursorsVisited(0), mLogFile(0),
+ mConnection(Connection::create(RClient::NumOptions)), mUnionRecursion(false),
+ mInTemplateFunction(0)
+{
+ mConnection->newMessage().connect(std::bind(&ClangIndexer::onMessage, this,
+ std::placeholders::_1, std::placeholders::_2));
+}
+
+ClangIndexer::~ClangIndexer()
+{
+ if (mLogFile)
+ fclose(mLogFile);
+}
+
+bool ClangIndexer::exec(const String &data)
+{
+ Deserializer deserializer(data);
+ uint16_t protocolVersion;
+ deserializer >> protocolVersion;
+ if (protocolVersion != RTags::DatabaseVersion) {
+ error("Wrong protocol %d vs %d", protocolVersion, RTags::DatabaseVersion);
+ return false;
+ }
+ uint64_t id;
+ String socketFile;
+ Flags indexerJobFlags;
+ uint32_t connectTimeout, connectAttempts;
+ int32_t niceValue;
+ Hash blockedFiles;
+
+ deserializer >> sServerSandboxRoot;
+ deserializer >> id;
+ deserializer >> socketFile;
+ deserializer >> mProject;
+ uint32_t count;
+ deserializer >> count;
+ mSources.resize(count);
+ for (uint32_t i=0; i> mSourceFile;
+ deserializer >> indexerJobFlags;
+ deserializer >> mVisitFileTimeout;
+ deserializer >> mIndexDataMessageTimeout;
+ deserializer >> connectTimeout;
+ deserializer >> connectAttempts;
+ deserializer >> niceValue;
+ deserializer >> sServerOpts;
+ deserializer >> mUnsavedFiles;
+ deserializer >> mDataDir;
+ deserializer >> mDebugLocations;
+ deserializer >> blockedFiles;
+
+ if (sServerOpts & Server::NoRealPath) {
+ Path::setRealPathEnabled(false);
+ }
+
+#if 0
+ while (true) {
+ FILE *f = fopen((String("/tmp/stop_") + mSourceFile.fileName()).constData(), "r+");
+ if (f) {
+ fseek(f, 0, SEEK_END);
+ fprintf(f, "Waiting ... %d\n", getpid());
+ fclose(f);
+ sleep(1);
+ } else {
+ break;
+ }
+ }
+#endif
+
+ const uint64_t parseTime = Rct::currentTimeMs();
+
+ if (niceValue != INT_MIN) {
+ errno = 0;
+ if (nice(niceValue) == -1) {
+ error() << "Failed to nice rp" << Rct::strerror();
+ }
+ }
+
+ if (mSourceFile.isEmpty()) {
+ error("No sourcefile");
+ return false;
+ }
+
+ switch (mSources.size()) {
+ case 0:
+ error("No sourcefile");
+ return false;
+ case 1:
+ if (!mSources.front().fileId) {
+ error("Bad fileId");
+ return false;
+ }
+ break;
+ default:
+ for (size_t i=1; iconnectUnix(socketFile, connectTimeout))
+ break;
+ if (!--connectAttempts) {
+ error("Failed to connect to rdm on %s (%dms timeout)", socketFile.constData(), connectTimeout);
+ return false;
+ }
+ usleep(500 * 1000);
+ }
+ // mLogFile = fopen(String::format("/tmp/%s", mSourceFile.fileName()).constData(), "w");
+ mIndexDataMessage.setProject(mProject);
+ mIndexDataMessage.setIndexerJobFlags(indexerJobFlags);
+ mIndexDataMessage.setParseTime(parseTime);
+ mIndexDataMessage.setId(id);
+
+ assert(mConnection->isConnected());
+ assert(mSources.front().fileId);
+ mIndexDataMessage.files()[mSources.front().fileId] |= IndexDataMessage::Visited;
+ parse() && visit() && diagnose();
+ String message = mSourceFile.toTilde();
+ String err;
+
+ StopWatch sw;
+ int writeDuration = -1;
+ bool hasUnit = false;
+ for (const auto &u : mTranslationUnits) {
+ if (u->unit) {
+ hasUnit = true;
+ break;
+ }
+ }
+ if (!hasUnit || !writeFiles(RTags::encodeSourceFilePath(mDataDir, mProject, 0), err)) {
+ message += " error";
+ if (!err.isEmpty())
+ message += (' ' + err);
+ } else {
+ writeDuration = sw.elapsed();
+ }
+ message += String::format<16>(" in %lldms. ", mTimer.elapsed());
+ if (mSources.size() > 1) {
+ message += String::format("(%zu builds) ", mSources.size());
+ }
+ int cursorCount = 0;
+ int symbolNameCount = 0;
+ for (const auto &unit : mUnits) {
+ cursorCount += unit.second->symbols.size();
+ symbolNameCount += unit.second->symbolNames.size();
+ }
+ if (hasUnit) {
+ String queryData;
+ if (mFileIdsQueried)
+ queryData = String::format(", %d queried %dms", mFileIdsQueried, mFileIdsQueriedTime);
+ const char *format = "(%d syms, %d symNames, %d includes, %d of %d files, symbols: %d of %d, %d cursors, %zu bytes written%s%s) (%d/%d/%dms)";
+ message += String::format<1024>(format, cursorCount, symbolNameCount,
+ mIndexDataMessage.includes().size(), mIndexed,
+ mIndexDataMessage.files().size(), mAllowed,
+ mAllowed + mBlocked, mCursorsVisited,
+ mIndexDataMessage.bytesWritten(),
+ queryData.constData(), mIndexDataMessage.flags() & IndexDataMessage::UsedPCH ? ", pch" : "",
+ mParseDuration, mVisitDuration, writeDuration);
+ }
+ if (mIndexDataMessage.indexerJobFlags() & IndexerJob::Dirty) {
+ message += " (dirty)";
+ } else if (mIndexDataMessage.indexerJobFlags() & IndexerJob::Reindex) {
+ message += " (reindex)";
+ }
+
+
+ mIndexDataMessage.setMessage(message);
+ sw.restart();
+ if (!mConnection->send(mIndexDataMessage)) {
+ error() << "Couldn't send IndexDataMessage" << mSourceFile;
+ return false;
+ }
+ mConnection->finished().connect(std::bind(&EventLoop::quit, EventLoop::eventLoop()));
+ if (EventLoop::eventLoop()->exec(mIndexDataMessageTimeout) == EventLoop::Timeout) {
+ error() << "Timed out sending IndexDataMessage" << mSourceFile;
+ return false;
+ }
+ if (getenv("RDM_DEBUG_INDEXERMESSAGE"))
+ error() << "Send took" << sw.elapsed() << "for" << mSourceFile;
+
+ if (mSerializeTU) {
+ Path path = mDataDir + "tucache/";
+ Path::mkdir(path, Path::Recursive);
+ path << mSources.front().fileId;
+ Path tmp = path;
+ tmp << ".tmp";
+ StopWatch sw2;
+ clang_saveTranslationUnit(mSerializeTU->unit, tmp.constData(), clang_defaultSaveOptions(mSerializeTU->unit));
+ rename(tmp.constData(), path.constData());
+ error() << "SAVED CACHED FILE FOR" << mSourceFile << path << sw2.elapsed();
+ }
+ return true;
+}
+
+void ClangIndexer::onMessage(const std::shared_ptr &msg, const std::shared_ptr &/*conn*/)
+{
+ assert(msg->messageId() == VisitFileResponseMessage::MessageId);
+ const std::shared_ptr vm = std::static_pointer_cast(msg);
+ mVisitFileResponseMessageVisit = vm->visit();
+ mVisitFileResponseMessageFileId = vm->fileId();
+ assert(EventLoop::eventLoop());
+ EventLoop::eventLoop()->quit();
+}
+
+Location ClangIndexer::createLocation(const Path &sourceFile, unsigned int line, unsigned int col, bool *blockedPtr)
+{
+ uint32_t id = Location::fileId(sourceFile);
+ Path resolved;
+ if (!id) {
+ bool ok;
+ for (int i=0; i<4; ++i) {
+ resolved = sourceFile.resolved(Path::RealPath, Path(), &ok);
+ // if ok is false it means the file is gone, in case this happens
+ // during a git pull or something we'll give it a couple of chances.
+ if (ok)
+ break;
+ usleep(50000);
+ }
+ if (!ok)
+ return Location();
+ id = Location::fileId(resolved);
+ if (id)
+ Location::set(sourceFile, id);
+ }
+ assert(!resolved.contains("/../"));
+
+ if (id) {
+ if (blockedPtr) {
+ Hash >::iterator it = mIndexDataMessage.files().find(id);
+ if (it == mIndexDataMessage.files().end()) {
+ // the only reason we already have an id for a file that isn't
+ // in the mIndexDataMessage.mFiles is that it's blocked from the outset.
+ // The assumption is that we never will go and fetch a file id
+ // for a location without passing blockedPtr since any reference
+ // to a symbol in another file should have been preceded by that
+ // header in which case we would have to make a decision on
+ // whether or not to index it. This is a little hairy but we
+ // have to try to optimize this process.
+#ifndef NDEBUG
+ if (resolved.isEmpty())
+ resolved = sourceFile.resolved();
+#endif
+ assert(id);
+ mIndexDataMessage.files()[id] = IndexDataMessage::NoFileFlag;
+ *blockedPtr = true;
+ } else if (!it->second) {
+ *blockedPtr = true;
+ }
+ }
+ return Location(id, line, col);
+ }
+
+ ++mFileIdsQueried;
+ VisitFileMessage msg(resolved, mProject, mSources.front().fileId);
+
+ mVisitFileResponseMessageFileId = UINT_MAX;
+ mVisitFileResponseMessageVisit = false;
+ mConnection->send(msg);
+ StopWatch sw;
+ EventLoop::eventLoop()->exec(mVisitFileTimeout);
+ const int elapsed = sw.elapsed();
+ mFileIdsQueriedTime += elapsed;
+ switch (mVisitFileResponseMessageFileId) {
+ case 0:
+ return Location();
+ case UINT_MAX:
+ // timed out.
+ if (mVisitFileResponseMessageFileId == UINT_MAX) {
+ error() << "Error getting fileId for" << resolved << mLastCursor
+ << elapsed << mVisitFileTimeout;
+ }
+ exit(1);
+ default:
+ id = mVisitFileResponseMessageFileId;
+ break;
+ }
+ assert(id);
+ Flags &flags = mIndexDataMessage.files()[id];
+ if (mVisitFileResponseMessageVisit) {
+ flags |= IndexDataMessage::Visited;
+ ++mIndexed;
+ }
+ // fprintf(mLogFile, "%s %s\n", file.second ? "WON" : "LOST", resolved.constData());
+
+ Location::set(resolved, id);
+ if (resolved != sourceFile)
+ Location::set(sourceFile, id);
+
+ if (blockedPtr)
+ *blockedPtr = !mVisitFileResponseMessageVisit;
+ return Location(id, line, col);
+}
+
+CXTranslationUnit ClangIndexer::unit(size_t u) const
+{
+ return mTranslationUnits[u]->unit;
+}
+
+static inline void tokenize(const char *buf, int start,
+ int *templateStart, int *templateEnd,
+ int *sectionCount, int sections[1024])
+{
+ int templateCount = 0;
+ *templateStart = *templateEnd = -1;
+ *sectionCount = 1;
+ sections[0] = start;
+ int functionStart = -1;
+ int functionEnd = -1;
+
+ int idx = start;
+ while (true) {
+ switch (buf[++idx]) {
+ case '<':
+ if (buf[idx + 1] == '<') {
+ ++idx;
+ } else if (functionStart == -1 && (idx - 8 < 0 || strncmp("operator", buf + idx - 8, 8) != 0)) {
+ if (!templateCount++)
+ *templateStart = idx;
+ }
+ break;
+ case '>':
+ if (buf[idx + 1] == '>') {
+ ++idx;
+ } else if (functionStart == -1 && (idx - 8 < 0 || strncmp("operator", buf + idx - 8, 8) != 0)) {
+ if (!--templateCount)
+ *templateEnd = idx;
+ }
+ break;
+ case '(':
+ if (!templateCount)
+ functionStart = idx;
+ break;
+ case ')':
+ if (!templateCount)
+ functionEnd = idx;
+ break;
+ case ':':
+ if (!templateCount && (functionStart == -1 || functionEnd != -1) && buf[idx + 1] == ':' && (*sectionCount) < 1024) {
+ sections[(*sectionCount)++] = idx + 2;
+ ++idx;
+ }
+ break;
+ case '\0':
+ if (templateCount) {
+ *templateStart = *templateEnd = -1;
+ }
+ return;
+ }
+ }
+}
+
+String ClangIndexer::addNamePermutations(const CXCursor &cursor, Location location, RTags::CursorType cursorType)
+{
+ CXCursorKind kind = clang_getCursorKind(cursor);
+ const CXCursorKind originalKind = kind;
+ char buf[1024 * 512];
+ int pos = sizeof(buf) - 1;
+ buf[pos] = '\0';
+ int cutoff = -1;
+
+ CXCursor c = cursor;
+ do {
+ CXStringScope displayName(clang_getCursorDisplayName(c));
+ const char *name = displayName.data();
+ if (!name)
+ break;
+ const int len = strlen(name);
+ if (!len)
+ break;
+
+ if (pos != sizeof(buf) - 1) {
+ pos -= 2;
+ if (pos >= 0)
+ memset(buf + pos, ':', 2);
+ }
+ pos -= len;
+ if (pos < 0) {
+ error("SymbolName too long. Giving up");
+ return String();
+ }
+ memcpy(buf + pos, name, len);
+
+ c = clang_getCursorSemanticParent(c);
+ kind = clang_getCursorKind(c);
+ if (cutoff == -1) {
+ switch (kind) {
+ case CXCursor_ClassDecl:
+ case CXCursor_ClassTemplate:
+ case CXCursor_StructDecl:
+ break;
+ case CXCursor_Namespace:
+ // namespaces can include all namespaces in their symbolname
+ if (originalKind == CXCursor_Namespace)
+ break;
+ RCT_FALL_THROUGH;
+ default:
+ cutoff = pos;
+ break;
+ }
+ }
+ } while (RTags::needsQualifiers(kind));
+
+ if (static_cast(pos) == sizeof(buf) - 1) {
+ return String();
+ }
+ String type;
+ String trailer;
+ switch (originalKind) {
+ case CXCursor_StructDecl:
+ type = "struct ";
+ break;
+ case CXCursor_ClassDecl:
+ case CXCursor_ClassTemplate:
+ type = "class ";
+ break;
+ case CXCursor_Namespace:
+ type = "namespace ";
+ break;
+ case CXCursor_Destructor:
+ case CXCursor_Constructor:
+ break;
+ default: {
+ type = RTags::eatString(clang_getTypeSpelling(clang_getCanonicalType(clang_getCursorType(cursor))));
+ if (originalKind == CXCursor_FunctionDecl || originalKind == CXCursor_CXXMethod || originalKind == CXCursor_FunctionTemplate) {
+ const size_t idx = type.indexOf(" -> ");
+ if (idx != String::npos)
+ trailer = type.mid(idx);
+ }
+ const size_t paren = type.indexOf('(');
+ if (paren != String::npos) {
+ type.resize(paren);
+ } else if (!type.isEmpty() && !type.endsWith('*') && !type.endsWith('&')) {
+ type.append(' ');
+ }
+ break; }
+ }
+
+ if (cutoff == -1)
+ cutoff = pos;
+
+ String ret;
+ if (!type.isEmpty()) {
+ ret = type;
+ ret.append(buf + cutoff, std::max(0, sizeof(buf) - cutoff - 1));
+ if (!trailer.isEmpty())
+ ret += trailer;
+ if (cursorType != RTags::Type_Reference) {
+ unit(location.fileId())->symbolNames[ret].insert(location);
+ }
+ } else {
+ ret.assign(buf + cutoff, std::max(0, sizeof(buf) - cutoff - 1));
+ }
+ if (cursorType == RTags::Type_Reference) {
+ return ret;
+ }
+
+ int templateStart, templateEnd, colonColonCount;
+ int colonColons[1024];
+ ::tokenize(buf, pos,
+ &templateStart, &templateEnd,
+ &colonColonCount, colonColons);
+ assert((templateStart != -1) == (templateEnd != -1));
+
+ // i == 0 --> with templates,
+ // i == 1 without templates or without EnumConstantDecl part
+ for (int i=0; i<2; ++i) {
+ for (int j=0; j(0, sizeof(buf) - (ch - buf) - 1));
+ if (name.isEmpty())
+ continue;
+ unit(location.fileId())->symbolNames[name].insert(location);
+ if (originalKind == CXCursor_ObjCClassMethodDecl) {
+ const size_t idx = name.indexOf(':');
+ if (idx != String::npos && idx > 0) {
+ name.resize(idx);
+ unit(location.fileId())->symbolNames[name].insert(location);
+ }
+ }
+ if (!type.isEmpty() && (originalKind != CXCursor_ParmDecl || !strchr(ch, '('))) {
+ // We only want to add the type to the final declaration for ParmDecls
+ // e.g.
+ // void foo(int)::bar
+ // and
+ // int bar
+ //
+ // not
+ // int void foo(int)::bar
+ // or
+ // void foo(int)::int bar
+
+ unit(location.fileId())->symbolNames[type + name].insert(location);
+ }
+ }
+
+ if (i == 1 || (templateStart == -1 && originalKind != CXCursor_EnumConstantDecl)) {
+ // nothing more to do
+ break;
+ }
+
+ if (originalKind == CXCursor_EnumConstantDecl) { // remove CXCursor_EnumDecl
+ // struct A { enum B { C } };
+ // Will by default generate a A::B::C symbolname.
+ // This code removes the B:: part from it
+ if (colonColonCount > 2) {
+ const char *last = buf + colonColons[colonColonCount - 1];
+ const char *secondLast = buf + colonColons[colonColonCount - 2];
+ const int len = (last - secondLast);
+ memmove(buf + pos + len, buf + pos, secondLast - (buf + pos));
+ pos += len;
+ }
+ } else { // remove templates
+ assert(templateStart != -1);
+ assert(templateEnd != -1);
+ const int templateSize = (templateEnd - templateStart) + 1;
+ memmove(buf + pos + templateSize, buf + pos, (buf + templateStart) - (buf + pos));
+ pos += templateSize;
+ }
+ // ### We could/should just move the colon colon values but this
+ // should be pretty quick and I don't want to write the code to
+ // do it.
+ ::tokenize(buf, pos,
+ &templateStart, &templateEnd,
+ &colonColonCount, colonColons);
+ }
+
+ return ret;
+}
+
+static inline CXCursor findDestructorForDelete(const CXCursor &deleteStatement)
+{
+ const CXCursor child = RTags::findFirstChild(deleteStatement);
+ CXCursorKind kind = clang_getCursorKind(child);
+ switch (kind) {
+ case CXCursor_UnexposedExpr:
+ case CXCursor_CallExpr:
+ break;
+ default:
+ return clang_getNullCursor();
+ }
+
+ const CXCursor var = clang_getCursorReferenced(child);
+ kind = clang_getCursorKind(var);
+ switch (kind) {
+ case CXCursor_ObjCIvarDecl:
+ case CXCursor_VarDecl:
+ case CXCursor_FieldDecl:
+ case CXCursor_ParmDecl:
+ case CXCursor_CXXMethod:
+ case CXCursor_FunctionDecl:
+ case CXCursor_ConversionFunction:
+ break;
+ default:
+ if (!clang_isInvalid(kind)) {
+ error() << "Got unexpected cursor" << deleteStatement << var;
+ // assert(0);
+ }
+ return clang_getNullCursor();
+ }
+
+ CXCursor ref = RTags::findChild(var, CXCursor_TypeRef);
+ if (ref != CXCursor_TypeRef)
+ ref = RTags::findChild(var, CXCursor_TemplateRef);
+ kind = clang_getCursorKind(ref);
+ switch (kind) {
+ case CXCursor_TypeRef:
+ case CXCursor_TemplateRef:
+ break;
+ default:
+ return clang_getNullCursor();
+ }
+
+ const CXCursor referenced = clang_getCursorReferenced(ref);
+ kind = clang_getCursorKind(referenced);
+ switch (kind) {
+ case CXCursor_StructDecl:
+ case CXCursor_ClassDecl:
+ case CXCursor_ClassTemplate:
+ break;
+ default:
+ return clang_getNullCursor();
+ }
+ const CXCursor destructor = RTags::findChild(referenced, CXCursor_Destructor);
+ return destructor;
+}
+
+CXChildVisitResult ClangIndexer::visitorHelper(CXCursor cursor, CXCursor, CXClientData data)
+{
+ ClangIndexer *indexer = static_cast(data);
+ const CXChildVisitResult res = indexer->indexVisitor(cursor);
+ if (res == CXChildVisit_Recurse)
+ indexer->visit(cursor);
+ return CXChildVisit_Continue;
+}
+
+CXChildVisitResult ClangIndexer::indexVisitor(CXCursor cursor)
+{
+ ++mCursorsVisited;
+ // error() << "indexVisitor" << cursor;
+ // FILE *f = fopen("/tmp/clangindex.log", "a");
+ // String str;
+ // Log(&str) << cursor;
+ // fwrite(str.constData(), 1, str.size(), f);
+ // fwrite("\n", 1, 1, f);
+ // fclose(f);
+
+ const CXCursorKind kind = clang_getCursorKind(cursor);
+ const RTags::CursorType type = RTags::cursorType(kind);
+ if (type == RTags::Type_Other) {
+ return CXChildVisit_Recurse;
+ }
+
+ struct UpdateLastCursor {
+ ~UpdateLastCursor() { func(); }
+ std::function func;
+ } call = { [this, cursor]() { mLastCursor = cursor; } };
+
+ bool blocked = false;
+
+ Location loc = createLocation(cursor, kind, &blocked);
+ if (blocked) {
+ ++mBlocked;
+ return CXChildVisit_Continue;
+ } else if (loc.isNull()) {
+ // error() << "Got null" << cursor;
+ return CXChildVisit_Recurse;
+ }
+ for (const String &debug : mDebugLocations) {
+ if (debug == "all" || debug == loc) {
+ Log log(LogLevel::Error);
+ log << cursor;
+ CXCursor ref = clang_getCursorReferenced(cursor);
+ if (!clang_isInvalid(clang_getCursorKind(ref)) && ref != cursor) {
+ log << "refs" << ref;
+ }
+ break;
+ }
+ }
+ ++mAllowed;
+ if (mLogFile) {
+ String out;
+ Log(&out) << cursor;
+ fwrite(out.constData(), 1, out.size(), mLogFile);
+ fwrite("\n", 1, 1, mLogFile);
+ }
+
+ if (testLog(LogLevel::VerboseDebug)) {
+ Log log(LogLevel::VerboseDebug);
+ log << cursor;
+ CXCursor ref = clang_getCursorReferenced(cursor);
+ if (!clang_isInvalid(clang_getCursorKind(ref)) && ref != cursor) {
+ log << "refs" << ref;
+ }
+ }
+
+ if (Symbol::isClass(kind)) {
+ mLastClass = loc;
+ } else {
+ if (kind == CXCursor_CXXBaseSpecifier) {
+ handleBaseClassSpecifier(cursor);
+ return CXChildVisit_Recurse;
+ }
+ }
+
+ CXChildVisitResult visitResult = CXChildVisit_Recurse;
+ switch (type) {
+ case RTags::Type_Cursor:
+ visitResult = handleCursor(cursor, kind, loc);
+ break;
+ case RTags::Type_Include:
+ handleInclude(cursor, kind, loc);
+ break;
+ case RTags::Type_Literal:
+ handleLiteral(cursor, kind, loc);
+ break;
+ case RTags::Type_Statement:
+ visitResult = handleStatement(cursor, kind, loc);
+ break;
+ case RTags::Type_Reference:
+ switch (kind) {
+ case CXCursor_OverloadedDeclRef: {
+ const int count = clang_getNumOverloadedDecls(cursor);
+ for (int i=0; i arguments;
+ extractArguments(&arguments, cursor);
+ Symbol *old = 0;
+ Location oldLoc;
+ std::swap(mLastCallExprSymbol, old);
+ const CXCursor ref = clang_getCursorReferenced(cursor);
+ bool handled = false;
+ const CXCursorKind refKind = clang_getCursorKind(ref);
+ if (refKind == CXCursor_Constructor
+ && (clang_getCursorKind(mLastCursor) == CXCursor_TypeRef || clang_getCursorKind(mLastCursor) == CXCursor_TemplateRef)) {
+ handled = true;
+ for (int pos = mParents.size() - 1; pos >= 0; --pos) {
+ const CXCursor &parent = mParents[pos];
+ const CXCursorKind k = clang_getCursorKind(parent);
+ if (k == CXCursor_VarDecl) {
+ handled = false;
+ break;
+ } else if (k == CXCursor_CallExpr) {
+ if (!clang_isInvalid(clang_getCursorKind(clang_getCursorReferenced(parent)))) {
+ handled = false;
+ break;
+ }
+ } else if (k != CXCursor_UnexposedExpr) {
+ break;
+ }
+ }
+ if (handled) {
+ loc = createLocation(mLastCursor);
+ handleReference(mLastCursor, kind, loc, ref);
+ }
+ } else if (refKind == CXCursor_FieldDecl) {
+ handled = true;
+ }
+ if (!handled) {
+ handleReference(cursor, kind, loc, ref);
+ }
+ List destArguments;
+ extractArguments(&destArguments, ref);
+ visit(cursor);
+ if (mLastCallExprSymbol && !arguments.isEmpty()) {
+ const Location invokedLocation = createLocation(ref, refKind);
+ auto u = unit(loc);
+ size_t idx = 0;
+ for (const auto &arg : arguments) {
+ const auto destArg = destArguments.value(idx);
+ if (destArg.location.isNull())
+ break;
+ const Location start = arg.location;
+ Location end;
+ if (idx + 1 == arguments.size()) {
+ end = Location(start.fileId(), start.line(), start.column() + arg.length); // this falls apart with multi-line args
+ } else {
+ end = arguments.value(idx + 1).location;
+ }
+ auto it = u->symbols.lower_bound(start);
+ while (it != u->symbols.end() && it->first < end) {
+ auto &sym = it->second;
+ sym.argumentUsage.index = idx;
+ sym.argumentUsage.invokedFunction = invokedLocation;
+ sym.argumentUsage.argument = destArg;
+ sym.argumentUsage.invocation = mLastCallExprSymbol->location;
+ ++it;
+ }
+ ++idx;
+ }
+
+ mLastCallExprSymbol->arguments = std::move(arguments);
+ }
+ std::swap(old, mLastCallExprSymbol);
+ visitResult = CXChildVisit_Continue;
+ break; }
+ default:
+ handleReference(cursor, kind, loc, clang_getCursorReferenced(cursor));
+ break;
+ }
+ break;
+ case RTags::Type_Other:
+ assert(0);
+ break;
+ }
+ return visitResult;
+}
+
+static inline bool isImplicit(const CXCursor &cursor)
+{
+ return clang_equalLocations(clang_getCursorLocation(cursor),
+ clang_getCursorLocation(clang_getCursorSemanticParent(cursor)));
+}
+
+bool ClangIndexer::superclassTemplateMemberFunctionUgleHack(const CXCursor &cursor, CXCursorKind kind,
+ Location location, const CXCursor &/*ref*/,
+ Symbol **cursorPtr)
+{
+ // This is for references to superclass template functions. Awful awful
+ // shit. See https://github.com/Andersbakken/rtags/issues/62 and commit
+ // for details. I really should report this as a bug.
+ if (cursorPtr)
+ *cursorPtr = 0;
+ if (kind != CXCursor_MemberRefExpr && clang_getCursorKind(mParents.last()) != CXCursor_CallExpr)
+ return false;
+
+ const CXCursor templateRef = RTags::findChild(cursor, CXCursor_TemplateRef);
+ if (templateRef != CXCursor_TemplateRef)
+ return false;
+
+ const CXCursor classTemplate = clang_getCursorReferenced(templateRef);
+ if (classTemplate != CXCursor_ClassTemplate)
+ return false;
+ FILE *f = fopen(location.path().constData(), "r");
+ if (!f)
+ return false;
+
+ const CXSourceRange range = clang_getCursorExtent(cursor);
+ const CXSourceLocation end = clang_getRangeEnd(range);
+ unsigned int offset;
+ clang_getSpellingLocation(end, 0, 0, 0, &offset);
+
+ String name;
+ while (offset > 0) {
+ fseek(f, --offset, SEEK_SET);
+ char ch = static_cast(fgetc(f));
+ if (isalnum(ch) || ch == '_' || ch == '~') {
+ name.prepend(ch);
+ } else {
+ break;
+ }
+ }
+ fclose(f);
+ if (!name.isEmpty()) {
+ RTags::Filter out;
+ out.kinds.insert(CXCursor_MemberRefExpr);
+ const int argCount = RTags::children(mParents.last(), RTags::Filter(), out).size();
+ RTags::Filter in(RTags::Filter::And);
+ in.names.insert(name);
+ in.argumentCount = argCount;
+ const List alternatives = RTags::children(classTemplate, in);
+ switch (alternatives.size()) {
+ case 1:
+ // ### not sure this is correct with line/col
+ return handleReference(cursor, kind,
+ Location(location.fileId(), location.line(), location.column() + 1),
+ alternatives.first(), cursorPtr);
+ break;
+ case 0:
+ break;
+ default:
+ warning() << "Can't decide which of these symbols are right for me"
+ << cursor << alternatives
+ << "Need to parse types";
+ break;
+ }
+ }
+ return false;
+}
+
+bool ClangIndexer::handleReference(const CXCursor &cursor, CXCursorKind kind, Location location, CXCursor ref, Symbol **cursorPtr)
+{
+ if (cursorPtr)
+ *cursorPtr = 0;
+ // error() << "handleReference" << cursor << kind << location << ref;
+ const CXCursorKind refKind = clang_getCursorKind(ref);
+ if (clang_isInvalid(refKind)) {
+ return superclassTemplateMemberFunctionUgleHack(cursor, kind, location, ref, cursorPtr);
+ }
+
+ const CXCursor originalRef = ref;
+ bool isOperator = false;
+ if (kind == CXCursor_CallExpr && (refKind == CXCursor_CXXMethod
+ || refKind == CXCursor_FunctionDecl
+ || refKind == CXCursor_FunctionTemplate)) {
+ // These are bullshit. for this construct:
+ // foo.bar();
+ // the position of the cursor is at the foo, not the bar.
+ // They are not interesting for followLocation, renameSymbol or find
+ // references so we toss them.
+ // For functions it can be the position of the namespace.
+ // E.g. Foo::bar(); cursor is on Foo
+ // For constructors they happen to be the only thing we have that
+ // actually refs the constructor and not the class so we have to keep
+ // them for that.
+ return false;
+ }
+
+ Location refLoc = createLocation(ref, refKind);
+ if (!refLoc.isValid()) {
+ // ### THIS IS NOT SOLVED
+ // if (kind == CXCursor_ObjCMessageExpr) {
+ // mIndexDataMessage.mPendingReferenceMap[RTags::eatString(clang_getCursorUSR(clang_getCanonicalCursor(ref)))].insert(location);
+ // // insert it, we'll hook up the target and references later
+ // return handleCursor(cursor, kind, location, cursorPtr);
+ // }
+ return false;
+ }
+
+ switch (refKind) {
+ case CXCursor_Constructor:
+ case CXCursor_CXXMethod:
+ case CXCursor_FunctionDecl:
+ case CXCursor_Destructor:
+ case CXCursor_FunctionTemplate: {
+ bool visitReference = false;
+ ref = resolveTemplate(ref, refLoc, &visitReference);
+ if (visitReference && (kind == CXCursor_DeclRefExpr || kind == CXCursor_MemberRefExpr)) {
+ mTemplateSpecializations.insert(originalRef);
+ }
+
+ if (refKind == CXCursor_FunctionDecl)
+ break;
+ if (refKind == CXCursor_Constructor || refKind == CXCursor_Destructor) {
+ if (isImplicit(ref)) {
+ return false;
+ }
+ } else {
+ CXStringScope scope = clang_getCursorDisplayName(ref);
+ const char *data = scope.data();
+ if (data) {
+ const int len = strlen(data);
+ if (len > 8 && !strncmp(data, "operator", 8) && !isalnum(data[8]) && data[8] != '_') {
+ if (isImplicit(ref)) {
+ return false; // eat implicit operator calls
+ }
+ isOperator = true;
+ }
+ }
+ }
+ break; }
+ default:
+ break;
+ }
+
+ const String refUsr = usr(ref);
+ if (refUsr.isEmpty()) {
+ return false;
+ }
+
+ FindResult result;
+ auto reffedCursor = findSymbol(refLoc, &result);
+ Map &targets = unit(location)->targets[location];
+ if (result == NotFound && !mUnionRecursion) {
+ CXCursor parent = clang_getCursorSemanticParent(ref);
+ CXCursor best = clang_getNullCursor();
+ while (true) {
+ if (clang_getCursorKind(parent) != CXCursor_UnionDecl)
+ break;
+ best = parent;
+ parent = clang_getCursorSemanticParent(parent);
+ }
+ if (best == CXCursor_UnionDecl) {
+ mUnionRecursion = true;
+ // for anonymous unions we don't get to their fields with normal
+ // recursing of the AST. In these cases we visit the union decl
+ visit(best);
+ mUnionRecursion = false;
+ reffedCursor = findSymbol(refLoc, &result);
+ }
+ }
+ int16_t refTargetValue;
+ if (result == Found) {
+ refTargetValue = reffedCursor.targetsValue();
+ } else {
+ refTargetValue = RTags::createTargetsValue(refKind, clang_isCursorDefinition(ref));
+ }
+
+ Symbol *c = &unit(location)->symbols[location];
+ assert(c);
+ bool setTarget = true;
+ if (c->kind == CXCursor_MacroExpansion) {
+ for (const auto &t : targets) {
+ if (RTags::targetsValueKind(t.second) == CXCursor_MacroDefinition) {
+ for (const auto &u : mUnits) { // ### should only search the ones we depend on
+ const auto it = u.second->usrs.find(t.first);
+ if (it != u.second->usrs.end()) {
+ auto mit = mMacroTokens.find(*it->second.begin());
+ if (mit != mMacroTokens.end()) {
+ const String id = RTags::eatString(clang_getCursorSpelling(cursor));
+ auto idit = mit->second.data.find(id);
+ if (idit != mit->second.data.end()) {
+ List &locs = idit->second.locations;
+ assert(!locs.isEmpty());
+ location = locs.front();
+ if (locs.size() == 1) {
+ if (mit->second.data.size() == 1) {
+ mMacroTokens.erase(mit);
+ } else {
+ mit->second.data.erase(idit);
+ }
+ } else {
+ locs.remove(0, 1);
+ }
+ std::shared_ptr uu = unit(location);
+ c = &uu->symbols[location];
+ Map &tt = uu->targets[location];
+ tt[refUsr] = refTargetValue;
+ setTarget = false;
+ }
+ }
+ break;
+ }
+ }
+ break;
+ }
+ }
+ }
+
+ assert(!refUsr.isEmpty());
+ targets[refUsr] = refTargetValue;
+
+ if (mInTemplateFunction)
+ c->flags |= Symbol::TemplateReference;
+
+ if (cursorPtr)
+ *cursorPtr = c;
+
+ // We need the new cursor to replace the symbolLength. This is important
+ // in the following case:
+ // struct R { R(const &r); ... }
+ // R foo();
+ // ...
+ // R r = foo();
+
+ // The first cursor on foo() will be a reference to the copy constructor and
+ // this cursor will have a symbolLength of 1. Thus you won't be able to jump
+ // to foo from the o. This is fixed by making sure the newer target, if
+ // better, gets to decide on the symbolLength
+
+ // The !isCursor is var decls and field decls where we set up a target even
+ // if they're not considered references
+
+ if (setTarget && !c->isNull()) {
+ if (RTags::isCursor(c->kind))
+ return true;
+ auto best = targets.end();
+ int bestRank = RTags::targetRank(RTags::targetsValueKind(refTargetValue));
+ for (auto it = targets.begin(); it != targets.end(); ++it) {
+ const int r = RTags::targetRank(RTags::targetsValueKind(it->second));
+ if (r > bestRank || (r == bestRank && RTags::targetsValueIsDefinition(it->second))) {
+ bestRank = r;
+ best = it;
+ }
+ }
+ if (best != targets.end() && best->first != refUsr) { // another target is better
+ return true;
+ }
+ }
+
+#if CINDEX_VERSION >= CINDEX_VERSION_ENCODE(0, 35)
+ if (result == Found) {
+ c->size = reffedCursor.size;
+ c->alignment = reffedCursor.alignment;
+ } else {
+ const CXType type = clang_getCursorType(ref);
+ if (type.kind != CXType_LValueReference
+ && type.kind != CXType_RValueReference
+ && type.kind != CXType_Auto
+ && type.kind != CXType_Unexposed) {
+ c->size = std::max(0, clang_Type_getSizeOf(type));
+ c->alignment = std::max(-1, clang_Type_getAlignOf(type));
+ }
+ }
+#endif
+
+ CXSourceRange range = clang_getCursorExtent(cursor);
+ uint16_t symLength;
+ setRange(*c, range, &symLength);
+ c->kind = kind;
+ c->location = location;
+
+ c->symbolName = RTags::eatString(clang_getCursorSpelling(cursor));
+ if (c->symbolName.isEmpty())
+ c->symbolName = (result == Found ? reffedCursor.symbolName : addNamePermutations(ref, refLoc, RTags::Type_Reference));
+ if (isOperator) {
+ c->symbolLength = symLength;
+ } else {
+ c->symbolLength = result == Found ? reffedCursor.symbolLength : symbolLength(refKind, ref);
+ }
+ if (!c->symbolLength) {
+ unit(location)->symbols.remove(location);
+ if (cursorPtr)
+ *cursorPtr = 0;
+ return false;
+ }
+ setType(*c, clang_getCursorType(kind == CXCursor_MemberRefExpr ? ref : cursor));
+ if (RTags::isFunction(refKind)) {
+ mLastCallExprSymbol = c;
+ }
+
+ if (mInTemplateFunction && !mParents.isEmpty()) {
+ if ((kind == CXCursor_DeclRefExpr && mParents.last() == CXCursor_MemberRefExpr)
+ || (kind == CXCursor_TypeRef && mParents.last() == CXCursor_DeclRefExpr)) {
+ CXSourceRange parentRange = clang_getCursorExtent(mParents.last());
+ CXToken *tokens = 0;
+ unsigned numTokens = 0;
+ auto tu = mTranslationUnits.at(mCurrentTranslationUnit)->unit;
+ clang_tokenize(tu, parentRange, &tokens, &numTokens);
+ for (size_t i=0; i" || str == "." || str == "::") && ++i < numTokens) {
+ assert(i < numTokens);
+ CXSourceRange memberRange = clang_getTokenExtent(tu, tokens[i]);
+ unsigned line, column;
+ clang_getSpellingLocation(clang_getRangeStart(memberRange), 0, &line, &column, 0);
+ const CXStringScope memberSpelling(clang_getTokenSpelling(tu, tokens[i]));
+ const Location loc(location.fileId(), line, column);
+ Symbol &sym = unit(loc)->symbols[loc];
+ sym.location = loc;
+ sym.symbolName = memberSpelling.data();
+ sym.symbolLength = sym.symbolName.size();
+ if (kind == CXCursor_DeclRefExpr) {
+ sym.kind = CXCursor_MemberRefExpr;
+ } else {
+ sym.kind = CXCursor_DeclRefExpr; // yes this is weird
+ }
+ sym.flags = Symbol::TemplateReference;
+ setType(sym, clang_getCursorType(mParents.last()));
+ setRange(sym, memberRange);
+ if (kind == CXCursor_DeclRefExpr) // there might be more than one level of ::
+ break;
+ }
+ }
+ }
+
+ clang_disposeTokens(tu, tokens, numTokens);
+ }
+ }
+
+ return true;
+}
+
+std::unordered_set ClangIndexer::addOverriddenCursors(const CXCursor &c, Location location)
+{
+ // error() << "addOverriddenCursors" << cursor << location;
+ std::unordered_set ret;
+ std::function process = [location, &ret, this, &process](const CXCursor &cursor) {
+ CXCursor *overridden;
+ unsigned int count;
+ clang_getOverriddenCursors(cursor, &overridden, &count);
+ if (overridden) {
+ ret.insert(cursor);
+ for (unsigned int i=0; itargets[location][usr] = 0;
+ process(overridden[i]);
+ }
+ clang_disposeOverriddenCursors(overridden);
+ }
+ };
+ process(c);
+ return ret;
+}
+
+void ClangIndexer::handleInclude(const CXCursor &cursor, CXCursorKind kind, Location location)
+{
+ assert(kind == CXCursor_InclusionDirective);
+ (void)kind;
+ CXFile includedFile = clang_getIncludedFile(cursor);
+ if (includedFile) {
+ const Location refLoc = createLocation(includedFile, 1, 1);
+ if (!refLoc.isNull()) {
+ Symbol &c = unit(location)->symbols[location];
+ if (!c.isNull())
+ return;
+
+ String include = "#include ";
+ Path path = refLoc.path();
+ assert(mSources.front().fileId);
+ unit(location)->symbolNames[(include + path)].insert(location);
+ unit(location)->symbolNames[(include + path.fileName())].insert(location);
+ mIndexDataMessage.includes().push_back(std::make_pair(location.fileId(), refLoc.fileId()));
+ c.symbolName = "#include " + RTags::eatString(clang_getCursorDisplayName(cursor));
+ c.kind = cursor.kind;
+ c.symbolLength = c.symbolName.size() + 2;
+ c.location = location;
+ unit(location)->targets[location][refLoc.toString(Location::NoColor|Location::ConvertToRelative)] = 0; // ### what targets value to create for this?
+ // this fails for things like:
+ // # include
+ return;
+ }
+ }
+
+ mIndexDataMessage.files()[location.fileId()] |= IndexDataMessage::IncludeError;
+ error() << "handleInclude failed" << includedFile << cursor;
+}
+
+void ClangIndexer::handleLiteral(const CXCursor &cursor, CXCursorKind kind, Location location)
+{
+ auto tu = mTranslationUnits.at(mCurrentTranslationUnit)->unit;
+ auto u = unit(location);
+ // error() << location << kind
+ // << RTags::eatString(clang_getCursorDisplayName(cursor))
+ // << RTags::eatString(clang_getCursorSpelling(cursor))
+ // << clang_getCursorType(cursor).kind;
+
+ CXType type = clang_getCursorType(cursor);
+ // error() << location << kind << displayName;
+ Symbol &s = u->symbols[location];
+ if (!s.isNull())
+ return;
+ s.location = location;
+ s.kind = kind;
+ setType(s, type);
+ CXSourceRange range = clang_getCursorExtent(cursor);
+ setRange(s, range, &s.symbolLength);
+
+ String symbolName;
+ if (kind != CXCursor_StringLiteral) {
+ CXToken *tokens = 0;
+ unsigned numTokens = 0;
+ clang_tokenize(tu, range, &tokens, &numTokens);
+ if (numTokens) {
+ symbolName = RTags::eatString(clang_getTokenSpelling(tu, tokens[0]));
+ } else {
+ Log(&symbolName) << type.kind;
+ }
+
+ clang_disposeTokens(tu, tokens, numTokens);
+ } else {
+ symbolName = RTags::eatString(clang_getCursorSpelling(cursor));
+ }
+ s.symbolName = symbolName;
+ u->symbolNames[symbolName].insert(location);
+ s.symbolLength = symbolName.size();
+}
+
+CXChildVisitResult ClangIndexer::handleStatement(const CXCursor &cursor, CXCursorKind kind, Location location)
+{
+ auto u = unit(location);
+ // error() << "got dude" << kind << location;
+ switch (kind) {
+ case CXCursor_CompoundStmt: {
+ Symbol &c = u->symbols[location];
+ if (!c.isNull()) {
+ break;
+ }
+ setRange(c, clang_getCursorExtent(cursor));
+ const Scope scope = {
+ Scope::Other, 0,
+ Location(location.fileId(), c.startLine, c.startColumn),
+ Location(location.fileId(), c.endLine, c.endColumn - 1)
+ };
+ if (mScopeStack.isEmpty() || mScopeStack.back().end != scope.end) {
+ c.location = location;
+ c.kind = kind;
+ c.symbolName = "{}";
+ c.symbolLength = 1;
+ // should it have a symbolLength?
+ mScopeStack.append(scope);
+ visit(cursor);
+ mScopeStack.removeLast();
+ } else {
+ // this is the function body, no need for this CompoundStmt
+ u->symbols.remove(location);
+ visit(cursor);
+ }
+ return CXChildVisit_Continue; }
+ case CXCursor_ReturnStmt: {
+ Symbol &c = u->symbols[location];
+ if (!c.isNull())
+ break;
+
+ for (int i=mScopeStack.size() - 1; i>=0; --i) {
+ const auto &scope = mScopeStack.at(i);
+ if (scope.type == Scope::FunctionDefinition) {
+ c.kind = kind;
+ c.symbolName = "return";
+ u->symbolNames[c.symbolName].insert(location);
+ c.kind = kind;
+ c.symbolLength = 6;
+ c.location = location;
+ setRange(c, clang_getCursorExtent(cursor));
+ u->targets[location][scope.start.toString(Location::NoColor|Location::ConvertToRelative)] = 0;
+ break;
+ }
+ }
+ if (!c.symbolLength)
+ u->symbols.remove(location);
+ break; }
+ case CXCursor_ForStmt:
+ case CXCursor_WhileStmt:
+ case CXCursor_DoStmt:
+ case CXCursor_IfStmt:
+ case CXCursor_SwitchStmt: {
+ Symbol &c = u->symbols[location];
+ if (!c.isNull())
+ break;
+ setRange(c, clang_getCursorExtent(cursor));
+ c.kind = kind;
+ switch (kind) {
+ case CXCursor_SwitchStmt: c.symbolName = "switch"; break;
+ case CXCursor_IfStmt: c.symbolName = "if"; break;
+ case CXCursor_ForStmt: c.symbolName = "for"; break;
+ case CXCursor_WhileStmt: c.symbolName = "while"; break;
+ case CXCursor_DoStmt: c.symbolName = "do"; break;
+ default: assert(0); break;
+ }
+ u->symbolNames[c.symbolName].insert(location);
+ c.symbolLength = c.symbolName.size();
+ c.location = location;
+ if (kind != CXCursor_IfStmt) {
+ const Loop loop = {
+ kind,
+ Location(location.fileId(), c.startLine, c.startColumn),
+ Location(location.fileId(), c.endLine, c.endColumn)
+ };
+
+ mLoopStack.append(loop);
+ visit(cursor);
+ mLoopStack.removeLast();
+ return CXChildVisit_Continue;
+ }
+ break; }
+ case CXCursor_ContinueStmt:
+ case CXCursor_BreakStmt: {
+ Symbol &c = u->symbols[location];
+ if (!c.isNull())
+ break;
+ Location target;
+ for (int i = mLoopStack.size() - 1; i>=0; --i) {
+ const auto &loop = mLoopStack.at(i);
+ if (kind == CXCursor_BreakStmt) {
+ target = loop.end;
+ break;
+ } else if (loop.kind != CXCursor_SwitchStmt) {
+ target = loop.start;
+ break;
+ }
+ }
+ if (target.isNull()) {
+ u->symbols.remove(location);
+ break;
+ }
+ setRange(c, clang_getCursorExtent(cursor));
+ c.symbolName = kind == CXCursor_BreakStmt ? "break" : "continue";
+ u->symbolNames[c.symbolName].insert(location);
+ c.kind = kind;
+ c.symbolLength = c.symbolName.size();
+ c.location = location;
+ u->targets[location][target.toString(Location::NoColor|Location::ConvertToRelative)] = 0;
+ break; }
+ default:
+ break;
+ }
+ return CXChildVisit_Recurse;
+}
+
+void ClangIndexer::handleBaseClassSpecifier(const CXCursor &cursor)
+{
+ auto &lastClass = unit(mLastClass)->symbols[mLastClass];
+ if (!lastClass.isClass()) {
+ // this happens with some weird macros in /usr/include/dispatch/io.h:161:1 and others on Mac
+ // error() << "Couldn't find class for" << cursor << mLastClass;
+ return;
+ }
+ CXCursor ref = clang_getCursorReferenced(cursor);
+ if (clang_isInvalid(clang_getCursorKind(ref))) { // this happens when the base class is a template parameter
+ return;
+ }
+
+ while (true) {
+ CXCursor tmp = resolveTypedef(resolveTemplate(ref));
+ if (tmp == ref) {
+ break;
+ } else {
+ ref = std::move(tmp);
+ }
+ }
+ const String usr = ::usr(ref);
+ if (usr.isEmpty()) {
+ warning() << "Couldn't find usr for" << clang_getCursorReferenced(cursor) << cursor << mLastClass;
+ return;
+ }
+ assert(!usr.isEmpty());
+ lastClass.baseClasses << usr;
+}
+
+void ClangIndexer::extractArguments(List *arguments, const CXCursor &cursor)
+{
+ assert(arguments);
+ List args;
+ const int count = std::max(0, RTags::cursorArguments(cursor, &args));
+ arguments->resize(count);
+ for (int i=0; iunit;
+ const String usr = ::usr(cursor);
+ // error() << "Got a cursor" << cursor;
+ Symbol &c = unit(location)->symbols[location];
+ if (cursorPtr)
+ *cursorPtr = &c;
+ if (!c.isNull()) {
+ if (c.kind == CXCursor_MacroExpansion) {
+ addNamePermutations(cursor, location, RTags::Type_Cursor);
+ unit(location)->usrs[usr].insert(location);
+ }
+ return CXChildVisit_Recurse;
+ }
+
+ // if (mLogFile) {
+ // String out;
+ // Log(&out) << cursor << a;
+ // fwrite(out.constData(), 1, out.size(), mLogFile);
+ // fwrite("\n", 1, 1, mLogFile);
+ // }
+ CXStringScope name = clang_getCursorSpelling(cursor);
+ const char *cstr = name.data();
+ c.symbolLength = cstr ? strlen(cstr) : 0;
+ const CXType type = clang_getCursorType(cursor);
+ setType(c, type);
+ c.location = location;
+ c.usr = usr;
+ if (!c.symbolLength) {
+ // this is for these constructs:
+ // typedef struct {
+ // int a;
+ // } foobar;
+ //
+ // We end up not getting a spelling for the cursor
+
+ switch (kind) {
+ case CXCursor_ClassDecl:
+ c.symbolLength = 5;
+ c.symbolName = "class";
+ break;
+ case CXCursor_UnionDecl:
+ c.symbolLength = 5;
+ c.symbolName = "union";
+ break;
+ case CXCursor_StructDecl:
+ c.symbolLength = 6;
+ c.symbolName = "struct";
+ break;
+ case CXCursor_LambdaExpr:
+ c.symbolLength = 2;
+ c.symbolName = c.typeName;
+ break;
+ default:
+ unit(location)->symbols.remove(location);
+ if (cursorPtr)
+ *cursorPtr = 0;
+ return CXChildVisit_Recurse;
+ }
+ } else {
+ if (kind == CXCursor_VarDecl || kind == CXCursor_ParmDecl) {
+ RTags::Auto resolvedAuto;
+ if (RTags::resolveAuto(cursor, &resolvedAuto)) {
+ c.flags |= Symbol::Auto;
+ if (resolvedAuto.type.kind != CXType_Invalid) {
+ setType(c, resolvedAuto.type);
+ } else {
+ warning() << "Couldn't resolve auto for" << cursor;
+ }
+ }
+ }
+
+ c.symbolName = addNamePermutations(cursor, location, RTags::Type_Cursor);
+ }
+
+ if (clang_isCursorDefinition(cursor))
+ c.flags |= Symbol::Definition;
+
+ const CXSourceRange range = clang_getCursorExtent(cursor);
+ setRange(c, range);
+
+ switch (kind) {
+ case CXCursor_ParmDecl:
+ case CXCursor_VarDecl: {
+ if (type.kind != CXType_Record || mScopeStack.isEmpty() || mScopeStack.back().type == Scope::FunctionDeclaration)
+ break;
+
+ CXCursor ref = RTags::findChild(cursor, CXCursor_TypeRef);
+ if (ref != CXCursor_TypeRef)
+ ref = RTags::findChild(cursor, CXCursor_TemplateRef);
+ switch (clang_getCursorKind(ref)) {
+ case CXCursor_TypeRef:
+ case CXCursor_TemplateRef: {
+ const CXCursor referenced = clang_getCursorReferenced(ref);
+ switch (clang_getCursorKind(referenced)) {
+ case CXCursor_StructDecl:
+ case CXCursor_ClassDecl:
+ case CXCursor_ClassTemplate: {
+ const CXCursor destructor = RTags::findChild(referenced, CXCursor_Destructor);
+ if (RTags::isValid(destructor)) {
+ const String destructorUsr = ::usr(destructor);
+ assert(!destructorUsr.isEmpty());
+ const Location scopeEndLocation = mScopeStack.back().end;
+ auto u = unit(scopeEndLocation);
+ Map &t = u->targets[scopeEndLocation];
+ t[destructorUsr] = 0;
+ Symbol &scopeEnd = u->symbols[scopeEndLocation];
+ scopeEnd.symbolName = "}";
+ scopeEnd.location = scopeEndLocation;
+ scopeEnd.symbolLength = 1;
+ scopeEnd.flags = Symbol::ImplicitDestruction;
+ scopeEnd.kind = CXCursor_CallExpr;
+ // error() << "Found destructor" << destructor << "for" << cursor << "in scope that ends on" << mScopeStack.back();
+ }
+ break; }
+ default:
+ break;
+ }
+ break; }
+ default:
+ break;
+ }
+ break; }
+ case CXCursor_EnumConstantDecl:
+#if CINDEX_VERSION >= CINDEX_VERSION_ENCODE(0, 2)
+ c.enumValue = clang_getEnumConstantDeclValue(cursor);
+#endif
+ break;
+ case CXCursor_MacroDefinition: {
+ CXToken *tokens = 0;
+ unsigned numTokens = 0;
+ clang_tokenize(tu, range, &tokens, &numTokens);
+ MacroData ¯oData = mMacroTokens[location];
+ enum {
+ Unset,
+ GettingArgs,
+ ArgsDone
+ } macroState = Unset;
+ MacroLocationData *last = 0;
+ bool lastWasHashHash = false;
+ for (size_t i=1; iunit, tokens[i]));
+ if (macroState == Unset) {
+ if (k == CXToken_Punctuation) {
+ const CXStringScope scope(clang_getTokenSpelling(tu, tokens[i]));
+ if (!strcmp(scope.data(), "("))
+ macroState = GettingArgs;
+ }
+ if (macroState == Unset)
+ macroState = ArgsDone;
+ }
+ // error() << i << clang_getTokenKind(tokens[i])
+ // << RTags::eatString(clang_getTokenSpelling(tu, tokens[i]));
+ bool isHashHash = false;
+ if (k == CXToken_Identifier) {
+ const String spelling = RTags::eatString(clang_getTokenSpelling(tu, tokens[i]));
+ if (macroState == GettingArgs) {
+ macroData.arguments.append(spelling);
+ } else {
+ if (!lastWasHashHash) {
+ last = ¯oData.data[spelling];
+
+ List &locs = last->locations;
+ locs.append(createLocation(clang_getTokenLocation(tu, tokens[i])));
+ }
+ if (last) {
+ const size_t idx = macroData.arguments.indexOf(spelling);
+ if (idx != String::npos) {
+ last->arguments.insert(idx);
+ }
+ }
+ }
+ } else if (macroState == GettingArgs && k == CXToken_Punctuation) {
+ const CXStringScope scope(clang_getTokenSpelling(tu, tokens[i]));
+ if (!strcmp(scope.data(), ")"))
+ macroState = ArgsDone;
+ } else if (k == CXToken_Punctuation) {
+ const CXStringScope scope(clang_getTokenSpelling(tu, tokens[i]));
+ if (!strcmp(scope.data(), "##")) {
+ isHashHash = true;
+ } else {
+ last = 0;
+ }
+ } else {
+ last = 0;
+ }
+ lastWasHashHash = isHashHash;
+ }
+ // error() << macroData.arguments;
+ // for (const auto &d : macroData.data) {
+ // error() << d.first << d.second.locations << d.second.arguments;
+ // }
+
+ clang_disposeTokens(tu, tokens, numTokens);
+ break; }
+ case CXCursor_FieldDecl:
+#if CINDEX_VERSION >= CINDEX_VERSION_ENCODE(0, 30)
+ c.fieldOffset = std::max(-1, clang_Cursor_getOffsetOfField(cursor));
+#endif
+ // fall through
+ default:
+ break;
+ }
+
+#if CINDEX_VERSION >= CINDEX_VERSION_ENCODE(0, 35)
+ if (!(c.flags & Symbol::Auto)
+ && c.type != CXType_LValueReference
+ && c.type != CXType_RValueReference
+ && c.type != CXType_Auto
+ && c.type != CXType_Unexposed) {
+ c.size = std::max(0, clang_Type_getSizeOf(type));
+ c.alignment = std::max(-1, clang_Type_getAlignOf(type));
+ if (c.size > 0 && (kind == CXCursor_VarDecl || kind == CXCursor_ParmDecl)) {
+ for (int i=mScopeStack.size() - 1; i>=0; --i) {
+ auto &scope = mScopeStack.at(i);
+ if (scope.type == Scope::FunctionDefinition) {
+ assert(scope.symbol);
+ scope.symbol->stackCost += c.size;
+ break;
+ } else if (scope.type == Scope::FunctionDeclaration) {
+ break;
+ }
+ }
+ }
+ }
+#endif
+
+ c.kind = kind;
+ c.linkage = clang_getCursorLinkage(cursor);
+ // apparently some function decls will give a different usr for
+ // their definition and their declaration. Using the canonical
+ // cursor's usr allows us to join them. Check JSClassRelease in
+ // JavaScriptCore for an example.
+ unit(location)->usrs[c.usr].insert(location);
+ if (c.linkage == CXLinkage_External && !c.isDefinition()) {
+ switch (c.kind) {
+ case CXCursor_FunctionDecl:
+ case CXCursor_VarDecl: {
+ const auto k = clang_getCursorKind(clang_getCursorSemanticParent(cursor));
+ switch (k) {
+ case CXCursor_ClassDecl:
+ case CXCursor_ClassTemplate:
+ case CXCursor_StructDecl:
+ break;
+ default:
+ unit(location)->targets[location][usr] = RTags::createTargetsValue(k, true);
+ break;
+ }
+ break; }
+ default:
+ break;
+ }
+ }
+
+ std::unordered_set cursors;
+ switch (c.kind) {
+ case CXCursor_CXXMethod:
+#if CINDEX_VERSION >= CINDEX_VERSION_ENCODE(0, 20)
+ if (clang_CXXMethod_isPureVirtual(cursor))
+ c.flags |= Symbol::PureVirtualMethod;
+ else
+#endif
+ if (clang_CXXMethod_isVirtual(cursor))
+ c.flags |= Symbol::VirtualMethod;
+
+ if (clang_CXXMethod_isStatic(cursor))
+ c.flags |= Symbol::StaticMethod;
+#if CINDEX_VERSION >= CINDEX_VERSION_ENCODE(0, 27)
+ if (clang_CXXMethod_isConst(cursor))
+ c.flags |= Symbol::ConstMethod;
+#endif
+
+ cursors = addOverriddenCursors(cursor, location);
+ switch (clang_getCursorKind(clang_getCursorSemanticParent(cursor))) {
+ case CXCursor_ClassTemplate:
+ case CXCursor_ClassTemplatePartialSpecialization:
+ c.flags |= Symbol::TemplateFunction;
+ break;
+ default:
+ break;
+ }
+
+ // fall through
+ case CXCursor_FunctionDecl:
+ case CXCursor_FunctionTemplate:
+ if (c.kind == CXCursor_FunctionTemplate)
+ c.flags |= Symbol::TemplateFunction;
+#if CINDEX_VERSION >= CINDEX_VERSION_ENCODE(0, 19)
+ if (clang_Cursor_isVariadic(cursor))
+ c.flags |= Symbol::Variadic;
+#endif
+#if CINDEX_VERSION >= CINDEX_VERSION_ENCODE(0, 33)
+ if (clang_Cursor_isFunctionInlined(cursor))
+ c.flags |= Symbol::InlineFunction;
+#endif
+
+ extractArguments(&c.arguments, cursor);
+ break;
+ case CXCursor_LambdaExpr:
+ extractArguments(&c.arguments, cursor);
+ break;
+ case CXCursor_Constructor:
+ extractArguments(&c.arguments, cursor);
+ // fall through
+ case CXCursor_Destructor: {
+ CXCursor parent = clang_getCursorSemanticParent(cursor);
+
+ switch (clang_getCursorKind(parent)) {
+ case CXCursor_ClassTemplate:
+ case CXCursor_ClassTemplatePartialSpecialization:
+ c.flags |= Symbol::TemplateFunction;
+ break;
+ default:
+ break;
+ }
+
+ // these are for joining constructors/destructor with their classes (for renaming symbols)
+ assert(!::usr(parent).isEmpty());
+ unit(location)->targets[location][::usr(parent)] = 0;
+ break; }
+ case CXCursor_ClassTemplate:
+ case CXCursor_StructDecl:
+ case CXCursor_ClassDecl: {
+ const CXCursor specialization = clang_getSpecializedCursorTemplate(cursor);
+ if (RTags::isValid(specialization)) {
+ unit(location)->targets[location][::usr(specialization)] = 0;
+ c.flags |= Symbol::TemplateSpecialization;
+ }
+ break; }
+ default:
+ break;
+ }
+
+ if (!(ClangIndexer::serverOpts() & Server::NoComments)) {
+ CXComment comment = clang_Cursor_getParsedComment(cursor);
+ if (clang_Comment_getKind(comment) != CXComment_Null) {
+ c.briefComment = RTags::eatString(clang_Cursor_getBriefCommentText(cursor));
+ c.xmlComment = RTags::eatString(clang_FullComment_getAsXML(comment));
+ }
+
+ for (auto it = cursors.begin(); it != cursors.end() && (c.briefComment.isEmpty() || c.xmlComment.isEmpty()); ++it) {
+ comment = clang_Cursor_getParsedComment(*it);
+ if (clang_Comment_getKind(comment) != CXComment_Null) {
+ if (c.briefComment.isEmpty()) {
+ c.briefComment = RTags::eatString(clang_Cursor_getBriefCommentText(*it));
+ }
+ if (c.xmlComment.isEmpty())
+ c.xmlComment = RTags::eatString(clang_FullComment_getAsXML(comment));
+ }
+ }
+ }
+
+ if (RTags::isFunction(c.kind)) {
+ const bool definition = c.flags & Symbol::Definition;
+ mScopeStack.append({definition ? Scope::FunctionDefinition : Scope::FunctionDeclaration, definition ? &c : 0,
+ Location(location.fileId(), c.startLine, c.startColumn),
+ Location(location.fileId(), c.endLine, c.endColumn - 1)});
+ bool isTemplateFunction = c.kind == CXCursor_FunctionTemplate;
+ if (!isTemplateFunction && (c.kind == CXCursor_CXXMethod
+ || c.kind == CXCursor_Constructor
+ || c.kind == CXCursor_Destructor)
+ && clang_getCursorSemanticParent(cursor) == CXCursor_ClassTemplate) {
+ isTemplateFunction = true;
+ }
+ if (isTemplateFunction)
+ ++mInTemplateFunction;
+ visit(cursor);
+ if (isTemplateFunction)
+ --mInTemplateFunction;
+ mScopeStack.removeLast();
+ return CXChildVisit_Continue;
+ }
+
+ return CXChildVisit_Recurse;
+}
+
+bool ClangIndexer::parse()
+{
+ StopWatch sw;
+ assert(mTranslationUnits.isEmpty());
+ Flags commandLineFlags = Source::Default;
+ if (ClangIndexer::serverOpts() & Server::PCHEnabled)
+ commandLineFlags |= Source::PCHEnabled;
+
+ Flags flags = CXTranslationUnit_DetailedPreprocessingRecord;
+ if (mIndexDataMessage.indexerJobFlags() & IndexerJob::Active) {
+ flags |= CXTranslationUnit_PrecompiledPreamble;
+ flags |= CXTranslationUnit_ForSerialization;
+#if CINDEX_VERSION >= CINDEX_VERSION_ENCODE(0, 32)
+ flags |= CXTranslationUnit_CreatePreambleOnFirstParse;
+#endif
+ } else {
+#if CINDEX_VERSION_MINOR > 33
+ flags |= CXTranslationUnit_KeepGoing;
+#endif
+ }
+ bool pch;
+ switch (mSources.front().language) {
+ case Source::CPlusPlus11Header:
+ case Source::CPlusPlusHeader:
+ case Source::CHeader:
+ flags |= CXTranslationUnit_Incomplete;
+ pch = true;
+ break;
+ default:
+ pch = false;
+ break;
+ }
+
+ List unsavedFiles(mUnsavedFiles.size() + 1);
+ int unsavedIndex = 0;
+ for (const auto &it : mUnsavedFiles) {
+ unsavedFiles[unsavedIndex++] = {
+ it.first.constData(),
+ it.second.constData(),
+ static_cast(it.second.size())
+ };
+ }
+
+ bool ok = false;
+ for (const Source &source : mSources) {
+ if (testLog(LogLevel::Debug))
+ debug() << "CI::parse: " << source.toCommandLine(commandLineFlags) << "\n";
+
+ // for (const auto it : source.toCommandLine(commandLineFlags)) {
+ // error("[%s]", it.constData());
+ // }
+ bool usedPch = false;
+ const List args = source.toCommandLine(commandLineFlags, &usedPch);
+ if (usedPch)
+ mIndexDataMessage.setFlag(IndexDataMessage::UsedPCH);
+
+ std::shared_ptr unit;
+ if (mIndexDataMessage.indexerJobFlags() & IndexerJob::Active && serverOpts() & Server::TranslationUnitCache) {
+ Path path = mDataDir + "tucache/";
+ Path::mkdir(path, Path::Recursive);
+ path << mSources.front().fileId;
+ StopWatch sw2;
+ unit = RTags::TranslationUnit::load(path);
+ if (unit) {
+ error() << "loaded cached unit in" << sw2.restart();
+ if (!unit->reparse(&unsavedFiles[0], unsavedIndex)) {
+ error() << "Failed to reparse";
+ unit.reset();
+ } else {
+ error() << "reparsed cached unit in" << sw2.restart();
+ }
+ }
+ }
+
+ if (!unit)
+ unit = RTags::TranslationUnit::create(mSourceFile, args, &unsavedFiles[0], unsavedIndex, flags, false);
+ mTranslationUnits.push_back(unit);
+
+ warning() << "CI::parse loading unit:" << unit->clangLine << " " << (unit->unit != 0);
+ if (unit->unit) {
+ if (pch && ClangIndexer::serverOpts() & Server::PCHEnabled) {
+ Path path = RTags::encodeSourceFilePath(mDataDir, mProject, source.fileId);
+ Path::mkdir(path, Path::Recursive);
+ path << "pch.h.gch";
+ Path tmp = path;
+ tmp << ".tmp";
+ clang_saveTranslationUnit(unit->unit, tmp.constData(), clang_defaultSaveOptions(unit->unit));
+ rename(tmp.constData(), path.constData());
+ warning() << "SAVED PCH" << path;
+ } else if (!mSerializeTU && mIndexDataMessage.indexerJobFlags() & IndexerJob::Active && serverOpts() & Server::TranslationUnitCache) {
+ mSerializeTU = unit;
+ }
+
+ ok = true;
+ mParseDuration = sw.elapsed();
+ } else {
+ error() << "Failed to parse" << unit->clangLine;
+ mIndexDataMessage.setFlag(IndexDataMessage::ParseFailure);
+ }
+ }
+ return ok;
+}
+
+static inline Map > convertTargets(const Map > &in, bool hasRoot)
+{
+ Map > ret;
+ if (hasRoot) {
+ for (const auto &v : in) {
+ for (const auto &u : v.second) {
+ ret[Sandbox::encoded(u.first)].insert(v.first);
+ }
+ }
+ } else {
+ for (const auto &v : in) {
+ for (const auto &u : v.second) {
+ ret[u.first].insert(v.first);
+ }
+ }
+ }
+ return ret;
+}
+
+static inline void encodeSymbols(Map &symbols)
+{
+ assert(Sandbox::hasRoot());
+ for (auto &sym : symbols) {
+ Sandbox::encode(sym.second.symbolName);
+ Sandbox::encode(sym.second.usr);
+ Sandbox::encode(sym.second.typeName);
+ Sandbox::encode(sym.second.briefComment);
+ Sandbox::encode(sym.second.xmlComment);
+ }
+}
+
+bool ClangIndexer::writeFiles(const Path &root, String &error)
+{
+ size_t bytesWritten = 0;
+ const Path p = Sandbox::encoded(mSourceFile);
+ const bool hasRoot = Sandbox::hasRoot();
+ const uint32_t fileId = mSources.front().fileId;
+
+ auto process = [&](Hash >::const_iterator unit) {
+ assert(mIndexDataMessage.files().value(unit->first) & IndexDataMessage::Visited);
+ String unitRoot = root;
+ unitRoot << unit->first;
+ Path::mkdir(unitRoot, Path::Recursive);
+ const Path path = Location::path(unit->first);
+ if (unit->first != fileId) {
+ FILE *f = fopen((unitRoot + "/info").constData(), "w");
+ if (!f)
+ return false;
+ Path rpath = path;
+ Sandbox::encode(rpath);
+ bytesWritten += fprintf(f, "%s\nIndexed by %s at %llu\n",
+ rpath.constData(),
+ p.constData(), static_cast(mIndexDataMessage.parseTime()));
+ fclose(f);
+ }
+
+ auto uit = mUnsavedFiles.find(path);
+ if (uit == mUnsavedFiles.end()) {
+ Path::rm(unitRoot + "/unsaved");
+ } else {
+ FILE *f = fopen((unitRoot + "/unsaved").constData(), "w");
+ if (!f)
+ return false;
+ bool ok = fwrite(uit->second.constData(), uit->second.size(), 1, f);
+ fclose(f);
+ if (!ok)
+ return false;
+ bytesWritten += uit->second.size();
+ }
+
+ //::error() << "Writing file" << Location::path(unit->first) << unitRoot << unit->second->symbols.size()
+ // << unit->second->targets.size()
+ // << unit->second->usrs.size()
+ // << unit->second->symbolNames.size();
+ uint32_t fileMapOpts = 0;
+ if (ClangIndexer::serverOpts() & Server::NoFileLock)
+ fileMapOpts |= FileMap::NoLock;
+
+ if (hasRoot) {
+ encodeSymbols(unit->second->symbols);
+ Sandbox::encode(unit->second->usrs);
+ Sandbox::encode(unit->second->symbolNames);
+ }
+
+ size_t w;
+ // for (const char *name : { "/symbols", "/targets", "/usrs", "/symnames", "/tokens" }) {
+ // if (Path::exists(unitRoot + "/symbols"))
+ // ::error() << (unitRoot + name) << "already exists";
+ // }
+ if (!(w = FileMap::write(unitRoot + "/symbols", unit->second->symbols, fileMapOpts))) {
+ error = "Failed to write symbols";
+ return false;
+ }
+ bytesWritten += w;
+
+ if (!(w = FileMap >::write(unitRoot + "/targets", convertTargets(unit->second->targets, hasRoot), fileMapOpts))) {
+ error = "Failed to write targets";
+ return false;
+ }
+ bytesWritten += w;
+
+ if (!(w += FileMap >::write(unitRoot + "/usrs", unit->second->usrs, fileMapOpts))) {
+ error = "Failed to write usrs";
+ return false;
+ }
+ bytesWritten += w;
+
+ if (!(w += FileMap >::write(unitRoot + "/symnames", unit->second->symbolNames, fileMapOpts))) {
+ error = "Failed to write symbolNames";
+ return false;
+ }
+ bytesWritten += w;
+
+ if (!(w += FileMap::write(unitRoot + "/tokens", unit->second->tokens, fileMapOpts))) {
+ error = "Failed to write symbolNames";
+ return false;
+ }
+ bytesWritten += w;
+ return true;
+ };
+
+ List > templateSpecializationTargets;
+ auto self = mUnits.end();
+ for (auto it = mUnits.begin(); it != mUnits.end(); ++it) {
+ if (!(mIndexDataMessage.files().value(it->first) & IndexDataMessage::Visited)) {
+ ::error() << "Wanting to write something for"
+ << it->first << Location::path(it->first)
+ << "but we didn't visit it" << mSourceFile
+ << "targets" << it->second->targets.size()
+ << "usrs" << it->second->usrs.size()
+ << "symbolNames" << it->second->symbolNames.size()
+ << "symbols" << it->second->symbols.size()
+ << "tokens" << it->second->tokens.size();
+ continue;
+ }
+ if (it->first == fileId) {
+ self = it;
+ } else if (!process(it)) {
+ return false;
+ }
+ }
+
+ if (self != mUnits.end()) {
+ for (const std::shared_ptr &t : templateSpecializationTargets) {
+ self->second->targets.unite(t->targets);
+ }
+ if (!process(self)) {
+ return false;
+ }
+ }
+ String sourceRoot = root;
+ sourceRoot << fileId;
+ Path::mkdir(sourceRoot, Path::Recursive);
+ sourceRoot << "/info";
+ FILE *f = fopen(sourceRoot.constData(), "w");
+ if (!f) {
+ return false;
+ }
+
+ for (const Source &source : mSources) {
+ const String args = Sandbox::encoded(String::join(source.toCommandLine(Source::Default|Source::IncludeCompiler|Source::IncludeSourceFile), ' '));
+
+ bytesWritten += fprintf(f, "%s\n%s\n", p.constData(), args.constData());
+ }
+ bytesWritten += fprintf(f, "Indexed at %llu\n", static_cast(mIndexDataMessage.parseTime()));
+
+ fclose(f);
+ mIndexDataMessage.setBytesWritten(bytesWritten);
+ return true;
+}
+
+bool ClangIndexer::diagnose()
+{
+ DiagnosticsProvider::diagnose();
+ for (size_t i=0; iunit;
+ if (!tu) {
+ continue;
+ }
+ for (const auto &it : mIndexDataMessage.files()) {
+ if (it.second & IndexDataMessage::Visited) {
+ const Location loc(it.first, 0, 0);
+ const Path path = loc.path();
+ CXFile file = clang_getFile(tu, path.constData());
+ if (file) {
+ tokenize(file, it.first, path);
+ }
+ }
+ }
+ }
+
+ return true;
+}
+
+void ClangIndexer::tokenize(CXFile file, uint32_t fileId, const Path &path)
+{
+ const auto &tu = mTranslationUnits.at(mCurrentTranslationUnit)->unit;
+ StopWatch sw;
+ const CXSourceLocation startLoc = clang_getLocationForOffset(tu, file, 0);
+ const CXSourceLocation endLoc = clang_getLocationForOffset(tu, file, path.fileSize());
+
+ CXSourceRange range = clang_getRange(startLoc, endLoc);
+ CXToken *tokens = 0;
+ unsigned numTokens = 0;
+ auto &map = unit(fileId)->tokens;
+ clang_tokenize(tu, range, &tokens, &numTokens);
+ for (unsigned i=0; iunit) {
+ continue;
+ }
+
+ visit(clang_getTranslationUnitCursor(unit->unit));
+
+ if (testLog(LogLevel::VerboseDebug)) {
+ VerboseVisitorUserData u = { 0, "clangLine + ">\n", this };
+ clang_visitChildren(clang_getTranslationUnitCursor(unit->unit),
+ ClangIndexer::verboseVisitor, &u);
+ u.out += "clangLine + ">";
+ if (getenv("RTAGS_INDEXERJOB_DUMP_TO_FILE")) {
+ char buf[1024];
+ snprintf(buf, sizeof(buf), "/tmp/%s.log", mSourceFile.fileName());
+ FILE *f = fopen(buf, "w");
+ assert(f);
+ fwrite(u.out.constData(), 1, u.out.size(), f);
+ fclose(f);
+ } else {
+ logDirect(LogLevel::VerboseDebug, u.out);
+ }
+ }
+ }
+
+ for (const auto &it : mIndexDataMessage.files()) {
+ if (it.second & IndexDataMessage::Visited)
+ addFileSymbol(it.first);
+ }
+
+ std::unordered_set seen;
+ for (const CXCursor &spec : mTemplateSpecializations) {
+ std::function visitor = [&visitor, &seen, this](CXCursor cursor) {
+ if (!seen.insert(cursor).second) {
+ return CXChildVisit_Continue;
+ }
+ const CXCursorKind kind = clang_getCursorKind(cursor);
+ const CXCursor ref = clang_getCursorReferenced(cursor);
+ if (!ref)
+ return CXChildVisit_Recurse;
+ const CXCursorKind refKind = clang_getCursorKind(ref);
+ if (kind == CXCursor_CallExpr && (refKind == CXCursor_CXXMethod
+ || refKind == CXCursor_FunctionDecl
+ || refKind == CXCursor_FunctionTemplate)) {
+ return CXChildVisit_Recurse;
+ }
+
+ // error() << "considering" << cursor << "for" << ref;
+ bool ignored;
+ const Location loc = createLocation(cursor, kind, &ignored);
+ if (!loc.isNull()) {
+ const String refUsr = usr(resolveTemplate(ref));
+ if (!refUsr.isEmpty()) {
+ assert(!refUsr.isEmpty());
+ const uint32_t fileId = mSources.front().fileId;
+ unit(fileId)->targets[loc][refUsr] = RTags::createTargetsValue(refKind, clang_isCursorDefinition(ref));
+ }
+ if (RTags::isFunction(refKind) && mTemplateSpecializations.find(ref) == mTemplateSpecializations.end()) {
+ RTags::TranslationUnit::visit(ref, visitor);
+ }
+ // error() << "inserting" << loc << refUsr;
+ }
+ return CXChildVisit_Recurse;
+ };
+ RTags::TranslationUnit::visit(spec, visitor);
+ }
+
+ mVisitDuration = watch.elapsed();
+
+ return true;
+}
+
+CXChildVisitResult ClangIndexer::verboseVisitor(CXCursor cursor, CXCursor, CXClientData userData)
+{
+ VerboseVisitorUserData *u = reinterpret_cast(userData);
+ Location loc = u->indexer->createLocation(cursor);
+ if (loc.fileId()) {
+ CXCursor ref = clang_getCursorReferenced(cursor);
+
+ if (u->indent >= 0)
+ u->out += String(u->indent, ' ');
+ u->out += RTags::cursorToString(cursor);
+ if (ref == cursor) {
+ u->out += " refs self";
+ } else if (RTags::isValid(ref)) {
+ u->out += " refs " + RTags::cursorToString(ref);
+ }
+
+ if (loc.fileId() && u->indexer->mIndexDataMessage.files().value(loc.fileId()) & IndexDataMessage::Visited) {
+ if (u->indexer->unit(loc)->symbols.contains(loc)) {
+ u->out += " used as cursor\n";
+ } else {
+ u->out += " not used\n";
+ }
+ } else {
+ u->out += " not indexed\n";
+ }
+ }
+ if (u->indent >= 0) {
+ u->indent += 2;
+ clang_visitChildren(cursor, ClangIndexer::verboseVisitor, userData);
+ u->indent -= 2;
+ return CXChildVisit_Continue;
+ } else {
+ return CXChildVisit_Recurse;
+ }
+}
+
+void ClangIndexer::addFileSymbol(uint32_t file)
+{
+ const Location loc(file, 1, 1);
+ const Path path = Location::path(file);
+ auto ref = unit(loc);
+ ref->symbolNames[path].insert(loc);
+ const char *fn = path.fileName();
+ ref->symbolNames[fn].insert(loc);
+ Symbol &sym = ref->symbols[loc];
+ if (sym.isNull())
+ sym.flags |= Symbol::FileSymbol;
+ sym.location = loc;
+}
+
+int ClangIndexer::symbolLength(CXCursorKind kind, const CXCursor &cursor)
+{
+ if (kind == CXCursor_VarDecl && RTags::resolveAuto(cursor)) {
+ return 4;
+ }
+
+ CXStringScope name = clang_getCursorSpelling(cursor);
+ const char *cstr = name.data();
+ if (cstr)
+ return strlen(cstr);
+
+ // this is for these constructs:
+ // ||
+ // \/
+ // typedef struct {
+ // int a;
+ // } foobar;
+ //
+ // We end up not getting a spelling for the cursor
+
+ switch (kind) {
+ case CXCursor_EnumDecl:
+ return 4;
+ case CXCursor_ClassDecl:
+ case CXCursor_UnionDecl:
+ return 5;
+ case CXCursor_StructDecl:
+ return 6;
+ default:
+ break;
+ }
+ return 0;
+}
+
+Symbol ClangIndexer::findSymbol(Location location, FindResult *result) const
+{
+ auto it = mUnits.find(location.fileId());
+ if (it != mUnits.end()) {
+ bool ok;
+ Symbol ret = it->second->symbols.value(location, Symbol(), &ok);
+ if (ok) {
+ *result = Found;
+ return ret;
+ }
+ }
+
+ if (mIndexDataMessage.files().value(location.fileId()) & IndexDataMessage::Visited) {
+ *result = NotFound;
+ } else {
+ *result = NotIndexed;
+ }
+ return Symbol();
+}
+
+CXCursor ClangIndexer::resolveTemplate(CXCursor cursor, Location location, bool *specialized)
+{
+ if (specialized)
+ *specialized = false;
+ while (true) {
+ const CXCursor general = clang_getSpecializedCursorTemplate(cursor);
+ if (clang_Cursor_isNull(general))
+ break;
+ if (specialized)
+ *specialized = true;
+ if (location.isNull())
+ location = createLocation(cursor);
+ if (createLocation(general) == location) {
+ cursor = general;
+ } else {
+ break;
+ }
+ }
+ return cursor;
+}
+
+CXCursor ClangIndexer::resolveTypedef(CXCursor cursor)
+{
+ while (clang_getCursorKind(cursor) == CXCursor_TypedefDecl) {
+ CXCursor typedeffed = clang_getTypeDeclaration(clang_getTypedefDeclUnderlyingType(cursor));
+ if (RTags::isValid(typedeffed)) {
+ cursor = typedeffed;
+ } else {
+ break;
+ }
+ }
+ return cursor;
+}
diff --git a/rtags/src/ClangIndexer.h b/rtags/src/ClangIndexer.h
new file mode 100644
index 0000000..ce40b72
--- /dev/null
+++ b/rtags/src/ClangIndexer.h
@@ -0,0 +1,196 @@
+/* This file is part of RTags (http://rtags.net).
+
+ RTags is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ RTags is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with RTags. If not, see . */
+
+#ifndef ClangIndexer_h
+#define ClangIndexer_h
+
+#include
+#include "Token.h"
+
+#include "IndexDataMessage.h"
+#include "rct/Hash.h"
+#include "rct/Path.h"
+#include "rct/StopWatch.h"
+#include "RTags.h"
+#include "Server.h"
+#include "Symbol.h"
+#include
+
+struct Unit;
+class ClangIndexer : public RTags::DiagnosticsProvider
+{
+public:
+ ClangIndexer();
+ ~ClangIndexer();
+
+ bool exec(const String &data);
+ static Flags serverOpts() { return sServerOpts; }
+ static const Path &serverSandboxRoot() { return sServerSandboxRoot; }
+private:
+ bool diagnose();
+ bool visit();
+ bool parse();
+ void tokenize(CXFile file, uint32_t fileId, const Path &path);
+ bool writeFiles(const Path &root, String &error);
+
+ void addFileSymbol(uint32_t file);
+ int symbolLength(CXCursorKind kind, const CXCursor &cursor);
+ void extractArguments(List *arguments, const CXCursor &cursor);
+ CXCursor resolveTemplate(CXCursor cursor, Location location = Location(), bool *specialized = 0);
+ static CXCursor resolveTypedef(CXCursor cursor);
+
+ // DiagnosticsProvider
+ using RTags::DiagnosticsProvider::createLocation;
+ virtual Location createLocation(const Path &file, unsigned int line, unsigned int col, bool *blocked = 0) override;
+ virtual CXTranslationUnit unit(size_t u) const override;
+ virtual size_t unitCount() const override
+ {
+ return mTranslationUnits.size();
+ }
+ virtual size_t diagnosticCount(size_t unit) const override
+ {
+ if (CXTranslationUnit u = mTranslationUnits[unit]->unit) {
+ return clang_getNumDiagnostics(u);
+ }
+ return 0;
+ }
+ virtual CXDiagnostic diagnostic(size_t unit, size_t idx) const override
+ {
+ assert(mTranslationUnits[unit]->unit);
+ return clang_getDiagnostic(mTranslationUnits[unit]->unit, idx);
+ }
+
+ virtual uint32_t sourceFileId() const override { return mSources.front().fileId; }
+ virtual IndexDataMessage &indexDataMessage() override { return mIndexDataMessage; }
+
+ String addNamePermutations(const CXCursor &cursor,
+ Location location,
+ RTags::CursorType cursorType);
+
+ CXChildVisitResult handleCursor(const CXCursor &cursor, CXCursorKind kind,
+ Location location, Symbol **cursorPtr = 0);
+ bool handleReference(const CXCursor &cursor, CXCursorKind kind,
+ Location loc, CXCursor reference,
+ Symbol **cursorPtr = 0);
+ void handleBaseClassSpecifier(const CXCursor &cursor);
+ void handleInclude(const CXCursor &cursor, CXCursorKind kind, Location location);
+ void handleLiteral(const CXCursor &cursor, CXCursorKind kind, Location location);
+ CXChildVisitResult handleStatement(const CXCursor &cursor, CXCursorKind kind, Location location);
+ Location findByUSR(const CXCursor &cursor, CXCursorKind kind, Location loc) const;
+ std::unordered_set addOverriddenCursors(const CXCursor &cursor, Location location);
+ bool superclassTemplateMemberFunctionUgleHack(const CXCursor &cursor, CXCursorKind kind,
+ Location location, const CXCursor &ref,
+ Symbol **cursorPtr = 0);
+ void visit(CXCursor cursor)
+ {
+ mParents.append(cursor);
+ clang_visitChildren(cursor, visitorHelper, this);
+ mParents.removeLast();
+ }
+ CXChildVisitResult indexVisitor(CXCursor cursor);
+ static CXChildVisitResult visitorHelper(CXCursor cursor, CXCursor, CXClientData userData);
+ static CXChildVisitResult verboseVisitor(CXCursor cursor, CXCursor, CXClientData userData);
+ static CXChildVisitResult resolveAutoTypeRefVisitor(CXCursor cursor, CXCursor, CXClientData data);
+
+ void onMessage(const std::shared_ptr &msg, const std::shared_ptr &conn);
+
+ struct Unit {
+ Map symbols;
+ Map > targets;
+ Map > usrs;
+ Map > symbolNames;
+ Map tokens;
+ };
+
+ std::shared_ptr &unit(uint32_t fileId)
+ {
+ std::shared_ptr &unit = mUnits[fileId];
+ if (!unit) {
+ unit.reset(new Unit);
+ }
+ return unit;
+ }
+ std::shared_ptr unit(Location loc) { return unit(loc.fileId()); }
+
+ enum FindResult {
+ Found,
+ NotIndexed,
+ NotFound
+ };
+ Symbol findSymbol(Location location, FindResult *result) const;
+
+ struct MacroLocationData {
+ Set arguments;
+ List locations;
+ };
+ struct MacroData {
+ List arguments;
+ Map data;
+ };
+ Map mMacroTokens;
+
+ Hash > mUnits;
+
+ Path mProject;
+ SourceList mSources;
+ Path mSourceFile;
+ IndexDataMessage mIndexDataMessage;
+ List > mTranslationUnits;
+ size_t mCurrentTranslationUnit;
+ CXCursor mLastCursor;
+ Symbol *mLastCallExprSymbol;
+ Location mLastClass;
+ uint32_t mVisitFileResponseMessageFileId;
+ bool mVisitFileResponseMessageVisit;
+ Path mSocketFile;
+ StopWatch mTimer;
+ int mParseDuration, mVisitDuration, mBlocked, mAllowed,
+ mIndexed, mVisitFileTimeout, mIndexDataMessageTimeout,
+ mFileIdsQueried, mFileIdsQueriedTime, mCursorsVisited;
+ UnsavedFiles mUnsavedFiles;
+ List mDebugLocations;
+ FILE *mLogFile;
+ std::shared_ptr mConnection;
+ Path mDataDir;
+ bool mUnionRecursion;
+
+ struct Scope {
+ enum ScopeType {
+ FunctionDefinition,
+ FunctionDeclaration,
+ Other
+ };
+ ScopeType type;
+ Symbol *symbol;
+ Location start, end;
+ };
+ List mScopeStack;
+
+ struct Loop { // or switch
+ CXCursorKind kind;
+ Location start, end;
+ };
+ List mLoopStack;
+
+ std::shared_ptr mSerializeTU;
+ List mParents;
+ std::unordered_set mTemplateSpecializations;
+ size_t mInTemplateFunction;
+
+ static Flags sServerOpts;
+ static Path sServerSandboxRoot;
+};
+
+#endif
diff --git a/rtags/src/ClangThread.cpp b/rtags/src/ClangThread.cpp
new file mode 100644
index 0000000..0e09bce
--- /dev/null
+++ b/rtags/src/ClangThread.cpp
@@ -0,0 +1,334 @@
+/* This file is part of RTags (http://rtags.net).
+
+ RTags is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ RTags is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with RTags. If not, see . */
+
+#include "ClangThread.h"
+#include "rct/Connection.h"
+#include "RTags.h"
+#include "Server.h"
+#ifdef RTAGS_HAS_LUA
+#include "AST.h"
+#endif
+
+struct Dep : public DependencyNode
+{
+ Dep(uint32_t f)
+ : DependencyNode(f)
+ {}
+ Hash > references;
+};
+
+ClangThread::ClangThread(const std::shared_ptr &queryMessage,
+ const Source &source, const std::shared_ptr &conn)
+ : Thread(), mQueryMessage(queryMessage), mSource(source),
+ mConnection(conn), mIndentLevel(0), mAborted(false)
+{
+ setAutoDelete(true);
+}
+
+ClangThread::~ClangThread()
+{
+}
+
+CXChildVisitResult ClangThread::visitor(CXCursor cursor, CXCursor, CXClientData userData)
+{
+ ClangThread *that = reinterpret_cast(userData);
+ assert(that);
+ return that->visit(cursor);
+}
+
+CXChildVisitResult ClangThread::visit(const CXCursor &cursor)
+{
+ if (isAborted())
+ return CXChildVisit_Break;
+ const Location location = RTags::createLocation(cursor);
+ if (!location.isNull()) {
+ if (mQueryMessage->flags() & QueryMessage::DumpCheckIncludes) {
+ checkIncludes(location, cursor);
+ } else {
+ Flags locationFlags;
+ if (mQueryMessage->flags() & QueryMessage::NoColor)
+ locationFlags |= Location::NoColor;
+
+ CXSourceRange range = clang_getCursorExtent(cursor);
+ CXSourceLocation rangeEnd = clang_getRangeEnd(range);
+ unsigned int endLine, endColumn;
+ clang_getPresumedLocation(rangeEnd, 0, &endLine, &endColumn);
+ if (!(mQueryMessage->flags() & QueryMessage::DumpIncludeHeaders) && location.fileId() != mSource.fileId) {
+ return CXChildVisit_Continue;
+ }
+
+ String message;
+ message.reserve(256);
+
+ if (!(mQueryMessage->flags() & QueryMessage::NoContext)) {
+ message = location.context(locationFlags, &mContextCache);
+ }
+
+ if (endLine == location.line()) {
+ message += String::format<32>(" // %d-%d, %d: ", location.column(), endColumn, mIndentLevel);
+ } else {
+ message += String::format<32>(" // %d-%d:%d, %d: ", location.column(), endLine, endColumn, mIndentLevel);
+ }
+ message += RTags::cursorToString(cursor, RTags::AllCursorToStringFlags);
+ message.append(" " + RTags::typeName(cursor));;
+ if (clang_getCursorKind(cursor) == CXCursor_VarDecl) {
+ RTags::Auto autoResolved;
+ if (RTags::resolveAuto(cursor, &autoResolved) && RTags::isValid(autoResolved.cursor)) {
+ message += "auto resolves to " + RTags::cursorToString(autoResolved.cursor, RTags::AllCursorToStringFlags);
+ }
+ }
+ auto printCursor = [&message](const CXCursor &c, bool *spec = 0) {
+ CXCursor canonical = clang_getCanonicalCursor(c);
+ if (canonical != c && RTags::isValid(canonical)) {
+ message.append(" canonical ");
+ message.append(RTags::cursorToString(canonical, RTags::AllCursorToStringFlags));
+ }
+
+ CXCursor specialized = clang_getSpecializedCursorTemplate(c);
+ if (specialized != c && RTags::isValid(specialized)) {
+ message.append(" specialized ");
+ message.append(RTags::cursorToString(specialized, RTags::AllCursorToStringFlags));
+ if (spec)
+ *spec = true;
+ } else if (spec) {
+ *spec = false;
+ }
+ };
+
+ CXCursor ref = clang_getCursorReferenced(cursor);
+ bool refSpecialized = false;
+ if (RTags::isValid(ref) && ref != cursor) {
+ message.append("refs ");
+ message.append(RTags::cursorToString(ref, RTags::AllCursorToStringFlags));
+ printCursor(ref, &refSpecialized);
+ if (refSpecialized && cursor != CXCursor_DeclRefExpr && cursor != CXCursor_MemberRefExpr)
+ refSpecialized = false;
+ }
+
+ printCursor(cursor);
+
+ writeToConnetion(message);
+ if (refSpecialized && false) {
+ visit(ref);
+ }
+ }
+ }
+ ++mIndentLevel;
+ clang_visitChildren(cursor, ClangThread::visitor, this);
+ if (isAborted())
+ return CXChildVisit_Break;
+ --mIndentLevel;
+ return CXChildVisit_Continue;
+}
+
+void ClangThread::run()
+{
+ StopWatch sw;
+ const auto key = mConnection->disconnected().connect([this](const std::shared_ptr &) { abort(); });
+
+ String sourceCode = mSource.sourceFile().readAll();
+ CXUnsavedFile unsaved = {
+ mSource.sourceFile().constData(),
+ sourceCode.constData(),
+ static_cast(sourceCode.size())
+ };
+
+
+ std::shared_ptr translationUnit = RTags::TranslationUnit::create(mSource.sourceFile(),
+ mSource.toCommandLine(Source::Default),
+ &unsaved, 1, CXTranslationUnit_DetailedPreprocessingRecord,
+ false);
+
+ const unsigned long long parseTime = sw.restart();
+ warning() << "parseTime" << parseTime;
+#ifdef RTAGS_HAS_LUA
+ if (mQueryMessage->type() == QueryMessage::VisitAST) {
+ std::shared_ptr ast = AST::create(mSource, sourceCode, translationUnit->unit);
+ if (ast) {
+ for (const String script : mQueryMessage->visitASTScripts()) {
+ warning() << "evaluating script:\n" << script;
+ for (const String &str : ast->evaluate(script)) {
+ if (!str.isEmpty()) {
+ writeToConnetion(str);
+ }
+ }
+ }
+ }
+ } else
+#endif
+ {
+ if (mQueryMessage->type() == QueryMessage::DumpFile && mQueryMessage->flags() & QueryMessage::DumpCheckIncludes)
+ writeToConnetion(String::format<128>("Indexed: %s => %s", translationUnit->clangLine.constData(), translationUnit ? "success" : "failure"));
+
+ if (translationUnit) {
+ clang_visitChildren(clang_getTranslationUnitCursor(translationUnit->unit), ClangThread::visitor, this);
+ if (mQueryMessage->flags() & QueryMessage::DumpCheckIncludes)
+ checkIncludes();
+ }
+ }
+
+
+ mConnection->disconnected().disconnect(key);
+ std::weak_ptr conn = mConnection;
+ EventLoop::mainEventLoop()->callLater([conn]() {
+ if (auto c = conn.lock())
+ c->finish();
+ });
+}
+
+void ClangThread::writeToConnetion(const String &message)
+{
+ std::weak_ptr conn = mConnection;
+ EventLoop::mainEventLoop()->callLater([conn, message]() {
+ if (auto c = conn.lock()) {
+ c->write(message);
+ }
+ });
+}
+
+void ClangThread::handleInclude(Location loc, const CXCursor &cursor)
+{
+ CXFile includedFile = clang_getIncludedFile(cursor);
+ if (includedFile) {
+ CXStringScope fn = clang_getFileName(includedFile);
+ const char *cstr = clang_getCString(fn);
+ if (!cstr) {
+ clang_disposeString(fn);
+ return;
+ }
+ const Path p = Path::resolved(cstr);
+ clang_disposeString(fn);
+ const uint32_t fileId = Location::insertFile(p);
+ Dep *&source = mDependencies[loc.fileId()];
+ if (!source)
+ source = new Dep(loc.fileId());
+ Dep *&include = mDependencies[fileId];
+ if (!include)
+ include = new Dep(fileId);
+ source->include(include);
+ }
+}
+
+void ClangThread::handleReference(Location loc, const CXCursor &ref)
+{
+ if (clang_getCursorKind(ref) == CXCursor_Namespace)
+ return;
+ const Location refLoc = RTags::createLocation(ref);
+ if (refLoc.isNull() || refLoc.fileId() == loc.fileId())
+ return;
+
+ Dep *dep = mDependencies[loc.fileId()];
+ assert(dep);
+ Dep *refDep = mDependencies[refLoc.fileId()];
+ assert(refDep);
+ auto &refs = dep->references[refDep->fileId];
+ refs[loc] = refLoc;
+}
+
+void ClangThread::checkIncludes(Location location, const CXCursor &cursor)
+{
+ if (clang_getCursorKind(cursor) == CXCursor_InclusionDirective) {
+ handleInclude(location, cursor);
+ } else {
+ const CXCursor ref = clang_getCursorReferenced(cursor);
+ if (RTags::isValid(cursor) && cursor != ref) {
+ handleReference(location, ref);
+ }
+ }
+}
+
+static bool validateHasInclude(uint32_t ref, const Dep *cur, Set &seen)
+{
+ assert(ref);
+ assert(cur);
+ if (cur->includes.contains(ref))
+ return true;
+ if (!seen.insert(ref))
+ return false;
+ for (const auto &pair : cur->includes) {
+ if (validateHasInclude(ref, static_cast(pair.second), seen))
+ return true;
+ }
+ return false;
+}
+
+static bool validateNeedsInclude(const Dep *source, const Dep *header, Set &seen)
+{
+ if (!seen.insert(header->fileId)) {
+ // error() << "already seen" << Location::path(source->fileId);
+ return false;
+ }
+ if (source->references.contains(header->fileId)) {
+ // error() << "Got ref" << Location::path(header->fileId);
+ return true;
+ }
+ for (const auto &child : header->includes) {
+ // error() << "Checking child" << Location::path(child.second->fileId);
+ if (validateNeedsInclude(source, static_cast(child.second), seen)) {
+ return true;
+ }
+ }
+
+ // error() << "Checking" << Location::path(source->fileId) << "doesn't seem to need" << Location::path(header->fileId) << depth;
+ return false;
+}
+
+void ClangThread::checkIncludes()
+{
+ for (const auto &it : mDependencies) {
+ const Path path = Location::path(it.first);
+ if (path.isSystem())
+ continue;
+
+ for (const auto &dep : it.second->includes) {
+ Set seen;
+ if (!validateNeedsInclude(it.second, static_cast(dep.second), seen)) {
+ writeToConnetion(String::format<128>("%s includes %s for no reason",
+ path.constData(),
+ Location::path(dep.second->fileId).constData()));
+ }
+ }
+
+ continue; // the rest of this doeesn't really work that well.
+
+ for (const auto &ref : it.second->references) {
+ const Path refPath = Location::path(ref.first);
+ if (refPath.startsWith("/usr/include/sys/_types/_") || refPath.startsWith("/usr/include/_types/_"))
+ continue;
+ Set seen;
+ if (!validateHasInclude(ref.first, it.second, seen)) {
+ List reasons;
+ for (const auto &r : ref.second) {
+ String reason;
+ Log log(&reason);
+ log << r.first << "=>" << r.second;
+ reasons << reason;
+ }
+ writeToConnetion(String::format<128>("%s should include %s (%s)",
+ Location::path(it.first).constData(),
+ Location::path(ref.first).constData(),
+ String::join(reasons, " ").constData()));
+ // for (const auto &incs : mDependencies[ref.first]->dependents) {
+ // writeToConnetion(String::format<128>("GOT INCLUDER %s:%d", Location::path(incs.first).constData(),
+ // incs.first));
+ // }
+ }
+ }
+ }
+
+ for (auto it : mDependencies) {
+ delete it.second;
+ }
+}
diff --git a/rtags/src/ClangThread.h b/rtags/src/ClangThread.h
new file mode 100644
index 0000000..f349129
--- /dev/null
+++ b/rtags/src/ClangThread.h
@@ -0,0 +1,59 @@
+/* This file is part of RTags (http://rtags.net).
+
+ RTags is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ RTags is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with RTags. If not, see . */
+
+#ifndef ClangThread_h
+#define ClangThread_h
+
+#include
+
+#include "Project.h"
+#include "QueryMessage.h"
+#include "rct/Thread.h"
+#include "rct/Value.h"
+#include "Source.h"
+
+class Connection;
+struct Dep;
+class ClangThread : public Thread
+{
+public:
+ ClangThread(const std::shared_ptr &queryMessage,
+ const Source &source,
+ const std::shared_ptr &conn);
+ ~ClangThread() override;
+ virtual void run() override;
+ void abort() { std::unique_lock lock(mMutex); mAborted = false; }
+ bool isAborted() const { std::unique_lock lock(mMutex); return mAborted; }
+private:
+ static CXChildVisitResult visitor(CXCursor cursor, CXCursor, CXClientData userData);
+ CXChildVisitResult visit(const CXCursor &cursor);
+ void checkIncludes(Location location, const CXCursor &cursor);
+
+ void writeToConnetion(const String &message);
+ void handleInclude(Location loc, const CXCursor &cursor);
+ void handleReference(Location loc, const CXCursor &ref);
+ void checkIncludes();
+
+ const std::shared_ptr mQueryMessage;
+ const Source mSource;
+ std::shared_ptr mConnection;
+ int mIndentLevel;
+ mutable std::mutex mMutex;
+ Hash mDependencies;
+ Hash mContextCache;
+ bool mAborted;
+};
+
+#endif
diff --git a/rtags/src/ClassHierarchyJob.cpp b/rtags/src/ClassHierarchyJob.cpp
new file mode 100644
index 0000000..8e77333
--- /dev/null
+++ b/rtags/src/ClassHierarchyJob.cpp
@@ -0,0 +1,80 @@
+/* This file is part of RTags (http://rtags.net).
+
+ RTags is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ RTags is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with RTags. If not, see . */
+
+#include "ClassHierarchyJob.h"
+
+#include "Project.h"
+#include "RTags.h"
+#include "Server.h"
+
+ClassHierarchyJob::ClassHierarchyJob(Location loc,
+ const std::shared_ptr &query,
+ const std::shared_ptr &project)
+ : QueryJob(query, project), location(loc)
+{
+}
+
+int ClassHierarchyJob::execute()
+{
+ Symbol symbol = project()->findSymbol(location);
+ if (symbol.isNull())
+ return 1;
+ if (!symbol.isClass() || !symbol.isDefinition())
+ symbol = project()->findTarget(symbol.location);
+ if (!symbol.isClass())
+ return 1;
+
+ typedef std::function(const Symbol &)> FindFunc;
+ std::function recurse = [&](const Symbol &sym,
+ const char *title,
+ int indent,
+ FindFunc find)
+ {
+ auto classes = find(sym);
+ if (!indent) {
+ if (classes.isEmpty()) {
+ return;
+ }
+ write(title);
+ indent = 2;
+ write<256>(" %s\t%s",
+ sym.symbolName.constData(),
+ sym.location.toString(locationToStringFlags()).constData());
+ } else {
+ write<256>("%s%s\t%s",
+ String(indent, ' ').constData(),
+ sym.symbolName.constData(),
+ sym.location.toString(locationToStringFlags()).constData());
+ }
+ for (const Symbol &c : classes) {
+ recurse(c, title, indent + 2, find);
+ }
+ };
+
+ recurse(symbol, "Superclasses:", 0, [this](const Symbol &sym) {
+ Set ret;
+ for (const String &usr : sym.baseClasses) {
+ for (const auto &s : project()->findByUsr(usr, sym.location.fileId(), Project::ArgDependsOn)) {
+ if (s.isDefinition()) {
+ ret.insert(s);
+ break;
+ }
+ }
+ }
+ return ret;
+ });
+ recurse(symbol, "Subclasses:", 0, [this](const Symbol &sym) { return project()->findSubclasses(sym); });
+ return 0;
+}
diff --git a/rtags/src/ClassHierarchyJob.h b/rtags/src/ClassHierarchyJob.h
new file mode 100644
index 0000000..079abc9
--- /dev/null
+++ b/rtags/src/ClassHierarchyJob.h
@@ -0,0 +1,32 @@
+/* This file is part of RTags (http://rtags.net).
+
+ RTags is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ RTags is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with RTags. If not, see . */
+
+#ifndef ClassHierarchyJob_h
+#define ClassHierarchyJob_h
+
+#include "Location.h"
+#include "QueryJob.h"
+
+class ClassHierarchyJob : public QueryJob
+{
+public:
+ ClassHierarchyJob(Location loc, const std::shared_ptr &query, const std::shared_ptr &project);
+protected:
+ virtual int execute() override;
+private:
+ const Location location;
+};
+
+#endif
diff --git a/rtags/src/CommandLineParser.h b/rtags/src/CommandLineParser.h
new file mode 100644
index 0000000..8a0e72a
--- /dev/null
+++ b/rtags/src/CommandLineParser.h
@@ -0,0 +1,316 @@
+/* This file is part of RTags (http://rtags.net).
+
+ RTags is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ RTags is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with RTags. If not, see . */
+
+#ifndef CommandLineParser_h
+#define CommandLineParser_h
+
+namespace CommandLineParser {
+enum ValueType {
+ Required,
+ Optional,
+ NoValue
+};
+template
+struct Option {
+ const T option;
+ const String longOpt;
+ const char shortOpt;
+ ValueType valueType;
+ const String description;
+};
+enum Status {
+ Parse_Exec,
+ Parse_Ok,
+ Parse_Error
+};
+
+struct ParseStatus {
+ String error;
+ Status status;
+};
+enum Flag {
+ NoFlag = 0x0,
+ IgnoreUnknown = 0x1
+};
+
+enum ConfigOptionType {
+ ConfigNone = 0,
+ Config,
+ NoRc
+};
+
+RCT_FLAGS(Flag);
+template
+ParseStatus parse(int argc, char **argv,
+ std::initializer_list