What are lexical scope and dynamic scope and what are their main differences?

What are lexical scope and dynamic scope and what are their main differences?

Author: Carlos Cinelli, 2014-04-15

3 answers

The scope of a variable determines in which parts of the program that variable can be accessed. The simplest (and best known) example of scope is global scope and local scope :

var x = 10;       // Escopo global - pode ser acessada em qualquer lugar, inclusive em f
function f() {
    var y = 20;   // Escopo local - pode ser acessada somente dentro de f
}

Modern programming languages support the concept of nested structures. That is, a code structure contained in another code structure (instead of being in the top-level):

class Foo {
    int x;
    void bar() { 
        int y;
    }

    class Baz { ... }
}

It is at this moment that a doubt: do "inside" structures have access to "outside" structures or not? Each language implements this in a way.

var x = 0;

function foo() {
    var x = 10;
    return function() {
        return x;
    }
}
var bar = foo();

function baz() {
    var x = 20;
    bar();
}
baz(); // O que é retornado?

Dynamic scope

In dynamically scoped languages, functions can access any variable present in the execution stack. In the example above, how baz defined x = 20 and then called bar, bar you can access this x, and its value will be 20.

insert the description of the image here

This type of scope is deprecated, since it is difficult to keep track of which variables are visible at any given time, besides damaging the encapsulation (i.e. any function call could at first modify any local variable of the calling function). The vast majority of modern languages do not use this type of scope.

Lexical scope

In languages with lexical scope, what counts is the "grammatical" structure of the program, that is, if in the source code one structure is nested in another, that of inside can access variables on the outside. In the example, bar is nested to foo, so it can access its variable x - even if foo has already returned and is no longer in the stack.

insert the description of the image here

The figure above is a simplification of abstract syntactic tree (Abstract Syntax Tree - AST) of the sample code. Note that-in a well-identified code-the level of each statement in that tree corresponds to its level of identification in the source code. In the anonymous function nested to foo, the variable x matches the "closest" definition in the scope hierarchy (in green).

The anonymous function does not define variables, foo defines a x, and the top-level defines x, foo, bar and baz. Since the x of the foo is "closer" than the x of the top-level, it is the one who is accessible in the anonymous function. The x of the baz is not even considered - since it is not part of the lexical hierarchy - even though is the one who calls the anonymous function (saved in bar).

That is, it is possible to accurately determine which variables are accessible by simple reading the source code, without having to mentally visualize who calls what and in what order.

This type of scope is the most commonly used in modern languages. In those that allow nested functions (as in the example above, in JavaScript), the access of an internal function to the local variables of the external function is called closure (closure) , and requires a "spaghetti stack" to be possible. Others, which do not allow nested functions (such as Java), still use lexical scope to determine that the inner classes (inner classes) have access to the fields of the outer classes (in the second example of this answer, the class Baz has access to the field x of the class Foo).

 27
Author: mgibsonbr, 2017-04-13 12:59:39

From the text of Wikipedia(Lexical scope vs. dynamic scope):

What is it?

In Computer Science scope is a delimiting context to which values and expressions are associated. Programming languages have several types of scopes. The scope type will determine what types of entities it can contain and how they are affected, in other words, their semantics. Typically, the scope is used to define the degree of concealment visibility and accessibility to variables in different parts of the program.

Lexical scope vs. dynamic scope

The scope lexical (or static) was introduced by the ALGOL 60 language. The scope is so named, because it can be determined statically, that is, before execution.

The lexical scope defines the scope in terms of the lexical structure of the program. With lexical scope, a name always refers to its lexical (more or less) local environment. This is a property of the program text and is made independent of the call stack at runtime by the language implementation. That is, the lexical scope of a statement is the part of the program text where the use of the identifier is a reference to that particular statement of the identifier.

Because this match only requires parsing the static program text, this type of scope delimitation is also called static scope.

