名字解析 (程序设计)
计算机程序设计语言中,名字解析是指把程序表达式中的标记(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; } }
参见编辑
参考文献编辑
- ^ [Python-Ideas] str.format utility function. 9 May 2009 [2011-01-23]. (原始内容存档于2018-07-14).
- ^ 8.6. Dictionary-based string formatting. diveintopython.org. Mark Pilgrim. [2011-01-23]. (原始内容存档于2019-12-23).
- ^ 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
🔥 Top keywords: Baike: 首页Special:搜索毛泽东家族榮耀之繼承者天之驕女鐵拳英雄九龍城寨之圍城黃循財背着善宰跑篠崎泫妮妃雅新生 (网络剧)劉偉健斯洛伐克习近平劉俊謙 (香港)李显龙歌手2024佛誕淚之女王2024年泰國羽球公開賽新加坡總理邊佑錫新加坡Energy (組合)庆余年九龍寨城六四事件家族榮耀金智媛彌助菲律宾胖猫跳江事件劉寶傑DAY6林峯張文傑李光耀神耆小子張鳳妮黃世聰Seventeen (組合)维基百科願榮光歸香港中華民國鬼滅之刃 柱訓練篇2024年英雄联盟季中邀请赛中华人民共和国TripleS金秀賢 (男演員)罗伯特·菲佐井柏然2024年世界女排联赛黃偉哲怪獸8號佘詩曼Foodpanda金惠奫新加坡总统香緹·摩爾于北辰 (1968年)王嘉爾笑看風雲排球少年!!角色列表林飛帆郭葦昀馴鹿寶貝翁靜晶猩球崛起:王國誕生ILLIT尼古拉·約基奇春色寄情人周殷廷鬼滅之刃排球少年!!吳釗燮逆天奇案2不夠善良的我們BABYMONSTER李正皓尚达曼BOYNEXTDOOR胡子彤IVE (組合)陳靜 (香港)香港吴作栋黃道十二宮凡希亚·奥伊亚胡宇威長洲太平清醮張員瑛搜查班長1958伍允龍习明泽黄岩岛賴清德偶然遇見的你虽然不是英雄