tokenizer.h 16 KB

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