-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscanner.cc
302 lines (258 loc) · 9.14 KB
/
scanner.cc
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
#include <sstream>
#include <iomanip>
#include <cctype>
#include <algorithm>
#include <utility>
#include <set>
#include <array>
#include "scanner.h"
/*
* C++ Starter code for CS241 A3
* All code requires C++14, so if you're getting compile errors make sure to
* use -std=c++14.
*
* This file contains helpers for asm.cc and you don't need to modify it.
* Furthermore, while this code may be helpful to understand starting with
* the DFA assignments, you do not need to understand it to write the assembler.
*/
Token::Token(Token::Kind kind, std::string lexeme):
kind(kind), lexeme(std::move(lexeme)) {}
Token:: Kind Token::getKind() const { return kind; }
const std::string &Token::getLexeme() const { return lexeme; }
std::ostream &operator<<(std::ostream &out, const Token &tok) {
out << "Token(";
switch (tok.getKind()) {
case Token::ID: out << "ID"; break;
case Token::LABEL: out << "LABEL"; break;
case Token::WORD: out << "WORD"; break;
case Token::COMMA: out << "COMMA"; break;
case Token::LPAREN: out << "LPAREN"; break;
case Token::RPAREN: out << "RPAREN"; break;
case Token::INT: out << "INT"; break;
case Token::HEXINT: out << "HEXINT"; break;
case Token::REG: out << "REG"; break;
case Token::WHITESPACE: out << "WHITESPACE"; break;
case Token::COMMENT: out << "COMMENT"; break;
}
out << ", " << tok.getLexeme() << ")";
return out;
}
int64_t Token::toLong() const {
std::istringstream iss;
int64_t result;
if (kind == INT) {
iss.str(lexeme);
} else if (kind == HEXINT) {
iss.str(lexeme.substr(2));
iss >> std::hex;
} else if (kind == REG) {
iss.str(lexeme.substr(1));
} else {
// This should never happen if the user calls this function correctly
return 0;
}
iss >> result;
return result;
}
ScanningFailure::ScanningFailure(std::string message):
message(std::move(message)) {}
const std::string &ScanningFailure::what() const { return message; }
/* Represents a DFA (which you will see formally in class later)
* to handle the scanning
* process. You should not need to interact with this directly:
* it is handled through the starter code.
*/
class AsmDFA {
public:
enum State {
// States that are also kinds
ID = 0,
LABEL,
COMMA,
LPAREN,
RPAREN,
INT,
HEXINT,
REG,
WHITESPACE,
COMMENT,
// States that are not also kinds
FAIL,
START,
DOT,
DOTID,
ZERO,
ZEROX,
MINUS,
DOLLARS,
// Hack to let this be used easily in arrays. This should always be the
// final element in the enum, and should always point to the previous
// element.
LARGEST_STATE = DOLLARS
};
private:
/* A set of all accepting states for the DFA.
* Currently non-accepting states are not actually present anywhere
* in memory, but a list can be found in the constructor.
*/
std::set<State> acceptingStates;
/*
* The transition function for the DFA, stored as a map.
*/
std::array<std::array<State, 128>, LARGEST_STATE + 1> transitionFunction;
/*
* Converts a state to a kind to allow construction of Tokens from States.
* Throws an exception if conversion is not possible.
*/
Token::Kind stateToKind(State s) const {
switch(s) {
case ID: return Token::ID;
case LABEL: return Token::LABEL;
case DOTID: return Token::WORD;
case COMMA: return Token::COMMA;
case LPAREN: return Token::LPAREN;
case RPAREN: return Token::RPAREN;
case INT: return Token::INT;
case ZERO: return Token::INT;
case HEXINT: return Token::HEXINT;
case REG: return Token::REG;
case WHITESPACE: return Token::WHITESPACE;
case COMMENT: return Token::COMMENT;
default: throw ScanningFailure("ERROR: Cannot convert state to kind.");
}
}
public:
/* Tokenizes an input string according to the SMM algorithm.
* You will learn the SMM algorithm in class around the time of Assignment 6.
*/
std::vector<Token> simplifiedMaximalMunch(const std::string &input) const {
std::vector<Token> result;
State state = start();
std::string munchedInput;
// We can't use a range-based for loop effectively here
// since the iterator doesn't always increment.
for (std::string::const_iterator inputPosn = input.begin();
inputPosn != input.end();) {
State oldState = state;
state = transition(state, *inputPosn);
if (!failed(state)) {
munchedInput += *inputPosn;
oldState = state;
++inputPosn;
}
if (inputPosn == input.end() || failed(state)) {
if (accept(oldState)) {
result.push_back(Token(stateToKind(oldState), munchedInput));
munchedInput = "";
state = start();
} else {
if (failed(state)) {
munchedInput += *inputPosn;
}
throw ScanningFailure("ERROR: Simplified maximal munch failed on input: "
+ munchedInput);
}
}
}
return result;
}
/* Initializes the accepting states for the DFA.
*/
AsmDFA() {
acceptingStates = {ID, LABEL, DOTID, HEXINT,
INT, ZERO, COMMA, REG,
LPAREN, RPAREN, WHITESPACE, COMMENT};
//Non-accepting states are DOT, MINUS, ZEROX, DOLLARS, START
// Initialize transitions for the DFA
for (size_t i = 0; i < transitionFunction.size(); ++i) {
for (size_t j = 0; j < transitionFunction[0].size(); ++j) {
transitionFunction[i][j] = FAIL;
}
}
registerTransition(START, isalpha, ID);
registerTransition(START, ".", DOT);
registerTransition(START, "0", ZERO);
registerTransition(START, "123456789", INT);
registerTransition(START, "-", MINUS);
registerTransition(START, ";", COMMENT);
registerTransition(START, isspace, WHITESPACE);
registerTransition(START, "$", DOLLARS);
registerTransition(START, ",", COMMA);
registerTransition(START, "(", LPAREN);
registerTransition(START, ")", RPAREN);
registerTransition(ID, isalnum, ID);
registerTransition(ID, ":", LABEL);
registerTransition(DOT, isalpha, DOTID);
registerTransition(DOTID, isalpha, DOTID);
registerTransition(ZERO, "x", ZEROX);
registerTransition(ZERO, isdigit, INT);
registerTransition(ZEROX, isxdigit, HEXINT);
registerTransition(HEXINT, isxdigit, HEXINT);
registerTransition(MINUS, isdigit, INT);
registerTransition(INT, isdigit, INT);
registerTransition(COMMENT, [](int c) -> int { return c != '\n'; },
COMMENT);
registerTransition(WHITESPACE, isspace, WHITESPACE);
registerTransition(DOLLARS, isdigit, REG);
registerTransition(REG, isdigit, REG);
}
// Register a transition on all chars in chars
void registerTransition(State oldState, const std::string &chars,
State newState) {
for (char c : chars) {
transitionFunction[oldState][c] = newState;
}
}
// Register a transition on all chars matching test
// For some reason the cctype functions all use ints, hence the function
// argument type.
void registerTransition(State oldState, int (*test)(int), State newState) {
for (int c = 0; c < 128; ++c) {
if (test(c)) {
transitionFunction[oldState][c] = newState;
}
}
}
/* Returns the state corresponding to following a transition
* from the given starting state on the given character,
* or a special fail state if the transition does not exist.
*/
State transition(State state, char nextChar) const {
return transitionFunction[state][nextChar];
}
/* Checks whether the state returned by transition
* corresponds to failure to transition.
*/
bool failed(State state) const { return state == FAIL; }
/* Checks whether the state returned by transition
* is an accepting state.
*/
bool accept(State state) const {
return acceptingStates.count(state) > 0;
}
/* Returns the starting state of the DFA
*/
State start() const { return START; }
};
std::vector<Token> scan(const std::string &input) {
static AsmDFA theDFA;
std::vector<Token> tokens = theDFA.simplifiedMaximalMunch(input);
// We need to:
// * Throw exceptions for WORD tokens whose lexemes aren't ".word".
// * Remove WHITESPACE and COMMENT tokens entirely.
std::vector<Token> newTokens;
for (auto &token : tokens) {
if (token.getKind() == Token::WORD) {
if (token.getLexeme() == ".word") {
newTokens.push_back(token);
} else {
throw ScanningFailure("ERROR: DOTID token unrecognized: " +
token.getLexeme());
}
} else if (token.getKind() != Token::WHITESPACE
&& token.getKind() != Token::Kind::COMMENT) {
newTokens.push_back(token);
}
}
return newTokens;
}