Sfoglia il codice sorgente

Convert first Print argument to String before evaluating (#1548)

Fixes #1439.
Thejaswi Kadur 3 anni fa
parent
commit
790e075986

+ 8 - 5
explorer/interpreter/interpreter.cpp

@@ -1156,15 +1156,18 @@ auto Interpreter::StepExp() -> ErrorOr<Success> {
       switch (cast<IntrinsicExpression>(exp).intrinsic()) {
         case IntrinsicExpression::Intrinsic::Print: {
           const auto& args = cast<TupleValue>(*act.results()[0]).elements();
+          CARBON_ASSIGN_OR_RETURN(
+              Nonnull<const Value*> format_string_value,
+              Convert(args[0], arena_->New<StringType>(), exp.source_loc()));
+          const char* format_string =
+              cast<StringValue>(*format_string_value).value().c_str();
           switch (args.size()) {
             case 1:
-              llvm::outs() << llvm::formatv(
-                  cast<StringValue>(*args[0]).value().c_str());
+              llvm::outs() << llvm::formatv(format_string);
               break;
             case 2:
-              llvm::outs() << llvm::formatv(
-                  cast<StringValue>(*args[0]).value().c_str(),
-                  cast<IntValue>(*args[1]).value());
+              llvm::outs() << llvm::formatv(format_string,
+                                            cast<IntValue>(*args[1]).value());
               break;
             default:
               CARBON_FATAL() << "Unexpected arg count: " << args.size();

+ 27 - 0
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;
+}