180814287SRaphael Isemann //===-- CommandCompletions.cpp --------------------------------------------===//
2c9af18a5SGreg Clayton //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6c9af18a5SGreg Clayton //
7c9af18a5SGreg Clayton //===----------------------------------------------------------------------===//
8c9af18a5SGreg Clayton 
9c8ecc2a9SEugene Zelenko #include "llvm/ADT/SmallString.h"
102cc5a18dSZachary Turner #include "llvm/ADT/StringSet.h"
11c8ecc2a9SEugene Zelenko 
129b62fd2fSGreg Clayton #include "lldb/Core/FileSpecList.h"
131f746071SGreg Clayton #include "lldb/Core/Module.h"
14190fadcdSZachary Turner #include "lldb/Core/PluginManager.h"
15190fadcdSZachary Turner #include "lldb/Host/FileSystem.h"
169b62fd2fSGreg Clayton #include "lldb/Interpreter/CommandCompletions.h"
179b62fd2fSGreg Clayton #include "lldb/Interpreter/CommandInterpreter.h"
18633a29cfSZachary Turner #include "lldb/Interpreter/OptionValueProperties.h"
191f746071SGreg Clayton #include "lldb/Symbol/CompileUnit.h"
20f21feadcSGreg Clayton #include "lldb/Symbol/Variable.h"
21a14f4a75SGongyu Deng #include "lldb/Target/RegisterContext.h"
225713a05bSZachary Turner #include "lldb/Utility/FileSpec.h"
232f3df613SZachary Turner #include "lldb/Utility/StreamString.h"
242cc5a18dSZachary Turner #include "lldb/Utility/TildeExpressionResolver.h"
25c9af18a5SGreg Clayton 
267d86ee5aSZachary Turner #include "llvm/Support/FileSystem.h"
272cc5a18dSZachary Turner #include "llvm/Support/Path.h"
28190fadcdSZachary Turner 
29c9af18a5SGreg Clayton using namespace lldb_private;
30c9af18a5SGreg Clayton 
31440460f1SRaphael Isemann // This is the command completion callback that is used to complete the
32440460f1SRaphael Isemann // argument of the option it is bound to (in the OptionDefinition table
33440460f1SRaphael Isemann // below).
34440460f1SRaphael Isemann typedef void (*CompletionCallback)(CommandInterpreter &interpreter,
35440460f1SRaphael Isemann                                    CompletionRequest &request,
36440460f1SRaphael Isemann                                    // A search filter to limit the search...
37440460f1SRaphael Isemann                                    lldb_private::SearchFilter *searcher);
38440460f1SRaphael Isemann 
39440460f1SRaphael Isemann struct CommonCompletionElement {
40440460f1SRaphael Isemann   uint32_t type;
41440460f1SRaphael Isemann   CompletionCallback callback;
42440460f1SRaphael Isemann };
43440460f1SRaphael Isemann 
44440460f1SRaphael Isemann bool CommandCompletions::InvokeCommonCompletionCallbacks(
45440460f1SRaphael Isemann     CommandInterpreter &interpreter, uint32_t completion_mask,
46440460f1SRaphael Isemann     CompletionRequest &request, SearchFilter *searcher) {
47440460f1SRaphael Isemann   bool handled = false;
48440460f1SRaphael Isemann 
49440460f1SRaphael Isemann   const CommonCompletionElement common_completions[] = {
50c9af18a5SGreg Clayton       {eSourceFileCompletion, CommandCompletions::SourceFiles},
51558ce124SJim Ingham       {eDiskFileCompletion, CommandCompletions::DiskFiles},
52558ce124SJim Ingham       {eDiskDirectoryCompletion, CommandCompletions::DiskDirectories},
53c9af18a5SGreg Clayton       {eSymbolCompletion, CommandCompletions::Symbols},
54c9af18a5SGreg Clayton       {eModuleCompletion, CommandCompletions::Modules},
553df9a8dfSCaroline Tice       {eSettingsNameCompletion, CommandCompletions::SettingsNames},
56ab65b34fSGreg Clayton       {ePlatformPluginCompletion, CommandCompletions::PlatformPluginNames},
57ab65b34fSGreg Clayton       {eArchitectureCompletion, CommandCompletions::ArchitectureNames},
58f21feadcSGreg Clayton       {eVariablePathCompletion, CommandCompletions::VariablePath},
59a14f4a75SGongyu Deng       {eRegisterCompletion, CommandCompletions::Registers},
60*0e50b9a4SGongyu Deng       {eBreakpointCompletion, CommandCompletions::Breakpoints},
61c8ecc2a9SEugene Zelenko       {eNoCompletion, nullptr} // This one has to be last in the list.
62c9af18a5SGreg Clayton   };
63c9af18a5SGreg Clayton 
64b9c1b51eSKate Stone   for (int i = 0;; i++) {
65440460f1SRaphael Isemann     if (common_completions[i].type == eNoCompletion)
66c9af18a5SGreg Clayton       break;
67440460f1SRaphael Isemann     else if ((common_completions[i].type & completion_mask) ==
68440460f1SRaphael Isemann                  common_completions[i].type &&
69440460f1SRaphael Isemann              common_completions[i].callback != nullptr) {
70c9af18a5SGreg Clayton       handled = true;
71440460f1SRaphael Isemann       common_completions[i].callback(interpreter, request, searcher);
72c9af18a5SGreg Clayton     }
73c9af18a5SGreg Clayton   }
74c9af18a5SGreg Clayton   return handled;
75c9af18a5SGreg Clayton }
76c9af18a5SGreg Clayton 
77572fc897SRaphael Isemann namespace {
78572fc897SRaphael Isemann // The Completer class is a convenient base class for building searchers that
79572fc897SRaphael Isemann // go along with the SearchFilter passed to the standard Completer functions.
80572fc897SRaphael Isemann class Completer : public Searcher {
81572fc897SRaphael Isemann public:
82572fc897SRaphael Isemann   Completer(CommandInterpreter &interpreter, CompletionRequest &request)
83572fc897SRaphael Isemann       : m_interpreter(interpreter), m_request(request) {}
84572fc897SRaphael Isemann 
85572fc897SRaphael Isemann   ~Completer() override = default;
86572fc897SRaphael Isemann 
87572fc897SRaphael Isemann   CallbackReturn SearchCallback(SearchFilter &filter, SymbolContext &context,
88572fc897SRaphael Isemann                                 Address *addr) override = 0;
89572fc897SRaphael Isemann 
90572fc897SRaphael Isemann   lldb::SearchDepth GetDepth() override = 0;
91572fc897SRaphael Isemann 
92572fc897SRaphael Isemann   virtual void DoCompletion(SearchFilter *filter) = 0;
93572fc897SRaphael Isemann 
94572fc897SRaphael Isemann protected:
95572fc897SRaphael Isemann   CommandInterpreter &m_interpreter;
96572fc897SRaphael Isemann   CompletionRequest &m_request;
97572fc897SRaphael Isemann 
98572fc897SRaphael Isemann private:
99572fc897SRaphael Isemann   DISALLOW_COPY_AND_ASSIGN(Completer);
100572fc897SRaphael Isemann };
101572fc897SRaphael Isemann } // namespace
102572fc897SRaphael Isemann 
103572fc897SRaphael Isemann // SourceFileCompleter implements the source file completer
104572fc897SRaphael Isemann namespace {
105572fc897SRaphael Isemann class SourceFileCompleter : public Completer {
106572fc897SRaphael Isemann public:
107572fc897SRaphael Isemann   SourceFileCompleter(CommandInterpreter &interpreter,
108572fc897SRaphael Isemann                       CompletionRequest &request)
109572fc897SRaphael Isemann       : Completer(interpreter, request), m_matching_files() {
110572fc897SRaphael Isemann     FileSpec partial_spec(m_request.GetCursorArgumentPrefix());
111572fc897SRaphael Isemann     m_file_name = partial_spec.GetFilename().GetCString();
112572fc897SRaphael Isemann     m_dir_name = partial_spec.GetDirectory().GetCString();
113572fc897SRaphael Isemann   }
114572fc897SRaphael Isemann 
115572fc897SRaphael Isemann   lldb::SearchDepth GetDepth() override { return lldb::eSearchDepthCompUnit; }
116572fc897SRaphael Isemann 
117572fc897SRaphael Isemann   Searcher::CallbackReturn SearchCallback(SearchFilter &filter,
118572fc897SRaphael Isemann                                           SymbolContext &context,
119572fc897SRaphael Isemann                                           Address *addr) override {
120572fc897SRaphael Isemann     if (context.comp_unit != nullptr) {
121572fc897SRaphael Isemann       const char *cur_file_name =
122572fc897SRaphael Isemann           context.comp_unit->GetPrimaryFile().GetFilename().GetCString();
123572fc897SRaphael Isemann       const char *cur_dir_name =
124572fc897SRaphael Isemann           context.comp_unit->GetPrimaryFile().GetDirectory().GetCString();
125572fc897SRaphael Isemann 
126572fc897SRaphael Isemann       bool match = false;
127572fc897SRaphael Isemann       if (m_file_name && cur_file_name &&
128572fc897SRaphael Isemann           strstr(cur_file_name, m_file_name) == cur_file_name)
129572fc897SRaphael Isemann         match = true;
130572fc897SRaphael Isemann 
131572fc897SRaphael Isemann       if (match && m_dir_name && cur_dir_name &&
132572fc897SRaphael Isemann           strstr(cur_dir_name, m_dir_name) != cur_dir_name)
133572fc897SRaphael Isemann         match = false;
134572fc897SRaphael Isemann 
135572fc897SRaphael Isemann       if (match) {
136572fc897SRaphael Isemann         m_matching_files.AppendIfUnique(context.comp_unit->GetPrimaryFile());
137572fc897SRaphael Isemann       }
138572fc897SRaphael Isemann     }
139572fc897SRaphael Isemann     return Searcher::eCallbackReturnContinue;
140572fc897SRaphael Isemann   }
141572fc897SRaphael Isemann 
142572fc897SRaphael Isemann   void DoCompletion(SearchFilter *filter) override {
143572fc897SRaphael Isemann     filter->Search(*this);
144572fc897SRaphael Isemann     // Now convert the filelist to completions:
145572fc897SRaphael Isemann     for (size_t i = 0; i < m_matching_files.GetSize(); i++) {
146572fc897SRaphael Isemann       m_request.AddCompletion(
147572fc897SRaphael Isemann           m_matching_files.GetFileSpecAtIndex(i).GetFilename().GetCString());
148572fc897SRaphael Isemann     }
149572fc897SRaphael Isemann   }
150572fc897SRaphael Isemann 
151572fc897SRaphael Isemann private:
152572fc897SRaphael Isemann   FileSpecList m_matching_files;
153572fc897SRaphael Isemann   const char *m_file_name;
154572fc897SRaphael Isemann   const char *m_dir_name;
155572fc897SRaphael Isemann 
156572fc897SRaphael Isemann   DISALLOW_COPY_AND_ASSIGN(SourceFileCompleter);
157572fc897SRaphael Isemann };
158572fc897SRaphael Isemann } // namespace
159572fc897SRaphael Isemann 
160572fc897SRaphael Isemann static bool regex_chars(const char comp) {
161572fc897SRaphael Isemann   return llvm::StringRef("[](){}+.*|^$\\?").contains(comp);
162572fc897SRaphael Isemann }
163572fc897SRaphael Isemann 
164572fc897SRaphael Isemann namespace {
165572fc897SRaphael Isemann class SymbolCompleter : public Completer {
166572fc897SRaphael Isemann 
167572fc897SRaphael Isemann public:
168572fc897SRaphael Isemann   SymbolCompleter(CommandInterpreter &interpreter, CompletionRequest &request)
169572fc897SRaphael Isemann       : Completer(interpreter, request) {
170572fc897SRaphael Isemann     std::string regex_str;
171572fc897SRaphael Isemann     if (!m_request.GetCursorArgumentPrefix().empty()) {
172572fc897SRaphael Isemann       regex_str.append("^");
173572fc897SRaphael Isemann       regex_str.append(std::string(m_request.GetCursorArgumentPrefix()));
174572fc897SRaphael Isemann     } else {
175572fc897SRaphael Isemann       // Match anything since the completion string is empty
176572fc897SRaphael Isemann       regex_str.append(".");
177572fc897SRaphael Isemann     }
178572fc897SRaphael Isemann     std::string::iterator pos =
179572fc897SRaphael Isemann         find_if(regex_str.begin() + 1, regex_str.end(), regex_chars);
180572fc897SRaphael Isemann     while (pos < regex_str.end()) {
181572fc897SRaphael Isemann       pos = regex_str.insert(pos, '\\');
182572fc897SRaphael Isemann       pos = find_if(pos + 2, regex_str.end(), regex_chars);
183572fc897SRaphael Isemann     }
184572fc897SRaphael Isemann     m_regex = RegularExpression(regex_str);
185572fc897SRaphael Isemann   }
186572fc897SRaphael Isemann 
187572fc897SRaphael Isemann   lldb::SearchDepth GetDepth() override { return lldb::eSearchDepthModule; }
188572fc897SRaphael Isemann 
189572fc897SRaphael Isemann   Searcher::CallbackReturn SearchCallback(SearchFilter &filter,
190572fc897SRaphael Isemann                                           SymbolContext &context,
191572fc897SRaphael Isemann                                           Address *addr) override {
192572fc897SRaphael Isemann     if (context.module_sp) {
193572fc897SRaphael Isemann       SymbolContextList sc_list;
194572fc897SRaphael Isemann       const bool include_symbols = true;
195572fc897SRaphael Isemann       const bool include_inlines = true;
196572fc897SRaphael Isemann       context.module_sp->FindFunctions(m_regex, include_symbols,
197572fc897SRaphael Isemann                                        include_inlines, sc_list);
198572fc897SRaphael Isemann 
199572fc897SRaphael Isemann       SymbolContext sc;
200572fc897SRaphael Isemann       // Now add the functions & symbols to the list - only add if unique:
201572fc897SRaphael Isemann       for (uint32_t i = 0; i < sc_list.GetSize(); i++) {
202572fc897SRaphael Isemann         if (sc_list.GetContextAtIndex(i, sc)) {
203572fc897SRaphael Isemann           ConstString func_name = sc.GetFunctionName(Mangled::ePreferDemangled);
204572fc897SRaphael Isemann           // Ensure that the function name matches the regex. This is more than
205572fc897SRaphael Isemann           // a sanity check. It is possible that the demangled function name
206572fc897SRaphael Isemann           // does not start with the prefix, for example when it's in an
207572fc897SRaphael Isemann           // anonymous namespace.
208572fc897SRaphael Isemann           if (!func_name.IsEmpty() && m_regex.Execute(func_name.GetStringRef()))
209572fc897SRaphael Isemann             m_match_set.insert(func_name);
210572fc897SRaphael Isemann         }
211572fc897SRaphael Isemann       }
212572fc897SRaphael Isemann     }
213572fc897SRaphael Isemann     return Searcher::eCallbackReturnContinue;
214572fc897SRaphael Isemann   }
215572fc897SRaphael Isemann 
216572fc897SRaphael Isemann   void DoCompletion(SearchFilter *filter) override {
217572fc897SRaphael Isemann     filter->Search(*this);
218572fc897SRaphael Isemann     collection::iterator pos = m_match_set.begin(), end = m_match_set.end();
219572fc897SRaphael Isemann     for (pos = m_match_set.begin(); pos != end; pos++)
220572fc897SRaphael Isemann       m_request.AddCompletion((*pos).GetCString());
221572fc897SRaphael Isemann   }
222572fc897SRaphael Isemann 
223572fc897SRaphael Isemann private:
224572fc897SRaphael Isemann   RegularExpression m_regex;
225572fc897SRaphael Isemann   typedef std::set<ConstString> collection;
226572fc897SRaphael Isemann   collection m_match_set;
227572fc897SRaphael Isemann 
228572fc897SRaphael Isemann   DISALLOW_COPY_AND_ASSIGN(SymbolCompleter);
229572fc897SRaphael Isemann };
230572fc897SRaphael Isemann } // namespace
231572fc897SRaphael Isemann 
232572fc897SRaphael Isemann namespace {
233572fc897SRaphael Isemann class ModuleCompleter : public Completer {
234572fc897SRaphael Isemann public:
235572fc897SRaphael Isemann   ModuleCompleter(CommandInterpreter &interpreter, CompletionRequest &request)
236572fc897SRaphael Isemann       : Completer(interpreter, request) {
237572fc897SRaphael Isemann     FileSpec partial_spec(m_request.GetCursorArgumentPrefix());
238572fc897SRaphael Isemann     m_file_name = partial_spec.GetFilename().GetCString();
239572fc897SRaphael Isemann     m_dir_name = partial_spec.GetDirectory().GetCString();
240572fc897SRaphael Isemann   }
241572fc897SRaphael Isemann 
242572fc897SRaphael Isemann   lldb::SearchDepth GetDepth() override { return lldb::eSearchDepthModule; }
243572fc897SRaphael Isemann 
244572fc897SRaphael Isemann   Searcher::CallbackReturn SearchCallback(SearchFilter &filter,
245572fc897SRaphael Isemann                                           SymbolContext &context,
246572fc897SRaphael Isemann                                           Address *addr) override {
247572fc897SRaphael Isemann     if (context.module_sp) {
248572fc897SRaphael Isemann       const char *cur_file_name =
249572fc897SRaphael Isemann           context.module_sp->GetFileSpec().GetFilename().GetCString();
250572fc897SRaphael Isemann       const char *cur_dir_name =
251572fc897SRaphael Isemann           context.module_sp->GetFileSpec().GetDirectory().GetCString();
252572fc897SRaphael Isemann 
253572fc897SRaphael Isemann       bool match = false;
254572fc897SRaphael Isemann       if (m_file_name && cur_file_name &&
255572fc897SRaphael Isemann           strstr(cur_file_name, m_file_name) == cur_file_name)
256572fc897SRaphael Isemann         match = true;
257572fc897SRaphael Isemann 
258572fc897SRaphael Isemann       if (match && m_dir_name && cur_dir_name &&
259572fc897SRaphael Isemann           strstr(cur_dir_name, m_dir_name) != cur_dir_name)
260572fc897SRaphael Isemann         match = false;
261572fc897SRaphael Isemann 
262572fc897SRaphael Isemann       if (match) {
263572fc897SRaphael Isemann         m_request.AddCompletion(cur_file_name);
264572fc897SRaphael Isemann       }
265572fc897SRaphael Isemann     }
266572fc897SRaphael Isemann     return Searcher::eCallbackReturnContinue;
267572fc897SRaphael Isemann   }
268572fc897SRaphael Isemann 
269572fc897SRaphael Isemann   void DoCompletion(SearchFilter *filter) override { filter->Search(*this); }
270572fc897SRaphael Isemann 
271572fc897SRaphael Isemann private:
272572fc897SRaphael Isemann   const char *m_file_name;
273572fc897SRaphael Isemann   const char *m_dir_name;
274572fc897SRaphael Isemann 
275572fc897SRaphael Isemann   DISALLOW_COPY_AND_ASSIGN(ModuleCompleter);
276572fc897SRaphael Isemann };
277572fc897SRaphael Isemann } // namespace
278572fc897SRaphael Isemann 
279ae34ed2cSRaphael Isemann void CommandCompletions::SourceFiles(CommandInterpreter &interpreter,
280a2e76c0bSRaphael Isemann                                      CompletionRequest &request,
281a2e76c0bSRaphael Isemann                                      SearchFilter *searcher) {
28262174682SRaphael Isemann   SourceFileCompleter completer(interpreter, request);
283c9af18a5SGreg Clayton 
284b9c1b51eSKate Stone   if (searcher == nullptr) {
2852976d00aSJim Ingham     lldb::TargetSP target_sp = interpreter.GetDebugger().GetSelectedTarget();
28633df7cd3SJim Ingham     SearchFilterForUnconstrainedSearches null_searcher(target_sp);
287c9af18a5SGreg Clayton     completer.DoCompletion(&null_searcher);
288b9c1b51eSKate Stone   } else {
289c9af18a5SGreg Clayton     completer.DoCompletion(searcher);
290c9af18a5SGreg Clayton   }
291c9af18a5SGreg Clayton }
292c9af18a5SGreg Clayton 
293ae34ed2cSRaphael Isemann static void DiskFilesOrDirectories(const llvm::Twine &partial_name,
2945edee822SRaphael Isemann                                    bool only_directories,
2955edee822SRaphael Isemann                                    CompletionRequest &request,
2962cc5a18dSZachary Turner                                    TildeExpressionResolver &Resolver) {
2972cc5a18dSZachary Turner   llvm::SmallString<256> CompletionBuffer;
2982cc5a18dSZachary Turner   llvm::SmallString<256> Storage;
2992cc5a18dSZachary Turner   partial_name.toVector(CompletionBuffer);
300b2f1fb29SVirgile Bello 
3012cc5a18dSZachary Turner   if (CompletionBuffer.size() >= PATH_MAX)
302ae34ed2cSRaphael Isemann     return;
303b2f1fb29SVirgile Bello 
3042cc5a18dSZachary Turner   namespace path = llvm::sys::path;
305b2f1fb29SVirgile Bello 
3062cc5a18dSZachary Turner   llvm::StringRef SearchDir;
3072cc5a18dSZachary Turner   llvm::StringRef PartialItem;
3082cc5a18dSZachary Turner 
3092cc5a18dSZachary Turner   if (CompletionBuffer.startswith("~")) {
3102cc5a18dSZachary Turner     llvm::StringRef Buffer(CompletionBuffer);
3115c5091fcSZachary Turner     size_t FirstSep =
3125c5091fcSZachary Turner         Buffer.find_if([](char c) { return path::is_separator(c); });
3132cc5a18dSZachary Turner 
3142cc5a18dSZachary Turner     llvm::StringRef Username = Buffer.take_front(FirstSep);
3152cc5a18dSZachary Turner     llvm::StringRef Remainder;
3162cc5a18dSZachary Turner     if (FirstSep != llvm::StringRef::npos)
3172cc5a18dSZachary Turner       Remainder = Buffer.drop_front(FirstSep + 1);
3182cc5a18dSZachary Turner 
319b3f44ad9SStella Stamenova     llvm::SmallString<256> Resolved;
3202cc5a18dSZachary Turner     if (!Resolver.ResolveExact(Username, Resolved)) {
3212cc5a18dSZachary Turner       // We couldn't resolve it as a full username.  If there were no slashes
3222cc5a18dSZachary Turner       // then this might be a partial username.   We try to resolve it as such
3232cc5a18dSZachary Turner       // but after that, we're done regardless of any matches.
3242cc5a18dSZachary Turner       if (FirstSep == llvm::StringRef::npos) {
3252cc5a18dSZachary Turner         llvm::StringSet<> MatchSet;
326a2e76c0bSRaphael Isemann         Resolver.ResolvePartial(Username, MatchSet);
3272cc5a18dSZachary Turner         for (const auto &S : MatchSet) {
3282cc5a18dSZachary Turner           Resolved = S.getKey();
3292cc5a18dSZachary Turner           path::append(Resolved, path::get_separator());
3305edee822SRaphael Isemann           request.AddCompletion(Resolved, "", CompletionMode::Partial);
331b2f1fb29SVirgile Bello         }
332b2f1fb29SVirgile Bello       }
333ae34ed2cSRaphael Isemann       return;
3342cc5a18dSZachary Turner     }
3350734e6a5SZachary Turner 
33605097246SAdrian Prantl     // If there was no trailing slash, then we're done as soon as we resolve
33705097246SAdrian Prantl     // the expression to the correct directory.  Otherwise we need to continue
3382cc5a18dSZachary Turner     // looking for matches within that directory.
3392cc5a18dSZachary Turner     if (FirstSep == llvm::StringRef::npos) {
3402cc5a18dSZachary Turner       // Make sure it ends with a separator.
3412cc5a18dSZachary Turner       path::append(CompletionBuffer, path::get_separator());
3425edee822SRaphael Isemann       request.AddCompletion(CompletionBuffer, "", CompletionMode::Partial);
343ae34ed2cSRaphael Isemann       return;
3442cc5a18dSZachary Turner     }
3452cc5a18dSZachary Turner 
3462cc5a18dSZachary Turner     // We want to keep the form the user typed, so we special case this to
3472cc5a18dSZachary Turner     // search in the fully resolved directory, but CompletionBuffer keeps the
3482cc5a18dSZachary Turner     // unmodified form that the user typed.
3492cc5a18dSZachary Turner     Storage = Resolved;
35088ec2e4eSPavel Labath     llvm::StringRef RemainderDir = path::parent_path(Remainder);
3514621e0b0SRaphael Isemann     if (!RemainderDir.empty()) {
3524621e0b0SRaphael Isemann       // Append the remaining path to the resolved directory.
3534621e0b0SRaphael Isemann       Storage.append(path::get_separator());
3544621e0b0SRaphael Isemann       Storage.append(RemainderDir);
3554621e0b0SRaphael Isemann     }
35617843885SRaphael Isemann     SearchDir = Storage;
3570734e6a5SZachary Turner   } else {
3582cc5a18dSZachary Turner     SearchDir = path::parent_path(CompletionBuffer);
3592cc5a18dSZachary Turner   }
3602cc5a18dSZachary Turner 
3612cc5a18dSZachary Turner   size_t FullPrefixLen = CompletionBuffer.size();
3622cc5a18dSZachary Turner 
3632cc5a18dSZachary Turner   PartialItem = path::filename(CompletionBuffer);
36478a10a7aSFrederic Riss 
36578a10a7aSFrederic Riss   // path::filename() will return "." when the passed path ends with a
36678a10a7aSFrederic Riss   // directory separator. We have to filter those out, but only when the
36778a10a7aSFrederic Riss   // "." doesn't come from the completion request itself.
36878a10a7aSFrederic Riss   if (PartialItem == "." && path::is_separator(CompletionBuffer.back()))
3692cc5a18dSZachary Turner     PartialItem = llvm::StringRef();
3702cc5a18dSZachary Turner 
371426d1379SZachary Turner   if (SearchDir.empty()) {
372426d1379SZachary Turner     llvm::sys::fs::current_path(Storage);
373426d1379SZachary Turner     SearchDir = Storage;
374426d1379SZachary Turner   }
3752cc5a18dSZachary Turner   assert(!PartialItem.contains(path::get_separator()));
3762cc5a18dSZachary Turner 
3772cc5a18dSZachary Turner   // SearchDir now contains the directory to search in, and Prefix contains the
3782cc5a18dSZachary Turner   // text we want to match against items in that directory.
3792cc5a18dSZachary Turner 
380edaf2bccSJonas Devlieghere   FileSystem &fs = FileSystem::Instance();
3812cc5a18dSZachary Turner   std::error_code EC;
382edaf2bccSJonas Devlieghere   llvm::vfs::directory_iterator Iter = fs.DirBegin(SearchDir, EC);
383edaf2bccSJonas Devlieghere   llvm::vfs::directory_iterator End;
3842cc5a18dSZachary Turner   for (; Iter != End && !EC; Iter.increment(EC)) {
3852cc5a18dSZachary Turner     auto &Entry = *Iter;
386edaf2bccSJonas Devlieghere     llvm::ErrorOr<llvm::vfs::Status> Status = fs.GetStatus(Entry.path());
387edaf2bccSJonas Devlieghere 
388edaf2bccSJonas Devlieghere     if (!Status)
389edaf2bccSJonas Devlieghere       continue;
3902cc5a18dSZachary Turner 
3912cc5a18dSZachary Turner     auto Name = path::filename(Entry.path());
3922cc5a18dSZachary Turner 
3932cc5a18dSZachary Turner     // Omit ".", ".."
3942cc5a18dSZachary Turner     if (Name == "." || Name == ".." || !Name.startswith(PartialItem))
3952cc5a18dSZachary Turner       continue;
3962cc5a18dSZachary Turner 
397edaf2bccSJonas Devlieghere     bool is_dir = Status->isDirectory();
3982cc5a18dSZachary Turner 
3992cc5a18dSZachary Turner     // If it's a symlink, then we treat it as a directory as long as the target
4002cc5a18dSZachary Turner     // is a directory.
401edaf2bccSJonas Devlieghere     if (Status->isSymlink()) {
402edaf2bccSJonas Devlieghere       FileSpec symlink_filespec(Entry.path());
403edaf2bccSJonas Devlieghere       FileSpec resolved_filespec;
404edaf2bccSJonas Devlieghere       auto error = fs.ResolveSymbolicLink(symlink_filespec, resolved_filespec);
405edaf2bccSJonas Devlieghere       if (error.Success())
406edaf2bccSJonas Devlieghere         is_dir = fs.IsDirectory(symlink_filespec);
4072cc5a18dSZachary Turner     }
408edaf2bccSJonas Devlieghere 
4092cc5a18dSZachary Turner     if (only_directories && !is_dir)
4102cc5a18dSZachary Turner       continue;
4112cc5a18dSZachary Turner 
4122cc5a18dSZachary Turner     // Shrink it back down so that it just has the original prefix the user
4132cc5a18dSZachary Turner     // typed and remove the part of the name which is common to the located
4142cc5a18dSZachary Turner     // item and what the user typed.
4152cc5a18dSZachary Turner     CompletionBuffer.resize(FullPrefixLen);
4162cc5a18dSZachary Turner     Name = Name.drop_front(PartialItem.size());
4172cc5a18dSZachary Turner     CompletionBuffer.append(Name);
4182cc5a18dSZachary Turner 
4192cc5a18dSZachary Turner     if (is_dir) {
4202cc5a18dSZachary Turner       path::append(CompletionBuffer, path::get_separator());
4210734e6a5SZachary Turner     }
4220734e6a5SZachary Turner 
4235edee822SRaphael Isemann     CompletionMode mode =
4245edee822SRaphael Isemann         is_dir ? CompletionMode::Partial : CompletionMode::Normal;
4255edee822SRaphael Isemann     request.AddCompletion(CompletionBuffer, "", mode);
426d5bd3a1eSZachary Turner   }
427558ce124SJim Ingham }
428558ce124SJim Ingham 
4295edee822SRaphael Isemann static void DiskFilesOrDirectories(const llvm::Twine &partial_name,
4305edee822SRaphael Isemann                                    bool only_directories, StringList &matches,
4315edee822SRaphael Isemann                                    TildeExpressionResolver &Resolver) {
4325edee822SRaphael Isemann   CompletionResult result;
4335edee822SRaphael Isemann   std::string partial_name_str = partial_name.str();
4345edee822SRaphael Isemann   CompletionRequest request(partial_name_str, partial_name_str.size(), result);
4355edee822SRaphael Isemann   DiskFilesOrDirectories(partial_name, only_directories, request, Resolver);
4365edee822SRaphael Isemann   result.GetMatches(matches);
4375edee822SRaphael Isemann }
4385edee822SRaphael Isemann 
439ae34ed2cSRaphael Isemann static void DiskFilesOrDirectories(CompletionRequest &request,
4401a6d7ab5SRaphael Isemann                                    bool only_directories) {
44172787ac6SJonas Devlieghere   StandardTildeExpressionResolver resolver;
4421a6d7ab5SRaphael Isemann   DiskFilesOrDirectories(request.GetCursorArgumentPrefix(), only_directories,
4435edee822SRaphael Isemann                          request, resolver);
4441a6d7ab5SRaphael Isemann }
4451a6d7ab5SRaphael Isemann 
446ae34ed2cSRaphael Isemann void CommandCompletions::DiskFiles(CommandInterpreter &interpreter,
447a2e76c0bSRaphael Isemann                                    CompletionRequest &request,
448a2e76c0bSRaphael Isemann                                    SearchFilter *searcher) {
449ae34ed2cSRaphael Isemann   DiskFilesOrDirectories(request, /*only_dirs*/ false);
4502cc5a18dSZachary Turner }
4512cc5a18dSZachary Turner 
452ae34ed2cSRaphael Isemann void CommandCompletions::DiskFiles(const llvm::Twine &partial_file_name,
4532cc5a18dSZachary Turner                                    StringList &matches,
4542cc5a18dSZachary Turner                                    TildeExpressionResolver &Resolver) {
455ae34ed2cSRaphael Isemann   DiskFilesOrDirectories(partial_file_name, false, matches, Resolver);
456558ce124SJim Ingham }
457558ce124SJim Ingham 
458ae34ed2cSRaphael Isemann void CommandCompletions::DiskDirectories(CommandInterpreter &interpreter,
459a2e76c0bSRaphael Isemann                                          CompletionRequest &request,
460a2e76c0bSRaphael Isemann                                          SearchFilter *searcher) {
461ae34ed2cSRaphael Isemann   DiskFilesOrDirectories(request, /*only_dirs*/ true);
4622cc5a18dSZachary Turner }
4632cc5a18dSZachary Turner 
464ae34ed2cSRaphael Isemann void CommandCompletions::DiskDirectories(const llvm::Twine &partial_file_name,
4652cc5a18dSZachary Turner                                          StringList &matches,
4662cc5a18dSZachary Turner                                          TildeExpressionResolver &Resolver) {
467ae34ed2cSRaphael Isemann   DiskFilesOrDirectories(partial_file_name, true, matches, Resolver);
468558ce124SJim Ingham }
469558ce124SJim Ingham 
470ae34ed2cSRaphael Isemann void CommandCompletions::Modules(CommandInterpreter &interpreter,
471a2e76c0bSRaphael Isemann                                  CompletionRequest &request,
472a2e76c0bSRaphael Isemann                                  SearchFilter *searcher) {
473a2e76c0bSRaphael Isemann   ModuleCompleter completer(interpreter, request);
474c9af18a5SGreg Clayton 
475b9c1b51eSKate Stone   if (searcher == nullptr) {
4762976d00aSJim Ingham     lldb::TargetSP target_sp = interpreter.GetDebugger().GetSelectedTarget();
47733df7cd3SJim Ingham     SearchFilterForUnconstrainedSearches null_searcher(target_sp);
478c9af18a5SGreg Clayton     completer.DoCompletion(&null_searcher);
479b9c1b51eSKate Stone   } else {
480c9af18a5SGreg Clayton     completer.DoCompletion(searcher);
481c9af18a5SGreg Clayton   }
482c9af18a5SGreg Clayton }
483c9af18a5SGreg Clayton 
484ae34ed2cSRaphael Isemann void CommandCompletions::Symbols(CommandInterpreter &interpreter,
485a2e76c0bSRaphael Isemann                                  CompletionRequest &request,
486a2e76c0bSRaphael Isemann                                  SearchFilter *searcher) {
487a2e76c0bSRaphael Isemann   SymbolCompleter completer(interpreter, request);
488c9af18a5SGreg Clayton 
489b9c1b51eSKate Stone   if (searcher == nullptr) {
4902976d00aSJim Ingham     lldb::TargetSP target_sp = interpreter.GetDebugger().GetSelectedTarget();
49133df7cd3SJim Ingham     SearchFilterForUnconstrainedSearches null_searcher(target_sp);
492c9af18a5SGreg Clayton     completer.DoCompletion(&null_searcher);
493b9c1b51eSKate Stone   } else {
494c9af18a5SGreg Clayton     completer.DoCompletion(searcher);
495c9af18a5SGreg Clayton   }
496c9af18a5SGreg Clayton }
497c9af18a5SGreg Clayton 
498ae34ed2cSRaphael Isemann void CommandCompletions::SettingsNames(CommandInterpreter &interpreter,
499a2e76c0bSRaphael Isemann                                        CompletionRequest &request,
500a2e76c0bSRaphael Isemann                                        SearchFilter *searcher) {
50167cc0636SGreg Clayton   // Cache the full setting name list
50267cc0636SGreg Clayton   static StringList g_property_names;
503b9c1b51eSKate Stone   if (g_property_names.GetSize() == 0) {
50467cc0636SGreg Clayton     // Generate the full setting name list on demand
505b9c1b51eSKate Stone     lldb::OptionValuePropertiesSP properties_sp(
506b9c1b51eSKate Stone         interpreter.GetDebugger().GetValueProperties());
507b9c1b51eSKate Stone     if (properties_sp) {
50867cc0636SGreg Clayton       StreamString strm;
509c8ecc2a9SEugene Zelenko       properties_sp->DumpValue(nullptr, strm, OptionValue::eDumpOptionName);
510adcd0268SBenjamin Kramer       const std::string &str = std::string(strm.GetString());
51167cc0636SGreg Clayton       g_property_names.SplitIntoLines(str.c_str(), str.size());
51267cc0636SGreg Clayton     }
51367cc0636SGreg Clayton   }
5143df9a8dfSCaroline Tice 
51593ca36d7SRaphael Isemann   for (const std::string &s : g_property_names)
51693ca36d7SRaphael Isemann     request.TryCompleteCurrentArg(s);
517b8639f5cSRaphael Isemann }
518b8639f5cSRaphael Isemann 
519ae34ed2cSRaphael Isemann void CommandCompletions::PlatformPluginNames(CommandInterpreter &interpreter,
520a2e76c0bSRaphael Isemann                                              CompletionRequest &request,
521a2e76c0bSRaphael Isemann                                              SearchFilter *searcher) {
522ae34ed2cSRaphael Isemann   PluginManager::AutoCompletePlatformName(request.GetCursorArgumentPrefix(),
523ae34ed2cSRaphael Isemann                                           request);
524ab65b34fSGreg Clayton }
525ab65b34fSGreg Clayton 
526ae34ed2cSRaphael Isemann void CommandCompletions::ArchitectureNames(CommandInterpreter &interpreter,
527a2e76c0bSRaphael Isemann                                            CompletionRequest &request,
528a2e76c0bSRaphael Isemann                                            SearchFilter *searcher) {
529ae34ed2cSRaphael Isemann   ArchSpec::AutoComplete(request);
530ab65b34fSGreg Clayton }
531ab65b34fSGreg Clayton 
532ae34ed2cSRaphael Isemann void CommandCompletions::VariablePath(CommandInterpreter &interpreter,
533a2e76c0bSRaphael Isemann                                       CompletionRequest &request,
534a2e76c0bSRaphael Isemann                                       SearchFilter *searcher) {
535ae34ed2cSRaphael Isemann   Variable::AutoComplete(interpreter.GetExecutionContext(), request);
536f21feadcSGreg Clayton }
537a14f4a75SGongyu Deng 
538a14f4a75SGongyu Deng void CommandCompletions::Registers(CommandInterpreter &interpreter,
539a14f4a75SGongyu Deng                                    CompletionRequest &request,
540a14f4a75SGongyu Deng                                    SearchFilter *searcher) {
541a14f4a75SGongyu Deng   std::string reg_prefix = "";
542a14f4a75SGongyu Deng   if (request.GetCursorArgumentPrefix().startswith("$"))
543a14f4a75SGongyu Deng     reg_prefix = "$";
544a14f4a75SGongyu Deng 
545a14f4a75SGongyu Deng   RegisterContext *reg_ctx =
546a14f4a75SGongyu Deng       interpreter.GetExecutionContext().GetRegisterContext();
547a14f4a75SGongyu Deng   const size_t reg_num = reg_ctx->GetRegisterCount();
548a14f4a75SGongyu Deng   for (size_t reg_idx = 0; reg_idx < reg_num; ++reg_idx) {
549a14f4a75SGongyu Deng     const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoAtIndex(reg_idx);
550a14f4a75SGongyu Deng     request.TryCompleteCurrentArg(reg_prefix + reg_info->name,
551a14f4a75SGongyu Deng                                   reg_info->alt_name);
552a14f4a75SGongyu Deng   }
553a14f4a75SGongyu Deng }
554*0e50b9a4SGongyu Deng 
555*0e50b9a4SGongyu Deng void CommandCompletions::Breakpoints(CommandInterpreter &interpreter,
556*0e50b9a4SGongyu Deng                                      CompletionRequest &request,
557*0e50b9a4SGongyu Deng                                      SearchFilter *searcher) {
558*0e50b9a4SGongyu Deng   lldb::TargetSP target = interpreter.GetDebugger().GetSelectedTarget();
559*0e50b9a4SGongyu Deng   if (!target)
560*0e50b9a4SGongyu Deng     return;
561*0e50b9a4SGongyu Deng 
562*0e50b9a4SGongyu Deng   const BreakpointList &breakpoints = target->GetBreakpointList();
563*0e50b9a4SGongyu Deng 
564*0e50b9a4SGongyu Deng   std::unique_lock<std::recursive_mutex> lock;
565*0e50b9a4SGongyu Deng   target->GetBreakpointList().GetListMutex(lock);
566*0e50b9a4SGongyu Deng 
567*0e50b9a4SGongyu Deng   size_t num_breakpoints = breakpoints.GetSize();
568*0e50b9a4SGongyu Deng   if (num_breakpoints == 0)
569*0e50b9a4SGongyu Deng     return;
570*0e50b9a4SGongyu Deng 
571*0e50b9a4SGongyu Deng   for (size_t i = 0; i < num_breakpoints; ++i) {
572*0e50b9a4SGongyu Deng     lldb::BreakpointSP bp = breakpoints.GetBreakpointAtIndex(i);
573*0e50b9a4SGongyu Deng 
574*0e50b9a4SGongyu Deng     StreamString s;
575*0e50b9a4SGongyu Deng     bp->GetDescription(&s, lldb::eDescriptionLevelBrief);
576*0e50b9a4SGongyu Deng     llvm::StringRef bp_info = s.GetString();
577*0e50b9a4SGongyu Deng 
578*0e50b9a4SGongyu Deng     const size_t colon_pos = bp_info.find_first_of(':');
579*0e50b9a4SGongyu Deng     if (colon_pos != llvm::StringRef::npos)
580*0e50b9a4SGongyu Deng       bp_info = bp_info.drop_front(colon_pos + 2);
581*0e50b9a4SGongyu Deng 
582*0e50b9a4SGongyu Deng     request.TryCompleteCurrentArg(std::to_string(bp->GetID()), bp_info);
583*0e50b9a4SGongyu Deng   }
584*0e50b9a4SGongyu Deng }
585