fccf
— это инструмент командной строки, который быстро выполняет поиск в исходном коде C/C++ в каталоге на основе строки поиска и печатает соответствующие фрагменты кода, соответствующие запросу.
В следующем видео показан поиск fccf
и фрагментов кода в torvalds/linux.
fccf
(современный C++) В следующем видео показан поиск fccf
в исходном коде fccf
C++.
Обратите внимание, что результаты поиска здесь включают:
--flag
который соответствует Предоставьте пустой запрос для соответствия любому --flag
, например, любому объявлению перечисления.
... или любой конструктор класса
for
Используйте --for-statement
для for
операторов. fccf
попытается найти for
(включая C++, расположенные for
), содержащие строку запроса.
Используйте опцию --include-expressions
чтобы найти выражения, соответствующие запросу.
В следующем примере показаны вызовы fccf
find для isdigit()
.
В следующем примере показано, как fccf
находит ссылки на переменную clang_options
.
using
объявлений Используйте опцию --using-declaration
, чтобы найти объявления using
, директивы using
и объявления псевдонимов типов.
namespace
Используйте опцию --namespace-alias
, чтобы найти псевдонимы namespace
.
throw
Используйте --throw-expression
с запросом для поиска конкретных выражений throw
содержащих строку запроса.
Как было показано ранее, пустой запрос попытается сопоставить любое выражение throw
в базе кода:
Создайте fccf
с помощью CMake. Более подробную информацию можно найти на сайте BUILDING.md.
ПРИМЕЧАНИЕ. fccf
необходимы установленные libclang
и LLVM
.
# Install libclang and LLVM
# sudo apt install libclang-dev llvm
git clone https://github.com/p-ranav/fccf
cd fccf
# Build
cmake -S . -B build -D CMAKE_BUILD_TYPE=Release
cmake --build build
# Install
sudo cmake --install build
fccf
foo@bar:~ $ fccf --help
Usage: fccf [--help] [--version] [--help] [--exact-match] [--json] [--filter VAR] [-j VAR] [--enum] [--struct] [--union] [--member-function] [--function] [--function-template] [-F] [--class] [--class-template] [--class-constructor] [--class-destructor] [-C] [--for-statement] [--namespace-alias] [--parameter-declaration] [--typedef] [--using-declaration] [--variable-declaration] [--verbose] [--include-expressions] [--static-cast] [--dynamic-cast] [--reinterpret-cast] [--const-cast] [-c] [--throw-expression] [--ignore-single-line-results] [--include-dir VAR]... [--language VAR] [--std VAR] [--no-color] query [path]...
Positional arguments:
query
path [nargs: 0 or more]
Optional arguments:
-h, --help shows help message and exits
-v, --version prints version information and exits
-h, --help Shows help message and exits
-E, --exact-match Only consider exact matches
--json Print results in JSON format
-f, --filter Only evaluate files that match filter pattern [nargs=0..1] [default: "*.*"]
-j Number of threads [nargs=0..1] [default: 5]
--enum Search for enum declaration
--struct Search for struct declaration
--union Search for union declaration
--member-function Search for class member function declaration
--function Search for function declaration
--function-template Search for function template declaration
-F Search for any function or function template or class member function
--class Search for class declaration
--class-template Search for class template declaration
--class-constructor Search for class constructor declaration
--class-destructor Search for class destructor declaration
-C Search for any class or class template or struct
--for-statement Search for `for` statement
--namespace-alias Search for namespace alias
--parameter-declaration Search for function or method parameter
--typedef Search for typedef declaration
--using-declaration Search for using declarations, using directives, and type alias declarations
--variable-declaration Search for variable declaration
--verbose Request verbose output
--ie, --include-expressions Search for expressions that refer to some value or member, e.g., function, variable, or enumerator.
--static-cast Search for static_cast
--dynamic-cast Search for dynamic_cast
--reinterpret-cast Search for reinterpret_cast
--const-cast Search for const_cast
-c Search for any static_cast, dynamic_cast, reinterpret_cast, orconst_cast expression
--throw-expression Search for throw expression
--isl, --ignore-single-line-results Ignore forward declarations, member function declarations, etc.
-I, --include-dir Additional include directories [nargs=0..1] [default: {}] [may be repeated]
-l, --language Language option used by clang [nargs=0..1] [default: "c++"]
--std C++ standard to be used by clang [nargs=0..1] [default: "c++17"]
--nc, --no-color Stops fccf from coloring the output
fccf
выполняет рекурсивный поиск в каталоге иголки в стоге сена — например, grep
или ripgrep
— он использует алгоритм SSE2
strstr
SIMD (модифицированный поиск SIMD Рабина-Карпа; см. здесь), если это возможно, чтобы быстро найти в нескольких потоках подмножество исходные файлы в каталоге, содержащем иглу.libclang
для анализа единицы перевода (построения абстрактного синтаксического дерева).CXCursor_FunctionDecl
для объявлений функций.libclang
) соответствует поисковому запросу, тогда определяется исходный диапазон узла AST. Исходный диапазон — это начальный и конечный индекс фрагмента кода в буферinclude_directories
Чтобы все это работало, fccf сначала идентифицирует каталоги-кандидаты, содержащие файлы заголовков, например пути, заканчивающиеся на include/
. Затем он добавляет эти пути к параметрам clang (перед анализом единицы перевода) как -Ifoo -Ibar/baz
и т. д. Кроме того, для каждой единицы перевода родительский и родительский пути также добавляются в каталоги включения для этой единицы, чтобы увеличить вероятность успешного разбора.
Дополнительные каталоги включения также могут быть предоставлены fccf
с помощью опции -I
или --include-dir
. Используя подробный вывод ( --verbose
), можно выявить ошибки в анализе libclang и попытаться их исправить (например, добавив правильные каталоги включения, чтобы libclang
работал нормально).
Чтобы запустить fccf
в исходном коде fccf
без каких-либо ошибок libclang, мне пришлось явно указать путь включения из LLVM-12, например:
foo@bar:~ $ fccf --verbose ' lexer ' . --include-dir /usr/lib/llvm-12/include/
Checking ./source/lexer.cpp
Checking ./source/lexer.hpp
Checking ./source/searcher.cpp
// ./source/lexer.hpp (Line: 14 to 40)
class lexer
{
std::string_view m_input;
fmt::memory_buffer* m_out;
std::size_t m_index {0};
bool m_is_stdout {true};
char previous() const;
char current() const;
char next() const;
void move_forward(std::size_t n = 1);
bool is_line_comment();
bool is_block_comment();
bool is_start_of_identifier();
bool is_start_of_string();
bool is_start_of_number();
void process_line_comment();
void process_block_comment();
bool process_identifier(bool maybe_class_or_struct = false);
void process_string();
std::size_t get_number_of_characters(std::string_view str);
public:
void tokenize_and_pretty_print(std::string_view source,
fmt::memory_buffer* out,
bool is_stdout = true);
}