2 // Copyright (C) 2006 Matthias Braun <matze@braunis.de>
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with this program. If not, see <http://www.gnu.org/licenses/>.
17 #include "lisp/lexer.hpp"
26 Lexer::Lexer(std::istream& newstream)
27 : stream(newstream), eof(false), linenumber(0)
29 // trigger a refill of the buffer
42 if(bufpos >= bufend) {
47 stream.read(buffer, BUFFER_SIZE);
48 size_t bytes_read = stream.gcount();
51 bufend = buffer + bytes_read;
53 // the following is a hack that appends an additional ' ' at the end of
54 // the file to avoid problems when parsing symbols/elements and a sudden
55 // EOF. This is faster than relying on unget and IMO also nicer.
56 if(bytes_read == 0 || stream.eof()) {
70 if(token_length < MAX_TOKEN_LENGTH)
71 token_string[token_length++] = c;
78 static const char* delims = "\"();";
91 return getNextToken(); // and again
94 return TOKEN_OPEN_PAREN;
97 return TOKEN_CLOSE_PAREN;
99 int startline = linenumber;
105 goto string_finished;
122 std::stringstream msg;
123 msg << "Parse error in line " << startline << ": "
124 << "EOF while parsing string.";
125 throw std::runtime_error(msg.str());
130 if(token_length < MAX_TOKEN_LENGTH)
131 token_string[token_length++] = c;
134 token_string[token_length] = 0;
137 case '#': // constant
140 while(isalnum(c) || c == '_') {
143 token_string[token_length] = 0;
145 if(strcmp(token_string, "t") == 0)
147 if(strcmp(token_string, "f") == 0)
150 // we only handle #t and #f constants at the moment...
152 std::stringstream msg;
153 msg << "Parse Error in line " << linenumber << ": "
154 << "Unknown constant '" << token_string << "'.";
155 throw std::runtime_error(msg.str());
162 if(isdigit(c) || c == '-') {
163 bool have_nondigits = false;
164 bool have_digits = false;
165 int have_floating_point = 0;
171 ++have_floating_point;
172 else if(isalnum(c) || c == '_')
173 have_nondigits = true;
176 } while(!isspace(c) && !strchr(delims, c));
178 token_string[token_length] = 0;
182 if(have_nondigits || !have_digits || have_floating_point > 1)
184 else if(have_floating_point == 1)
187 return TOKEN_INTEGER;
191 } while(!isspace(c) && !strchr(delims, c));
192 token_string[token_length] = 0;
201 } // end of namespace lisp