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) :
36 // trigger a refill of the buffer
49 if(bufpos >= bufend) {
54 stream.read(buffer, BUFFER_SIZE);
55 size_t bytes_read = stream.gcount();
58 bufend = buffer + bytes_read;
60 // the following is a hack that appends an additional ' ' at the end of
61 // the file to avoid problems when parsing symbols/elements and a sudden
62 // EOF. This is faster than relying on unget and IMO also nicer.
63 if(bytes_read == 0 || stream.eof()) {
77 if(token_length < MAX_TOKEN_LENGTH)
78 token_string[token_length++] = c;
85 static const char* delims = "\"();";
98 return getNextToken(); // and again
101 return TOKEN_OPEN_PAREN;
104 return TOKEN_CLOSE_PAREN;
105 case '"': { // string
106 int startline = linenumber;
112 goto string_finished;
129 std::stringstream msg;
130 msg << "Parse error in line " << startline << ": "
131 << "EOF while parsing string.";
132 throw std::runtime_error(msg.str());
137 if(token_length < MAX_TOKEN_LENGTH)
138 token_string[token_length++] = c;
141 token_string[token_length] = 0;
144 case '#': // constant
147 while(isalnum(c) || c == '_') {
150 token_string[token_length] = 0;
152 if(strcmp(token_string, "t") == 0)
154 if(strcmp(token_string, "f") == 0)
157 // we only handle #t and #f constants at the moment...
159 std::stringstream msg;
160 msg << "Parse Error in line " << linenumber << ": "
161 << "Unknown constant '" << token_string << "'.";
162 throw std::runtime_error(msg.str());
169 if(isdigit(c) || c == '-') {
170 bool have_nondigits = false;
171 bool have_digits = false;
172 int have_floating_point = 0;
178 ++have_floating_point;
179 else if(isalnum(c) || c == '_')
180 have_nondigits = true;
183 } while(!isspace(c) && !strchr(delims, c));
185 token_string[token_length] = 0;
189 if(have_nondigits || !have_digits || have_floating_point > 1)
191 else if(have_floating_point == 1)
194 return TOKEN_INTEGER;
198 } while(!isspace(c) && !strchr(delims, c));
199 token_string[token_length] = 0;
208 } // end of namespace lisp