名字解析 (程序設計)

計算機程序設計語言中,名字解析是指把程序表達式中的標記token)對應解析到程序成分(program components)。

概述 編輯

不同語言的名字解析算法的複雜度不同。例如,匯編語言的名字解析只需要簡單地查關聯表英語Associative array。而C++的名字解析就非常複雜,受命名空間作用域、可見性規則(visibility rules)、函數重載、可訪問性(accessibility)影響。

靜態解析與動態解析 編輯

編譯時完成的稱靜態名字解析;運行時完成的稱動態名字解析。

動態類型並不意味着動態名字解析。例如,Erlang是動態類型但靜態名字解析。

下述Python程序:

>>> locals()['num'] = 999 # equivalent to: num = 999
>>> noun = "troubles"
>>> noun2 = "hound"
>>> # which variables to use are decided at runtime
>>> print("{num} {noun} and a {noun2} ain't one".format(**locals()))
999 troubles and a hound ain't one

但現在的Python編程風格指引不建議使用動態名字解析。[1][2][3]

靜態名字解析的語言有:C語言, C++, E語言, Erlang, Haskell, Java, Pascal語言, Scheme語言, Smalltalk。動態名字解析的語言有:Lisp, Perl, PHP, Python, REBOL, Tcl.

名字屏蔽 編輯

名字屏蔽name Masking)發生在同一個名字用於不同的實體,出現在重疊的作用域內。 例如,在下述Java程序中:

  private int foo;  // A declaration with name "foo" in an outer scope
  public void setFoo(int foo) {  // A declaration with the same name in the inner scope
    // "foo" is resolved by looking in the innermost scope first,
    // so the author uses a different syntax, this.foo, to refer to the name "foo"
    // in the outer scope.
    this.foo = foo;
  }
  // "foo" here means the same as this.foo below,
  // since setFoo's parameter is no longer in scope.
  public int getFoo() { return foo; }

α更名簡化了名字解析 編輯

程序設計語言使用α-變換使得沒有變量名屏蔽了其它同名的實體。可用於靜態代碼分析,使得理解源代碼更為容易。

例如:

  class Point {
  private:
    double x, y;

  public:
    Point(double x, double y) {  // x and y declared here mask the privates
      setX(x);
      setY(y);
    }

    void setX(double newx) { x = newx; }
    void setY(double newy) { y = newy; }
  }

Point構造函數中,類的數據成員xy被局部變量屏蔽了。這可通過α更名改善:

  class Point {
  private:
    double x, y;

  public:
    Point(double a, double b) {
      setX(a);
      setY(b);
    }

    void setX(double newx) { x = newx; }
    void setY(double newy) { y = newy; }
  }


參見 編輯

參考文獻 編輯

  1. ^ [Python-Ideas] str.format utility function. 9 May 2009 [2011-01-23]. (原始內容存檔於2018-07-14). 
  2. ^ 8.6. Dictionary-based string formatting. diveintopython.org. Mark Pilgrim. [2011-01-23]. (原始內容存檔於2019-12-23). 
  3. ^ 9. Classes - Python v2.7.1 documentation. [2011-01-23]. (原始內容存檔於2012-10-23). search for names is done dynamically, at run time — however, the language definition is evolving towards static name resolution