-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathScanner.py
224 lines (181 loc) · 6.04 KB
/
Scanner.py
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
# pylint: disable = unused-wildcard-import
# pylint: disable = too-few-public-methods
"""
Filename: Scanner.py
Description: Tokenizer to break text input into tokens
The tokenizer is built to suport a MATLAB script with basic
functionality as input
Author: Juan Trejo
Github: https://github.com/jtrejo13
"""
# -------
# imports
# -------
from typing import Dict
# ----------------------------------------------------
# Token Types
#
# ID (variable name): used to represent an identifier,
# or variable, in the program
#
# EOF (end-of-file): token is used to indicate that
# there is no more input left for lexical analysis
# ----------------------------------------------------
ID, INTEGER, FLOAT, ASSIGN, PLUS, MINUS, MUL, DIV, LPAREN, RPAREN, SEMI, EOF = (
'ID', 'INTEGER', 'FLOAT', 'ASSIGN', 'PLUS', 'MINUS', 'MUL', 'DIV', 'LPAREN', 'RPAREN', 'SEMI', 'EOF'
)
"""
Reserved Keywords
Words that cannot be used as identifier, such as the name
of a variable or function
"""
RESERVED_KEYWORDS = {} # type: Dict[str, Token]
class Token(object):
"""
A class to represent a valid token in a MATLAB script
Args:
type (Token Type): The type of the token
value (str_int_or_float): The value of the token
Attributes:
type (Token Type): The type of the token
value (str_int_or_float): The value of the token
"""
def __init__(self, type, value):
self.type = type
self.value = value
def __str__(self):
"""
Returns:
str: String representation of token
Examples:
'Token(INTEGER, 2)'
'Token(FLOAT, 3.5)'
'Token(MINUS, -)'
'Token(ID, myVar)'
"""
return 'Token({type}, {value})'.format(
type=self.type,
value=self.value
)
def __repr__(self):
"""String representation of token"""
return self.__str__()
class Scanner(object):
"""
Tokenizer of a MATLAB script
Args:
text(str): The input text to be tokenized
Attributes:
text(str): The input text to be tokenized
"""
def __init__(self, text):
self.text = text
self._pos = 0
try:
self.current_char = self.text[self._pos]
except IndexError:
self.current_char = None
def next_token(self):
"""
Scans and outputs the next token in the input text
Returns:
token(Token): The next valid token in the input text.
If EOF file is reached, returns (EOF, None) token
Raises:
Expection: If invalid charcter is provided
"""
while self.current_char is not None:
if self.current_char == '%':
self._skip_comment()
continue
if self.current_char.isspace():
self.skip_whitespace()
continue
if self.current_char.isdigit():
token = self.get_number()
return token
if self.current_char == '+':
self.advance()
return Token(PLUS, '+')
if self.current_char == '-':
self.advance()
return Token(MINUS, '-')
if self.current_char == '*':
self.advance()
return Token(MUL, '*')
if self.current_char == '/':
self.advance()
return Token(DIV, '/')
if self.current_char == '(':
self.advance()
return Token(LPAREN, '(')
if self.current_char == ')':
self.advance()
return Token(RPAREN, ')')
if self.current_char.isalnum():
return self._id()
if self.current_char == '=':
self.advance()
return Token(ASSIGN, '=')
if self.current_char == ';':
self.advance()
return Token(SEMI, ';')
self.raise_error() # if invalid character
return Token(EOF, None)
def get_number(self):
"""Scans input for a real or integer number"""
start = self._pos
while self.current_char is not None \
and (self.current_char.isdigit() or self.current_char == '.'):
self.advance()
result = self.text[start:self._pos]
period_count = result.count('.')
if period_count > 1:
self.raise_error()
elif period_count == 1:
return Token(FLOAT, float(result))
else:
return Token(INTEGER, int(result))
def _id(self):
start = self._pos
while self.current_char is not None \
and self.current_char.isalnum():
self.advance()
result = self.text[start:self._pos]
return RESERVED_KEYWORDS.get(result, Token(ID, result))
def advance(self):
"""Advances internal pointer by one character"""
self._pos += 1
if self._pos > len(self.text) - 1:
self.current_char = None
else:
self.current_char = self.text[self._pos]
def peek(self):
"""
Looks at one character past the current position
Returns:
character(str): The character next to the current position
"""
peek_pos = self._pos + 1
if peek_pos > len(self.text) - 1:
return None
# else: still in bounds
return self.text[peek_pos]
def _skip_comment(self):
while self.current_char is not None \
and self.current_char != '\n':
self.advance()
def skip_whitespace(self):
"""
Skips all whitespace in input up to the next
non-whitespace character or until the EOF is reached
"""
while self.current_char is not None \
and self.current_char.isspace():
self.advance()
def raise_error(self):
"""
Raises:
Exception: Invalid character exception
"""
raise Exception('Invalid character')