Varible Shadowing

According to the project specification, subsection 4.2 Scope:

Function definitions open a new local scope. The function’s parameters belong to this local scope. Blocks additionally open new local scopes.

As a result, it might be possible that a fuction parameter is shadowed by a local variable in the body of this function.

Coming to code generation for a function definition based on the rule in the script Subsection 9.3.3: The Function Prologue and Epilogue, which states that

The code c of the body s of a function f with parameters k1 x1; …; km xm; can be generated by considering the function’s body wrapped in a block where parameters are declared as local variables.

Therefore, if a function f has a block as its body, then for code generation it’s cosidered as a block which contains its body (a nested block). However, the pro- and epilogue machine code in the same subsection seems to state that the parameters are prepended to the body as local variable declarations. In other words, function parameters and local variables in its body share the same scope (of code generation) since they share the same offset function, which seems not logical as shadowing a parameter by a local variable (directly contained by the function’s body) is no longer possible.

The questions are:

  • Do the function parameters and the local variables defined in its body share the same offset function (i.e. the same scope of code generation)?
  • If yes, how does it work in the case that a parameter is shadowed by a local variable?

From the project description page 7:

int foo ( int x , int y ) { // 2 nd declaration of x , hides global variable
  // int y ; Error : y is already declared in this scope ( as parameter )
  {
    int x = 1; // 3 rd declaration of x
    x = x + 1;  // x references the 3 rd declaration
  }
  return x ;  // x references the 2 nd declaration
}
1 Like

Depends on what you consider a scope. If you simply allocate space for all local variables. if not, then not. Implement it in such a way that it works, you are free to change the details!

Tha really should not matter for code generation. The generated code should be exactly as if all variables were named apart. Since you resolve shadowing in the semantic analysis (hopefully), you should not even be looking at the names here, so shadowing is not an issue. If it is, you may be doing something wrong.

1 Like