3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alejandro Aguilar Sierra
7 * \author Lars Gullik Bjønnes
8 * \author Jean-Marc Lasgouttes
11 * Full author contact details are available in file CREDITS.
16 #include "support/Lexer.h"
18 #include "support/convert.h"
19 #include "support/debug.h"
20 #include "support/FileName.h"
21 #include "support/filetools.h"
22 #include "support/gzstream.h"
23 #include "support/lassert.h"
24 #include "support/lstrings.h"
25 #include "support/lyxalgo.h"
27 #include <algorithm> // sort, lower_bound
40 //////////////////////////////////////////////////////////////////////
44 //////////////////////////////////////////////////////////////////////
51 Pimpl(LexerKeyword * tab, int num);
53 string const getString() const;
55 docstring const getDocString() const;
57 void printError(string const & message) const;
59 void printTable(ostream & os);
61 void pushTable(LexerKeyword * tab, int num);
65 bool setFile(FileName const & filename);
67 void setStream(istream & i);
69 void setCommentChar(char c);
71 bool next(bool esc = false);
73 int searchKeyword(char const * const tag) const;
80 /// test if there is a pushed token or the stream is ok
81 bool inputAvailable();
83 void pushToken(string const &);
84 /// gz_ is only used to open files, the stream is accessed through is.
87 /// the stream that we use.
103 /// used for error messages
109 Pimpl(Pimpl const &);
110 void operator=(Pimpl const &);
119 : table_elem(nullptr), table_siz(0) {}
121 PushedTable(LexerKeyword * ki, int siz)
122 : table_elem(ki), table_siz(siz) {}
124 LexerKeyword * table_elem;
129 stack<PushedTable> pushed;
135 // used by lower_bound, sort and sorted
136 bool compareTags(LexerKeyword const & a, LexerKeyword const & b)
138 // we use the ascii version, because in turkish, 'i'
139 // is not the lowercase version of 'I', and thus
140 // turkish locale breaks parsing of tags.
141 return compare_ascii_no_case(a.tag, b.tag) < 0;
148 Lexer::Pimpl::Pimpl(LexerKeyword * tab, int num)
149 : is(&gz_), table(tab), no_items(num),
150 status(0), lineno(0), commentChar('#')
156 string const Lexer::Pimpl::getString() const
162 docstring const Lexer::Pimpl::getDocString() const
164 return from_utf8(buff);
168 void Lexer::Pimpl::printError(string const & message) const
170 string const tmpmsg = subst(message, "$$Token", getString());
171 lyxerr << "LyX: " << tmpmsg << " [around line " << lineno
172 << " of file " << to_utf8(makeDisplayPath(name))
173 << " current token: '" << getString() << "'"
174 << " context: '" << context << "']" << endl;
178 void Lexer::Pimpl::printTable(ostream & os)
180 os << "\nNumber of tags: " << no_items << endl;
181 for (int i= 0; i < no_items; ++i)
183 << "]: tag: `" << table[i].tag
184 << "' code:" << table[i].code << '\n';
189 void Lexer::Pimpl::verifyTable()
191 // Check if the table is sorted and if not, sort it.
193 && !lyx::sorted(table, table + no_items, &compareTags)) {
194 lyxerr << "The table passed to Lexer is not sorted!\n"
195 << "Tell the developers to fix it!" << endl;
196 // We sort it anyway to avoid problems.
197 lyxerr << "\nUnsorted:" << endl;
200 sort(table, table + no_items, &compareTags);
201 lyxerr << "\nSorted:" << endl;
207 void Lexer::Pimpl::pushTable(LexerKeyword * tab, int num)
209 PushedTable tmppu(table, no_items);
219 void Lexer::Pimpl::popTable()
221 if (pushed.empty()) {
222 lyxerr << "Lexer error: nothing to pop!" << endl;
226 PushedTable tmp = pushed.top();
228 table = tmp.table_elem;
229 no_items = tmp.table_siz;
233 bool Lexer::Pimpl::setFile(FileName const & filename)
235 if (gz_.is_open() || istream::off_type(is.tellg()) > -1)
236 LYXERR0("Error in LyXLex::setFile: file or stream already set.");
237 gz_.open(filename.toSafeFilesystemEncoding().c_str(), ios::in);
239 name = filename.absFileName();
241 if (!gz_.is_open() || !is.good())
244 // Skip byte order mark.
245 if (is.peek() == 0xef) {
247 if (is.peek() == 0xbb) {
249 LASSERT(is.get() == 0xbf, /**/);
258 void Lexer::Pimpl::setStream(istream & i)
260 if (gz_.is_open() || istream::off_type(is.tellg()) > 0)
261 LYXERR0("Error in Lexer::setStream: file or stream already set.");
267 void Lexer::Pimpl::setCommentChar(char c)
273 bool Lexer::Pimpl::next(bool esc /* = false */)
275 if (!pushTok.empty()) {
276 // There can have been a whole line pushed so
277 // we extract the first word and leaves the rest
279 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
281 pushTok = split(pushTok, buff, ' ');
293 while (is && !status) {
295 unsigned char c = cc;
297 if (c == commentChar) {
298 // Read rest of line (fast :-)
300 // That is not fast... (Lgb)
304 LYXERR(Debug::LYXLEX, "Comment read: `" << string(1, c) << dummy << '\'');
306 // unfortunately ignore is buggy (Lgb)
307 is.ignore(100, '\n');
319 bool escaped = false;
322 if (c == '\r') continue;
324 // escape the next char
327 if (c == '\"' || c == '\\')
330 buff.push_back('\\');
334 if (!escaped && c == '\"')
336 } while (c != '\n' && is);
345 } while (c != '\"' && c != '\n' && is);
350 printError("Missing quote");
355 buff.resize(buff.size() - 1);
361 continue; /* Skip ','s */
363 // using relational operators with chars other
364 // than == and != is not safe. And if it is done
365 // the type _have_ to be unsigned. It usually a
366 // lot better to use the functions from cctype
371 if (esc && c == '\\') {
372 // escape the next char
380 } while (c > ' ' && c != ',' && is);
384 if (c == '\r' && is) {
385 // The Windows support has lead to the
386 // possibility of "\r\n" at the end of
387 // a line. This will stop LyX choking
388 // when it expected to find a '\n'
400 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
406 int Lexer::Pimpl::searchKeyword(char const * const tag) const
408 LexerKeyword search_tag = { tag, 0 };
410 lower_bound(table, table + no_items,
411 search_tag, &compareTags);
412 // use the compare_ascii_no_case instead of compare_no_case,
413 // because in turkish, 'i' is not the lowercase version of 'I',
414 // and thus turkish locale breaks parsing of tags.
415 if (res != table + no_items
416 && !compare_ascii_no_case(res->tag, tag))
422 int Lexer::Pimpl::lex()
424 //NOTE: possible bug.
425 if (next() && status == LEX_TOKEN)
426 return searchKeyword(getString().c_str());
431 bool Lexer::Pimpl::eatLine()
435 unsigned char c = '\0';
437 while (is && c != '\n') {
440 //LYXERR(Debug::LYXLEX, "Lexer::EatLine read char: `" << c << '\'');
447 buff.resize(buff.size() - 1);
450 } else if (buff.length() > 0) { // last line
459 bool Lexer::Pimpl::nextToken()
461 if (!pushTok.empty()) {
462 // There can have been a whole line pushed so
463 // we extract the first word and leaves the rest
465 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
467 pushTok = split(pushTok, buff, ' ');
477 while (is && !status) {
482 if ((c >= ' ' || c == '\t') && is) {
485 if (c == '\\') { // first char == '\\'
490 } while (c > ' ' && c != '\\' && is);
496 } while ((c >= ' ' || c == '\t') && c != '\\' && is);
500 is.putback(c); // put it back
511 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
517 bool Lexer::Pimpl::inputAvailable()
523 void Lexer::Pimpl::pushToken(string const & pt)
531 //////////////////////////////////////////////////////////////////////
535 //////////////////////////////////////////////////////////////////////
538 : pimpl_(new Pimpl(nullptr, 0)), lastReadOk_(false)
542 void Lexer::init(LexerKeyword * tab, int num)
544 pimpl_ = new Pimpl(tab, num);
554 bool Lexer::isOK() const
556 return pimpl_->inputAvailable();
560 void Lexer::setLineNumber(int l)
566 int Lexer::lineNumber() const
568 return pimpl_->lineno;
572 istream & Lexer::getStream()
578 void Lexer::pushTable(LexerKeyword * tab, int num)
580 pimpl_->pushTable(tab, num);
584 void Lexer::popTable()
590 void Lexer::printTable(ostream & os)
592 pimpl_->printTable(os);
596 void Lexer::printError(string const & message) const
598 pimpl_->printError(message);
602 bool Lexer::setFile(FileName const & filename)
604 return pimpl_->setFile(filename);
608 void Lexer::setStream(istream & i)
610 pimpl_->setStream(i);
614 void Lexer::setCommentChar(char c)
616 pimpl_->setCommentChar(c);
622 return pimpl_->lex();
626 int Lexer::getInteger() const
628 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
630 pimpl_->printError("integer token missing");
634 if (isStrInt(pimpl_->getString()))
635 return convert<int>(pimpl_->getString());
638 pimpl_->printError("Bad integer `$$Token'");
643 double Lexer::getFloat() const
645 // replace comma with dot in case the file was written with
646 // the wrong locale (should be rare, but is easy enough to
648 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
650 pimpl_->printError("float token missing");
654 string const str = subst(pimpl_->getString(), ",", ".");
656 return convert<double>(str);
659 pimpl_->printError("Bad float `$$Token'");
664 string const Lexer::getString(bool trim) const
666 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
669 return trim ? support::trim(pimpl_->getString(), "\t ") : pimpl_->getString();
675 docstring const Lexer::getDocString(bool trim) const
677 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
680 return trim ? support::trim(pimpl_->getDocString(), "\t ") : pimpl_->getDocString();
686 // I would prefer to give a tag number instead of an explicit token
687 // here, but it is not possible because Buffer::readDocument uses
688 // explicit tokens (JMarc)
689 docstring Lexer::getLongString(docstring const & endtoken)
693 bool firstline = true;
694 bool foundend = false;
696 while (pimpl_->is) { //< eatLine only reads from is, not from pushTok
698 // blank line in the file being read
700 docstring tmpstr = getDocString();
701 docstring const token = trim(tmpstr, " \t");
703 LYXERR(Debug::PARSER, "LongString: `" << tmpstr << '\'');
705 // We do a case independent comparison, like searchKeyword does.
706 if (compare_no_case(token, endtoken) == 0) {
712 size_t i = tmpstr.find_first_not_of(from_ascii(" \t"));
713 if (i != string::npos)
714 prefix = tmpstr.substr(0, i);
716 LYXERR(Debug::PARSER, "Prefix = `" << prefix << "\'");
719 // further lines in long strings may have the same
720 // whitespace prefix as the first line. Remove it.
721 if (!prefix.empty() && prefixIs(tmpstr, prefix))
722 tmpstr.erase(0, prefix.length());
724 str += tmpstr + '\n';
728 printError("Long string not ended by `" + to_utf8(endtoken) + '\'');
734 bool Lexer::getBool() const
736 string const s = pimpl_->getString();
737 if (s == "false" || s == "0") {
741 if (s == "true" || s == "1") {
745 pimpl_->printError("Bad boolean `$$Token'. "
746 "Use \"false\" or \"true\"");
752 bool Lexer::eatLine()
754 return pimpl_->eatLine();
758 bool Lexer::next(bool esc)
760 return pimpl_->next(esc);
764 bool Lexer::nextToken()
766 return pimpl_->nextToken();
770 void Lexer::pushToken(string const & pt)
772 pimpl_->pushToken(pt);
776 Lexer::operator void const *() const
778 // This behaviour is NOT the same as the streams which would
779 // use fail() here. However, our implementation of getString() et al.
780 // can cause the eof() and fail() bits to be set, even though we
781 // haven't tried to read 'em.
782 return lastReadOk_? this : nullptr;
786 bool Lexer::operator!() const
792 Lexer & Lexer::operator>>(string & s)
804 Lexer & Lexer::operator>>(docstring & s)
816 Lexer & Lexer::operator>>(double & s)
828 Lexer & Lexer::operator>>(int & s)
840 Lexer & Lexer::operator>>(unsigned int & s)
852 Lexer & Lexer::operator>>(bool & s)
864 Lexer & Lexer::operator>>(char & c)
874 // quotes a string, e.g. for use in preferences files or as an argument
875 // of the "log" dialog
876 string Lexer::quoteString(string const & arg)
880 res += subst(subst(arg, "\\", "\\\\"), "\"", "\\\"");
886 // same for docstring
887 docstring Lexer::quoteString(docstring const & arg)
891 res += subst(subst(arg, from_ascii("\\"), from_ascii("\\\\")),
892 from_ascii("\""), from_ascii("\\\""));
898 Lexer & Lexer::operator>>(char const * required)
902 if (token != required) {
903 LYXERR0("Missing '" << required << "'-tag in " << pimpl_->context
904 << ". Got " << token << " instead. Line: " << lineNumber());
911 bool Lexer::checkFor(char const * required)
915 if (token == required)
922 void Lexer::setContext(std::string const & functionName)
924 pimpl_->context = functionName;
927 } // namespace support