Talk:Scope (programming)

From Wikipedia, the free encyclopedia

Contents

[edit] Brighterorange's fixes

I rewrote the part on static scoping. It contained many factual errors.

Functions deeper in the call stack have no way of getting to it.
  • Not true; in many statically-scoped languages functions can be nested, and the nested functions can refer to variables in the outer scope. These functions can of course be "deeper in the call stack".
The binding and associated object are destroyed when the control flow leaves the scope.
  • Definitely not: although there are languages that destroy local objects when exiting the block (ie, C, C++), in many other languages this is not the case (Java, ML). For instance, in ML:
fun f() =
  let val x = (1, 2)
  in
     x
  end
... the pair (1,2) is returned from the function, certainly not destroyed, despite x having static scope.

I believe I am an expert in this issue, since I am studying for my PhD in programming languages. However, I am willing to explain further if you guys disagree. Brighterorange 17:31, 2 Jun 2005 (UTC)

In that example the binding for x is destroyed even though its value is not. An even more compelling example is:

fun g () =
  let val y = (3,4)
      fun h(z) = z + (#1 y)
  in 
     h
  end

because the both the pair (3,4) and the binding of y outlive the let. Cjoev 14:54, 3 Jun 2005 (UTC)

[edit] Eelis' partial rewrite plans

Ok, this is my first attempt at a rewrite. I've also merged static and dynamic scoping into this article (I've reused some paragraphs, but have rewritten others). I've also used significantly simpler source code examples. I hope you agree that this is a major improvement.

-- Eelis 14:03, 2005 May 23 (UTC)

