]> git.lyx.org Git - lyx.git/blob - src/support/Lexer.cpp
Move Lexer to support/ directory (and lyx::support namespace)
[lyx.git] / src / support / Lexer.cpp
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.
5  *
6  * \author Alejandro Aguilar Sierra
7  * \author Lars Gullik Bjønnes
8  * \author Jean-Marc Lasgouttes
9  * \author John Levon
10  *
11  * Full author contact details are available in file CREDITS.
12  */
13
14 #include <config.h>
15
16 #include "support/Lexer.h"
17
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"
26
27 #include <algorithm> // sort, lower_bound
28 #include <functional>
29 #include <fstream>
30 #include <istream>
31 #include <stack>
32 #include <vector>
33
34 using namespace std;
35
36 namespace lyx {
37
38 namespace support {
39
40 //////////////////////////////////////////////////////////////////////
41 //
42 // Lexer::Pimpl
43 //
44 //////////////////////////////////////////////////////////////////////
45
46
47 ///
48 class Lexer::Pimpl {
49 public:
50         ///
51         Pimpl(LexerKeyword * tab, int num);
52         ///
53         string const getString() const;
54         ///
55         docstring const getDocString() const;
56         ///
57         void printError(string const & message) const;
58         ///
59         void printTable(ostream & os);
60         ///
61         void pushTable(LexerKeyword * tab, int num);
62         ///
63         void popTable();
64         ///
65         bool setFile(FileName const & filename);
66         ///
67         void setStream(istream & i);
68         ///
69         void setCommentChar(char c);
70         ///
71         bool next(bool esc = false);
72         ///
73         int searchKeyword(char const * const tag) const;
74         ///
75         int lex();
76         ///
77         bool eatLine();
78         ///
79         bool nextToken();
80         /// test if there is a pushed token or the stream is ok
81         bool inputAvailable();
82         ///
83         void pushToken(string const &);
84         /// gz_ is only used to open files, the stream is accessed through is.
85         gz::gzstreambuf gz_;
86
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;
101         ///
102         string pushTok;
103         /// used for error messages
104         string context;
105         ///
106         char commentChar;
107 private:
108         /// non-copyable
109         Pimpl(Pimpl const &);
110         void operator=(Pimpl const &);
111
112         ///
113         void verifyTable();
114         ///
115         class PushedTable {
116         public:
117                 ///
118                 PushedTable()
119                         : table_elem(nullptr), table_siz(0) {}
120                 ///
121                 PushedTable(LexerKeyword * ki, int siz)
122                         : table_elem(ki), table_siz(siz) {}
123                 ///
124                 LexerKeyword * table_elem;
125                 ///
126                 int table_siz;
127         };
128         ///
129         stack<PushedTable> pushed;
130 };
131
132
133 namespace {
134
135 // used by lower_bound, sort and sorted
136 bool compareTags(LexerKeyword const & a, LexerKeyword const & b)
137 {
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;
142 }
143
144 } // namespace
145
146
147
148 Lexer::Pimpl::Pimpl(LexerKeyword * tab, int num)
149         : is(&gz_), table(tab), no_items(num),
150           status(0), lineno(0), commentChar('#')
151 {
152         verifyTable();
153 }
154
155
156 string const Lexer::Pimpl::getString() const
157 {
158         return buff;
159 }
160
161
162 docstring const Lexer::Pimpl::getDocString() const
163 {
164         return from_utf8(buff);
165 }
166
167
168 void Lexer::Pimpl::printError(string const & message) const
169 {
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;
175 }
176
177
178 void Lexer::Pimpl::printTable(ostream & os)
179 {
180         os << "\nNumber of tags: " << no_items << endl;
181         for (int i= 0; i < no_items; ++i)
182                 os << "table[" << i
183                    << "]:  tag: `" << table[i].tag
184                    << "'  code:" << table[i].code << '\n';
185         os.flush();
186 }
187
188
189 void Lexer::Pimpl::verifyTable()
190 {
191         // Check if the table is sorted and if not, sort it.
192         if (table
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;
198                 printTable(lyxerr);
199
200                 sort(table, table + no_items, &compareTags);
201                 lyxerr << "\nSorted:" << endl;
202                 printTable(lyxerr);
203         }
204 }
205
206
207 void Lexer::Pimpl::pushTable(LexerKeyword * tab, int num)
208 {
209         PushedTable tmppu(table, no_items);
210         pushed.push(tmppu);
211
212         table = tab;
213         no_items = num;
214
215         verifyTable();
216 }
217
218
219 void Lexer::Pimpl::popTable()
220 {
221         if (pushed.empty()) {
222                 lyxerr << "Lexer error: nothing to pop!" << endl;
223                 return;
224         }
225
226         PushedTable tmp = pushed.top();
227         pushed.pop();
228         table = tmp.table_elem;
229         no_items = tmp.table_siz;
230 }
231
232
233 bool Lexer::Pimpl::setFile(FileName const & filename)
234 {
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);
238                 is.rdbuf(&gz_);
239                 name = filename.absFileName();
240                 lineno = 0;
241                 if (!gz_.is_open() || !is.good())
242                         return false;
243
244         // Skip byte order mark.
245         if (is.peek() == 0xef) {
246                 is.get();
247                 if (is.peek() == 0xbb) {
248                         is.get();
249                         LASSERT(is.get() == 0xbf, /**/);
250                 } else
251                         is.unget();
252         }
253
254         return true;
255 }
256
257
258 void Lexer::Pimpl::setStream(istream & i)
259 {
260         if (gz_.is_open() || istream::off_type(is.tellg()) > 0)
261                 LYXERR0("Error in Lexer::setStream: file or stream already set.");
262         is.rdbuf(i.rdbuf());
263         lineno = 0;
264 }
265
266
267 void Lexer::Pimpl::setCommentChar(char c)
268 {
269         commentChar = c;
270 }
271
272
273 bool Lexer::Pimpl::next(bool esc /* = false */)
274 {
275         if (!pushTok.empty()) {
276                 // There can have been a whole line pushed so
277                 // we extract the first word and leaves the rest
278                 // in pushTok. (Lgb)
279                 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
280                         buff.clear();
281                         pushTok = split(pushTok, buff, ' ');
282                 } else {
283                         buff = pushTok;
284                         pushTok.clear();
285                 }
286                 status = LEX_TOKEN;
287                 return true;
288         }
289
290
291         char cc = 0;
292         status = 0;
293         while (is && !status) {
294                 is.get(cc);
295                 unsigned char c = cc;
296
297                 if (c == commentChar) {
298                         // Read rest of line (fast :-)
299 #if 1
300                         // That is not fast... (Lgb)
301                         string dummy;
302                         getline(is, dummy);
303
304                         LYXERR(Debug::LYXLEX, "Comment read: `" << string(1, c) << dummy << '\'');
305 #else
306                         // unfortunately ignore is buggy (Lgb)
307                         is.ignore(100, '\n');
308 #endif
309                         ++lineno;
310                         continue;
311                 }
312
313                 if (c == '\"') {
314                         buff.clear();
315
316                         if (esc) {
317
318                                 do {
319                                         bool escaped = false;
320                                         is.get(cc);
321                                         c = cc;
322                                         if (c == '\r') continue;
323                                         if (c == '\\') {
324                                                 // escape the next char
325                                                 is.get(cc);
326                                                 c = cc;
327                                                 if (c == '\"' || c == '\\')
328                                                         escaped = true;
329                                                 else
330                                                         buff.push_back('\\');
331                                         }
332                                         buff.push_back(c);
333
334                                         if (!escaped && c == '\"')
335                                                 break;
336                                 } while (c != '\n' && is);
337
338                         } else {
339
340                                 do {
341                                         is.get(cc);
342                                         c = cc;
343                                         if (c != '\r')
344                                                 buff.push_back(c);
345                                 } while (c != '\"' && c != '\n' && is);
346
347                         }
348
349                         if (c != '\"') {
350                                 printError("Missing quote");
351                                 if (c == '\n')
352                                         ++lineno;
353                         }
354
355                         buff.resize(buff.size() - 1);
356                         status = LEX_DATA;
357                         break;
358                 }
359
360                 if (c == ',')
361                         continue;              /* Skip ','s */
362
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
367                 if (c > ' ' && is)  {
368                         buff.clear();
369
370                         do {
371                                 if (esc && c == '\\') {
372                                         // escape the next char
373                                         is.get(cc);
374                                         c = cc;
375                                         //escaped = true;
376                                 }
377                                 buff.push_back(c);
378                                 is.get(cc);
379                                 c = cc;
380                         } while (c > ' ' && c != ',' && is);
381                         status = LEX_TOKEN;
382                 }
383
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'
389                         is.get(cc);
390                         c = cc;
391                 }
392
393                 if (c == '\n')
394                         ++lineno;
395
396         }
397         if (status)
398                 return true;
399
400         status = is.eof() ? LEX_FEOF: LEX_UNDEF;
401         buff.clear();
402         return false;
403 }
404
405
406 int Lexer::Pimpl::searchKeyword(char const * const tag) const
407 {
408         LexerKeyword search_tag = { tag, 0 };
409         LexerKeyword * res =
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))
417                 return res->code;
418         return LEX_UNDEF;
419 }
420
421
422 int Lexer::Pimpl::lex()
423 {
424         //NOTE: possible bug.
425         if (next() && status == LEX_TOKEN)
426                 return searchKeyword(getString().c_str());
427         return status;
428 }
429
430
431 bool Lexer::Pimpl::eatLine()
432 {
433         buff.clear();
434
435         unsigned char c = '\0';
436         char cc = 0;
437         while (is && c != '\n') {
438                 is.get(cc);
439                 c = cc;
440                 //LYXERR(Debug::LYXLEX, "Lexer::EatLine read char: `" << c << '\'');
441                 if (c != '\r' && is)
442                         buff.push_back(c);
443         }
444
445         if (c == '\n') {
446                 ++lineno;
447                 buff.resize(buff.size() - 1);
448                 status = LEX_DATA;
449                 return true;
450         } else if (buff.length() > 0) { // last line
451                 status = LEX_DATA;
452                 return true;
453         } else {
454                 return false;
455         }
456 }
457
458
459 bool Lexer::Pimpl::nextToken()
460 {
461         if (!pushTok.empty()) {
462                 // There can have been a whole line pushed so
463                 // we extract the first word and leaves the rest
464                 // in pushTok. (Lgb)
465                 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
466                         buff.clear();
467                         pushTok = split(pushTok, buff, ' ');
468                 } else {
469                         buff = pushTok;
470                         pushTok.clear();
471                 }
472                 status = LEX_TOKEN;
473                 return true;
474         }
475
476         status = 0;
477         while (is && !status) {
478                 unsigned char c = 0;
479                 char cc = 0;
480                 is.get(cc);
481                 c = cc;
482                 if ((c >= ' ' || c == '\t') && is) {
483                         buff.clear();
484
485                         if (c == '\\') { // first char == '\\'
486                                 do {
487                                         buff.push_back(c);
488                                         is.get(cc);
489                                         c = cc;
490                                 } while (c > ' ' && c != '\\' && is);
491                         } else {
492                                 do {
493                                         buff.push_back(c);
494                                         is.get(cc);
495                                         c = cc;
496                                 } while ((c >= ' ' || c == '\t') && c != '\\' && is);
497                         }
498
499                         if (c == '\\')
500                                 is.putback(c); // put it back
501                         status = LEX_TOKEN;
502                 }
503
504                 if (c == '\n')
505                         ++lineno;
506
507         }
508         if (status)
509                 return true;
510
511         status = is.eof() ? LEX_FEOF: LEX_UNDEF;
512         buff.clear();
513         return false;
514 }
515
516
517 bool Lexer::Pimpl::inputAvailable()
518 {
519         return is.good();
520 }
521
522
523 void Lexer::Pimpl::pushToken(string const & pt)
524 {
525         pushTok = pt;
526 }
527
528
529
530
531 //////////////////////////////////////////////////////////////////////
532 //
533 // Lexer
534 //
535 //////////////////////////////////////////////////////////////////////
536
537 Lexer::Lexer()
538         : pimpl_(new Pimpl(nullptr, 0)), lastReadOk_(false)
539 {}
540
541
542 void Lexer::init(LexerKeyword * tab, int num)
543 {
544          pimpl_ = new Pimpl(tab, num);
545 }
546
547
548 Lexer::~Lexer()
549 {
550         delete pimpl_;
551 }
552
553
554 bool Lexer::isOK() const
555 {
556         return pimpl_->inputAvailable();
557 }
558
559
560 void Lexer::setLineNumber(int l)
561 {
562         pimpl_->lineno = l;
563 }
564
565
566 int Lexer::lineNumber() const
567 {
568         return pimpl_->lineno;
569 }
570
571
572 istream & Lexer::getStream()
573 {
574         return pimpl_->is;
575 }
576
577
578 void Lexer::pushTable(LexerKeyword * tab, int num)
579 {
580         pimpl_->pushTable(tab, num);
581 }
582
583
584 void Lexer::popTable()
585 {
586         pimpl_->popTable();
587 }
588
589
590 void Lexer::printTable(ostream & os)
591 {
592         pimpl_->printTable(os);
593 }
594
595
596 void Lexer::printError(string const & message) const
597 {
598         pimpl_->printError(message);
599 }
600
601
602 bool Lexer::setFile(FileName const & filename)
603 {
604         return pimpl_->setFile(filename);
605 }
606
607
608 void Lexer::setStream(istream & i)
609 {
610         pimpl_->setStream(i);
611 }
612
613
614 void Lexer::setCommentChar(char c)
615 {
616         pimpl_->setCommentChar(c);
617 }
618
619
620 int Lexer::lex()
621 {
622         return pimpl_->lex();
623 }
624
625
626 int Lexer::getInteger() const
627 {
628         lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
629         if (!lastReadOk_) {
630                 pimpl_->printError("integer token missing");
631                 return -1;
632         }
633
634         if (isStrInt(pimpl_->getString()))
635                 return convert<int>(pimpl_->getString());
636
637         lastReadOk_ = false;
638         pimpl_->printError("Bad integer `$$Token'");
639         return -1;
640 }
641
642
643 double Lexer::getFloat() const
644 {
645         // replace comma with dot in case the file was written with
646         // the wrong locale (should be rare, but is easy enough to
647         // avoid).
648         lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
649         if (!lastReadOk_) {
650                 pimpl_->printError("float token missing");
651                 return -1;
652         }
653
654         string const str = subst(pimpl_->getString(), ",", ".");
655         if (isStrDbl(str))
656                 return convert<double>(str);
657
658         lastReadOk_ = false;
659         pimpl_->printError("Bad float `$$Token'");
660         return -1;
661 }
662
663
664 string const Lexer::getString(bool trim) const
665 {
666         lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
667
668         if (lastReadOk_)
669                 return trim ? support::trim(pimpl_->getString(), "\t ") : pimpl_->getString();
670
671         return string();
672 }
673
674
675 docstring const Lexer::getDocString(bool trim) const
676 {
677         lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
678
679         if (lastReadOk_)
680                 return trim ? support::trim(pimpl_->getDocString(), "\t ") : pimpl_->getDocString();
681
682         return docstring();
683 }
684
685
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)
690 {
691         docstring str;
692         docstring prefix;
693         bool firstline = true;
694         bool foundend = false;
695
696         while (pimpl_->is) { //< eatLine only reads from is, not from pushTok
697                 if (!eatLine())
698                         // blank line in the file being read
699                         continue;
700                 docstring tmpstr = getDocString();
701                 docstring const token = trim(tmpstr, " \t");
702
703                 LYXERR(Debug::PARSER, "LongString: `" << tmpstr << '\'');
704
705                 // We do a case independent comparison, like searchKeyword does.
706                 if (compare_no_case(token, endtoken) == 0) {
707                         foundend = true;
708                         break;
709                 }
710
711                 if (firstline) {
712                         size_t i = tmpstr.find_first_not_of(from_ascii(" \t"));
713                         if (i != string::npos)
714                                 prefix = tmpstr.substr(0, i);
715                         firstline = false;
716                         LYXERR(Debug::PARSER, "Prefix = `" << prefix << "\'");
717                 }
718
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());
723
724                 str += tmpstr + '\n';
725         }
726
727         if (!foundend)
728                 printError("Long string not ended by `" + to_utf8(endtoken) + '\'');
729
730         return str;
731 }
732
733
734 bool Lexer::getBool() const
735 {
736         string const s = pimpl_->getString();
737         if (s == "false" || s == "0") {
738                 lastReadOk_ = true;
739                 return false;
740         }
741         if (s == "true" || s == "1") {
742                 lastReadOk_ = true;
743                 return true;
744         }
745         pimpl_->printError("Bad boolean `$$Token'. "
746                                  "Use \"false\" or \"true\"");
747         lastReadOk_ = false;
748         return false;
749 }
750
751
752 bool Lexer::eatLine()
753 {
754         return pimpl_->eatLine();
755 }
756
757
758 bool Lexer::next(bool esc)
759 {
760         return pimpl_->next(esc);
761 }
762
763
764 bool Lexer::nextToken()
765 {
766         return pimpl_->nextToken();
767 }
768
769
770 void Lexer::pushToken(string const & pt)
771 {
772         pimpl_->pushToken(pt);
773 }
774
775
776 Lexer::operator void const *() const
777 {
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;
783 }
784
785
786 bool Lexer::operator!() const
787 {
788         return !lastReadOk_;
789 }
790
791
792 Lexer & Lexer::operator>>(string & s)
793 {
794         if (isOK()) {
795                 next();
796                 s = getString();
797         } else {
798                 lastReadOk_ = false;
799         }
800         return *this;
801 }
802
803
804 Lexer & Lexer::operator>>(docstring & s)
805 {
806         if (isOK()) {
807                 next();
808                 s = getDocString();
809         } else {
810                 lastReadOk_ = false;
811         }
812         return *this;
813 }
814
815
816 Lexer & Lexer::operator>>(double & s)
817 {
818         if (isOK()) {
819                 next();
820                 s = getFloat();
821         } else {
822                 lastReadOk_ = false;
823         }
824         return *this;
825 }
826
827
828 Lexer & Lexer::operator>>(int & s)
829 {
830         if (isOK()) {
831                 next();
832                 s = getInteger();
833         } else {
834                 lastReadOk_ = false;
835         }
836         return *this;
837 }
838
839
840 Lexer & Lexer::operator>>(unsigned int & s)
841 {
842         if (isOK()) {
843                 next();
844                 s = getInteger();
845         } else {
846                 lastReadOk_ = false;
847         }
848         return *this;
849 }
850
851
852 Lexer & Lexer::operator>>(bool & s)
853 {
854         if (isOK()) {
855                 next();
856                 s = getBool();
857         } else {
858                 lastReadOk_ = false;
859         }
860         return *this;
861 }
862
863
864 Lexer & Lexer::operator>>(char & c)
865 {
866         string s;
867         operator>>(s);
868         if (!s.empty())
869                 c = s[0];
870         return *this;
871 }
872
873
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)
877 {
878         string res;
879         res += '"';
880         res += subst(subst(arg, "\\", "\\\\"), "\"", "\\\"");
881         res += '"';
882         return res;
883 }
884
885
886 // same for docstring
887 docstring Lexer::quoteString(docstring const & arg)
888 {
889         docstring res;
890         res += '"';
891         res += subst(subst(arg, from_ascii("\\"), from_ascii("\\\\")),
892                      from_ascii("\""), from_ascii("\\\""));
893         res += '"';
894         return res;
895 }
896
897
898 Lexer & Lexer::operator>>(char const * required)
899 {
900         string token;
901         *this >> token;
902         if (token != required) {
903                 LYXERR0("Missing '" << required << "'-tag in " << pimpl_->context
904                         << ". Got " << token << " instead. Line: " << lineNumber());
905                 pushToken(token);
906         }
907         return *this;
908 }
909
910
911 bool Lexer::checkFor(char const * required)
912 {
913         string token;
914         *this >> token;
915         if (token == required)
916                 return true;
917         pushToken(token);
918         return false;
919 }
920
921
922 void Lexer::setContext(std::string const & functionName)
923 {
924         pimpl_->context = functionName;
925 }
926
927 } // namespace support
928
929 } // namespace lyx