gpt4 book ai didi

rust - 允许针对不同版本的源代码进行互操作的确切机制是什么?

转载 作者:行者123 更新时间:2023-11-29 07:54:07 24 4
gpt4 key购买 nike

我了解版本的目标以及如何使用它们,但是 the documentation没有阐明他们的内部运作。

假设我有两个源文件:

  • old.rs,针对 Rust 2015;

  • new.rs,目标是 Rust 2018。

我想构建一个同时使用它们的应用程序。正在使用什么机制来确保它们可以互操作?

old.rsnew.rs 是否都转换为相同的 HIR 模型?或者均质化发生在之前(例如 AST 级别)还是之后(例如 MIR 级别)?

最佳答案

版本只会影响语法,不会改变编译器编译代码的方式。解析器几乎是编译器中唯一可识别版本的组件,通过对版本进行一些检查来决定如何解析内容。两个版本的 AST 是相同的,尽管 span 知道它们的版本并且编译器中的一些东西检查它们使用的是哪个版本。 HIR 和 MIR 不需要知道版本。

例如。对于 new keywords :

/// Returns `true` if the token is a keyword used in the language.
pub fn is_used_keyword(self) -> bool {
// Note: `span.edition()` is relatively expensive, don't call it unless necessary.
self.name >= kw::As && self.name <= kw::While ||
self.name.is_used_keyword_2018() && self.span.rust_2018()
}

额外的self.name.is_used_keyword_2018() && self.span.rust_2018() 会检查关键字是否是2018版新增的关键字(eg. dyn),2015 年,它将被视为常规符号。

另一个例子是,在 2015 年,可以在 trait 声明中省略参数名称,但现在已被禁止。这是 handled transparently as well :

// We don't allow argument names to be left off in edition 2018.
let is_name_required = p.token.span.rust_2018();
p.parse_arg_general(true, false, |_| is_name_required)

然后是另外一段代码will emit an error in this case, but only for 2018 :

if require_name && (
is_trait_item ||
self.token == token::Comma ||
self.token == token::CloseDelim(token::Paren)
) { // `fn foo(a, b) {}` or `fn foo(usize, usize) {}`
err.span_suggestion(
pat.span,
"if this was a parameter name, give it a type",
format!("{}: TypeName", ident),
Applicability::HasPlaceholders,
);
err.span_suggestion(
pat.span,
"if this is a type, explicitly ignore the parameter name",
format!("_: {}", ident),
Applicability::MachineApplicable,
);
err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)");
return Some(ident);
}

对于 2015 年,a dummy name is created instead :

let ident = Ident::new(kw::Invalid, self.prev_span);
let pat = P(Pat {
id: ast::DUMMY_NODE_ID,
node: PatKind::Ident(
BindingMode::ByValue(Mutability::Immutable), ident, None),
span: ty.span,
});

编译器的其余部分不需要知道用户是否实际提供了名称。

关于rust - 允许针对不同版本的源代码进行互操作的确切机制是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57332016/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com