File: SwiftExpressionSourceCode.cpp

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (675 lines) | stat: -rw-r--r-- 26,288 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
//===-- SwiftExpressionSourceCode.cpp --------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "SwiftExpressionSourceCode.h"
#include "SwiftPersistentExpressionState.h"

#include "Plugins/ExpressionParser/Swift/SwiftASTManipulator.h"
#include "Plugins/TypeSystem/Swift/SwiftASTContext.h"
#include "lldb/Target/Language.h"
#include "lldb/Target/Platform.h"
#include "lldb/Target/Target.h"
#include "lldb/Utility/StreamString.h"

#include "swift/Basic/LangOptions.h"
#include "swift/Demangling/Demangle.h"
#include "swift/Demangling/Demangler.h"

#include "llvm/ADT/StringRef.h"
#include "llvm/BinaryFormat/Dwarf.h"

using namespace lldb;
using namespace lldb_private;

namespace lldb_private {
std::optional<std::pair<unsigned, unsigned>>
ParseSwiftGenericParameter(llvm::StringRef name) {
  if (!name.consume_front("$τ_"))
    return {};

  auto pair = name.split('_');
  auto depth_str = pair.first;
  auto index_str = pair.second;
  unsigned depth, index;
  if (depth_str.getAsInteger(10, depth) || index_str.getAsInteger(10, index))
    return {};
  return {{depth, index}};
}
} // namespace lldb_private

static const char *GetUserCodeStartMarker() {
  return "/*__LLDB_USER_START__*/\n";
}
static const char *GetUserCodeEndMarker() { return "\n/*__LLDB_USER_END__*/"; }

/// Remove SILPacktype and print the name with substitutions applied.
static llvm::Expected<std::string> TransformPackType(
    CompilerType type,
    llvm::SmallDenseMap<std::pair<unsigned, unsigned>, llvm::SmallString<4>>
        subs) {
  auto tss = type.GetTypeSystem().dyn_cast_or_null<TypeSystemSwift>();
  if (!tss)
    return llvm::createStringError(llvm::errc::not_supported,
                                   "unexpected typesystem");
  auto &ts = tss->GetTypeSystemSwiftTypeRef();
  using namespace swift::Demangle;
  Demangler dem;
  NodePointer node = ts.GetCanonicalDemangleTree(
      dem, type.GetMangledTypeName().GetStringRef());

  node = TypeSystemSwiftTypeRef::Transform(dem, node, [](NodePointer n) {
    if (n->getKind() == Node::Kind::SILPackIndirect &&
        n->getNumChildren() == 1) {
      n = n->getFirstChild();
      if (n->getKind() == Node::Kind::Type && n->getNumChildren() == 1)
        return n->getFirstChild();
    }
    return n;
  });

  bool error = false;
  ConstString type_name = ts.RemangleAsType(dem, node).GetMangledTypeName();
  swift::Demangle::DemangleOptions options;
  options = swift::Demangle::DemangleOptions::SimplifiedUIDemangleOptions();
  options.DisplayStdlibModule = false;
  options.DisplayObjCModule = false;
  options.QualifyEntities = true;
  options.DisplayModuleNames = true;
  options.DisplayLocalNameContexts = false;
  options.DisplayDebuggerGeneratedModule = false;
  options.GenericParameterName = [&](uint64_t depth,
                                     uint64_t index) -> std::string {
    auto it = subs.find({depth, index});
    if (it != subs.end())
      return it->second.str().str();
    error = true;
    return "$error";
  };
  std::string name = swift::Demangle::demangleSymbolAsString(
      type_name.GetStringRef(), options);
  if (error)
    return llvm::createStringError(llvm::errc::not_supported,
                                   "unexpected generic parameter");
  return name;
}

struct CallsAndArgs {
  std::string lldb_user_expr;
  std::string lldb_trampoline;
  std::string lldb_sink;
  std::string lldb_call;
};