Call it sour grapes, but I don't like this at all. I disagree with the implication that "a scope" is the same thing as "a block". I rather think the word "scope" is used primarily in phrases like "the scope of x" or "x has global scope", where x is an identifier or the thing bound to an identifier.
A definition of a term should attempt to capture the essence of that term. Listing a few examples of common phrases is useful, but is not much of a primary definition. "Enclosing context" was my best attempt, if you can do better then please do. -- Eelis 19:27, 2005 Jun 3 (UTC)
A definition of a term should make its meaning clear, precise and unambiguous. A good definition, especially of a technical term, should give the reader everything he or she needs in order to decide whether the word is the right one for a particular use and everything he or she needs in order to interpret (if not understand) uses of the word he or she encounters. I would rather have precise definitions for phrases in which a word is used than a vague definition for the word itself. -- Cjoev 16:06, 4 Jun 2005 (UTC)
The fact that most of the article is about static versus dynamic scoping (of names) seems to contradict your claim on this page that scope is a much broader concept. Prove me wrong.
I do not claim that the article is complete. I do claim that static and dynamic scoping use "scoping" in a very narrow sense. Static and dynamic scoping affect the semantics of introducing a local variable with a certain name, but say nothing about class or namespace scopes. -- Eelis 19:27, 2005 Jun 3 (UTC)
Here is my understanding of class scope (as it works in my mental default OO language, which is Java): When the name of a field or method of a class appears inside the class (i.e., inside the body of a method of the class), the name is understood to refer to that field or method in the object on whose behalf the method is being executed ("this"), unless a method parameter or local variable binding of the same name obscures it. This is consistent with the spirit of static scoping, since occurrences of such a name outside the class never have that meaning. Outside the class you have to use the dot notation to refer to the class's members. (I suppose "class scope" could also be interpreted to mean something to do with the public/private/protected distinction, which I am prepared to admit is a different animal.) One could also imagine a "dynamic" version of class scoping, in which the dynamic scoping's characteristic notion that "names that have a certain meaning in a certain context have the same meaning in functions called from that context, unless they are shadowed by some binding in between" covers fields and methods as well as whatever else (that is not a precise statement, I realize), although I personally am not familiar with any languages that work this way. In other words, classes are just another construct that introduces bindings for names, and as such can be fit into a static or dynamic scoping framework. I agree, though, that simply saying a language has static scoping or has dynamic scoping falls well short of describing its name resolution rules completely. Any particular scoping rules, disciplines, or whatever that we can describe in this article are at best patterns and fragments that any particular language may piece together in its own way. -- Cjoev 16:06, 4 Jun 2005 (UTC)
Also, I think this article benefits way too much from the vagueness of the statement "A scope is an enclosing context." What is a "context"? In a language with static scoping, "context" can meaningfully be understood as a static entity, i.e. a part of the program text such as a function or class. For every variable, there is such a region outside of which that variable does not make sense.
"Benefits way too much" ? Benefits are good, right? And yes, "context" is vague, but I think it does capture the essence of "scope". Still, please improve if possible. I do think the "for every variable.." definition is far too limited, because all identifiers (including those of classes, namespaces, and functions) are bound to scopes, not just variables. And in my opinion the "make sense" part is at least as vague as "context". What does it mean for an identifier to "make sense"? -- Eelis 19:27, 2005 Jun 3 (UTC)
"Benefits too much from" was a nice way of saying "cheats by exploiting". (Exploiting vagueness is bad, because vagueness itself is bad and we shouldn't construct the article in such a way that vagueness is crucial to it.) To rephrase, I think that if we want to discuss static versus dynamic scoping within a single article (which of course we must) then we need to make sure that the basic terms we use in the discussion can have the same meaning for both. If the very meaning of scope is different when we are talking about statically scoped languages than when we are talking about dynamically scoped ones, then trying to compare them to each other in a meaningful way becomes difficult or impossible. For the record, my sentence above that begins "For every variable..." was not intended to be a definition. And, in the introduction to the article that you replaced, it was quite clear (I think) that the notion of scope (or scoping) applied to all kinds of named entities, not just variables. -- Cjoev 16:06, 4 Jun 2005 (UTC)
In languages with dynamic scoping, this is not the case, so for these languages we have to take "context" to mean something dynamic, related to (but not exactly the same as) the call stack. The consequence of this difference is that sentences like "a function is a scope" or "scopes can be nested" mean completely different things depending on whether the language is statically or dynamically scoped.
I'll readily admit that I have little experience with dynamic scoping, and consider it very possible that I have implicitly assumed static scoping in some sentences. Go ahead and improve. -- Eelis 19:27, 2005 Jun 3 (UTC)
Honestly, I don't either. -- Cjoev 16:06, 4 Jun 2005 (UTC)
-- Cjoev 14:42, 3 Jun 2005 (UTC)


The current text focuses almost exclusively on how variables bind to scopes, and on name resolution. However, the former is described in Variable#Scope_and_extent, and the latter is described in name resolution. Scopes are a much broader concept.

At this point I've made sure that all information and observations in this article regarding those two subjects are present in the two articles mentioned above. I'm currently in the process of writing a complete replacement for this article.

(Note: I've removed some comments which discussed how the ambiguation page should be set up, because apparently concensus has been reached and everybody seems happy with the current ambiguation page)

-- Eelis 21:23, 2005 May 22 (UTC)



When this was split from the disambiguation page, I think a bit of material was lost. I've copied at least the definition of scope back to the disambiguation page. Otherwise, an excellent job of making the disambiguation page!

First, I don't think we need to mention the definition of a word scope. This is an English edition, so we can assume readers are English speakers and know what a word scope means. Second, it seems there are no much to say about scope other than stuff in cs, so scope in cs as a main article is fine. -- Taku 00:07, Aug 1, 2004 (UTC)
I don't suppose you've seen scope (disambiguation)? --ssd 03:17, 1 Aug 2004 (UTC)

I wrote a new introductory paragraph and changed some things later on to make them consistent with my new introduction. I fear my prose may be awkward (scope is a tricky thing to talk about informally) but I think my facts are right. Edit away.

My intent in writing the new introduction was to make the definition of scope more about languages than about the practice or experience of programming, and in particular to clear the way for discussing both static and dynamic scoping in a single article. If this article is ever merged with the ones on static scoping and dynamic scoping, most of the concrete discussion may have to be moved, as it seems to be biased toward static scoping. Perhaps this should be made clear regardless.

-- Cjoev 22:27, 14 Apr 2005 (UTC)

just my oppinion: reference should be made to the object-based scoping model used in the language Self? I am not sure what this one is called exactly, but I have typically been using the term "object scoping". other possibilities could be "prototype object scoping" or "delegate scoping"...

rough: you have an object called 'self' (or 'this' in many languages), which may refer to 0 or more objects as delegates. attempts to access a slot not found in the current object results in a recursive search of all delegated to objects, and their delegates, and such forth.

note: I am new to wikis...

(supposed to write own date string? sorry, dunno what the username is so I just used my typical handle...). -- cr88192, Mon Apr 25 00:05:04 UTC 2005

ok, I understand now, sorry for all the edits...

Sure, why not. I agree that an encyclopedia article on scoping should give a good sense of the range of possible scoping rules language designers have come up with over the years, particularly if they are used in more than one language. That's exactly the direction I hoped I could steer us in with my recent edit. So, two questions: (1) Is this rule from Self used in any languages besides Self? If it's just an idiosyncrasy of that particular language then I don't know if it belongs in a general article. (2) Can you point me to an online reference for Self so I can learn more?
Also, the language designer in me feels compelled to say: What a horrible rule! How could a language that works that way possibly be any good? Just a gut reaction... not that it makes a difference when it comes to including it in the article, of course.
Cjoev 15:16, 25 Apr 2005 (UTC)

ok, the rule also exists as a secondary scheme in javascript afaik (one can omit self and still access values in delegates). javascript by default uses lexical scoping for most things.

newtonscript is another example.

self link: http://en.wikipedia.org/wiki/Self_programming_language

a few related languages: http://en.wikipedia.org/wiki/Category:Prototype-based_programming_languages

sorry, off hand I don't have many good links. I still don't know what it is called.

misc: I have my own language as well, which also uses this model (as the default scoping). lexical and dynamic scoping are also present, just with lexical scoping more relegated to use in locals and construction of closures and such, and dynamic scoping for what uses it still has...

why I think it is cool: it is much looser than lexical scoping; it deals with the module issue much better imo; it maps over much better to a networked environment imo (or more like, one where nodes can interact and readily share code/data); imo it works better with persistent stores where only part of the environment is being saved; ...

of course, yes, imo lexical scoping is still quite useful, I just like it's use more being for local vars, tighter/more-complex code, and similar...

or such...

-- cr88192, Tue, 03 May 2005 11:46:53 +0000

[edit] not only for experts

this is way too abstract for novices -- even novice PROGRAMMERS -- to understand. while it may or may not be precise...this is beyond encyclopedic level. imagine coming to this page your second (or 10th) week of programming trying to figure out what the hell your instructor means by scope --172.195.81.145 04:49, 11 July 2005 (UTC)

Well, I kind of disagree. I came to this article wanting to learn about lexical vs. dynamic scoping and the article did its job very well. After having read it, it seems well written and concise and it relayed to me the information I was seeking. I definitely wouldn't want it to be dumbed down, because the way it is right now, it is quite clear and helpful. The 'cleanup' marker in particular appears undeserved, I hope nobody minds if I remove it. Denis bider 01:25, 9 August 2005 (UTC)

[edit] C

I did not think that C's scoping rules qualified as "lexical scoping" since you cannot refer to a variable in an enclosing (functional, not block) scope, unless it is a global variable. Maybe this can be construed as some kind of degenerate case of lexical scoping? e.g.:

void f1()
{
  int x;
  x = 3;
  f2();
}

void f2()
{
  printf("%d", x);
}

the above code would cause a compiler error because the variable "x" does not exist in the scope of f2 -- f2 cannot refer to variables in an outer scope. So even if you use function pointers, there is no closure associated with the function pointer except the global scope. Maybe the author was referring to static variables?

Actually, this is precisely why C's scoping rules are lexical. C does not consider f1 to "enclose" f2, simply because the definition of f2 is outside the body of f1 in the program text (as is always the case in C). The fact that this, rather than what happens at runtime, is what determines scopes is exactly what it means to say C's scoping is lexical. Cjoev 01:51, 26 January 2006 (UTC)
That's right, the example above (if it worked) would be using dynamic scoping, not lexical scoping. Michael Geary 10:33, 20 February 2006 (UTC)
C's scoping rules happen to be lexical, but you can't nest scopes (there's really just global or local), so it's a moot point. 216.213.63.10 18:43, 12 September 2006 (UTC)

[edit] Compiled languages

I removed the sentence "In compiled languages, scopes are strictly compile time entities. Scopes are used to define and structure various program entities, but a compiled program is completely unaware of scope."

A given programming language could have both a compiler and interpreter, but the scoping rules of the language wouldn't be determined by which implementation you happened to use (otherwise they wouldn't be the same language).

That is correct. Indeed several languages that are typically implemented using a compiler support run-time representations of scopes. In fact I wrote one less than a year ago.
Actually, that's not true (interepreted vs. compiled scoping). That was a deficiency since Lisp 1.5 and was finally removed by Common Lisp because of the headaches it caused. Interpreted code used dynamic scoping and compiled code used lexical scoping. Rahul-jain 18:48, 12 September 2006 (UTC)
Do sign your posts, though. Wouter Lievens 10:36, 20 February 2006 (UTC)
(Note: the above anonymous comment is not mine.) Would it be more accurate to say that in statically scoped languages, scopes are compile time entities? That seems to be an important aspect of the difference between static and dynamic scoping: under dynamic scoping, the only thing that counts when resolving a variable is which of the currently active bindings was created the most "recently" (a dynamic concept), but under static scoping, the lexical structure of the program comes into play. Cjoev 18:59, 20 February 2006 (UTC)
You don't always need to remove static scope information after compilation, but a good optimizer could make the static scope information completely irrelevant to the resulting code, so there would be no possible way to access it. Rahul-jain 18:48, 12 September 2006 (UTC)

[edit] Scheme

Scheme's lexical scoping was inspired by Algol. It was an attempt to show that a Lisp could be implemented such that it had consistently lexical scoping. Guy Steele, when desigining Common Lisp, accepted Scheme's argument and made the default scoping mechanism in Lisp to be lexical, with the option of declaring a variable to have dynamic scoping instead. I think the History section needs some revising in light of these details. Rahul-jain 18:49, 12 September 2006 (UTC)

[edit] Namespaces

Namespaces are unrelated to scopes. The same name can have different bindings in different scopes. The issue at hand is that C++ does not have first-class names or dynamic binding, where such differences can appear.Rahul-jain 19:07, 12 September 2006 (UTC)

[edit] Example

I changed the Perl example to one which correctly demonstrates dynamic scope. The prior one's "dynamic" variable $y did not use a stack (see the "Dynamic scoping" section above; it correctly mentions this as a defining characteristic), so it was not a dynamically-bound variable! It was a global variable. My example demonstrates all three, and they're correctly labeled.

You are confusing global vs. local and dynamic vs. lexical. Of course $x is dynamic
{
  my $x = "lexical"; # $x is defined lexically for function lexical()
 $x  = "2nd value";
 sub lexical {
      print "\nXL=$x, YL=$y";
  }
}

Note that my use of local for dynamic variables is also consistent with Perl's documentation. In the perlsub manual page, the "Temporary Values via local()" subsection, the very first line says:


          local $foo;                 # make $foo dynamically local

Likewise, in the "Private Variables via my()" subsection,

          my $foo;            # declare $foo lexically local

And near the top of the "DESCRIPTION" section:

      Variables that aren't declared to be
      private are global variables.


Jbolden1517, please do not revert again without explaining here.

Slamb 18:19, 10 December 2006 (UTC)

Okay, you just reverted again without explaining here. That annoys me, but you did it quickly enough that maybe you looked at the talk page between me pointing you at it and adding this section. In regards to your explanation that my version is incorrect:

In other words the enclosing blocks syntax will mean that variables resolve to the value assigned in the environment of definition, not resolve in the environment of execution.

Look again at my example. That is true of it as well, and it demonstrates this difference. f()'s lexically-bound variable $x does not affect g's environment (even though g is executed within f) but f()'s dynamically-bound and global variables $y and $z do.

Slamb 18:41, 10 December 2006 (UTC)

You are getting two things confused:

  • A lexical name space
  • A lexical variable.

Larry's usage of the term is unusual, but again he's trying to explain local vs. my to programmers learning Perl not scope to computer language theorists . The article is trying to explain scope and the correct usage. Why don't you read the article which explains the correct usage? Or at least tie your example into the rest of the article. I've given a fairly strong citation for the definition I'm using. [1].

I'm not sure I see a point. But out of AGF its been explained here. The article explains it rather well. You didn't read the article you are editing, so I don't really expect you to read what I write here. If you have any interest in actually addressing the point [2] will help you to clarify what you are getting confused. I doubt that's the case. So feel free to write a deliberately misleading article based on an accidentally misleading aside in the camel book. jbolden1517Talk 18:47, 10 December 2006 (UTC)

You'd already annoyed me by reverting without the requested explanation. Now you've reverted again, accused me of deliberate misinformation, removed part of my explanation (which I am adding back in this revision), posted part of your comment within mine (which I've moved in this revision), and accused me of not reading the article. And you're claiming to follow AGF? Have you gone insane?

I've cited both another section of the article and the documentation of the programming language in question, and I've presented arguments. In the interest of following AGF, I'll take a bit to read through and understand the reference you cited (which will take a while since Lisp is not my functional language of choice). I suggest you take the same time to calm down and think about what you're doing.

Slamb 19:18, 10 December 2006 (UTC)