電腦程式設計語言中,名字解析是指把程式表達式中的標記(token)對應解析到程式成分(program components)。
概述
不同語言的名字解析演算法的複雜度不同。例如,匯編語言的名字解析只需要簡單地查關聯表。而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建構函式中,類的數據成員x與y被局部變數封鎖了。這可通過α更名改善:
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; }
}
參見
參考文獻
Wikiwand in your browser!
Seamless Wikipedia browsing. On steroids.
Every time you click a link to Wikipedia, Wiktionary or Wikiquote in your browser's search results, it will show the modern Wikiwand interface.
Wikiwand extension is a five stars, simple, with minimum permission required to keep your browsing private, safe and transparent.