- 论坛徽章:
- 0
|
本帖最后由 幻の上帝 于 2012-09-26 00:45 编辑
(擦。。。又忘记勾上禁用表情……)
回复 156# starwing83
当你说“为什么C语法如此规定呢”的时候,就已经超越C的范畴了——C没有强大到能自举它的语义。C的背后的变量和标识符再怎么合理或者不合理,也没法改变像语法这样的“死”的事实的既定性质。假设“C语法是这么规定的”不合理,你也没办法——它已经这样地使用了这么多年,而改变它需要做好改变所有用户的认识的准备。
你大概没清楚地理解我想说的entity是什么。entity意味着它是语言抽象的目标——除了不是单用来引用entity的手段(名称,包括C++这样的name、identifier等),它可以是能影响语义(排除label等)表达(程序行为)的任何抽象的东西。即便没有明确entity的概念(就像ISO C一样),entity和name的区别是实在的、无法忽视的。对于允许同一个名称在不同上下文的含义发生改变的语言(有做不到这点的语言么……应该有,但看来没实际意义)来说,variable能够具有类型,一个前提就是它不是name,或者说,只要有必要,variable和variable name之间总可以找到绝对的界限来区分。否则,字面上的和背后的含义就无法分辨了——谁知道你这个variable name意味着是哪个variable?
//以下伪代码以C++为例。
class token
{
//...
};
class identifier : public token
{
//...
};
class punctuator : public token
{
//...
};
class alternative_token : public token
{
//...
};
typedef unspecified<token> token_list;
class name
{
//...
};
name make_qualified_name(token_list);
token_list parse_name(name);
class expression //原本想final……看在一堆virtual上就算了。
{
private:
expression_impl* pimpl // for storage of tokens
public:
expression(token_list);
virtual type get_type();
virtual value& get_value(); //对于无副作用的语言,去掉&
private:
virtual storage_location(); //这个不是必要的公共接口。
entity get_entity(name) throw(error); //不必然成功,表达式并非一定能引用实体,名称也不一定正确——可能没有声明。
virtual void verify_sema_rules() throw(error, warning);
public:
//accessors for value category、enclosing scope、attributes...
};
// entity不出现在其中,因为entity是抽象上最顶层的东西,并不和表达式关联(不像name/identifier这样可以通过语法直接或间接的定义)。ISO C++之所以用单独列举外延而不是描述内涵或和表达式放在一起来定义这个概念,这应该是重要原因。
enum class entity_category
{
object,
function,
reference,
type
//...略
};
entity_category get_referent_category(entity_category);
class entity
{
private:
entity category;
public:
//ctor
bool is_object() const{return category == entity_category::object;}
bool is_function() const{return category == entity_category::function;}
bool is_variable() const{return is_object() || (is_reference() && get_referent_category(category) == entity_category::object);}
entity_category get_category() const;
//other accessors
//...
};
//当然也可以不这么描述,用派生类表示各种具体的实体。反正一种语言的entity一共就这么些。
|
|