tokenizer.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc. All rights reserved.
  3. // https://developers.google.com/protocol-buffers/
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are
  7. // met:
  8. //
  9. // * Redistributions of source code must retain the above copyright
  10. // notice, this list of conditions and the following disclaimer.
  11. // * Redistributions in binary form must reproduce the above
  12. // copyright notice, this list of conditions and the following disclaimer
  13. // in the documentation and/or other materials provided with the
  14. // distribution.
  15. // * Neither the name of Google Inc. nor the names of its
  16. // contributors may be used to endorse or promote products derived from
  17. // this software without specific prior written permission.
  18. //
  19. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. // Author: kenton@google.com (Kenton Varda)
  31. // Based on original Protocol Buffers design by
  32. // Sanjay Ghemawat, Jeff Dean, and others.
  33. //
  34. // Class for parsing tokenized text from a ZeroCopyInputStream.
  35. #ifndef GOOGLE_PROTOBUF_IO_TOKENIZER_H__
  36. #define GOOGLE_PROTOBUF_IO_TOKENIZER_H__
  37. #include <string>
  38. #include <vector>
  39. #include <google/protobuf/stubs/common.h>
  40. #include <google/protobuf/stubs/logging.h>
  41. #include <google/protobuf/port_def.inc>
  42. namespace google {
  43. namespace protobuf {
  44. namespace io {
  45. class ZeroCopyInputStream; // zero_copy_stream.h
  46. // Defined in this file.
  47. class ErrorCollector;
  48. class Tokenizer;
  49. // By "column number", the proto compiler refers to a count of the number
  50. // of bytes before a given byte, except that a tab character advances to
  51. // the next multiple of 8 bytes. Note in particular that column numbers
  52. // are zero-based, while many user interfaces use one-based column numbers.
  53. typedef int ColumnNumber;
  54. // Abstract interface for an object which collects the errors that occur
  55. // during parsing. A typical implementation might simply print the errors
  56. // to stdout.
  57. class PROTOBUF_EXPORT ErrorCollector {
  58. public:
  59. inline ErrorCollector() {}
  60. virtual ~ErrorCollector();
  61. // Indicates that there was an error in the input at the given line and
  62. // column numbers. The numbers are zero-based, so you may want to add
  63. // 1 to each before printing them.
  64. virtual void AddError(int line, ColumnNumber column,
  65. const std::string& message) = 0;
  66. // Indicates that there was a warning in the input at the given line and
  67. // column numbers. The numbers are zero-based, so you may want to add
  68. // 1 to each before printing them.
  69. virtual void AddWarning(int /* line */, ColumnNumber /* column */,
  70. const std::string& /* message */) {}
  71. private:
  72. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ErrorCollector);
  73. };
  74. // This class converts a stream of raw text into a stream of tokens for
  75. // the protocol definition parser to parse. The tokens recognized are
  76. // similar to those that make up the C language; see the TokenType enum for
  77. // precise descriptions. Whitespace and comments are skipped. By default,
  78. // C- and C++-style comments are recognized, but other styles can be used by
  79. // calling set_comment_style().
  80. class PROTOBUF_EXPORT Tokenizer {
  81. public:
  82. // Construct a Tokenizer that reads and tokenizes text from the given
  83. // input stream and writes errors to the given error_collector.
  84. // The caller keeps ownership of input and error_collector.
  85. Tokenizer(ZeroCopyInputStream* input, ErrorCollector* error_collector);
  86. ~Tokenizer();
  87. enum TokenType {
  88. TYPE_START, // Next() has not yet been called.
  89. TYPE_END, // End of input reached. "text" is empty.
  90. TYPE_IDENTIFIER, // A sequence of letters, digits, and underscores, not
  91. // starting with a digit. It is an error for a number
  92. // to be followed by an identifier with no space in
  93. // between.
  94. TYPE_INTEGER, // A sequence of digits representing an integer. Normally
  95. // the digits are decimal, but a prefix of "0x" indicates
  96. // a hex number and a leading zero indicates octal, just
  97. // like with C numeric literals. A leading negative sign
  98. // is NOT included in the token; it's up to the parser to
  99. // interpret the unary minus operator on its own.
  100. TYPE_FLOAT, // A floating point literal, with a fractional part and/or
  101. // an exponent. Always in decimal. Again, never
  102. // negative.
  103. TYPE_STRING, // A quoted sequence of escaped characters. Either single
  104. // or double quotes can be used, but they must match.
  105. // A string literal cannot cross a line break.
  106. TYPE_SYMBOL, // Any other printable character, like '!' or '+'.
  107. // Symbols are always a single character, so "!+$%" is
  108. // four tokens.
  109. };
  110. // Structure representing a token read from the token stream.
  111. struct Token {
  112. TokenType type;
  113. std::string text; // The exact text of the token as it appeared in
  114. // the input. e.g. tokens of TYPE_STRING will still
  115. // be escaped and in quotes.
  116. // "line" and "column" specify the position of the first character of
  117. // the token within the input stream. They are zero-based.
  118. int line;
  119. ColumnNumber column;
  120. ColumnNumber end_column;
  121. };
  122. // Get the current token. This is updated when Next() is called. Before
  123. // the first call to Next(), current() has type TYPE_START and no contents.
  124. const Token& current();
  125. // Return the previous token -- i.e. what current() returned before the
  126. // previous call to Next().
  127. const Token& previous();
  128. // Advance to the next token. Returns false if the end of the input is
  129. // reached.
  130. bool Next();
  131. // Like Next(), but also collects comments which appear between the previous
  132. // and next tokens.
  133. //
  134. // Comments which appear to be attached to the previous token are stored
  135. // in *prev_tailing_comments. Comments which appear to be attached to the
  136. // next token are stored in *next_leading_comments. Comments appearing in
  137. // between which do not appear to be attached to either will be added to
  138. // detached_comments. Any of these parameters can be NULL to simply discard
  139. // the comments.
  140. //
  141. // A series of line comments appearing on consecutive lines, with no other
  142. // tokens appearing on those lines, will be treated as a single comment.
  143. //
  144. // Only the comment content is returned; comment markers (e.g. //) are
  145. // stripped out. For block comments, leading whitespace and an asterisk will
  146. // be stripped from the beginning of each line other than the first. Newlines
  147. // are included in the output.
  148. //
  149. // Examples:
  150. //
  151. // optional int32 foo = 1; // Comment attached to foo.
  152. // // Comment attached to bar.
  153. // optional int32 bar = 2;
  154. //
  155. // optional string baz = 3;
  156. // // Comment attached to baz.
  157. // // Another line attached to baz.
  158. //
  159. // // Comment attached to qux.
  160. // //
  161. // // Another line attached to qux.
  162. // optional double qux = 4;
  163. //
  164. // // Detached comment. This is not attached to qux or corge
  165. // // because there are blank lines separating it from both.
  166. //
  167. // optional string corge = 5;
  168. // /* Block comment attached
  169. // * to corge. Leading asterisks
  170. // * will be removed. */
  171. // /* Block comment attached to
  172. // * grault. */
  173. // optional int32 grault = 6;
  174. bool NextWithComments(std::string* prev_trailing_comments,
  175. std::vector<std::string>* detached_comments,
  176. std::string* next_leading_comments);
  177. // Parse helpers ---------------------------------------------------
  178. // Parses a TYPE_FLOAT token. This never fails, so long as the text actually
  179. // comes from a TYPE_FLOAT token parsed by Tokenizer. If it doesn't, the
  180. // result is undefined (possibly an assert failure).
  181. static double ParseFloat(const std::string& text);
  182. // Parses a TYPE_STRING token. This never fails, so long as the text actually
  183. // comes from a TYPE_STRING token parsed by Tokenizer. If it doesn't, the
  184. // result is undefined (possibly an assert failure).
  185. static void ParseString(const std::string& text, std::string* output);
  186. // Identical to ParseString, but appends to output.
  187. static void ParseStringAppend(const std::string& text, std::string* output);
  188. // Parses a TYPE_INTEGER token. Returns false if the result would be
  189. // greater than max_value. Otherwise, returns true and sets *output to the
  190. // result. If the text is not from a Token of type TYPE_INTEGER originally
  191. // parsed by a Tokenizer, the result is undefined (possibly an assert
  192. // failure).
  193. static bool ParseInteger(const std::string& text, uint64_t max_value,
  194. uint64_t* output);
  195. // Options ---------------------------------------------------------
  196. // Set true to allow floats to be suffixed with the letter 'f'. Tokens
  197. // which would otherwise be integers but which have the 'f' suffix will be
  198. // forced to be interpreted as floats. For all other purposes, the 'f' is
  199. // ignored.
  200. void set_allow_f_after_float(bool value) { allow_f_after_float_ = value; }
  201. // Valid values for set_comment_style().
  202. enum CommentStyle {
  203. // Line comments begin with "//", block comments are delimited by "/*" and
  204. // "*/".
  205. CPP_COMMENT_STYLE,
  206. // Line comments begin with "#". No way to write block comments.
  207. SH_COMMENT_STYLE
  208. };
  209. // Sets the comment style.
  210. void set_comment_style(CommentStyle style) { comment_style_ = style; }
  211. // Whether to require whitespace between a number and a field name.
  212. // Default is true. Do not use this; for Google-internal cleanup only.
  213. void set_require_space_after_number(bool require) {
  214. require_space_after_number_ = require;
  215. }
  216. // Whether to allow string literals to span multiple lines. Default is false.
  217. // Do not use this; for Google-internal cleanup only.
  218. void set_allow_multiline_strings(bool allow) {
  219. allow_multiline_strings_ = allow;
  220. }
  221. // External helper: validate an identifier.
  222. static bool IsIdentifier(const std::string& text);
  223. // -----------------------------------------------------------------
  224. private:
  225. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Tokenizer);
  226. Token current_; // Returned by current().
  227. Token previous_; // Returned by previous().
  228. ZeroCopyInputStream* input_;
  229. ErrorCollector* error_collector_;
  230. char current_char_; // == buffer_[buffer_pos_], updated by NextChar().
  231. const char* buffer_; // Current buffer returned from input_.
  232. int buffer_size_; // Size of buffer_.
  233. int buffer_pos_; // Current position within the buffer.
  234. bool read_error_; // Did we previously encounter a read error?
  235. // Line and column number of current_char_ within the whole input stream.
  236. int line_;
  237. ColumnNumber column_;
  238. // String to which text should be appended as we advance through it.
  239. // Call RecordTo(&str) to start recording and StopRecording() to stop.
  240. // E.g. StartToken() calls RecordTo(&current_.text). record_start_ is the
  241. // position within the current buffer where recording started.
  242. std::string* record_target_;
  243. int record_start_;
  244. // Options.
  245. bool allow_f_after_float_;
  246. CommentStyle comment_style_;
  247. bool require_space_after_number_;
  248. bool allow_multiline_strings_;
  249. // Since we count columns we need to interpret tabs somehow. We'll take
  250. // the standard 8-character definition for lack of any way to do better.
  251. // This must match the documentation of ColumnNumber.
  252. static const int kTabWidth = 8;
  253. // -----------------------------------------------------------------
  254. // Helper methods.
  255. // Consume this character and advance to the next one.
  256. void NextChar();
  257. // Read a new buffer from the input.
  258. void Refresh();
  259. inline void RecordTo(std::string* target);
  260. inline void StopRecording();
  261. // Called when the current character is the first character of a new
  262. // token (not including whitespace or comments).
  263. inline void StartToken();
  264. // Called when the current character is the first character after the
  265. // end of the last token. After this returns, current_.text will
  266. // contain all text consumed since StartToken() was called.
  267. inline void EndToken();
  268. // Convenience method to add an error at the current line and column.
  269. void AddError(const std::string& message) {
  270. error_collector_->AddError(line_, column_, message);
  271. }
  272. // -----------------------------------------------------------------
  273. // The following four methods are used to consume tokens of specific
  274. // types. They are actually used to consume all characters *after*
  275. // the first, since the calling function consumes the first character
  276. // in order to decide what kind of token is being read.
  277. // Read and consume a string, ending when the given delimiter is
  278. // consumed.
  279. void ConsumeString(char delimiter);
  280. // Read and consume a number, returning TYPE_FLOAT or TYPE_INTEGER
  281. // depending on what was read. This needs to know if the first
  282. // character was a zero in order to correctly recognize hex and octal
  283. // numbers.
  284. // It also needs to know if the first character was a . to parse floating
  285. // point correctly.
  286. TokenType ConsumeNumber(bool started_with_zero, bool started_with_dot);
  287. // Consume the rest of a line.
  288. void ConsumeLineComment(std::string* content);
  289. // Consume until "*/".
  290. void ConsumeBlockComment(std::string* content);
  291. enum NextCommentStatus {
  292. // Started a line comment.
  293. LINE_COMMENT,
  294. // Started a block comment.
  295. BLOCK_COMMENT,
  296. // Consumed a slash, then realized it wasn't a comment. current_ has
  297. // been filled in with a slash token. The caller should return it.
  298. SLASH_NOT_COMMENT,
  299. // We do not appear to be starting a comment here.
  300. NO_COMMENT
  301. };
  302. // If we're at the start of a new comment, consume it and return what kind
  303. // of comment it is.
  304. NextCommentStatus TryConsumeCommentStart();
  305. // -----------------------------------------------------------------
  306. // These helper methods make the parsing code more readable. The
  307. // "character classes" referred to are defined at the top of the .cc file.
  308. // Basically it is a C++ class with one method:
  309. // static bool InClass(char c);
  310. // The method returns true if c is a member of this "class", like "Letter"
  311. // or "Digit".
  312. // Returns true if the current character is of the given character
  313. // class, but does not consume anything.
  314. template <typename CharacterClass>
  315. inline bool LookingAt();
  316. // If the current character is in the given class, consume it and return
  317. // true. Otherwise return false.
  318. // e.g. TryConsumeOne<Letter>()
  319. template <typename CharacterClass>
  320. inline bool TryConsumeOne();
  321. // Like above, but try to consume the specific character indicated.
  322. inline bool TryConsume(char c);
  323. // Consume zero or more of the given character class.
  324. template <typename CharacterClass>
  325. inline void ConsumeZeroOrMore();
  326. // Consume one or more of the given character class or log the given
  327. // error message.
  328. // e.g. ConsumeOneOrMore<Digit>("Expected digits.");
  329. template <typename CharacterClass>
  330. inline void ConsumeOneOrMore(const char* error);
  331. };
  332. // inline methods ====================================================
  333. inline const Tokenizer::Token& Tokenizer::current() { return current_; }
  334. inline const Tokenizer::Token& Tokenizer::previous() { return previous_; }
  335. inline void Tokenizer::ParseString(const std::string& text,
  336. std::string* output) {
  337. output->clear();
  338. ParseStringAppend(text, output);
  339. }
  340. } // namespace io
  341. } // namespace protobuf
  342. } // namespace google
  343. #include <google/protobuf/port_undef.inc>
  344. #endif // GOOGLE_PROTOBUF_IO_TOKENIZER_H__