File: SwiftExpressionParser.h

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 (271 lines) | stat: -rw-r--r-- 10,519 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
//===-- SwiftExpressionParser.h ---------------------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#ifndef liblldb_SwiftExpressionParser_h_
#define liblldb_SwiftExpressionParser_h_

#include "Plugins/TypeSystem/Swift/SwiftASTContext.h"
#include "SwiftASTManipulator.h"

#include "Plugins/ExpressionParser/Clang/IRForTarget.h"
#include "SwiftPersistentExpressionState.h"
#include "lldb/Utility/ArchSpec.h"
#include "lldb/Utility/Status.h"
#include "lldb/Expression/ExpressionParser.h"
#include "lldb/Expression/Materializer.h"
#include "lldb/Symbol/SymbolContext.h"
#include "lldb/Target/Target.h"
#include "lldb/lldb-public.h"

#include "swift/SIL/SILDebuggerClient.h"
#include <string>
#include <vector>

namespace lldb_private {

class IRExecutionUnit;
class SwiftLanguageRuntime;
class LLDBNameLookup;
//----------------------------------------------------------------------
/// @class SwiftExpressionParser SwiftExpressionParser.h
/// "lldb/Expression/SwiftExpressionParser.h"
/// @brief Encapsulates an instance of Swift that can parse expressions.
///
/// SwiftExpressionParser is responsible for preparing an instance of
/// ClangExpression for execution.  SwiftExpressionParser uses ClangExpression
/// as a glorified parameter list, performing the required parsing and
/// conversion to formats (DWARF bytecode, or JIT compiled machine code)
/// that can be executed.
//----------------------------------------------------------------------
class SwiftExpressionParser : public ExpressionParser {
public:
  enum class ParseResult {
    success,
    retry_fresh_context, 
    retry_no_bind_generic_params,
    unrecoverable_error
  };
  //------------------------------------------------------------------
  /// Constructor
  ///
  /// Initializes class variabes.
  ///
  /// @param[in] exe_scope,
  ///     If non-NULL, an execution context scope that can help to
  ///     correctly create an expression with a valid process for
  ///     optional tuning Objective-C runtime support. Can be NULL.
  ///
  /// @param[in] expr
  ///     The expression to be parsed.
  ///
  /// @param[in] local_variables
  ///     The local variables that are in scope.
  ///
  /// @param[in] options
  ///     Additional options for the parser.
  //------------------------------------------------------------------
  SwiftExpressionParser(
       ExecutionContextScope *exe_scope,
       SwiftASTContextForExpressions &swift_ast_ctx, Expression &expr,
       llvm::SmallVector<SwiftASTManipulator::VariableInfo> &&local_variables,
       const EvaluateExpressionOptions &options);
  //------------------------------------------------------------------
  /// Attempts to find possible command line completions for the given
  /// expression.
  ///
  /// Currently unimplemented for Swift.
  //------------------------------------------------------------------
  bool Complete(CompletionRequest &request, unsigned line, unsigned pos,
                unsigned typed_pos) override;

  //------------------------------------------------------------------
  /// Parse a single expression and convert it to IR using Swift.  Don't
  /// wrap the expression in anything at all.
  ///
  /// @param[in] diagnostic_manager
  ///     The diagnostic manager to report errors to.
  ///
  /// @return
  ///     The number of errors encountered during parsing.  0 means
  ///     success.
  //------------------------------------------------------------------
  ParseResult Parse(DiagnosticManager &diagnostic_manager,
                    uint32_t first_line = 0, uint32_t last_line = UINT32_MAX);

  /// Returns true if the call to parse of this type is cacheable.
  bool IsParseCacheable() const {
    return m_is_cacheable;
  }

  //------------------------------------------------------------------
  /// Ready an already-parsed expression for execution, possibly
  /// evaluating it statically.
  ///
  /// @param[out] func_addr
  ///     The address to which the function has been written.
  ///
  /// @param[out] func_end
  ///     The end of the function's allocated memory region.  (func_addr
  ///     and func_end do not delimit an allocated region; the allocated
  ///     region may begin before func_addr.)
  ///
  /// @param[in] execution_unit_ap
  ///     After parsing, ownership of the execution unit for
  ///     for the expression is handed to this unique pointer.
  ///
  /// @param[in] exe_ctx
  ///     The execution context to write the function into.
  ///
  /// @param[out] evaluated_statically
  ///     Set to true if the expression could be interpreted statically;
  ///     untouched otherwise.
  ///
  /// @param[out] const_result
  ///     If the result of the expression is constant, and the
  ///     expression has no side effects, this is set to the result of the
  ///     expression.
  ///
  /// @param[in] execution_policy
  ///     Determines whether the expression must be JIT-compiled, must be
  ///     evaluated statically, or whether this decision may be made
  ///     opportunistically.
  ///
  /// @return
  ///     An error code indicating the success or failure of the operation.
  ///     Test with Success().
  //------------------------------------------------------------------
  Status
  PrepareForExecution(lldb::addr_t &func_addr, lldb::addr_t &func_end,
                      lldb::IRExecutionUnitSP &execution_unit_ap,
                      ExecutionContext &exe_ctx, bool &can_interpret,
                      lldb_private::ExecutionPolicy execution_policy) override;

