名字解析 (程式設計)

本頁使用了標題或全文手工轉換
維基百科,自由的百科全書

電腦程式設計語言中,名字解析是指把程式表達式中的標記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