You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

tokenizer.h 18 kB

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