-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathplytoken.py
146 lines (121 loc) · 2.56 KB
/
plytoken.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
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 22 16:02:05 2019
@author: Hengky Sanjaya
"""
import ply.lex as lex
reserved = {
'if': 'IF',
'then': 'THEN',
'else': 'ELSE',
'while': 'WHILE',
'for': 'FOR',
'cin': 'CIN',
'cout': 'COUT',
'else if': 'ELSEIF',
'operator': 'OPERATOR'
,'identifier': 'IDENTIFIER'
}
tokens = [
# 'INT',
# 'FLOAT',
# 'NAME',
# 'PLUS',
# 'MINUS',
# 'DIVIDE',
# 'MULTIPLY',
'EQUALS',
'ID',
'STRING',
'LCURLY',
'RCURLY',
'LPAR',
'RPAR',
# 'AND',
# 'OR',
'SEMICOLON',
'LEFTSHIFT',
'RIGHTSHIFT'
# 'EQEQ'
] + list(reserved.values())
# t_PLUS = r'\+'
# t_MINUS = r'\-'
# t_MULTIPLY = r'\*'
# t_DIVIDE = r'\/'
t_EQUALS = r'\='
# t_EQEQ = r'\=='
t_LCURLY = r'\{'
t_RCURLY = r'\}'
t_LPAR = r'\('
t_RPAR = r'\)'
# t_AND = r'\&&'
# t_OR = r'(\|\|)'
t_SEMICOLON = r';'
t_ignore = '\t '
# t_LEFTSHIFT = '<<'
# t_RIGHTSHIFT = '>>'
#t_NEWLINE = r'\n+'
# t_SPACE = r' '
def t_IDENTIFIER(t):
r'int|string|char|bool|float'
t.type = reserved.get(t.value, 'IDENTIFIER')
print(t.value,"t_IDENTIFIER reached")
return t
def t_OPERATOR(t):
r'&&|(\|\|)'
t.type = reserved.get(t.value, 'OPERATOR')
# print("reserved : ", reserved.get(t.value, 'OPERATOR'))
return t
def t_ID(t):
r'(if|else|then|while|cin|cout)'
print(t.value, "t_ID reached")
if t.value in reserved:
t.type = reserved.get(t.value, 'STRING')
# print("reserved : ", reserved.get(t.value, 'STRING'))
return t
else:
return t
def t_LEFTSHIFT(t):
r'<<'
t.type = reserved.get(t.value, 'LEFTSHIFT')
return t
def t_RIGHTSHIFT(t):
r'>>'
t.type = reserved.get(t.value, 'RIGHTSHIFT')
return t
def t_STRING(t):
r'[a-zA-Z_0-9"<> ][a-zA-Z_=*+-/_0-9"<> ]*'
if t.value in reserved:
t.type = reserved.get(t.value, 'STRING')
return t
# def t_FLOAT(t):
# r'\d+\.\d+'
# t.value = float(t.value)
# return t
#
# def t_INT(t):
# r'\d+'
# t.value = int(t.value)
# return t
# def t_NAME(t):
# r'[a-zA-Z_][a-zA-z_0-9]*'
# t.type = 'NAME'
# return t
# Define a rule so we can track line numbers
def t_newline(t):
r'\n+'
t.lexer.lineno += len(t.value)
print('t.lexer.lineno : ',t.lexer.lineno)
# t.lexer.lineno += 1
# len(t.value)
def t_error(t):
print("Illegal characters!", t)
t.lexer.skip(1)
def t_COMMENT(t):
r'\//.*'
pass
# No return value. Token discarded
# Build the lexer
def build_lexer():
lexer = lex.lex()
return lexer