Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

adding exception handling #1

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
4 changes: 2 additions & 2 deletions cplusplus/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

A library that that transforms python code into cpp code.

The 'temp.py' file metamorphosed into 'temp.cpp'.
The 'temp.py' file gets metamorphosed into 'temp.cpp'.

## Libraries created

Expand All @@ -19,4 +19,4 @@ Taking the input and producing output of a script.
Extracting text from the code. We get two lists of strings, one is a list of keywords ('print' etc),
and a list of texts (the text enclosed in parentheses).

This is not a stable version as exception handling has not been implemented.
Currently, the code is being tested for bugs.
195 changes: 173 additions & 22 deletions cplusplus/extract/extract.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
"""

import re
import scriptIO

""" stable """
"""
gets the keywords (print etc), and the text within thr parentheses

Expand All @@ -16,36 +19,184 @@

returns: keywords (list of strings), texts (list of strings)
"""
def extractFromScript(text):
def clean_raw_code(text):
keywords = []
texts = []

for line in text:
try:

if str(line)[0] == '':
continue
"""
get value before the parentheses
"""
keyword = re.compile("(.*?)\s*\(")
flag = re.search("(.*?)\s*\(", line)
if flag is None:
continue
else:
keyword = keyword.match(line)
keyword = keyword.group(1)
keywords.append(keyword)

"""
get value in the parentheses
"""
text = re.compile(".*?\((.*?)\)")
text = text.match(line)
text = text.group(1)
texts.append(text)

except:
keywords, texts = -1, -1
print("An error occurred while applying regular expressions")
raise

return keywords, texts

""" stable """
# returns whether comment exists or not and if yes the column number also
def comment_exists(text):
col = text.find('#')
if(col != -1):
return 1, col
else:
return 0, -1


""" stable """
""" returns the indices of the rows where code and / or comments are present"""

def get_indices(script):

codeRowIndices, commentRowIndices = [], []
row = 0
flag, col = 0, 0

for line in script:
row += 1
flag, col = comment_exists(line)

# check whether comment exists on the line
if(flag):
# add the row number to commentIndices
commentRowIndices.append(row)
if (col > 0):
codeRowIndices.append(row)

"""
get value before the parentheses
"""
keyword = re.compile("(.*?)\s*\(")
keyword = keyword.match(line)
keyword = keyword.group(1)
keywords.append(keyword)

"""
get value in the parentheses
"""
text = re.compile(".*?\((.*?)\)")
text = text.match(line)
text = text.group(1)
texts.append(text)
# if line has an empty line
elif line == '':
continue

return keywords, texts
else:
codeRowIndices.append(row)

return commentRowIndices, codeRowIndices


""" stable """
"""
removes the comments from the python script
def comment(text):

removes the single line comments from the python script
"""
def strip_comments(script):
"""
initializing empty lists to get the comments,
and an empty string to store the comments
"""
comments = []
comment = ''
row = 0

# iterate over the script line by line
for line in script:

row += 1
# get single line comments

if line.find('#') != -1:

# get where the comment begins in the line
ind = line.find('#')



# isolate commment from the line
comment = (str(line))[ind:]

# append comment to the list of comments
comments.append(comment)


# replacing the comments in script with an empty string
def replaceCharacters(s, unwanted, input_char = ''):
# Iterate over the strings to be replaced
for elem in unwanted:
# Replace the string, does not do anything if `elem` not in `s`
s = s.replace(elem, input_char)
return s

# call the function
script_new = [replaceCharacters(x, comments) for x in script]


# remove all the empty strings in the script_new
raw_code = list(filter(None, script_new))

return raw_code, comments


""" the code below is the proof of concept for converting python comments to cpp comments """

"""
keywords, texts = extractFromScript(script)
filename = 'temp.py'
script = scriptIO.readScript(filename)
script = list(filter(None, script))
commentRowIndices, codeRowIndices = get_indices(script)
commentRowIndices.append(-1)
codeRowIndices.append(-1)
raw_code, comments = stripComments(script)
keywords, texts = clean_raw_code(raw_code)
print(texts[0])
print(str(comments[0])[1:])
#
def POC(keywords, texts, comments, commentRowIndices, codeRowIndices):
codeIterator, commentIterator = 0, 0

len_code = len(keywords)

len_comments = len(comments)

while(codeIterator < len_code and commentIterator < len_comments):
if(codeRowIndices[codeIterator] == commentRowIndices[commentIterator]):

print('print ' + str(texts[codeIterator]) + ' // ' + str(comments[commentIterator])[1:] + '\n')
codeIterator += 1
commentIterator += 1

elif (codeRowIndices[codeIterator] > commentRowIndices[commentIterator]):

print('// ' + str(comments[commentIterator])[1:] + '\n')
commentIterator += 1

elif (codeRowIndices[codeIterator] < commentRowIndices[commentIterator]):

if keywords[codeIterator] == 'print':
print('print ' + str(texts[codeIterator]) + '\n')
codeIterator += 1


while(commentIterator < len_comments):
print('// ' + str(comments[commentIterator])[1:] + '\n')
commentIterator += 1

while(codeIterator < len_code):
if keywords[codeIterator] == 'print':
print('print ' + str(texts[codeIterator]) + '\n')
codeIterator += 1



POC(keywords, texts, comments, commentRowIndices, codeRowIndices)

"""

9 changes: 9 additions & 0 deletions cplusplus/helloWorld.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#include<iostream>

using namespace std;
int main(void){
// This is a working model for converting python scripts to .cpp files
cout << "\nHello World!" ; // comment 1
cout << "\nThis is Bhasha" ; // comment 2
return 0;
}
41 changes: 27 additions & 14 deletions cplusplus/scriptIO/scriptIO.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,39 @@
# -*- coding: utf-8 -*-
""" -*- coding: utf-8 -*- """
"""
Created on Tue Jun 9 20:49:09 2020

@author: vgadi
"""

import sys
""" stable """
"""
reads a .py script

function readScript() has the following parameters:

1) filename (string): the name of the file from which text to be extracted

returns: list of strings with newlines split as '\n'
returns: list of strings new lines split with '\n'
"""
def readScript(filename):
# open file to read
script = open(filename, 'r')
# read the file
script = script.read()
# convert the newlines into '\n'
script = script.split('\n')
return script


try:
# open file to read
script = open(filename, 'r')
# read the file
script = script.read()
# convert the newlines into '\n'
script = script.split('\n')
return script
except OSError as err:
print("OS error: {0}".format(err))
raise
except:
print("Unexpected error: ", sys.exc_info()[0])
raise


""" stable """
"""
creating the required file

Expand All @@ -36,7 +46,10 @@ def readScript(filename):
returns: nothing
"""
def createScript(extension, code, filename = 'helloWorld'):
filename = filename + extension
writeFile = open(filename, 'w')
try:
filename = filename + extension
writeFile = open(filename, 'w')

writeFile = writeFile.write(code)
writeFile = writeFile.write(code)
except:
print("\nAn error occrred while writing to file.")
Loading