This isn't robustly written for pattern matching as a C sharp to Python translator but at least it provides a somewhat easier method for porting code with literal translation. I manage to do this by the way through a combination of things, but some key points are some translator dictionary terms
instantiationkeywords
- A string match on these word terms means that list type is provided from a given c sharp array type to a python list type. In python lists may commonly be grown or shrunk through a populate or remove functions, but I opted for the method of instantiating a fixed list type matching a given array.
defheaderwords
-or type (e.g., int is integer type, double is double type, and so forth) , there is also another layer (redundant) in matching a given type whether it falls into a python list type of specific multidimensional allotment or not a list at all. This type list can be customized for pattern matching on keywords, by simply populating added type words with translation data.
This may still have some bugs, although I've done some testing up to now...I haven't scoured this to remove much of deprecated stuff, but at least it appears to be functioning fairly well.
class conversionCsharptopython:
classscope = False
classfuncscope = False
casescope = False
casevalues = []
casevar = ''
caseenditer = 0
caseiter = 0
classfuncscopeintervalleft = []
classfuncscopeintervalright = []
classname = ''
indentlevel = 0
classfuncnames = {}
classfuncnames_rev = {}
classvars = {}
classfuncvars = {}
classscopecounter = []
var = []
linescope = {}
writenextlineclosuref = False
classfuncwords = ['public','private']
keywords = ['Debug.Log','break', 'Console.Write','return','//',
'new','.ToArray()','DenseVector.OfArray(',
'DenseMatrix.CreateDiagonal(','.Length]',
'(int)','(double)', '(float)']
keywordinterpret = {'.ToArray()':'.tolist()', '.ToArray ()':'.tolist()',
'DenseVector.OfArray(':'numpy.matrix(',
'DenseMatrix.CreateDiagonal(':'numpy.matrix(',
'Console.Write':'print','Debug.Log':'print',
'//':'##', '(int)':'', '(double)':'', '(float)':'',
'.PI':'.pi','Math':'math','true':'True',
'false':'False', ';':'', 'Sin':'sin','Cos':'cos',
'Tan':'tan','AssetDatabase':'##AssetDatabase'}
instantiationkeywords = {'new Vector[':'Vector[','new findter(':'findter.findter(',
'new Boundaryedges(':'Boundaryedges.Boundaryedges(',
'new float[':'float[',
'new computetranslations(':'Computetranslations.computetranslations(',
'new computetranslationsgroup(':'Computetranslationsgroup.computetranslationsgroup(',
'new int[':'int[',
'new linearalgpckg.pointsrescale (':'linearalgpckg.pointrescale (',
'new AssemblyCSharp.computetranslations': 'Computetranslations.computetranslations',
'new Vector3 (':'mathutils.Vector([',
'new Vector3(':'mathutils.Vector([',
'new LoadHeightmap(':'LoadHeightmap.LoadHeightmap(',
'new double[':'double['
}
##these are defined types. This list likely expands.
defheaderwords = {'int':'single','float':'single','int[]':'list', 'int[ ]':'list',
'int[,]':'2dlists','int[':'sr','float[]':'list','float[,]':'2dlists',
'float [,]':'2dlists','int [,]':'2dlists',
'double [,]':'2dlists',
'float[,] ':'2dlists','Matrix':'matrix',
'Matrix[]':'list',
'Matrix[,]':'2dlist',
'float[][]':'2dlist','float[][,]':'3dlist',
'Vector':'matrix',
'Vector[]':'list','Vector[][]':'2dlist',
'double':'single',
'double[]':'list','double[][]':'2dlist',
'double[,]':'2dlists','bool':'single', 'Boundaryedges':'single', 'findter':'single',
'computetranslationsgroup':'single', 'computetranslations':'single', 'int[][]':'2dlist'}
falseequiv = ['(int)','(double)','(float)', 'checkpoints', 'point', 'checkpoint']
##arraylist = {'int[]':1, 'int[,]':2, '':}
def __doublelistinit(self, lefteqtokens, listlenstring):
returnstring += lefteqtokens
returnstring += '='
returnstring += 'Initialize.initalize.doublelist(listlenstring)'
return returnstring
def __intlistinit(self,lefteqtokens, listlenstring):
returnstring += lefteqtokens
returnstring += '='
returnstring += 'Initialize.initalize.intlist(listlenstring)'
return returnstring
def __matrixinit(self,lefteqtokens, matrixdatvarstring):
returnstring += lefteqtokens
returnstring += '='
returnstring += 'numpy.matrix('
returnstring += matrixdatvarstring
returnstring += ')'
def replacekeyword(self, stringline):
for word in self.keywordinterpret:
if word in stringline:
stringline = stringline.replace(word,self.keywordinterpret[word])
return stringline
def deftype(self, stringline):
if '[]' in stringline:
if '[][,]' in stringline:
return '3dlist'
elif '[][]' in stringline:
return '2dlist'
else:
return 'list'
elif '[,]' in stringline:
return '2dlist'
else:
return 'single'
def getsetclosure(self, sep, sepc, stringline):
sepcount = 0
sepccount = 0
line = 0
indexr = 0
for char in stringline:
if char == sep:
sepcount += 1
if char == sepc:
if sepcount == 0:
print('found')
indexr = line
break
else:
sepcount -= 1
line += 1
return stringline[0:indexr]
def getsetclosure2(self, sep, sepc, stringline):
# this assumes set closure is found at its first instance sep pairing which is included in the string search
sepcount = 0
sepccount = 0
line = 0
indexl = 0
indexr = 0
for char in stringline:
if char == sep:
if sepcount == 0:
indexl = line
sepcount += 1
else:
sepcount += 1
if char == sepc:
if sepcount == 1:
print('found')
indexr = line
break
else:
sepcount -= 1
line += 1
return stringline[indexl+1:indexr]
def writenextlineclosure(self, stringline):
self.writenextlineclosuref = False
return self.getsetclosure('[', ']', stringline) +')'
def instantiationcheck(self,stringline, itera):
#problems between c sharp and python, are that one would likely
#want class level object types instantiated at the outset in python
#whereas class object type variables maybe instantiated later
#. The solution is to initialize a variable with some arbitrary
# value that fits necessary operable conditions. Easy if we
# are working with non array types. More difficult otherwise.
# Can you think why? Obviously, array type objects may not
# be instanced with any defining array length, so we'd need to fish
# out this information in the body of the program. So we'll need
# to define special instancing rules and search algorithms to aid
# us.
instantstring = ''
iterm = -1
maxcount = 0
wordflag = False
for word in self.instantiationkeywords:
if word in stringline:
maxcount = 0
iterm = -1
count = 0
wordflag = True
for word2 in self.defheaderwords:
if word2 in stringline:
## print('stringline at word2 match:')
## print(word2)
## print(stringline)
check = False
for word3 in self.falseequiv:
if word3 in stringline:
if not stringline.find(word2)-1 == stringline.find(word3):
check = True
else:
check = False
break
else:
check = True
if check:
if len(word2) > maxcount:
maxcount = len(word2)
iterm = word2
iword = word
break
if not iterm == -1 and wordflag:
ocheck, varname, matchtype = self.checkreturnvar(stringline)
if '//' in stringline:
print('at // check:')
print(stringline)
print(varname)
if stringline.index('//') < stringline.index(varname):
instantstring += '##'
instantstring += self.getspacing2(itera)
print('variable name:')
print(varname)
instantstring += varname
instantstring += ' = '
## print(word2)
## print(iterm)
if self.defheaderwords[iterm] == 'list':
rightval = stringline.split(iword)[1]
print('rightval:')
print(rightval)
val = self.getsetclosure('[', ']', rightval)
## val = rightval.split(']')[0]
try: int(val); c = True
except: None; c = False
instantstring += 'Initialize.initalize.list('+val+')'
print('instantiation with new list: ')
print(instantstring)
self.writefileline (instantstring)
return True
elif self.defheaderwords[iterm] == '2dlist':
rightval = stringline.split(iword)[1]
val = self.getsetclosure('[', ']', rightval)
## val = rightval.split(']')[0]
instantstring += 'Initialize.initalize.2dlist('+val+')'
print('instantiation with new 2dlist: ')
print(instantstring)
self.writefileline (instantstring)
return True
elif self.defheaderwords[iterm] == '2dlists':
rightval = stringline.split(iword)[1]
## val = rightval.split(']')[0]
print(len(rightval.split(',')))
if ';' in rightval:
val1 = rightval.split(',')[0]
val2 = rightval.split(',')[1]
val2 = self.getsetclosure('[', ']', val2)
instantstring += 'Initialize.initalize.2dlists('+val1+','+val2+')'
print('instantiation with new 2dlist: ')
print(instantstring)
else:
print('************')
val1 = rightval.split(',')[0]
## val2 = val.split(',')[0]
instantstring += 'Initialize.initalize.2dlists('+val1+','
self.writenextlineclosuref = True
print('instantiation with new 2dlist: ')
print(instantstring)
self.writefileline (instantstring)
return True
elif self.defheaderwords[iterm] == '3dlist':
rightval = stringline.split(iword)[1]
val = self.getsetclosure('[', ']', rightval)
## val = rightval.split(']')[0]
try: int(val); c = True
except: None; c = False
instantstring += 'Initialize.initalize.list('+val+')'
print('instantiation with new word match 3dlist: ')
print(instantstring)
self.writefileline (instantstring)
return True
elif self.defheaderwords[iterm] == 'sr':
rightval = stringline.split('new ')[1]
if '{' in rightval:
rightval = rightval.split('{')[1]
val = rightval.split('}')[0]
instantstring += ' [' + val + ']'
print('instantiation with new special: ')
print(instantstring)
print(self.linescope[itera])
self.writefileline(instantstring)
else:
rightval = stringline.split(iword)[1]
print('rightval:')
print(rightval)
val = self.getsetclosure('[', ']', rightval)
## val = rightval.split(']')[0]
try: int(val); c = True
except: None; c = False
instantstring += 'Initialize.initalize.list('+val+')'
print('instantiation with new list: ')
print(instantstring)
self.writefileline(instantstring)
return True
else:
## no match defheader match but we have a instantiation of somesort
## so we replace some things on the line
newstring = ''
newstring += self.getspacing2(itera)
newstringadd = self.getStringnotabsspaces2(stringline)
newstringadd = newstringadd.replace(word,self.instantiationkeywords[word])
newstringadd = newstringadd + ' ##' +iterm
newstringadd = newstringadd.replace(iterm,'', 1)
newstringadd = self.replacekeyword(newstringadd)
newstring += self.getStringnotabsspaces2(newstringadd)
print('instantiation with new word match not list:')
print(newstring)
self.writefileline(newstring)
return True
elif iterm == -1 and wordflag:
newstring = ''
newstring += self.getspacing2(itera)
newstringadd = self.getStringnotabsspaces2(stringline)
newstringadd = newstringadd.replace(word,self.instantiationkeywords[word])
newstringadd = self.replacekeyword(newstringadd)
newstring += self.getStringnotabsspaces2(newstringadd)
print('instantiation with new no word match: ')
print(newstring)
self.writefileline(newstring)
return True
else:
return False
def instantiationWithoutNewCheck(self,stringline, itera):
maxcount = 0
iterm = -1
count = 0
wordflag = True
for word2 in self.defheaderwords:
if word2 in stringline:
check = False
for word3 in self.falseequiv:
if word3 in stringline:
if not stringline.find(word2)-1 == stringline.find(word3):
check = True
if word2 in word3:
check = False
break
else:
check = False
break
else:
check = True
if check:
if len(word2) > maxcount:
maxcount = len(word2)
iterm = word2
if not iterm == -1:
newstring = ''
newstring += self.getspacing2(itera)
newstringadd = self.getStringnotabsspaces2(stringline)
newstringadd = newstringadd.replace(iterm,'',1)
newstringadd = self.replacekeyword(newstringadd)
newstringadd = self.getStringnotabsspaces2(newstringadd)
newstring += newstringadd
print('instantiation without new: ')
print(newstring)
self.writefileline(newstring)
return True
else:
return False
def getStringnotabsspaces(self, stringline):
#use the second function of this type for now.
def findnonemptyr(stringset, itera):
returnit = 0
if stringset[itera] == '':
returnit = findnonemptyr(stringset, itera-1)
else:
return itera
return returnit
def findnonemptyrts(stringset, itera, map2):
returnit = 0
index1, index2 = map2[itera]
if stringset[index1][index2] == '':
returnit = findnonemptyrts(stringset, itera-1,map2)
else:
return itera
return returnit
def findnonemptylts(stringset, itera, map2):
returnit = 0
index1, index2 = map2[itera]
if stringset[index1][index2] == '':
returnit = findnonemptylts(stringset, itera+1,map2)
else:
return itera
return returnit
def map2dlist(listset):
count = 0
mapset = {}
setindex = 0
for listr in listset:
listindex = 0
for strin in listr:
mapset[count] = (setindex, listindex)
listindex += 1
count += 1
setindex += 1
return mapset
def getcopylist(stringset, itera, iterb, map2):
index1l, index2l = map2[itera]
index1r, index2r = map2[iterb]
allset = []
if not index1l == index1r:
print('stringset:')
print(stringset)
retset = [stringset[index1l][index2l:len(stringset[index1l])]]
print(retset)
if not index1l+1 == index1r:
retsetb = stringset[index1l+1:index1r]
retsetc = [stringset[index1r][0:index2r+1]]
allset = retset+retsetb+retsetc
else:
retsetb = [stringset[index1r][0:index2r+1]]
allset = retset+retsetb
else:
allset = stringset[index1l][index2l:index2r+1]
return allset
def buildnfrmsetl(stringset,itera, add):
namestring = ''
for i in range(0,itera+1):
## namestring += add + stringset[i]
if not i == 0:
namestring += add + stringset[i]
print(i)
print(stringset[i])
else:
namestring += stringset[i]
return namestring
def buildnfrmsetlr(stringset, adds, addt):
namestring = ''
## for i in range(itera,iterb+1):
## namestring += add + stringset[i]
count = 0
strngsetcount = 0
for set1 in stringset:
setcount = 0
print(set1)
for strin in set1:
if not count == 0:
if setcount == 0:
namestring += adds + strin
## print(i)
## print(stringset[i])
else:
namestring += addt + strin
else:
namestring += strin
count += 1
setcount += 1
strngsetcount += 1
return namestring
def findnonemptyl(stringset,itera):
returnit = 0
if stringset[itera] == '':
returnit = findnonemptyr(stringset, itera+1)
else:
return itera
return returnit
def buildnfrmsetr(stringset,itera, add):
namestring = ''
for i in range(itera,len(stringset)):
if not i == itera:
namestring += add + stringset[i]
else:
namestring += stringset[i]
return namestring
def getsplitsets(stringline):
splitsets = []
spaceset = stringline.split(' ')
count = 0
for word in spaceset:
tabset = word.split('\t')
splitsets.append(tabset)
count += 1
print(splitsets)
return splitsets
splitsets = getsplitsets(stringline)
map2 = map2dlist(splitsets)
iterb = findnonemptyrts(splitsets, len(map2)-1, map2)
itera = findnonemptylts(splitsets, 0, map2)
trunclist = getcopylist(splitsets, itera, iterb, map2)
return buildnfrmsetlr(trunclist, ' ', '\t')
def getStringnotabsspaces2(self, stringline):
def forward(stringline, itera):
retiter = 0
if stringline[itera] == ' ' or stringline[itera] == '\t':
retiter = forward(stringline, itera+1)
else:
if stringline[itera] == '':
retiter = forward(stringline,itera+1)
else:
return itera
return retiter
def rev(stringline, itera):
retiter = 0
if stringline[itera] == ' ' or stringline[itera] == '\t':
retiter = rev(stringline, itera-1)
else:
if stringline[itera] == '':
retiter = rev(stringline,itera-1)
else:
return itera
return retiter
iter1 = forward(stringline,0)
iter2 = rev(stringline, len(stringline)-1)
return stringline[iter1:iter2+1]
## spaceset = stringline.split(' ')
## print(spaceset)
## iterl = findnonemptyl(spaceset, 0)
## stringl = buildnfrmsetr(spaceset,iterl, ' ')
## spacesetr = stringl.split(' ')
## print(spacesetr)
## iterr = findnonemptyr(spacesetr, len(spacesetr)-1)
## print(iterr)
## stringr = buildnfrmsetl(spacesetr, iterr, ' ')
##
## tabset = stringr.split('\t')
## iterlt = findnonemptyl(tabset, 0)
## stringl = buildnfrmsetr(tabset,iterlt, '\t')
## tabsetr = stringl.split('\t')
## iterrt = findnonemptyr(tabsetr, len(tabsetr)-1)
## stringr = buildnfrmsetl(tabsetr, iterrt, '\t')
##
## spaceset = stringr.split(' ')
## print(spaceset)
## iterl = findnonemptyl(spaceset, 0)
## stringl = buildnfrmsetr(spaceset,iterl, ' ')
## spacesetr = stringl.split(' ')
## print(spacesetr)
## iterr = findnonemptyr(spacesetr, len(spacesetr)-1)
## print(iterr)
## stringr = buildnfrmsetl(spacesetr, iterr, ' ')
## return stringr
## def getStringnotabsspaces(self, stringline):
## def findnonemptyr(stringset, itera):
## returnit = 0
## if stringset[itera] == '':
## returnit = findnonemptyr(stringset, itera-1)
## else:
## return itera
## return itera
##
##
## def buildnfrmsetl(stringset,itera, add):
## namestring = ''
## for i in range(0,itera):
## namestring += add + stringset[i]
##
## return namestring
##
## def findnonemptyl(stringset,itera):
## returnit = 0
## if stringset[itera] == '':
## returnit = findnonemptyr(stringset, itera+1)
## else:
## return itera
## return itera
##
## def buildnfrmsetr(stringset,itera, add):
## namestring = ''
## for i in range(itera,len(stringset)):
## if not i == itera:
## namestring += add + stringset[i]
## else:
## namestring += stringset[i]
## return namestring
##
## spaceset = stringline.split(' ')
## iterl = findnonemptyl(spaceset, 0)
## stringl = buildnfrmsetr(spaceset,iterl, ' ')
## spacesetr = stringl.split(' ')
## iterr = findnonemptyr(spacesetr, len(spaceset)-1)
## stringr = buildnfrmsetl(spacesetr, iterr, ' ')
## tabset = stringr.split('\t')
## iterlt = findnonemptyl(tabset, 0)
## stringl = buildnfrmsetr(tabset,iterlt, '\t')
## tabsetr = stringl.split('\t')
## iterrt = findnonemptyr(tabsetr, len(tabset)-1)
## stringr = buildnfrmsetl(tabsetr, iterrt, '\t')
## return stringr
def adddefheaderword(self, word):
if word not in self.defheaderwords:
rettype = self.deftype(word)
self.defheaderwords[word] = rettype
print(word)
print(rettype)
def checksingleline(self, stringline):
if ';' in stringline:
return True
else:
return False
def strengthmatching(self, stringline, flg):
def getsubstringindex(word1, word2):
#word2 is a substring of word1 (that is smaller)
return word1.index(word2)
def checkindices(word1,word2,stringline,subind):
#word2 is checked as amatched substring of word1 (that is smaller)
ind1 = stringline.index(word1)
ind2 = stringline.index(word2)
if (ind2-ind1) == subind:
return True
else:
return False
flgset = [self.classfuncnames, self.classvars]
cwordlist = []
cword = 'abc'
for word in flgset[flg]:
if word in stringline:
check = True
strength = len(word)
for word2 in flgset[flg]:
if word2 in stringline:
if (len(word2) > strength) and (word in word2):
ind1 = getsubstringindex(word2, word)
if checkindices(word2,word,stringline,ind1):
check = False
break
if check:
stringline = stringline.replace(word,'self.'+word)
return stringline
def checkclassfuncscopelineexec(self, stringline, itera):
## cword = 'abc'
## for word in self.classfuncnames:
## if word in stringline:
## if not (word in cword) or not (cword in word):
## stringline = stringline.replace(word,'self.'+word)
## cword = word
## print(cword)
stringline = self.strengthmatching(stringline, 0)
self.checkclassvars(stringline, itera)
## self.checkclassfuncvars(stringline, itera)
## print('first self app:')
## print(stringline)
## cword = 'abc'
## for word in self.classvars:
## if word in stringline:
## if not ((word in cword) or (cword in word)):
## stringline = stringline.replace(word,'self.'+word)
## cword = word
## print(cword)
## print('after self app:')
## print(stringline)
stringline = self.strengthmatching(stringline, 1)
if not self.instantiationcheck(stringline, itera):
if not self.instantiationWithoutNewCheck(stringline, itera):
newstring = ''
newstring += self.getspacing2(itera)
newstring += self.getStringnotabsspaces2(stringline)
newstring = self.replacekeyword(newstring)
print('no instantiation: ')
print(newstring)
self.writefileline(newstring)
def checkreturnvar(self, stringline):
removelist = {'{':'', '}':''}
def removes(stringline):
if '{' in stringline:
stringline = stringline.replace('{','')
if '}' in stringline:
stringline = stringline.replace('}','')
elif '}' in stringline:
stringline = stringline.replace('}','')
return stringline
def getname (stringline, wordmatch):
if '=' in stringline:
print('indexing:')
print(stringline.index(wordmatch))
print(stringline.index('='))
print(wordmatch)
if stringline.index(wordmatch) > stringline.index('='):
varmatch = stringline.split('=')[0]
varmatch = self.getStringnotabsspaces2(varmatch)
return varmatch
else:
varmatch = stringline.split('=')[0]
varmatch = varmatch.split(wordmatch)[1]
varmatch = self.getStringnotabsspaces2(varmatch)
return varmatch
else:
return stringline.split(wordmatch)[1]
strength = 0
matchindex = 0
matchtype = ''
i = 0
found = False
var = ''
for word in self.defheaderwords:
if word in stringline:
if len(word)>strength:
strength = len(word)
matchindex = i
matchtype = word
var = getname(stringline, word)
var = removes(var)
## var = stringline.split(word)[0]
## var = self.getStringnotabsspaces2(var)
var = self.removespacefromstring(var)
found = True
i+=1
return (found, var, matchtype)
def checkclassfuncvars(self, classvarstring, itera):
#deprecated/bordering. Using alternate string
# parsing methods above.
def findnonemptyr(stringset, itera):
returnit = 0
if stringset[itera] == '':
returnit = findnonemptyr(stringset, itera-1)
else:
return itera
return returnit
def buildnfrmset(stringset,itera):
namestring = ''
for i in range(0,itera):
namestring += stringset[i]
return namestring
classlevelstring = ''
## print('linescope: ')
## print(self.linescope[itera])
if not itera in self.classfuncnames_rev:
## if self.linescope[itera] == 2 and self.classscope:
## writestring = classvarstring[0:len(classvarstring)]
## writestring = '##'+writestring
## print(writestring)
## self.writefileline (switchfirstline)
if not '=' in classvarstring:
if self.checksingleline(classvarstring):
v = classvarstring.split(';')[0]
v = self.getStringnotabsspaces2(v)
print('p check: ')
print(v)
print(len(v.split(' ')))
if len(v.split(' ')) > 1:
if not '()' in v.split(' ')[1]:
vs = v.split(' ')
##next line finds from the right hand side
## the next(first) non empty character set
vsriter = findnonemptyr(vs,len(vs)-1)
classvar = vs[vsriter]
classtypea = buildnfrmset(vs,
vsriter)
classtypeset = classtypea.split('\t')
classtype = buildnfrmset(classtypeset,len(classtypeset))
self.classvars[classvar] = classtype
self.adddefheaderword(classtype)
else:
if not '==' in classvarstring:
print('unidentified type hit: ')
eqleftvar = classvarstring.split('=')[0]
check, classvar, ctype = self.checkreturnvar(eqleftvar)
if check:
self.classvars[classvar] = ctype
## classlevelstring =
else:
classvarset = eqleftvar.split(' ')
## presuming non empty character set supplied
classvarnameiter = findnonemptyr(classvarset,
len(classvarset)-1)
classvarname = classvarset[classvarnameiter]
classtypea = buildnfrmset(classvarset,
classvarnameiter)
classtypeset = classtypea.split('\t')
classtype = buildnfrmset(classtypeset,len(classtypeset))
self.classvars[classvarname] = classtype
self.adddefheaderword(classtype)
return True
## else:
## return False
else:
return False
def checkclassvars(self, classvarstring, itera):
#deprecated/bordering. Using alternate string
# parsing methods above.
def findnonemptyr(stringset, itera):
returnit = 0
if stringset[itera] == '':
returnit = findnonemptyr(stringset, itera-1)
else:
return itera
return returnit
def buildnfrmset(stringset,itera):
namestring = ''
for i in range(0,itera):
namestring += stringset[i]
return namestring
classlevelstring = ''
## print('linescope: ')
## print(self.linescope[itera])
if not itera in self.classfuncnames_rev:
if self.linescope[itera] == 2 and self.classscope:
writestring = classvarstring[0:len(classvarstring)]
writestring = '##'+writestring
print(writestring)
## self.writefileline (switchfirstline)
if not '=' in classvarstring:
if self.checksingleline(classvarstring):
v = classvarstring.split(';')[0]
vs = v.split(' ')
##next line finds from the right hand side
## the next(first) non empty character set
vsriter = findnonemptyr(vs,len(vs)-1)
classvar = vs[vsriter]
classtypea = buildnfrmset(vs,
vsriter)
classtypeset = classtypea.split('\t')
classtype = buildnfrmset(classtypeset,len(classtypeset))
self.classvars[classvar] = classtype
self.adddefheaderword(classtype)
else:
if not '==' in classvarstring:
print('unidentified type hit: ')
eqleftvar = classvarstring.split('=')[0]
check, classvar, ctype = self.checkreturnvar(eqleftvar)
if check:
self.classvars[classvar] = ctype
## classlevelstring =
else:
classvarset = eqleftvar.split(' ')
## presuming non empty character set supplied
classvarnameiter = findnonemptyr(classvarset,
len(classvarset)-1)
classvarname = classvarset[classvarnameiter]
classtypea = buildnfrmset(classvarset,
classvarnameiter)
classtypeset = classtypea.split('\t')
classtype = buildnfrmset(classtypeset,len(classtypeset))
self.classvars[classvarname] = classtype
self.adddefheaderword(classtype)
return True
else:
return False
else:
return False
def removespacefromstringstart(self, stringline):
if stringline.startswith(' '):
rstring = stringline[0:len(stringline)]
rstring.replace(' ','',1)
return rstring
else:
return stringline
def removespacefromstring(self, stringline):
scount = stringline.rfind(' ')
return stringline.replace(' ','',scount)
def getspacing(self):
spacestring = ''
for i in range(0,self.indentlevel):
spacestring += '\t'
return spacestring
def getspacing2(self, lineint):
spacestring = ''
for i in range(0,self.linescope[lineint]):
spacestring += '\t'
return spacestring
def getclassfuncinputs(self, classstring):
funcvalinputnamesstring = '(self'
leftparsplit = classstring.split('(')
rightparstring = leftparsplit[1]
leftparstring = rightparstring.split(')')
funcinputvals = leftparstring[0].split(',')
i = 0
## funcvalinputnamesstring = ''
for funcinputval in funcinputvals:
if not i == len(funcinputvals) - 1:
funcvalinputnamesstring += ', '
funcinputvalsplit = funcinputval.split(' ')
funcvalinputnamesstring += self.findfirstnonnullfromlast(funcinputvalsplit)
else:
if len(funcinputvals) < 2:
funcinputvalsplit = funcinputval.split(' ')
if self.findfirstnonnullfromlast(funcinputvalsplit) == '':
funcvalinputnamesstring += self.findfirstnonnullfromlast(funcinputvalsplit)
funcvalinputnamesstring += '):'
else:
funcvalinputnamesstring += ', '
funcvalinputnamesstring += self.findfirstnonnullfromlast(funcinputvalsplit)
funcvalinputnamesstring += '):'
else:
funcvalinputnamesstring += ', '
funcinputvalsplit = funcinputval.split(' ')
funcvalinputnamesstring += self.findfirstnonnullfromlast(funcinputvalsplit)
funcvalinputnamesstring += '):'
i += 1
return funcvalinputnamesstring
def findsecondnonnull(self,splitlist):
firsthit = False
for item in splitlist:
if not item == '':
if not firsthit:
firsthit = True
else:
return item
return ''
def findfirstnonnullfromlast(self, splitlist):
c = splitlist[0:len(splitlist)]
c.reverse()
return self.findfirstnonnull(c)
def findfirstnonnull(self,splitlist):
for item in splitlist:
if not item == '':
return item
return ''
def checkusing(self, stringline):
if 'using' in stringline:
if stringline.index('using') == 0:
newstringline = "##" + stringline
print(newstringline)
self.writefileline (newstringline)
return True
else:
return False
return False
def checkleftbracenextline(self, stringline):
if '{' in stringline:
self.cmtleftbracenextline = False
else:
self.cmtleftbracenextline = True
def checknamespace(self, stringline):
if 'namespace' in stringline:
self.checkleftbracenextline(stringline)
newstringline = "##" + stringline
print(newstringline)
self.writefileline (newstringline)
return True
return False
def rebuildsplit(self, splitset):
line = ''
for stringpart in splitset:
line += stringpart
return line
def checkcmtleftbracenextline(self, stringline):
if self.cmtleftbracenextline:
if '{' in stringline:
## newstringline = stringline.split('{')[0] + stringline.split('{')[1]
##newstringline = "##" + stringline
newstringline = self.rebuildsplit(stringline.split('{'))
print(newstringline)
self.writefileline (newstringline)
self.cmtleftbracenextline = False
return True
else:
##expected good code writing no double left bracing on the same
## line
##self.cmtleftbracenextline = False
return False
else:
return False
def checkclass(self, stringline):
if 'class' in stringline:
classstring = ''
classstring += 'class '
classstringf = stringline.split('class')
classnamestringlist = classstringf[1].split(' ')
## ## assumed class name returned below is non null value good
## ## programming
classname = self.findfirstnonnull(classnamestringlist)
self.classname = classname.split('\n')[0]
## classstring += self.getclassfuncinputs(self, stringline)
self.checkleftbracenextline(stringline)
classstring += self.classname + ':'
print(classstring)
print(self.cmtleftbracenextline)
self.writefileline (classstring)
self.indentlevel += 1
self.classscope = True
return True
else:
return False
def checkiffuncandscope(self, filea,lineint):
## deprecated function using buildclassfunccompletion instead
markincheck = False
markin = 0
scopelevel = 0
markout = 0
for i in range(lineint, len(filea)):
if not markincheck and not ';' in filea[i]:
if '{' in filea[i]:
##if not markincheck:
markin = i
markincheck = True
self.classfuncscopeintervalleft.append(i)
if not '}' in filea[i]:
continue
elif not markincheck and ';' in filea[i]:
return False
if markincheck:
if '{' in filea[i]:
scopelevel += 1
self.classfuncscopeintervalleft.append(i)
if scopelevel == 0:
if '}' in filea[i]:
markout = i
classfuncscope = True
self.classfuncscopeintervalright.append(i)
##classfuncscopeinterval = [markin,markout]
return true
else:
if '}' in filea[i]:
scopelevel -= 1
self.classfuncscopeintervalright.append(i)
def buildclassfunccompletions(self, filea,lineint):
def findnonemptyr(stringset, itera):
returnit = 0
## print(stringset)
if stringset[itera] == ' ':
returnit = findnonemptyr(stringset, itera-1)
else:
return itera
return returnit
def findnonemptyl(stringset, itera):
returnit = 0
## print(stringset)
if stringset[itera] == ' ':
returnit = findnonemptyr(stringset, itera+1)
else:
return itera
return returnit
def buildnfrmset(stringset,itera):
namestring = ''
for i in range(0,itera+1):
namestring += stringset[i]
return namestring
def findname(filea, itera):
niter = 0
## print(filea[itera])
if not '(' in filea[itera]:
niter = findname(filea,itera-1)
else:
return itera
return niter
def nocommentcheck(filea,itera, name):
if '//' in filea[itera]:
if filea[itera].index('//') < filea[itera].index(name):
return True
else:
return False
else:
return False
## def parseclassfuncname(stringline):
## leftpar = stringline.split('(')[0]
namelist = ['namespace','class']
markincheck = False
markin = 0
scopelevel = 0
markout = 0
recordline = ''
namelistcounter = 0
for i in range(lineint, len(filea)):
for word in namelist:
if word in filea[i]:
namelistcounter += 1
count = 0
## print(namelistcounter)
for i in range(lineint, len(filea)):
self.linescope[i] = scopelevel
if scopelevel == namelistcounter:
## print(scopelevel)
if not markincheck and not ';' in filea[i]:
recordline = filea[i]
if '{' in filea[i]:
##if not markincheck:
markin = i
markincheck = True
fiter = findname(filea, i)
leftpar = filea[fiter].split('(')[0]
filea[fiter].split('(')[0][len(leftpar)-1] == ' '
## print(filea[fiter].split('(')[0][len(leftpar)-1])
funcnameiter = findnonemptyr(leftpar,
len(leftpar)-1)
funcnspace = buildnfrmset(leftpar,funcnameiter)
## funcnspace = leftpar[funcnameiter]
funcnspaceset = funcnspace.split(' ')
## print(funcnspaceset)
## funcspacei = findnonemptyr(funcnspaceset,
## len(funcnspaceset)-1)
if not nocommentcheck(filea,fiter, funcnspaceset[len(funcnspaceset)-1]):
self.classfuncnames[funcnspaceset[len(funcnspaceset)-1]] = fiter
self.classfuncnames_rev[fiter] = funcnspaceset[len(funcnspaceset)-1]
##self.classfuncscopeintervalleft.append(i)
## if not '}' in filea[i]:
## continue
## elif not markincheck and ';' in filea[i]:
## return False
elif scopelevel < namelistcounter:
if '{' in filea[i]:
csplit = len(filea[i].split('{'))-1
scopelevel += csplit
if '}' in filea[i]:
csplitl = len(filea[i].split('}'))-1
scopelevel -= csplitl
self.linescope[i] = scopelevel
elif '}' in filea[i]:
scopelevel -= 1
if '{' in filea[i]:
scopelevel += 1
else:
self.classfuncscopeintervalright.append(i)
if markincheck:
## if '{' in filea[i]:
## scopelevel += 1
##self.classfuncscopeintervalleft.append(i)
if scopelevel == namelistcounter+1:
if '}' in filea[i]:
markout = i
classfuncscope = True
markincheck = False
csplit = len(filea[i].split('}'))-1
scopelevel -= csplit
if '{' in filea[i]:
csplitl = len(filea[i].split('{'))-1
scopelevel += csplitl
if scopelevel > namelistcounter:
markincheck = True
else:
self.classscopecounter.append(i)
else:
self.classscopecounter.append(i)
self.classfuncscopeintervalright.append(i)
##classfuncscopeinterval = [markin,markout]
##return true
elif '{' in filea[i]:
scopelevel += 1
if '}' in filea[i]:
scopelevel -= 1
else:
if '}' in filea[i]:
csplit = len(filea[i].split('}'))-1
scopelevel -= csplit
if '{' in filea[i]:
csplitl = len(filea[i].split('{'))-1
scopelevel += csplitl
else:
self.classfuncscopeintervalright.append(i)
elif '{' in filea[i]:
scopelevel += 1
if '}' in filea[i]:
scopelevel -= 1
##self.classfuncscopeintervalright.append(i)
count += 1
def checkclassfuncname(self, stringline):
if self.classname in stringline:
return True
else:
return False
def checkleftbrace(self, filea, itera):
if itera in self.classfuncscopeintervalleft and '}' in filea[itera]:
##self.indentlevel -= 1
return filea[itera].split('{')[0]+filea[itera].split('{')[1]
def checkclassfuncscope(self, itera):
if itera in self.classscopecounter:
self.classfuncscope = False
def checkrightbrace(self, filea, itera):
if itera in self.classfuncscopeintervalright:
if itera == self.classfuncscopeintervalright[len(self.classfuncscopeintervalright)-1]:
## self.classfuncscope = False
self.indentlevel -= 1
elif self.casescope == True:
if itera == self.caseenditer:
self.casescope = False
self.indentlevel -= 1
else:
self.indentlevel -= 1
else:
self.indentlevel -= 1
print('right brace line: ')
print(filea[itera].split('}')[0]+ filea[itera].split('}')[1])
return True
else:
return False
def checkcontrolscopenonfor(self, filea,itera):
returncheck = False
markrightpar = False
for i in range(itera, len(filea)):
if ')' in filea[i]:
rightpar = filea[i].split(')')[1]
if not ';' in rightpar:
if '{' in filea[i] and i in self.classfuncscopeintervalleft:
return True
else:
markrightpar = True
else:
return False
else:
if ';' in filea[i]:
return False
else:
if markrightpar:
if '{' in filea[i] and i in self.classfuncscopeintervalleft:
return True
return returncheck
def findcasecompletion(self, filea,itera):
val = []
for i in range(itera, len(filea)):
if not '}' in filea[i]:
if 'case' in filea[i]:
casesplitright = filea[i].split('case')[1]
value = casesplitright.split(':')[0]
val.append(value)
else:
self.casevalues = val
self.caseenditer = i
break
def getfor(self, stringline, itera):
##retrieve brace information, presuming a (int i = 0; i<...;i++) example
##structure, my writing style, this is not generalized
returnstring = ''
if 'for (' in stringline:
leftpar = stringline.split('for (')[1]
elif 'for(' in stringline:
leftpar = stringline.split('for(')[1]
rightpar = leftpar.split('){')[0]
parsemicolonsplit = rightpar.split(';')
parsemicolonsplit[0] = parsemicolonsplit[0].replace('int ','')
rangemin = parsemicolonsplit[0].split('=')[1]
var = parsemicolonsplit[0].split('=')[0]
rangemax = parsemicolonsplit[1].split('<')[1]
print(rangemax)
rangemaxnew =''
if '.Length' in rangemax:
rangemaxnewl = rangemax.split('.Length')[0]
rangemaxnewr = rangemax.split('.Length')[1]
rangemaxnew = 'len(' + rangemaxnewl+')'+rangemaxnewr
else:
rangemaxnew = rangemax
## returnstring += self.getspacing()
returnstring += self.getspacing2(itera)
returnstring += 'for '
returnstring += var
returnstring += ' in range('
returnstring += rangemin
returnstring += ','
returnstring += rangemaxnew
returnstring += '):'
return returnstring
def getif(self, stringline, itera):
##retrieve brace information, presuming a (int i = 0; i<...;i++) example
##structure, my writing style, this is not generalized
returnstring = ''
## leftpar = stringline.split('(')[1]
## rightpar = leftpar.split(')')[0]
## returnstring += self.getspacing()
leftpar = stringline.split('if')[1]
rightpar = self.getsetclosure2('(', ')', leftpar)
returnstring += self.getspacing2(itera)
returnstring += 'if '
returnstring += rightpar
returnstring += ':'
return returnstring
def getelse(self, stringline, itera):
##retrieve brace information, presuming a (int i = 0; i<...;i++) example
##structure, my writing style, this is not generalized
returnstring = ''
## returnstring += self.getspacing()
returnstring += self.getspacing2(itera)
returnstring += 'else: '
return returnstring
def getelseif(self, stringline, itera):
##retrieve brace information, presuming a (int i = 0; i<...;i++) example
##structure, my writing style, this is not generalized
returnstring = ''
## leftpar = stringline.split('(')[1]
## rightpar = leftpar.split(')')[0]
leftpar = stringline.split('else if')[1]
rightpar = self.getsetclosure2('(', ')', leftpar)
## returnstring += self.getspacing()
returnstring += self.getspacing2(itera)
returnstring += 'elif '
returnstring += rightpar
returnstring += ':'
return returnstring
def getparinput(self, stringline):
parleft = stringline.split('(')[1]
parright = parleft.split
def getswitchvar(self, stringline):
if 'switch' in stringline:
varpar = stringline.split('(')[1]
var = stringline.split(')')[0]
self.casevar = var
def getswitchline(self, caseiter, itera):
if caseiter == 0:
switchline = ''
## switchline += self.getspacing()
switchline += self.getspacing2(itera)
switchline += 'if '
switchline += self.casevar
switchline += '=='
switchline += self.casevalues[0]
switchline += ':'
else:
switchline = ''
## switchline += self.getspacing()
switchline += self.getspacing2(itera)
switchline += 'elif '
switchline += self.casevar
switchline += '=='
switchline += self.casevalues[0]
switchline += ':'
return switchline
def checkcontrol(self, stringline, filea,itera):
charcheck = ['\t',' ']
atypes = ('for','if ','if(', 'switch', 'else', 'else if', 'while')
atypetrans = {'for':'for','switch':'switch','else':'else','else if':'else if','if ':'if', 'if(':'if'}
strength = 0
ratype = ''
for atype in atypes:
if atype in stringline:
if len(atype) > strength:
for char in charcheck:
if char == stringline[stringline.index(atype)-1]:
ratype = atype
## this suffers unfortunately from the possibility that a word
## is embedded in a variable name...although we eliminate
## with additional checking algorithms the possibility that
## a single line non control loop set of tokens are interpreted
## as a control structure by cross checking outside for paranthesis
## , braces, and semi colons. Semi colons outside of for loops
## at least in my programming writing style should suffice in most
## cases to be interpreted that a structure is not likely a control
## structure as opposed to a single line executable set of tokens
## control paranthesis are expected on a single line with control
## token. Thus I haven't taken into account the possibility
## of multi line control token statements.
check = False
if '//' in stringline:
if stringline.index('//') < stringline.index(ratype):
check = True
if not check:
if ratype == 'for':
print('for stringline:')
print(stringline)
rightpar = stringline.split(')')[1]
## if self.checkcontrolscopenonfor(filea,itera):
forstring = ''
forstring += self.getfor(stringline, itera)
self.indentlevel += 1
self.checkleftbracenextline(stringline)
forstring = self.replacekeyword(forstring)
print(forstring)
self.writefileline (forstring)
return True
## else:
## return False
elif ratype == 'if ':
if atypetrans[ratype] == 'if':
## if self.checkcontrolscopenonfor(filea,itera):
ifstring = ''
print('if stringline:')
print(stringline)
ifstring += self.getif(stringline, itera)
self.indentlevel += 1
self.checkleftbracenextline(stringline)
ifstring = self.replacekeyword(ifstring)
print(ifstring)
print(itera)
print(self.linescope[itera])
if '{' in stringline and ';' in stringline:
stringexec = stringline[stringline.index('{'):len(stringline)]
self.checkclassfuncscopelineexec(stringexec, itera+1)
self.writefileline (ifstring)
return True
## else:
## return False
elif ratype == 'if(':
if atypetrans[ratype] == 'if':
## if self.checkcontrolscopenonfor(filea,itera):
ifstring = ''
print('if stringline:')
print(stringline)
ifstring += self.getif(stringline, itera)
self.indentlevel += 1
self.checkleftbracenextline(stringline)
ifstring = self.replacekeyword(ifstring)
print(ifstring)
print(itera)
print(self.linescope[itera])
if '{' in stringline and ';' in stringline:
stringexec = stringline[stringline.index('{'):len(stringline)]
self.checkclassfuncscopelineexec(stringexec, itera+1)
self.writefileline (ifstring)
return True
## else:
## return False
elif ratype == 'switch':
## if self.checkcontrolscopenonfor(filea,itera):
self.findcasecompletion(filea,itera)
self.getswitchvar(stringline)
print('switch stringline:')
print(stringline)
switchfirstline = self.getswitchline(self.caseiter,
itera)
self.indentlevel += 1
self.caseiter += 1
self.checkleftbracenextline(stringline)
switchfirstline = self.replacekeyword(switchfirstline)
print(switchfirstline)
self.writefileline (switchfirstline)
self.casescope = True
return True
## else:
## return False
elif ratype == 'else if':
## if self.checkcontrolscopenonfor(filea,itera):
elifstring = ''
print('else if stringline:')
print(stringline)
elifstring += self.getelseif(stringline, itera)
self.indentlevel += 1
self.checkleftbracenextline(stringline)
elifstring = self.replacekeyword(elifstring)
print(elifstring)
self.writefileline (elifstring)
if '{' in stringline and ';' in stringline:
stringexec = stringline[stringline.index('{'):len(stringline)]
self.checkclassfuncscopelineexec(stringexec)
return True
## else:
## return False
elif ratype == 'else':
## if self.checkcontrolscopenonfor(filea,itera):
elsestring = ''
print('else stringline:')
print(stringline)
elsestring += self.getelse(stringline, itera)
self.indentlevel += 1
self.checkleftbracenextline(stringline)
elsestring = self.replacekeyword(elsestring)
print(elsestring)
print(self.linescope[itera])
self.writefileline (elsestring)
if '{' in stringline and ';' in stringline:
stringexec = stringline[stringline.index('{'):len(stringline)]
self.checkclassfuncscopelineexec(stringexec, itera+1)
return True
## else:
## return False
else:
return False
else:
return False
def checkcase(self, stringline):
if self.casescope:
if 'case' in stringline:
self.indentlevel -= 1
switchfirstline = self.getswitchline(self.caseiter)
self.indentlevel += 1
self.caseiter += 1
self.writefileline (switchfirstline)
return True
else:
return False
else:
return False
def checkfunc(self, stringline, filea, lineint):
## for word in self.classfuncwords:
## if word in stringline and not ';' in stringline:
if lineint in self.classfuncnames_rev:
## if '(' in stringline:
## if self.checkiffuncandscope(filea,lineint):
##if ')' in stringline:
funcstring = ''
## funcstring += self.getspacing()
funcstring += self.getspacing2(lineint)
funcstring += 'def '
if self.checkclassfuncname(stringline):
funcstring += '__init__'
else:
## classstring = stringline.split('class')
## classnamestringlist = classstring[1].split(' ')
## ## assumed class name returned below is non null value good
## ## programming
## funcstring += self.findfirstnonnull(classnamestringlist)
funcstring += self.classfuncnames_rev[lineint]
funcstring += self.getclassfuncinputs(stringline)
self.checkleftbracenextline(stringline)
print(funcstring)
self.writefileline (funcstring)
self.indentlevel += 1
self.classfuncscope = True
return True
## else:
## return False
## else:
## return False
else:
return False
## def checkvardefinition(self, linestring):
##simplest keyword token looks for '=' are there points
## of ambiguity on this?! Potentially I might want to confuse
## this with '=='. Definitions often omit this and may have
## a single line ';' character, but this is not necessary for
## program execution. So searching for '=' may aid us here.
## We can rest a little easier that any control loop
## using conditional logic '==' are previously scanned in our
## body parsing structure.
## This may not be very good in retrospect unless I eliminate
## other keywords on given line/multi line
def writefileline(self,stringdata):
stringdata = stringdata.replace('\n','')
stringdata += '\n'
self.writefile.write(stringdata)
def readwritefile(self):
filea = open(self.file, 'rU')
semicolondatasplit = []
lineint = -1
fileb = self.getfilelines(filea)
self.buildclassfunccompletions(fileb,lineint)
for line in fileb:
lineint += 1
self.checkclassfuncscope(lineint)
if self.checkusing(line):
continue
if self.checknamespace(line):
continue
if self.checkcmtleftbracenextline(line):
continue
if not self.classscope:
if self.checkclass(line):
continue
else:
if self.checkclassvars(line, lineint):
continue
## if self.checkclassvars(line):
## continue
if not self.classfuncscope:
print(lineint)
print(line)
if self.checkfunc(line, fileb, lineint):
continue
## if self.casescope:
## if self.checkcase(line):
## continue
if self.checkcontrol(line, fileb,lineint):
continue
if self.checkrightbrace(fileb, lineint):
continue
print(line)
if self.writenextlineclosuref:
line = self.writenextlineclosure(line)
self.checkclassfuncscopelineexec(line, lineint)
##
##
filea.close()
self.writefile.close()
def getfilelines(self, filea):
filed = []
for line in filea:
filed.append(line)
return filed
def startwritefile(self):
self.writefile = open(self.writefilenamepath +self.filename.replace('.cs','')+".py", "w")
def __init__(self, filenamepath=None, filename=None, writefilenamepath=None):
self.filenamepath = filenamepath
self.filename = filename
self.file = self.filenamepath+self.filename
self.writefilenamepath = writefilenamepath
self.cmtleftbracenextline = False
self.startwritefile()
path = 'C:\\Users\\StrangeCharmQuark\\Documents\\New Unity Project 4\\Assets\\'
filename = 'Boundaryedgesgroup.cs'
path2 = 'C:\\Users\\StrangeCharmQuark\\Documents\\'
a = conversionCsharptopython(path,filename, path2)
a.readwritefile()
filename2 = 'test.py'