tokenizer.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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. TYPE_WHITESPACE, // A sequence of whitespace. This token type is only
  110. // produced if report_whitespace() is true. It is not
  111. // reported for whitespace within comments or strings.
  112. TYPE_NEWLINE, // A newline (\n). This token type is only
  113. // produced if report_whitespace() is true and
  114. // report_newlines() is true. It is not reported for
  115. // newlines in comments or strings.
  116. };
  117. // Structure representing a token read from the token stream.
  118. struct Token {
  119. TokenType type;
  120. std::string text; // The exact text of the token as it appeared in
  121. // the input. e.g. tokens of TYPE_STRING will still
  122. // be escaped and in quotes.
  123. // "line" and "column" specify the position of the first character of
  124. // the token within the input stream. They are zero-based.
  125. int line;
  126. ColumnNumber column;
  127. ColumnNumber end_column;
  128. };
  129. // Get the current token. This is updated when Next() is called. Before
  130. // the first call to Next(), current() has type TYPE_START and no contents.
  131. const Token& current();
  132. // Return the previous token -- i.e. what current() returned before the
  133. // previous call to Next().
  134. const Token& previous();
  135. // Advance to the next token. Returns false if the end of the input is
  136. // reached.
  137. bool Next();
  138. // Like Next(), but also collects comments which appear between the previous
  139. // and next tokens.
  140. //
  141. // Comments which appear to be attached to the previous token are stored
  142. // in *prev_tailing_comments. Comments which appear to be attached to the
  143. // next token are stored in *next_leading_comments. Comments appearing in
  144. // between which do not appear to be attached to either will be added to
  145. // detached_comments. Any of these parameters can be NULL to simply discard
  146. // the comments.
  147. //
  148. // A series of line comments appearing on consecutive lines, with no other
  149. // tokens appearing on those lines, will be treated as a single comment.
  150. //
  151. // Only the comment content is returned; comment markers (e.g. //) are
  152. // stripped out. For block comments, leading whitespace and an asterisk will
  153. // be stripped from the beginning of each line other than the first. Newlines
  154. // are included in the output.
  155. //
  156. // Examples:
  157. //
  158. // optional int32 foo = 1; // Comment attached to foo.
  159. // // Comment attached to bar.
  160. // optional int32 bar = 2;
  161. //
  162. // optional string baz = 3;
  163. // // Comment attached to baz.
  164. // // Another line attached to baz.
  165. //
  166. // // Comment attached to qux.
  167. // //
  168. // // Another line attached to qux.
  169. // optional double qux = 4;
  170. //
  171. // // Detached comment. This is not attached to qux or corge
  172. // // because there are blank lines separating it from both.
  173. //
  174. // optional string corge = 5;
  175. // /* Block comment attached
  176. // * to corge. Leading asterisks
  177. // * will be removed. */
  178. // /* Block comment attached to
  179. // * grault. */
  180. // optional int32 grault = 6;
  181. bool NextWithComments(std::string* prev_trailing_comments,
  182. std::vector<std::string>* detached_comments,
  183. std::string* next_leading_comments);
  184. // Parse helpers ---------------------------------------------------
  185. // Parses a TYPE_FLOAT token. This never fails, so long as the text actually
  186. // comes from a TYPE_FLOAT token parsed by Tokenizer. If it doesn't, the
  187. // result is undefined (possibly an assert failure).
  188. static double ParseFloat(const std::string& text);
  189. // Parses a TYPE_STRING token. This never fails, so long as the text actually
  190. // comes from a TYPE_STRING token parsed by Tokenizer. If it doesn't, the
  191. // result is undefined (possibly an assert failure).
  192. static void ParseString(const std::string& text, std::string* output);
  193. // Identical to ParseString, but appends to output.
  194. static void ParseStringAppend(const std::string& text, std::string* output);
  195. // Parses a TYPE_INTEGER token. Returns false if the result would be
  196. // greater than max_value. Otherwise, returns true and sets *output to the
  197. // result. If the text is not from a Token of type TYPE_INTEGER originally
  198. // parsed by a Tokenizer, the result is undefined (possibly an assert
  199. // failure).
  200. static bool ParseInteger(const std::string& text, uint64_t max_value,
  201. uint64_t* output);
  202. // Options ---------------------------------------------------------
  203. // Set true to allow floats to be suffixed with the letter 'f'. Tokens
  204. // which would otherwise be integers but which have the 'f' suffix will be
  205. // forced to be interpreted as floats. For all other purposes, the 'f' is
  206. // ignored.
  207. void set_allow_f_after_float(bool value) { allow_f_after_float_ = value; }
  208. // Valid values for set_comment_style().
  209. enum CommentStyle {
  210. // Line comments begin with "//", block comments are delimited by "/*" and
  211. // "*/".
  212. CPP_COMMENT_STYLE,
  213. // Line comments begin with "#". No way to write block comments.
  214. SH_COMMENT_STYLE
  215. };
  216. // Sets the comment style.
  217. void set_comment_style(CommentStyle style) { comment_style_ = style; }
  218. // Whether to require whitespace between a number and a field name.
  219. // Default is true. Do not use this; for Google-internal cleanup only.
  220. void set_require_space_after_number(bool require) {
  221. require_space_after_number_ = require;
  222. }
  223. // Whether to allow string literals to span multiple lines. Default is false.
  224. // Do not use this; for Google-internal cleanup only.
  225. void set_allow_multiline_strings(bool allow) {
  226. allow_multiline_strings_ = allow;
  227. }
  228. // If true, whitespace tokens are reported by Next().
  229. // Note: `set_report_whitespace(false)` implies `set_report_newlines(false)`.
  230. bool report_whitespace() const;
  231. void set_report_whitespace(bool report);
  232. // If true, newline tokens are reported by Next().
  233. // Note: `set_report_newlines(true)` implies `set_report_whitespace(true)`.
  234. bool report_newlines() const;
  235. void set_report_newlines(bool report);
  236. // External helper: validate an identifier.
  237. static bool IsIdentifier(const std::string& text);
  238. // -----------------------------------------------------------------
  239. private:
  240. GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Tokenizer);
  241. Token current_; // Returned by current().
  242. Token previous_; // Returned by previous().
  243. ZeroCopyInputStream* input_;
  244. ErrorCollector* error_collector_;
  245. char current_char_; // == buffer_[buffer_pos_], updated by NextChar().
  246. const char* buffer_; // Current buffer returned from input_.
  247. int buffer_size_; // Size of buffer_.
  248. int buffer_pos_; // Current position within the buffer.
  249. bool read_error_; // Did we previously encounter a read error?
  250. // Line and column number of current_char_ within the whole input stream.
  251. int line_;
  252. ColumnNumber column_;
  253. // String to which text should be appended as we advance through it.
  254. // Call RecordTo(&str) to start recording and StopRecording() to stop.
  255. // E.g. StartToken() calls RecordTo(&current_.text). record_start_ is the
  256. // position within the current buffer where recording started.
  257. std::string* record_target_;
  258. int record_start_;
  259. // Options.
  260. bool allow_f_after_float_;
  261. CommentStyle comment_style_;
  262. bool require_space_after_number_;
  263. bool allow_multiline_strings_;
  264. bool report_whitespace_ = false;
  265. bool report_newlines_ = false;
  266. // Since we count columns we need to interpret tabs somehow. We'll take
  267. // the standard 8-character definition for lack of any way to do better.
  268. // This must match the documentation of ColumnNumber.
  269. static const int kTabWidth = 8;
  270. // -----------------------------------------------------------------
  271. // Helper methods.
  272. // Consume this character and advance to the next one.
  273. void NextChar();
  274. // Read a new buffer from the input.
  275. void Refresh();
  276. inline void RecordTo(std::string* target);
  277. inline void StopRecording();
  278. // Called when the current character is the first character of a new
  279. // token (not including whitespace or comments).
  280. inline void StartToken();
  281. // Called when the current character is the first character after the
  282. // end of the last token. After this returns, current_.text will
  283. // contain all text consumed since StartToken() was called.
  284. inline void EndToken();
  285. // Convenience method to add an error at the current line and column.
  286. void AddError(const std::string& message) {
  287. error_collector_->AddError(line_, column_, message);
  288. }
  289. // -----------------------------------------------------------------
  290. // The following four methods are used to consume tokens of specific
  291. // types. They are actually used to consume all characters *after*
  292. // the first, since the calling function consumes the first character
  293. // in order to decide what kind of token is being read.
  294. // Read and consume a string, ending when the given delimiter is
  295. // consumed.
  296. void ConsumeString(char delimiter);
  297. // Read and consume a number, returning TYPE_FLOAT or TYPE_INTEGER
  298. // depending on what was read. This needs to know if the first
  299. // character was a zero in order to correctly recognize hex and octal
  300. // numbers.
  301. // It also needs to know if the first character was a . to parse floating
  302. // point correctly.
  303. TokenType ConsumeNumber(bool started_with_zero, bool started_with_dot);
  304. // Consume the rest of a line.
  305. void ConsumeLineComment(std::string* content);
  306. // Consume until "*/".
  307. void ConsumeBlockComment(std::string* content);
  308. enum NextCommentStatus {
  309. // Started a line comment.
  310. LINE_COMMENT,
  311. // Started a block comment.
  312. BLOCK_COMMENT,
  313. // Consumed a slash, then realized it wasn't a comment. current_ has
  314. // been filled in with a slash token. The caller should return it.
  315. SLASH_NOT_COMMENT,
  316. // We do not appear to be starting a comment here.
  317. NO_COMMENT
  318. };
  319. // If we're at the start of a new comment, consume it and return what kind
  320. // of comment it is.
  321. NextCommentStatus TryConsumeCommentStart();
  322. // If we're looking at a TYPE_WHITESPACE token and `report_whitespace_` is
  323. // true, consume it and return true.
  324. bool TryConsumeWhitespace();
  325. // If we're looking at a TYPE_NEWLINE token and `report_newlines_` is true,
  326. // consume it and return true.
  327. bool TryConsumeNewline();
  328. // -----------------------------------------------------------------
  329. // These helper methods make the parsing code more readable. The
  330. // "character classes" referred to are defined at the top of the .cc file.
  331. // Basically it is a C++ class with one method:
  332. // static bool InClass(char c);
  333. // The method returns true if c is a member of this "class", like "Letter"
  334. // or "Digit".
  335. // Returns true if the current character is of the given character
  336. // class, but does not consume anything.
  337. template <typename CharacterClass>
  338. inline bool LookingAt();
  339. // If the current character is in the given class, consume it and return
  340. // true. Otherwise return false.
  341. // e.g. TryConsumeOne<Letter>()
  342. template <typename CharacterClass>
  343. inline bool TryConsumeOne();
  344. // Like above, but try to consume the specific character indicated.
  345. inline bool TryConsume(char c);
  346. // Consume zero or more of the given character class.
  347. template <typename CharacterClass>
  348. inline void ConsumeZeroOrMore();
  349. // Consume one or more of the given character class or log the given
  350. // error message.
  351. // e.g. ConsumeOneOrMore<Digit>("Expected digits.");
  352. template <typename CharacterClass>
  353. inline void ConsumeOneOrMore(const char* error);
  354. };
  355. // inline methods ====================================================
  356. inline const Tokenizer::Token& Tokenizer::current() { return current_; }
  357. inline const Tokenizer::Token& Tokenizer::previous() { return previous_; }
  358. inline void Tokenizer::ParseString(const std::string& text,
  359. std::string* output) {
  360. output->clear();
  361. ParseStringAppend(text, output);
  362. }
  363. } // namespace io
  364. } // namespace protobuf
  365. } // namespace google
  366. #include <google/protobuf/port_undef.inc>
  367. #endif // GOOGLE_PROTOBUF_IO_TOKENIZER_H__