master_lexer.cc 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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. #include <exceptions/exceptions.h>
  15. #include <dns/master_lexer.h>
  16. #include <dns/master_lexer_inputsource.h>
  17. #include <dns/master_lexer_state.h>
  18. #include <boost/shared_ptr.hpp>
  19. #include <boost/lexical_cast.hpp>
  20. #include <bitset>
  21. #include <cassert>
  22. #include <string>
  23. #include <vector>
  24. namespace isc {
  25. namespace dns {
  26. namespace {
  27. typedef boost::shared_ptr<master_lexer_internal::InputSource> InputSourcePtr;
  28. } // end unnamed namespace
  29. using namespace master_lexer_internal;
  30. struct MasterLexer::MasterLexerImpl {
  31. MasterLexerImpl() : source_(NULL), token_(MasterToken::NOT_STARTED),
  32. paren_count_(0), last_was_eol_(false),
  33. has_previous_(false),
  34. previous_paren_count_(0),
  35. previous_was_eol_(false)
  36. {
  37. separators_.set('\r');
  38. separators_.set('\n');
  39. separators_.set(' ');
  40. separators_.set('\t');
  41. separators_.set('(');
  42. separators_.set(')');
  43. esc_separators_.set('\r');
  44. esc_separators_.set('\n');
  45. }
  46. // A helper method to skip possible comments toward the end of EOL or EOF.
  47. // commonly used by state classes. It returns the corresponding "end-of"
  48. // character in case it's a comment; otherwise it simply returns the
  49. // current character.
  50. int skipComment(int c, bool escaped = false) {
  51. if (c == ';' && !escaped) {
  52. while (true) {
  53. c = source_->getChar();
  54. if (c == '\n' || c == InputSource::END_OF_STREAM) {
  55. return (c);
  56. }
  57. }
  58. }
  59. return (c);
  60. }
  61. bool isTokenEnd(int c, bool escaped) {
  62. // Special case of EOF (end of stream); this is not in the bitmaps
  63. if (c == InputSource::END_OF_STREAM) {
  64. return (true);
  65. }
  66. // In this implementation we only ensure the behavior for unsigned
  67. // range of characters, so we restrict the range of the values up to
  68. // 0x7f = 127
  69. return (escaped ? esc_separators_.test(c & 0x7f) :
  70. separators_.test(c & 0x7f));
  71. }
  72. std::vector<InputSourcePtr> sources_;
  73. InputSource* source_; // current source (NULL if sources_ is empty)
  74. MasterToken token_; // currently recognized token (set by a state)
  75. std::vector<char> data_; // placeholder for string data
  76. // These are used in states, and defined here only as a placeholder.
  77. // The main lexer class does not need these members.
  78. size_t paren_count_; // nest count of the parentheses
  79. bool last_was_eol_; // whether the lexer just passed an end-of-line
  80. // Bitmaps that gives whether a given (positive) character should be
  81. // considered a separator of a string/number token. The esc_ version
  82. // is a subset of the other, excluding characters that can be ignored
  83. // if escaped by a backslash. See isTokenEnd() for the bitmap size.
  84. std::bitset<128> separators_;
  85. std::bitset<128> esc_separators_;
  86. // These are to allow restoring state before previous token.
  87. bool has_previous_;
  88. size_t previous_paren_count_;
  89. bool previous_was_eol_;
  90. };
  91. MasterLexer::MasterLexer() : impl_(new MasterLexerImpl) {
  92. }
  93. MasterLexer::~MasterLexer() {
  94. delete impl_;
  95. }
  96. bool
  97. MasterLexer::pushSource(const char* filename, std::string* error) {
  98. if (filename == NULL) {
  99. isc_throw(InvalidParameter,
  100. "NULL filename for MasterLexer::pushSource");
  101. }
  102. try {
  103. impl_->sources_.push_back(InputSourcePtr(new InputSource(filename)));
  104. } catch (const InputSource::OpenError& ex) {
  105. if (error != NULL) {
  106. *error = ex.what();
  107. }
  108. return (false);
  109. }
  110. impl_->source_ = impl_->sources_.back().get();
  111. impl_->has_previous_ = false;
  112. return (true);
  113. }
  114. void
  115. MasterLexer::pushSource(std::istream& input) {
  116. impl_->sources_.push_back(InputSourcePtr(new InputSource(input)));
  117. impl_->source_ = impl_->sources_.back().get();
  118. impl_->has_previous_ = false;
  119. }
  120. void
  121. MasterLexer::popSource() {
  122. if (impl_->sources_.empty()) {
  123. isc_throw(InvalidOperation,
  124. "MasterLexer::popSource on an empty source");
  125. }
  126. impl_->sources_.pop_back();
  127. impl_->source_ = impl_->sources_.empty() ? NULL :
  128. impl_->sources_.back().get();
  129. impl_->has_previous_ = false;
  130. }
  131. std::string
  132. MasterLexer::getSourceName() const {
  133. if (impl_->sources_.empty()) {
  134. return (std::string());
  135. }
  136. return (impl_->sources_.back()->getName());
  137. }
  138. size_t
  139. MasterLexer::getSourceLine() const {
  140. if (impl_->sources_.empty()) {
  141. return (0);
  142. }
  143. return (impl_->sources_.back()->getCurrentLine());
  144. }
  145. const MasterToken&
  146. MasterLexer::getNextToken(Options options) {
  147. if (impl_->source_ == NULL) {
  148. isc_throw(isc::InvalidOperation, "No source to read tokens from");
  149. }
  150. // Store the current state so we can restore it in ungetToken
  151. impl_->previous_paren_count_ = impl_->paren_count_;
  152. impl_->previous_was_eol_ = impl_->last_was_eol_;
  153. impl_->source_->mark();
  154. impl_->has_previous_ = true;
  155. // Reset the token now. This is to check a token was actually produced.
  156. // This is debugging aid.
  157. impl_->token_ = MasterToken(MasterToken::NO_TOKEN_PRODUCED);
  158. // And get the token
  159. // This actually handles EOF internally too.
  160. const State* state = State::start(*this, options);
  161. if (state != NULL) {
  162. state->handle(*this);
  163. }
  164. // Make sure a token was produced. Since this Can Not Happen, we assert
  165. // here instead of throwing.
  166. assert(impl_->token_.getType() != MasterToken::ERROR ||
  167. impl_->token_.getErrorCode() != MasterToken::NO_TOKEN_PRODUCED);
  168. return (impl_->token_);
  169. }
  170. namespace {
  171. inline MasterLexer::Options
  172. optionsForTokenType(MasterToken::Type expect) {
  173. switch (expect) {
  174. case MasterToken::STRING:
  175. return (MasterLexer::NONE);
  176. case MasterToken::QSTRING:
  177. return (MasterLexer::QSTRING);
  178. case MasterToken::NUMBER:
  179. return (MasterLexer::NUMBER);
  180. default:
  181. isc_throw(InvalidParameter,
  182. "expected type for getNextToken not supported: " << expect);
  183. }
  184. }
  185. }
  186. const MasterToken&
  187. MasterLexer::getNextToken(MasterToken::Type expect, bool eol_ok) {
  188. // Get the next token, specifying an appropriate option corresponding to
  189. // the expected type. The result should be set in impl_->token_.
  190. getNextToken(optionsForTokenType(expect));
  191. if (impl_->token_.getType() == MasterToken::ERROR) {
  192. if (impl_->token_.getErrorCode() == MasterToken::NUMBER_OUT_OF_RANGE) {
  193. ungetToken();
  194. }
  195. throw LexerError(__FILE__, __LINE__, impl_->token_);
  196. }
  197. const bool is_eol_like =
  198. (impl_->token_.getType() == MasterToken::END_OF_LINE ||
  199. impl_->token_.getType() == MasterToken::END_OF_FILE);
  200. if (eol_ok && is_eol_like) {
  201. return (impl_->token_);
  202. }
  203. if (impl_->token_.getType() == MasterToken::STRING &&
  204. expect == MasterToken::QSTRING) {
  205. return (impl_->token_);
  206. }
  207. if (impl_->token_.getType() != expect) {
  208. ungetToken();
  209. if (is_eol_like) {
  210. throw LexerError(__FILE__, __LINE__,
  211. MasterToken(MasterToken::UNEXPECTED_END));
  212. }
  213. assert(expect == MasterToken::NUMBER);
  214. throw LexerError(__FILE__, __LINE__,
  215. MasterToken(MasterToken::BAD_NUMBER));
  216. }
  217. return (impl_->token_);
  218. }
  219. void
  220. MasterLexer::ungetToken() {
  221. if (impl_->has_previous_) {
  222. impl_->has_previous_ = false;
  223. impl_->source_->ungetAll();
  224. impl_->last_was_eol_ = impl_->previous_was_eol_;
  225. impl_->paren_count_ = impl_->previous_paren_count_;
  226. } else {
  227. isc_throw(isc::InvalidOperation, "No token to unget ready");
  228. }
  229. }
  230. namespace {
  231. const char* const error_text[] = {
  232. "lexer not started", // NOT_STARTED
  233. "unbalanced parentheses", // UNBALANCED_PAREN
  234. "unexpected end of input", // UNEXPECTED_END
  235. "unbalanced quotes", // UNBALANCED_QUOTES
  236. "no token produced", // NO_TOKEN_PRODUCED
  237. "number out of range", // NUMBER_OUT_OF_RANGE
  238. "not a valid number" // BAD_NUMBER
  239. };
  240. const size_t error_text_max_count = sizeof(error_text) / sizeof(error_text[0]);
  241. } // end unnamed namespace
  242. std::string
  243. MasterToken::getErrorText() const {
  244. if (type_ != ERROR) {
  245. isc_throw(InvalidOperation,
  246. "MasterToken::getErrorText() for non error type");
  247. }
  248. // The class integrity ensures the following:
  249. assert(val_.error_code_ < error_text_max_count);
  250. return (error_text[val_.error_code_]);
  251. }
  252. namespace master_lexer_internal {
  253. // Below we implement state classes for state transitions of MasterLexer.
  254. // Note that these need to be defined here so that they can refer to
  255. // the details of MasterLexerImpl.
  256. bool
  257. State::wasLastEOL(const MasterLexer& lexer) const {
  258. return (lexer.impl_->last_was_eol_);
  259. }
  260. const MasterToken&
  261. State::getToken(const MasterLexer& lexer) const {
  262. return (lexer.impl_->token_);
  263. }
  264. size_t
  265. State::getParenCount(const MasterLexer& lexer) const {
  266. return (lexer.impl_->paren_count_);
  267. }
  268. namespace {
  269. class CRLF : public State {
  270. public:
  271. CRLF() {}
  272. virtual ~CRLF() {} // see the base class for the destructor
  273. virtual void handle(MasterLexer& lexer) const {
  274. // We've just seen '\r'. If this is part of a sequence of '\r\n',
  275. // we combine them as a single END-OF-LINE. Otherwise we treat the
  276. // single '\r' as an EOL and continue tokeniziation from the character
  277. // immediately after '\r'. One tricky case is that there's a comment
  278. // between '\r' and '\n'. This implementation combines these
  279. // characters and treats them as a single EOL (the behavior derived
  280. // from BIND 9). Technically this may not be correct, but in practice
  281. // the caller wouldn't distinguish this case from the case it has
  282. // two EOLs, so we simplify the process.
  283. const int c = getLexerImpl(lexer)->skipComment(
  284. getLexerImpl(lexer)->source_->getChar());
  285. if (c != '\n') {
  286. getLexerImpl(lexer)->source_->ungetChar();
  287. }
  288. getLexerImpl(lexer)->token_ = MasterToken(MasterToken::END_OF_LINE);
  289. getLexerImpl(lexer)->last_was_eol_ = true;
  290. }
  291. };
  292. class String : public State {
  293. public:
  294. String() {}
  295. virtual ~String() {} // see the base class for the destructor
  296. virtual void handle(MasterLexer& lexer) const;
  297. };
  298. class QString : public State {
  299. public:
  300. QString() {}
  301. virtual ~QString() {} // see the base class for the destructor
  302. virtual void handle(MasterLexer& lexer) const;
  303. };
  304. class Number : public State {
  305. public:
  306. Number() {}
  307. virtual ~Number() {}
  308. virtual void handle(MasterLexer& lexer) const;
  309. };
  310. // We use a common instance of a each state in a singleton-like way to save
  311. // construction overhead. They are not singletons in its strict sense as
  312. // we don't prohibit direct construction of these objects. But that doesn't
  313. // matter much anyway, because the definitions are completely hidden within
  314. // this file.
  315. const CRLF CRLF_STATE;
  316. const String STRING_STATE;
  317. const QString QSTRING_STATE;
  318. const Number NUMBER_STATE;
  319. } // end unnamed namespace
  320. const State&
  321. State::getInstance(ID state_id) {
  322. switch (state_id) {
  323. case CRLF:
  324. return (CRLF_STATE);
  325. case String:
  326. return (STRING_STATE);
  327. case QString:
  328. return (QSTRING_STATE);
  329. case Number:
  330. return (NUMBER_STATE);
  331. }
  332. // This is a bug of the caller, and this method is only expected to be
  333. // used by tests, so we just forcefully make it fail by asserting the
  334. // condition.
  335. assert(false);
  336. return (STRING_STATE); // a dummy return, to silence some compilers.
  337. }
  338. const State*
  339. State::start(MasterLexer& lexer, MasterLexer::Options options) {
  340. // define some shortcuts
  341. MasterLexer::MasterLexerImpl& lexerimpl = *lexer.impl_;
  342. size_t& paren_count = lexerimpl.paren_count_;
  343. // Note: the if-else in the loop is getting complicated. When we complete
  344. // #2374, revisit the organization to see if we need a fundamental
  345. // refactoring.
  346. while (true) {
  347. const int c = lexerimpl.skipComment(lexerimpl.source_->getChar());
  348. if (c == InputSource::END_OF_STREAM) {
  349. lexerimpl.last_was_eol_ = false;
  350. if (paren_count != 0) {
  351. lexerimpl.token_ = MasterToken(MasterToken::UNBALANCED_PAREN);
  352. paren_count = 0; // reset to 0; this helps in lenient mode.
  353. return (NULL);
  354. }
  355. lexerimpl.token_ = MasterToken(MasterToken::END_OF_FILE);
  356. return (NULL);
  357. } else if (c == ' ' || c == '\t') {
  358. // If requested and we are not in (), recognize the initial space.
  359. if (lexerimpl.last_was_eol_ && paren_count == 0 &&
  360. (options & MasterLexer::INITIAL_WS) != 0) {
  361. lexerimpl.last_was_eol_ = false;
  362. lexerimpl.token_ = MasterToken(MasterToken::INITIAL_WS);
  363. return (NULL);
  364. }
  365. } else if (c == '\n') {
  366. lexerimpl.last_was_eol_ = true;
  367. if (paren_count == 0) { // we don't recognize EOL if we are in ()
  368. lexerimpl.token_ = MasterToken(MasterToken::END_OF_LINE);
  369. return (NULL);
  370. }
  371. } else if (c == '\r') {
  372. if (paren_count == 0) { // check if we are in () (see above)
  373. return (&CRLF_STATE);
  374. }
  375. } else if (c == '"' && (options & MasterLexer::QSTRING) != 0) {
  376. lexerimpl.last_was_eol_ = false;
  377. return (&QSTRING_STATE);
  378. } else if (c == '(') {
  379. lexerimpl.last_was_eol_ = false;
  380. ++paren_count;
  381. } else if (c == ')') {
  382. lexerimpl.last_was_eol_ = false;
  383. if (paren_count == 0) {
  384. lexerimpl.token_ = MasterToken(MasterToken::UNBALANCED_PAREN);
  385. return (NULL);
  386. }
  387. --paren_count;
  388. } else if ((options & MasterLexer::NUMBER) != 0 &&isdigit(c)) {
  389. lexerimpl.last_was_eol_ = false;
  390. // this character will be handled in the number state
  391. lexerimpl.source_->ungetChar();
  392. return (&NUMBER_STATE);
  393. } else {
  394. // this character will be handled in the string state
  395. lexerimpl.source_->ungetChar();
  396. lexerimpl.last_was_eol_ = false;
  397. return (&STRING_STATE);
  398. }
  399. // no code should be here; we just continue the loop.
  400. }
  401. }
  402. void
  403. String::handle(MasterLexer& lexer) const {
  404. std::vector<char>& data = getLexerImpl(lexer)->data_;
  405. data.clear();
  406. bool escaped = false;
  407. while (true) {
  408. const int c = getLexerImpl(lexer)->skipComment(
  409. getLexerImpl(lexer)->source_->getChar(), escaped);
  410. if (getLexerImpl(lexer)->isTokenEnd(c, escaped)) {
  411. getLexerImpl(lexer)->source_->ungetChar();
  412. // make sure it nul-terminated as a c-str (excluded from token
  413. // data).
  414. data.push_back('\0');
  415. getLexerImpl(lexer)->token_ =
  416. MasterToken(&data.at(0), data.size() - 1);
  417. return;
  418. }
  419. escaped = (c == '\\' && !escaped);
  420. data.push_back(c);
  421. }
  422. }
  423. void
  424. QString::handle(MasterLexer& lexer) const {
  425. MasterToken& token = getLexerImpl(lexer)->token_;
  426. std::vector<char>& data = getLexerImpl(lexer)->data_;
  427. data.clear();
  428. bool escaped = false;
  429. while (true) {
  430. const int c = getLexerImpl(lexer)->source_->getChar();
  431. if (c == InputSource::END_OF_STREAM) {
  432. token = MasterToken(MasterToken::UNEXPECTED_END);
  433. return;
  434. } else if (c == '"') {
  435. if (escaped) {
  436. // found escaped '"'. overwrite the preceding backslash.
  437. assert(!data.empty());
  438. escaped = false;
  439. data.back() = '"';
  440. } else {
  441. // make sure it nul-terminated as a c-str (excluded from token
  442. // data). This also simplifies the case of an empty string.
  443. data.push_back('\0');
  444. token = MasterToken(&data.at(0), data.size() - 1, true);
  445. return;
  446. }
  447. } else if (c == '\n' && !escaped) {
  448. getLexerImpl(lexer)->source_->ungetChar();
  449. token = MasterToken(MasterToken::UNBALANCED_QUOTES);
  450. return;
  451. } else {
  452. escaped = (c == '\\' && !escaped);
  453. data.push_back(c);
  454. }
  455. }
  456. }
  457. void
  458. Number::handle(MasterLexer& lexer) const {
  459. MasterToken& token = getLexerImpl(lexer)->token_;
  460. // It may yet turn out to be a string, so we first
  461. // collect all the data
  462. bool digits_only = true;
  463. std::vector<char>& data = getLexerImpl(lexer)->data_;
  464. data.clear();
  465. bool escaped = false;
  466. while (true) {
  467. const int c = getLexerImpl(lexer)->skipComment(
  468. getLexerImpl(lexer)->source_->getChar(), escaped);
  469. if (getLexerImpl(lexer)->isTokenEnd(c, escaped)) {
  470. getLexerImpl(lexer)->source_->ungetChar();
  471. // We need to close the string whether it's digits-only (for
  472. // lexical_cast) or not (see String::handle()).
  473. data.push_back('\0');
  474. if (digits_only) {
  475. try {
  476. const uint32_t number32 =
  477. boost::lexical_cast<uint32_t, const char*>(&data[0]);
  478. token = MasterToken(number32);
  479. } catch (const boost::bad_lexical_cast&) {
  480. // Since we already know we have only digits,
  481. // range should be the only possible problem.
  482. token = MasterToken(MasterToken::NUMBER_OUT_OF_RANGE);
  483. }
  484. } else {
  485. token = MasterToken(&data.at(0), data.size() - 1);
  486. }
  487. return;
  488. }
  489. if (!isdigit(c)) {
  490. digits_only = false;
  491. }
  492. escaped = (c == '\\' && !escaped);
  493. data.push_back(c);
  494. }
  495. }
  496. } // namespace master_lexer_internal
  497. } // end of namespace dns
  498. } // end of namespace isc