]> git.lyx.org Git - lyx.git/blob - src/Lexer.cpp
GuiToc::initialiseParams(): Fix list type parsing
[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/debug.h"
19
20 #include "support/convert.h"
21 #include "support/FileName.h"
22 #include "support/filetools.h"
23 #include "support/gzstream.h"
24 #include "support/lstrings.h"
25 #include "support/lyxalgo.h"
26 #include "support/types.h"
27
28 #include <boost/noncopyable.hpp>
29
30 #include <functional>
31 #include <istream>
32 #include <stack>
33 #include <sstream>
34 #include <vector>
35
36 using namespace std;
37 using namespace lyx::support;
38
39 namespace lyx {
40
41 //////////////////////////////////////////////////////////////////////
42 //
43 // Lexer::Pimpl
44 //
45 //////////////////////////////////////////////////////////////////////
46
47
48 ///
49 class Lexer::Pimpl : boost::noncopyable {
50 public:
51         ///
52         Pimpl(keyword_item * tab, int num);
53         ///
54         string const getString() const;
55         ///
56         docstring const getDocString() const;
57         ///
58         void printError(string const & message) const;
59         ///
60         void printTable(ostream & os);
61         ///
62         void pushTable(keyword_item * tab, int num);
63         ///
64         void popTable();
65         ///
66         bool setFile(FileName const & filename);
67         ///
68         void setStream(istream & i);
69         ///
70         void setCommentChar(char c);
71         ///
72         bool next(bool esc = false);
73         ///
74         int search_kw(char const * const tag) const;
75         ///
76         int lex();
77         ///
78         bool eatLine();
79         ///
80         bool nextToken();
81         /// test if there is a pushed token or the stream is ok
82         bool inputAvailable();
83         ///
84         void pushToken(string const &);
85         /// fb_ is only used to open files, the stream is accessed through is.
86         filebuf fb_;
87
88         /// gz_ is only used to open files, the stream is accessed through is.
89         gz::gzstreambuf gz_;
90
91         /// the stream that we use.
92         istream is;
93         ///
94         string name;
95         ///
96         keyword_item * table;
97         ///
98         int no_items;
99         ///
100         string buff;
101         ///
102         int status;
103         ///
104         int lineno;
105         ///
106         string pushTok;
107         ///
108         char commentChar;
109 private:
110         ///
111         void verifyTable();
112         ///
113         class PushedTable {
114         public:
115                 ///
116                 PushedTable()
117                         : table_elem(0), table_siz(0) {}
118                 ///
119                 PushedTable(keyword_item * ki, int siz)
120                         : table_elem(ki), table_siz(siz) {}
121                 ///
122                 keyword_item * 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<keyword_item, keyword_item, bool> {
136 public:
137         // used by lower_bound, sort and sorted
138         bool operator()(keyword_item const & a, keyword_item 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(keyword_item * 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(keyword_item * 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         if (!esc) {
304                 unsigned char c = 0; // getc() returns an int
305                 char cc = 0;
306                 status = 0;
307                 while (is && !status) {
308                         is.get(cc);
309                         c = cc;
310                         if (c == commentChar) {
311                                 // Read rest of line (fast :-)
312 #if 1
313                                 // That is not fast... (Lgb)
314                                 string dummy;
315                                 getline(is, dummy);
316
317                                 LYXERR(Debug::LYXLEX, "Comment read: `" << c << dummy << '\'');
318 #else
319                                 // unfortunately ignore is buggy (Lgb)
320                                 is.ignore(100, '\n');
321 #endif
322                                 ++lineno;
323                                 continue;
324                         }
325
326                         if (c == '\"') {
327                                 buff.clear();
328
329                                 do {
330                                         is.get(cc);
331                                         c = cc;
332                                         if (c != '\r')
333                                                 buff.push_back(c);
334                                 } while (c != '\"' && c != '\n' && is);
335
336                                 if (c != '\"') {
337                                         printError("Missing quote");
338                                         if (c == '\n')
339                                                 ++lineno;
340                                 }
341
342                                 buff.resize(buff.size()-1);
343                                 status = LEX_DATA;
344                                 break;
345                         }
346
347                         if (c == ',')
348                                 continue;              /* Skip ','s */
349
350                                 // using relational operators with chars other
351                                 // than == and != is not safe. And if it is done
352                                 // the type _have_ to be unsigned. It usually a
353                                 // lot better to use the functions from cctype
354                         if (c > ' ' && is)  {
355                                 buff.clear();
356
357                                 do {
358                                         buff.push_back(c);
359                                         is.get(cc);
360                                         c = cc;
361                                 } while (c > ' ' && c != ',' && is);
362
363                                 status = LEX_TOKEN;
364                         }
365
366                         if (c == '\r' && is) {
367                                 // The Windows support has lead to the
368                                 // possibility of "\r\n" at the end of
369                                 // a line.  This will stop LyX choking
370                                 // when it expected to find a '\n'
371                                 is.get(cc);
372                                 c = cc;
373                         }
374
375                         if (c == '\n')
376                                 ++lineno;
377
378                 }
379                 if (status)
380                         return true;
381
382                 status = is.eof() ? LEX_FEOF: LEX_UNDEF;
383                 buff.clear();
384                 return false;
385         } else {
386                 unsigned char c = 0; // getc() returns an int
387                 char cc = 0;
388
389                 status = 0;
390                 while (is && !status) {
391                         is.get(cc);
392                         c = cc;
393
394                         // skip ','s
395                         if (c == ',')
396                                 continue;
397
398                         if (c == commentChar) {
399                                 // Read rest of line (fast :-)
400 #if 1
401                                 // That is still not fast... (Lgb)
402                                 string dummy;
403                                 getline(is, dummy);
404
405                                 LYXERR(Debug::LYXLEX, "Comment read: `" << c << dummy << '\'');
406 #else
407                                 // but ignore is also still buggy (Lgb)
408                                 // This is fast (Lgb)
409                                 is.ignore(100, '\n');
410 #endif
411                                 ++lineno;
412                                 continue;
413                         }
414
415                         // string
416                         if (c == '\"') {
417                                 buff.clear();
418
419                                 bool escaped = false;
420                                 do {
421                                         escaped = false;
422                                         is.get(cc);
423                                         c = cc;
424                                         if (c == '\r') continue;
425                                         if (c == '\\') {
426                                                 // escape the next char
427                                                 is.get(cc);
428                                                 c = cc;
429                                                 if (c == '\"' || c == '\\')
430                                                         escaped = true;
431                                                 else
432                                                         buff.push_back('\\');
433                                         }
434                                         buff.push_back(c);
435
436                                         if (!escaped && c == '\"')
437                                                 break;
438                                 } while (c != '\n' && is);
439
440                                 if (c != '\"') {
441                                         printError("Missing quote");
442                                         if (c == '\n')
443                                                 ++lineno;
444                                 }
445
446                                 buff.resize(buff.size() -1);
447                                 status = LEX_DATA;
448                                 break;
449                         }
450
451                         if (c > ' ' && is) {
452                                 buff.clear();
453
454                                 do {
455                                         if (c == '\\') {
456                                                 // escape the next char
457                                                 is.get(cc);
458                                                 c = cc;
459                                                 //escaped = true;
460                                         }
461                                         buff.push_back(c);
462                                         is.get(cc);
463                                         c = cc;
464                                 } while (c > ' ' && c != ',' && is);
465
466                                 status = LEX_TOKEN;
467                         }
468                         // new line
469                         if (c == '\n')
470                                 ++lineno;
471                 }
472
473                 if (status)
474                         return true;
475
476                 status = is.eof() ? LEX_FEOF : LEX_UNDEF;
477                 buff.clear();
478                 return false;
479         }
480 }
481
482
483 int Lexer::Pimpl::search_kw(char const * const tag) const
484 {
485         keyword_item search_tag = { tag, 0 };
486         keyword_item * res =
487                 lower_bound(table, table + no_items,
488                             search_tag, CompareTags());
489         // use the compare_ascii_no_case instead of compare_no_case,
490         // because in turkish, 'i' is not the lowercase version of 'I',
491         // and thus turkish locale breaks parsing of tags.
492         if (res != table + no_items
493             && !compare_ascii_no_case(res->tag, tag))
494                 return res->code;
495         return LEX_UNDEF;
496 }
497
498
499 int Lexer::Pimpl::lex()
500 {
501         //NOTE: possible bug.
502         if (next() && status == LEX_TOKEN)
503                 return search_kw(getString().c_str());
504         return status;
505 }
506
507
508 bool Lexer::Pimpl::eatLine()
509 {
510         buff.clear();
511
512         unsigned char c = '\0';
513         char cc = 0;
514         while (is && c != '\n') {
515                 is.get(cc);
516                 c = cc;
517                 //LYXERR(Debug::LYXLEX, "Lexer::EatLine read char: `" << c << '\'');
518                 if (c != '\r')
519                         buff.push_back(c);
520         }
521
522         if (c == '\n') {
523                 ++lineno;
524                 buff.resize(buff.size() - 1);
525                 status = LEX_DATA;
526                 return true;
527         } else if (buff.length() > 0) { // last line
528                 status = LEX_DATA;
529                 return true;
530         } else {
531                 return false;
532         }
533 }
534
535
536 bool Lexer::Pimpl::nextToken()
537 {
538         if (!pushTok.empty()) {
539                 // There can have been a whole line pushed so
540                 // we extract the first word and leaves the rest
541                 // in pushTok. (Lgb)
542                 if (pushTok[0] == '\\' && pushTok.find(' ') != string::npos) {
543                         buff.clear();
544                         pushTok = split(pushTok, buff, ' ');
545                 } else {
546                         buff = pushTok;
547                         pushTok.clear();
548                 }
549                 status = LEX_TOKEN;
550                 return true;
551         }
552
553         status = 0;
554         while (is && !status) {
555                 unsigned char c = 0;
556                 char cc = 0;
557                 is.get(cc);
558                 c = cc;
559                 if (c >= ' ' && is) {
560                         buff.clear();
561
562                         if (c == '\\') { // first char == '\\'
563                                 do {
564                                         buff.push_back(c);
565                                         is.get(cc);
566                                         c = cc;
567                                 } while (c > ' ' && c != '\\' && is);
568                         } else {
569                                 do {
570                                         buff.push_back(c);
571                                         is.get(cc);
572                                         c = cc;
573                                 } while (c >= ' ' && c != '\\' && is);
574                         }
575
576                         if (c == '\\')
577                                 is.putback(c); // put it back
578                         status = LEX_TOKEN;
579                 }
580
581                 if (c == '\n')
582                         ++lineno;
583
584         }
585         if (status)
586                 return true;
587
588         status = is.eof() ? LEX_FEOF: LEX_UNDEF;
589         buff.clear();
590         return false;
591 }
592
593
594 bool Lexer::Pimpl::inputAvailable()
595 {
596         return is.good();
597 }
598
599
600 void Lexer::Pimpl::pushToken(string const & pt)
601 {
602         pushTok = pt;
603 }
604
605
606
607
608 //////////////////////////////////////////////////////////////////////
609 //
610 // Lexer
611 //
612 //////////////////////////////////////////////////////////////////////
613
614 Lexer::Lexer(keyword_item * tab, int num)
615         : pimpl_(new Pimpl(tab, num))
616 {}
617
618
619 Lexer::~Lexer()
620 {
621         delete pimpl_;
622 }
623
624
625 bool Lexer::isOK() const
626 {
627         return pimpl_->inputAvailable();
628 }
629
630
631 void Lexer::setLineNo(int l)
632 {
633         pimpl_->lineno = l;
634 }
635
636
637 int Lexer::getLineNo() const
638 {
639         return pimpl_->lineno;
640 }
641
642
643 istream & Lexer::getStream()
644 {
645         return pimpl_->is;
646 }
647
648
649 void Lexer::pushTable(keyword_item * tab, int num)
650 {
651         pimpl_->pushTable(tab, num);
652 }
653
654
655 void Lexer::popTable()
656 {
657         pimpl_->popTable();
658 }
659
660
661 void Lexer::printTable(ostream & os)
662 {
663         pimpl_->printTable(os);
664 }
665
666
667 void Lexer::printError(string const & message) const
668 {
669         pimpl_->printError(message);
670 }
671
672
673 bool Lexer::setFile(FileName const & filename)
674 {
675         return pimpl_->setFile(filename);
676 }
677
678
679 void Lexer::setStream(istream & i)
680 {
681         pimpl_->setStream(i);
682 }
683
684
685 void Lexer::setCommentChar(char c)
686 {
687         pimpl_->setCommentChar(c);
688 }
689
690 int Lexer::lex()
691 {
692         return pimpl_->lex();
693 }
694
695
696 int Lexer::getInteger() const
697 {
698         lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
699         if (!lastReadOk_) {
700                 pimpl_->printError("integer token missing");
701                 return -1;
702         }
703
704         if (isStrInt(pimpl_->getString()))
705                 return convert<int>(pimpl_->getString());
706
707         lastReadOk_ = false;
708         pimpl_->printError("Bad integer `$$Token'");
709         return -1;
710 }
711
712
713 double Lexer::getFloat() const
714 {
715         // replace comma with dot in case the file was written with
716         // the wrong locale (should be rare, but is easy enough to
717         // avoid).
718         lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
719         if (!lastReadOk_) {
720                 pimpl_->printError("float token missing");
721                 return -1;
722         }
723
724         string const str = subst(pimpl_->getString(), ",", ".");
725         if (isStrDbl(str))
726                 return convert<double>(str);
727
728         lastReadOk_ = false;
729         pimpl_->printError("Bad float `$$Token'");
730         return -1;
731 }
732
733
734 string const Lexer::getString() const
735 {
736         lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
737
738         if (lastReadOk_)
739         return pimpl_->getString();
740
741         return string();
742 }
743
744
745 docstring const Lexer::getDocString() const
746 {
747         lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
748
749         if (lastReadOk_)
750                 return pimpl_->getDocString();
751
752         return docstring();
753 }
754
755
756 // I would prefer to give a tag number instead of an explicit token
757 // here, but it is not possible because Buffer::readDocument uses
758 // explicit tokens (JMarc)
759 string const Lexer::getLongString(string const & endtoken)
760 {
761         string str, prefix;
762         bool firstline = true;
763
764         while (pimpl_->is) { //< eatLine only reads from is, not from pushTok
765                 if (!eatLine())
766                         // blank line in the file being read
767                         continue;
768
769                 string const token = trim(getString(), " \t");
770
771                 LYXERR(Debug::PARSER, "LongString: `" << getString() << '\'');
772
773                 // We do a case independent comparison, like search_kw does.
774                 if (compare_ascii_no_case(token, endtoken) == 0)
775                         break;
776
777                 string tmpstr = getString();
778                 if (firstline) {
779                         string::size_type i(tmpstr.find_first_not_of(' '));
780                         if (i != string::npos)
781                                 prefix = tmpstr.substr(0, i);
782                         firstline = false;
783                         LYXERR(Debug::PARSER, "Prefix = `" << prefix << "\'");
784                 }
785
786                 // further lines in long strings may have the same
787                 // whitespace prefix as the first line. Remove it.
788                 if (prefix.length() && prefixIs(tmpstr, prefix)) {
789                         tmpstr.erase(0, prefix.length() - 1);
790                 }
791
792                 str += ltrim(tmpstr, "\t") + '\n';
793         }
794
795         if (!pimpl_->is) {
796                 printError("Long string not ended by `" + endtoken + '\'');
797         }
798
799         return str;
800 }
801
802
803 bool Lexer::getBool() const
804 {
805         if (pimpl_->getString() == "true") {
806                 lastReadOk_ = true;
807                 return true;
808         } else if (pimpl_->getString() != "false") {
809                 pimpl_->printError("Bad boolean `$$Token'. "
810                                    "Use \"false\" or \"true\"");
811                 lastReadOk_ = false;
812         }
813         lastReadOk_ = true;
814         return false;
815 }
816
817
818 bool Lexer::eatLine()
819 {
820         return pimpl_->eatLine();
821 }
822
823
824 bool Lexer::next(bool esc)
825 {
826         return pimpl_->next(esc);
827 }
828
829
830 bool Lexer::nextToken()
831 {
832         return pimpl_->nextToken();
833 }
834
835
836 void Lexer::pushToken(string const & pt)
837 {
838         pimpl_->pushToken(pt);
839 }
840
841
842 Lexer::operator void const *() const
843 {
844         // This behaviour is NOT the same as the streams which would
845         // use fail() here. However, our implementation of getString() et al.
846         // can cause the eof() and fail() bits to be set, even though we
847         // haven't tried to read 'em.
848         return lastReadOk_? this : 0;
849 }
850
851
852 bool Lexer::operator!() const
853 {
854         return !lastReadOk_;
855 }
856
857
858 Lexer & Lexer::operator>>(string & s)
859 {
860         if (isOK()) {
861                 next();
862                 s = getString();
863         } else {
864                 lastReadOk_ = false;
865         }
866         return *this;
867 }
868
869
870 Lexer & Lexer::operator>>(docstring & s)
871 {
872         if (isOK()) {
873                 next();
874                 s = getDocString();
875         } else {
876                 lastReadOk_ = false;
877         }
878         return *this;
879 }
880
881
882 Lexer & Lexer::operator>>(double & s)
883 {
884         if (isOK()) {
885                 next();
886                 s = getFloat();
887         } else {
888                 lastReadOk_ = false;
889         }
890         return *this;
891 }
892
893
894 Lexer & Lexer::operator>>(int & s)
895 {
896         if (isOK()) {
897                 next();
898                 s = getInteger();
899         } else {
900                 lastReadOk_ = false;
901         }
902         return *this;
903 }
904
905
906 Lexer & Lexer::operator>>(unsigned int & s)
907 {
908         if (isOK()) {
909                 next();
910                 s = getInteger();
911         } else {
912                 lastReadOk_ = false;
913         }
914         return *this;
915 }
916
917
918 Lexer & Lexer::operator>>(bool & s)
919 {
920         if (isOK()) {
921                 next();
922                 s = getBool();
923         } else {
924                 lastReadOk_ = false;
925         }
926         return *this;
927 }
928
929
930 /// quotes a string, e.g. for use in preferences files or as an argument of the "log" dialog
931 string const Lexer::quoteString(string const & arg)
932 {
933         ostringstream os;
934         os << '"' << subst(subst(arg, "\\", "\\\\"), "\"", "\\\"") << '"';
935         return os.str();
936 }
937
938
939 } // namespace lyx