AstGen: require @import operand to be string literal

See #2206
This commit is contained in:
Andrew Kelley 2021-04-16 15:50:28 -07:00
parent 333a577d73
commit adc2aed587
3 changed files with 16 additions and 8 deletions

View File

@ -4674,8 +4674,17 @@ fn builtinCall(
return rvalue(gz, scope, rl, .void_value, node);
},
.import => {
const target = try expr(gz, scope, .none, params[0]);
const result = try gz.addUnNode(.import, target, node);
const node_tags = tree.nodes.items(.tag);
const node_datas = tree.nodes.items(.data);
const operand_node = params[0];
if (node_tags[operand_node] != .string_literal) {
// Spec reference: https://github.com/ziglang/zig/issues/2206
return astgen.failNode(operand_node, "@import operand must be a string literal", .{});
}
const str_lit_token = main_tokens[operand_node];
const str = try gz.strLitAsString(str_lit_token);
const result = try gz.addStrTok(.import, str.index, str_lit_token);
return rvalue(gz, scope, rl, result, node);
},
.error_to_int => {

View File

@ -3900,10 +3900,9 @@ fn zirImport(sema: *Sema, block: *Scope.Block, inst: Zir.Inst.Index) InnerError!
defer tracy.end();
const mod = sema.mod;
const inst_data = sema.code.instructions.items(.data)[inst].un_node;
const inst_data = sema.code.instructions.items(.data)[inst].str_tok;
const src = inst_data.src();
const operand_src: LazySrcLoc = .{ .node_offset_builtin_call_arg0 = inst_data.src_node };
const operand = try sema.resolveConstString(block, operand_src, inst_data.operand);
const operand = inst_data.get(sema.code);
const file = mod.importFile(block.getFileScope().pkg, operand) catch |err| switch (err) {
error.ImportOutsidePkgPath => {

View File

@ -377,8 +377,8 @@ pub const Inst = struct {
/// Implements the `@hasDecl` builtin.
/// Uses the `pl_node` union field. Payload is `Bin`.
has_decl,
/// `@import(operand)`.
/// Uses the `un_node` field.
/// Implements the `@import` builtin.
/// Uses the `str_tok` field.
import,
/// Integer literal that fits in a u64. Uses the int union value.
int,
@ -1699,7 +1699,6 @@ const Writer = struct {
.load,
.ensure_result_used,
.ensure_result_non_error,
.import,
.ptrtoint,
.ret_node,
.set_eval_branch_quota,
@ -1871,6 +1870,7 @@ const Writer = struct {
.enum_literal,
.decl_ref_named,
.decl_val_named,
.import,
=> try self.writeStrTok(stream, inst),
.func => try self.writeFunc(stream, inst, false),