  const EvaluateExpressionOptions &GetOptions() const { return m_options; }

  bool RewriteExpression(DiagnosticManager &diagnostic_manager) override;

  static CompilerType ResolveVariable(
      lldb::VariableSP variable_sp, lldb::StackFrameSP &stack_frame_sp,
      SwiftLanguageRuntime *runtime, lldb::DynamicValueType use_dynamic,
      lldb::BindGenericTypes bind_generic_types);

  static lldb::VariableSP FindSelfVariable(Block *block);

  //------------------------------------------------------------------
  /// Information about each variable provided to the expression, so
  /// that we can generate proper accesses in the SIL.
  //------------------------------------------------------------------
  struct SILVariableInfo {
    CompilerType type;
    uint64_t offset = 0;
    bool needs_init = false;
    bool is_unowned_self = false;

    SILVariableInfo() = default;
    SILVariableInfo(CompilerType t, uint64_t o, bool ni, bool s)
      : type(t), offset(o), needs_init(ni), is_unowned_self(s) {}
  };

  //------------------------------------------------------------------
  /// A container for variables, created during a parse and discarded
  /// when done.
  //------------------------------------------------------------------
  typedef std::map<const char *, SILVariableInfo> SILVariableMap;

private:
  /// This holds the result of ParseAndImport.
  struct ParsedExpression {
    std::unique_ptr<SwiftASTManipulator> code_manipulator;
    swift::ModuleDecl &module;
    LLDBNameLookup &external_lookup;
    swift::SourceFile &source_file;
    std::string main_filename;
    unsigned buffer_id;
  };

  /// Attempt to parse an expression and import all the Swift modules
  /// the expression and its context depend on.
  llvm::Expected<ParsedExpression>
  ParseAndImport(SwiftASTContext::ScopedDiagnostics &expr_diagnostics,
                 SwiftExpressionParser::SILVariableMap &variable_map,
                 unsigned &buffer_id, DiagnosticManager &diagnostic_manager);

  /// Initialize the SwiftASTContext and return the wrapped
  /// ThreadSafeASTContext when successful.
  ThreadSafeASTContext GetASTContext(DiagnosticManager &diagnostic_manager);

  /// The expression to be parsed.
  Expression &m_expr;
  /// The context to use for IR generation.
  std::unique_ptr<llvm::LLVMContext> m_llvm_context;
  /// The module to build IR into.
  std::unique_ptr<llvm::Module> m_module;
  /// The container for the IR, to be JIT-compiled or interpreted.
  lldb::IRExecutionUnitSP m_execution_unit_sp;
  /// The AST context to build the expression into.
  SwiftASTContextForExpressions &m_swift_ast_ctx;
  /// Used to manage the memory of a potential on-off context.
  //lldb::TypeSystemSP m_typesystem_sp;
  /// The symbol context to use when parsing.
  SymbolContext m_sc;
  // The execution context scope of the expression.
  ExecutionContextScope *m_exe_scope;
  /// The stack frame to use (if possible) when determining dynamic
  /// types.
  lldb::StackFrameWP m_stack_frame_wp;

  /// The variables in scope.
  llvm::SmallVector<SwiftASTManipulator::VariableInfo> m_local_variables;

  /// If true, we are running in REPL mode
  EvaluateExpressionOptions m_options;

  /// Indicates whether the call to Parse of this type is cacheable.
  bool m_is_cacheable;

  /// Once token to initialize the swift::ASTContext.
  llvm::once_flag m_ast_init_once_flag;

  /// Indicates if the ThreadSafeASTContext was initialized correctly.
  bool m_ast_init_successful;
};

class LLDBNameLookup : public swift::SILDebuggerClient {
public:
  LLDBNameLookup(swift::SourceFile &source_file,
                 SwiftExpressionParser::SILVariableMap &variable_map,
                 SymbolContext &sc, ExecutionContextScope &exe_scope);

  swift::SILValue emitLValueForVariable(swift::VarDecl *var,
                                        swift::SILBuilder &builder) override;

  SwiftPersistentExpressionState::SwiftDeclMap &GetStagedDecls();

  void RegisterTypeAliases(
      llvm::SmallVectorImpl<swift::TypeAliasDecl *> &type_aliases);

protected:
  Log *m_log;
  swift::SourceFile &m_source_file;
  SwiftExpressionParser::SILVariableMap &m_variable_map;
  SymbolContext m_sc;
  SwiftPersistentExpressionState *m_persistent_vars = nullptr;

  // Subclasses stage globalized decls in this map. They get copied
  // over to the SwiftPersistentVariable store if the parse succeeds.
  SwiftPersistentExpressionState::SwiftDeclMap m_staged_decls;
  llvm::SmallVector<swift::TypeAliasDecl *> m_type_aliases;
};

} // namespace lldb_private

#endif // liblldb_SwiftExpressionParser_h_