Part 3: Implementation of the while loop
Preface
I have done a programming language: mylang
Start
In fact, the if should be first, but in order to maintain the concept of "explain the single-branch structure first, then the multi-branch structure", the if is passed
Source code
def parse_while(block):
global status
try:
foo = block.split('\n')[0][6:-2]
except:
return ['error','WhileSentenceError:wrong initial']
while(1):
F = comp(foo)
if(F[0] == 'error'):
return F
if(not F[0]):
break
for i in block.split('\n')[1:-1]:
i = i.strip()
val = comp(i)
if(val[0] == 'error'):
return val
if(status == MYL_BREAK_STATUS):
status = MYL_NONE_STATUS
return ['']
return ['']
For status global variables, see
Chapter 2 of [Use python self-made programming language]
Parameters
block
: code
At the beginning
try:
foo = block.split('\n')[0][6:-2]
except:
return ['error','WhileSentenceError:wrong initial']
To understand this, look at the syntax of for:
while(<foo>){
<code>
}
Here block.split('\n')[0]
is while(<foo>){
the line, 6: -2 is <foo>
therefore to beg <foo>
used
later
while(1):
F = comp(foo)
if(F[0] == 'error'):
return F
if(not F[0]):
break
for i in block.split('\n')[1:-1]:
i = i.strip()
val = comp(i)
if(val[0] == 'error'):
return val
if(status == MYL_BREAK_STATUS):
status = MYL_NONE_STATUS
return ['']
Look separately
At the beginning
F = comp(foo)
if(F[0] == 'error'):
return F
if(not F[0]):
break
Check expression<foo>
later
for i in block.split('\n')[1:-1]:
i = i.strip()
val = comp(i)
if(val[0] == 'error'):
return val
if(status == MYL_BREAK_STATUS):
status = MYL_NONE_STATUS
return ['']
Execute the code and judgebreak
At last
return ['']
End
in conclusion
Author
hit-road
Bye, get out of class is over!
Hit-road will be updated from time to time, see or leave!