4 // Copyright (C) 2006 Matthias Braun <matze@braunis.de>
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License
8 // as published by the Free Software Foundation; either version 2
9 // of the License, or (at your option) any later version.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
32 Lexer::Lexer(std::istream& newstream)
33 : stream(newstream), eof(false), linenumber(0)
35 // trigger a refill of the buffer
48 if(bufpos >= bufend) {
53 stream.read(buffer, BUFFER_SIZE);
54 size_t bytes_read = stream.gcount();
57 bufend = buffer + bytes_read;
59 // the following is a hack that appends an additional ' ' at the end of
60 // the file to avoid problems when parsing symbols/elements and a sudden
61 // EOF. This is faster than relying on unget and IMO also nicer.
62 if(bytes_read == 0 || stream.eof()) {
76 if(token_length < MAX_TOKEN_LENGTH)
77 token_string[token_length++] = c;
84 static const char* delims = "\"();";
97 return getNextToken(); // and again
100 return TOKEN_OPEN_PAREN;
103 return TOKEN_CLOSE_PAREN;
104 case '"': { // string
105 int startline = linenumber;
111 goto string_finished;
128 std::stringstream msg;
129 msg << "Parse error in line " << startline << ": "
130 << "EOF while parsing string.";
131 throw std::runtime_error(msg.str());
136 if(token_length < MAX_TOKEN_LENGTH)
137 token_string[token_length++] = c;
140 token_string[token_length] = 0;
143 case '#': // constant
146 while(isalnum(c) || c == '_') {
149 token_string[token_length] = 0;
151 if(strcmp(token_string, "t") == 0)
153 if(strcmp(token_string, "f") == 0)
156 // we only handle #t and #f constants at the moment...
158 std::stringstream msg;
159 msg << "Parse Error in line " << linenumber << ": "
160 << "Unknown constant '" << token_string << "'.";
161 throw std::runtime_error(msg.str());
168 if(isdigit(c) || c == '-') {
169 bool have_nondigits = false;
170 bool have_digits = false;
171 int have_floating_point = 0;
177 ++have_floating_point;
178 else if(isalnum(c) || c == '_')
179 have_nondigits = true;
182 } while(!isspace(c) && !strchr(delims, c));
184 token_string[token_length] = 0;
188 if(have_nondigits || !have_digits || have_floating_point > 1)
190 else if(have_floating_point == 1)
193 return TOKEN_INTEGER;
197 } while(!isspace(c) && !strchr(delims, c));
198 token_string[token_length] = 0;
207 } // end of namespace lisp