/// Constructs the signatures for the expression evaluation functions based on
/// the metadata variables in scope and any variadic functiontion parameters.
/// For every outermost metadata pointer in scope ($τ_0_0, $τ_0_1, etc), we want
/// to generate:
///
/// - A $__lldb_user_expr signature that takes in that many metadata pointers:
///
/// func $__lldb_user_expr<T0, T1, ..., Tn>
///     (_ $__lldb_arg: UnsafeMutablePointer<(T0, T1, ..., Tn)>)
///
/// - An optional $__lldb_trampoline signature like the above, but
///   that also takes in a pointer to self:
///
/// func $__lldb_trampoline<T0, T1, ..., Tn>
///      (_ $__lldb_arg: UnsafeMutablePointer<(T0, T1, ..., Tn)>,
///       _ $__lldb_injected_self: inout $__lldb_context)
///
/// - A $__lldb_sink signature that matches the number of parameters of the
///   trampoline:
///
/// func $__lldb_sink(_ $__lldb_arg : UnsafeMutablePointer<Any>,
///                   _: $__lldb_builtin_ptr_t, // the self variable
///                   _: $__lldb_builtin_ptr_t, // T0
///                   _: $__lldb_builtin_ptr_t, // T1
///                   ...,
///                   _: $__lldb_builtin_ptr_t) // Tn
///
/// - And a matching call to the sink function:
///
/// lldb_sink($__lldb_arg, [$__lldb_injected_self, [pack args, pack counts...]],
///           $τ_0_0, $τ_0_1, ..., $τ_0_n)
static llvm::Expected<CallsAndArgs> MakeGenericSignaturesAndCalls(
    llvm::ArrayRef<SwiftASTManipulator::VariableInfo> local_variables,
    const std::optional<SwiftLanguageRuntime::GenericSignature> &generic_sig,
    bool needs_object_ptr) {
  llvm::SmallVector<const SwiftASTManipulator::VariableInfo *>
      metadata_variables;
  for (auto &var : local_variables)
    if (var.IsOutermostMetadataPointer())
      metadata_variables.push_back(&var);

  // The number of metadata variables could be > if the function is in
  // a generic context.
  if (generic_sig &&
      (metadata_variables.size() < generic_sig->dependent_generic_param_count))
    return llvm::createStringError(llvm::errc::not_supported,
                                   "Inconsistent generic signature");

  llvm::SmallDenseMap<std::pair<unsigned, unsigned>, llvm::SmallString<4>> subs;
  std::string generic_params;
  std::string generic_params_no_packs;
  llvm::raw_string_ostream s_generic_params(generic_params);
  llvm::raw_string_ostream s_generic_params_no_packs(generic_params_no_packs);
  for (size_t i = 0; i < metadata_variables.size(); ++i) {
    llvm::SmallString<4> archetype_name;
    llvm::raw_svector_ostream s_archetype_name(archetype_name);
    bool is_pack = false;
    unsigned depth, index;
    if (generic_sig) {
      auto &gp = generic_sig->generic_params[i];
      is_pack = gp.is_pack;
      depth = gp.depth;
      index = gp.index;
    } else {
      auto di =
          ParseSwiftGenericParameter(metadata_variables[i]->GetName().str());
      if (!di)
        return llvm::createStringError(llvm::errc::not_supported,
                                       "unexpected metadata variable");
      depth = di->first;
      index = di->second;
    }
    if (is_pack)
      s_archetype_name << "each ";
    s_archetype_name << "T" << i;
    if (!is_pack)
      s_generic_params_no_packs << archetype_name << ",";
    subs.insert({{depth, index}, archetype_name});
    s_generic_params << archetype_name << ",";
  }

  if (!generic_params.empty())
    generic_params.pop_back();
  if (!generic_params_no_packs.empty())
    generic_params_no_packs.pop_back();

  std::string user_expr; 
  llvm::raw_string_ostream user_expr_stream(user_expr);
  user_expr_stream << "func $__lldb_user_expr<" << generic_params
                   << ">(_ $__lldb_arg: UnsafeMutablePointer<("
                   << generic_params_no_packs << ")>";
  for (auto &var : local_variables)
    if (var.GetType().GetTypeInfo() & lldb::eTypeIsPack) {
      auto pack_type = TransformPackType(var.GetType(), subs);
      if (!pack_type)
        return pack_type.takeError();
      user_expr_stream << ", _ " << var.GetName() << ": "
                       << *pack_type;
    }
  user_expr_stream << ")";

  std::string trampoline;
  llvm::raw_string_ostream trampoline_stream(trampoline);
  trampoline_stream << "func $__lldb_trampoline<" << generic_params
                    << ">(_ $__lldb_arg: UnsafeMutablePointer<("
                    << generic_params_no_packs << ")>";
  if (needs_object_ptr)
    trampoline_stream << ", _ $__lldb_injected_self: inout $__lldb_context";
  trampoline_stream << ")";

  std::string sink;
  std::string call;
  llvm::raw_string_ostream sink_stream(sink);
  llvm::raw_string_ostream call_stream(call);
  sink_stream << "func $__lldb_sink(_ $__lldb_arg : "
    "UnsafeMutablePointer<Any>";
  call_stream << "$__lldb_sink($__lldb_arg";
  if (needs_object_ptr) {
    sink_stream << ", _: $__lldb_builtin_ptr_t";
    call_stream << ", $__lldb_injected_self";
  }
  unsigned num_value_packs = 0;
  for (auto &var : local_variables)
    if (var.IsUnboundPack()) {
      ++num_value_packs;
      sink_stream << ", _: $__lldb_builtin_ptr_t";
      call_stream << ", " << var.GetName();
    }
  // FIXME: This assumes all pack variables are local function arguments.
  assert(!generic_sig ||
         num_value_packs == generic_sig->pack_expansions.size());

  if (generic_sig)
    for (unsigned i = 0; i < generic_sig->num_counts; ++i) {
      sink_stream << ", _: $__lldb_builtin_int_t";
      call_stream << ", $pack_count_" << i;
    }
  for (auto &var : metadata_variables) {
    sink_stream << ", _: $__lldb_builtin_ptr_t";
    call_stream << ", " << var->GetName().str();
  }
  sink_stream << ")";
  call_stream << ")";

  CallsAndArgs retval = {user_expr, trampoline, sink, call};
  return retval;
}

