Boost Spirit and Forward Statements

Can someone please give me some tips / ideas on how to deal with situations where you need to look at further announcements in order to be able to do the right semantic actions at the moment? For example, this is a well-known phenomenon when someone writes an interpreter / compiler of some programming language that does not support “advanced declarations”. Take an example:

foo(123);//<-- our parser targets here. we estimate we have a function 
         //    invocation, but we have no idea about foo declaration/prototype,
         //     so we can't be sure that "foo" takes one integer argument.   


void foo(int i){
//...
}

It is quite clear that we must have at least two passes. First, we analyze all the declarations of functions and get all the necessary information, such as: the quantity arguments that the function takes, their types, and then we deal with function calls and eliminating difficulties, as indicated above. If we go this way, we will have to make all these passes using some AST mechanisms / visitors. In this case, we must deal with the AST passing / using visitors, and we must say "goodbye" to all the beauty of the phoenix constructions embedded directly in our parsers.

How would you handle this?

+3
source share
3 answers

[2- , ] . , , - , , . , , , () . , , . , , .

, . - , ++ - - . , . AST , .

+3

, , te, , , . ,

[functionCall(name, args)]
[functionDef(name, args, body)]

- ( , )

functionCall(string name, vector<string> args)
{
  if (!first_pass) {
    // check args for validity
    // whatever else you need to do
  }
} 

functionDef(string name, vector<string> args, ... body)
{
  if (first_pass)
    // Add function decleration to symbol table
  else
    // define function
}
+2

I think you are making unsubstantiated assumptions. For example, "it’s pretty clear that we must have at least two passes." No, it is not. If the syntax is such that it foo(123)can only be analyzed as it is function-name "(" expression ")", then one pass is enough.

Therefore, I would advise developing your syntax for unambiguous parsing. Avoid constructs that cannot be analyzed in isolation, for example. Avoid dependencies on ads elsewhere.

+1
source

Source: https://habr.com/ru/post/1721953/


All Articles