]> git.lyx.org Git - lyx.git/blob - src/Lexer.cpp
* GuiView.{cpp, h}:
[lyx.git] / src / 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 "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/lstrings.h"
24 #include "support/lyxalgo.h"
25 #include "support/types.h"
26
27 #include <functional>
28 #include <istream>
29 #include <stack>
30 #include <vector>
31
32 using namespace std;
33 using namespace lyx::support;
34
35 namespace lyx {
36
37 //////////////////////////////////////////////////////////////////////
38 //
39 // Lexer::Pimpl
40 //
41 //////////////////////////////////////////////////////////////////////
42
43
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_;
83
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         ///
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 &);
111
112         ///
113         void verifyTable();
114         ///
115         class PushedTable {
116         public:
117                 ///
118                 PushedTable()
119                         : table_elem(0), 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
134 namespace {
135
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
141         {
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;
146         }
147 };
148
149 } // end of anon namespace
150
151
152 Lexer::Pimpl::Pimpl(LexerKeyword * tab, int num)
153         : is(&fb_), table(tab), no_items(num),
154           status(0), lineno(0), commentChar('#')
155 {
156         verifyTable();
157 }
158
159
160 string const Lexer::Pimpl::getString() const
161 {
162         return buff;
163 }
164
165
166 docstring const Lexer::Pimpl::getDocString() const
167 {
168         return from_utf8(buff);
169 }
170
171
172 void Lexer::Pimpl::printError(string const & message) const
173 {
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;
179 }
180
181
182 void Lexer::Pimpl::printTable(ostream & os)
183 {
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();
190 }
191
192
193 void Lexer::Pimpl::verifyTable()
194 {
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);
203
204                 sort(table, table + no_items, CompareTags());
205                 lyxerr << "\nSorted:" << endl;
206                 printTable(lyxerr);
207         }
208 }
209
210
211 void Lexer::Pimpl::pushTable(LexerKeyword * tab, int num)
212 {
213         PushedTable tmppu(table, no_items);
214         pushed.push(tmppu);
215
216         table = tab;
217         no_items = num;
218
219         verifyTable();
220 }
221
222
223 void Lexer::Pimpl::popTable()
224 {
225         if (pushed.empty()) {
226                 lyxerr << "Lexer error: nothing to pop!" << endl;
227                 return;
228         }
229
230         PushedTable tmp = pushed.top();
231         pushed.pop();
232         table = tmp.table_elem;
233         no_items = tmp.table_siz;
234 }
235
236
237 bool Lexer::Pimpl::setFile(FileName const & filename)
238 {
239         // Check the format of the file.
240         string const format = filename.guessFormatFromContents();
241
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");
257
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.");
264                 }
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();
270         }
271 }
272
273
274 void Lexer::Pimpl::setStream(istream & i)
275 {
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.");
279         }
280         is.rdbuf(i.rdbuf());
281         lineno = 0;
282 }
283
284
285 void Lexer::Pimpl::setCommentChar(char c)
286 {
287         commentChar = c;
288 }
289
290
291 bool Lexer::Pimpl::next(bool esc /* = false */)
292 {
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();
303                 }
304                 status = LEX_TOKEN;
305                 return true;
306         }
307
308
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;
315
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);
322
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;
330                 }
331
332                 if (c == '\"') {
333                         buff.clear();
334
335                         if (esc) {
336
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('\\');
351                                         }
352                                         buff.push_back(c);
353
354                                         if (!escaped && c == '\"')
355                                                 break;
356                                 } while (c != '\n' && is);
357
358                         } else {
359
360                                 do {
361                                         is.get(cc);
362                                         c = cc;
363                                         if (c != '\r')
364                                                 buff.push_back(c);
365                                 } while (c != '\"' && c != '\n' && is);
366
367                         }
368
369                         if (c != '\"') {
370                                 printError("Missing quote");
371                                 if (c == '\n')
372                                         ++lineno;
373                         }
374
375                         buff.resize(buff.size() - 1);
376                         status = LEX_DATA;
377                         break;
378                 }
379
380                 if (c == ',')
381                         continue;              /* Skip ','s */
382
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();
389
390                         do {
391                                 if (esc && c == '\\') {
392                                         // escape the next char
393                                         is.get(cc);
394                                         c = cc;
395                                         //escaped = true;
396                                 }
397                                 buff.push_back(c);
398                                 is.get(cc);
399                                 c = cc;
400                         } while (c > ' ' && c != ',' && is);
401                         status = LEX_TOKEN;
402                 }
403
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;
411                 }
412
413                 if (c == '\n')
414                         ++lineno;
415
416         }
417         if (status)
418                 return true;
419
420         status = is.eof() ? LEX_FEOF: LEX_UNDEF;
421         buff.clear();
422         return false;
423 }
424
425
426 int Lexer::Pimpl::searchKeyword(char const * const tag) const
427 {
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;
439 }
440
441
442 int Lexer::Pimpl::lex()
443 {
444         //NOTE: possible bug.
445         if (next() && status == LEX_TOKEN)
446                 return searchKeyword(getString().c_str());
447         return status;
448 }
449
450
451 bool Lexer::Pimpl::eatLine()
452 {
453         buff.clear();
454
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);
463         }
464
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;
475         }
476 }
477
478
479 bool Lexer::Pimpl::nextToken()
480 {
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();
491                 }
492                 status = LEX_TOKEN;
493                 return true;
494         }
495
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();
504
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);
517                         }
518
519                         if (c == '\\')
520                                 is.putback(c); // put it back
521                         status = LEX_TOKEN;
522                 }
523
524                 if (c == '\n')
525                         ++lineno;
526
527         }
528         if (status)
529                 return true;
530
531         status = is.eof() ? LEX_FEOF: LEX_UNDEF;
532         buff.clear();
533         return false;
534 }
535
536
537 bool Lexer::Pimpl::inputAvailable()
538 {
539         return is.good();
540 }
541
542
543 void Lexer::Pimpl::pushToken(string const & pt)
544 {
545         pushTok = pt;
546 }
547
548
549
550
551 //////////////////////////////////////////////////////////////////////
552 //
553 // Lexer
554 //
555 //////////////////////////////////////////////////////////////////////
556
557 Lexer::Lexer()
558         : pimpl_(new Pimpl(0, 0))
559 {}
560
561
562 void Lexer::init(LexerKeyword * tab, int num)
563 {
564          pimpl_ = new Pimpl(tab, num);
565 }
566
567
568 Lexer::~Lexer()
569 {
570         delete pimpl_;
571 }
572
573
574 bool Lexer::isOK() const
575 {
576         return pimpl_->inputAvailable();
577 }
578
579
580 void Lexer::setLineNumber(int l)
581 {
582         pimpl_->lineno = l;
583 }
584
585
586 int Lexer::lineNumber() const
587 {
588         return pimpl_->lineno;
589 }
590
591
592 istream & Lexer::getStream()
593 {
594         return pimpl_->is;
595 }
596
597
598 void Lexer::pushTable(LexerKeyword * tab, int num)
599 {
600         pimpl_->pushTable(tab, num);
601 }
602
603
604 void Lexer::popTable()
605 {
606         pimpl_->popTable();
607 }
608
609
610 void Lexer::printTable(ostream & os)
611 {
612         pimpl_->printTable(os);
613 }
614
615
616 void Lexer::printError(string const & message) const
617 {
618         pimpl_->printError(message);
619 }
620
621
622 bool Lexer::setFile(FileName const & filename)
623 {
624         return pimpl_->setFile(filename);
625 }
626
627
628 void Lexer::setStream(istream & i)
629 {
630         pimpl_->setStream(i);
631 }
632
633
634 void Lexer::setCommentChar(char c)
635 {
636         pimpl_->setCommentChar(c);
637 }
638
639 int Lexer::lex()
640 {
641         return pimpl_->lex();
642 }
643
644
645 int Lexer::getInteger() const
646 {
647         lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
648         if (!lastReadOk_) {
649                 pimpl_->printError("integer token missing");
650                 return -1;
651         }
652
653         if (isStrInt(pimpl_->getString()))
654                 return convert<int>(pimpl_->getString());
655
656         lastReadOk_ = false;
657         pimpl_->printError("Bad integer `$$Token'");
658         return -1;
659 }
660
661
662 double Lexer::getFloat() const
663 {
664         // replace comma with dot in case the file was written with
665         // the wrong locale (should be rare, but is easy enough to
666         // avoid).
667         lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
668         if (!lastReadOk_) {
669                 pimpl_->printError("float token missing");
670                 return -1;
671         }
672
673         string const str = subst(pimpl_->getString(), ",", ".");
674         if (isStrDbl(str))
675                 return convert<double>(str);
676
677         lastReadOk_ = false;
678         pimpl_->printError("Bad float `$$Token'");
679         return -1;
680 }
681
682
683 string const Lexer::getString() const
684 {
685         lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
686
687         if (lastReadOk_)
688         return pimpl_->getString();
689
690         return string();
691 }
692
693
694 docstring const Lexer::getDocString() const
695 {
696         lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
697
698         if (lastReadOk_)
699                 return pimpl_->getDocString();
700
701         return docstring();
702 }
703
704
705 // I would prefer to give a tag number instead of an explicit token
706 // here, but it is not possible because Buffer::readDocument uses
707 // explicit tokens (JMarc)
708 string const Lexer::getLongString(string const & endtoken)
709 {
710         string str;
711         string prefix;
712         bool firstline = true;
713
714         while (pimpl_->is) { //< eatLine only reads from is, not from pushTok
715                 if (!eatLine())
716                         // blank line in the file being read
717                         continue;
718
719                 string const token = trim(getString(), " \t");
720
721                 LYXERR(Debug::PARSER, "LongString: `" << getString() << '\'');
722
723                 // We do a case independent comparison, like searchKeyword does.
724                 if (compare_ascii_no_case(token, endtoken) == 0)
725                         break;
726
727                 string tmpstr = getString();
728                 if (firstline) {
729                         size_t i = tmpstr.find_first_not_of(' ');
730                         if (i != string::npos)
731                                 prefix = tmpstr.substr(0, i);
732                         firstline = false;
733                         LYXERR(Debug::PARSER, "Prefix = `" << prefix << "\'");
734                 }
735
736                 // further lines in long strings may have the same
737                 // whitespace prefix as the first line. Remove it.
738                 if (prefix.length() && prefixIs(tmpstr, prefix))
739                         tmpstr.erase(0, prefix.length() - 1);
740
741                 str += ltrim(tmpstr, "\t") + '\n';
742         }
743
744         if (!pimpl_->is)
745                 printError("Long string not ended by `" + endtoken + '\'');
746
747         return str;
748 }
749
750
751 bool Lexer::getBool() const
752 {
753         string const s = pimpl_->getString();   
754         if (s == "false" || s == "0") {
755                 lastReadOk_ = true;
756                 return false;
757         }
758         if (s == "true" || s == "1") {
759                 lastReadOk_ = true;
760                 return true;
761         }
762         pimpl_->printError("Bad boolean `$$Token'. "
763                                  "Use \"false\" or \"true\"");
764         lastReadOk_ = false;
765         return false;
766 }
767
768
769 bool Lexer::eatLine()
770 {
771         return pimpl_->eatLine();
772 }
773
774
775 bool Lexer::next(bool esc)
776 {
777         return pimpl_->next(esc);
778 }
779
780
781 bool Lexer::nextToken()
782 {
783         return pimpl_->nextToken();
784 }
785
786
787 void Lexer::pushToken(string const & pt)
788 {
789         pimpl_->pushToken(pt);
790 }
791
792
793 Lexer::operator void const *() const
794 {
795         // This behaviour is NOT the same as the streams which would
796         // use fail() here. However, our implementation of getString() et al.
797         // can cause the eof() and fail() bits to be set, even though we
798         // haven't tried to read 'em.
799         return lastReadOk_? this : 0;
800 }
801
802
803 bool Lexer::operator!() const
804 {
805         return !lastReadOk_;
806 }
807
808
809 Lexer & Lexer::operator>>(string & s)
810 {
811         if (isOK()) {
812                 next();
813                 s = getString();
814         } else {
815                 lastReadOk_ = false;
816         }
817         return *this;
818 }
819
820
821 Lexer & Lexer::operator>>(docstring & s)
822 {
823         if (isOK()) {
824                 next();
825                 s = getDocString();
826         } else {
827                 lastReadOk_ = false;
828         }
829         return *this;
830 }
831
832
833 Lexer & Lexer::operator>>(double & s)
834 {
835         if (isOK()) {
836                 next();
837                 s = getFloat();
838         } else {
839                 lastReadOk_ = false;
840         }
841         return *this;
842 }
843
844
845 Lexer & Lexer::operator>>(int & s)
846 {
847         if (isOK()) {
848                 next();
849                 s = getInteger();
850         } else {
851                 lastReadOk_ = false;
852         }
853         return *this;
854 }
855
856
857 Lexer & Lexer::operator>>(unsigned int & s)
858 {
859         if (isOK()) {
860                 next();
861                 s = getInteger();
862         } else {
863                 lastReadOk_ = false;
864         }
865         return *this;
866 }
867
868
869 Lexer & Lexer::operator>>(bool & s)
870 {
871         if (isOK()) {
872                 next();
873                 s = getBool();
874         } else {
875                 lastReadOk_ = false;
876         }
877         return *this;
878 }
879
880
881 Lexer & Lexer::operator>>(char & c)
882 {
883         string s;
884         operator>>(s);
885         if (!s.empty())
886                 c = s[0];
887         return *this;
888 }
889
890
891 // quotes a string, e.g. for use in preferences files or as an argument
892 // of the "log" dialog
893 string Lexer::quoteString(string const & arg)
894 {
895         string res;
896         res += '"';
897         res += subst(subst(arg, "\\", "\\\\"), "\"", "\\\"");
898         res += '"';
899         return res;
900 }
901
902
903 Lexer & Lexer::operator>>(char const * required)
904 {
905         string token;
906         *this >> token;
907         if (token != required) {
908                 LYXERR0("Missing '" << required << "'-tag in " << pimpl_->context 
909                         << ". Got " << token << " instead. Line: " << lineNumber());
910                 pushToken(token);
911         }
912         return *this;
913 }
914
915
916 bool Lexer::checkFor(char const * required)
917 {
918         string token;
919         *this >> token;
920         if (token == required)
921                 return true;
922         pushToken(token);
923         return false;
924 }
925
926
927 void Lexer::setContext(std::string const & str)
928 {
929         pimpl_->context = str;
930 }
931
932
933 } // namespace lyx