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

Asked

Viewed 10,198 times

38

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

3 answers

27


The scope of a variable determines in which parts of the program this variable can be accessed. The simplest (and best known) example of the scope is the global scope and the 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 question arises: do the "inside" structures have access to the "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 rundown. In the above example, how baz defined x = 20 and then called bar, bar can access this x, and its value will be 20.

inserir a descrição da imagem aqui

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

Lexical scope

In lexical-scoped languages, what counts is the "grammatical" structure of the program, i.e., if in the source code one structure is nested in another, the inside can access variables in the outside. In the example, bar is nestled to foo, then she can access your variable x - even though foo has already returned and is no longer in the stack.

inserir a descrição da imagem aqui

The figure above is a simplification of Abstract Syntactic Tree (Abstract Syntax Tree - AST) of the example code. Note that - in a well-indented code - the level of each instruction in that tree matches its identation level in the source code. In the nested anonymous function the foo, the variable x corresponds to the "nearest" definition in the scope hierarchy (in green).

Anonymous function does not define variables, foo defines a x, and the top-level defines x, foo, bar and baz. Like the x of foo is "closer" than the x of top-level, he is the one who is accessible in the anonymous function. The x of baz nor is it considered - since it is not part of the lexical hierarchy - although whoever flame the anonymous function (saved in bar).

That is, it is possible to determine precisely which variables are accessible by simple source code reading, 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 (enclosure), and requires a "spaghetti pile" to be possible. Others, which do not allow nested functions (such as Java), still use lexical scope to determine which internal classes (Inner classes) have access to the fields of the external classes (in the second example of this response, the class Baz has access to the field x class Foo).

15

From the text of Wikipedia(Lexical Scope vs. Dynamic Scope):

What is?

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

Lexical Scope vs. Dynamic Scope

The scope lexicon(or static) was introduced by the language ALGOL 60. The scope is so named because it can be determined statically, ie before the 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 local (more or less) lexical 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 text part of the program, where the use of the identifier is a reference to that particular identifier statement.

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

The static scope 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 separately. Due to the understanding that the static scope makes programming more reliable, there is a tendency to reject the dynamic scope.

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

With dynamic scope, each identifier has a global bind stack. Introducing a local variable named x stack a binding on the global stack x (that may be empty), which will be popped when the control flow leaves the scope. Evaluate x in any context 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 delimiting is called dynamic scope.

Consider this example from 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.

inserir a descrição da imagem aqui

The variable I is visible at all points because it is never covered up by another variable of the same name. The char variable K is visible only in the main programme, because it is hidden by the variable K visible reality in the procedure B, C and D only.

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

In addition, the procedures C and D are only visible in procedures B, C and 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 programme, 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 the scope of variables.

10

What Means Scope of a Variable?

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 not declared on it.

The data type binding of a variable can be specified static (lexicon) or dynamics.

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 link will be used. 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 until the further. If all the surrounding blocks have been verified and the declaration not found,
  3. If the name is in the global environment, that link will be used, otherwise there is no link to that name in the environment.

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

Dynamic scope

In dynamically scoped programming languages, the scope is determined through the execution line of the program, and is therefore dependent on the execution order of the routines. Using dynamic scope, the valid binding for a name is the one created most recently during program execution, based on unit call sequences of programs, not on 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

  • 1

    For me it was the answer that defined more clearly and objectively what each one is and the difference. + 1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.