]> git.lyx.org Git - lyx.git/blob - src/Lexer.cpp
546ae0e9e9e865cd7834ebe667421abc30db618b
[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 >= ' ' || c == '\t') && 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 == '\t') && 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
640 int Lexer::lex()
641 {
642         return pimpl_->lex();
643 }
644
645
646 int Lexer::getInteger() const
647 {
648         lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
649         if (!lastReadOk_) {
650                 pimpl_->printError("integer token missing");
651                 return -1;
652         }
653
654         if (isStrInt(pimpl_->getString()))
655                 return convert<int>(pimpl_->getString());
656
657         lastReadOk_ = false;
658         pimpl_->printError("Bad integer `$$Token'");
659         return -1;
660 }
661
662
663 double Lexer::getFloat() const
664 {
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;
672         }
673
674         string const str = subst(pimpl_->getString(), ",", ".");
675         if (isStrDbl(str))
676                 return convert<double>(str);
677
678         lastReadOk_ = false;
679         pimpl_->printError("Bad float `$$Token'");
680         return -1;
681 }
682
683
684 string const Lexer::getString() const
685 {
686         lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
687
688         if (lastReadOk_)
689         return pimpl_->getString();
690
691         return string();
692 }
693
694
695 docstring const Lexer::getDocString() const
696 {
697         lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
698
699         if (lastReadOk_)
700                 return pimpl_->getDocString();
701
702         return docstring();
703 }
704
705
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)
710 {
711         string str;
712         string prefix;
713         bool firstline = true;
714
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;
719
720                 string const token = trim(getString(), " \t");
721
722                 LYXERR(Debug::PARSER, "LongString: `" << getString() << '\'');
723
724                 // We do a case independent comparison, like searchKeyword does.
725                 if (compare_ascii_no_case(token, endtoken) == 0)
726                         break;
727
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 << "\'");
735                 }
736
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);
741
742                 str += ltrim(tmpstr, "\t") + '\n';
743         }
744
745         if (!pimpl_->is)
746                 printError("Long string not ended by `" + endtoken + '\'');
747
748         return str;
749 }
750
751
752 bool Lexer::getBool() const
753 {
754         string const s = pimpl_->getString();   
755         if (s == "false" || s == "0") {
756                 lastReadOk_ = true;
757                 return false;
758         }
759         if (s == "true" || s == "1") {
760                 lastReadOk_ = true;
761                 return true;
762         }
763         pimpl_->printError("Bad boolean `$$Token'. "
764                                  "Use \"false\" or \"true\"");
765         lastReadOk_ = false;
766         return false;
767 }
768
769
770 bool Lexer::eatLine()
771 {
772         return pimpl_->eatLine();
773 }
774
775
776 bool Lexer::next(bool esc)
777 {
778         return pimpl_->next(esc);
779 }
780
781
782 bool Lexer::nextToken()
783 {
784         return pimpl_->nextToken();
785 }
786
787
788 void Lexer::pushToken(string const & pt)
789 {
790         pimpl_->pushToken(pt);
791 }
792
793
794 Lexer::operator void const *() const
795 {
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;
801 }
802
803
804 bool Lexer::operator!() const
805 {
806         return !lastReadOk_;
807 }
808
809
810 Lexer & Lexer::operator>>(string & s)
811 {
812         if (isOK()) {
813                 next();
814                 s = getString();
815         } else {
816                 lastReadOk_ = false;
817         }
818         return *this;
819 }
820
821
822 Lexer & Lexer::operator>>(docstring & s)
823 {
824         if (isOK()) {
825                 next();
826                 s = getDocString();
827         } else {
828                 lastReadOk_ = false;
829         }
830         return *this;
831 }
832
833
834 Lexer & Lexer::operator>>(double & s)
835 {
836         if (isOK()) {
837                 next();
838                 s = getFloat();
839         } else {
840                 lastReadOk_ = false;
841         }
842         return *this;
843 }
844
845
846 Lexer & Lexer::operator>>(int & s)
847 {
848         if (isOK()) {
849                 next();
850                 s = getInteger();
851         } else {
852                 lastReadOk_ = false;
853         }
854         return *this;
855 }
856
857
858 Lexer & Lexer::operator>>(unsigned int & s)
859 {
860         if (isOK()) {
861                 next();
862                 s = getInteger();
863         } else {
864                 lastReadOk_ = false;
865         }
866         return *this;
867 }
868
869
870 Lexer & Lexer::operator>>(bool & s)
871 {
872         if (isOK()) {
873                 next();
874                 s = getBool();
875         } else {
876                 lastReadOk_ = false;
877         }
878         return *this;
879 }
880
881
882 Lexer & Lexer::operator>>(char & c)
883 {
884         string s;
885         operator>>(s);
886         if (!s.empty())
887                 c = s[0];
888         return *this;
889 }
890
891
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)
895 {
896         string res;
897         res += '"';
898         res += subst(subst(arg, "\\", "\\\\"), "\"", "\\\"");
899         res += '"';
900         return res;
901 }
902
903
904 // same for docstring
905 docstring Lexer::quoteString(docstring const & arg)
906 {
907         docstring res;
908         res += '"';
909         res += subst(subst(arg, from_ascii("\\"), from_ascii("\\\\")), 
910                      from_ascii("\""), from_ascii("\\\""));
911         res += '"';
912         return res;
913 }
914
915
916 Lexer & Lexer::operator>>(char const * required)
917 {
918         string token;
919         *this >> token;
920         if (token != required) {
921                 LYXERR0("Missing '" << required << "'-tag in " << pimpl_->context 
922                         << ". Got " << token << " instead. Line: " << lineNumber());
923                 pushToken(token);
924         }
925         return *this;
926 }
927
928
929 bool Lexer::checkFor(char const * required)
930 {
931         string token;
932         *this >> token;
933         if (token == required)
934                 return true;
935         pushToken(token);
936         return false;
937 }
938
939
940 void Lexer::setContext(std::string const & str)
941 {
942         pimpl_->context = str;
943 }
944
945
946 } // namespace lyx