9#ifndef LLDB_SOURCE_PLUGINS_SCRIPTINTERPRETER_PYTHON_INTERFACES_SCRIPTEDPYTHONINTERFACE_H
10#define LLDB_SOURCE_PLUGINS_SCRIPTINTERPRETER_PYTHON_INTERFACES_SCRIPTEDPYTHONINTERFACE_H
53 std::variant<std::monostate, InvalidArgumentCountPayload>
payload;
64 return llvm::createStringError(
"scripted Interface has invalid object");
67 PythonObject(PyRefType::Borrowed,
70 if (!py_obj.IsAllocated())
71 return llvm::createStringError(
72 "scripted Interface has invalid python object");
74 PythonObject py_obj_class = py_obj.GetAttributeValue(
"__class__");
75 if (!py_obj_class.IsValid())
76 return llvm::createStringError(
77 "scripted Interface python object is missing '__class__' attribute");
79 PythonObject py_obj_module = py_obj_class.GetAttributeValue(
"__module__");
80 if (!py_obj_module.IsValid())
81 return llvm::createStringError(
82 "scripted Interface python object '__class__' is missing "
83 "'__module__' attribute");
85 PythonString py_obj_module_str = py_obj_module.Str();
86 if (!py_obj_module_str.IsValid())
87 return llvm::createStringError(
88 "scripted Interface python object '__class__.__module__' attribute "
91 llvm::StringRef py_obj_module_str_ref = py_obj_module_str.GetString();
92 PythonModule py_module = PythonModule::AddModule(py_obj_module_str_ref);
93 if (!py_module.IsValid())
94 return llvm::createStringError(
"failed to import '%s' module",
95 py_obj_module_str_ref.data());
97 PythonObject py_module_file = py_module.GetAttributeValue(
"__file__");
98 if (!py_module_file.IsValid())
99 return llvm::createStringError(
100 "module '%s' is missing '__file__' attribute",
101 py_obj_module_str_ref.data());
103 PythonString py_module_file_str = py_module_file.Str();
104 if (!py_module_file_str.IsValid())
105 return llvm::createStringError(
106 "module '%s.__file__' attribute is not a string",
107 py_obj_module_str_ref.data());
109 return FileSpec(py_module_file_str.GetString());
112 llvm::Expected<std::map<llvm::StringLiteral, AbstractMethodCheckerPayload>>
118 std::map<llvm::StringLiteral, AbstractMethodCheckerPayload> checker;
119#define SET_CASE_AND_CONTINUE(method_name, case) \
121 checker[method_name] = {case, {}}; \
127 llvm::StringLiteral method_name = requirement.name;
128 if (!class_dict.
HasKey(method_name))
131 llvm::Expected<PythonObject> callable_or_err =
132 class_dict.
GetItem(method_name);
133 if (!callable_or_err) {
134 llvm::consumeError(callable_or_err.takeError());
139 PythonCallable callable = callable_or_err->AsType<PythonCallable>();
144 if (!requirement.min_arg_count)
147 auto arg_info_or_err = callable.GetArgInfo();
148 if (!arg_info_or_err) {
149 llvm::consumeError(arg_info_or_err.takeError());
154 PythonCallable::ArgInfo arg_info = *arg_info_or_err;
155 if (requirement.min_arg_count <= arg_info.max_positional_args) {
158 checker[method_name] = {
161 requirement.min_arg_count, arg_info.max_positional_args)};
165#undef SET_CASE_AND_CONTINUE
170 template <
typename...
Args>
171 llvm::Expected<StructuredData::GenericSP>
178 auto create_error = [](llvm::StringLiteral format,
auto &&...ts) {
179 return llvm::createStringError(
180 llvm::formatv(format.data(), std::forward<
decltype(ts)>(ts)...)
185 llvm::StringRef class_name = scripted_metadata.
GetClassName();
186 bool has_class_name = !class_name.empty();
187 bool has_interpreter_dict =
188 !(llvm::StringRef(
m_interpreter.GetDictionaryName()).empty());
189 if (!has_class_name && !has_interpreter_dict && !script_obj) {
191 return create_error(
"Missing script class name.");
192 else if (!has_interpreter_dict)
193 return create_error(
"Invalid script interpreter dictionary.");
195 return create_error(
"Missing scripting object.");
201 PythonObject result = {};
204 result = PythonObject(PyRefType::Borrowed,
205 static_cast<PyObject *
>(script_obj->
GetValue()));
210 if (!dict.IsAllocated())
211 return create_error(
"Could not find interpreter dictionary: {0}",
215 PythonObject::ResolveNameWithDictionary<python::PythonCallable>(
217 if (!init.IsAllocated())
218 return create_error(
"Could not find script class: {0}",
221 std::tuple<
Args...> original_args = std::forward_as_tuple(args...);
224 std::string error_string;
225 llvm::Expected<PythonCallable::ArgInfo> arg_info = init.GetArgInfo();
227 llvm::handleAllErrors(
228 arg_info.takeError(),
229 [&](PythonException &E) { error_string.append(E.ReadBacktrace()); },
230 [&](
const llvm::ErrorInfoBase &E) {
231 error_string.append(E.message());
233 return llvm::createStringError(llvm::inconvertibleErrorCode(),
237 llvm::Expected<PythonObject> expected_return_object =
238 create_error(
"Resulting object is not initialized.");
252 size_t num_args =
sizeof...(Args);
253 if (arg_info->max_positional_args != PythonCallable::ArgInfo::UNBOUNDED &&
254 num_args != arg_info->max_positional_args) {
255 if (num_args != arg_info->max_positional_args - 1) {
259 llvm::consumeError(expected_return_object.takeError());
260 return create_error(
"Passed arguments ({0}) doesn't match the number "
261 "of expected arguments ({1}).",
262 num_args, arg_info->max_positional_args);
266 [&init, &expected_return_object](
auto &&...args) {
267 llvm::consumeError(expected_return_object.takeError());
268 expected_return_object = init(args...);
270 std::tuple_cat(transformed_args, std::make_tuple(dict)));
273 [&init, &expected_return_object](
auto &&...args) {
274 llvm::consumeError(expected_return_object.takeError());
275 expected_return_object = init(args...);
280 if (!expected_return_object)
281 return expected_return_object.takeError();
282 result = expected_return_object.get();
285 if (!result.IsValid())
286 return create_error(
"Resulting object is not a valid Python Object.");
287 if (!result.HasAttribute(
"__class__"))
288 return create_error(
"Resulting object doesn't have '__class__' member.");
290 PythonObject obj_class = result.GetAttributeValue(
"__class__");
291 if (!obj_class.IsValid())
292 return create_error(
"Resulting class object is not a valid.");
293 if (!obj_class.HasAttribute(
"__name__"))
295 "Resulting object class doesn't have '__name__' member.");
296 PythonString obj_class_name =
297 obj_class.GetAttributeValue(
"__name__").AsType<PythonString>();
299 PythonObject object_class_mapping_proxy =
300 obj_class.GetAttributeValue(
"__dict__");
301 if (!obj_class.HasAttribute(
"__dict__"))
303 "Resulting object class doesn't have '__dict__' member.");
305 PythonCallable dict_converter = PythonModule::BuiltinsModule()
307 .AsType<PythonCallable>();
308 if (!dict_converter.IsAllocated())
310 "Python 'builtins' module doesn't have 'dict' class.");
312 PythonDictionary object_class_dict =
313 dict_converter(object_class_mapping_proxy).AsType<PythonDictionary>();
314 if (!object_class_dict.IsAllocated())
315 return create_error(
"Coudn't create dictionary from resulting object "
316 "class mapping proxy object.");
320 return checker_or_err.takeError();
322 llvm::Error abstract_method_errors = llvm::Error::success();
323 for (
const auto &method_checker : *checker_or_err)
324 switch (method_checker.second.checker_case) {
326 abstract_method_errors = llvm::joinErrors(
327 std::move(abstract_method_errors),
328 std::move(create_error(
"Abstract method {0}.{1} not implemented.",
329 obj_class_name.GetString(),
330 method_checker.first)));
333 abstract_method_errors = llvm::joinErrors(
334 std::move(abstract_method_errors),
335 std::move(create_error(
"Abstract method {0}.{1} not allocated.",
336 obj_class_name.GetString(),
337 method_checker.first)));
340 abstract_method_errors = llvm::joinErrors(
341 std::move(abstract_method_errors),
342 std::move(create_error(
"Abstract method {0}.{1} not callable.",
343 obj_class_name.GetString(),
344 method_checker.first)));
347 abstract_method_errors = llvm::joinErrors(
348 std::move(abstract_method_errors),
349 std::move(create_error(
350 "Abstract method {0}.{1} has unknown argument count.",
351 obj_class_name.GetString(), method_checker.first)));
354 auto &payload_variant = method_checker.second.payload;
355 if (!std::holds_alternative<
358 abstract_method_errors = llvm::joinErrors(
359 std::move(abstract_method_errors),
360 std::move(create_error(
361 "Abstract method {0}.{1} has unexpected argument count.",
362 obj_class_name.GetString(), method_checker.first)));
364 auto payload = std::get<
367 abstract_method_errors = llvm::joinErrors(
368 std::move(abstract_method_errors),
370 create_error(
"Abstract method {0}.{1} has unexpected "
371 "argument count (expected {2} but has {3}).",
372 obj_class_name.GetString(), method_checker.first,
373 payload.required_argument_count,
374 payload.actual_argument_count)));
378 LLDB_LOG(log,
"Abstract method {0}.{1} implemented & valid.",
379 obj_class_name.GetString(), method_checker.first);
383 if (abstract_method_errors) {
385 LLDB_LOG(log,
"Abstract method error in {0}:\n{1}", class_name,
387 return error.ToError();
391 new StructuredPythonObject(std::move(result)));
414 std::string caller_signature =
415 llvm::Twine(LLVM_PRETTY_FUNCTION + llvm::Twine(
" (") +
416 llvm::Twine(class_name) + llvm::Twine(
".") +
417 llvm::Twine(method_name) + llvm::Twine(
")"))
420 if (class_name.empty())
431 if (!dict.IsAllocated())
434 llvm::formatv(
"could not find interpreter dictionary: {0}",
441 PythonObject::ResolveNameWithDictionary<python::PythonCallable>(
443 if (!class_obj.IsAllocated())
446 llvm::formatv(
"could not find script class: {0}", class_name).str(),
450 if (!class_obj.HasAttribute(method_name))
453 llvm::formatv(
"class {0} does not have method {1}", class_name,
458 PythonCallable method =
459 class_obj.GetAttributeValue(method_name).AsType<PythonCallable>();
460 if (!method.IsAllocated())
462 llvm::formatv(
"method {0}.{1} is not callable",
463 class_name, method_name)
468 std::tuple<
Args...> original_args = std::forward_as_tuple(args...);
472 llvm::Expected<PythonObject> expected_return_object =
473 llvm::createStringError(
"not initialized");
475 [&method, &expected_return_object](
auto &&...args) {
476 llvm::consumeError(expected_return_object.takeError());
477 expected_return_object = method(args...);
481 if (llvm::Error e = expected_return_object.takeError()) {
484 caller_signature,
"python static method could not be called",
error);
487 PythonObject py_return = std::move(expected_return_object.get());
490 if (
sizeof...(
Args) > 0)
494 "couldn't re-assign reference and pointer arguments",
error);
501 template <
typename T = StructuredData::ObjectSP>
511 std::string caller_signature =
512 llvm::Twine(LLVM_PRETTY_FUNCTION + llvm::Twine(
" (") +
513 llvm::Twine(method_name) + llvm::Twine(
")"))
522 PythonObject implementor(PyRefType::Borrowed,
525 if (!implementor.IsAllocated())
528 "python implementor not allocated",
532 std::tuple<
Args...> original_args = std::forward_as_tuple(args...);
535 llvm::Expected<PythonObject> expected_return_object =
536 llvm::createStringError(
"not initialized");
538 [&implementor, &method_name, &expected_return_object](
auto &&...args) {
539 llvm::consumeError(expected_return_object.takeError());
540 expected_return_object =
541 implementor.CallMethod(method_name.data(), args...);
545 if (llvm::Error e = expected_return_object.takeError()) {
548 "python method could not be called",
error);
551 PythonObject py_return = std::move(expected_return_object.get());
557 if (
sizeof...(
Args) > 0)
561 "couldn't re-assign reference and pointer arguments",
error);
563 if (!py_return.IsAllocated())
568 template <
typename...
Args>
598 template <
typename T,
typename = std::enable_if_t<
599 std::is_base_of_v<StructuredData::Object, T>>>
678 for (
const std::string &s : arg)
692 template <
typename T,
typename U>
697 template <
typename T>
707 template <
typename T>
716 original_arg = boolean_arg.
GetValue();
719 "{}: Invalid boolean argument.", LLVM_PRETTY_FUNCTION);
722 template <std::size_t... I,
typename...
Args>
724 std::index_sequence<I...>) {
725 return std::make_tuple(
Transform(std::get<I>(args))...);
730 template <
typename...
Args>
735 template <
typename T,
typename U>
744 template <
typename T,
typename SB>
749 template <std::size_t... I,
typename... Ts,
typename... Us>
751 std::tuple<Us...> &transformed_args,
752 std::index_sequence<I...>) {
754 (
TransformBack(std::get<I>(original_args), std::get<I>(transformed_args),
757 return error.Success();
760 template <
typename... Ts,
typename... Us>
762 std::tuple<Us...> &transformed_args) {
763 if (
sizeof...(Ts) !=
sizeof...(Us))
767 std::make_index_sequence<
sizeof...(Ts)>());
770 template <
typename T,
typename...
Args>
776 template <
typename T>
void FormatArgs(std::string &fmt, T arg)
const {
848std::optional<MemoryRegionInfo>
883std::optional<lldb::ValueType>
893std::vector<std::string>
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
ScriptInterpreterPythonImpl::Locker Locker
#define SET_CASE_AND_CONTINUE(method_name, case)
A command line argument class.
static Ret ErrorWithMessage(llvm::StringRef caller_name, llvm::StringRef error_msg, Status &error, LLDBLog log_category=LLDBLog::Process)
std::optional< ScriptedMetadata > m_scripted_metadata
llvm::SmallVector< llvm::StringLiteral > const GetAbstractMethods() const
virtual llvm::SmallVector< AbstractMethodRequirement > GetAbstractMethodRequirements() const =0
ScriptedInterface()=default
StructuredData::GenericSP m_object_instance_sp
python::ScopedPythonObject< lldb::SBCommandReturnObject > Transform(CommandReturnObject *arg)
python::PythonObject Transform(lldb::StackFrameListSP arg)
python::PythonObject Transform(lldb::ThreadPlanSP arg)
Status GetStatusFromMethod(llvm::StringRef method_name, Args &&...args)
python::PythonObject Transform(lldb::ProcessSP arg)
void TransformBack(T &original_arg, U transformed_arg, Status &error)
ScriptInterpreterPythonImpl & m_interpreter
python::PythonObject Transform(Event *arg)
auto TransformArgs(const std::tuple< Args... > &args)
python::PythonObject Transform(lldb::ExecutionContextRefSP arg)
python::PythonObject Transform(lldb::ThreadSP arg)
llvm::Expected< std::map< llvm::StringLiteral, AbstractMethodCheckerPayload > > CheckAbstractMethodImplementation(const python::PythonDictionary &class_dict) const
python::PythonObject Transform(const StructuredDataImpl &arg)
T ExtractValueFromPythonObject(python::PythonObject &p, Status &error)
~ScriptedPythonInterface() override=default
python::PythonObject Transform(const TypeSummaryOptions &arg)
llvm::Expected< FileSpec > GetScriptedModulePath() override
python::PythonObject Transform(lldb::DescriptionLevel arg)
python::PythonObject Transform(const Status &arg)
python::PythonObject Transform(const SymbolContext &arg)
void ReverseTransform(T &original_arg, python::PythonObject transformed_arg, Status &error)
void FormatArgs(std::string &fmt, T arg, Args... args) const
python::PythonObject Transform(lldb::BreakpointSP arg)
void FormatArgs(std::string &fmt, T arg) const
python::PythonObject Transform(lldb::DebuggerSP arg)
ScriptedPythonInterface(ScriptInterpreterPythonImpl &interpreter)
python::PythonObject Transform(const std::vector< std::string > &arg)
void ReverseTransform(T &original_arg, U transformed_arg, Status &error)
T CallStaticMethod(llvm::StringRef class_name, llvm::StringRef method_name, Status &error, Args &&...args)
Call a static method on a Python class without creating an instance.
void FormatArgs(std::string &fmt) const
T Dispatch(llvm::StringRef method_name, Status &error, Args &&...args)
python::PythonObject Transform(lldb::BreakpointLocationSP arg)
python::PythonObject Transform(std::shared_ptr< T > arg)
bool ReassignPtrsOrRefsArgs(std::tuple< Ts... > &original_args, std::tuple< Us... > &transformed_args)
python::PythonObject Transform(lldb::StreamSP arg)
python::PythonObject Transform(Status &&arg)
python::PythonObject Transform(lldb::DataExtractorSP arg)
python::PythonObject Transform(lldb::StackFrameSP arg)
bool ReassignPtrsOrRefsArgs(std::tuple< Ts... > &original_args, std::tuple< Us... > &transformed_args, std::index_sequence< I... >)
python::PythonObject Transform(lldb::ProcessLaunchInfoSP arg)
llvm::Expected< StructuredData::GenericSP > CreatePluginObject(const ScriptedMetadata &scripted_metadata, StructuredData::Generic *script_obj, Args... args)
python::PythonObject Transform(lldb::TargetSP arg)
void TransformBack(T &original_arg, python::ScopedPythonObject< SB > &transformed_arg, Status &error)
auto TransformTuple(const std::tuple< Args... > &args, std::index_sequence< I... >)
AbstractMethodCheckerCases
void ReverseTransform(bool &original_arg, python::PythonObject transformed_arg, Status &error)
python::PythonObject Transform(lldb::ValueObjectSP arg)
void ReverseTransform(const T &original_arg, python::PythonObject transformed_arg, Status &error)
python::PythonObject Transform(lldb::ProcessAttachInfoSP arg)
python::PythonObject Transform(bool arg)
Status Clone() const
Don't call this function in new code.
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
std::shared_ptr< Generic > GenericSP
std::shared_ptr< Dictionary > DictionarySP
std::shared_ptr< Object > ObjectSP
std::shared_ptr< Array > ArraySP
Defines a symbol context baton that can be handed other debug core functions.
llvm::Expected< PythonObject > GetItem(const PythonObject &key) const
bool HasKey(const llvm::Twine &key) const
void AppendItem(const PythonObject &object)
StructuredData::ObjectSP CreateStructuredObject() const
static PythonObject ToSWIGWrapper(std::unique_ptr< lldb::SBValue > value_sb)
A class that automatically clears an SB object when it goes out of scope.
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
std::shared_ptr< lldb_private::ThreadPlan > ThreadPlanSP
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
std::shared_ptr< lldb_private::BreakpointLocation > BreakpointLocationSP
DescriptionLevel
Description levels for "void GetDescription(Stream *, DescriptionLevel)" calls.
std::shared_ptr< lldb_private::Thread > ThreadSP
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
std::shared_ptr< lldb_private::ProcessAttachInfo > ProcessAttachInfoSP
std::shared_ptr< lldb_private::Stream > StreamSP
std::shared_ptr< lldb_private::Breakpoint > BreakpointSP
std::shared_ptr< lldb_private::Process > ProcessSP
std::shared_ptr< lldb_private::ValueObjectList > ValueObjectListSP
std::shared_ptr< lldb_private::Debugger > DebuggerSP
std::shared_ptr< lldb_private::Target > TargetSP
std::shared_ptr< lldb_private::DataExtractor > DataExtractorSP
std::shared_ptr< lldb_private::ProcessLaunchInfo > ProcessLaunchInfoSP
std::shared_ptr< lldb_private::StackFrameList > StackFrameListSP
std::shared_ptr< lldb_private::ExecutionContextRef > ExecutionContextRefSP
InvalidArgumentCountPayload(size_t required, size_t actual)
size_t actual_argument_count
size_t required_argument_count
std::variant< std::monostate, InvalidArgumentCountPayload > payload
AbstractMethodCheckerCases checker_case