move LyXerr QString specialisation to support/qstring_helpers
[lyx.git] / src / Lexer.cpp
blob108d26ba2caacd77194429203808638eeb6e6bcf
1 /**
2 * \file Lexer.cpp
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
9 * \author John Levon
11 * Full author contact details are available in file CREDITS.
14 #include <config.h>
16 #include "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/lstrings.h"
24 #include "support/lyxalgo.h"
25 #include "support/types.h"
27 #include <functional>
28 #include <istream>
29 #include <stack>
30 #include <vector>
32 using namespace std;
33 using namespace lyx::support;
35 namespace lyx {
37 //////////////////////////////////////////////////////////////////////
39 // Lexer::Pimpl
41 //////////////////////////////////////////////////////////////////////
44 ///
45 class Lexer::Pimpl {
46 public:
47 ///
48 Pimpl(LexerKeyword * tab, int num);
49 ///
50 string const getString() const;
51 ///
52 docstring const getDocString() const;
53 ///
54 void printError(string const & message) const;
55 ///
56 void printTable(ostream & os);
57 ///
58 void pushTable(LexerKeyword * tab, int num);
59 ///
60 void popTable();
61 ///
62 bool setFile(FileName const & filename);
63 ///
64 void setStream(istream & i);
65 ///
66 void setCommentChar(char c);
67 ///
68 bool next(bool esc = false);
69 ///
70 int searchKeyword(char const * const tag) const;
71 ///
72 int lex();
73 ///
74 bool eatLine();
75 ///
76 bool nextToken();
77 /// test if there is a pushed token or the stream is ok
78 bool inputAvailable();
79 ///
80 void pushToken(string const &);
81 /// fb_ is only used to open files, the stream is accessed through is.
82 filebuf fb_;
84 /// gz_ is only used to open files, the stream is accessed through is.
85 gz::gzstreambuf gz_;
87 /// the stream that we use.
88 istream is;
89 ///
90 string name;
91 ///
92 LexerKeyword * table;
93 ///
94 int no_items;
95 ///
96 string buff;
97 ///
98 int status;
99 ///
100 int lineno;
102 string pushTok;
104 char commentChar;
105 /// used for error messages
106 string context;
107 private:
108 /// non-copyable
109 Pimpl(Pimpl const &);
110 void operator=(Pimpl const &);
113 void verifyTable();
115 class PushedTable {
116 public:
118 PushedTable()
119 : table_elem(0), table_siz(0) {}
121 PushedTable(LexerKeyword * ki, int siz)
122 : table_elem(ki), table_siz(siz) {}
124 LexerKeyword * table_elem;
126 int table_siz;
129 stack<PushedTable> pushed;
134 namespace {
136 class CompareTags
137 : public binary_function<LexerKeyword, LexerKeyword, bool> {
138 public:
139 // used by lower_bound, sort and sorted
140 bool operator()(LexerKeyword const & a, LexerKeyword const & b) const
142 // we use the ascii version, because in turkish, 'i'
143 // is not the lowercase version of 'I', and thus
144 // turkish locale breaks parsing of tags.
145 return compare_ascii_no_case(a.tag, b.tag) < 0;
149 } // end of anon namespace
152 Lexer::Pimpl::Pimpl(LexerKeyword * tab, int num)
153 : is(&fb_), table(tab), no_items(num),
154 status(0), lineno(0), commentChar('#')
156 verifyTable();
160 string const Lexer::Pimpl::getString() const
162 return buff;
166 docstring const Lexer::Pimpl::getDocString() const
168 return from_utf8(buff);
172 void Lexer::Pimpl::printError(string const & message) const
174 string const tmpmsg = subst(message, "$$Token", getString());
175 lyxerr << "LyX: " << tmpmsg << " [around line " << lineno
176 << " of file " << to_utf8(makeDisplayPath(name))
177 << " current token: '" << getString() << "'"
178 << " context: '" << context << "']" << endl;
182 void Lexer::Pimpl::printTable(ostream & os)
184 os << "\nNumber of tags: " << no_items << endl;
185 for (int i= 0; i < no_items; ++i)
186 os << "table[" << i
187 << "]: tag: `" << table[i].tag
188 << "' code:" << table[i].code << '\n';
189 os.flush();
193 void Lexer::Pimpl::verifyTable()
195 // Check if the table is sorted and if not, sort it.
196 if (table
197 && !lyx::sorted(table, table + no_items, CompareTags())) {
198 lyxerr << "The table passed to Lexer is not sorted!\n"
199 << "Tell the developers to fix it!" << endl;
200 // We sort it anyway to avoid problems.
201 lyxerr << "\nUnsorted:" << endl;
202 printTable(lyxerr);
204 sort(table, table + no_items, CompareTags());
205 lyxerr << "\nSorted:" << endl;
206 printTable(lyxerr);
211 void Lexer::Pimpl::pushTable(LexerKeyword * tab, int num)
213 PushedTable tmppu(table, no_items);
214 pushed.push(tmppu);
216 table = tab;
217 no_items = num;
219 verifyTable();
223 void Lexer::Pimpl::popTable()
225 if (pushed.empty()) {
226 lyxerr << "Lexer error: nothing to pop!" << endl;
227 return;
230 PushedTable tmp = pushed.top();
231 pushed.pop();
232 table = tmp.table_elem;
233 no_items = tmp.table_siz;
237 bool Lexer::Pimpl::setFile(FileName const & filename)
239 // Check the format of the file.
240 string const format = filename.guessFormatFromContents();
242 if (format == "gzip" || format == "zip" || format == "compress") {
243 LYXERR(Debug::LYXLEX, "lyxlex: compressed");
244 // The check only outputs a debug message, because it triggers
245 // a bug in compaq cxx 6.2, where is_open() returns 'true' for
246 // a fresh new filebuf. (JMarc)
247 if (gz_.is_open() || istream::off_type(is.tellg()) > -1)
248 LYXERR(Debug::LYXLEX, "Error in LyXLex::setFile: "
249 "file or stream already set.");
250 gz_.open(filename.toFilesystemEncoding().c_str(), ios::in);
251 is.rdbuf(&gz_);
252 name = filename.absFilename();
253 lineno = 0;
254 return gz_.is_open() && is.good();
255 } else {
256 LYXERR(Debug::LYXLEX, "lyxlex: UNcompressed");
258 // The check only outputs a debug message, because it triggers
259 // a bug in compaq cxx 6.2, where is_open() returns 'true' for
260 // a fresh new filebuf. (JMarc)
261 if (fb_.is_open() || istream::off_type(is.tellg()) > 0) {
262 LYXERR(Debug::LYXLEX, "Error in Lexer::setFile: "
263 "file or stream already set.");
265 fb_.open(filename.toFilesystemEncoding().c_str(), ios::in);
266 is.rdbuf(&fb_);
267 name = filename.absFilename();
268 lineno = 0;
269 return fb_.is_open() && is.good();
274 void Lexer::Pimpl::setStream(istream & i)
276 if (fb_.is_open() || istream::off_type(is.tellg()) > 0) {
277 LYXERR(Debug::LYXLEX, "Error in Lexer::setStream: "
278 "file or stream already set.");
280 is.rdbuf(i.rdbuf());
281 lineno = 0;
285 void Lexer::Pimpl::setCommentChar(char c)
287 commentChar = c;
291 bool Lexer::Pimpl::next(bool esc /* = false */)
293 if (!pushTok.empty()) {
294 // There can have been a whole line pushed so
295 // we extract the first word and leaves the rest
296 // in pushTok. (Lgb)
297 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
298 buff.clear();
299 pushTok = split(pushTok, buff, ' ');
300 } else {
301 buff = pushTok;
302 pushTok.clear();
304 status = LEX_TOKEN;
305 return true;
309 unsigned char c = 0; // getc() returns an int
310 char cc = 0;
311 status = 0;
312 while (is && !status) {
313 is.get(cc);
314 c = cc;
316 if (c == commentChar) {
317 // Read rest of line (fast :-)
318 #if 1
319 // That is not fast... (Lgb)
320 string dummy;
321 getline(is, dummy);
323 LYXERR(Debug::LYXLEX, "Comment read: `" << c << dummy << '\'');
324 #else
325 // unfortunately ignore is buggy (Lgb)
326 is.ignore(100, '\n');
327 #endif
328 ++lineno;
329 continue;
332 if (c == '\"') {
333 buff.clear();
335 if (esc) {
337 bool escaped = false;
338 do {
339 escaped = false;
340 is.get(cc);
341 c = cc;
342 if (c == '\r') continue;
343 if (c == '\\') {
344 // escape the next char
345 is.get(cc);
346 c = cc;
347 if (c == '\"' || c == '\\')
348 escaped = true;
349 else
350 buff.push_back('\\');
352 buff.push_back(c);
354 if (!escaped && c == '\"')
355 break;
356 } while (c != '\n' && is);
358 } else {
360 do {
361 is.get(cc);
362 c = cc;
363 if (c != '\r')
364 buff.push_back(c);
365 } while (c != '\"' && c != '\n' && is);
369 if (c != '\"') {
370 printError("Missing quote");
371 if (c == '\n')
372 ++lineno;
375 buff.resize(buff.size() - 1);
376 status = LEX_DATA;
377 break;
380 if (c == ',')
381 continue; /* Skip ','s */
383 // using relational operators with chars other
384 // than == and != is not safe. And if it is done
385 // the type _have_ to be unsigned. It usually a
386 // lot better to use the functions from cctype
387 if (c > ' ' && is) {
388 buff.clear();
390 do {
391 if (esc && c == '\\') {
392 // escape the next char
393 is.get(cc);
394 c = cc;
395 //escaped = true;
397 buff.push_back(c);
398 is.get(cc);
399 c = cc;
400 } while (c > ' ' && c != ',' && is);
401 status = LEX_TOKEN;
404 if (c == '\r' && is) {
405 // The Windows support has lead to the
406 // possibility of "\r\n" at the end of
407 // a line. This will stop LyX choking
408 // when it expected to find a '\n'
409 is.get(cc);
410 c = cc;
413 if (c == '\n')
414 ++lineno;
417 if (status)
418 return true;
420 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
421 buff.clear();
422 return false;
426 int Lexer::Pimpl::searchKeyword(char const * const tag) const
428 LexerKeyword search_tag = { tag, 0 };
429 LexerKeyword * res =
430 lower_bound(table, table + no_items,
431 search_tag, CompareTags());
432 // use the compare_ascii_no_case instead of compare_no_case,
433 // because in turkish, 'i' is not the lowercase version of 'I',
434 // and thus turkish locale breaks parsing of tags.
435 if (res != table + no_items
436 && !compare_ascii_no_case(res->tag, tag))
437 return res->code;
438 return LEX_UNDEF;
442 int Lexer::Pimpl::lex()
444 //NOTE: possible bug.
445 if (next() && status == LEX_TOKEN)
446 return searchKeyword(getString().c_str());
447 return status;
451 bool Lexer::Pimpl::eatLine()
453 buff.clear();
455 unsigned char c = '\0';
456 char cc = 0;
457 while (is && c != '\n') {
458 is.get(cc);
459 c = cc;
460 //LYXERR(Debug::LYXLEX, "Lexer::EatLine read char: `" << c << '\'');
461 if (c != '\r')
462 buff.push_back(c);
465 if (c == '\n') {
466 ++lineno;
467 buff.resize(buff.size() - 1);
468 status = LEX_DATA;
469 return true;
470 } else if (buff.length() > 0) { // last line
471 status = LEX_DATA;
472 return true;
473 } else {
474 return false;
479 bool Lexer::Pimpl::nextToken()
481 if (!pushTok.empty()) {
482 // There can have been a whole line pushed so
483 // we extract the first word and leaves the rest
484 // in pushTok. (Lgb)
485 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
486 buff.clear();
487 pushTok = split(pushTok, buff, ' ');
488 } else {
489 buff = pushTok;
490 pushTok.clear();
492 status = LEX_TOKEN;
493 return true;
496 status = 0;
497 while (is && !status) {
498 unsigned char c = 0;
499 char cc = 0;
500 is.get(cc);
501 c = cc;
502 if (c >= ' ' && is) {
503 buff.clear();
505 if (c == '\\') { // first char == '\\'
506 do {
507 buff.push_back(c);
508 is.get(cc);
509 c = cc;
510 } while (c > ' ' && c != '\\' && is);
511 } else {
512 do {
513 buff.push_back(c);
514 is.get(cc);
515 c = cc;
516 } while (c >= ' ' && c != '\\' && is);
519 if (c == '\\')
520 is.putback(c); // put it back
521 status = LEX_TOKEN;
524 if (c == '\n')
525 ++lineno;
528 if (status)
529 return true;
531 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
532 buff.clear();
533 return false;
537 bool Lexer::Pimpl::inputAvailable()
539 return is.good();
543 void Lexer::Pimpl::pushToken(string const & pt)
545 pushTok = pt;
551 //////////////////////////////////////////////////////////////////////
553 // Lexer
555 //////////////////////////////////////////////////////////////////////
557 Lexer::Lexer()
558 : pimpl_(new Pimpl(0, 0))
562 void Lexer::init(LexerKeyword * tab, int num)
564 pimpl_ = new Pimpl(tab, num);
568 Lexer::~Lexer()
570 delete pimpl_;
574 bool Lexer::isOK() const
576 return pimpl_->inputAvailable();
580 void Lexer::setLineNumber(int l)
582 pimpl_->lineno = l;
586 int Lexer::lineNumber() const
588 return pimpl_->lineno;
592 istream & Lexer::getStream()
594 return pimpl_->is;
598 void Lexer::pushTable(LexerKeyword * tab, int num)
600 pimpl_->pushTable(tab, num);
604 void Lexer::popTable()
606 pimpl_->popTable();
610 void Lexer::printTable(ostream & os)
612 pimpl_->printTable(os);
616 void Lexer::printError(string const & message) const
618 pimpl_->printError(message);
622 bool Lexer::setFile(FileName const & filename)
624 return pimpl_->setFile(filename);
628 void Lexer::setStream(istream & i)
630 pimpl_->setStream(i);
634 void Lexer::setCommentChar(char c)
636 pimpl_->setCommentChar(c);
640 int Lexer::lex()
642 return pimpl_->lex();
646 int Lexer::getInteger() const
648 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
649 if (!lastReadOk_) {
650 pimpl_->printError("integer token missing");
651 return -1;
654 if (isStrInt(pimpl_->getString()))
655 return convert<int>(pimpl_->getString());
657 lastReadOk_ = false;
658 pimpl_->printError("Bad integer `$$Token'");
659 return -1;
663 double Lexer::getFloat() const
665 // replace comma with dot in case the file was written with
666 // the wrong locale (should be rare, but is easy enough to
667 // avoid).
668 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
669 if (!lastReadOk_) {
670 pimpl_->printError("float token missing");
671 return -1;
674 string const str = subst(pimpl_->getString(), ",", ".");
675 if (isStrDbl(str))
676 return convert<double>(str);
678 lastReadOk_ = false;
679 pimpl_->printError("Bad float `$$Token'");
680 return -1;
684 string const Lexer::getString() const
686 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
688 if (lastReadOk_)
689 return pimpl_->getString();
691 return string();
695 docstring const Lexer::getDocString() const
697 lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
699 if (lastReadOk_)
700 return pimpl_->getDocString();
702 return docstring();
706 // I would prefer to give a tag number instead of an explicit token
707 // here, but it is not possible because Buffer::readDocument uses
708 // explicit tokens (JMarc)
709 string const Lexer::getLongString(string const & endtoken)
711 string str;
712 string prefix;
713 bool firstline = true;
715 while (pimpl_->is) { //< eatLine only reads from is, not from pushTok
716 if (!eatLine())
717 // blank line in the file being read
718 continue;
720 string const token = trim(getString(), " \t");
722 LYXERR(Debug::PARSER, "LongString: `" << getString() << '\'');
724 // We do a case independent comparison, like searchKeyword does.
725 if (compare_ascii_no_case(token, endtoken) == 0)
726 break;
728 string tmpstr = getString();
729 if (firstline) {
730 size_t i = tmpstr.find_first_not_of(' ');
731 if (i != string::npos)
732 prefix = tmpstr.substr(0, i);
733 firstline = false;
734 LYXERR(Debug::PARSER, "Prefix = `" << prefix << "\'");
737 // further lines in long strings may have the same
738 // whitespace prefix as the first line. Remove it.
739 if (prefix.length() && prefixIs(tmpstr, prefix))
740 tmpstr.erase(0, prefix.length() - 1);
742 str += ltrim(tmpstr, "\t") + '\n';
745 if (!pimpl_->is)
746 printError("Long string not ended by `" + endtoken + '\'');
748 return str;
752 bool Lexer::getBool() const
754 string const s = pimpl_->getString();
755 if (s == "false" || s == "0") {
756 lastReadOk_ = true;
757 return false;
759 if (s == "true" || s == "1") {
760 lastReadOk_ = true;
761 return true;
763 pimpl_->printError("Bad boolean `$$Token'. "
764 "Use \"false\" or \"true\"");
765 lastReadOk_ = false;
766 return false;
770 bool Lexer::eatLine()
772 return pimpl_->eatLine();
776 bool Lexer::next(bool esc)
778 return pimpl_->next(esc);
782 bool Lexer::nextToken()
784 return pimpl_->nextToken();
788 void Lexer::pushToken(string const & pt)
790 pimpl_->pushToken(pt);
794 Lexer::operator void const *() const
796 // This behaviour is NOT the same as the streams which would
797 // use fail() here. However, our implementation of getString() et al.
798 // can cause the eof() and fail() bits to be set, even though we
799 // haven't tried to read 'em.
800 return lastReadOk_? this : 0;
804 bool Lexer::operator!() const
806 return !lastReadOk_;
810 Lexer & Lexer::operator>>(string & s)
812 if (isOK()) {
813 next();
814 s = getString();
815 } else {
816 lastReadOk_ = false;
818 return *this;
822 Lexer & Lexer::operator>>(docstring & s)
824 if (isOK()) {
825 next();
826 s = getDocString();
827 } else {
828 lastReadOk_ = false;
830 return *this;
834 Lexer & Lexer::operator>>(double & s)
836 if (isOK()) {
837 next();
838 s = getFloat();
839 } else {
840 lastReadOk_ = false;
842 return *this;
846 Lexer & Lexer::operator>>(int & s)
848 if (isOK()) {
849 next();
850 s = getInteger();
851 } else {
852 lastReadOk_ = false;
854 return *this;
858 Lexer & Lexer::operator>>(unsigned int & s)
860 if (isOK()) {
861 next();
862 s = getInteger();
863 } else {
864 lastReadOk_ = false;
866 return *this;
870 Lexer & Lexer::operator>>(bool & s)
872 if (isOK()) {
873 next();
874 s = getBool();
875 } else {
876 lastReadOk_ = false;
878 return *this;
882 Lexer & Lexer::operator>>(char & c)
884 string s;
885 operator>>(s);
886 if (!s.empty())
887 c = s[0];
888 return *this;
892 // quotes a string, e.g. for use in preferences files or as an argument
893 // of the "log" dialog
894 string Lexer::quoteString(string const & arg)
896 string res;
897 res += '"';
898 res += subst(subst(arg, "\\", "\\\\"), "\"", "\\\"");
899 res += '"';
900 return res;
904 Lexer & Lexer::operator>>(char const * required)
906 string token;
907 *this >> token;
908 if (token != required) {
909 LYXERR0("Missing '" << required << "'-tag in " << pimpl_->context
910 << ". Got " << token << " instead. Line: " << lineNumber());
911 pushToken(token);
913 return *this;
917 bool Lexer::checkFor(char const * required)
919 string token;
920 *this >> token;
921 if (token == required)
922 return true;
923 pushToken(token);
924 return false;
928 void Lexer::setContext(std::string const & str)
930 pimpl_->context = str;
934 } // namespace lyx