Jojo Jonas
Jojo Jonas

Reputation: 223

Python parsing input as an interpreter

So, I'm designing an interpreter a language as a project. Accepted programs can consist of zero or more declarations, followed by zero or more statements. I call a different (recursive) procedure to handle both of these possibilities, each of which returns either True upon completion or False upon error.

Declarations can be distinguished from statements in that declarations always begin with a non-terminal "type" (which itself is another procedure that returns True of False).

So my question is as follows. I need to check for both errors and when the declarations at the beginning of the input file are finished. The following is a snippet from the top layer that will check for declarations and statements:

while self.declaration():
    #Do stuff
while self.statement():
    #Do stuff

So as you recursively travel down these function calls, you will eventually be returned True or False based on whether or not your code has any errors. But at the same time, I need to be able to check when there are no more declarations, which would move from the declaration() loop to the statement() loop.

In other words, in the first loop, the code is going to return False both when it encounters an error and when declarations are finished. How do I fix this?

NOTE: Both functions move the index (that extracts the individual keywords from the code) forward in the program, meaning I cannot call extra checks to determine if a "type" is next.

Maybe I could read ahead (using that index) before the parser starts and count the number of declarations in the code, then call declaration() for the number of the declarations I've detected. Can anyone think of a better solution? Thanks for your help.

Here's a sample of legal code (disregard whether or not the variables would contain anything useful):

int c ?                 #Declaration
if ( foo < 3 ) {
    a is 7 ?
}

Here's a sample of illegal code:

if ( foo < 3 ) {
    array int [ 3 ] a ? #Declaration
}
int c ?                 #Declaration

The point being, any declarations that are made in the accepted program should precede all other statements.

Upvotes: 0

Views: 284

Answers (2)

Jojo Jonas
Jojo Jonas

Reputation: 223

What I ended up doing was exiting on error, and counting False as incorrect path taken down the recursion tree. It was fairly easy and surprisingly accurate.

Upvotes: 0

Odomontois
Odomontois

Reputation: 16328

Take a look at special language parsing tools for python.

Upvotes: 3

Related Questions