]> git.lyx.org Git - lyx.git/blob - src/Lexer.cpp
remove 50 lines of duplicated code
[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 search_kw(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 private:
106         /// non-copyable
107         Pimpl(Pimpl const &);
108         void operator=(Pimpl const &);
109
110         ///
111         void verifyTable();
112         ///
113         class PushedTable {
114         public:
115                 ///
116                 PushedTable()
117                         : table_elem(0), table_siz(0) {}
118                 ///
119                 PushedTable(LexerKeyword * ki, int siz)
120                         : table_elem(ki), table_siz(siz) {}
121                 ///
122                 LexerKeyword * table_elem;
123                 ///
124                 int table_siz;
125         };
126         ///
127         stack<PushedTable> pushed;
128 };
129
130
131
132 namespace {
133
134 class CompareTags
135         : public binary_function<LexerKeyword, LexerKeyword, bool> {
136 public:
137         // used by lower_bound, sort and sorted
138         bool operator()(LexerKeyword const & a, LexerKeyword const & b) const
139         {
140                 // we use the ascii version, because in turkish, 'i'
141                 // is not the lowercase version of 'I', and thus
142                 // turkish locale breaks parsing of tags.
143                 return compare_ascii_no_case(a.tag, b.tag) < 0;
144         }
145 };
146
147 } // end of anon namespace
148
149
150 Lexer::Pimpl::Pimpl(LexerKeyword * tab, int num)
151         : is(&fb_), table(tab), no_items(num),
152           status(0), lineno(0), commentChar('#')
153 {
154         verifyTable();
155 }
156
157
158 string const Lexer::Pimpl::getString() const
159 {
160         return buff;
161 }
162
163
164 docstring const Lexer::Pimpl::getDocString() const
165 {
166         return from_utf8(buff);
167 }
168
169
170 void Lexer::Pimpl::printError(string const & message) const
171 {
172         string const tmpmsg = subst(message, "$$Token", getString());
173         lyxerr << "LyX: " << tmpmsg << " [around line " << lineno
174                 << " of file " << to_utf8(makeDisplayPath(name)) << ']' << 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         // Check the format of the file.
236         string const format = filename.guessFormatFromContents();
237
238         if (format == "gzip" || format == "zip" || format == "compress") {
239                 LYXERR(Debug::LYXLEX, "lyxlex: compressed");
240                 // The check only outputs a debug message, because it triggers
241                 // a bug in compaq cxx 6.2, where is_open() returns 'true' for
242                 // a fresh new filebuf.  (JMarc)
243                 if (gz_.is_open() || istream::off_type(is.tellg()) > -1)
244                         LYXERR(Debug::LYXLEX, "Error in LyXLex::setFile: "
245                                 "file or stream already set.");
246                 gz_.open(filename.toFilesystemEncoding().c_str(), ios::in);
247                 is.rdbuf(&gz_);
248                 name = filename.absFilename();
249                 lineno = 0;
250                 return gz_.is_open() && is.good();
251         } else {
252                 LYXERR(Debug::LYXLEX, "lyxlex: UNcompressed");
253
254                 // The check only outputs a debug message, because it triggers
255                 // a bug in compaq cxx 6.2, where is_open() returns 'true' for
256                 // a fresh new filebuf.  (JMarc)
257                 if (fb_.is_open() || istream::off_type(is.tellg()) > 0) {
258                         LYXERR(Debug::LYXLEX, "Error in Lexer::setFile: "
259                                 "file or stream already set.");
260                 }
261                 fb_.open(filename.toFilesystemEncoding().c_str(), ios::in);
262                 is.rdbuf(&fb_);
263                 name = filename.absFilename();
264                 lineno = 0;
265                 return fb_.is_open() && is.good();
266         }
267 }
268
269
270 void Lexer::Pimpl::setStream(istream & i)
271 {
272         if (fb_.is_open() || istream::off_type(is.tellg()) > 0) {
273                 LYXERR(Debug::LYXLEX, "Error in Lexer::setStream: "
274                         "file or stream already set.");
275         }
276         is.rdbuf(i.rdbuf());
277         lineno = 0;
278 }
279
280
281 void Lexer::Pimpl::setCommentChar(char c)
282 {
283         commentChar = c;
284 }
285
286
287 bool Lexer::Pimpl::next(bool esc /* = false */)
288 {
289         if (!pushTok.empty()) {
290                 // There can have been a whole line pushed so
291                 // we extract the first word and leaves the rest
292                 // in pushTok. (Lgb)
293                 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
294                         buff.clear();
295                         pushTok = split(pushTok, buff, ' ');
296                 } else {
297                         buff = pushTok;
298                         pushTok.clear();
299                 }
300                 status = LEX_TOKEN;
301                 return true;
302         }
303
304
305         unsigned char c = 0; // getc() returns an int
306         char cc = 0;
307         status = 0;
308         while (is && !status) {
309                 is.get(cc);
310                 c = cc;
311
312                 // skip ','s
313                 if (esc && c == ',')
314                         continue;
315
316                 
317                 if (c == commentChar) {
318                         // Read rest of line (fast :-)
319 #if 1
320                         // That is not fast... (Lgb)
321                         string dummy;
322                         getline(is, dummy);
323
324                         LYXERR(Debug::LYXLEX, "Comment read: `" << c << dummy << '\'');
325 #else
326                         // unfortunately ignore is buggy (Lgb)
327                         is.ignore(100, '\n');
328 #endif
329                         ++lineno;
330                         continue;
331                 }
332
333                 if (c == '\"') {
334                         buff.clear();
335
336                         if (esc) {
337
338                                 bool escaped = false;
339                                 do {
340                                         escaped = false;
341                                         is.get(cc);
342                                         c = cc;
343                                         if (c == '\r') continue;
344                                         if (c == '\\') {
345                                                 // escape the next char
346                                                 is.get(cc);
347                                                 c = cc;
348                                                 if (c == '\"' || c == '\\')
349                                                         escaped = true;
350                                                 else
351                                                         buff.push_back('\\');
352                                         }
353                                         buff.push_back(c);
354
355                                         if (!escaped && c == '\"')
356                                                 break;
357                                 } while (c != '\n' && is);
358
359                         } else {
360
361                                 do {
362                                         is.get(cc);
363                                         c = cc;
364                                         if (c != '\r')
365                                                 buff.push_back(c);
366                                 } while (c != '\"' && c != '\n' && is);
367
368                         }
369
370                         if (c != '\"') {
371                                 printError("Missing quote");
372                                 if (c == '\n')
373                                         ++lineno;
374                         }
375
376                         buff.resize(buff.size() - 1);
377                         status = LEX_DATA;
378                         break;
379                 }
380
381                 if (!esc && c == ',')
382                         continue;              /* Skip ','s */
383
384                         // using relational operators with chars other
385                         // than == and != is not safe. And if it is done
386                         // the type _have_ to be unsigned. It usually a
387                         // lot better to use the functions from cctype
388                 if (c > ' ' && is)  {
389                         buff.clear();
390
391                         do {
392                                 if (esc && c == '\\') {
393                                         // escape the next char
394                                         is.get(cc);
395                                         c = cc;
396                                         //escaped = true;
397                                 }
398                                 buff.push_back(c);
399                                 is.get(cc);
400                                 c = cc;
401                         } while (c > ' ' && c != ',' && is);
402                         status = LEX_TOKEN;
403                 }
404
405                 if (!esc && c == '\r' && is) {
406                         // The Windows support has lead to the
407                         // possibility of "\r\n" at the end of
408                         // a line.  This will stop LyX choking
409                         // when it expected to find a '\n'
410                         is.get(cc);
411                         c = cc;
412                 }
413
414                 if (c == '\n')
415                         ++lineno;
416
417         }
418         if (status)
419                 return true;
420
421         status = is.eof() ? LEX_FEOF: LEX_UNDEF;
422         buff.clear();
423         return false;
424 }
425
426
427 int Lexer::Pimpl::search_kw(char const * const tag) const
428 {
429         LexerKeyword search_tag = { tag, 0 };
430         LexerKeyword * res =
431                 lower_bound(table, table + no_items,
432                             search_tag, CompareTags());
433         // use the compare_ascii_no_case instead of compare_no_case,
434         // because in turkish, 'i' is not the lowercase version of 'I',
435         // and thus turkish locale breaks parsing of tags.
436         if (res != table + no_items
437             && !compare_ascii_no_case(res->tag, tag))
438                 return res->code;
439         return LEX_UNDEF;
440 }
441
442
443 int Lexer::Pimpl::lex()
444 {
445         //NOTE: possible bug.
446         if (next() && status == LEX_TOKEN)
447                 return search_kw(getString().c_str());
448         return status;
449 }
450
451
452 bool Lexer::Pimpl::eatLine()
453 {
454         buff.clear();
455
456         unsigned char c = '\0';
457         char cc = 0;
458         while (is && c != '\n') {
459                 is.get(cc);
460                 c = cc;
461                 //LYXERR(Debug::LYXLEX, "Lexer::EatLine read char: `" << c << '\'');
462                 if (c != '\r')
463                         buff.push_back(c);
464         }
465
466         if (c == '\n') {
467                 ++lineno;
468                 buff.resize(buff.size() - 1);
469                 status = LEX_DATA;
470                 return true;
471         } else if (buff.length() > 0) { // last line
472                 status = LEX_DATA;
473                 return true;
474         } else {
475                 return false;
476         }
477 }
478
479
480 bool Lexer::Pimpl::nextToken()
481 {
482         if (!pushTok.empty()) {
483                 // There can have been a whole line pushed so
484                 // we extract the first word and leaves the rest
485                 // in pushTok. (Lgb)
486                 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
487                         buff.clear();
488                         pushTok = split(pushTok, buff, ' ');
489                 } else {
490                         buff = pushTok;
491                         pushTok.clear();
492                 }
493                 status = LEX_TOKEN;
494                 return true;
495         }
496
497         status = 0;
498         while (is && !status) {
499                 unsigned char c = 0;
500                 char cc = 0;
501                 is.get(cc);
502                 c = cc;
503                 if (c >= ' ' && is) {
504                         buff.clear();
505
506                         if (c == '\\') { // first char == '\\'
507                                 do {
508                                         buff.push_back(c);
509                                         is.get(cc);
510                                         c = cc;
511                                 } while (c > ' ' && c != '\\' && is);
512                         } else {
513                                 do {
514                                         buff.push_back(c);
515                                         is.get(cc);
516                                         c = cc;
517                                 } while (c >= ' ' && c != '\\' && is);
518                         }
519
520                         if (c == '\\')
521                                 is.putback(c); // put it back
522                         status = LEX_TOKEN;
523                 }
524
525                 if (c == '\n')
526                         ++lineno;
527
528         }
529         if (status)
530                 return true;
531
532         status = is.eof() ? LEX_FEOF: LEX_UNDEF;
533         buff.clear();
534         return false;
535 }
536
537
538 bool Lexer::Pimpl::inputAvailable()
539 {
540         return is.good();
541 }
542
543
544 void Lexer::Pimpl::pushToken(string const & pt)
545 {
546         pushTok = pt;
547 }
548
549
550
551
552 //////////////////////////////////////////////////////////////////////
553 //
554 // Lexer
555 //
556 //////////////////////////////////////////////////////////////////////
557
558 Lexer::Lexer()
559         : pimpl_(new Pimpl(0, 0))
560 {}
561
562
563 void Lexer::init(LexerKeyword * tab, int num)
564 {
565          pimpl_ = new Pimpl(tab, num);
566 }
567
568
569 Lexer::~Lexer()
570 {
571         delete pimpl_;
572 }
573
574
575 bool Lexer::isOK() const
576 {
577         return pimpl_->inputAvailable();
578 }
579
580
581 void Lexer::setLineNumber(int l)
582 {
583         pimpl_->lineno = l;
584 }
585
586
587 int Lexer::lineNumber() const
588 {
589         return pimpl_->lineno;
590 }
591
592
593 istream & Lexer::getStream()
594 {
595         return pimpl_->is;
596 }
597
598
599 void Lexer::pushTable(LexerKeyword * tab, int num)
600 {
601         pimpl_->pushTable(tab, num);
602 }
603
604
605 void Lexer::popTable()
606 {
607         pimpl_->popTable();
608 }
609
610
611 void Lexer::printTable(ostream & os)
612 {
613         pimpl_->printTable(os);
614 }
615
616
617 void Lexer::printError(string const & message) const
618 {
619         pimpl_->printError(message);
620 }
621
622
623 bool Lexer::setFile(FileName const & filename)
624 {
625         return pimpl_->setFile(filename);
626 }
627
628
629 void Lexer::setStream(istream & i)
630 {
631         pimpl_->setStream(i);
632 }
633
634
635 void Lexer::setCommentChar(char c)
636 {
637         pimpl_->setCommentChar(c);
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 search_kw 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         if (pimpl_->getString() == "true") {
755                 lastReadOk_ = true;
756                 return true;
757         } else if (pimpl_->getString() != "false") {
758                 pimpl_->printError("Bad boolean `$$Token'. "
759                                    "Use \"false\" or \"true\"");
760                 lastReadOk_ = false;
761         }
762         lastReadOk_ = true;
763         return false;
764 }
765
766
767 bool Lexer::eatLine()
768 {
769         return pimpl_->eatLine();
770 }
771
772
773 bool Lexer::next(bool esc)
774 {
775         return pimpl_->next(esc);
776 }
777
778
779 bool Lexer::nextToken()
780 {
781         return pimpl_->nextToken();
782 }
783
784
785 void Lexer::pushToken(string const & pt)
786 {
787         pimpl_->pushToken(pt);
788 }
789
790
791 Lexer::operator void const *() const
792 {
793         // This behaviour is NOT the same as the streams which would
794         // use fail() here. However, our implementation of getString() et al.
795         // can cause the eof() and fail() bits to be set, even though we
796         // haven't tried to read 'em.
797         return lastReadOk_? this : 0;
798 }
799
800
801 bool Lexer::operator!() const
802 {
803         return !lastReadOk_;
804 }
805
806
807 Lexer & Lexer::operator>>(string & s)
808 {
809         if (isOK()) {
810                 next();
811                 s = getString();
812         } else {
813                 lastReadOk_ = false;
814         }
815         return *this;
816 }
817
818
819 Lexer & Lexer::operator>>(docstring & s)
820 {
821         if (isOK()) {
822                 next();
823                 s = getDocString();
824         } else {
825                 lastReadOk_ = false;
826         }
827         return *this;
828 }
829
830
831 Lexer & Lexer::operator>>(double & s)
832 {
833         if (isOK()) {
834                 next();
835                 s = getFloat();
836         } else {
837                 lastReadOk_ = false;
838         }
839         return *this;
840 }
841
842
843 Lexer & Lexer::operator>>(int & s)
844 {
845         if (isOK()) {
846                 next();
847                 s = getInteger();
848         } else {
849                 lastReadOk_ = false;
850         }
851         return *this;
852 }
853
854
855 Lexer & Lexer::operator>>(unsigned int & s)
856 {
857         if (isOK()) {
858                 next();
859                 s = getInteger();
860         } else {
861                 lastReadOk_ = false;
862         }
863         return *this;
864 }
865
866
867 Lexer & Lexer::operator>>(bool & s)
868 {
869         if (isOK()) {
870                 next();
871                 s = getBool();
872         } else {
873                 lastReadOk_ = false;
874         }
875         return *this;
876 }
877
878
879 // quotes a string, e.g. for use in preferences files or as an argument
880 // of the "log" dialog
881 string const Lexer::quoteString(string const & arg)
882 {
883         string res;
884         res += '"';
885         res += subst(subst(arg, "\\", "\\\\"), "\"", "\\\"");
886         res += '"';
887         return res;
888 }
889
890
891 } // namespace lyx