-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpyndi.py
310 lines (229 loc) · 13 KB
/
pyndi.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
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
303
304
305
306
307
308
309
310
# -*- coding: utf-8 -*-
import sys
import time
import re
import traceback
from contextlib import redirect_stdout
from io import StringIO
import os
# reading filename from the system arguments coming from command line
n = len(sys.argv)
print("Total arguments passed:", n)
print("First argument :",sys.argv[0])
print("Filename :",sys.argv[1])
#filename = input("Enter filename")
filename = sys.argv[1]
#removing blank lines from the pyndi file before-hand
with open(filename) as reader, open(filename, 'r+') as writer:
for line in reader:
if line.strip():
writer.write(line)
writer.truncate()
# opening and reading the user's pyndi file
text_file = open(filename, "r")
#read whole file to a string
code_pyndi = text_file.read()
#close file
text_file.close()
print('$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$')
print('------------pyndi code begins here------------')
print(code_pyndi)
print('------------pyndi code ends here------------')
print('$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$')
keyword_list=['if','elif','else','while','print','for']
def string_replacement(code_python):
string_list_double = re.findall(r'"(.*?)"', code_python)
string_list_single = re.findall(r"'(.*?)'", code_python)
comment_list = re.findall('#(.+?)\n', code_python)
string_list_total = string_list_double + string_list_single+ comment_list
string_list = []
counter = 0
for string_i in string_list_total:
code_python = code_python.replace(string_i ,"str_"+str(counter))
string_list.append(string_i)
counter = counter + 1
#collect lines in line_list
return string_list, code_python
def translate_keywords(code_pyndi):
# Also getting string list out so that it isnt affected
string_list, code_python=string_replacement(code_pyndi)
code_python = code_python.lower()
# All the translation happens here
# removing empty lines
line_list = []
for line in code_python.splitlines():
line_stripped = re.sub(r'\s+', '', line)
line_restripped = re.sub(r'(\s|\u180B|\u200B|\u200C|\u200D|\u2060|\uFEFF)+', '', line_stripped)
if len(line_restripped)>0:
line_list.append(line)
code_python = "\n".join(line_list)
#minor_translations_(similar_words_into_one_convention)
#maybe a better idea is to use arrays to handle them
while_words = ["jabtk","jbtk","jbtak","jabtak","jab tak","jb tk","jb tak","jab tk"]
while_regex = re.compile(r'\b%s\b' % r'\b|\b'.join(map(re.escape, while_words)))
code_python = while_regex.sub("while", code_python)
nahin_words = ["nhi to","nhin to","nahi to","naahi to"]
nahin_regex = re.compile(r'\b%s\b' % r'\b|\b'.join(map(re.escape, nahin_words)))
code_python = nahin_regex.sub("nahin to", code_python)
bdhaao_words = ["badhao","bdhao","bdha","bdhaa","jodo","jod","jdo"]
bdhaao_regex = re.compile(r'\b%s\b' % r'\b|\b'.join(map(re.escape, bdhaao_words)))
code_python = bdhaao_regex.sub("bdhaao", code_python)
ghtaao_words = ["ghtao","kam kro","kam krdo","km kro","km krdo","ghatao","ghta"]
ghtaao_regex = re.compile(r'\b%s\b' % r'\b|\b'.join(map(re.escape, ghtaao_words)))
code_python = ghtaao_regex.sub("ghtaao", code_python)
bhaag_words = ["bhag","vibhajit","wibhajit","vibhajan","wibhajan","bhaag"]
bhaag_regex = re.compile(r'\b%s\b' % r'\b|\b'.join(map(re.escape, bhaag_words)))
code_python = bhaag_regex.sub("bhaag", code_python)
print_words = ["likh","likho","bol","dikha","dikhao","dikhaao"]
print_regex = re.compile(r'\b%s\b' % r'\b|\b'.join(map(re.escape, print_words)))
code_python = print_regex.sub("print", code_python)
barabar_words = ["barabar","brabr","barabr"]
barabar_regex = re.compile(r'\b%s\b' % r'\b|\b'.join(map(re.escape, barabar_words)))
code_python = barabar_regex.sub("=", code_python)
code_python = code_python.replace("agr","agar")
code_python = code_python.replace("ydi","agar")
code_python = code_python.replace("yadi","agar")
code_python = code_python.replace("har","hr")
code_python = code_python.replace("lekar","lekr")
# if else conditions **** The order of replacement here needs to be maintained ****
code_python = code_python.replace("nahin to agar","elif")
code_python = code_python.replace("agar","if")
code_python = code_python.replace("nahin to","else")
return code_python, string_list
code_python, string_list = translate_keywords(code_pyndi)
print('$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$')
print('------------code after translation begins here------------')
print(code_python)
print('------------code after translation ends here------------')
print('$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$')
#making_efficient_by_performing_splitting_only_once
def for_and_dec_op_syntax_simpli(code_python,string_list):
"""
this function takes 'translated' pyndi code and processes for loop
hr (har) is the keyword used to know that the for loop begins there
currently only works for numbers
need to generalise it for all for loop
then deciphers the operations and operands present in all the lines
finally some syntax simplification stuff
"""
code_python_list=code_python.splitlines() # extracting_lines
line_list=[]
for line in code_python_list:
#### handling indentation ######
line = line.replace(" ","\t")
number_of_spaces = len(line) - len(line.lstrip())
line = line.lstrip()
#### handling print statement----starts
# just handling no brackets for now
if "print" in line:
if line[5] == " ":
line = line.replace("print ","print(")
line = line + ')'
#### handling print statement----ends
#### handling for statement----starts
if 'hr' in line: #seeking if it has 'hr'; if so it has to be 'if' statement
word_list=line.strip().split(' ') #splitting line
hr_index=word_list.index('hr') #where is 'hr'?
var=word_list[hr_index+1]
low_limit=word_list[0] #extracting the lower_limit of variable
upp_limit=word_list[3] #extracting the upper_limit of variable
line='for '+var+' in range('+ low_limit + ','+upp_limit+ '):'
#rephrasing line as a standard python code
#### handling for statement----ends
####deciphering operations and operands-----starts
### if these three conditions are not met, we assume that the line contains statement for updating a variable
############# IMPORTANT - THESE CONDITIONS MIGHT BREAK DOWN AS NEW FUNCTIONS ARE ADDED ################
if 'bdhaao' in line or 'ghtaao'in line or 'guna'in line or 'bhaag' in line: ##(3) no print statement
# Need number of spaces to keep track of indentation
# currently only works when indentation is done using tab
#indentation thing
## var is the variable and r_var is the number by which it needs to be updated by
## assuming semantic-rule is followed (specified in readme)
r_var=line.strip().split(" ")[2]
first_word = line.strip().split(" ")[0] #extracting r_var
var=first_word #extracting var
# updation can be of four types, add subtract multiply or divide
if 'bdhaao'in line: #addition
line = var + '=' + var + '+' + r_var #rephrasing line as a standard python code
elif 'ghtaao'in line: #subtraction
line = var + '=' + var + '-' + r_var #rephrasing line as a standard python code
elif 'guna'in line: #multiplication
line = var + '=' + var + '*' + r_var #rephrasing line as a standard python code
elif 'bhaag' in line: #divison
if (r_var=="0"):
print("maaf kijiye, 0 se bhaag nhi krste") #divison by zero error
line = var + '=' + var + '/' + r_var #rephrasing line as a standard python code
else:
line = var + '=' + var + '/' + r_var #rephrasing line as a standard python code
else:
print(line + " ko is trh se likh bhai: a ko 1 se bdhaa do") #if user does not follow semantic-rule
#indentation thing
####deciphering operations and operands-----ends
####handling minor syntax things in if statement---starts
###(based on the observation that only comparison operator should follow if/elif statements)
if 'if' in line:
# comparison operator two different ways
if ("barabar" in line):
line=line.replace("barabar",'==')
if line.count('=')==1:
line=line.replace("=","==")
line = line.lstrip()
### Removing the need for colon in if, for and while statements
if 'for' in line or 'while' in line or 'if' in line or 'elif' in line or 'else' in line:
if line.count(':')==0:
line=line+':'
####handling minor syntax things in if statement---ends
####refining_the_print_statement_part_2-----starts
#### displaying_variable's_name_alongwith_value
if 'print' in line:
if '"' not in line: #variable written in print's argument
if "'" not in line:
obc_index=line.rfind('(')
cbc_index=line.rfind(')')
var_name=line[obc_index+1:cbc_index] #extracting variable's name
line = 'print("' + var_name + ' itna hai :",' +var_name + ')' #refined print statement
####refining_the_print_statement_part_2-----ends
line = ' '*number_of_spaces*6+line
line_list.append(line) #appending the modified line to line_list
code_python = "\n".join(line_list)
for counter in range(len(string_list)):
code_python = code_python.replace("str_"+str(counter),string_list[counter])
return code_python
code_python=for_and_dec_op_syntax_simpli(code_python,string_list)
print('$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$')
print('------------Final python code begins here------------')
print(code_python)
print('------------Final python code ends here------------')
print('$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$')
exec(code_python)
# Saving the python code in a .py file just in case the user wants it
filename_py = filename.split(".")[0] + ".py"
py_file = open(filename_py, "w")
n = py_file.write(code_python)
py_file.close()
f = StringIO()
try:
with redirect_stdout(f):
exec(code_python)
s = f.getvalue()
s = "Bahut Badhiya! Aapka code sahi se chala \n" + s
except Exception as e:
error_message = traceback.format_exc()
error_message = error_message.replace("Traceback (most recent call last):","Kuch to gadbad hai. Daya, pata karo!")
error_message = error_message.replace('File "<string>", ',"")
error_message_list = error_message.splitlines(True)
error_message_list.pop(1)
error_message_list.pop(1)
error_line_list=[]
for line in error_message_list:
if "line" in line:
line_no = line.lstrip().split(" ")[1]
line_no = line_no[:-1]
line = "Gadbad shayad line " + line_no + " mein hai\n"
error_line_list.append(line)
error_message = "".join(error_line_list)
s = error_message
filename_output = filename.split(".")[0] + "_output.txt"
output_file = open(filename_output, "w")
n = output_file.write(s)
output_file.close()