static Status WrapExpression(
    lldb_private::Stream &wrapped_stream, const char *orig_text,
    bool needs_object_ptr, bool static_method, bool is_class, bool weak_self,
    const EvaluateExpressionOptions &options, llvm::StringRef os_version,
    uint32_t &first_body_line,
    llvm::ArrayRef<SwiftASTManipulator::VariableInfo> local_variables,
    const std::optional<SwiftLanguageRuntime::GenericSignature> &generic_sig) {
  Status status;
  first_body_line = 0; // set to invalid
  // TODO make the extension private so we're not polluting the class
  static unsigned int counter = 0;
  unsigned int current_counter = counter++;

  const bool playground = options.GetPlaygroundTransformEnabled();
  const bool repl = options.GetREPLEnabled();
  const bool generate_debug_info = options.GetGenerateDebugInfo();
  const char *pound_file = options.GetPoundLineFilePath();
  const uint32_t pound_line = options.GetPoundLineLine();
  const char *text = orig_text;
  StreamString fixed_text;

  if (playground) {
    const char *playground_logger_declarations = R"(
@_silgen_name ("playground_logger_initialize") func __builtin_logger_initialize ()
@_silgen_name ("playground_log_hidden") func __builtin_log_with_id<T> (_ object : T, _ name : String, _ id : Int, _ sl : Int, _ el : Int, _ sc : Int, _ ec: Int, _ moduleID: Int, _ fileID: Int) -> AnyObject
@_silgen_name ("playground_log_scope_entry") func __builtin_log_scope_entry (_ sl : Int, _ el : Int, _ sc : Int, _ ec: Int, _ moduleID: Int, _ fileID: Int) -> AnyObject
@_silgen_name ("playground_log_scope_exit") func __builtin_log_scope_exit (_ sl : Int, _ el : Int, _ sc : Int, _ ec: Int, _ moduleID: Int, _ fileID: Int) -> AnyObject
@_silgen_name ("playground_log_postprint") func __builtin_postPrint (_ sl : Int, _ el : Int, _ sc : Int, _ ec: Int, _ moduleID: Int, _ fileID: Int) -> AnyObject
@_silgen_name ("DVTSendPlaygroundLogData") func __builtin_send_data (_ :  AnyObject!)
__builtin_logger_initialize()
)";

    // The debug function declarations need only be declared once per session -
    // on the first REPL call.  This code assumes that the first call is the
    // first REPL call; don't call playground once then playground || repl
    // again
    bool first_expression = options.GetPreparePlaygroundStubFunctions();

    const char *playground_prefix =
        first_expression ? playground_logger_declarations : "";

    if (pound_file && pound_line) {
      wrapped_stream.Printf("%s#sourceLocation(file: \"%s\", line: %u)\n%s\n",
                            playground_prefix, pound_file, pound_line,
                            orig_text);
    } else {
      // In 2017+, xcode playgrounds send orig_text that starts with a module
      // loading prefix (not the above prefix), then a sourceLocation specifier
      // that indicates the page name, and then the page body text.  The
      // first_body_line mechanism in this function cannot be used to
      // compensate for the playground_prefix added here, since it incorrectly
      // continues to apply even after sourceLocation directives are read from
      // the orig_text.  To make sure playgrounds work correctly whether or not
      // they supply their own sourceLocation, create a dummy sourceLocation
      // here with a fake filename that starts counting the first line of
      // orig_text as line 1.
      wrapped_stream.Printf("%s#sourceLocation(file: \"%s\", line: %u)\n%s\n",
                            playground_prefix, "Playground.swift", 1,
                            orig_text);
    }
    first_body_line = 1;
    return status;
  }

  assert(!playground && "Playground mode not expected");

  if (repl) {
    if (pound_file && pound_line) {
      wrapped_stream.Printf("#sourceLocation(file: \"%s\", line:  %u)\n%s\n",
                            llvm::sys::path::filename(pound_file).str().c_str(),
                            pound_line, orig_text);
    } else {
      wrapped_stream.Printf("%s", orig_text);
    }
    first_body_line = 1;
    return status;
  }

  assert(!playground && !repl && "Playground/REPL mode not expected");

  auto path_literal = [](const char *path) -> std::string {
    std::string escaped;
    llvm::raw_string_ostream os(escaped);
    llvm::printEscapedString(path, os);
    return escaped;
  };

  if (pound_file && pound_line) {
    fixed_text.Printf("#sourceLocation(file: \"%s\", line: %u)\n%s\n",
                      path_literal(pound_file).c_str(), pound_line, orig_text);
    text = fixed_text.GetString().data();
  } else if (generate_debug_info) {
    std::string expr_source_path;
    if (SwiftASTManipulator::SaveExpressionTextToTempFile(orig_text, options,
                                                          expr_source_path)) {
      fixed_text.Printf("#sourceLocation(file: \"%s\", line: 1)\n%s\n",
                        path_literal(expr_source_path.c_str()).c_str(),
                        orig_text);
      text = fixed_text.GetString().data();
    }
  }

  // Note: All the wrapper functions we make are marked with the
  // @LLDBDebuggerFunction macro so that the compiler can do whatever special
  // treatment it need to do on them.  If you add new variants be sure to mark
  // them this way.  Also, any function that might end up being in an extension
  // of swift class needs to be marked final, since otherwise the compiler
  // might try to dispatch them dynamically, which it can't do correctly for
  // these functions.

  std::string availability = "";
  if (!os_version.empty())
    availability = (llvm::Twine("@available(") + os_version + ", *)").str();

  StreamString wrapped_expr_text;

  // Avoid indenting user code: this makes column information from compiler
  // errors match up with what the user typed.
  wrapped_expr_text.Printf(R"(
do {
%s%s%s
} catch (let __lldb_tmp_error) {
  var %s = __lldb_tmp_error
}
)",
                           GetUserCodeStartMarker(), text,
                           GetUserCodeEndMarker(),
                           SwiftASTManipulator::GetErrorName());

  if (needs_object_ptr || static_method) {
    const char *func_decorator = "";
    if (static_method) {
      if (is_class)
        func_decorator = "final class";
      else
        func_decorator = "static";
    } else if (is_class && !weak_self) {
      func_decorator = "final";
    } else {
      func_decorator = "mutating";
    }

    const char *optional_extension =
        weak_self ? "Swift.Optional where Wrapped == " : "";

    // The expression text is inserted into the body of $__lldb_user_expr_%u.
    if (options.GetBindGenericTypes() == lldb::eDontBind) {
      // A Swift program can't have types with non-bound generic type parameters
      // inside a non generic function. For example, the following program would
      // not compile as T is not part of foo's signature.
      //
      // func foo() {
      //   let bar: Baz<T> = ... // Where does T come from?
      //  }
      //
      // LLDB has to circumvent this problem, as the entry-point function for
      // expression evaluation can't be generic. LLDB achieves this by bypassing
      // the Swift typesystem, by:
      // - Setting the type of self in the expression to an opaque pointer type.
      // - Setting up $__lldb_trampoline, which calls the method
      // with the user's code. The purpose of this function is to have a common
      // number of function parameters regardless of the type of self. This
      // function is initially not called anywhere.
      // - Setting up $__lldb_sink, whose signature should match that of
      // $__lldb_trampoline, in number and position of parameters,
      // but which takes in type erased pointers instead (currently only the
      // pointer to self, and the pointer to the metadata). This function is
      // what is initially called by $__lldb_expr.
      // - After generating LLVM IR SwiftExpressionParser uses the sink call to
      // fish out the parameters, and redirect the call to
      // $__lldb_trampoline instead.
      // - SwiftASTManipulator also needs to make sure $__lldb_trampoline and
      // $__lldb_user_expr are generic, it does that by referring to the
      // generic parameters in the tuple argument of $__lldb_arg. This is safe
      // to do because the only purpose of $__lldb_arg is to be used by the
      // materializer to materialize the user's current environment in the lldb
      // expression.
      // FIXME: the current approach always passes in the first metadata
      // pointer, change it to allow as many metadata pointers as necessary be
      // passed in.
      // FIXME: the current approach only evaluates self as generic, make it so
      // every variable in scope can be passed in as generic, adding the
      // variables and generic parameters to the signature as demanded.
      // FIXME: the current approach names the generic parameter "T", use the
      // user's name for the generic parameter, so they can refer to it in
      // their expression.
      auto c = MakeGenericSignaturesAndCalls(local_variables, generic_sig,
                                             needs_object_ptr);
      if (!c) {
        status.SetErrorString(llvm::toString(c.takeError()));
        return status;
      }
      wrapped_stream.Printf(
          R"(
extension %s$__lldb_context {
  @LLDBDebuggerFunction %s
  %s %s {
    %s
  }
}

@LLDBDebuggerFunction %s
%s {
  do {
    $__lldb_injected_self.$__lldb_user_expr(
      $__lldb_arg
    )
  }
}


@LLDBDebuggerFunction %s
%s {
}


@LLDBDebuggerFunction %s
func $__lldb_expr(_ $__lldb_arg : UnsafeMutablePointer<Any>) {
%s
}
)",
          optional_extension, availability.c_str(), func_decorator,
          c->lldb_user_expr.c_str(), wrapped_expr_text.GetData(),
          availability.c_str(), c->lldb_trampoline.c_str(),
          availability.c_str(), c->lldb_sink.c_str(), availability.c_str(),
          c->lldb_call.c_str());

    } else {
      wrapped_stream.Printf(R"(
extension %s$__lldb_context {
  @LLDBDebuggerFunction %s
  %s func $__lldb_user_expr_%u(_ $__lldb_arg : UnsafeMutablePointer<Any>) {
    %s
  }
}
@LLDBDebuggerFunction %s
func $__lldb_expr(_ $__lldb_arg : UnsafeMutablePointer<Any>) {
  do {
    $__lldb_injected_self.$__lldb_user_expr_%u(
      $__lldb_arg
    )
  }
}
)",
                            optional_extension, availability.c_str(),
                            func_decorator, current_counter,
                            wrapped_expr_text.GetData(), availability.c_str(),
                            current_counter);
    }
  } else if (options.GetBindGenericTypes() == lldb::eDontBind) {
    auto c = MakeGenericSignaturesAndCalls(local_variables, generic_sig,
                                           needs_object_ptr);
    if (!c) {
      status.SetErrorString(llvm::toString(c.takeError()));
      return status;
    }
    wrapped_stream.Printf(R"(
@LLDBDebuggerFunction %s  %s {
    %s
}

@LLDBDebuggerFunction %s
%s {}


@LLDBDebuggerFunction %s
func $__lldb_expr(_ $__lldb_arg : UnsafeMutablePointer<Any>) {
  %s
}
)",
                          availability.c_str(), c->lldb_user_expr.c_str(),
                          wrapped_expr_text.GetData(), availability.c_str(),
                          c->lldb_sink.c_str(), availability.c_str(),
                          c->lldb_call.c_str());

  } else {
    wrapped_stream.Printf(
        "@LLDBDebuggerFunction %s\n"
        "func $__lldb_expr(_ $__lldb_arg : UnsafeMutablePointer<Any>) {\n"
        "%s" // This is the expression text (with newlines).
        "}\n",
        availability.c_str(), wrapped_expr_text.GetData());
  }
  return status;
}

