]> git.lyx.org Git - lyx.git/blob - src/Lexer.cpp
if we have a buffer we don't need to pass part of it separately...
[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)) << ']' << endl;
177 }
178
179
180 void Lexer::Pimpl::printTable(ostream & os)
181 {
182         os << "\nNumber of tags: " << no_items << endl;
183         for (int i= 0; i < no_items; ++i)
184                 os << "table[" << i
185                    << "]:  tag: `" << table[i].tag
186                    << "'  code:" << table[i].code << '\n';
187         os.flush();
188 }
189
190
191 void Lexer::Pimpl::verifyTable()
192 {
193         // Check if the table is sorted and if not, sort it.
194         if (table
195             && !lyx::sorted(table, table + no_items, CompareTags())) {
196                 lyxerr << "The table passed to Lexer is not sorted!\n"
197                        << "Tell the developers to fix it!" << endl;
198                 // We sort it anyway to avoid problems.
199                 lyxerr << "\nUnsorted:" << endl;
200                 printTable(lyxerr);
201
202                 sort(table, table + no_items, CompareTags());
203                 lyxerr << "\nSorted:" << endl;
204                 printTable(lyxerr);
205         }
206 }
207
208
209 void Lexer::Pimpl::pushTable(LexerKeyword * tab, int num)
210 {
211         PushedTable tmppu(table, no_items);
212         pushed.push(tmppu);
213
214         table = tab;
215         no_items = num;
216
217         verifyTable();
218 }
219
220
221 void Lexer::Pimpl::popTable()
222 {
223         if (pushed.empty()) {
224                 lyxerr << "Lexer error: nothing to pop!" << endl;
225                 return;
226         }
227
228         PushedTable tmp = pushed.top();
229         pushed.pop();
230         table = tmp.table_elem;
231         no_items = tmp.table_siz;
232 }
233
234
235 bool Lexer::Pimpl::setFile(FileName const & filename)
236 {
237         // Check the format of the file.
238         string const format = filename.guessFormatFromContents();
239
240         if (format == "gzip" || format == "zip" || format == "compress") {
241                 LYXERR(Debug::LYXLEX, "lyxlex: compressed");
242                 // The check only outputs a debug message, because it triggers
243                 // a bug in compaq cxx 6.2, where is_open() returns 'true' for
244                 // a fresh new filebuf.  (JMarc)
245                 if (gz_.is_open() || istream::off_type(is.tellg()) > -1)
246                         LYXERR(Debug::LYXLEX, "Error in LyXLex::setFile: "
247                                 "file or stream already set.");
248                 gz_.open(filename.toFilesystemEncoding().c_str(), ios::in);
249                 is.rdbuf(&gz_);
250                 name = filename.absFilename();
251                 lineno = 0;
252                 return gz_.is_open() && is.good();
253         } else {
254                 LYXERR(Debug::LYXLEX, "lyxlex: UNcompressed");
255
256                 // The check only outputs a debug message, because it triggers
257                 // a bug in compaq cxx 6.2, where is_open() returns 'true' for
258                 // a fresh new filebuf.  (JMarc)
259                 if (fb_.is_open() || istream::off_type(is.tellg()) > 0) {
260                         LYXERR(Debug::LYXLEX, "Error in Lexer::setFile: "
261                                 "file or stream already set.");
262                 }
263                 fb_.open(filename.toFilesystemEncoding().c_str(), ios::in);
264                 is.rdbuf(&fb_);
265                 name = filename.absFilename();
266                 lineno = 0;
267                 return fb_.is_open() && is.good();
268         }
269 }
270
271
272 void Lexer::Pimpl::setStream(istream & i)
273 {
274         if (fb_.is_open() || istream::off_type(is.tellg()) > 0) {
275                 LYXERR(Debug::LYXLEX, "Error in Lexer::setStream: "
276                         "file or stream already set.");
277         }
278         is.rdbuf(i.rdbuf());
279         lineno = 0;
280 }
281
282
283 void Lexer::Pimpl::setCommentChar(char c)
284 {
285         commentChar = c;
286 }
287
288
289 bool Lexer::Pimpl::next(bool esc /* = false */)
290 {
291         if (!pushTok.empty()) {
292                 // There can have been a whole line pushed so
293                 // we extract the first word and leaves the rest
294                 // in pushTok. (Lgb)
295                 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
296                         buff.clear();
297                         pushTok = split(pushTok, buff, ' ');
298                 } else {
299                         buff = pushTok;
300                         pushTok.clear();
301                 }
302                 status = LEX_TOKEN;
303                 return true;
304         }
305
306
307         unsigned char c = 0; // getc() returns an int
308         char cc = 0;
309         status = 0;
310         while (is && !status) {
311                 is.get(cc);
312                 c = cc;
313
314                 if (c == commentChar) {
315                         // Read rest of line (fast :-)
316 #if 1
317                         // That is not fast... (Lgb)
318                         string dummy;
319                         getline(is, dummy);
320
321                         LYXERR(Debug::LYXLEX, "Comment read: `" << c << dummy << '\'');
322 #else
323                         // unfortunately ignore is buggy (Lgb)
324                         is.ignore(100, '\n');
325 #endif
326                         ++lineno;
327                         continue;
328                 }
329
330                 if (c == '\"') {
331                         buff.clear();
332
333                         if (esc) {
334
335                                 bool escaped = false;
336                                 do {
337                                         escaped = false;
338                                         is.get(cc);
339                                         c = cc;
340                                         if (c == '\r') continue;
341                                         if (c == '\\') {
342                                                 // escape the next char
343                                                 is.get(cc);
344                                                 c = cc;
345                                                 if (c == '\"' || c == '\\')
346                                                         escaped = true;
347                                                 else
348                                                         buff.push_back('\\');
349                                         }
350                                         buff.push_back(c);
351
352                                         if (!escaped && c == '\"')
353                                                 break;
354                                 } while (c != '\n' && is);
355
356                         } else {
357
358                                 do {
359                                         is.get(cc);
360                                         c = cc;
361                                         if (c != '\r')
362                                                 buff.push_back(c);
363                                 } while (c != '\"' && c != '\n' && is);
364
365                         }
366
367                         if (c != '\"') {
368                                 printError("Missing quote");
369                                 if (c == '\n')
370                                         ++lineno;
371                         }
372
373                         buff.resize(buff.size() - 1);
374                         status = LEX_DATA;
375                         break;
376                 }
377
378                 if (c == ',')
379                         continue;              /* Skip ','s */
380
381                 // using relational operators with chars other
382                 // than == and != is not safe. And if it is done
383                 // the type _have_ to be unsigned. It usually a
384                 // lot better to use the functions from cctype
385                 if (c > ' ' && is)  {
386                         buff.clear();
387
388                         do {
389                                 if (esc && c == '\\') {
390                                         // escape the next char
391                                         is.get(cc);
392                                         c = cc;
393                                         //escaped = true;
394                                 }
395                                 buff.push_back(c);
396                                 is.get(cc);
397                                 c = cc;
398                         } while (c > ' ' && c != ',' && is);
399                         status = LEX_TOKEN;
400                 }
401
402                 if (c == '\r' && is) {
403                         // The Windows support has lead to the
404                         // possibility of "\r\n" at the end of
405                         // a line.  This will stop LyX choking
406                         // when it expected to find a '\n'
407                         is.get(cc);
408                         c = cc;
409                 }
410
411                 if (c == '\n')
412                         ++lineno;
413
414         }
415         if (status)
416                 return true;
417
418         status = is.eof() ? LEX_FEOF: LEX_UNDEF;
419         buff.clear();
420         return false;
421 }
422
423
424 int Lexer::Pimpl::searchKeyword(char const * const tag) const
425 {
426         LexerKeyword search_tag = { tag, 0 };
427         LexerKeyword * res =
428                 lower_bound(table, table + no_items,
429                             search_tag, CompareTags());
430         // use the compare_ascii_no_case instead of compare_no_case,
431         // because in turkish, 'i' is not the lowercase version of 'I',
432         // and thus turkish locale breaks parsing of tags.
433         if (res != table + no_items
434             && !compare_ascii_no_case(res->tag, tag))
435                 return res->code;
436         return LEX_UNDEF;
437 }
438
439
440 int Lexer::Pimpl::lex()
441 {
442         //NOTE: possible bug.
443         if (next() && status == LEX_TOKEN)
444                 return searchKeyword(getString().c_str());
445         return status;
446 }
447
448
449 bool Lexer::Pimpl::eatLine()
450 {
451         buff.clear();
452
453         unsigned char c = '\0';
454         char cc = 0;
455         while (is && c != '\n') {
456                 is.get(cc);
457                 c = cc;
458                 //LYXERR(Debug::LYXLEX, "Lexer::EatLine read char: `" << c << '\'');
459                 if (c != '\r')
460                         buff.push_back(c);
461         }
462
463         if (c == '\n') {
464                 ++lineno;
465                 buff.resize(buff.size() - 1);
466                 status = LEX_DATA;
467                 return true;
468         } else if (buff.length() > 0) { // last line
469                 status = LEX_DATA;
470                 return true;
471         } else {
472                 return false;
473         }
474 }
475
476
477 bool Lexer::Pimpl::nextToken()
478 {
479         if (!pushTok.empty()) {
480                 // There can have been a whole line pushed so
481                 // we extract the first word and leaves the rest
482                 // in pushTok. (Lgb)
483                 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
484                         buff.clear();
485                         pushTok = split(pushTok, buff, ' ');
486                 } else {
487                         buff = pushTok;
488                         pushTok.clear();
489                 }
490                 status = LEX_TOKEN;
491                 return true;
492         }
493
494         status = 0;
495         while (is && !status) {
496                 unsigned char c = 0;
497                 char cc = 0;
498                 is.get(cc);
499                 c = cc;
500                 if (c >= ' ' && is) {
501                         buff.clear();
502
503                         if (c == '\\') { // first char == '\\'
504                                 do {
505                                         buff.push_back(c);
506                                         is.get(cc);
507                                         c = cc;
508                                 } while (c > ' ' && c != '\\' && is);
509                         } else {
510                                 do {
511                                         buff.push_back(c);
512                                         is.get(cc);
513                                         c = cc;
514                                 } while (c >= ' ' && c != '\\' && is);
515                         }
516
517                         if (c == '\\')
518                                 is.putback(c); // put it back
519                         status = LEX_TOKEN;
520                 }
521
522                 if (c == '\n')
523                         ++lineno;
524
525         }
526         if (status)
527                 return true;
528
529         status = is.eof() ? LEX_FEOF: LEX_UNDEF;
530         buff.clear();
531         return false;
532 }
533
534
535 bool Lexer::Pimpl::inputAvailable()
536 {
537         return is.good();
538 }
539
540
541 void Lexer::Pimpl::pushToken(string const & pt)
542 {
543         pushTok = pt;
544 }
545
546
547
548
549 //////////////////////////////////////////////////////////////////////
550 //
551 // Lexer
552 //
553 //////////////////////////////////////////////////////////////////////
554
555 Lexer::Lexer()
556         : pimpl_(new Pimpl(0, 0))
557 {}
558
559
560 void Lexer::init(LexerKeyword * tab, int num)
561 {
562          pimpl_ = new Pimpl(tab, num);
563 }
564
565
566 Lexer::~Lexer()
567 {
568         delete pimpl_;
569 }
570
571
572 bool Lexer::isOK() const
573 {
574         return pimpl_->inputAvailable();
575 }
576
577
578 void Lexer::setLineNumber(int l)
579 {
580         pimpl_->lineno = l;
581 }
582
583
584 int Lexer::lineNumber() const
585 {
586         return pimpl_->lineno;
587 }
588
589
590 istream & Lexer::getStream()
591 {
592         return pimpl_->is;
593 }
594
595
596 void Lexer::pushTable(LexerKeyword * tab, int num)
597 {
598         pimpl_->pushTable(tab, num);
599 }
600
601
602 void Lexer::popTable()
603 {
604         pimpl_->popTable();
605 }
606
607
608 void Lexer::printTable(ostream & os)
609 {
610         pimpl_->printTable(os);
611 }
612
613
614 void Lexer::printError(string const & message) const
615 {
616         pimpl_->printError(message);
617 }
618
619
620 bool Lexer::setFile(FileName const & filename)
621 {
622         return pimpl_->setFile(filename);
623 }
624
625
626 void Lexer::setStream(istream & i)
627 {
628         pimpl_->setStream(i);
629 }
630
631
632 void Lexer::setCommentChar(char c)
633 {
634         pimpl_->setCommentChar(c);
635 }
636
637 int Lexer::lex()
638 {
639         return pimpl_->lex();
640 }
641
642
643 int Lexer::getInteger() const
644 {
645         lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
646         if (!lastReadOk_) {
647                 pimpl_->printError("integer token missing");
648                 return -1;
649         }
650
651         if (isStrInt(pimpl_->getString()))
652                 return convert<int>(pimpl_->getString());
653
654         lastReadOk_ = false;
655         pimpl_->printError("Bad integer `$$Token'");
656         return -1;
657 }
658
659
660 double Lexer::getFloat() const
661 {
662         // replace comma with dot in case the file was written with
663         // the wrong locale (should be rare, but is easy enough to
664         // avoid).
665         lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
666         if (!lastReadOk_) {
667                 pimpl_->printError("float token missing");
668                 return -1;
669         }
670
671         string const str = subst(pimpl_->getString(), ",", ".");
672         if (isStrDbl(str))
673                 return convert<double>(str);
674
675         lastReadOk_ = false;
676         pimpl_->printError("Bad float `$$Token'");
677         return -1;
678 }
679
680
681 string const Lexer::getString() const
682 {
683         lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
684
685         if (lastReadOk_)
686         return pimpl_->getString();
687
688         return string();
689 }
690
691
692 docstring const Lexer::getDocString() const
693 {
694         lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
695
696         if (lastReadOk_)
697                 return pimpl_->getDocString();
698
699         return docstring();
700 }
701
702
703 // I would prefer to give a tag number instead of an explicit token
704 // here, but it is not possible because Buffer::readDocument uses
705 // explicit tokens (JMarc)
706 string const Lexer::getLongString(string const & endtoken)
707 {
708         string str;
709         string prefix;
710         bool firstline = true;
711
712         while (pimpl_->is) { //< eatLine only reads from is, not from pushTok
713                 if (!eatLine())
714                         // blank line in the file being read
715                         continue;
716
717                 string const token = trim(getString(), " \t");
718
719                 LYXERR(Debug::PARSER, "LongString: `" << getString() << '\'');
720
721                 // We do a case independent comparison, like searchKeyword does.
722                 if (compare_ascii_no_case(token, endtoken) == 0)
723                         break;
724
725                 string tmpstr = getString();
726                 if (firstline) {
727                         size_t i = tmpstr.find_first_not_of(' ');
728                         if (i != string::npos)
729                                 prefix = tmpstr.substr(0, i);
730                         firstline = false;
731                         LYXERR(Debug::PARSER, "Prefix = `" << prefix << "\'");
732                 }
733
734                 // further lines in long strings may have the same
735                 // whitespace prefix as the first line. Remove it.
736                 if (prefix.length() && prefixIs(tmpstr, prefix))
737                         tmpstr.erase(0, prefix.length() - 1);
738
739                 str += ltrim(tmpstr, "\t") + '\n';
740         }
741
742         if (!pimpl_->is)
743                 printError("Long string not ended by `" + endtoken + '\'');
744
745         return str;
746 }
747
748
749 bool Lexer::getBool() const
750 {
751         string const s = pimpl_->getString();   
752         if (s == "false" || s == "0") {
753                 lastReadOk_ = true;
754                 return false;
755         }
756         if (s == "true" || s == "1") {
757                 lastReadOk_ = true;
758                 return true;
759         }
760         pimpl_->printError("Bad boolean `$$Token'. "
761                                  "Use \"false\" or \"true\"");
762         lastReadOk_ = false;
763 }
764
765
766 bool Lexer::eatLine()
767 {
768         return pimpl_->eatLine();
769 }
770
771
772 bool Lexer::next(bool esc)
773 {
774         return pimpl_->next(esc);
775 }
776
777
778 bool Lexer::nextToken()
779 {
780         return pimpl_->nextToken();
781 }
782
783
784 void Lexer::pushToken(string const & pt)
785 {
786         pimpl_->pushToken(pt);
787 }
788
789
790 Lexer::operator void const *() const
791 {
792         // This behaviour is NOT the same as the streams which would
793         // use fail() here. However, our implementation of getString() et al.
794         // can cause the eof() and fail() bits to be set, even though we
795         // haven't tried to read 'em.
796         return lastReadOk_? this : 0;
797 }
798
799
800 bool Lexer::operator!() const
801 {
802         return !lastReadOk_;
803 }
804
805
806 Lexer & Lexer::operator>>(string & s)
807 {
808         if (isOK()) {
809                 next();
810                 s = getString();
811         } else {
812                 lastReadOk_ = false;
813         }
814         return *this;
815 }
816
817
818 Lexer & Lexer::operator>>(docstring & s)
819 {
820         if (isOK()) {
821                 next();
822                 s = getDocString();
823         } else {
824                 lastReadOk_ = false;
825         }
826         return *this;
827 }
828
829
830 Lexer & Lexer::operator>>(double & s)
831 {
832         if (isOK()) {
833                 next();
834                 s = getFloat();
835         } else {
836                 lastReadOk_ = false;
837         }
838         return *this;
839 }
840
841
842 Lexer & Lexer::operator>>(int & s)
843 {
844         if (isOK()) {
845                 next();
846                 s = getInteger();
847         } else {
848                 lastReadOk_ = false;
849         }
850         return *this;
851 }
852
853
854 Lexer & Lexer::operator>>(unsigned int & s)
855 {
856         if (isOK()) {
857                 next();
858                 s = getInteger();
859         } else {
860                 lastReadOk_ = false;
861         }
862         return *this;
863 }
864
865
866 Lexer & Lexer::operator>>(bool & s)
867 {
868         if (isOK()) {
869                 next();
870                 s = getBool();
871         } else {
872                 lastReadOk_ = false;
873         }
874         return *this;
875 }
876
877
878 Lexer & Lexer::operator>>(char & c)
879 {
880         string s;
881         operator>>(s);
882         if (!s.empty())
883                 c = s[0];
884         return *this;
885 }
886
887
888 // quotes a string, e.g. for use in preferences files or as an argument
889 // of the "log" dialog
890 string Lexer::quoteString(string const & arg)
891 {
892         string res;
893         res += '"';
894         res += subst(subst(arg, "\\", "\\\\"), "\"", "\\\"");
895         res += '"';
896         return res;
897 }
898
899
900 Lexer & Lexer::operator>>(char const * required)
901 {
902         string token;
903         *this >> token;
904         if (token != required) {
905                 LYXERR0("Missing '" << required << "'-tag in " << pimpl_->context 
906                         << ". Got " << token << " instead. Line: " << lineNumber());
907                 pushToken(token);
908         }
909         return *this;
910 }
911
912
913 bool Lexer::checkFor(char const * required)
914 {
915         string token;
916         *this >> token;
917         if (token == required)
918                 return true;
919         pushToken(token);
920         return false;
921 }
922
923
924 void Lexer::setContext(std::string const & str)
925 {
926         pimpl_->context = str;
927 }
928
929
930 } // namespace lyx