introduction.qbk 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. [/==============================================================================
  2. Copyright (C) 2001-2011 Joel de Guzman
  3. Copyright (C) 2001-2011 Hartmut Kaiser
  4. Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. ===============================================================================/]
  7. [section Introduction]
  8. Boost Spirit is an object-oriented, recursive-descent parser and
  9. output generation library for C++. It allows you to write grammars and
  10. format descriptions using a format similar to Extended Backus Naur
  11. Form (EBNF)[footnote [@http://www.cl.cam.ac.uk/%7Emgk25/iso-14977.pdf
  12. ISO-EBNF]] directly in C++. These inline grammar
  13. specifications can mix freely with other C++ code and, thanks to the
  14. generative power of C++ templates, are immediately executable. In
  15. retrospect, conventional compiler-compilers or parser-generators have
  16. to perform an additional translation step from the source EBNF code to
  17. C or C++ code.
  18. The syntax and semantics of the libraries' API directly form domain-specific
  19. embedded languages (DSEL). In fact, Spirit exposes 3 different DSELs to the
  20. user:
  21. * one for creating parser grammars,
  22. * one for the specification of the required tokens to be used for parsing,
  23. * and one for the description of the required output formats.
  24. Since the target input grammars and output formats are written entirely in C++
  25. we do not need any separate tools to compile, preprocess or integrate those
  26. into the build process. __spirit__ allows seamless integration of the parsing
  27. and output generation process with other C++ code. This often allows for
  28. simpler and more efficient code.
  29. Both the created parsers and generators are fully attributed, which allows you
  30. to easily build and handle hierarchical data structures in memory. These data
  31. structures resemble the structure of the input data and can directly be used
  32. to generate arbitrarily-formatted output.
  33. The [link spirit.spiritstructure figure] below depicts the overall structure
  34. of the Boost Spirit library. The library consists of 4 major parts:
  35. * __classic__: This is the almost-unchanged code base taken from the
  36. former Boost Spirit V1.8 distribution. It has been moved into the namespace
  37. boost::spirit::classic. A special compatibility layer has been added to
  38. ensure complete compatibility with existing code using Spirit V1.8.
  39. * __qi__: This is the parser library allowing you to build recursive
  40. descent parsers. The exposed domain-specific language can be used to describe
  41. the grammars to implement, and the rules for storing the parsed information.
  42. * __lex__: This is the library usable to create tokenizers (lexers). The
  43. domain-specific language exposed by __lex__ allows you to define regular
  44. expressions used to match tokens (create token definitions), associate these
  45. regular expressions with code to be executed whenever they are matched, and
  46. to add the token definitions to the lexical analyzer.
  47. * __karma__: This is the generator library allowing you to create code for
  48. recursive descent, data type-driven output formatting. The exposed
  49. domain-specific language is almost equivalent to the parser description language
  50. used in __qi__, except that it is used to describe the required output
  51. format to generate from a given data structure.
  52. [fig spiritstructure.png..The overall structure of the Boost Spirit library..spirit.spiritstructure]
  53. The three components, __qi__, __karma__ and __lex__, are designed to be used
  54. either stand alone, or together. The general methodology is to use the token
  55. sequence generated by __lex__ as the input for a parser generated by __qi__.
  56. On the opposite side of the equation, the hierarchical data structures generated
  57. by __qi__ are used for the output generators created using __karma__.
  58. However, there is nothing to stop you from using any of these components all
  59. by themselves.
  60. The [link spirit.spiritkarmaflow figure] below shows the typical data flow of
  61. some input being converted to some internal representation. After some
  62. (optional) transformation these data are converted back into some different,
  63. external representation. The picture highlights Spirit's place in this data
  64. transformation flow.
  65. [fig spiritkarmaflow.png..The place of __qi__ and __karma__ in a data transformation flow of a typical application..spirit.spiritkarmaflow]
  66. [heading A Quick Overview of Parsing with __qi__]
  67. __qi__ is Spirit's sublibrary dealing with generating parsers based on a given
  68. target grammar (essentially a format description of the input data to read).
  69. A simple EBNF grammar snippet:
  70. group ::= '(' expression ')'
  71. factor ::= integer | group
  72. term ::= factor (('*' factor) | ('/' factor))*
  73. expression ::= term (('+' term) | ('-' term))*
  74. is approximated using facilities of Spirit's /Qi/ sublibrary as seen in this
  75. code snippet:
  76. group = '(' >> expression >> ')';
  77. factor = integer | group;
  78. term = factor >> *(('*' >> factor) | ('/' >> factor));
  79. expression = term >> *(('+' >> term) | ('-' >> term));
  80. Through the magic of expression templates, this is perfectly valid and
  81. executable C++ code. The production rule `expression` is, in fact, an object that
  82. has a member function `parse` that does the work given a source code written in
  83. the grammar that we have just declared. Yes, it's a calculator. We shall
  84. simplify for now by skipping the type declarations and the definition of the
  85. rule `integer` invoked by `factor`. Now, the production rule `expression` in our
  86. grammar specification, traditionally called the `start` symbol, can recognize
  87. inputs such as:
  88. 12345
  89. -12345
  90. +12345
  91. 1 + 2
  92. 1 * 2
  93. 1/2 + 3/4
  94. 1 + 2 + 3 + 4
  95. 1 * 2 * 3 * 4
  96. (1 + 2) * (3 + 4)
  97. (-1 + 2) * (3 + -4)
  98. 1 + ((6 * 200) - 20) / 6
  99. (1 + (2 + (3 + (4 + 5))))
  100. Certainly we have modified the original EBNF syntax. This is done to
  101. conform to C++ syntax rules. Most notably we see the abundance of
  102. shift >> operators. Since there are no 'empty' operators in C++, it is
  103. simply not possible to write something like:
  104. a b
  105. as seen in math syntax, for example, to mean multiplication or, in our case,
  106. as seen in EBNF syntax to mean sequencing (b should follow a). __qi__
  107. uses the shift `>>` operator instead for this purpose. We take the `>>` operator,
  108. with arrows pointing to the right, to mean "is followed by". Thus we write:
  109. a >> b
  110. The alternative operator `|` and the parentheses `()` remain as is. The
  111. assignment operator `=` is used in place of EBNF's `::=`. Last but not least,
  112. the Kleene star `*`, which in this case is a postfix operator in EBNF becomes a
  113. prefix. Instead of:
  114. a* //... in EBNF syntax,
  115. we write:
  116. *a //... in Spirit.
  117. since there are no postfix stars, `*`, in C/C++. Finally, we terminate each
  118. rule with the ubiquitous semi-colon, `;`.
  119. [heading A Quick Overview of Output Generation with __karma__]
  120. Spirit not only allows you to describe the structure of the input, it also enables
  121. the specification of the output format for your data in a similar way, and based
  122. on a single syntax and compatible semantics.
  123. Let's assume we need to generate a textual representation from a simple data
  124. structure such as a `std::vector<int>`. Conventional code probably would look like:
  125. std::vector<int> v (initialize_and_fill());
  126. std::vector<int>::iterator end = v.end();
  127. for (std::vector<int>::iterator it = v.begin(); it != end; ++it)
  128. std::cout << *it << std::endl;
  129. which is not very flexible and quite difficult to maintain when it comes to
  130. changing the required output format. Spirit's sublibrary /Karma/ allows you to
  131. specify output formats for arbitrary data structures in a very flexible way.
  132. The following snippet is the /Karma/ format description used to create the
  133. same output as the traditional code above:
  134. *(int_ << eol)
  135. Here are some more examples of format descriptions for different output
  136. representations of the same `std::vector<int>`:
  137. [table Different output formats for `std::vector<int>`
  138. [ [Format] [Example] [Description] ]
  139. [ [`'[' << *(int_ << ',') << ']'`] [`[1,8,10,]`] [Comma separated list of integers] ]
  140. [ [`*('(' << int_ << ')' << ',')`] [`(1),(8),(10),`] [Comma separated list of integers in parenthesis] ]
  141. [ [`*hex`] [`18a`] [A list of hexadecimal numbers] ]
  142. [ [`*(double_ << ',')`] [`1.0,8.0,10.0,`] [A list of floating point numbers] ]
  143. ]
  144. We will see later in this documentation how it is possible to avoid printing
  145. the trailing `','`.
  146. Overall, the syntax is similar to __qi__ with the exception that we use the `<<`
  147. operator for output concatenation. This should be easy to understand as it
  148. follows the conventions used in the Standard's I/O streams.
  149. Another important feature of __karma__ allows you to fully decouple the data
  150. type from the output format. You can use the same output format with different
  151. data types as long as these conform conceptually. The next table gives some
  152. related examples.
  153. [table Different data types usable with the output format `*(int_ << eol)`
  154. [ [Data type] [Description] ]
  155. [ [`int i[4]`] [C style arrays] ]
  156. [ [`std::vector<int>`] [Standard vector] ]
  157. [ [`std::list<int>`] [Standard list] ]
  158. [ [`boost::array<long, 20>`] [Boost array] ]
  159. ]
  160. [endsect]