/// Format the OS name the way that Swift availability attributes do.
static llvm::StringRef getAvailabilityName(const llvm::Triple &triple) {
    swift::LangOptions lang_options;
  lang_options.setTarget(triple);
  return swift::platformString(swift::targetPlatform(lang_options));
}

uint32_t SwiftExpressionSourceCode::GetNumBodyLines() {
  if (m_num_body_lines == 0)
    // 2 = <one for zero indexing> + <one for the body start marker>
    m_num_body_lines = 2 + std::count(m_body.begin(), m_body.end(), '\n');
  return m_num_body_lines;
}

Status SwiftExpressionSourceCode::GetText(
    std::string &text, SourceLanguage wrapping_language, bool needs_object_ptr,
    bool static_method, bool is_class, bool weak_self,
    const EvaluateExpressionOptions &options,
    const std::optional<SwiftLanguageRuntime::GenericSignature> &generic_sig,
    ExecutionContext &exe_ctx, uint32_t &first_body_line,
    llvm::ArrayRef<SwiftASTManipulator::VariableInfo> local_variables) const {
  Status status;
  Target *target = exe_ctx.GetTargetPtr();
  if (m_wrap) {
    const char *body = m_body.c_str();
    const char *pound_file = options.GetPoundLineFilePath();
    const uint32_t pound_line = options.GetPoundLineLine();
    StreamString pound_body;
    if (pound_file && pound_line) {
      if (wrapping_language.name == llvm::dwarf::DW_LNAME_Swift) {
        pound_body.Printf("#sourceLocation(file: \"%s\", line: %u)\n%s",
                          pound_file, pound_line, body);
      } else {
        pound_body.Printf("#line %u \"%s\"\n%s", pound_line, pound_file, body);
      }
      body = pound_body.GetString().data();
    }

    if (wrapping_language.name != llvm::dwarf::DW_LNAME_Swift) {
      status.SetErrorString("language is not Swift");
      return status;
    }

    StreamString wrap_stream;


    // First construct a tagged form of the user expression so we can find it
    // later:
    std::string tagged_body;
    llvm::SmallString<16> buffer;
    llvm::raw_svector_ostream os_vers(buffer);

    auto arch_spec = target->GetArchitecture();
    auto triple = arch_spec.GetTriple();
    if (triple.isOSDarwin()) {
      if (auto process_sp = exe_ctx.GetProcessSP()) {
        os_vers << getAvailabilityName(triple) << " ";
        auto platform = target->GetPlatform();
        bool is_simulator = platform->GetPluginName().endswith("-simulator");
        if (is_simulator) {
          // The simulators look like the host OS to Process, but Platform
          // can the version out of an environment variable.
          os_vers << platform->GetOSVersion(process_sp.get()).getAsString();
        } else {
          llvm::VersionTuple version = process_sp->GetHostOSVersion();
          os_vers << version.getAsString();
        }
      }
    }

    SwiftPersistentExpressionState *persistent_state =
        llvm::cast<SwiftPersistentExpressionState>(
            target->GetPersistentExpressionStateForLanguage(
                lldb::eLanguageTypeSwift));
    if (!persistent_state) {
      status.SetErrorString("no persistent state");
      return status;
    }
    std::vector<CompilerDecl> persistent_results;
    // Check if we have already declared the playground stub debug functions
    persistent_state->GetSwiftPersistentDecls("__builtin_log_with_id", {},
                                              persistent_results);

    size_t num_persistent_results = persistent_results.size();
    bool need_to_declare_log_functions = num_persistent_results == 0;
    EvaluateExpressionOptions localOptions(options);

    localOptions.SetPreparePlaygroundStubFunctions(
        need_to_declare_log_functions);

    std::string full_body = m_prefix + m_body;
    status = WrapExpression(wrap_stream, full_body.c_str(), needs_object_ptr,
                            static_method, is_class, weak_self, localOptions,
                            os_vers.str(), first_body_line, local_variables,
                            generic_sig);
    if (status.Fail())
      return status;

    text = wrap_stream.GetString().str();
  } else {
    text.append(m_body);
  }

  if (!first_body_line) {
    // If this is not a playground or REPL expression, compute the
    // first line, by locating the marker. While this could be
    // determined statically, it's more future-proof to calculate it
    // here.
    uint32_t start_idx, end_idx;
    if (GetOriginalBodyBounds(text, start_idx, end_idx))
      first_body_line =
          StringRef(text.data(), text.size() - start_idx).count('\n') + 1;
  }
  return status;
}

bool SwiftExpressionSourceCode::GetOriginalBodyBounds(
    std::string transformed_text, uint32_t &start_loc, uint32_t &end_loc) {
  StringRef start_marker = GetUserCodeStartMarker();
  StringRef end_marker = GetUserCodeEndMarker();
  size_t found_loc = transformed_text.find(start_marker);
  if (found_loc == StringRef::npos ||
      found_loc > std::numeric_limits<uint32_t>::max())
    return false;
  start_loc = found_loc;

  start_loc += start_marker.size();
  found_loc = transformed_text.find(end_marker);
  if (found_loc == StringRef::npos ||
      found_loc > std::numeric_limits<uint32_t>::max())
    return false;
  end_loc = found_loc;
  return true;
}