Indentation and grouping proposal
Otto Smith
otto at olympus.net
Tue Jun 8 23:11:33 EDT 1999
# Re: Indentation and grouping proposal
# You don't need to change python to get
# the functionality you request..
# nips.py
# Non Intuitive Parsing System...
'''
Here are some routines that allow you to
write in a style similar to that proposed
in the: "Indentation and grouping proposal".
The routines will take ugly unreadable code
and translate it to simple, neatly indented
python code. The constants below set the
block grouping symbols to '_{' and '}_'
and the statement separator to ';', but you
are welcome to change these to anything
you want.
Usage is simple:
parsenips() takes block delimited code
and converts it into a list of lists format.
makeright() takes the output of parsnips
and makes it into python indented code.
Example:
#####
import from nips import makeright, parsenips
ugly = """ if 1<2: _{ print 'Ho ho'; print '1 < 2' }_
else: _{ print "surprise";
print '2 < 1!!!' }_
"""
print makeright(parsenips( ugly ))
#####
Which produces:
if 1<2:
print 'Ho ho'
print '1 < 2'
else:
print 'surprise'
print '2 < 1!!!'
'''
import string
SPARSEX = "String parse exception"
MYSTART = '_{'
MYEND = '}_'
MYLINE = ';'
BADQUOTES = "'"+'"'
len_mystart = len(MYSTART)
len_myline = len(MYLINE)
def match(beg, end, str):
lbeg = len(beg)
lend = len(end)
dex = lbeg
count = 1
while dex < len(str):
if str[dex:dex+lend] == end:
count = count-1
if count == 0:
return (str[lbeg:dex],str[dex+lbeg:])
dex = dex+lend
elif str[dex:dex+lbeg] == beg:
count = count+1
dex = dex+lbeg
else:
dex = dex + 1
continue
if count < 0:
raise SPARSEX, 'badly matched quote brackets'
raise SPARSEX, 'badly matched quote brackets'
def parsenips( str ):
str = string.strip(str)
curinst = ''
statementlist = []
dex = 0
while str:
if str[dex] in BADQUOTES:
quote = str[dex]
val, str = match( quote, quote, str[dex:] )
curinst = curinst+quote+val+quote
dex = 0
elif str[dex:dex+len_mystart] == MYSTART:
if curinst:
statementlist.append( string.strip(curinst) )
val, str = match( MYSTART, MYEND, str[dex:] )
statementlist.append( parsenips(val))
curinst = ''
dex = 0
elif str[dex:dex+len_myline] == MYLINE:
statementlist.append( string.strip(curinst) )
str = string.strip(str[dex+len_myline:])
curinst = ''
dex = 0
else:
curinst = curinst + str[dex]
dex = dex+1
if string.strip(curinst):
statementlist.append( string.strip(curinst))
return filter(None, statementlist)
SPACER = ' '
def makeright( list, level=0 ):
pystrings = []
for val in list:
if type(val) == type(""):
pystrings.append( (SPACER*level)+val )
else: ## Assert type(val) == ListType
pystrings.append( makeright(val,level+1) )
return string.join( pystrings, '\n')
#Otto
#otto at olympus.net
More information about the Python-list
mailing list