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.
31 Lexer::Lexer(std::istream& newstream)
32 : stream(newstream), eof(false), linenumber(0)
34 // trigger a refill of the buffer
47 if(bufpos >= bufend) {
52 stream.read(buffer, BUFFER_SIZE);
53 size_t bytes_read = stream.gcount();
56 bufend = buffer + bytes_read;
58 // the following is a hack that appends an additional ' ' at the end of
59 // the file to avoid problems when parsing symbols/elements and a sudden
60 // EOF. This is faster than relying on unget and IMO also nicer.
61 if(bytes_read == 0 || stream.eof()) {
75 if(token_length < MAX_TOKEN_LENGTH)
76 token_string[token_length++] = c;
83 static const char* delims = "\"();";
96 return getNextToken(); // and again
99 return TOKEN_OPEN_PAREN;
102 return TOKEN_CLOSE_PAREN;
103 case '"': { // string
104 int startline = linenumber;
110 goto string_finished;
127 std::stringstream msg;
128 msg << "Parse error in line " << startline << ": "
129 << "EOF while parsing string.";
130 throw std::runtime_error(msg.str());
135 if(token_length < MAX_TOKEN_LENGTH)
136 token_string[token_length++] = c;
139 token_string[token_length] = 0;
142 case '#': // constant
145 while(isalnum(c) || c == '_') {
148 token_string[token_length] = 0;
150 if(strcmp(token_string, "t") == 0)
152 if(strcmp(token_string, "f") == 0)
155 // we only handle #t and #f constants at the moment...
157 std::stringstream msg;
158 msg << "Parse Error in line " << linenumber << ": "
159 << "Unknown constant '" << token_string << "'.";
160 throw std::runtime_error(msg.str());
167 if(isdigit(c) || c == '-') {
168 bool have_nondigits = false;
169 bool have_digits = false;
170 int have_floating_point = 0;
176 ++have_floating_point;
177 else if(isalnum(c) || c == '_')
178 have_nondigits = true;
181 } while(!isspace(c) && !strchr(delims, c));
183 token_string[token_length] = 0;
187 if(have_nondigits || !have_digits || have_floating_point > 1)
189 else if(have_floating_point == 1)
192 return TOKEN_INTEGER;
196 } while(!isspace(c) && !strchr(delims, c));
197 token_string[token_length] = 0;
206 } // end of namespace lisp