Static scoping is standard in all ALGOL-based languages, such as Pascal, ADA, and C, as it allows the programmer to elaborate reasoning about values, parameters, and references to objects (i.e. variables, constants, functions, etc.), as simple name substitutions. This makes it much easier to make the code modular and reason about it, since the local naming structure can be understood in isolation. Due to understanding that the static scope makes programming more reliable, there is a tendency to reject the dynamic scope.

In contrast, dynamic scoping forces the programmer to anticipate all possible dynamic contexts in which module code can be invoked.

With dynamic scope, each identifier has a global stack of bindings. Entering a local variable with the name of x stack a link on the global stack x (which may be empty ), which will be empty when the control flow leaves scope. Evaluate x in any context it always produces the most binding to the top.

In other words, a global identifier refers to the identifier associated with the most recent environment. Note that this cannot be done at compile time, because the binding stack only exists at runtime, which is why this type of delimitation is called dynamic scope.

Consider this example done in Pascal:

program A;

var I:integer; // Variável global
    K:char; --------------------------
                                      |  
    procedure B;                      |  
    var K:real; -----------------------
        L:integer;                    |
                                      | 
        procedure C;                  |
        var M:real;                   | 
        begin                         |
         (*escopo A+B+C*)             |
        end;                          |
                                      |
        procedure D;                  |
        var K:integer; ----------------
        begin
         (*escopo A+B+D*)
        end;

    begin
     (*escopo A+B*)
    end;
begin
 (*escopo A*)
end.

insert the description of the image here

The variable I it is visible at all points, because it is never covered by another variable of the same name. The char variableK it is visible only in the main program , because it is covered by the variable K real visible in procedure B, C e D only.

The variable L it is also visible only in B procedures, C and D, but does not hide any other variables. The variable M it is visible only in process C and therefore is not accessible either from procedure B, procedure D, or from the main program.

In addition, procedures C and D are only visible in procedures B, C e D (C and D are procedures with the same static parent and therefore see each other), and therefore cannot be called from the main program.

In addition, there could be yet another procedure C declared in the program, outside the process B. The exact place in the program where C is called then determines which procedure C is called, and this is precisely analogous to scope of variables.

 15
Author: stderr, 2014-04-15 17:01:10

What does the scope of a variable mean?

The scope of a variable represents the area of the program where it is visible.

  • a variable is visible in a command if it can be referenced in that command.
  • a variable is local to a program unit if it is declared in it.
  • a variable is non-local to a program unit if it is visible but has not been declared in it.

The Binding of the data type of a variable can be specified in a static way (lexical ) or dynamic.

Static scope (lexicon)

In programming languages with static (or lexical) scope, the scope is determined through the textual structure of the program. Using static scope( lexicon), The Binding of a name in the environment is determined by the following algorithm:

  1. if the name was declared in the execution block, that binding will be used. Case otherwise,
  2. if the name has not been declared in the running block, it must be sought in the blocks that surround it, from the immediately surrounding to the farther away. If all the surrounding blocks have been verified and the statement not found,
  3. if the name is in the global environment, that binding will be used, otherwise there is no binding to that name in the environment.

One can informally say that the snippet of code where a name is visible is the block where it has been declared and all blocks nested within it, and for this reason it is often used "lexical scope" as a synonym for "static scope".

Dynamic scope

In programming languages with dynamic scope, the scope is determined through the execution line of the program, and is therefore dependent on the order of execution of the routines. Using dynamic scope, the valid binding to a name is the one created most recently during execution of the program, based on sequences of calls of program units, not on the textual layout.

Example

x: integer
procedure print_x()
begin
    print(x);
end
procedure p2
x: integer;
begin
    x= 4;
    print_x();
end
begin
    x = 3;
    p2();
end

If the scope is dynamic the program prints 4. If the scope is static, the program prints 3.

Source: http://www.inf.puc-rio.br / ~ inf1621 / scope. pdf

 10
Author: Lucas Henrique, 2014-04-19 04:23:31