master_lexer.h 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. // Copyright (C) 2012 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #ifndef MASTER_LEXER_H
  15. #define MASTER_LEXER_H 1
  16. #include <exceptions/exceptions.h>
  17. #include <istream>
  18. #include <string>
  19. #include <stdint.h>
  20. namespace isc {
  21. namespace dns {
  22. namespace master_lexer_internal {
  23. class State;
  24. }
  25. /// \brief Tokens for \c MasterLexer
  26. ///
  27. /// This is a simple value-class encapsulating a type of a lexer token and
  28. /// (if it has a value) its value. Essentially, the class provides
  29. /// constructors corresponding to different types of tokens, and corresponding
  30. /// getter methods. The type and value are fixed at the time of construction
  31. /// and will never be modified throughout the lifetime of the object.
  32. /// The getter methods are still provided to maximize the safety; an
  33. /// application cannot refer to a value that is invalid for the type of token.
  34. ///
  35. /// This class is intentionally implemented as copyable and assignable
  36. /// (using the default version of copy constructor and assignment operator),
  37. /// but it's mainly for internal implementation convenience. Applications will
  38. /// simply refer to Token object as a reference via the \c MasterLexer class.
  39. class MasterToken {
  40. public:
  41. /// \brief Enumeration for token types
  42. ///
  43. /// \note At the time of initial implementation, all numeric tokens
  44. /// that would be extracted from \c MasterLexer should be represented
  45. /// as an unsigned 32-bit integer. If we see the need for larger integers
  46. /// or negative numbers, we can then extend the token types.
  47. enum Type {
  48. END_OF_LINE, ///< End of line detected
  49. END_OF_FILE, ///< End of file detected
  50. INITIAL_WS, ///< White spaces at the beginning of a line after an
  51. ///< end of line or at the beginning of file (if asked
  52. // for detecting it)
  53. NOVALUE_TYPE_MAX = INITIAL_WS, ///< Max integer corresponding to
  54. /// no-value (type only) types.
  55. /// Mainly for internal use.
  56. STRING, ///< A single string
  57. QSTRING, ///< A single string quoted by double-quotes (").
  58. NUMBER, ///< A decimal number (unsigned 32-bit)
  59. ERROR ///< Error detected in getting a token
  60. };
  61. /// \brief Enumeration for lexer error codes
  62. enum ErrorCode {
  63. NOT_STARTED, ///< The lexer is just initialized and has no token
  64. UNBALANCED_PAREN, ///< Unbalanced parentheses detected
  65. UNEXPECTED_END, ///< The lexer reaches the end of line or file
  66. /// unexpectedly
  67. UNBALANCED_QUOTES, ///< Unbalanced quotations detected
  68. NO_TOKEN_PRODUCED, ///< No token was produced. This means programmer
  69. /// error and should never get out of the lexer.
  70. NUMBER_OUT_OF_RANGE, ///< Number was out of range
  71. BAD_NUMBER, ///< Number is expected but not recognized
  72. MAX_ERROR_CODE ///< Max integer corresponding to valid error codes.
  73. /// (excluding this one). Mainly for internal use.
  74. };
  75. /// \brief A simple representation of a range of a string.
  76. ///
  77. /// This is a straightforward pair of the start pointer of a string
  78. /// and its length. The \c STRING and \c QSTRING types of tokens
  79. /// will be primarily represented in this form.
  80. ///
  81. /// Any character can be stored in the valid range of the region.
  82. /// In particular, there can be a nul character (\0) in the middle of
  83. /// the region. So the usual string manipulation API may not work
  84. /// as expected.
  85. ///
  86. /// The `MasterLexer` implementation ensures that there are at least
  87. /// len + 1 bytes of valid memory region starting from beg, and that
  88. /// beg[len] is \0. This means the application can use the bytes as a
  89. /// validly nul-terminated C string if there is no intermediate nul
  90. /// character. Note also that due to this property beg is always non
  91. /// NULL; for an empty string len will be set to 0 and beg[0] is \0.
  92. struct StringRegion {
  93. const char* beg; ///< The start address of the string
  94. size_t len; ///< The length of the string in bytes
  95. };
  96. /// \brief Constructor for non-value type of token.
  97. ///
  98. /// \throw InvalidParameter A value type token is specified.
  99. /// \param type The type of the token. It must indicate a non-value
  100. /// type (not larger than \c NOVALUE_TYPE_MAX).
  101. explicit MasterToken(Type type) : type_(type) {
  102. if (type > NOVALUE_TYPE_MAX) {
  103. isc_throw(InvalidParameter, "Token per-type constructor "
  104. "called with invalid type: " << type);
  105. }
  106. }
  107. /// \brief Constructor for string and quoted-string types of token.
  108. ///
  109. /// The optional \c quoted parameter specifies whether it's a quoted or
  110. /// non quoted string.
  111. ///
  112. /// The string is specified as a pair of a pointer to the start address
  113. /// and its length. Any character can be contained in any position of
  114. /// the valid range (see \c StringRegion).
  115. ///
  116. /// When it's a quoted string, the quotation marks must be excluded
  117. /// from the specified range.
  118. ///
  119. /// \param str_beg The start address of the string
  120. /// \param str_len The size of the string in bytes
  121. /// \param quoted true if it's a quoted string; false otherwise.
  122. MasterToken(const char* str_beg, size_t str_len, bool quoted = false) :
  123. type_(quoted ? QSTRING : STRING)
  124. {
  125. val_.str_region_.beg = str_beg;
  126. val_.str_region_.len = str_len;
  127. }
  128. /// \brief Constructor for number type of token.
  129. ///
  130. /// \brief number An unsigned 32-bit integer corresponding to the token
  131. /// value.
  132. explicit MasterToken(uint32_t number) : type_(NUMBER) {
  133. val_.number_ = number;
  134. }
  135. /// \brief Constructor for error type of token.
  136. ///
  137. /// \throw InvalidParameter Invalid error code value is specified.
  138. /// \brief error_code A pre-defined constant of \c ErrorCode.
  139. explicit MasterToken(ErrorCode error_code) : type_(ERROR) {
  140. if (!(error_code < MAX_ERROR_CODE)) {
  141. isc_throw(InvalidParameter, "Invalid master lexer error code: "
  142. << error_code);
  143. }
  144. val_.error_code_ = error_code;
  145. }
  146. /// \brief Return the token type.
  147. ///
  148. /// \throw none
  149. Type getType() const { return (type_); }
  150. /// \brief Return the value of a string-variant token.
  151. ///
  152. /// \throw InvalidOperation Called on a non string-variant types of token.
  153. /// \return A reference to \c StringRegion corresponding to the string
  154. /// token value.
  155. const StringRegion& getStringRegion() const {
  156. if (type_ != STRING && type_ != QSTRING) {
  157. isc_throw(InvalidOperation,
  158. "Token::getStringRegion() for non string-variant type");
  159. }
  160. return (val_.str_region_);
  161. }
  162. /// \brief Return the value of a string-variant token as a string object.
  163. ///
  164. /// Note that the underlying string may contain a nul (\0) character
  165. /// in the middle. The returned string object will contain all characters
  166. /// of the valid range of the underlying string. So some string
  167. /// operations such as c_str() may not work as expected.
  168. ///
  169. /// \throw InvalidOperation Called on a non string-variant types of token.
  170. /// \throw std::bad_alloc Resource allocation failure in constructing the
  171. /// string object.
  172. /// \return A std::string object corresponding to the string token value.
  173. std::string getString() const {
  174. std::string ret;
  175. getString(ret);
  176. return (ret);
  177. }
  178. /// \brief Fill in a string with the value of a string-variant token.
  179. ///
  180. /// This is similar to the other version of \c getString(), but
  181. /// the caller is supposed to pass a placeholder string object.
  182. /// This will be more efficient if the caller uses the same
  183. /// \c MasterLexer repeatedly and needs to get string token in the
  184. /// form of a string object many times as this version could reuse
  185. /// the existing internal storage of the passed string.
  186. ///
  187. /// Any existing content of the passed string will be removed.
  188. ///
  189. /// \throw InvalidOperation Called on a non string-variant types of token.
  190. /// \throw std::bad_alloc Resource allocation failure in constructing the
  191. /// string object.
  192. ///
  193. /// \param ret A string object to be filled with the token string.
  194. void getString(std::string& ret) const {
  195. if (type_ != STRING && type_ != QSTRING) {
  196. isc_throw(InvalidOperation,
  197. "Token::getString() for non string-variant type");
  198. }
  199. ret.assign(val_.str_region_.beg,
  200. val_.str_region_.beg + val_.str_region_.len);
  201. }
  202. /// \brief Return the value of a string-variant token as a string object.
  203. ///
  204. /// \throw InvalidOperation Called on a non number type of token.
  205. /// \return The integer corresponding to the number token value.
  206. uint32_t getNumber() const {
  207. if (type_ != NUMBER) {
  208. isc_throw(InvalidOperation,
  209. "Token::getNumber() for non number type");
  210. }
  211. return (val_.number_);
  212. }
  213. /// \brief Return the error code of a error type token.
  214. ///
  215. /// \throw InvalidOperation Called on a non error type of token.
  216. /// \return The error code of the token.
  217. ErrorCode getErrorCode() const {
  218. if (type_ != ERROR) {
  219. isc_throw(InvalidOperation,
  220. "Token::getErrorCode() for non error type");
  221. }
  222. return (val_.error_code_);
  223. };
  224. /// \brief Return a textual description of the error of a error type token.
  225. ///
  226. /// The returned string would be useful to produce a log message when
  227. /// a zone file parser encounters an error.
  228. ///
  229. /// \throw InvalidOperation Called on a non error type of token.
  230. /// \throw std::bad_alloc Resource allocation failure in constructing the
  231. /// string object.
  232. /// \return A string object that describes the meaning of the error.
  233. std::string getErrorText() const;
  234. private:
  235. Type type_; // this is not const so the class can be assignable
  236. // We use a union to represent different types of token values via the
  237. // unified Token class. The class integrity should ensure valid operation
  238. // on the union; getter methods should only refer to the member set at
  239. // the construction.
  240. union {
  241. StringRegion str_region_;
  242. uint32_t number_;
  243. ErrorCode error_code_;
  244. } val_;
  245. };
  246. /// \brief Tokenizer for parsing DNS master files.
  247. ///
  248. /// The \c MasterLexer class provides tokenize interfaces for parsing DNS
  249. /// master files. It understands some special rules of master files as
  250. /// defined in RFC 1035, such as comments, character escaping, and multi-line
  251. /// data, and provides the user application with the actual data in a
  252. /// more convenient form such as a std::string object.
  253. ///
  254. /// In order to support the $INCLUDE notation, this class is designed to be
  255. /// able to operate on multiple files or input streams in the nested way.
  256. /// The \c pushSource() and \c popSource() methods correspond to the push
  257. /// and pop operations.
  258. ///
  259. /// While this class is public, it is less likely to be used by normal
  260. /// applications; it's mainly expected to be used within this library,
  261. /// specifically by the \c MasterLoader class and \c Rdata implementation
  262. /// classes.
  263. ///
  264. /// \note The error handling policy of this class is slightly different from
  265. /// that of other classes of this library. We generally throw an exception
  266. /// for an invalid input, whether it's more likely to be a program error or
  267. /// a "user error", which means an invalid input that comes from outside of
  268. /// the library. But, this class returns an error code for some certain
  269. /// types of user errors instead of throwing an exception. Such cases include
  270. /// a syntax error identified by the lexer or a misspelled file name that
  271. /// causes a system error at the time of open. This is based on the assumption
  272. /// that the main user of this class is a parser of master files, where
  273. /// we want to give an option to ignore some non fatal errors and continue
  274. /// the parsing. This will be useful if it just performs overall error
  275. /// checks on a master file. When the (immediate) caller needs to do explicit
  276. /// error handling, exceptions are not that a useful tool for error reporting
  277. /// because we cannot separate the normal and error cases anyway, which would
  278. /// be one major advantage when we use exceptions. And, exceptions are
  279. /// generally more expensive, either when it happens or just by being able
  280. /// to handle with \c try and \c catch (depending on the underlying
  281. /// implementation of the exception handling). For these reasons, some of
  282. /// this class does not throw for an error that would be reported as an
  283. /// exception in other classes.
  284. class MasterLexer {
  285. friend class master_lexer_internal::State;
  286. public:
  287. /// \brief Exception thrown when we fail to read from the input
  288. /// stream or file.
  289. class ReadError : public Unexpected {
  290. public:
  291. ReadError(const char* file, size_t line, const char* what) :
  292. Unexpected(file, line, what)
  293. {}
  294. };
  295. /// \brief Exception thrown from a wrapper version of
  296. /// \c MasterLexer::getNextToken() for non fatal errors.
  297. ///
  298. /// See the method description for more details.
  299. ///
  300. /// The \c token_ member variable (read-only) is set to a \c MasterToken
  301. /// object of type ERROR indicating the reason for the error.
  302. class LexerError : public Exception {
  303. public:
  304. LexerError(const char* file, size_t line, MasterToken error_token) :
  305. Exception(file, line, error_token.getErrorText().c_str()),
  306. token_(error_token)
  307. {}
  308. const MasterToken token_;
  309. };
  310. /// \brief Special value for input source size meaning "unknown".
  311. ///
  312. /// This constant value will be used as a return value of
  313. /// \c getTotalSourceSize() when the size of one of the pushed sources
  314. /// is unknown. Note that this value itself is a valid integer in the
  315. /// range of the type, so there's still a small possibility of
  316. /// ambiguity. In practice, however, the value should be sufficiently
  317. /// large that should eliminate the possibility.
  318. static const size_t SOURCE_SIZE_UNKNOWN;
  319. /// \brief Options for getNextToken.
  320. ///
  321. /// A compound option, indicating multiple options are set, can be
  322. /// specified using the logical OR operator (operator|()).
  323. enum Options {
  324. NONE = 0, ///< No option
  325. INITIAL_WS = 1, ///< recognize begin-of-line spaces after an
  326. ///< end-of-line
  327. QSTRING = 2, ///< recognize quoted string
  328. NUMBER = 4 ///< recognize numeric text as integer
  329. };
  330. /// \brief The constructor.
  331. ///
  332. /// \throw std::bad_alloc Internal resource allocation fails (rare case).
  333. MasterLexer();
  334. /// \brief The destructor.
  335. ///
  336. /// It internally closes any remaining input sources.
  337. ~MasterLexer();
  338. /// \brief Open a file and make it the current input source of MasterLexer.
  339. ///
  340. /// The opened file can be explicitly closed by the \c popSource() method;
  341. /// if \c popSource() is not called within the lifetime of the
  342. /// \c MasterLexer, it will be closed in the destructor.
  343. ///
  344. /// In the case possible system errors in opening the file (most likely
  345. /// because of specifying a non-existent or unreadable file), it returns
  346. /// false, and if the optional \c error parameter is non NULL, it will be
  347. /// set to a description of the error (any existing content of the string
  348. /// will be discarded). If opening the file succeeds, the given
  349. /// \c error parameter will be intact.
  350. ///
  351. /// Note that this method has two styles of error reporting: one by
  352. /// returning \c false (and setting \c error optionally) and the other
  353. /// by throwing an exception. See the note for the class description
  354. /// about the distinction.
  355. ///
  356. /// \throw InvalidParameter filename is NULL
  357. /// \param filename A non NULL string specifying a master file
  358. /// \param error If non null, a placeholder to set error description in
  359. /// case of failure.
  360. ///
  361. /// \return true if pushing the file succeeds; false otherwise.
  362. bool pushSource(const char* filename, std::string* error = NULL);
  363. /// \brief Make the given stream the current input source of MasterLexer.
  364. ///
  365. /// The caller still holds the ownership of the passed stream; it's the
  366. /// caller's responsibility to keep it valid as long as it's used in
  367. /// \c MasterLexer or to release any resource for the stream after that.
  368. /// The caller can explicitly tell \c MasterLexer to stop using the
  369. /// stream by calling the \c popSource() method.
  370. ///
  371. /// The data in \c input must be complete at the time of this call.
  372. /// The behavior of the lexer is undefined if the caller builds or adds
  373. /// data in \c input after pushing it.
  374. ///
  375. /// Except for rare case system errors such as memory allocation failure,
  376. /// this method is generally expected to be exception free. However,
  377. /// it can still throw if it encounters an unexpected failure when it
  378. /// tries to identify the "size" of the input source (see
  379. /// \c getTotalSourceSize()). It's an unexpected result unless the
  380. /// caller intentionally passes a broken stream; otherwise it would mean
  381. /// some system-dependent unexpected behavior or possibly an internal bug.
  382. /// In these cases it throws an \c Unexpected exception. Note that
  383. /// this version of the method doesn't return a boolean unlike the
  384. /// other version that takes a file name; since this failure is really
  385. /// unexpected and can be critical, it doesn't make sense to give the
  386. /// caller an option to continue (other than by explicitly catching the
  387. /// exception).
  388. ///
  389. /// \throw Unexpected An unexpected failure happens in initialization.
  390. ///
  391. /// \param input An input stream object that produces textual
  392. /// representation of DNS RRs.
  393. void pushSource(std::istream& input);
  394. /// \brief Stop using the most recently opened input source (file or
  395. /// stream).
  396. ///
  397. /// If it's a file, the previously opened file will be closed internally.
  398. /// If it's a stream, \c MasterLexer will simply stop using
  399. /// the stream; the caller can assume it will be never used in
  400. /// \c MasterLexer thereafter.
  401. ///
  402. /// This method must not be called when there is no source pushed for
  403. /// \c MasterLexer. This method is otherwise exception free.
  404. ///
  405. /// \throw isc::InvalidOperation Called with no pushed source.
  406. void popSource();
  407. /// \brief Get number of sources inside the lexer.
  408. ///
  409. /// This method never throws.
  410. size_t getSourceCount() const;
  411. /// \brief Return the name of the current input source name.
  412. ///
  413. /// If it's a file, it will be the C string given at the corresponding
  414. /// \c pushSource() call, that is, its filename. If it's a stream, it will
  415. /// be formatted as \c "stream-%p" where \c %p is hex representation
  416. /// of the address of the stream object.
  417. ///
  418. /// If there is no opened source at the time of the call, this method
  419. /// returns an empty string.
  420. ///
  421. /// \throw std::bad_alloc Resource allocation failed for string
  422. /// construction (rare case)
  423. ///
  424. /// \return A string representation of the current source (see the
  425. /// description)
  426. std::string getSourceName() const;
  427. /// \brief Return the input source line number.
  428. ///
  429. /// If there is an opened source, the return value will be a non-0
  430. /// integer indicating the line number of the current source where
  431. /// the \c MasterLexer is currently working. The expected usage of
  432. /// this value is to print a helpful error message when parsing fails
  433. /// by specifically identifying the position of the error.
  434. ///
  435. /// If there is no opened source at the time of the call, this method
  436. /// returns 0.
  437. ///
  438. /// \throw None
  439. ///
  440. /// \return The current line number of the source (see the description)
  441. size_t getSourceLine() const;
  442. /// \brief Return the total size of pushed sources.
  443. ///
  444. /// This method returns the sum of the size of sources that have been
  445. /// pushed to the lexer by the time of the call. It would give the
  446. /// caller some hint about the amount of data the lexer is working on.
  447. ///
  448. /// The size of a normal file is equal to the file size at the time of
  449. /// the source is pushed. The size of other type of input stream is
  450. /// the size of the data available in the stream at the time of the
  451. /// source is pushed.
  452. ///
  453. /// In some special cases, it's possible that the size of the file or
  454. /// stream is unknown. It happens, for example, if the standard input
  455. /// is associated with a pipe from the output of another process and it's
  456. /// specified as an input source. If the size of some of the pushed
  457. /// source is unknown, this method returns SOURCE_SIZE_UNKNOWN.
  458. ///
  459. /// The total size won't change when a source is popped. So the return
  460. /// values of this method will monotonically increase or
  461. /// \c SOURCE_SIZE_UNKNOWN; once it returns \c SOURCE_SIZE_UNKNOWN,
  462. /// any subsequent call will also result in that value, by the above
  463. /// definition.
  464. ///
  465. /// Before pushing any source, it returns 0.
  466. ///
  467. /// \throw None
  468. size_t getTotalSourceSize() const;
  469. /// \brief Return the position of lexer in the pushed sources so far.
  470. ///
  471. /// This method returns the position in terms of the number of recognized
  472. /// characters from all sources that have been pushed by the time of the
  473. /// call. Conceptually, the position in a single source is the offset
  474. /// from the beginning of the file or stream to the current "read cursor"
  475. /// of the lexer. The return value of this method is the sum of the
  476. /// positions in all the pushed sources. If any of the sources has
  477. /// already been popped, the position of the source at the time of the
  478. /// pop operation will be used for the calculation.
  479. ///
  480. /// If the lexer reaches the end for each of all the pushed sources,
  481. /// the return value should be equal to that of \c getTotalSourceSize().
  482. /// It's generally expected that a source is popped when the lexer
  483. /// reaches the end of the source. So, when the application of this
  484. /// class parses all contents of all sources, possibly with multiple
  485. /// pushes and pops, the return value of this method and
  486. /// \c getTotalSourceSize() should be identical (unless the latter
  487. /// returns SOURCE_SIZE_UNKNOWN). But this is not necessarily
  488. /// guaranteed as the application can pop a source in the middle of
  489. /// parsing it.
  490. ///
  491. /// Before pushing any source, it returns 0.
  492. ///
  493. /// The return values of this method and \c getTotalSourceSize() would
  494. /// give the caller an idea of the progress of the lexer at the time of
  495. /// the call. Note, however, that since it's not predictable whether
  496. /// more sources will be pushed after the call, the progress determined
  497. /// this way may not make much sense; it can only give an informational
  498. /// hint of the progress.
  499. ///
  500. /// Note that the conceptual "read cursor" would move backward after a
  501. /// call to \c ungetToken(), in which case this method will return a
  502. /// smaller value. That is, unlike \c getTotalSourceSize(), return
  503. /// values of this method may not always monotonically increase.
  504. ///
  505. /// \throw None
  506. size_t getPosition() const;
  507. /// \brief Parse and return another token from the input.
  508. ///
  509. /// It reads a bit of the last opened source and produces another token
  510. /// found in it.
  511. ///
  512. /// This method does not provide the strong exception guarantee. Generally,
  513. /// if it throws, the object should not be used any more and should be
  514. /// discarded. It was decided all the exceptions thrown from here are
  515. /// serious enough that aborting the loading process is the only reasonable
  516. /// recovery anyway, so the strong exception guarantee is not needed.
  517. ///
  518. /// \param options The options can be used to modify the tokenization.
  519. /// The method can be made reporting things which are usually ignored
  520. /// by this parameter. Multiple options can be passed at once by
  521. /// bitwise or (eg. option1 | option 2). See description of available
  522. /// options.
  523. /// \return Next token found in the input. Note that the token refers to
  524. /// some internal data in the lexer. It is valid only until
  525. /// getNextToken or ungetToken is called. Also, the token becomes
  526. /// invalid when the lexer is destroyed.
  527. /// \throw isc::InvalidOperation in case the source is not available. This
  528. /// may mean the pushSource() has not been called yet, or that the
  529. /// current source has been read past the end.
  530. /// \throw ReadError in case there's problem reading from the underlying
  531. /// source (eg. I/O error in the file on the disk).
  532. /// \throw std::bad_alloc in case allocation of some internal resources
  533. /// or the token fail.
  534. const MasterToken& getNextToken(Options options = NONE);
  535. /// \brief Parse the input for the expected type of token.
  536. ///
  537. /// This method is a wrapper of the other version, customized for the case
  538. /// where a particular type of token is expected as the next one.
  539. /// More specifically, it's intended to be used to get tokens for RDATA
  540. /// fields. Since most RDATA types of fixed format, the token type is
  541. /// often predictable and the method interface can be simplified.
  542. ///
  543. /// This method basically works as follows: it gets the type of the
  544. /// expected token, calls the other version of \c getNextToken(Options),
  545. /// and returns the token if it's of the expected type (due to the usage
  546. /// assumption this should be normally the case). There are some non
  547. /// trivial details though:
  548. ///
  549. /// - If the expected type is MasterToken::QSTRING, both quoted and
  550. /// unquoted strings are recognized and returned.
  551. /// - If the optional \c eol_ok parameter is \c true (very rare case),
  552. /// MasterToken::END_OF_LINE and MasterToken::END_OF_FILE are recognized
  553. /// and returned if they are found instead of the expected type of
  554. /// token.
  555. /// - If the next token is not of the expected type (including the case
  556. /// a number is expected but it's out of range), ungetToken() is
  557. /// internally called so the caller can re-read that token.
  558. /// - If other types or errors (such as unbalanced parentheses) are
  559. /// detected, the erroneous part isn't "ungotten"; the caller can
  560. /// continue parsing after that part.
  561. ///
  562. /// In some very rare cases where the RDATA has an optional trailing field,
  563. /// the \c eol_ok parameter would be set to \c true. This way the caller
  564. /// can handle both cases (the field does or does not exist) by a single
  565. /// call to this method. In all other cases \c eol_ok should be set to
  566. /// \c false, and that is the default and can be omitted.
  567. ///
  568. /// Unlike the other version of \c getNextToken(Options), this method
  569. /// throws an exception of type \c LexerError for non fatal errors such as
  570. /// broken syntax or encountering an unexpected type of token. This way
  571. /// the caller can write RDATA parser code without bothering to handle
  572. /// errors for each field. For example, pseudo parser code for MX RDATA
  573. /// would look like this:
  574. /// \code
  575. /// const uint32_t pref =
  576. /// lexer.getNextToken(MasterToken::NUMBER).getNumber();
  577. /// // check if pref is the uint16_t range; no other check is needed.
  578. /// const Name mx(lexer.getNextToken(MasterToken::STRING).getString());
  579. /// \endcode
  580. ///
  581. /// In the case where \c LexerError exception is thrown, it's expected
  582. /// to be handled comprehensively for the parser of the RDATA or at a
  583. /// higher layer. The \c token_ member variable of the corresponding
  584. /// \c LexerError exception object stores a token of type
  585. /// \c MasterToken::ERROR that indicates the reason for the error.
  586. ///
  587. /// Due to the specific intended usage of this method, only a subset
  588. /// of \c MasterToken::Type values are acceptable for the \c expect
  589. /// parameter: \c MasterToken::STRING, \c MasterToken::QSTRING, and
  590. /// \c MasterToken::NUMBER. Specifying other values will result in
  591. /// an \c InvalidParameter exception.
  592. ///
  593. /// \throw InvalidParameter The expected token type is not allowed for
  594. /// this method.
  595. /// \throw LexerError The lexer finds non fatal error or it finds an
  596. /// \throw other Anything the other version of getNextToken() can throw.
  597. ///
  598. /// \param expect Expected type of token. Must be either STRING, QSTRING,
  599. /// or NUMBER.
  600. /// \param eol_ok \c true iff END_OF_LINE or END_OF_FILE is acceptable.
  601. /// \return The expected type of token.
  602. const MasterToken& getNextToken(MasterToken::Type expect,
  603. bool eol_ok = false);
  604. /// \brief Return the last token back to the lexer.
  605. ///
  606. /// The method undoes the lasts call to getNextToken(). If you call the
  607. /// getNextToken() again with the same options, it'll return the same
  608. /// token. If the options are different, it may return a different token,
  609. /// but it acts as if the previous getNextToken() was never called.
  610. ///
  611. /// It is possible to return only one token back in time (you can't call
  612. /// ungetToken() twice in a row without calling getNextToken() in between
  613. /// successfully).
  614. ///
  615. /// It does not work after change of source (by pushSource or popSource).
  616. ///
  617. /// \throw isc::InvalidOperation If called second time in a row or if
  618. /// getNextToken() was not called since the last change of the source.
  619. void ungetToken();
  620. private:
  621. struct MasterLexerImpl;
  622. MasterLexerImpl* impl_;
  623. };
  624. /// \brief Operator to combine \c MasterLexer options
  625. ///
  626. /// This is a trivial shortcut so that compound options can be specified
  627. /// in an intuitive way.
  628. inline MasterLexer::Options
  629. operator|(MasterLexer::Options o1, MasterLexer::Options o2) {
  630. return (static_cast<MasterLexer::Options>(
  631. static_cast<unsigned>(o1) | static_cast<unsigned>(o2)));
  632. }
  633. } // namespace dns
  634. } // namespace isc
  635. #endif // MASTER_LEXER_H
  636. // Local Variables:
  637. // mode: c++
  638. // End: