Part 4: Implementation of if
Preface
I have done a programming language: mylang
Start
Upload code
def split_subBlocks(block):
subBlocks = []
cnt = 0
buf = ''
flag = False
for i in block:
if(i == '{'):
cnt += 1
flag = True
elif(i == '}'):
cnt -= 1
flag = True
if(cnt == 0 and flag):
subBlocks.append(buf)
buf = ''
flag = False
else:
buf += i
subBlocks[-1] += '}'
return subBlocks
# ......N行之后......
def parse_if(block):
subBlocks = split_subBlocks(block)
if(subBlocks[0] == 'error'):
return subBlocks
for i in subBlocks:
if(i.startswith('if')):
foo = i.split('\n')[0][3:-2]
elif(i.startswith('elsif')):
foo = i.split('\n')[0][6:-2]
elif(i.startswith('else')):
foo = 'true'
else:
return ['error','IfSentenceError:find undefined branch head']
code = [j.strip() for j in i.split('\n')[1:-1]]
F = comp(foo)
if(F[0] == 'error'):
return F
if(F[0]):
for i in code:
val = comp(i)
if(val[0] == 'error'):
return val
return ['']
return ['']
Parameters
block
: code
At the beginning
subBlocks = split_subBlocks(block)
if(subBlocks[0] == 'error'):
return subBlocks
Here separate each block of if, elsif and else, see the code of split_subBlocks:
def split_subBlocks(block): subBlocks = [] cnt = 0 buf = '' flag = False for i in block: if(i == '{'): cnt += 1 flag = True elif(i == '}'): cnt -= 1 flag = True if(cnt == 0 and flag): subBlocks.append(buf) buf = '' flag = False else: buf += i subBlocks[-1] += '}' return subBlocks
first part
def split_subBlocks(block): subBlocks = [] cnt = 0 buf = ''
Here define variables subBlocks (blocks), cnt (number of brackets to be paired), buf (sentences that have not yet been segmented)
the second part
for i in block: if(i == '{'): cnt += 1 flag = True elif(i == '}'): cnt -= 1 flag = True if(cnt == 0 and flag): subBlocks.append(buf) buf = '' flag = False else: buf += i
Part II-1
if(i == '{'): cnt += 1 flag = True elif(i == '}'): cnt -= 1 flag = True
Count the number of braces
Part 2-2
if(cnt == 0 and flag): subBlocks.append(buf) buf = '' flag = False
If it can be segmented, segment
Part II-3
else: buf += i
If it cannot be segmented, record it as an unsegmented sentence
Behind
for i in subBlocks:
if(i.startswith('if')):
foo = i.split('\n')[0][3:-2]
elif(i.startswith('elsif')):
foo = i.split('\n')[0][6:-2]
elif(i.startswith('else')):
foo = 'true'
else:
return ['error','IfSentenceError:find undefined branch head']
Analyze the head of this paragraph
carry on
code = [j.strip() for j in i.split('\n')[1:-1]]
F = comp(foo)
if(F[0] == 'error'):
return F
if(F[0]):
for i in code:
val = comp(i)
if(val[0] == 'error'):
return val
return ['']
return ['']
The execution procedure
here is based on the previous, it should not be difficult to understand
in conclusion
in conclusion:
###### Author hit-road
Bye, get out of class is over!
Hit-road will be updated from time to time, see or leave!