From 790e075986acb74ad78cb28844b8a99e3c5cf969 Mon Sep 17 00:00:00 2001 From: Thejaswi Kadur Date: Wed, 27 Jul 2022 10:29:09 -0700 Subject: [PATCH] Convert first Print argument to String before evaluating (#1548) Fixes #1439. --- explorer/interpreter/interpreter.cpp | 13 +++++---- .../testdata/print/associated_constant.carbon | 27 +++++++++++++++++++ 2 files changed, 35 insertions(+), 5 deletions(-) create mode 100644 explorer/testdata/print/associated_constant.carbon diff --git a/explorer/interpreter/interpreter.cpp b/explorer/interpreter/interpreter.cpp index a8c362887be0..770a67adae13 100644 --- a/explorer/interpreter/interpreter.cpp +++ b/explorer/interpreter/interpreter.cpp @@ -1156,15 +1156,18 @@ auto Interpreter::StepExp() -> ErrorOr { switch (cast(exp).intrinsic()) { case IntrinsicExpression::Intrinsic::Print: { const auto& args = cast(*act.results()[0]).elements(); + CARBON_ASSIGN_OR_RETURN( + Nonnull format_string_value, + Convert(args[0], arena_->New(), exp.source_loc())); + const char* format_string = + cast(*format_string_value).value().c_str(); switch (args.size()) { case 1: - llvm::outs() << llvm::formatv( - cast(*args[0]).value().c_str()); + llvm::outs() << llvm::formatv(format_string); break; case 2: - llvm::outs() << llvm::formatv( - cast(*args[0]).value().c_str(), - cast(*args[1]).value()); + llvm::outs() << llvm::formatv(format_string, + cast(*args[1]).value()); break; default: CARBON_FATAL() << "Unexpected arg count: " << args.size(); diff --git a/explorer/testdata/print/associated_constant.carbon b/explorer/testdata/print/associated_constant.carbon new file mode 100644 index 000000000000..7d2836f61716 --- /dev/null +++ b/explorer/testdata/print/associated_constant.carbon @@ -0,0 +1,27 @@ +// Part of the Carbon Language project, under the Apache License v2.0 with LLVM +// Exceptions. See /LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +// RUN: %{explorer} %s 2>&1 | \ +// RUN: %{FileCheck} --match-full-lines --allow-unused-prefixes=false %s +// RUN: %{explorer} --parser_debug --trace_file=- %s 2>&1 | \ +// RUN: %{FileCheck} --match-full-lines --allow-unused-prefixes %s +// AUTOUPDATE: %{explorer} %s +// CHECK: i32 +// CHECK: String +// CHECK: result: 0 + +package Testcase api; + +interface HasName { + let Name:! String; +} + +external impl i32 as HasName where .Name == "i32" {} +external impl String as HasName where .Name == "String" {} + +fn Main() -> i32 { + Print(i32.(HasName.Name)); + Print(String.(HasName.Name)); + return 0; +}