]> git.lyx.org Git - features.git/blob - src/Lexer.cpp
'using namespace lyx::support' instead of 'using support::xxx'
[features.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/filetools.h"
22 #include "support/gzstream.h"
23 #include "support/lstrings.h"
24 #include "support/lyxalgo.h"
25 #include "support/types.h"
26 #include "support/unicode.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         std::string const getString() const;
55         ///
56         docstring const getDocString() const;
57         ///
58         void printError(std::string const & message) const;
59         ///
60         void printTable(std::ostream & os);
61         ///
62         void pushTable(keyword_item * tab, int num);
63         ///
64         void popTable();
65         ///
66         bool setFile(support::FileName const & filename);
67         ///
68         void setStream(std::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(std::string const &);
85         /// fb_ is only used to open files, the stream is accessed through is.
86         std::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         std::istream is;
93         ///
94         std::string name;
95         ///
96         keyword_item * table;
97         ///
98         int no_items;
99         ///
100         std::string buff;
101         ///
102         int status;
103         ///
104         int lineno;
105         ///
106         std::string pushTok;
107         ///
108         char commentChar;
109 private:
110         ///
111         void verifyTable();
112         ///
113         class pushed_table {
114         public:
115                 ///
116                 pushed_table()
117                         : table_elem(0), table_siz(0) {}
118                 ///
119                 pushed_table(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         std::stack<pushed_table> pushed;
128 };
129
130
131
132 namespace {
133
134 class compare_tags
135         : public std::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, compare_tags())) {
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, compare_tags());
201                 lyxerr << "\nSorted:" << endl;
202                 printTable(lyxerr);
203         }
204 }
205
206
207 void Lexer::Pimpl::pushTable(keyword_item * tab, int num)
208 {
209         pushed_table 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         pushed_table 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, compare_tags());
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 == '\\') is.putback(c); // put it back
577                         status = LEX_TOKEN;
578                 }
579
580                 if (c == '\n')
581                         ++lineno;
582
583         }
584         if (status)
585                 return true;
586
587         status = is.eof() ? LEX_FEOF: LEX_UNDEF;
588         buff.clear();
589         return false;
590 }
591
592
593 bool Lexer::Pimpl::inputAvailable()
594 {
595         return is.good();
596 }
597
598
599 void Lexer::Pimpl::pushToken(string const & pt)
600 {
601         pushTok = pt;
602 }
603
604
605
606
607 //////////////////////////////////////////////////////////////////////
608 //
609 // Lexer
610 //
611 //////////////////////////////////////////////////////////////////////
612
613 Lexer::Lexer(keyword_item * tab, int num)
614         : pimpl_(new Pimpl(tab, num))
615 {}
616
617
618 Lexer::~Lexer()
619 {
620         delete pimpl_;
621 }
622
623
624 bool Lexer::isOK() const
625 {
626         return pimpl_->inputAvailable();
627 }
628
629
630 void Lexer::setLineNo(int l)
631 {
632         pimpl_->lineno = l;
633 }
634
635
636 int Lexer::getLineNo() const
637 {
638         return pimpl_->lineno;
639 }
640
641
642 istream & Lexer::getStream()
643 {
644         return pimpl_->is;
645 }
646
647
648 void Lexer::pushTable(keyword_item * tab, int num)
649 {
650         pimpl_->pushTable(tab, num);
651 }
652
653
654 void Lexer::popTable()
655 {
656         pimpl_->popTable();
657 }
658
659
660 void Lexer::printTable(ostream & os)
661 {
662         pimpl_->printTable(os);
663 }
664
665
666 void Lexer::printError(string const & message) const
667 {
668         pimpl_->printError(message);
669 }
670
671
672 bool Lexer::setFile(support::FileName const & filename)
673 {
674         return pimpl_->setFile(filename);
675 }
676
677
678 void Lexer::setStream(istream & i)
679 {
680         pimpl_->setStream(i);
681 }
682
683
684 void Lexer::setCommentChar(char c)
685 {
686         pimpl_->setCommentChar(c);
687 }
688
689 int Lexer::lex()
690 {
691         return pimpl_->lex();
692 }
693
694
695 int Lexer::getInteger() const
696 {
697         lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
698         if (!lastReadOk_) {
699                 pimpl_->printError("integer token missing");
700                 return -1;
701         }
702
703         if (isStrInt(pimpl_->getString()))
704                 return convert<int>(pimpl_->getString());
705
706         lastReadOk_ = false;
707         pimpl_->printError("Bad integer `$$Token'");
708         return -1;
709 }
710
711
712 double Lexer::getFloat() const
713 {
714         // replace comma with dot in case the file was written with
715         // the wrong locale (should be rare, but is easy enough to
716         // avoid).
717         lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
718         if (!lastReadOk_) {
719                 pimpl_->printError("float token missing");
720                 return -1;
721         }
722
723         string const str = subst(pimpl_->getString(), ",", ".");
724         if (isStrDbl(str))
725                 return convert<double>(str);
726
727         lastReadOk_ = false;
728         pimpl_->printError("Bad float `$$Token'");
729         return -1;
730 }
731
732
733 string const Lexer::getString() const
734 {
735         lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
736
737         if (lastReadOk_)
738         return pimpl_->getString();
739
740         return string();
741 }
742
743
744 docstring const Lexer::getDocString() const
745 {
746         lastReadOk_ = pimpl_->status == LEX_DATA || pimpl_->status == LEX_TOKEN;
747
748         if (lastReadOk_)
749                 return pimpl_->getDocString();
750
751         return docstring();
752 }
753
754
755 // I would prefer to give a tag number instead of an explicit token
756 // here, but it is not possible because Buffer::readDocument uses
757 // explicit tokens (JMarc)
758 string const Lexer::getLongString(string const & endtoken)
759 {
760         string str, prefix;
761         bool firstline = true;
762
763         while (pimpl_->is) { //< eatLine only reads from is, not from pushTok
764                 if (!eatLine())
765                         // blank line in the file being read
766                         continue;
767
768                 string const token = trim(getString(), " \t");
769
770                 LYXERR(Debug::PARSER, "LongString: `" << getString() << '\'');
771
772                 // We do a case independent comparison, like search_kw does.
773                 if (compare_ascii_no_case(token, endtoken) == 0)
774                         break;
775
776                 string tmpstr = getString();
777                 if (firstline) {
778                         string::size_type i(tmpstr.find_first_not_of(' '));
779                         if (i != string::npos)
780                                 prefix = tmpstr.substr(0, i);
781                         firstline = false;
782                         LYXERR(Debug::PARSER, "Prefix = `" << prefix << "\'");
783                 }
784
785                 // further lines in long strings may have the same
786                 // whitespace prefix as the first line. Remove it.
787                 if (prefix.length() && prefixIs(tmpstr, prefix)) {
788                         tmpstr.erase(0, prefix.length() - 1);
789                 }
790
791                 str += ltrim(tmpstr, "\t") + '\n';
792         }
793
794         if (!pimpl_->is) {
795                 printError("Long string not ended by `" + endtoken + '\'');
796         }
797
798         return str;
799 }
800
801
802 bool Lexer::getBool() const
803 {
804         if (pimpl_->getString() == "true") {
805                 lastReadOk_ = true;
806                 return true;
807         } else if (pimpl_->getString() != "false") {
808                 pimpl_->printError("Bad boolean `$$Token'. "
809                                    "Use \"false\" or \"true\"");
810                 lastReadOk_ = false;
811         }
812         lastReadOk_ = true;
813         return false;
814 }
815
816
817 bool Lexer::eatLine()
818 {
819         return pimpl_->eatLine();
820 }
821
822
823 bool Lexer::next(bool esc)
824 {
825         return pimpl_->next(esc);
826 }
827
828
829 bool Lexer::nextToken()
830 {
831         return pimpl_->nextToken();
832 }
833
834
835 void Lexer::pushToken(string const & pt)
836 {
837         pimpl_->pushToken(pt);
838 }
839
840
841 Lexer::operator void const *() const
842 {
843         // This behaviour is NOT the same as the std::streams which would
844         // use fail() here. However, our implementation of getString() et al.
845         // can cause the eof() and fail() bits to be set, even though we
846         // haven't tried to read 'em.
847         return lastReadOk_? this : 0;
848 }
849
850
851 bool Lexer::operator!() const
852 {
853         return !lastReadOk_;
854 }
855
856
857 Lexer & Lexer::operator>>(std::string & s)
858 {
859         if (isOK()) {
860                 next();
861                 s = getString();
862         } else {
863                 lastReadOk_ = false;
864         }
865         return *this;
866 }
867
868
869 Lexer & Lexer::operator>>(docstring & s)
870 {
871         if (isOK()) {
872                 next();
873                 s = getDocString();
874         } else {
875                 lastReadOk_ = false;
876         }
877         return *this;
878 }
879
880
881 Lexer & Lexer::operator>>(double & s)
882 {
883         if (isOK()) {
884                 next();
885                 s = getFloat();
886         } else {
887                 lastReadOk_ = false;
888         }
889         return *this;
890 }
891
892
893 Lexer & Lexer::operator>>(int & s)
894 {
895         if (isOK()) {
896                 next();
897                 s = getInteger();
898         } else {
899                 lastReadOk_ = false;
900         }
901         return *this;
902 }
903
904
905 Lexer & Lexer::operator>>(unsigned int & s)
906 {
907         if (isOK()) {
908                 next();
909                 s = getInteger();
910         } else {
911                 lastReadOk_ = false;
912         }
913         return *this;
914 }
915
916
917 Lexer & Lexer::operator>>(bool & s)
918 {
919         if (isOK()) {
920                 next();
921                 s = getBool();
922         } else {
923                 lastReadOk_ = false;
924         }
925         return *this;
926 }
927
928
929 /// quotes a string, e.g. for use in preferences files or as an argument of the "log" dialog
930 string const Lexer::quoteString(string const & arg)
931 {
932         std::ostringstream os;
933         os << '"' << subst(subst(arg, "\\", "\\\\"), "\"", "\\\"") << '"';
934         return os.str();
935 }
936
937
938 } // namespace lyx