![]() |
![]() ![]() ![]() ![]() ![]() |
![]() |
SamplesBoost , ,
The Wave library contains several samples illustrating how to use the different features. This section describes these samples and its main characteristics. The quick_start sampleОбразец quick_start показывает минимальный способ использования препроцессорной библиотеки Wave. Он просто открывает файл, данный в качестве первого аргумента командной строки, предварительно обрабатывает его, предполагая, что нет никаких дополнительных путей или макро определений, и выводит текстовое представление токенов, генерируемых из данного входного файла. Этот образец может быть использован для введения в Wave, поскольку он не содержит всей потенциальной дополнительной сложности, выявленной более сложными образцами. The lexed_tokens sampleОбразец lexed_tokens показывает минимальный способ использования лексирующего компонента C++ Wave без использования препроцессора. Он открывает файл, указанный в качестве первого аргумента командной строки, и распечатывает содержимое токенов, возвращенных из лексера. The cpp_tokens sampleThe cpp_tokens sample dumps out the information contained within the tokens returned from the iterator supplied by the Wave library. It shows, how to use the Wave library in conjunction with custom lexer and custom token types. The lexer used within this sample is SLex [5] based, i.e. it is feeded during runtime (at startup) with the token definitions (regular expressions) and generates a resulting DFA table. This table is used for token identification and is saved to disc afterwards to avoid the table generation process at the next program startup. The name of the file to which the DFA table is saved is wave_slex_lexer.dfa. The main advantage of this SLex based lexer if compared to the default Re2C [3] generated lexer is, that it provides not only the line information, where a particular token was recognized, but also the related column position. Otherwise the SLex based lexer is functionally fully compatible to the Re2C based one, i.e. you always may switch your application to use it, if you additionally need to get the column information back from the preprocessing. Since no additional command line parameters are supported by this sample, it won't work well with include files, which aren't located in the same directory as the inspected input file. The command line syntax is straight forward: cpp_tokens input_file The list_includes sampleThe list_includes sample shows how the Wave library may be used to generate a include file dependency list for a particular input file. It completely depends on the default library configuration. The command line syntax for this sample is given below: Usage: list_includes [options] file ...: -h [ --help ] : print out program usage (this message) -v [ --version ] : print the version number -I [ --path ] dir : specify additional include directory -S [ --syspath ] dir : specify additional system include directory Please note though, that this sample will output only those include file names, which are visible to the preprocessor, i.e. given the following code snippet, only one of the two include file directives is triggered during preprocessing and for this reason only the corresponding file name is reported by the list_includes sample: #if defined(INCLUDE_FILE_A) # include "file_a.h" #else # include "file_b.h" #endif The advanced_hooks sampleThe advanced_hooks sample is based on the quick_start sample mentioned above. It shows how you may want to use the advanced preprocessing hooks of the Wave library to get in the output not only the preprocessed tokens from the evaluated conditional blocks, but also the tokens recognized inside the non-evaluated conditional blocks. To make the generated token stream useful for further processing the tokens from the non-evaluated conditional blocks are commented out. Here is a small sample what the advanced_hooks sample does. Consider the following input: #define TEST 1 #if defined(TEST) "TEST was defined: " TEST #else "TEST was not defined!" #endif которые будут производиться как его продукция: //"#if defined(TEST) "TEST was defined: " 1 //"#else //"TEST was not defined!" //"#endif As you can see, the sample application prints out the conditional directives in a commented out manner as well. The wave sampleBecause of its general usefulness the wave sample is not located in the sample directory of the library, but inside the tools directory of Boost. The wave sample is usable as a full fledged preprocessor executable on top of any other C++ compiler. It outputs the textual representation of the preprocessed tokens generated from a given input file. It is described in more details here. The waveidl sampleThe main point of the waveidl sample is to show, how a completely independent lexer type may be used in conjunction with the default token type of the Wave library. The lexer used in this sample is supposed to be used for an IDL language based preprocessor. It is based on the Re2C tool too, but recognizes a different set of tokens as the default C++ lexer contained within the Wave library. So this lexer does not recognize any keywords (except true and false, which are needed by the preprocessor itself). This is needed because there exist different IDL languages, where identifiers of one language may be keywords of others. Certainly this implies to postpone keyword identification after the preprocessing, but allows to use Wave for all of the IDL derivatives. It is only possible to use the Wave library to write an IDL preprocessor, because the token sets for both languages are very similar. The tokens to be recognized by the waveidl IDL language preprocessor is nearly a complete subset of the full C++ token set. The command line syntax usable for this sample is shown below: Usage: waveidl [options] [@config-file(s)] file: Options allowed on the command line only: -h [ --help ] : print out program usage (this message) -v [ --version ] : print the version number -c [ --copyright ] : print out the copyright statement --config-file filepath : specify a config file (alternatively: @filepath) Options allowed additionally in a config file: -o [ --output ] path : specify a file to use for output instead of stdout -I [ --include ] path : specify an additional include directory -S [ --sysinclude ] syspath : specify an additional system include directory -D [ --define ] macro[=[value]] : specify a macro to define -P [ --predefine ] macro[=[value]] : specify a macro to predefine -U [ --undefine ] macro : specify a macro to undefine The hannibal sampleОбразец hannibal показывает, как основывать грамматику духа на библиотеке Wave. Первоначально он был написан и внес вклад в библиотеку Wave Дэнни Хавенита (см. его связанную веб-страницу здесь ). Грамматика этого примера использует Wave в качестве препроцессора. Он реализует около 120 из примерно 250 правил грамматики, как они могут быть найдены в Язык программирования C++, третье издание . Правила 120 позволяют анализировать исходный файл C++ для всех типов информации и деклараций. На самом деле эта грамматика анализирует так же хорошо, как и все остальное, она анализирует объявления C++, включая определения классов и шаблонов, но пропускает функциональные тела. Если так настроено, программа выведет xml-свалку сгенерированного дерева. Это может быть хорошей отправной точкой для грамматики, которая может использоваться для таких вещей, как реверс-инжиниринг, как это делают некоторые инструменты моделирования UML. Или все, что вы можете найти для грамматики, которая дает вам список всех шаблонов и классов в файле и их членов.
Copyright © 2003-2011 Hartmut Kaiser Last updated: Wednesday, June 21, 2006 22:12
Статья Samples раздела может быть полезна для разработчиков на c++ и boost. Материалы статей собраны из открытых источников, владелец сайта не претендует на авторство. Там где авторство установить не удалось, материал подаётся без имени автора. В случае если Вы считаете, что Ваши права нарушены, пожалуйста, свяжитесь с владельцем сайта. :: Главная :: ::
|
|||||||||||||||
©KANSoftWare (разработка программного обеспечения, создание программ, создание интерактивных сайтов), 2007 |