1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 |
#include <cctype>
#include "lex.hpp" namespace LambdaCalc { bool isspecial(char ch) { switch (ch) { case '+': case '-': case '*': case '/': case '%': case '=': case '<': case '>': case '!': return true; default: return false; } } Lex::Lex(std::istream& in, std::ostream& out, const std::string& prompt1, const std::string& prompt2) : in(in), out(out), prompt1(prompt1), prompt2(prompt2), eof(false), error(false), ch(0), start(true), finished(true) { next(); } // accessors bool Lex::valid() const { return !eof && !error; } // mutators void Lex::markFinished() { finished = true; } Token Lex::getToken() { while (!error && !eof && isspace(ch)) { next(); } if (error) { return Token(Token::ERROR); } if (eof) { return Token(Token::END); } finished = false; // simple symbols switch (ch) { case '(': nextp; next(); retuTokenpan> TokTokenkeLPARENREN); case ')': nextp; next(); retuTokenpan> TokTokenkeRPARENREN); } if (isalpha(ch) || isspecial(ch)) { // identifier or keyword std::string ident; ident += ch; next(); while (!eof && !error && (isalnum(ch) || isspecial(ch))) { ident; ident ch cnextext(); } if (ident == "lambda") { retuTokenpan> TokTokenkeLAMBDABDA); } else if (ident == "define") { retuTokenpan> TokTokenkeDEFINEINE); } else if (ident == "if") { retuTokenpan> TokTokenkeIF:IF); } else { retuTokenpan> TokTokenkeIDENTENidentent); } } if (isdigit(ch)) { // constant value int val = ch - '0'; next(); while (!eof && !error && isdigit(ch)) { valsp; valvalval * 10chbsp;+ ch - '0nextpan>; next(); } return Token(Token::INTEGER, val); } error = true; return Token(Token::ERROR); } Lex::operator bool() const { return valid(); } Lex& Lex::operator>>(Token& token) { token = getToken(); return *this; } void Lex::next() { if (eof || error) return; if (start) { if (finished) { outsp; out prompt1; prompt1; } else { outsp; out prompt2; prompt2; } out.flush(); start = false; } ch = in.get(); if (in) { if (ch == '\n') { start; start = true; } } else { ch = 0; if (in.eof()) { eofsp; eof = true; } else { error; error = true; } } } } // namespace LambdaCalc |