Ruby:评论标记是什么?

时间:2011-05-25 13:57:49

标签: ruby

我刚刚在这里阅读(http://ruby.runpaint.org/programs#lexical)评论是令牌。我从来没有把评论视为标记,因为它们既可以是注释,也可以是后处理器。

评论真的是令牌还是这个来源错了?

2 个答案:

答案 0 :(得分:4)

是的,它们应该是令牌,但稍后会被解析器忽略。如果你使用看起来像这样的文件ruby --dump parsetree foo.rb

# this is a comment
1+1
# another comment

这是你得到的:

# @ NODE_SCOPE (line: 3)
# +- nd_tbl: (empty)
# +- nd_args:
# |   (null node)
# +- nd_body:
#     @ NODE_CALL (line: 2)
#     +- nd_mid: :+
#     +- nd_recv:
#     |   @ NODE_LIT (line: 2)
#     |   +- nd_lit: 1
#     +- nd_args:
#         @ NODE_ARRAY (line: 2)
#         +- nd_alen: 1
#         +- nd_head:
#         |   @ NODE_LIT (line: 2)
#         |   +- nd_lit: 1
#         +- nd_next:
#             (null node)

答案 1 :(得分:3)

是的,他们是解析器的代币。通常,如果使用解析器生成器,则这是注释的定义

{code} short_comment = '//' not_cr_lf* eol | '#' not_cr_lf* eol;
{code} long_comment = '/*' not_star* '*'+ (not_star_slash not_star* '*'+)* '/';  /* '4vim */
Ignored Tokens
  short_comment,
  long_comment;

这是一个SableCC语法。他们通常会忽略令牌。

请记住,您在源代码中编写的所有内容都是令牌,这始终是第一步。解析器需要从标记开始构建抽象语法树。