diff --git a/.clang-format b/.clang-format index 85391e6149..a8ab11231c 100644 --- a/.clang-format +++ b/.clang-format @@ -25,6 +25,9 @@ IncludeCategories: - Regex: '^' Priority: -1 SortPriority: 0 + - Regex: '^"precompiled_header.h"' + Priority: -1 + SortPriority: 0 - Regex: '^".*"' Priority: 1 SortPriority: 0 @@ -54,7 +57,7 @@ SpacesInAngles: false SpacesInContainerLiterals: true SpacesInCStyleCastParentheses: false SpacesInParentheses: false -Standard: C++11 +Standard: c++20 TabWidth: 4 UseTab: Never SortIncludes: true diff --git a/CodeLite/AsyncProcess/ChildProcess.cpp b/CodeLite/AsyncProcess/ChildProcess.cpp index 99f775cd36..a388b22ded 100644 --- a/CodeLite/AsyncProcess/ChildProcess.cpp +++ b/CodeLite/AsyncProcess/ChildProcess.cpp @@ -11,11 +11,11 @@ ChildProcess::~ChildProcess() { #if USE_IPROCESS - if(m_process) { + if (m_process) { m_process->Detach(); } #else - if(m_childProcess) { + if (m_childProcess) { m_childProcess->Detach(); } #endif @@ -25,7 +25,7 @@ namespace { wxString& wrap_with_quotes(wxString& str) { - if(!str.empty() && str.Contains(" ") && !str.StartsWith("\"") && !str.EndsWith("\"")) { + if (!str.empty() && str.Contains(" ") && !str.StartsWith("\"") && !str.EndsWith("\"")) { str.Prepend("\"").Append("\""); } return str; @@ -34,7 +34,7 @@ wxString& wrap_with_quotes(wxString& str) void ChildProcess::Start(const wxArrayString& args) { - if(args.IsEmpty()) { + if (args.IsEmpty()) { return; } #if USE_IPROCESS @@ -51,7 +51,7 @@ void ChildProcess::Start(const wxArrayString& args) // Launch the process m_process.reset(::CreateAsyncProcess(this, command, IProcessCreateDefault | IProcessStderrEvent)); - if(!m_process) { + if (!m_process) { throw clException(wxString() << "Failed to execute process: " << command); }; #else @@ -63,7 +63,7 @@ void ChildProcess::Write(const wxString& message) { Write(StringUtils::ToStdStri void ChildProcess::Write(const std::string& message) { - if(!IsOk()) { + if (!IsOk()) { return; } #if USE_IPROCESS diff --git a/CodeLite/AsyncProcess/TerminalEmulator.cpp b/CodeLite/AsyncProcess/TerminalEmulator.cpp index b229582244..4be36fc271 100644 --- a/CodeLite/AsyncProcess/TerminalEmulator.cpp +++ b/CodeLite/AsyncProcess/TerminalEmulator.cpp @@ -23,21 +23,25 @@ class MyProcess : public wxProcess : wxProcess(parent) , m_parent(parent) { - if(m_parent) { m_parent->m_myProcesses.push_back(this); } + if (m_parent) { + m_parent->m_myProcesses.push_back(this); + } } virtual ~MyProcess() { m_parent = NULL; } void OnTerminate(int pid, int status) { - if(m_parent) { + if (m_parent) { clCommandEvent terminateEvent(wxEVT_TERMINAL_COMMAND_EXIT); m_parent->AddPendingEvent(terminateEvent); m_parent->m_pid = wxNOT_FOUND; - std::list::iterator iter = - std::find_if(m_parent->m_myProcesses.begin(), m_parent->m_myProcesses.end(), - [&](wxProcess* proc) { return proc == this; }); - if(iter != m_parent->m_myProcesses.end()) { m_parent->m_myProcesses.erase(iter); } + std::list::iterator iter = std::find_if(m_parent->m_myProcesses.begin(), + m_parent->m_myProcesses.end(), + [&](wxProcess* proc) { return proc == this; }); + if (iter != m_parent->m_myProcesses.end()) { + m_parent->m_myProcesses.erase(iter); + } delete this; } } @@ -61,8 +65,11 @@ TerminalEmulator::~TerminalEmulator() } } -bool TerminalEmulator::ExecuteConsole(const wxString& command, bool waitOnExit, const wxString& command_args, - const wxString& workingDirectory, const wxString& title) +bool TerminalEmulator::ExecuteConsole(const wxString& command, + bool waitOnExit, + const wxString& command_args, + const wxString& workingDirectory, + const wxString& title) { wxUnusedVar(title); clConsoleBase::Ptr_t console = clConsoleBase::GetTerminal(); @@ -72,7 +79,7 @@ bool TerminalEmulator::ExecuteConsole(const wxString& command, bool waitOnExit, console->SetCallback(new MyProcess(this)); wxString strTitle = title; - if(strTitle.IsEmpty()) { + if (strTitle.IsEmpty()) { strTitle << "'" << command << "'"; } else { strTitle.Prepend("'").Append("'"); @@ -94,9 +101,11 @@ void TerminalEmulator::OnProcessTerminated(clProcessEvent& event) void TerminalEmulator::Terminate() { - if(IsRunning()) { - if(m_process) { m_process->Terminate(); } - if(m_pid != wxNOT_FOUND) { + if (IsRunning()) { + if (m_process) { + m_process->Terminate(); + } + if (m_pid != wxNOT_FOUND) { wxKill(m_pid, wxSIGKILL, NULL, wxKILL_CHILDREN); m_pid = wxNOT_FOUND; } @@ -114,7 +123,7 @@ void TerminalEmulator::OnProcessOutput(clProcessEvent& event) bool TerminalEmulator::ExecuteNoConsole(const wxString& commandToRun, const wxString& workingDirectory) { - if(m_process) { + if (m_process) { // another process is running return false; } @@ -122,7 +131,9 @@ bool TerminalEmulator::ExecuteNoConsole(const wxString& commandToRun, const wxSt wxString command; #ifdef __WXMSW__ wxString shell = wxGetenv("COMSPEC"); - if(shell.IsEmpty()) { shell = "CMD"; } + if (shell.IsEmpty()) { + shell = "CMD"; + } command << shell << wxT(" /c \""); command << commandToRun << wxT("\""); diff --git a/CodeLite/AsyncProcess/TerminalEmulator.h b/CodeLite/AsyncProcess/TerminalEmulator.h index 13f4f31884..5a5940d92f 100644 --- a/CodeLite/AsyncProcess/TerminalEmulator.h +++ b/CodeLite/AsyncProcess/TerminalEmulator.h @@ -73,8 +73,11 @@ class WXDLLIMPEXP_CL TerminalEmulator : public wxEvtHandler * "Hit any key to continue" * @param title set the terminal title. If an empty string is provided, use the command as the title */ - bool ExecuteConsole(const wxString& command, bool waitOnExit = false, const wxString& command_args = "", - const wxString& workingDirectory = "", const wxString& title = ""); + bool ExecuteConsole(const wxString& command, + bool waitOnExit = false, + const wxString& command_args = "", + const wxString& workingDirectory = "", + const wxString& title = ""); /** * @brief execute a command without attaching console */ diff --git a/CodeLite/AsyncProcess/TerminalEmulatorFrame.cpp b/CodeLite/AsyncProcess/TerminalEmulatorFrame.cpp index 6420cacbdd..274442ffd8 100644 --- a/CodeLite/AsyncProcess/TerminalEmulatorFrame.cpp +++ b/CodeLite/AsyncProcess/TerminalEmulatorFrame.cpp @@ -4,7 +4,6 @@ TerminalEmulatorFrame::TerminalEmulatorFrame(wxWindow* parent) : TerminalEmulatorFrameBase(parent) { m_terminal = new TerminalEmulatorUI(this); - GetSizer()->Add(m_terminal, 1, wxEXPAND|wxALL); - + GetSizer()->Add(m_terminal, 1, wxEXPAND | wxALL); } #endif // LIBCODELITE_WITH_UI diff --git a/CodeLite/AsyncProcess/TerminalEmulatorFrame.h b/CodeLite/AsyncProcess/TerminalEmulatorFrame.h index 2433b034b3..56387154f6 100644 --- a/CodeLite/AsyncProcess/TerminalEmulatorFrame.h +++ b/CodeLite/AsyncProcess/TerminalEmulatorFrame.h @@ -26,12 +26,13 @@ #ifndef TERMINALEMULATORFRAME_H #define TERMINALEMULATORFRAME_H -#include "TerminalEmulatorUIBase.h" #include "TerminalEmulatorUI.h" +#include "TerminalEmulatorUIBase.h" #if wxUSE_GUI class WXDLLIMPEXP_CL TerminalEmulatorFrame : public TerminalEmulatorFrameBase { TerminalEmulatorUI* m_terminal; + public: TerminalEmulatorFrame(wxWindow* parent); virtual ~TerminalEmulatorFrame() = default; diff --git a/CodeLite/AsyncProcess/TerminalEmulatorUI.cpp b/CodeLite/AsyncProcess/TerminalEmulatorUI.cpp index 9c3ddaf484..09aeb5cb36 100644 --- a/CodeLite/AsyncProcess/TerminalEmulatorUI.cpp +++ b/CodeLite/AsyncProcess/TerminalEmulatorUI.cpp @@ -10,11 +10,11 @@ void TerminalEmulatorUI::OnSendCommand(wxCommandEvent& event) {} void TerminalEmulatorUI::SetTerminal(TerminalEmulator* terminal) { - if(m_terminal) { + if (m_terminal) { DoUnBindTerminal(m_terminal); } this->m_terminal = terminal; - if(m_terminal) { + if (m_terminal) { DoBindTerminal(m_terminal); } } @@ -22,7 +22,7 @@ void TerminalEmulatorUI::SetTerminal(TerminalEmulator* terminal) void TerminalEmulatorUI::OnProcessExit(clCommandEvent& e) { e.Skip(); - if(m_terminal) { + if (m_terminal) { DoUnBindTerminal(m_terminal); m_terminal = NULL; } @@ -43,7 +43,7 @@ void TerminalEmulatorUI::OnProcessOutput(clCommandEvent& e) void TerminalEmulatorUI::DoBindTerminal(TerminalEmulator* terminal) { - if(terminal) { + if (terminal) { terminal->Bind(wxEVT_TERMINAL_COMMAND_EXIT, &TerminalEmulatorUI::OnProcessExit, this); terminal->Bind(wxEVT_TERMINAL_COMMAND_OUTPUT, &TerminalEmulatorUI::OnProcessOutput, this); } @@ -51,7 +51,7 @@ void TerminalEmulatorUI::DoBindTerminal(TerminalEmulator* terminal) void TerminalEmulatorUI::DoUnBindTerminal(TerminalEmulator* terminal) { - if(terminal) { + if (terminal) { terminal->Unbind(wxEVT_TERMINAL_COMMAND_EXIT, &TerminalEmulatorUI::OnProcessExit, this); terminal->Unbind(wxEVT_TERMINAL_COMMAND_OUTPUT, &TerminalEmulatorUI::OnProcessOutput, this); } diff --git a/CodeLite/AsyncProcess/TerminalEmulatorUI.h b/CodeLite/AsyncProcess/TerminalEmulatorUI.h index 879db57e71..93c27b030a 100644 --- a/CodeLite/AsyncProcess/TerminalEmulatorUI.h +++ b/CodeLite/AsyncProcess/TerminalEmulatorUI.h @@ -29,25 +29,26 @@ #include #if wxUSE_GUI -#include "TerminalEmulatorUIBase.h" #include "TerminalEmulator.h" +#include "TerminalEmulatorUIBase.h" class WXDLLIMPEXP_CL TerminalEmulatorUI : public TerminalEmulatorUIBase { TerminalEmulator* m_terminal; + private: void DoBindTerminal(TerminalEmulator* terminal); void DoUnBindTerminal(TerminalEmulator* terminal); - + public: TerminalEmulatorUI(wxWindow* parent); virtual ~TerminalEmulatorUI() = default; void Clear(); - void SetTerminal(TerminalEmulator* terminal) ; + void SetTerminal(TerminalEmulator* terminal); TerminalEmulator* GetTerminal() { return m_terminal; } wxStyledTextCtrl* GetTerminalOutputWindow() { return m_stc; } - + protected: virtual void OnSendCommand(wxCommandEvent& event); void OnProcessExit(clCommandEvent& e); diff --git a/CodeLite/AsyncProcess/UnixProcess.h b/CodeLite/AsyncProcess/UnixProcess.h index 27911b5e88..398e7725dc 100644 --- a/CodeLite/AsyncProcess/UnixProcess.h +++ b/CodeLite/AsyncProcess/UnixProcess.h @@ -1,6 +1,7 @@ #ifndef UNIX_PROCESS_H #define UNIX_PROCESS_H #if defined(__WXGTK__) || defined(__WXOSX__) +#include #include #include #include @@ -8,16 +9,15 @@ #include #include #include -#include -#include -#include #include +#include +#include // Wrapping pipe in a class makes sure they are closed when we leave scope -#define CLOSE_FD(fd) \ - if(fd != wxNOT_FOUND) { \ - ::close(fd); \ - fd = wxNOT_FOUND; \ +#define CLOSE_FD(fd) \ + if (fd != wxNOT_FOUND) { \ + ::close(fd); \ + fd = wxNOT_FOUND; \ } class CPipe @@ -39,7 +39,7 @@ class CPipe bool Open() { int fd[2]; - if(pipe(fd) == 0) { + if (pipe(fd) == 0) { m_readFd = fd[0]; m_writeFd = fd[1]; return true; diff --git a/CodeLite/AsyncProcess/ZombieReaperPOSIX.cpp b/CodeLite/AsyncProcess/ZombieReaperPOSIX.cpp index 474f078a98..7f754351f5 100644 --- a/CodeLite/AsyncProcess/ZombieReaperPOSIX.cpp +++ b/CodeLite/AsyncProcess/ZombieReaperPOSIX.cpp @@ -42,10 +42,10 @@ ZombieReaperPOSIX::ZombieReaperPOSIX() void* ZombieReaperPOSIX::Entry() { - while(!TestDestroy()) { + while (!TestDestroy()) { int status(0); pid_t pid = ::waitpid((pid_t)-1, &status, WNOHANG); - if(pid > 0) { + if (pid > 0) { // Notify about this process termination wxProcessEvent event(0, pid, status); event.SetEventType(wxEVT_CL_PROCESS_TERMINATED); @@ -61,7 +61,7 @@ void* ZombieReaperPOSIX::Entry() void ZombieReaperPOSIX::Stop() { - if(IsAlive()) { + if (IsAlive()) { Delete(NULL, wxTHREAD_WAIT_BLOCK); } else { Wait(wxTHREAD_WAIT_BLOCK); diff --git a/CodeLite/AsyncProcess/ZombieReaperPOSIX.h b/CodeLite/AsyncProcess/ZombieReaperPOSIX.h index 67d0641f82..96cc9552ef 100644 --- a/CodeLite/AsyncProcess/ZombieReaperPOSIX.h +++ b/CodeLite/AsyncProcess/ZombieReaperPOSIX.h @@ -28,10 +28,11 @@ #ifndef __WXMSW__ -#include -#include #include "codelite_exports.h" + +#include #include +#include wxDECLARE_EXPORTED_EVENT(WXDLLIMPEXP_CL, wxEVT_CL_PROCESS_TERMINATED, wxProcessEvent); @@ -42,13 +43,13 @@ class WXDLLIMPEXP_CL ZombieReaperPOSIX : public wxThread ZombieReaperPOSIX(); virtual ~ZombieReaperPOSIX() = default; - void Start() { + void Start() + { Create(); Run(); } - + void Stop(); }; -#endif +#endif #endif // ZOMBIEREAPERPOSIX_H - diff --git a/CodeLite/AsyncProcess/asyncprocess.h b/CodeLite/AsyncProcess/asyncprocess.h index f1599fe0f3..2cc8463347 100644 --- a/CodeLite/AsyncProcess/asyncprocess.h +++ b/CodeLite/AsyncProcess/asyncprocess.h @@ -53,7 +53,7 @@ enum IProcessCreateFlags { IProcessInteractiveSSH = (1 << 9), IProcessWrapInShell = (1 << 10), // wrap the command in the OS shell (CMD, BASH) IProcessPseudoConsole = (1 << 11), // MSW only: use CreatePseudoConsole API for creating the process - IProcessNoPty = (1 << 12), // Unix only: do not use forkpty, use normal fork() + IProcessNoPty = (1 << 12), // Unix only: do not use forkpty, use normal fork() }; class WXDLLIMPEXP_CL IProcess; @@ -186,7 +186,8 @@ class WXDLLIMPEXP_CL IProcess : public wxEvtHandler * @param workingDir set the working directory of the executed process * @return */ -WXDLLIMPEXP_CL IProcess* CreateAsyncProcess(wxEvtHandler* parent, const wxString& cmd, +WXDLLIMPEXP_CL IProcess* CreateAsyncProcess(wxEvtHandler* parent, + const wxString& cmd, size_t flags = IProcessCreateDefault, const wxString& workingDir = wxEmptyString, const clEnvList_t* env = nullptr, @@ -194,7 +195,8 @@ WXDLLIMPEXP_CL IProcess* CreateAsyncProcess(wxEvtHandler* parent, const wxString /** * @brief same as above, but uses array of instead of a single string */ -WXDLLIMPEXP_CL IProcess* CreateAsyncProcess(wxEvtHandler* parent, const wxArrayString& args, +WXDLLIMPEXP_CL IProcess* CreateAsyncProcess(wxEvtHandler* parent, + const wxArrayString& args, size_t flags = IProcessCreateDefault, const wxString& workingDir = wxEmptyString, const clEnvList_t* env = nullptr, @@ -204,7 +206,8 @@ WXDLLIMPEXP_CL IProcess* CreateAsyncProcess(wxEvtHandler* parent, const wxArrayS * @brief a wrapper for the variant that accepts wxArrayString. * This is because wxArrayString does not allow initializer list */ -WXDLLIMPEXP_CL IProcess* CreateAsyncProcess(wxEvtHandler* parent, const std::vector& args, +WXDLLIMPEXP_CL IProcess* CreateAsyncProcess(wxEvtHandler* parent, + const std::vector& args, size_t flags = IProcessCreateDefault, const wxString& workingDir = wxEmptyString, const clEnvList_t* env = nullptr, @@ -217,7 +220,8 @@ WXDLLIMPEXP_CL IProcess* CreateAsyncProcess(wxEvtHandler* parent, const std::vec * @param workingDir working directory for the new process * @return IProcess handle on success */ -WXDLLIMPEXP_CL IProcess* CreateSyncProcess(const wxString& cmd, size_t flags = IProcessCreateDefault, +WXDLLIMPEXP_CL IProcess* CreateSyncProcess(const wxString& cmd, + size_t flags = IProcessCreateDefault, const wxString& workingDir = wxEmptyString, const clEnvList_t* env = nullptr); @@ -229,8 +233,10 @@ WXDLLIMPEXP_CL IProcess* CreateSyncProcess(const wxString& cmd, size_t flags = I * @param workingDir set the working directory of the executed process * @param env */ -WXDLLIMPEXP_CL void CreateAsyncProcessCB(const wxString& cmd, std::function cb, +WXDLLIMPEXP_CL void CreateAsyncProcessCB(const wxString& cmd, + std::function cb, size_t flags = IProcessCreateDefault, - const wxString& workingDir = wxEmptyString, const clEnvList_t* env = nullptr); + const wxString& workingDir = wxEmptyString, + const clEnvList_t* env = nullptr); #endif // I_PROCESS_H diff --git a/CodeLite/AsyncProcess/clCommandProcessor.cpp b/CodeLite/AsyncProcess/clCommandProcessor.cpp index 23d8a70b6e..a17b159243 100644 --- a/CodeLite/AsyncProcess/clCommandProcessor.cpp +++ b/CodeLite/AsyncProcess/clCommandProcessor.cpp @@ -13,7 +13,6 @@ clCommandProcessor::clCommandProcessor(const wxString& command, const wxString& { Bind(wxEVT_ASYNC_PROCESS_OUTPUT, &clCommandProcessor::OnProcessOutput, this); Bind(wxEVT_ASYNC_PROCESS_TERMINATED, &clCommandProcessor::OnProcessTerminated, this); - } void clCommandProcessor::ExecuteCommand() @@ -24,10 +23,10 @@ void clCommandProcessor::ExecuteCommand() clCommandEvent eventStart(wxEVT_COMMAND_PROCESSOR_OUTPUT); eventStart.SetString(message); GetFirst()->ProcessEvent(eventStart); - + m_output.Clear(); m_process.reset(::CreateAsyncProcess(this, m_command, m_processFlags, m_workingDirectory)); - if(!m_process) { + if (!m_process) { clCommandEvent eventEnd(wxEVT_COMMAND_PROCESSOR_ENDED); eventEnd.SetString(wxString::Format(_("Failed to execute command: %s"), m_command)); GetFirst()->ProcessEvent(eventEnd); @@ -42,7 +41,7 @@ void clCommandProcessor::OnProcessOutput(clProcessEvent& event) m_output << event.GetOutput(); eventStart.SetString(event.GetOutput()); GetFirst()->ProcessEvent(eventStart); - if(eventStart.GetString() != event.GetOutput()) { + if (eventStart.GetString() != event.GetOutput()) { // user provided some input, write it to the running process m_process->WriteToConsole(eventStart.GetString()); } @@ -50,10 +49,10 @@ void clCommandProcessor::OnProcessOutput(clProcessEvent& event) void clCommandProcessor::OnProcessTerminated(clProcessEvent& event) { - if(m_obj && m_postExecCallback) { + if (m_obj && m_postExecCallback) { // Call the user callback, if the user returns false // stop the processor - if(!(m_obj->*m_postExecCallback)(this)) { + if (!(m_obj->*m_postExecCallback)(this)) { clCommandEvent eventEnd(wxEVT_COMMAND_PROCESSOR_ENDED); GetFirst()->ProcessEvent(eventEnd); DeleteChain(); @@ -61,7 +60,7 @@ void clCommandProcessor::OnProcessTerminated(clProcessEvent& event) } } - if(m_next) { + if (m_next) { m_process.reset(); // more commands, don't report an 'END' event m_next->ExecuteCommand(); @@ -77,7 +76,7 @@ void clCommandProcessor::OnProcessTerminated(clProcessEvent& event) clCommandProcessor* clCommandProcessor::Link(clCommandProcessor* next) { this->m_next = next; - if(m_next) { + if (m_next) { m_next->m_prev = this; } return next; @@ -89,7 +88,7 @@ void clCommandProcessor::DeleteChain() clCommandProcessor* first = GetFirst(); // delete - while(first) { + while (first) { clCommandProcessor* next = first->m_next; wxDELETE(first); first = next; @@ -99,7 +98,7 @@ void clCommandProcessor::DeleteChain() clCommandProcessor* clCommandProcessor::GetFirst() { clCommandProcessor* first = this; - while(first->m_prev) { + while (first->m_prev) { first = first->m_prev; } return first; @@ -108,8 +107,8 @@ clCommandProcessor* clCommandProcessor::GetFirst() void clCommandProcessor::Terminate() { clCommandProcessor* first = GetFirst(); - while(first) { - if(first->m_process) { + while (first) { + if (first->m_process) { first->m_process->Terminate(); break; } diff --git a/CodeLite/AsyncProcess/processreaderthread.cpp b/CodeLite/AsyncProcess/processreaderthread.cpp index 246f17a382..bbe3403516 100644 --- a/CodeLite/AsyncProcess/processreaderthread.cpp +++ b/CodeLite/AsyncProcess/processreaderthread.cpp @@ -47,44 +47,44 @@ ProcessReaderThread::~ProcessReaderThread() { m_notifiedWindow = NULL; } void* ProcessReaderThread::Entry() { - while(true) { + while (true) { // Did we get a request to terminate? - if(TestDestroy()) { + if (TestDestroy()) { break; } - if(m_suspend.load() && (m_is_suspended.load() == false)) { + if (m_suspend.load() && (m_is_suspended.load() == false)) { // request to suspend thread, but the status is not suspended m_is_suspended.store(true); - } else if(m_is_suspended.load() && m_suspend.load() == false) { + } else if (m_is_suspended.load() && m_suspend.load() == false) { // request to resume thread but the status is suspended m_is_suspended.store(false); } - if(m_is_suspended.load()) { + if (m_is_suspended.load()) { wxThread::Sleep(5); continue; } - if(m_process) { + if (m_process) { wxString buff; wxString buffErr; std::string raw_buff; std::string raw_buff_err; - if(m_process->IsRedirect()) { - if(m_process->Read(buff, buffErr, raw_buff, raw_buff_err)) { - if(!buff.IsEmpty() || !buffErr.IsEmpty()) { + if (m_process->IsRedirect()) { + if (m_process->Read(buff, buffErr, raw_buff, raw_buff_err)) { + if (!buff.IsEmpty() || !buffErr.IsEmpty()) { // If we got a callback object, use it bool isSuspended = m_is_suspended.load(); - if(!isSuspended) { - if(m_process && m_process->GetCallback()) { + if (!isSuspended) { + if (m_process && m_process->GetCallback()) { m_process->GetCallback()->CallAfter(&IProcessCallback::OnProcessOutput, buff); } else { // We fire an event per data (stderr/stdout) - if(!buff.IsEmpty() && m_notifiedWindow) { + if (!buff.IsEmpty() && m_notifiedWindow) { // fallback to the event system // we got some data, send event to parent clProcessEvent e(wxEVT_ASYNC_PROCESS_OUTPUT); @@ -94,7 +94,7 @@ void* ProcessReaderThread::Entry() m_notifiedWindow->QueueEvent(e.Clone()); } - if(!buffErr.IsEmpty() && m_notifiedWindow) { + if (!buffErr.IsEmpty() && m_notifiedWindow) { // we got some data, send event to parent clProcessEvent e(wxEVT_ASYNC_PROCESS_STDERR); e.SetOutput(buffErr); @@ -114,7 +114,7 @@ void* ProcessReaderThread::Entry() } } else { // Check if the process is alive - if(!m_process->IsAlive()) { + if (!m_process->IsAlive()) { // Notify about termination NotifyTerminated(); break; @@ -135,7 +135,7 @@ void ProcessReaderThread::Stop() { // Notify the thread to exit and // wait for it - if(IsAlive()) { + if (IsAlive()) { Delete(NULL, wxTHREAD_WAIT_BLOCK); } else { Wait(wxTHREAD_WAIT_BLOCK); @@ -153,14 +153,14 @@ void ProcessReaderThread::NotifyTerminated() { // Process terminated, exit // If we got a callback object, use it - if(m_process && m_process->GetCallback()) { + if (m_process && m_process->GetCallback()) { m_process->GetCallback()->CallAfter(&IProcessCallback::OnProcessTerminated); } else { // fallback to the event system clProcessEvent e(wxEVT_ASYNC_PROCESS_TERMINATED); e.SetProcess(m_process); - if(m_notifiedWindow) { + if (m_notifiedWindow) { m_notifiedWindow->AddPendingEvent(e); } } @@ -170,8 +170,8 @@ void ProcessReaderThread::Suspend() { m_suspend.store(true); // wait until we make sure that the reader thread is suspended - while(true) { - if(m_is_suspended.load()) { + while (true) { + if (m_is_suspended.load()) { break; } wxThread::Sleep(1); @@ -182,8 +182,8 @@ void ProcessReaderThread::Resume() { m_suspend.store(false); // wait until we make sure that the reader thread is resumed - while(true) { - if(!m_is_suspended.load()) { + while (true) { + if (!m_is_suspended.load()) { break; } wxThread::Sleep(1); diff --git a/CodeLite/AsyncProcess/unixprocess_impl.cpp b/CodeLite/AsyncProcess/unixprocess_impl.cpp index f00d4be29d..fbc834e8cb 100644 --- a/CodeLite/AsyncProcess/unixprocess_impl.cpp +++ b/CodeLite/AsyncProcess/unixprocess_impl.cpp @@ -284,7 +284,7 @@ namespace { bool create_pipe(int& read_end, int& write_end) { - int fds[2] = { 0, 0 }; + int fds[2] = {0, 0}; errno = 0; if (::pipe(fds) < 0) { clERROR() << "Failed to create pipe()." << strerror(errno); @@ -296,8 +296,11 @@ bool create_pipe(int& read_end, int& write_end) } } // namespace -IProcess* UnixProcessImpl::Execute(wxEvtHandler* parent, const wxArrayString& args, size_t flags, - const wxString& workingDirectory, IProcessCallback* cb) +IProcess* UnixProcessImpl::Execute(wxEvtHandler* parent, + const wxArrayString& args, + size_t flags, + const wxString& workingDirectory, + IProcessCallback* cb) { int argc = 0; char** argv = make_argv(args, argc); @@ -461,8 +464,8 @@ IProcess* UnixProcessImpl::Execute(wxEvtHandler* parent, const wxArrayString& ar } } -IProcess* UnixProcessImpl::Execute(wxEvtHandler* parent, const wxString& cmd, size_t flags, - const wxString& workingDirectory, IProcessCallback* cb) +IProcess* UnixProcessImpl::Execute( + wxEvtHandler* parent, const wxString& cmd, size_t flags, const wxString& workingDirectory, IProcessCallback* cb) { wxArrayString args = StringUtils::BuildArgv(cmd); clDEBUG() << "Executing:" << cmd << endl; diff --git a/CodeLite/AsyncProcess/unixprocess_impl.h b/CodeLite/AsyncProcess/unixprocess_impl.h index 80714a5bde..f43dba7ff2 100644 --- a/CodeLite/AsyncProcess/unixprocess_impl.h +++ b/CodeLite/AsyncProcess/unixprocess_impl.h @@ -48,11 +48,17 @@ class WXDLLIMPEXP_CL UnixProcessImpl : public IProcess UnixProcessImpl(wxEvtHandler* parent); virtual ~UnixProcessImpl(); - static IProcess* Execute(wxEvtHandler* parent, const wxArrayString& args, size_t flags, - const wxString& workingDirectory = wxEmptyString, IProcessCallback* cb = NULL); + static IProcess* Execute(wxEvtHandler* parent, + const wxArrayString& args, + size_t flags, + const wxString& workingDirectory = wxEmptyString, + IProcessCallback* cb = NULL); - static IProcess* Execute(wxEvtHandler* parent, const wxString& cmd, size_t flags, - const wxString& workingDirectory = wxEmptyString, IProcessCallback* cb = NULL); + static IProcess* Execute(wxEvtHandler* parent, + const wxString& cmd, + size_t flags, + const wxString& workingDirectory = wxEmptyString, + IProcessCallback* cb = NULL); void SetReadHandle(int readHandle) { this->m_readHandle = readHandle; } void SetWriteHandler(int writeHandler) { this->m_writeHandle = writeHandler; } diff --git a/CodeLite/AsyncProcess/winprocess_impl.cpp b/CodeLite/AsyncProcess/winprocess_impl.cpp index 2e2417bd36..2573291efc 100644 --- a/CodeLite/AsyncProcess/winprocess_impl.cpp +++ b/CodeLite/AsyncProcess/winprocess_impl.cpp @@ -88,7 +88,7 @@ class ConsoleAttacher ~ConsoleAttacher() { - if(isAttached) { + if (isAttached) { FreeConsole(); } isAttached = false; @@ -98,17 +98,18 @@ class ConsoleAttacher static bool CheckIsAlive(HANDLE hProcess) { DWORD dwExitCode; - if(GetExitCodeProcess(hProcess, &dwExitCode)) { - if(dwExitCode == STILL_ACTIVE) + if (GetExitCodeProcess(hProcess, &dwExitCode)) { + if (dwExitCode == STILL_ACTIVE) return true; } return false; } -template bool WriteStdin(const T& buffer, HANDLE hStdin, HANDLE hProcess) +template +bool WriteStdin(const T& buffer, HANDLE hStdin, HANDLE hProcess) { DWORD dwMode; - if(hStdin == INVALID_HANDLE_VALUE || hProcess == INVALID_HANDLE_VALUE) { + if (hStdin == INVALID_HANDLE_VALUE || hProcess == INVALID_HANDLE_VALUE) { clWARNING() << "Unable read from process Stdin: invalid handle" << endl; return false; } @@ -120,18 +121,18 @@ template bool WriteStdin(const T& buffer, HANDLE hStdin, HANDLE hPr long offset = 0; static constexpr int max_retry_count = 100; size_t retryCount = 0; - while(bytesLeft > 0 && (retryCount < max_retry_count)) { + while (bytesLeft > 0 && (retryCount < max_retry_count)) { DWORD dwWritten = 0; - if(!WriteFile(hStdin, buffer.c_str() + offset, bytesLeft, &dwWritten, NULL)) { + if (!WriteFile(hStdin, buffer.c_str() + offset, bytesLeft, &dwWritten, NULL)) { int errorCode = GetLastError(); LOG_IF_DEBUG { clDEBUG() << ">> WriteStdin: (WriteFile) error:" << errorCode << endl; } return false; } - if(!CheckIsAlive(hProcess)) { + if (!CheckIsAlive(hProcess)) { LOG_IF_DEBUG { clDEBUG() << "WriteStdin failed. Process is not alive" << endl; } return false; } - if(dwWritten == 0) { + if (dwWritten == 0) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); } bytesLeft -= dwWritten; @@ -139,7 +140,7 @@ template bool WriteStdin(const T& buffer, HANDLE hStdin, HANDLE hPr ++retryCount; } - if(retryCount >= max_retry_count) { + if (retryCount >= max_retry_count) { clERROR() << "Failed to write to process after" << max_retry_count << "retries. Written" << (buffer.length() - bytesLeft) << "/" << buffer.length() << "bytes" << endl; return false; @@ -168,7 +169,7 @@ class WXDLLIMPEXP_CL WinWriterThread void Start() { m_thread = new std::thread(&WinWriterThread::Entry, this, m_hStdin); } void Stop() { - if(m_thread) { + if (m_thread) { m_shutdown.store(true); m_thread->join(); wxDELETE(m_thread); @@ -177,9 +178,9 @@ class WXDLLIMPEXP_CL WinWriterThread static void Entry(WinWriterThread* thr, HANDLE hStdin) { auto& Q = thr->m_outgoingQueue; - while(!thr->m_shutdown.load()) { + while (!thr->m_shutdown.load()) { std::string cstr; - if(Q.ReceiveTimeout(50, cstr) == wxMSGQUEUE_NO_ERROR) { + if (Q.ReceiveTimeout(50, cstr) == wxMSGQUEUE_NO_ERROR) { WriteStdin(cstr, hStdin, thr->m_hProcess); } } @@ -194,7 +195,7 @@ namespace wxString ArrayJoin(const wxArrayString& args, size_t flags) { wxString command; - if(flags & IProcessWrapInShell) { + if (flags & IProcessWrapInShell) { // CMD /C [command] ... // Make sure that the first command is wrapped with "" if it contains spaces LOG_IF_TRACE @@ -203,7 +204,7 @@ wxString ArrayJoin(const wxArrayString& args, size_t flags) clDEBUG1() << "args[2] is:" << args[2] << endl; } - if((args.size() > 3) && (!args[2].StartsWith("\"")) && (args[2].Contains(" "))) { + if ((args.size() > 3) && (!args[2].StartsWith("\"")) && (args[2].Contains(" "))) { LOG_IF_DEBUG { clDEBUG() << "==> Fixing" << args << endl; } wxArrayString tmparr = args; wxString& firstCommand = tmparr[2]; @@ -212,15 +213,15 @@ wxString ArrayJoin(const wxArrayString& args, size_t flags) } else { command = wxJoin(args, ' ', 0); } - } else if(flags & IProcessCreateSSH) { + } else if (flags & IProcessCreateSSH) { // simple join command = wxJoin(args, ' ', 0); } else { wxArrayString arr; arr.reserve(args.size()); arr = args; - for(auto& arg : arr) { - if(arg.Contains(" ")) { + for (auto& arg : arr) { + if (arg.Contains(" ")) { // escape any " before we start escaping arg.Replace("\"", "\\\""); // now wrap with double quotes @@ -248,19 +249,19 @@ HRESULT PrepareStartupInformation(HPCON hpc, STARTUPINFOEX* psi) // Allocate memory to represent the list si.lpAttributeList = (PPROC_THREAD_ATTRIBUTE_LIST)HeapAlloc(GetProcessHeap(), 0, bytesRequired); - if(!si.lpAttributeList) { + if (!si.lpAttributeList) { return E_OUTOFMEMORY; } // Initialize the list memory location - if(!InitializeProcThreadAttributeList(si.lpAttributeList, 1, 0, &bytesRequired)) { + if (!InitializeProcThreadAttributeList(si.lpAttributeList, 1, 0, &bytesRequired)) { HeapFree(GetProcessHeap(), 0, si.lpAttributeList); return HRESULT_FROM_WIN32(GetLastError()); } // Set the pseudoconsole information into the list - if(!UpdateProcThreadAttribute(si.lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, hpc, sizeof(hpc), NULL, - NULL)) { + if (!UpdateProcThreadAttribute( + si.lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, hpc, sizeof(hpc), NULL, NULL)) { HeapFree(GetProcessHeap(), 0, si.lpAttributeList); return HRESULT_FROM_WIN32(GetLastError()); } @@ -272,16 +273,19 @@ HRESULT PrepareStartupInformation(HPCON hpc, STARTUPINFOEX* psi) } // namespace -IProcess* WinProcessImpl::Execute(wxEvtHandler* parent, const wxArrayString& args, size_t flags, - const wxString& workingDirectory, IProcessCallback* cb) +IProcess* WinProcessImpl::Execute(wxEvtHandler* parent, + const wxArrayString& args, + size_t flags, + const wxString& workingDirectory, + IProcessCallback* cb) { wxString cmd = ArrayJoin(args, flags); LOG_IF_TRACE { clDEBUG1() << "Windows process starting:" << cmd << endl; } return Execute(parent, cmd, flags, workingDirectory, cb); } -IProcess* WinProcessImpl::ExecuteConPTY(wxEvtHandler* parent, const wxString& cmd, size_t flags, - const wxString& workingDir) +IProcess* +WinProcessImpl::ExecuteConPTY(wxEvtHandler* parent, const wxString& cmd, size_t flags, const wxString& workingDir) { // - Close these after CreateProcess of child application with pseudoconsole object. HANDLE inputReadSide, outputWriteSide; @@ -291,10 +295,10 @@ IProcess* WinProcessImpl::ExecuteConPTY(wxEvtHandler* parent, const wxString& cm HPCON hPC = 0; // Create the in/out pipes: - if(!CreatePipe(&inputReadSide, &inputWriteSide, NULL, 0)) { + if (!CreatePipe(&inputReadSide, &inputWriteSide, NULL, 0)) { return nullptr; } - if(!CreatePipe(&outputReadSide, &outputWriteSide, NULL, 0)) { + if (!CreatePipe(&outputReadSide, &outputWriteSide, NULL, 0)) { ::CloseHandle(inputReadSide); ::CloseHandle(inputWriteSide); return nullptr; @@ -302,10 +306,10 @@ IProcess* WinProcessImpl::ExecuteConPTY(wxEvtHandler* parent, const wxString& cm #if !defined(_MSC_VER) // Create the Pseudo Console, using the pipes - if(loadOnce) { + if (loadOnce) { loadOnce = false; auto hDLL = ::LoadLibrary(L"Kernel32.dll"); - if(hDLL) { + if (hDLL) { CreatePseudoConsoleFunc = (CreatePseudoConsole_T)::GetProcAddress(hDLL, "CreatePseudoConsole"); ClosePseudoConsoleFunc = (ClosePseudoConsole_T)::GetProcAddress(hDLL, "ClosePseudoConsole"); FreeLibrary(hDLL); @@ -313,15 +317,15 @@ IProcess* WinProcessImpl::ExecuteConPTY(wxEvtHandler* parent, const wxString& cm } #endif - if(!CreatePseudoConsoleFunc || !ClosePseudoConsoleFunc) { + if (!CreatePseudoConsoleFunc || !ClosePseudoConsoleFunc) { ::CloseHandle(inputReadSide); ::CloseHandle(outputWriteSide); ::CloseHandle(inputWriteSide); ::CloseHandle(outputReadSide); return nullptr; } - auto hr = CreatePseudoConsoleFunc({ 1000, 32 }, inputReadSide, outputWriteSide, 0, &hPC); - if(FAILED(hr)) { + auto hr = CreatePseudoConsoleFunc({1000, 32}, inputReadSide, outputWriteSide, 0, &hPC); + if (FAILED(hr)) { ::CloseHandle(inputReadSide); ::CloseHandle(outputWriteSide); ::CloseHandle(inputWriteSide); @@ -336,10 +340,18 @@ IProcess* WinProcessImpl::ExecuteConPTY(wxEvtHandler* parent, const wxString& cm WinProcessImpl* prc = new WinProcessImpl(parent); ::ZeroMemory(&prc->piProcInfo, sizeof(prc->piProcInfo)); - auto fSuccess = CreateProcess(nullptr, (wchar_t*)cmd.wc_str(), nullptr, nullptr, FALSE, - EXTENDED_STARTUPINFO_PRESENT, nullptr, nullptr, &siEx.StartupInfo, &prc->piProcInfo); - - if(!fSuccess) { + auto fSuccess = CreateProcess(nullptr, + (wchar_t*)cmd.wc_str(), + nullptr, + nullptr, + FALSE, + EXTENDED_STARTUPINFO_PRESENT, + nullptr, + nullptr, + &siEx.StartupInfo, + &prc->piProcInfo); + + if (!fSuccess) { clERROR() << "Failed to launch process:" << cmd << "." << GetLastError() << endl; wxDELETE(prc); return nullptr; @@ -347,7 +359,7 @@ IProcess* WinProcessImpl::ExecuteConPTY(wxEvtHandler* parent, const wxString& cm ::CloseHandle(inputReadSide); ::CloseHandle(outputWriteSide); - if(!(prc->m_flags & IProcessCreateSync)) { + if (!(prc->m_flags & IProcessCreateSync)) { prc->StartReaderThread(); } prc->m_writerThread = new WinWriterThread(prc->piProcInfo.hProcess, inputWriteSide); @@ -361,12 +373,14 @@ IProcess* WinProcessImpl::ExecuteConPTY(wxEvtHandler* parent, const wxString& cm return prc; } -IProcess* WinProcessImpl::ExecuteConPTY(wxEvtHandler* parent, const std::vector& args, size_t flags, +IProcess* WinProcessImpl::ExecuteConPTY(wxEvtHandler* parent, + const std::vector& args, + size_t flags, const wxString& workingDir) { wxArrayString wxarr; wxarr.reserve(args.size()); - for(const auto& arg : args) { + for (const auto& arg : args) { wxarr.Add(arg); } wxString cmd = ArrayJoin(wxarr, flags); @@ -374,19 +388,18 @@ IProcess* WinProcessImpl::ExecuteConPTY(wxEvtHandler* parent, const std::vector< } /*static*/ -IProcess* WinProcessImpl::Execute(wxEvtHandler* parent, const wxString& cmd, size_t flags, const wxString& workingDir, - IProcessCallback* cb) +IProcess* WinProcessImpl::Execute( + wxEvtHandler* parent, const wxString& cmd, size_t flags, const wxString& workingDir, IProcessCallback* cb) { - if(flags & IProcessPseudoConsole) { + if (flags & IProcessPseudoConsole) { return ExecuteConPTY(parent, cmd, flags, workingDir); } SECURITY_ATTRIBUTES saAttr; BOOL fSuccess; - wxString wd(workingDir); - if(workingDir.IsEmpty()) { + if (workingDir.IsEmpty()) { wd = wxGetCwd(); } clDirChanger dg(wd); @@ -409,26 +422,31 @@ IProcess* WinProcessImpl::Execute(wxEvtHandler* parent, const wxString& cmd, siz // 4. Create a noninheritable duplicate of the read handle and // close the inheritable read handle. - if(redirectOutput) { + if (redirectOutput) { // Save the handle to the current STDOUT. prc->hSaveStdout = GetStdHandle(STD_OUTPUT_HANDLE); // Create a pipe for the child process's STDOUT. - if(!CreatePipe(&prc->hChildStdoutRd, &prc->hChildStdoutWr, &saAttr, 0)) { + if (!CreatePipe(&prc->hChildStdoutRd, &prc->hChildStdoutWr, &saAttr, 0)) { delete prc; return NULL; } // Set a write handle to the pipe to be STDOUT. - if(!SetStdHandle(STD_OUTPUT_HANDLE, prc->hChildStdoutWr)) { + if (!SetStdHandle(STD_OUTPUT_HANDLE, prc->hChildStdoutWr)) { delete prc; return NULL; } // Create noninheritable read handle and close the inheritable read handle. - fSuccess = DuplicateHandle(GetCurrentProcess(), prc->hChildStdoutRd, GetCurrentProcess(), - &prc->hChildStdoutRdDup, 0, FALSE, DUPLICATE_SAME_ACCESS); - if(!fSuccess) { + fSuccess = DuplicateHandle(GetCurrentProcess(), + prc->hChildStdoutRd, + GetCurrentProcess(), + &prc->hChildStdoutRdDup, + 0, + FALSE, + DUPLICATE_SAME_ACCESS); + if (!fSuccess) { delete prc; return NULL; } @@ -446,21 +464,26 @@ IProcess* WinProcessImpl::Execute(wxEvtHandler* parent, const wxString& cmd, siz prc->hSaveStderr = GetStdHandle(STD_ERROR_HANDLE); // Create a pipe for the child process's STDERR. - if(!CreatePipe(&prc->hChildStderrRd, &prc->hChildStderrWr, &saAttr, 0)) { + if (!CreatePipe(&prc->hChildStderrRd, &prc->hChildStderrWr, &saAttr, 0)) { delete prc; return NULL; } // Set a write handle to the pipe to be STDERR. - if(!SetStdHandle(STD_ERROR_HANDLE, prc->hChildStderrWr)) { + if (!SetStdHandle(STD_ERROR_HANDLE, prc->hChildStderrWr)) { delete prc; return NULL; } // Create noninheritable read handle and close the inheritable read handle. - fSuccess = DuplicateHandle(GetCurrentProcess(), prc->hChildStderrRd, GetCurrentProcess(), - &prc->hChildStderrRdDup, 0, FALSE, DUPLICATE_SAME_ACCESS); - if(!fSuccess) { + fSuccess = DuplicateHandle(GetCurrentProcess(), + prc->hChildStderrRd, + GetCurrentProcess(), + &prc->hChildStderrRdDup, + 0, + FALSE, + DUPLICATE_SAME_ACCESS); + if (!fSuccess) { delete prc; return NULL; } @@ -478,21 +501,24 @@ IProcess* WinProcessImpl::Execute(wxEvtHandler* parent, const wxString& cmd, siz prc->hSaveStdin = GetStdHandle(STD_INPUT_HANDLE); // Create a pipe for the child process's STDIN. - if(!CreatePipe(&prc->hChildStdinRd, &prc->hChildStdinWr, &saAttr, 0)) { + if (!CreatePipe(&prc->hChildStdinRd, &prc->hChildStdinWr, &saAttr, 0)) { delete prc; return NULL; } // Set a read handle to the pipe to be STDIN. - if(!SetStdHandle(STD_INPUT_HANDLE, prc->hChildStdinRd)) { + if (!SetStdHandle(STD_INPUT_HANDLE, prc->hChildStdinRd)) { delete prc; return NULL; } // Duplicate the write handle to the pipe so it is not inherited. - fSuccess = - DuplicateHandle(GetCurrentProcess(), prc->hChildStdinWr, GetCurrentProcess(), &prc->hChildStdinWrDup, 0, - FALSE, // not inherited - DUPLICATE_SAME_ACCESS); - if(!fSuccess) { + fSuccess = DuplicateHandle(GetCurrentProcess(), + prc->hChildStdinWr, + GetCurrentProcess(), + &prc->hChildStdinWrDup, + 0, + FALSE, // not inherited + DUPLICATE_SAME_ACCESS); + if (!fSuccess) { delete prc; return NULL; } @@ -507,7 +533,7 @@ IProcess* WinProcessImpl::Execute(wxEvtHandler* parent, const wxString& cmd, siz siStartInfo.cb = sizeof(STARTUPINFO); siStartInfo.dwFlags = STARTF_USESHOWWINDOW; - if(redirectOutput) { + if (redirectOutput) { siStartInfo.dwFlags |= STARTF_USESTDHANDLES; siStartInfo.hStdInput = prc->hChildStdinRd; siStartInfo.hStdOutput = prc->hChildStdoutWr; @@ -518,7 +544,7 @@ IProcess* WinProcessImpl::Execute(wxEvtHandler* parent, const wxString& cmd, siz siStartInfo.wShowWindow = flags & IProcessCreateConsole ? SW_SHOW : SW_HIDE; DWORD creationFlags = flags & IProcessCreateConsole ? CREATE_NEW_CONSOLE : CREATE_NO_WINDOW; - if(flags & IProcessCreateWithHiddenConsole) { + if (flags & IProcessCreateWithHiddenConsole) { siStartInfo.wShowWindow = SW_HIDE; creationFlags = CREATE_NEW_CONSOLE | CREATE_NEW_PROCESS_GROUP; } @@ -539,7 +565,7 @@ IProcess* WinProcessImpl::Execute(wxEvtHandler* parent, const wxString& cmd, siz &prc->piProcInfo); // receives PROCESS_INFORMATION } - if(ret) { + if (ret) { prc->dwProcessId = prc->piProcInfo.dwProcessId; } else { int err = GetLastError(); @@ -548,31 +574,31 @@ IProcess* WinProcessImpl::Execute(wxEvtHandler* parent, const wxString& cmd, siz return NULL; } - if(redirectOutput) { + if (redirectOutput) { // After process creation, restore the saved STDIN and STDOUT. - if(!SetStdHandle(STD_INPUT_HANDLE, prc->hSaveStdin)) { + if (!SetStdHandle(STD_INPUT_HANDLE, prc->hSaveStdin)) { delete prc; return NULL; } - if(!SetStdHandle(STD_OUTPUT_HANDLE, prc->hSaveStdout)) { + if (!SetStdHandle(STD_OUTPUT_HANDLE, prc->hSaveStdout)) { delete prc; return NULL; } - if(!SetStdHandle(STD_OUTPUT_HANDLE, prc->hSaveStderr)) { + if (!SetStdHandle(STD_OUTPUT_HANDLE, prc->hSaveStderr)) { delete prc; return NULL; } } - if((prc->m_flags & IProcessCreateConsole) || (prc->m_flags & IProcessCreateWithHiddenConsole)) { + if ((prc->m_flags & IProcessCreateConsole) || (prc->m_flags & IProcessCreateWithHiddenConsole)) { ConsoleAttacher ca(prc->GetPid()); - if(ca.isAttached) { + if (ca.isAttached) { freopen("CONOUT$", "wb", stdout); // reopen stout handle as console window output freopen("CONOUT$", "wb", stderr); // reopen stderr handle as console window output } } prc->SetPid(prc->dwProcessId); - if(!(prc->m_flags & IProcessCreateSync)) { + if (!(prc->m_flags & IProcessCreateSync)) { prc->StartReaderThread(); } prc->m_writerThread = new WinWriterThread(prc->piProcInfo.hProcess, prc->hChildStdinWrDup); @@ -604,37 +630,37 @@ bool WinProcessImpl::Read(wxString& buff, wxString& buffErr, std::string& raw_bu buffErr.clear(); // Sanity - if(!IsRedirect()) { + if (!IsRedirect()) { return false; } // Read data from STDOUT and STDERR - if(m_flags & IProcessStderrEvent) { + if (m_flags & IProcessStderrEvent) { // we want separate stderr events - if(!DoReadFromPipe(hChildStderrRdDup, buffErr, raw_buff_err)) { + if (!DoReadFromPipe(hChildStderrRdDup, buffErr, raw_buff_err)) { le2 = GetLastError(); } } else { - if(!DoReadFromPipe(hChildStderrRdDup, buff, raw_buff)) { + if (!DoReadFromPipe(hChildStderrRdDup, buff, raw_buff)) { le2 = GetLastError(); } } // read stdout - if(!DoReadFromPipe(hChildStdoutRdDup, buff, raw_buff)) { + if (!DoReadFromPipe(hChildStdoutRdDup, buff, raw_buff)) { le1 = GetLastError(); } - if((le1 == ERROR_NO_DATA) && (le2 == ERROR_NO_DATA)) { - if(IsAlive()) { + if ((le1 == ERROR_NO_DATA) && (le2 == ERROR_NO_DATA)) { + if (IsAlive()) { wxThread::Sleep(1); return true; } } bool success = !buff.empty() || !buffErr.empty(); - if(!success) { + if (!success) { DWORD dwExitCode; - if(GetExitCodeProcess(piProcInfo.hProcess, &dwExitCode)) { + if (GetExitCodeProcess(piProcInfo.hProcess, &dwExitCode)) { SetProcessExitCode(GetPid(), (int)dwExitCode); } } @@ -654,7 +680,7 @@ bool WinProcessImpl::WriteRaw(const wxString& buff) { return WriteRaw(StringUtil bool WinProcessImpl::WriteRaw(const std::string& buff) { // Sanity - if(!IsRedirect()) { + if (!IsRedirect()) { return false; } m_writerThread->Write(buff); @@ -664,8 +690,8 @@ bool WinProcessImpl::WriteRaw(const std::string& buff) bool WinProcessImpl::IsAlive() { DWORD dwExitCode; - if(GetExitCodeProcess(piProcInfo.hProcess, &dwExitCode)) { - if(dwExitCode == STILL_ACTIVE) + if (GetExitCodeProcess(piProcInfo.hProcess, &dwExitCode)) { + if (dwExitCode == STILL_ACTIVE) return true; } return false; @@ -673,25 +699,25 @@ bool WinProcessImpl::IsAlive() inline void CLOSE_HANDLE(HANDLE h) { - if(h != INVALID_HANDLE_VALUE) { + if (h != INVALID_HANDLE_VALUE) { ::CloseHandle(h); } } void WinProcessImpl::Cleanup() { - if(m_writerThread) { + if (m_writerThread) { m_writerThread->Stop(); wxDELETE(m_writerThread); } - if(m_hPseudoConsole) { + if (m_hPseudoConsole) { ClosePseudoConsoleFunc(m_hPseudoConsole); m_hPseudoConsole = nullptr; } // Under windows, the reader thread is detached - if(m_thr) { + if (m_thr) { // Stop the reader thread m_thr->Stop(); delete m_thr; @@ -699,7 +725,7 @@ void WinProcessImpl::Cleanup() m_thr = NULL; // terminate the process - if(IsAlive()) { + if (IsAlive()) { const auto tree = ProcUtils::GetProcTree(GetPid()); for (const auto& pid : tree) { @@ -714,7 +740,7 @@ void WinProcessImpl::Cleanup() ::TerminateProcess(piProcInfo.hProcess, 0); } - if(IsRedirect()) { + if (IsRedirect()) { CLOSE_HANDLE(hChildStdinRd); CLOSE_HANDLE(hChildStdinWrDup); CLOSE_HANDLE(hChildStdoutWr); @@ -751,7 +777,7 @@ bool WinProcessImpl::DoReadFromPipe(HANDLE pipe, wxString& buff, std::string& ra DWORD dwMode; DWORD dwTimeout; - if(pipe == INVALID_HANDLE_VALUE || pipe == 0x0) { + if (pipe == INVALID_HANDLE_VALUE || pipe == 0x0) { SetLastError(ERROR_NO_DATA); return false; } @@ -762,16 +788,16 @@ bool WinProcessImpl::DoReadFromPipe(HANDLE pipe, wxString& buff, std::string& ra SetNamedPipeHandleState(pipe, &dwMode, NULL, &dwTimeout); bool read_something = false; - while(true) { + while (true) { BOOL bRes = ReadFile(pipe, m_buffer, BUFFER_SIZE - 1, &dwRead, NULL); - if(bRes && (dwRead > 0)) { + if (bRes && (dwRead > 0)) { wxString tmpBuff; tmpBuff.reserve(dwRead * 2); // make enough room for the conversion raw_buff.append(m_buffer, dwRead); // Success read tmpBuff = wxString(m_buffer, wxConvUTF8, dwRead); - if(tmpBuff.IsEmpty() && dwRead > 0) { + if (tmpBuff.IsEmpty() && dwRead > 0) { // conversion failed tmpBuff = wxString::From8BitData(m_buffer, dwRead); } @@ -788,7 +814,7 @@ bool WinProcessImpl::DoReadFromPipe(HANDLE pipe, wxString& buff, std::string& ra void WinProcessImpl::Terminate() { // terminate the process - if(IsAlive()) { + if (IsAlive()) { const std::set tree = ProcUtils::GetProcTree(GetPid()); for (const auto& pid : tree) { @@ -809,23 +835,23 @@ bool WinProcessImpl::WriteToConsole(const wxString& buff) pass.Trim().Trim(false); // To write password, we need to attach to the child process console - if(!(m_flags & (IProcessCreateWithHiddenConsole | IProcessCreateConsole))) + if (!(m_flags & (IProcessCreateWithHiddenConsole | IProcessCreateConsole))) return false; ConsoleAttacher ca(GetPid()); - if(ca.isAttached == false) + if (ca.isAttached == false) return false; - HANDLE hStdIn = ::CreateFile(L"CONIN$", GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, - OPEN_EXISTING, 0, 0); - if(hStdIn == INVALID_HANDLE_VALUE) { + HANDLE hStdIn = ::CreateFile( + L"CONIN$", GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0); + if (hStdIn == INVALID_HANDLE_VALUE) { return false; } pass += wxT("\r\n"); std::vector pKeyEvents(pass.Len()); - for(size_t i = 0; i < pass.Len(); i++) { + for (size_t i = 0; i < pass.Len(); i++) { pKeyEvents[i].EventType = KEY_EVENT; pKeyEvents[i].Event.KeyEvent.bKeyDown = TRUE; pKeyEvents[i].Event.KeyEvent.wRepeatCount = 1; @@ -836,7 +862,7 @@ bool WinProcessImpl::WriteToConsole(const wxString& buff) } DWORD dwTextWritten; - if(::WriteConsoleInput(hStdIn, pKeyEvents.data(), pass.Len(), &dwTextWritten) == FALSE) { + if (::WriteConsoleInput(hStdIn, pKeyEvents.data(), pass.Len(), &dwTextWritten) == FALSE) { CloseHandle(hStdIn); return false; } @@ -846,7 +872,7 @@ bool WinProcessImpl::WriteToConsole(const wxString& buff) void WinProcessImpl::Detach() { - if(m_thr) { + if (m_thr) { // Stop the reader thread m_thr->Stop(); delete m_thr; diff --git a/CodeLite/AsyncProcess/winprocess_impl.h b/CodeLite/AsyncProcess/winprocess_impl.h index 16f1bfe63f..e59674e1c0 100644 --- a/CodeLite/AsyncProcess/winprocess_impl.h +++ b/CodeLite/AsyncProcess/winprocess_impl.h @@ -54,20 +54,28 @@ class WXDLLIMPEXP_CL WinProcessImpl : public IProcess ~WinProcessImpl() override; // Create process asynchronously and return a process object - static IProcess* Execute(wxEvtHandler* parent, const wxString& cmd, size_t flags = IProcessCreateDefault, - const wxString& workingDir = wxEmptyString, IProcessCallback* cb = NULL); + static IProcess* Execute(wxEvtHandler* parent, + const wxString& cmd, + size_t flags = IProcessCreateDefault, + const wxString& workingDir = wxEmptyString, + IProcessCallback* cb = NULL); // Create process asynchronously and return a process object - static IProcess* Execute(wxEvtHandler* parent, const wxArrayString& args, size_t flags = IProcessCreateDefault, - const wxString& workingDir = wxEmptyString, IProcessCallback* cb = NULL); + static IProcess* Execute(wxEvtHandler* parent, + const wxArrayString& args, + size_t flags = IProcessCreateDefault, + const wxString& workingDir = wxEmptyString, + IProcessCallback* cb = NULL); // Create process asynchronously and return a process object - static IProcess* ExecuteConPTY(wxEvtHandler* parent, const std::vector& args, + static IProcess* ExecuteConPTY(wxEvtHandler* parent, + const std::vector& args, size_t flags = IProcessCreateWithHiddenConsole, const wxString& workingDir = wxEmptyString); // Create process asynchronously and return a process object - static IProcess* ExecuteConPTY(wxEvtHandler* parent, const wxString& cmd, + static IProcess* ExecuteConPTY(wxEvtHandler* parent, + const wxString& cmd, size_t flags = IProcessCreateWithHiddenConsole, const wxString& workingDir = wxEmptyString); @@ -103,7 +111,7 @@ class WXDLLIMPEXP_CL WinProcessImpl : public IProcess hChildStderrRd = INVALID_HANDLE_VALUE, hChildStderrWr = INVALID_HANDLE_VALUE, hChildStderrRdDup = INVALID_HANDLE_VALUE, hSaveStdin = INVALID_HANDLE_VALUE, hSaveStdout = INVALID_HANDLE_VALUE, hSaveStderr = INVALID_HANDLE_VALUE; - + VOID* m_hPseudoConsole = nullptr; // Child process id & information DWORD dwProcessId = wxNOT_FOUND; diff --git a/CodeLite/BreakpointInfoArray.cpp b/CodeLite/BreakpointInfoArray.cpp index 42a5ac94e9..14978d6449 100644 --- a/CodeLite/BreakpointInfoArray.cpp +++ b/CodeLite/BreakpointInfoArray.cpp @@ -4,10 +4,10 @@ void BreakpointInfoArray::DeSerialize(Archive& arch) { size_t bt_count = 0; m_breakpoints.clear(); - if(!arch.Read("Count", bt_count)) + if (!arch.Read("Count", bt_count)) return; - for(size_t i = 0; i < bt_count; i++) { + for (size_t i = 0; i < bt_count; i++) { wxString name; name << "Breakpoint" << i; clDebuggerBreakpoint bkpt; @@ -19,7 +19,7 @@ void BreakpointInfoArray::DeSerialize(Archive& arch) void BreakpointInfoArray::Serialize(Archive& arch) { arch.Write(wxT("Count"), (size_t)m_breakpoints.size()); - for(size_t i = 0; i < m_breakpoints.size(); i++) { + for (size_t i = 0; i < m_breakpoints.size(); i++) { wxString name; name << "Breakpoint" << i; arch.Write(name, (SerializedObject*)&m_breakpoints[i]); diff --git a/CodeLite/BreakpointInfoArray.hpp b/CodeLite/BreakpointInfoArray.hpp index fee3021027..ba1e1dff58 100644 --- a/CodeLite/BreakpointInfoArray.hpp +++ b/CodeLite/BreakpointInfoArray.hpp @@ -14,7 +14,7 @@ class WXDLLIMPEXP_CL BreakpointInfoArray : public SerializedObject virtual ~BreakpointInfoArray() = default; void SetBreakpoints(const clDebuggerBreakpoint::Vec_t& breakpoints) { this->m_breakpoints = breakpoints; } const clDebuggerBreakpoint::Vec_t& GetBreakpoints() const { return m_breakpoints; } - + void DeSerialize(Archive& arch) override; void Serialize(Archive& arch) override; }; diff --git a/CodeLite/CTags.cpp b/CodeLite/CTags.cpp index 3409a60c9e..0b729db9d1 100644 --- a/CodeLite/CTags.cpp +++ b/CodeLite/CTags.cpp @@ -17,7 +17,7 @@ thread_local bool is_macrodef_supported = false; wxString CTags::WrapSpaces(const wxString& file) { wxString fixed = file; - if(fixed.Contains(" ")) { + if (fixed.Contains(" ")) { fixed.Prepend("\"").Append("\""); } return fixed; @@ -28,13 +28,16 @@ wxString fix_macro_entry(const wxString& macro) { wxString fixed = macro; fixed.Replace("%", "__arg_"); - //fixed.Replace("\"", "\\\""); + // fixed.Replace("\"", "\\\""); return fixed; } } // namespace -bool CTags::DoGenerate(const wxString& filesContent, const wxString& codelite_indexer, const wxStringMap_t& macro_table, - const wxString& ctags_kinds, wxString* output) +bool CTags::DoGenerate(const wxString& filesContent, + const wxString& codelite_indexer, + const wxStringMap_t& macro_table, + const wxString& ctags_kinds, + wxString* output) { Initialise(codelite_indexer); clDEBUG() << "Generating ctags files" << clEndl; @@ -44,15 +47,15 @@ bool CTags::DoGenerate(const wxString& filesContent, const wxString& codelite_in std::vector options_arr; options_arr.reserve(500); wxString fields_cxx = "--fields-c++=+{template}+{properties}"; - if(is_macrodef_supported) { + if (is_macrodef_supported) { fields_cxx << "+{macrodef}"; } - options_arr = { "--extras=-p", "--excmd=pattern", "--sort=no", - "--fields=aKmSsnit", "--language-force=c++", fields_cxx }; + options_arr = { + "--extras=-p", "--excmd=pattern", "--sort=no", "--fields=aKmSsnit", "--language-force=c++", fields_cxx}; wxString kinds_string; - if(ctags_kinds.empty()) { + if (ctags_kinds.empty()) { // default kinds_string << " --c-kinds=+pxz --C++-kinds=+pxz "; } else { @@ -61,12 +64,12 @@ bool CTags::DoGenerate(const wxString& filesContent, const wxString& codelite_in // we want the macros ordered, so we push them into std::set std::set macros; - for(const auto& vt : macro_table) { + for (const auto& vt : macro_table) { wxString macro_replacements; wxString fixed_macro_name = fix_macro_entry(vt.first); wxString fixed_macro_value = fix_macro_entry(vt.second); - if(fixed_macro_value.empty()) { + if (fixed_macro_value.empty()) { // simple -D macro_replacements << "-D" << fixed_macro_name; } else { @@ -78,17 +81,17 @@ bool CTags::DoGenerate(const wxString& filesContent, const wxString& codelite_in } // write the options into a file - wxFileName ctags_options_file(clStandardPaths::Get().GetUserDataDir(), - wxString() << "options-" << wxThread::GetCurrentId() << ".ctags"); - FileUtils::Deleter d{ ctags_options_file }; + wxFileName ctags_options_file( + clStandardPaths::Get().GetUserDataDir(), wxString() << "options-" << wxThread::GetCurrentId() << ".ctags"); + FileUtils::Deleter d{ctags_options_file}; wxString ctags_options_file_content; - for(const wxString& option : options_arr) { + for (const wxString& option : options_arr) { ctags_options_file_content << option << "\n"; } // append the macros - for(const auto& macro : macros) { + for (const auto& macro : macros) { ctags_options_file_content << macro << "\n"; } ctags_options_file_content.Trim(); @@ -99,8 +102,8 @@ bool CTags::DoGenerate(const wxString& filesContent, const wxString& codelite_in sw.Start(); // Split the list of files - wxFileName file_list(clStandardPaths::Get().GetTempDir(), - wxString() << "file-list-" << wxThread::GetCurrentId() << ".txt"); + wxFileName file_list( + clStandardPaths::Get().GetTempDir(), wxString() << "file-list-" << wxThread::GetCurrentId() << ".txt"); FileUtils::WriteFileContent(file_list, filesContent); wxString command_to_run; @@ -118,15 +121,17 @@ bool CTags::DoGenerate(const wxString& filesContent, const wxString& codelite_in return true; } -size_t CTags::ParseFiles(const std::vector& files, const wxString& codelite_indexer, - const wxStringMap_t& macro_table, std::vector& tags) +size_t CTags::ParseFiles(const std::vector& files, + const wxString& codelite_indexer, + const wxStringMap_t& macro_table, + std::vector& tags) { wxString filesList; - for(const auto& file : files) { + for (const auto& file : files) { filesList << file << "\n"; } wxString content; - if(!DoGenerate(filesList, codelite_indexer, macro_table, wxEmptyString, &content)) { + if (!DoGenerate(filesList, codelite_indexer, macro_table, wxEmptyString, &content)) { return 0; } @@ -136,9 +141,9 @@ size_t CTags::ParseFiles(const std::vector& files, const wxString& cod // convert the lines into tags TagEntryPtr prev_scoped_tag = nullptr; - for(wxString& line : lines) { + for (wxString& line : lines) { line.Trim(false).Trim(); - if(line.empty()) { + if (line.empty()) { continue; } @@ -147,18 +152,18 @@ size_t CTags::ParseFiles(const std::vector& files, const wxString& cod auto tag = tags.back(); tag->FromLine(line); - if(tag->IsEnumerator() // looking at an enumerator - && prev_scoped_tag // we have a previously seen scope - && prev_scoped_tag->GetFile() == tag->GetFile() /// and they are on the same file - && prev_scoped_tag->GetName() == tag->GetParent()) // and it belongs to it + if (tag->IsEnumerator() // looking at an enumerator + && prev_scoped_tag // we have a previously seen scope + && prev_scoped_tag->GetFile() == tag->GetFile() /// and they are on the same file + && prev_scoped_tag->GetName() == tag->GetParent()) // and it belongs to it { // remove one part of the scope wxArrayString scopes = ::wxStringTokenize(tag->GetScope(), ":", wxTOKEN_STRTOK); - if(scopes.size()) { + if (scopes.size()) { scopes.pop_back(); // remove the last part of the scope wxString new_scope; - for(const wxString& scope : scopes) { - if(!new_scope.empty()) { + for (const wxString& scope : scopes) { + if (!new_scope.empty()) { new_scope << "::"; } new_scope << scope; @@ -168,25 +173,30 @@ size_t CTags::ParseFiles(const std::vector& files, const wxString& cod } } - if(tag->IsEnum()) { + if (tag->IsEnum()) { prev_scoped_tag = tag; } } - if(tags.empty()) { + if (tags.empty()) { clDEBUG() << "0 tags, ctags output:" << content << endl; } return tags.size(); } -size_t CTags::ParseFile(const wxString& file, const wxString& codelite_indexer, const wxStringMap_t& macro_table, +size_t CTags::ParseFile(const wxString& file, + const wxString& codelite_indexer, + const wxStringMap_t& macro_table, std::vector& tags) { - return ParseFiles({ file }, codelite_indexer, macro_table, tags); + return ParseFiles({file}, codelite_indexer, macro_table, tags); } -size_t CTags::ParseBuffer(const wxFileName& filename, const wxString& buffer, const wxString& codelite_indexer, - const wxStringMap_t& macro_table, std::vector& tags) +size_t CTags::ParseBuffer(const wxFileName& filename, + const wxString& buffer, + const wxString& codelite_indexer, + const wxStringMap_t& macro_table, + std::vector& tags) { // create a temporary file with the content we want to parse clTempFile temp_file("cpp"); @@ -194,14 +204,17 @@ size_t CTags::ParseBuffer(const wxFileName& filename, const wxString& buffer, co // parse the file ParseFile(temp_file.GetFileName().GetFullPath(), codelite_indexer, macro_table, tags); // set the file name to the correct file - for(TagEntryPtr tag : tags) { + for (TagEntryPtr tag : tags) { tag->SetFile(filename.GetFullPath()); } return tags.size(); } -size_t CTags::ParseLocals(const wxFileName& filename, const wxString& buffer, const wxString& codelite_indexer, - const wxStringMap_t& macro_table, std::vector& tags) +size_t CTags::ParseLocals(const wxFileName& filename, + const wxString& buffer, + const wxString& codelite_indexer, + const wxStringMap_t& macro_table, + std::vector& tags) { wxString content; { @@ -212,7 +225,7 @@ size_t CTags::ParseLocals(const wxFileName& filename, const wxString& buffer, co filesList << temp_file.GetFullPath() << "\n"; // we want locals + functions (to resolve the scope) - if(!DoGenerate(filesList, codelite_indexer, macro_table, "lzpvfm", &content)) { + if (!DoGenerate(filesList, codelite_indexer, macro_table, "lzpvfm", &content)) { return 0; } } @@ -222,9 +235,9 @@ size_t CTags::ParseLocals(const wxFileName& filename, const wxString& buffer, co tags.reserve(lines.size()); // convert the lines into tags - for(auto& line : lines) { + for (auto& line : lines) { line.Trim().Trim(false); - if(line.empty()) { + if (line.empty()) { continue; } @@ -235,7 +248,7 @@ size_t CTags::ParseLocals(const wxFileName& filename, const wxString& buffer, co tag->SetFile(filename.GetFullPath()); } - if(tags.empty()) { + if (tags.empty()) { clDEBUG() << "0 local tags, ctags output:" << content << endl; } return tags.size(); @@ -243,22 +256,22 @@ size_t CTags::ParseLocals(const wxFileName& filename, const wxString& buffer, co void CTags::Initialise(const wxString& codelite_indexer) { - if(is_initialised) { + if (is_initialised) { return; } is_initialised = true; // check whether we have `macrodef` supported wxString output; - std::vector command = { codelite_indexer, "--list-fields=c++" }; + std::vector command = {codelite_indexer, "--list-fields=c++"}; auto process = ::CreateAsyncProcess(nullptr, command, IProcessCreateSync, wxEmptyString, nullptr, wxEmptyString); - if(process) { + if (process) { process->WaitForTerminate(output); } wxArrayString lines = ::wxStringTokenize(output, "\n", wxTOKEN_STRTOK); - for(const auto& line : lines) { - if(line.Contains("macrodef")) { + for (const auto& line : lines) { + if (line.Contains("macrodef")) { is_macrodef_supported = true; break; } diff --git a/CodeLite/CTags.hpp b/CodeLite/CTags.hpp index d3676df037..56bbd4a064 100644 --- a/CodeLite/CTags.hpp +++ b/CodeLite/CTags.hpp @@ -21,8 +21,10 @@ class WXDLLIMPEXP_CL CTags * @param output if provided, holds the ctags content * @return true on success, false otherwise */ - static bool DoGenerate(const wxString& filesContent, const wxString& codelite_indexer, - const wxStringMap_t& macro_table, const wxString& ctags_kinds = wxEmptyString, + static bool DoGenerate(const wxString& filesContent, + const wxString& codelite_indexer, + const wxStringMap_t& macro_table, + const wxString& ctags_kinds = wxEmptyString, wxString* output = nullptr); static void Initialise(const wxString& codelite_indexer); @@ -31,25 +33,35 @@ class WXDLLIMPEXP_CL CTags /** * @brief given a list of files, generate an output tags file and place it under 'path' */ - static size_t ParseFiles(const std::vector& files, const wxString& codelite_indexer, - const wxStringMap_t& macro_table, std::vector& tags); + static size_t ParseFiles(const std::vector& files, + const wxString& codelite_indexer, + const wxStringMap_t& macro_table, + std::vector& tags); /** * @brief given a list of files, generate an output tags file and place it under 'path' */ - static size_t ParseFile(const wxString& file, const wxString& codelite_indexer, const wxStringMap_t& macro_table, + static size_t ParseFile(const wxString& file, + const wxString& codelite_indexer, + const wxStringMap_t& macro_table, std::vector& tags); /** * @brief run codelite-indexer on a buffer and return list of tags */ - static size_t ParseBuffer(const wxFileName& filename, const wxString& buffer, const wxString& codelite_indexer, - const wxStringMap_t& macro_table, std::vector& tags); + static size_t ParseBuffer(const wxFileName& filename, + const wxString& buffer, + const wxString& codelite_indexer, + const wxStringMap_t& macro_table, + std::vector& tags); /** * @brief parse list of local variables from a given source file */ - static size_t ParseLocals(const wxFileName& filename, const wxString& buffer, const wxString& codelite_indexer, - const wxStringMap_t& macro_table, std::vector& tags); + static size_t ParseLocals(const wxFileName& filename, + const wxString& buffer, + const wxString& codelite_indexer, + const wxStringMap_t& macro_table, + std::vector& tags); }; #endif // CTAGSGENERATOR_HPP diff --git a/CodeLite/CompletionHelper.cpp b/CodeLite/CompletionHelper.cpp index ec160cf001..a66766036d 100644 --- a/CodeLite/CompletionHelper.cpp +++ b/CodeLite/CompletionHelper.cpp @@ -39,10 +39,10 @@ wxString wrap_lines(const wxString& str) } curLineBytes++; - if(curLineBytes == MAX_TIP_LINE_SIZE) { + if (curLineBytes == MAX_TIP_LINE_SIZE) { // Wrap the lines - if(wrappedString.IsEmpty() == false && wrappedString.Last() != '\n') { + if (wrappedString.IsEmpty() == false && wrappedString.Last() != '\n') { wrappedString << "\n"; } curLineBytes = 0; @@ -64,19 +64,19 @@ wxString CompletionHelper::get_expression(const wxString& file_content, bool for std::vector> tokens; tokens.reserve(10000); - while(tokenizer.NextToken(token)) { - tokens.push_back({ token.GetWXString(), token.GetType() }); + while (tokenizer.NextToken(token)) { + tokens.push_back({token.GetWXString(), token.GetType()}); } int i = static_cast(tokens.size() - 1); bool cont = true; int parentheses_depth = 0; - if(for_calltip) { + if (for_calltip) { // read backwards until we find the first open parentheses - for(; (i >= 0) && cont; --i) { - switch(tokens[i].second) { + for (; (i >= 0) && cont; --i) { + switch (tokens[i].second) { case '(': - if(parentheses_depth == 0) { + if (parentheses_depth == 0) { cont = false; } else { parentheses_depth--; @@ -95,15 +95,15 @@ wxString CompletionHelper::get_expression(const wxString& file_content, bool for std::vector types; int depth = 0; cont = true; - for(; (i >= 0) && cont; --i) { + for (; (i >= 0) && cont; --i) { const wxString& text = tokens[i].first; int type = tokens[i].second; - switch(type) { + switch (type) { case '[': case '{': case '(': case '<': - if(depth == 0) { + if (depth == 0) { cont = false; } else { PREPEND_STRING(text); @@ -113,7 +113,7 @@ wxString CompletionHelper::get_expression(const wxString& file_content, bool for case '>': case ']': case ')': - if(depth == 0 && LAST_TOKEN_IS(T_IDENTIFIER)) { + if (depth == 0 && LAST_TOKEN_IS(T_IDENTIFIER)) { cont = false; } else { PREPEND_STRING(text); @@ -121,7 +121,7 @@ wxString CompletionHelper::get_expression(const wxString& file_content, bool for } break; case '}': - if(depth == 0) { + if (depth == 0) { cont = false; } else { PREPEND_STRING(text); @@ -159,14 +159,14 @@ wxString CompletionHelper::get_expression(const wxString& file_content, bool for cont = false; break; case '=': - if(depth == 0) { + if (depth == 0) { cont = false; } else { PREPEND_STRING(text); } break; case T_IDENTIFIER: - if(LAST_TOKEN_IS(T_IDENTIFIER)) { + if (LAST_TOKEN_IS(T_IDENTIFIER)) { // we do not allow two consecutive T_IDENTIFIER cont = false; break; @@ -292,7 +292,7 @@ wxString CompletionHelper::get_expression(const wxString& file_content, bool for case ':': case '-': case '@': - if(depth <= 0) { + if (depth <= 0) { cont = false; } else { PREPEND_STRING(text); @@ -311,28 +311,30 @@ wxString CompletionHelper::get_expression(const wxString& file_content, bool for // build the expression from the vector wxString expression_string; - for(const auto& t : expression) { + for (const auto& t : expression) { expression_string << t; } - if(last_word && !expression.empty()) { + if (last_word && !expression.empty()) { *last_word = expression[expression.size() - 1]; } return expression_string; #undef LAST_TOKEN_IS } -wxString CompletionHelper::truncate_file_to_location(const wxString& file_content, size_t line, size_t column, +wxString CompletionHelper::truncate_file_to_location(const wxString& file_content, + size_t line, + size_t column, size_t flags) const { size_t curline = 0; size_t offset = 0; // locate the line - for(const auto& ch : file_content) { - if(curline == line) { + for (const auto& ch : file_content) { + if (curline == line) { break; } - switch(ch.GetValue()) { + switch (ch.GetValue()) { case '\n': ++curline; ++offset; @@ -343,23 +345,23 @@ wxString CompletionHelper::truncate_file_to_location(const wxString& file_conten } } - if(curline != line) { + if (curline != line) { return wxEmptyString; } // columns offset += column; - if(offset < file_content.size()) { - if(flags & (TRUNCATE_COMPLETE_WORDS | TRUNCATE_COMPLETE_LINES)) { - while(true) { + if (offset < file_content.size()) { + if (flags & (TRUNCATE_COMPLETE_WORDS | TRUNCATE_COMPLETE_LINES)) { + while (true) { size_t next_pos = offset; - if(next_pos < file_content.size()) { + if (next_pos < file_content.size()) { wxChar next_char = file_content[next_pos]; - if(flags & TRUNCATE_COMPLETE_WORDS) { + if (flags & TRUNCATE_COMPLETE_WORDS) { // complete words only - if(is_word_char(next_char)) { + if (is_word_char(next_char)) { offset += 1; } else { break; @@ -367,7 +369,7 @@ wxString CompletionHelper::truncate_file_to_location(const wxString& file_conten } else { // TRUNCATE_COMPLETE_LINES - if(next_char == '\n') { + if (next_char == '\n') { break; } else { offset += 1; @@ -388,7 +390,7 @@ namespace { void populate_keywords() { - if(words.empty()) { + if (words.empty()) { words.insert("auto"); words.insert("break"); words.insert("case"); @@ -472,15 +474,15 @@ bool CompletionHelper::is_cxx_keyword(const wxString& word) return words.count(word) != 0; } -std::vector CompletionHelper::split_function_signature(const wxString& signature, wxString* return_value, - size_t flags) const +std::vector +CompletionHelper::split_function_signature(const wxString& signature, wxString* return_value, size_t flags) const { // --------------------------------------------------------------------------------------------- // ----------------macros start------------------------------------------------------------------- // --------------------------------------------------------------------------------------------- #define ADD_CURRENT_PARAM(current_param) \ current_param->Trim().Trim(false); \ - if(!current_param->empty()) { \ + if (!current_param->empty()) { \ args.push_back(*current_param); \ } \ current_param->clear(); @@ -491,13 +493,13 @@ std::vector CompletionHelper::split_function_signature(const wxString& #define LAST_TOKEN_IS_ONE_OF_5(t1, t2, t3, t4, t5) (LAST_TOKEN_IS_ONE_OF_4(t1, t2, t3, t4) || LAST_TOKEN_IS(t5)) #define LAST_TOKEN_IS_CLOSING_PARENTHESES() LAST_TOKEN_IS_ONE_OF_4('}', ']', '>', ')') #define LAST_TOKEN_IS_OPEN_PARENTHESES() LAST_TOKEN_IS_ONE_OF_4('{', '[', '<', '(') -#define REMOVE_TRAILING_SPACE() \ - if(!current_param->empty() && (*current_param)[current_param->size() - 1] == ' ') { \ - current_param->RemoveLast(); \ +#define REMOVE_TRAILING_SPACE() \ + if (!current_param->empty() && (*current_param)[current_param->size() - 1] == ' ') { \ + current_param->RemoveLast(); \ } -#define APPEND_SPACE_IF_MISSING() \ - if(!current_param->empty() && ((*current_param)[current_param->size() - 1] != ' ')) { \ - current_param->Append(" "); \ +#define APPEND_SPACE_IF_MISSING() \ + if (!current_param->empty() && ((*current_param)[current_param->size() - 1] != ' ')) { \ + current_param->Append(" "); \ } // --------------------------------------------------------------------------------------------- @@ -516,8 +518,8 @@ std::vector CompletionHelper::split_function_signature(const wxString& std::vector types; // search for the first opening brace - while(tokenizer.NextToken(token)) { - if(token.GetType() == '(') { + while (tokenizer.NextToken(token)) { + if (token.GetType() == '(') { depth = 1; break; } @@ -527,12 +529,12 @@ std::vector CompletionHelper::split_function_signature(const wxString& constexpr int STATE_NORMAL = 0; constexpr int STATE_DEFAULT_VALUE = 1; int state = STATE_NORMAL; - while(tokenizer.NextToken(token)) { - switch(state) { + while (tokenizer.NextToken(token)) { + switch (state) { case STATE_DEFAULT_VALUE: // consume everything until we reach signature end // or until we hit a "," (where depth==1) - switch(token.GetType()) { + switch (token.GetType()) { case '<': case '{': case '(': @@ -546,7 +548,7 @@ std::vector CompletionHelper::split_function_signature(const wxString& break; case ')': depth--; - if(depth == 0) { + if (depth == 0) { // end of argument reading, switch back to the normal state tokenizer.UngetToken(); // restore the depth @@ -555,7 +557,7 @@ std::vector CompletionHelper::split_function_signature(const wxString& } break; case ',': - if(depth == 1) { + if (depth == 1) { tokenizer.UngetToken(); state = STATE_NORMAL; } @@ -565,7 +567,7 @@ std::vector CompletionHelper::split_function_signature(const wxString& } break; case STATE_NORMAL: - switch(token.GetType()) { + switch (token.GetType()) { case T_ALIGNAS: case T_ALIGNOF: case T_AND: @@ -679,7 +681,7 @@ std::vector CompletionHelper::split_function_signature(const wxString& APPEND_SPACE_IF_MISSING(); break; case '*': - if(LAST_TOKEN_IS('*')) { + if (LAST_TOKEN_IS('*')) { REMOVE_TRAILING_SPACE(); } current_param->Append(token.GetWXString()); @@ -690,27 +692,27 @@ std::vector CompletionHelper::split_function_signature(const wxString& bool add_identifier = true; int next_token_type = tokenizer.PeekToken(peeked_token_text); // Check if we want to ignore the argument name - if((depth == 1) && (next_token_type == ',' || next_token_type == '=' || next_token_type == ')') && - (flags & STRIP_NO_NAME)) { + if ((depth == 1) && (next_token_type == ',' || next_token_type == '=' || next_token_type == ')') && + (flags & STRIP_NO_NAME)) { // two consecutive T_IDENTIFIER, don't add it add_identifier = false; - } else if(LAST_TOKEN_IS_CLOSING_PARENTHESES() || LAST_TOKEN_IS_ONE_OF_2(T_IDENTIFIER, '*')) { + } else if (LAST_TOKEN_IS_CLOSING_PARENTHESES() || LAST_TOKEN_IS_ONE_OF_2(T_IDENTIFIER, '*')) { APPEND_SPACE_IF_MISSING(); } - if(add_identifier) { + if (add_identifier) { current_param->Append(token.GetWXString()); } } break; case T_ARROW: - if(done_collecting_args) { + if (done_collecting_args) { // we are collecting function return value now, disregard it } else { current_param->Append(token.GetWXString()); } break; case ',': - if(depth == 1) { + if (depth == 1) { ADD_CURRENT_PARAM(current_param); } else { current_param->Append(","); @@ -726,13 +728,13 @@ std::vector CompletionHelper::split_function_signature(const wxString& break; case ')': depth--; - if(!done_collecting_args && depth == 0) { + if (!done_collecting_args && depth == 0) { // reached signature end ADD_CURRENT_PARAM(current_param); func_args.swap(args); done_collecting_args = true; } else { - if(LAST_TOKEN_IS_CLOSING_PARENTHESES() || LAST_TOKEN_IS(T_IDENTIFIER)) { + if (LAST_TOKEN_IS_CLOSING_PARENTHESES() || LAST_TOKEN_IS(T_IDENTIFIER)) { REMOVE_TRAILING_SPACE(); } current_param->Append(token.GetWXString()); @@ -747,7 +749,7 @@ std::vector CompletionHelper::split_function_signature(const wxString& current_param->Append(token.GetWXString()); break; case '=': - if((depth == 1) && (flags & STRIP_NO_DEFAULT_VALUES)) { + if ((depth == 1) && (flags & STRIP_NO_DEFAULT_VALUES)) { state = STATE_DEFAULT_VALUE; } else { APPEND_SPACE_IF_MISSING(); @@ -764,13 +766,13 @@ std::vector CompletionHelper::split_function_signature(const wxString& types.push_back(token.GetType()); } - if(!done_collecting_args) { + if (!done_collecting_args) { // we did not complete func_args.swap(args); } else { // check if we have a return value ADD_CURRENT_PARAM(current_param); - if(!args.empty() && return_value) { + if (!args.empty() && return_value) { *return_value = args[0].Trim().Trim(false); } } @@ -806,29 +808,29 @@ wxString CompletionHelper::format_comment(TagEntryPtr tag, const wxString& input wxString CompletionHelper::format_comment(TagEntry* tag, const wxString& input_comment) const { wxString beautified_comment; - if(tag) { - if(tag->IsMethod()) { + if (tag) { + if (tag->IsMethod()) { auto args = split_function_signature(tag->GetSignature(), nullptr); beautified_comment << "```\n"; - if(args.empty()) { + if (args.empty()) { beautified_comment << tag->GetName() << "()\n"; } else { beautified_comment << tag->GetName() << "(\n"; - for(const wxString& arg : args) { + for (const wxString& arg : args) { beautified_comment << " " << arg << ",\n"; } - if(beautified_comment.EndsWith(",\n")) { + if (beautified_comment.EndsWith(",\n")) { beautified_comment.RemoveLast(2); } beautified_comment << ")\n"; } beautified_comment << "```\n"; - } else if(tag->GetKind() == "variable" || tag->GetKind() == "member" || tag->IsLocalVariable()) { + } else if (tag->GetKind() == "variable" || tag->GetKind() == "member" || tag->IsLocalVariable()) { wxString clean_pattern = tag->GetPatternClean(); clean_pattern.Trim().Trim(false); - if(!clean_pattern.empty()) { + if (!clean_pattern.empty()) { beautified_comment << "```\n"; beautified_comment << clean_pattern << "\n"; beautified_comment << "```\n"; @@ -839,7 +841,7 @@ wxString CompletionHelper::format_comment(TagEntry* tag, const wxString& input_c // other wxString clean_pattern = tag->GetPatternClean(); clean_pattern.Trim().Trim(false); - if(!clean_pattern.empty()) { + if (!clean_pattern.empty()) { beautified_comment << "```\n"; beautified_comment << clean_pattern << "\n"; beautified_comment << "```\n"; @@ -847,42 +849,42 @@ wxString CompletionHelper::format_comment(TagEntry* tag, const wxString& input_c } } wxString formatted_comment; - if(!input_comment.empty()) { + if (!input_comment.empty()) { formatted_comment = wrap_lines(input_comment); - if(reDoxyParam.IsValid() && reDoxyParam.Matches(formatted_comment)) { + if (reDoxyParam.IsValid() && reDoxyParam.Matches(formatted_comment)) { reDoxyParam.ReplaceAll(&formatted_comment, "\nParameter\n`\\2`"); } - if(reDoxyBrief.IsValid() && reDoxyBrief.Matches(formatted_comment)) { + if (reDoxyBrief.IsValid() && reDoxyBrief.Matches(formatted_comment)) { reDoxyBrief.ReplaceAll(&formatted_comment, ""); } - if(reDoxyThrow.IsValid() && reDoxyThrow.Matches(formatted_comment)) { + if (reDoxyThrow.IsValid() && reDoxyThrow.Matches(formatted_comment)) { reDoxyThrow.ReplaceAll(&formatted_comment, "\n`Throws:`\n"); } - if(reDoxyReturn.IsValid() && reDoxyReturn.Matches(formatted_comment)) { + if (reDoxyReturn.IsValid() && reDoxyReturn.Matches(formatted_comment)) { reDoxyReturn.ReplaceAll(&formatted_comment, "\n`Returns:`\n"); } - if(reDoxyToDo.IsValid() && reDoxyToDo.Matches(formatted_comment)) { + if (reDoxyToDo.IsValid() && reDoxyToDo.Matches(formatted_comment)) { reDoxyToDo.ReplaceAll(&formatted_comment, "\nTODO\n"); } - if(reDoxyRemark.IsValid() && reDoxyRemark.Matches(formatted_comment)) { + if (reDoxyRemark.IsValid() && reDoxyRemark.Matches(formatted_comment)) { reDoxyRemark.ReplaceAll(&formatted_comment, "\n "); } - if(reDate.IsValid() && reDate.Matches(formatted_comment)) { + if (reDate.IsValid() && reDate.Matches(formatted_comment)) { reDate.ReplaceAll(&formatted_comment, "Date "); } - if(reFN.IsValid() && reFN.Matches(formatted_comment)) { + if (reFN.IsValid() && reFN.Matches(formatted_comment)) { size_t fnStart, fnLen, fnEnd; - if(reFN.GetMatch(&fnStart, &fnLen)) { + if (reFN.GetMatch(&fnStart, &fnLen)) { fnEnd = formatted_comment.find('\n', fnStart); - if(fnEnd != wxString::npos) { + if (fnEnd != wxString::npos) { // remove the string from fnStart -> fnEnd (including ther terminating \n) formatted_comment.Remove(fnStart, (fnEnd - fnStart) + 1); } @@ -890,7 +892,7 @@ wxString CompletionHelper::format_comment(TagEntry* tag, const wxString& input_c } // horizontal line - if(!beautified_comment.empty()) { + if (!beautified_comment.empty()) { beautified_comment << "---\n"; } beautified_comment << formatted_comment; @@ -909,20 +911,20 @@ bool CompletionHelper::is_line_include_statement(const wxString& line, wxString* // search for the "#" wxString remainder; - if(!tmp_line.StartsWith("#", &remainder)) { + if (!tmp_line.StartsWith("#", &remainder)) { return false; } - if(!reIncludeFile.Matches(remainder)) { + if (!reIncludeFile.Matches(remainder)) { return false; } - if(file_name) { + if (file_name) { *file_name = reIncludeFile.GetMatch(remainder, 1); } - if(suffix) { - if(tmp_line.Contains("<")) { + if (suffix) { + if (tmp_line.Contains("<")) { *suffix = ">"; } else { *suffix = "\""; @@ -934,13 +936,13 @@ bool CompletionHelper::is_line_include_statement(const wxString& line, wxString* bool CompletionHelper::is_include_statement(const wxString& f_content, wxString* file_name, wxString* suffix) const { // read backward until we find LF - if(f_content.empty()) { + if (f_content.empty()) { return false; } int i = f_content.size() - 1; - for(; i >= 0; --i) { - if(f_content[i] == '\n') { + for (; i >= 0; --i) { + if (f_content[i] == '\n') { break; } } @@ -959,16 +961,16 @@ wxString CompletionHelper::normalize_function(const TagEntry* tag, size_t flags) fullname << name << "("; std::vector args = split_function_signature(signature, &return_value, flags); wxString funcsig; - for(const wxString& arg : args) { + for (const wxString& arg : args) { funcsig << arg << ", "; } - if(funcsig.EndsWith(", ")) { + if (funcsig.EndsWith(", ")) { funcsig.RemoveLast(2); } fullname << funcsig << ")"; - if(tag->is_const()) { + if (tag->is_const()) { fullname << " const"; } return fullname; @@ -983,7 +985,7 @@ void CompletionHelper::get_cxx_keywords(std::vector& keywords) { populate_keywords(); keywords.reserve(words.size()); - for(const wxString& word : words) { + for (const wxString& word : words) { keywords.push_back(word); } } diff --git a/CodeLite/CompletionHelper.hpp b/CodeLite/CompletionHelper.hpp index 11d58dbab8..0f2355fda9 100644 --- a/CodeLite/CompletionHelper.hpp +++ b/CodeLite/CompletionHelper.hpp @@ -30,16 +30,19 @@ class WXDLLIMPEXP_CL CompletionHelper * @brief normalize function signature by removing from its signature all * default values and removing the arguments name (both is configurable via `flags`) */ - wxString normalize_function(TagEntryPtr tag, size_t flags = CompletionHelper::STRIP_NO_DEFAULT_VALUES | - CompletionHelper::STRIP_NO_NAME); + wxString normalize_function(TagEntryPtr tag, + size_t flags = CompletionHelper::STRIP_NO_DEFAULT_VALUES | + CompletionHelper::STRIP_NO_NAME); /** * @brief same as above */ - wxString normalize_function(const TagEntry* tag, size_t flags = CompletionHelper::STRIP_NO_DEFAULT_VALUES | - CompletionHelper::STRIP_NO_NAME); + wxString normalize_function(const TagEntry* tag, + size_t flags = CompletionHelper::STRIP_NO_DEFAULT_VALUES | + CompletionHelper::STRIP_NO_NAME); wxString get_expression(const wxString& file_content, bool for_calltip, wxString* last_word = nullptr) const; wxString truncate_file_to_location(const wxString& file_content, size_t line, size_t column, size_t flags) const; - std::vector split_function_signature(const wxString& signature, wxString* return_value, + std::vector split_function_signature(const wxString& signature, + wxString* return_value, size_t flags = CompletionHelper::STRIP_DEFAULT) const; static bool is_cxx_keyword(const wxString& word); diff --git a/CodeLite/Console/clConsoleAlacritty.cpp b/CodeLite/Console/clConsoleAlacritty.cpp index 0fc87d43d9..f1a7d35ee0 100644 --- a/CodeLite/Console/clConsoleAlacritty.cpp +++ b/CodeLite/Console/clConsoleAlacritty.cpp @@ -22,8 +22,8 @@ wxString clConsoleAlacritty::PrepareCommand() wxString command = GetCommand(); command.Trim().Trim(false); - if(IsTerminalNeeded()) { - if(m_terminal.empty()) { + if (IsTerminalNeeded()) { + if (m_terminal.empty()) { // no terminal, but a terminal is required... return wxEmptyString; } @@ -31,16 +31,16 @@ wxString clConsoleAlacritty::PrepareCommand() // on mac, add `--args` here full_command = m_terminal; MacAddArgsIfNeeded(&full_command); - if(!GetWorkingDirectory().empty()) { + if (!GetWorkingDirectory().empty()) { full_command << " --working-directory " << WrapWithQuotesIfNeeded(GetWorkingDirectory()); } - if(IsWaitWhenDone()) { + if (IsWaitWhenDone()) { full_command << " --hold"; } // set the title - if(!command.empty()) { + if (!command.empty()) { full_command << " -t " << WrapWithQuotesIfNeeded(command); full_command << " -e " << command; } @@ -48,7 +48,7 @@ wxString clConsoleAlacritty::PrepareCommand() full_command << " " << command; } - if(!GetCommandArgs().IsEmpty()) { + if (!GetCommandArgs().IsEmpty()) { full_command << " " << GetCommandArgs(); } diff --git a/CodeLite/Console/clConsoleBase.cpp b/CodeLite/Console/clConsoleBase.cpp index 5e7c21eecc..30b93692a7 100644 --- a/CodeLite/Console/clConsoleBase.cpp +++ b/CodeLite/Console/clConsoleBase.cpp @@ -2,6 +2,7 @@ #include "clConsoleAlacritty.hpp" #include "clConsoleCMD.h" +#include "clConsoleGnomeConsole.h" #include "clConsoleGnomeTerminal.h" #include "clConsoleKitty.hpp" #include "clConsoleKonsole.h" @@ -11,7 +12,6 @@ #include "clConsoleQTerminal.h" #include "clConsoleRXVTerminal.h" #include "clConsoleXfce4Terminal.h" -#include "clConsoleGnomeConsole.h" #include "cl_config.h" #include "file_logger.h" #include "fileutils.h" @@ -50,29 +50,29 @@ clConsoleBase::Ptr_t clConsoleBase::GetTerminal() clConsoleBase::Ptr_t terminal; wxString terminalName = GetSelectedTerminalName(); #ifdef __WXMSW__ - if(terminalName.CmpNoCase("alacritty") == 0) { + if (terminalName.CmpNoCase("alacritty") == 0) { terminal.reset(new clConsoleAlacritty()); } else { terminal.reset(new clConsoleCMD()); } #elif defined(__WXGTK__) - if(terminalName.CmpNoCase("konsole") == 0) { + if (terminalName.CmpNoCase("konsole") == 0) { terminal.reset(new clConsoleKonsole()); - } else if(terminalName.CmpNoCase("alacritty") == 0) { + } else if (terminalName.CmpNoCase("alacritty") == 0) { terminal.reset(new clConsoleAlacritty()); - } else if(terminalName.CmpNoCase("kitty") == 0) { + } else if (terminalName.CmpNoCase("kitty") == 0) { terminal.reset(new clConsoleKitty()); - } else if(terminalName.CmpNoCase("lxterminal") == 0) { + } else if (terminalName.CmpNoCase("lxterminal") == 0) { terminal.reset(new clConsoleLXTerminal()); - } else if(terminalName.CmpNoCase("mate-terminal") == 0) { + } else if (terminalName.CmpNoCase("mate-terminal") == 0) { terminal.reset(new clConsoleMateTerminal()); - } else if(terminalName.CmpNoCase("xfce4-terminal") == 0) { + } else if (terminalName.CmpNoCase("xfce4-terminal") == 0) { terminal.reset(new clConsoleXfce4Terminal()); - } else if(terminalName.CmpNoCase("qterminal") == 0) { + } else if (terminalName.CmpNoCase("qterminal") == 0) { terminal.reset(new clConsoleQTerminal()); - } else if(terminalName.CmpNoCase("rxvt-unicode") == 0) { + } else if (terminalName.CmpNoCase("rxvt-unicode") == 0) { terminal.reset(new clConsoleRXVTTerminal()); - } else if(terminalName.CmpNoCase("kgx") == 0) { + } else if (terminalName.CmpNoCase("kgx") == 0) { terminal.reset(new clConsoleGnomeConsole()); } else { // the default terminal is "gnome-terminal" @@ -81,11 +81,11 @@ clConsoleBase::Ptr_t clConsoleBase::GetTerminal() #else clConsoleOSXTerminal* t = new clConsoleOSXTerminal(); terminal.reset(t); - if(terminalName.CmpNoCase("iTerm2") == 0) { + if (terminalName.CmpNoCase("iTerm2") == 0) { t->SetTerminalApp("iTerm"); - } else if(terminalName.CmpNoCase("alacritty") == 0) { + } else if (terminalName.CmpNoCase("alacritty") == 0) { terminal.reset(new clConsoleAlacritty()); - } else if(terminalName.CmpNoCase("kitty") == 0) { + } else if (terminalName.CmpNoCase("kitty") == 0) { terminal.reset(new clConsoleKitty()); } #endif @@ -119,7 +119,7 @@ wxString clConsoleBase::WrapWithQuotesIfNeeded(const wxString& s) const { wxString strimmed = s; strimmed.Trim().Trim(false); - if(strimmed.Contains(" ")) { + if (strimmed.Contains(" ")) { strimmed.Prepend("\"").Append("\""); } return strimmed; @@ -132,10 +132,10 @@ bool clConsoleBase::StartProcess(const wxString& command) env.Apply(); wxProcess* callback = nullptr; - if(m_callback) { + if (m_callback) { // user provided callback callback = m_callback; - } else if(m_sink) { + } else if (m_sink) { // using events. This object will get deleted when the process exits callback = new ConsoleProcess(m_sink, m_callbackUID); } @@ -153,7 +153,7 @@ bool clConsoleBase::StartProcess(const wxString& command) wxString clConsoleBase::GetSelectedTerminalName() { wxString terminalName = clConfig::Get().Read("Terminal", wxString()); - if(terminalName.empty()) { + if (terminalName.empty()) { #ifdef __WXGTK__ wxFileName file; terminalName = "gnome-terminal"; @@ -170,11 +170,11 @@ clConsoleEnvironment::~clConsoleEnvironment() { UnApply(); } void clConsoleEnvironment::Apply() { - if(!m_oldEnvironment.empty()) { + if (!m_oldEnvironment.empty()) { clWARNING() << "Refusing to apply environment. Already in a dirty state"; return; } - if(m_environment.empty()) { + if (m_environment.empty()) { return; } @@ -182,7 +182,7 @@ void clConsoleEnvironment::Apply() m_oldEnvironment.clear(); for (const auto& vt : m_environment) { wxString envvalue; - if(::wxGetEnv(vt.first, &envvalue)) { + if (::wxGetEnv(vt.first, &envvalue)) { m_oldEnvironment[vt.first] = envvalue; } else { m_oldEnvironment[vt.first] = "__no_such_env__"; @@ -193,11 +193,11 @@ void clConsoleEnvironment::Apply() void clConsoleEnvironment::UnApply() { - if(m_oldEnvironment.empty()) { + if (m_oldEnvironment.empty()) { return; } for (const auto& vt : m_oldEnvironment) { - if(vt.second == "__no_such_env__") { + if (vt.second == "__no_such_env__") { ::wxUnsetEnv(vt.second); } else { ::wxSetEnv(vt.first, vt.second); @@ -212,9 +212,9 @@ clConsoleEnvironment::clConsoleEnvironment(const wxStringMap_t& env) } #define ADD_CURRENT_TOKEN() \ - if(!curtoken.IsEmpty()) { \ + if (!curtoken.IsEmpty()) { \ curtoken.Trim().Trim(false); \ - if(!curtoken.IsEmpty()) { \ + if (!curtoken.IsEmpty()) { \ outputArr.Add(curtoken); \ } \ curtoken.Clear(); \ @@ -230,12 +230,12 @@ wxArrayString clConsoleBase::SplitArguments(const wxString& args) wxString curtoken; wxChar prevChar = 0; for (wxChar ch : args) { - switch(state) { + switch (state) { case STATE_NORMAL: { - switch(ch) { + switch (ch) { case ' ': case '\t': - if(prevChar == '\\') { + if (prevChar == '\\') { curtoken << ch; } else { ADD_CURRENT_TOKEN(); @@ -252,10 +252,10 @@ wxArrayString clConsoleBase::SplitArguments(const wxString& args) } } break; case STATE_STRING: { - switch(ch) { + switch (ch) { case '"': case '\'': - if(prevChar == '\\') { + if (prevChar == '\\') { curtoken << ch; } else { // we don't want to keep the string markers @@ -281,22 +281,22 @@ void clConsoleBase::SetEnvironment(const clEnvList_t& environment) { // convert the list into map m_environment.clear(); - for(const auto& p : environment) { - m_environment.insert({ p.first, p.second }); + for (const auto& p : environment) { + m_environment.insert({p.first, p.second}); } } void clConsoleBase::MacAddArgsIfNeeded(wxString* outcmd) { - if(!IsTerminalNeeded()) { + if (!IsTerminalNeeded()) { return; } #ifndef __WXMAC__ wxUnusedVar(outcmd); #else - if(!GetWorkingDirectory().empty() || !GetCommand().empty()) { - if(!outcmd->empty()) { + if (!GetWorkingDirectory().empty() || !GetCommand().empty()) { + if (!outcmd->empty()) { *outcmd << " "; } *outcmd << "--args "; diff --git a/CodeLite/Console/clConsoleBase.h b/CodeLite/Console/clConsoleBase.h index bb46bd54ab..59dd1957e7 100644 --- a/CodeLite/Console/clConsoleBase.h +++ b/CodeLite/Console/clConsoleBase.h @@ -48,7 +48,6 @@ class WXDLLIMPEXP_CL clConsoleBase wxString m_callbackUID; protected: - wxString WrapWithQuotesIfNeeded(const wxString& s) const; virtual bool StartProcess(const wxString& command); void MacAddArgsIfNeeded(wxString* outcmd); diff --git a/CodeLite/Console/clConsoleBash.cpp b/CodeLite/Console/clConsoleBash.cpp index 03231cab41..d7218f99f9 100644 --- a/CodeLite/Console/clConsoleBash.cpp +++ b/CodeLite/Console/clConsoleBash.cpp @@ -1,6 +1,8 @@ #include "clConsoleBash.h" + #include "cl_standard_paths.h" #include "fileutils.h" + #include #include @@ -16,33 +18,33 @@ wxFileName clConsoleBash::PrepareExecScript() const scriptPath.Mkdir(wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL); #endif - if(!GetCommand().IsEmpty()) { + if (!GetCommand().IsEmpty()) { wxString fileContent; fileContent << "#!/bin/bash\n"; fileContent << "command=\"" << GetCommand() << "\"\n"; wxString cdCommand; #ifdef __WXOSX__ // on OSX, we need to set the working directory via the script - if(!GetWorkingDirectory().IsEmpty()) { + if (!GetWorkingDirectory().IsEmpty()) { wxString workingDir = GetWorkingDirectory(); - if(workingDir.Contains(" ")) { + if (workingDir.Contains(" ")) { workingDir.Prepend("\"").Append("\""); } cdCommand << "cd " << workingDir << " && "; } #endif - if(!GetCommandArgs().IsEmpty()) { + if (!GetCommandArgs().IsEmpty()) { // Split the arguments line wxArrayString arr = SplitArguments(GetCommandArgs()); // Create an array in the script - for(size_t i = 0; i < arr.size(); ++i) { + for (size_t i = 0; i < arr.size(); ++i) { fileContent << "args[" << i << "]=\"" << arr[i] << "\"\n"; } fileContent << cdCommand << "\"${command}\" \"${args[@]}\"\n"; } else { fileContent << cdCommand << "\"${command}\"\n"; } - if(IsWaitWhenDone()) { + if (IsWaitWhenDone()) { fileContent << "echo Hit any key to continue...\nread"; } FileUtils::WriteFileContent(scriptPath, fileContent); diff --git a/CodeLite/Console/clConsoleBash.h b/CodeLite/Console/clConsoleBash.h index 733f5da892..d0a5a36746 100644 --- a/CodeLite/Console/clConsoleBash.h +++ b/CodeLite/Console/clConsoleBash.h @@ -3,6 +3,7 @@ #include "clConsoleBase.h" #include "codelite_exports.h" + #include class WXDLLIMPEXP_CL clConsoleBash : public clConsoleBase diff --git a/CodeLite/Console/clConsoleCMD.cpp b/CodeLite/Console/clConsoleCMD.cpp index 05a47cec04..391a1dd1dc 100644 --- a/CodeLite/Console/clConsoleCMD.cpp +++ b/CodeLite/Console/clConsoleCMD.cpp @@ -9,7 +9,7 @@ bool clConsoleCMD::Start() { DirSaver ds; // restore the directory upon exiting this function wxFileName fn(GetWorkingDirectory(), ""); - if(fn.DirExists()) { + if (fn.DirExists()) { ::wxSetWorkingDirectory(fn.GetPath()); } return StartProcess(PrepareCommand()); @@ -21,7 +21,7 @@ wxString clConsoleCMD::PrepareCommand() { // no args? just return the cmd command wxString command = WrapWithQuotesIfNeeded(GetCommand()); - if(command.empty()) { + if (command.empty()) { return "cmd"; } @@ -30,7 +30,7 @@ wxString clConsoleCMD::PrepareCommand() wxString rest_cmd; // if "wait-when-done" enabled, wrap the command with codelite-exec - if(IsWaitWhenDone()) { + if (IsWaitWhenDone()) { wxFileName fnCodeliteExec(clStandardPaths::Get().GetBinaryFullPath("codelite-exec")); wxString strCodeLiteExec = WrapWithQuotesIfNeeded(fnCodeliteExec.GetFullPath()); rest_cmd << strCodeLiteExec << " "; @@ -38,7 +38,7 @@ wxString clConsoleCMD::PrepareCommand() // append the command to run rest_cmd << command; - if(!GetCommandArgs().IsEmpty()) { + if (!GetCommandArgs().IsEmpty()) { rest_cmd << " " << GetCommandArgs(); } return commandToExecute + rest_cmd; diff --git a/CodeLite/Console/clConsoleGnomeConsole.cpp b/CodeLite/Console/clConsoleGnomeConsole.cpp index f1698240f8..4ff2f509f2 100644 --- a/CodeLite/Console/clConsoleGnomeConsole.cpp +++ b/CodeLite/Console/clConsoleGnomeConsole.cpp @@ -21,10 +21,10 @@ bool clConsoleGnomeConsole::FindProcessByCommand(const wxString& name, wxString& ProcUtils::SafeExecuteCommand(psCommand, arrOutput); - for(auto &curline : arrOutput) { + for (auto& curline : arrOutput) { curline.Trim().Trim(false); wxArrayString tokens = ::wxStringTokenize(curline, " ", wxTOKEN_STRTOK); - if(tokens.GetCount() < 3) { + if (tokens.GetCount() < 3) { continue; } @@ -32,7 +32,7 @@ bool clConsoleGnomeConsole::FindProcessByCommand(const wxString& name, wxString& curline.Replace("\t", " "); // remove any duplicate spaces - while(curline.Replace(" ", " ")) {} + while (curline.Replace(" ", " ")) {} wxString tmp_pid = curline.BeforeFirst(' '); curline = curline.AfterFirst(' '); @@ -43,7 +43,7 @@ bool clConsoleGnomeConsole::FindProcessByCommand(const wxString& name, wxString& wxString command = curline; // the remainder command.Trim().Trim(false); - if(command == name) { + if (command == name) { // we got our match tmp_tty = tmp_tty.AfterLast('/'); tmp_tty.Prepend("/dev/pts/"); @@ -78,7 +78,7 @@ bool clConsoleGnomeConsole::StartForDebugger() sleepCommand << " " << secondsToSleep; wxString homedir = wxGetHomeDir(); - if(homedir.Contains(" ")) { + if (homedir.Contains(" ")) { homedir.Prepend("\"").Append("\""); } wxString commandToExecute = GetTerminalCommand(); @@ -87,8 +87,8 @@ bool clConsoleGnomeConsole::StartForDebugger() ::wxExecute(commandToExecute); // Let it start ... (wait for it up to 5 seconds) - for(size_t i = 0; i < 100; ++i) { - if(FindProcessByCommand(sleepCommand, m_tty, m_pid)) { + for (size_t i = 0; i < 100; ++i) { + if (FindProcessByCommand(sleepCommand, m_tty, m_pid)) { // On GTK, redirection to TTY does not work with lldb // as a workaround, we create a symlink with different name @@ -99,7 +99,7 @@ bool clConsoleGnomeConsole::StartForDebugger() symlinkName.Replace("/dev/pts/", "/tmp/pts"); wxString lnCommand; lnCommand << "ln -sf " << m_tty << " " << symlinkName; - if(::system(lnCommand.mb_str(wxConvUTF8).data()) == 0) { + if (::system(lnCommand.mb_str(wxConvUTF8).data()) == 0) { m_tty.swap(symlinkName); } break; @@ -114,20 +114,20 @@ wxString clConsoleGnomeConsole::PrepareCommand() wxString commandToExecute; bool hasCommand = !GetCommand().IsEmpty(); commandToExecute = hasCommand ? GetTerminalCommand() : GetEmptyTerminalCommand(); - if(!IsTerminalNeeded()) { + if (!IsTerminalNeeded()) { commandToExecute = "%COMMAND%"; } - if(IsTerminalNeeded()) { + if (IsTerminalNeeded()) { // set the working directory wxString workingDirectory = WrapWithQuotesIfNeeded(GetWorkingDirectory()); - if(workingDirectory.IsEmpty()) { + if (workingDirectory.IsEmpty()) { workingDirectory = "."; } commandToExecute.Replace("%WD%", workingDirectory); } - if(hasCommand) { + if (hasCommand) { wxFileName scriptPath = PrepareExecScript(); wxString rowCommand; rowCommand << "/bin/bash -f \"" << scriptPath.GetFullPath() << "\""; diff --git a/CodeLite/Console/clConsoleGnomeTerminal.cpp b/CodeLite/Console/clConsoleGnomeTerminal.cpp index 4f182cd608..769008fde8 100644 --- a/CodeLite/Console/clConsoleGnomeTerminal.cpp +++ b/CodeLite/Console/clConsoleGnomeTerminal.cpp @@ -21,10 +21,10 @@ bool clConsoleGnomeTerminal::FindProcessByCommand(const wxString& name, wxString ProcUtils::SafeExecuteCommand(psCommand, arrOutput); - for(size_t i = 0; i < arrOutput.GetCount(); ++i) { + for (size_t i = 0; i < arrOutput.GetCount(); ++i) { wxString curline = arrOutput.Item(i).Trim().Trim(false); wxArrayString tokens = ::wxStringTokenize(curline, " ", wxTOKEN_STRTOK); - if(tokens.GetCount() < 3) { + if (tokens.GetCount() < 3) { continue; } @@ -32,7 +32,7 @@ bool clConsoleGnomeTerminal::FindProcessByCommand(const wxString& name, wxString curline.Replace("\t", " "); // remove any duplicate spaces - while(curline.Replace(" ", " ")) {} + while (curline.Replace(" ", " ")) {} wxString tmp_pid = curline.BeforeFirst(' '); curline = curline.AfterFirst(' '); @@ -43,7 +43,7 @@ bool clConsoleGnomeTerminal::FindProcessByCommand(const wxString& name, wxString wxString command = curline; // the remainder command.Trim().Trim(false); - if(command == name) { + if (command == name) { // we got our match tmp_tty = tmp_tty.AfterLast('/'); tmp_tty.Prepend("/dev/pts/"); @@ -78,7 +78,7 @@ bool clConsoleGnomeTerminal::StartForDebugger() sleepCommand << " " << secondsToSleep; wxString homedir = wxGetHomeDir(); - if(homedir.Contains(" ")) { + if (homedir.Contains(" ")) { homedir.Prepend("\"").Append("\""); } wxString commandToExecute = GetTerminalCommand(); @@ -87,8 +87,8 @@ bool clConsoleGnomeTerminal::StartForDebugger() ::wxExecute(commandToExecute); // Let it start ... (wait for it up to 5 seconds) - for(size_t i = 0; i < 100; ++i) { - if(FindProcessByCommand(sleepCommand, m_tty, m_pid)) { + for (size_t i = 0; i < 100; ++i) { + if (FindProcessByCommand(sleepCommand, m_tty, m_pid)) { // On GTK, redirection to TTY does not work with lldb // as a workaround, we create a symlink with different name @@ -99,7 +99,7 @@ bool clConsoleGnomeTerminal::StartForDebugger() symlinkName.Replace("/dev/pts/", "/tmp/pts"); wxString lnCommand; lnCommand << "ln -sf " << m_tty << " " << symlinkName; - if(::system(lnCommand.mb_str(wxConvUTF8).data()) == 0) { + if (::system(lnCommand.mb_str(wxConvUTF8).data()) == 0) { m_tty.swap(symlinkName); } break; @@ -114,20 +114,20 @@ wxString clConsoleGnomeTerminal::PrepareCommand() wxString commandToExecute; bool hasCommand = !GetCommand().IsEmpty(); commandToExecute = hasCommand ? GetTerminalCommand() : GetEmptyTerminalCommand(); - if(!IsTerminalNeeded()) { + if (!IsTerminalNeeded()) { commandToExecute = "%COMMAND%"; } - if(IsTerminalNeeded()) { + if (IsTerminalNeeded()) { // set the working directory wxString workingDirectory = WrapWithQuotesIfNeeded(GetWorkingDirectory()); - if(workingDirectory.IsEmpty()) { + if (workingDirectory.IsEmpty()) { workingDirectory = "."; } commandToExecute.Replace("%WD%", workingDirectory); } - if(hasCommand) { + if (hasCommand) { wxFileName scriptPath = PrepareExecScript(); wxString rowCommand; rowCommand << "/bin/bash -f \"" << scriptPath.GetFullPath() << "\""; diff --git a/CodeLite/Console/clConsoleKitty.cpp b/CodeLite/Console/clConsoleKitty.cpp index 952308da7a..cb80638543 100644 --- a/CodeLite/Console/clConsoleKitty.cpp +++ b/CodeLite/Console/clConsoleKitty.cpp @@ -22,8 +22,8 @@ wxString clConsoleKitty::PrepareCommand() wxString command = GetCommand(); command.Trim().Trim(false); - if(IsTerminalNeeded()) { - if(m_terminal.empty()) { + if (IsTerminalNeeded()) { + if (m_terminal.empty()) { // no terminal, but a terminal is required... return wxEmptyString; } @@ -31,22 +31,22 @@ wxString clConsoleKitty::PrepareCommand() // on mac, add `--args` here full_command = m_terminal; MacAddArgsIfNeeded(&full_command); - if(!GetWorkingDirectory().empty()) { + if (!GetWorkingDirectory().empty()) { full_command << " -d " << WrapWithQuotesIfNeeded(GetWorkingDirectory()); } - if(IsWaitWhenDone()) { + if (IsWaitWhenDone()) { full_command << " --hold"; } // set the title - if(!command.empty()) { + if (!command.empty()) { full_command << " -T " << WrapWithQuotesIfNeeded(command); } } full_command << " " << command; - if(!GetCommandArgs().IsEmpty()) { + if (!GetCommandArgs().IsEmpty()) { full_command << " " << GetCommandArgs(); } diff --git a/CodeLite/Console/clConsoleOSXTerminal.cpp b/CodeLite/Console/clConsoleOSXTerminal.cpp index c46aed4583..775c59cffb 100644 --- a/CodeLite/Console/clConsoleOSXTerminal.cpp +++ b/CodeLite/Console/clConsoleOSXTerminal.cpp @@ -29,11 +29,11 @@ wxString clConsoleOSXTerminal::PrepareCommand() // osascript -e 'tell app "Terminal" to do script "echo hello"' wxFileName scriptPath = PrepareExecScript(); - if(IsTerminalNeeded()) { + if (IsTerminalNeeded()) { commandToExecute << "open -n -a " << GetTerminalApp(); } - if(!GetCommand().IsEmpty()) { + if (!GetCommand().IsEmpty()) { commandToExecute << " " << scriptPath.GetFullPath(); } clDEBUG() << commandToExecute; diff --git a/CodeLite/Cxx/CxxCodeCompletion.cpp b/CodeLite/Cxx/CxxCodeCompletion.cpp index 472ae7111e..665740fc2f 100644 --- a/CodeLite/Cxx/CxxCodeCompletion.cpp +++ b/CodeLite/Cxx/CxxCodeCompletion.cpp @@ -26,7 +26,7 @@ wxArrayString to_wx_array_string(const std::vector& v) { wxArrayString a; a.reserve(v.size()); - for(const wxString& s : v) { + for (const wxString& s : v) { a.Add(s); } return a; @@ -36,14 +36,14 @@ wxArrayString to_wx_array_string(const std::vector& v) #define RECURSE_GUARD_RETURN_NULLPTR() \ m_recurse_protector++; \ - if(m_recurse_protector > 150) { \ + if (m_recurse_protector > 150) { \ return nullptr; \ } -#define RECURSE_GUARD_RETURN() \ - m_recurse_protector++; \ - if(m_recurse_protector > 150) { \ - return; \ +#define RECURSE_GUARD_RETURN() \ + m_recurse_protector++; \ + if (m_recurse_protector > 150) { \ + return; \ } CxxCodeCompletion::CxxCodeCompletion(ITagsStoragePtr lookup, const wxString& codelite_indexer) @@ -53,7 +53,8 @@ CxxCodeCompletion::CxxCodeCompletion(ITagsStoragePtr lookup, const wxString& cod m_template_manager.reset(new TemplateManager(this)); } -CxxCodeCompletion::CxxCodeCompletion(ITagsStoragePtr lookup, const wxString& codelite_indexer, +CxxCodeCompletion::CxxCodeCompletion(ITagsStoragePtr lookup, + const wxString& codelite_indexer, const std::unordered_map& unit_tests_db) : m_codelite_indexer(codelite_indexer) { @@ -63,39 +64,40 @@ CxxCodeCompletion::CxxCodeCompletion(ITagsStoragePtr lookup, const wxString& cod void CxxCodeCompletion::determine_current_scope() { - if(m_current_function_tag || m_filename.empty() || m_line_number == wxNOT_FOUND) { + if (m_current_function_tag || m_filename.empty() || m_line_number == wxNOT_FOUND) { return; } - if(!m_lookup) { + if (!m_lookup) { return; } m_current_function_tag = m_lookup->GetScope(m_filename, m_line_number + 1); - if(m_current_function_tag && m_current_function_tag->IsMethod()) { + if (m_current_function_tag && m_current_function_tag->IsMethod()) { std::vector tmp_tags; m_lookup->GetTagsByPath(m_current_function_tag->GetScope(), tmp_tags, 1); - if(tmp_tags.size() == 1) { + if (tmp_tags.size() == 1) { m_current_container_tag = std::move(tmp_tags[0]); } } } -TagEntryPtr CxxCodeCompletion::code_complete(const wxString& expression, const std::vector& visible_scopes, +TagEntryPtr CxxCodeCompletion::code_complete(const wxString& expression, + const std::vector& visible_scopes, CxxRemainder* remainder) { // build expression from the expression m_recurse_protector = 0; m_template_manager.reset(new TemplateManager(this)); - std::vector scopes = { visible_scopes.begin(), visible_scopes.end() }; + std::vector scopes = {visible_scopes.begin(), visible_scopes.end()}; std::vector expr_arr = from_expression(expression, remainder); // add extra scopes (global scope, file scopes) scopes = prepend_extra_scopes(scopes); // Check the current scope - if(m_current_container_tag) { + if (m_current_container_tag) { prepend_scope(scopes, m_current_container_tag->GetPath()); } @@ -112,16 +114,16 @@ TagEntryPtr CxxCodeCompletion::resolve_compound_expression(std::vector scopes = visible_scopes; - if(expression.size() == 1 && expression[0].type_name().empty() && expression[0].operand_string() == "::") { + if (expression.size() == 1 && expression[0].type_name().empty() && expression[0].operand_string() == "::") { // return a dummy entry representing the global scope return create_global_scope_tag(); - } else if(expression.size() >= 2 && expression[0].type_name().empty() && expression[0].operand_string() == "::") { + } else if (expression.size() >= 2 && expression[0].type_name().empty() && expression[0].operand_string() == "::") { // explicitly requesting for the global namespace // clear the `scopes` and use only the global namespace (empty string) scopes.clear(); @@ -131,12 +133,12 @@ TagEntryPtr CxxCodeCompletion::resolve_compound_expression(std::vectorsize(); } -void CxxCodeCompletion::shrink_scope(const wxString& text, std::unordered_map* locals, +void CxxCodeCompletion::shrink_scope(const wxString& text, + std::unordered_map* locals, FileScope* file_tags) const { // parse local variables @@ -162,7 +165,7 @@ void CxxCodeCompletion::shrink_scope(const wxString& text, std::unordered_mapreserve(variables.size()); std::vector parameters; - if(m_current_function_tag && m_current_function_tag->IsFunction()) { + if (m_current_function_tag && m_current_function_tag->IsFunction()) { std::vector all_lambdas; std::vector lambdas; // get the current function parameters @@ -173,37 +176,37 @@ void CxxCodeCompletion::shrink_scope(const wxString& text, std::unordered_map lambda_parameters_map; std::unordered_map function_parameters_map; - for(auto param : parameters) { - function_parameters_map.insert({ param->GetName(), param }); + for (auto param : parameters) { + function_parameters_map.insert({param->GetName(), param}); } - for(auto lambda : all_lambdas) { - if((lambda->GetLine() - 1) <= m_line_number) { + for (auto lambda : all_lambdas) { + if ((lambda->GetLine() - 1) <= m_line_number) { // load this lambda parameters and add them std::vector lambda_parameters; m_lookup->GetParameters(lambda->GetPath(), lambda_parameters); - for(auto param : lambda_parameters) { + for (auto param : lambda_parameters) { // if a function parameter with this name already exists, skip it - if(function_parameters_map.count(param->GetName())) { + if (function_parameters_map.count(param->GetName())) { continue; } // if we already encountered a lambda parameter with this name, replace it - if(lambda_parameters_map.count(param->GetName())) { + if (lambda_parameters_map.count(param->GetName())) { lambda_parameters_map.erase(param->GetName()); } - lambda_parameters_map.insert({ param->GetName(), param }); + lambda_parameters_map.insert({param->GetName(), param}); } } } // all the lambda parameters to the list of parameters - for(const auto& vt : lambda_parameters_map) { + for (const auto& vt : lambda_parameters_map) { parameters.emplace_back(vt.second); } } - if(file_tags) { + if (file_tags) { // set the function parameters (this includes any lambda parameters) file_tags->set_function_parameters(parameters); } @@ -215,24 +218,24 @@ void CxxCodeCompletion::shrink_scope(const wxString& text, std::unordered_mapGetScope().StartsWith("__anon")) { + for (auto tag : anonymous_tags) { + if (tag->GetScope().StartsWith("__anon")) { unique_scopes.insert(tag->GetScope()); } - if(tag->GetKind() == "variable") { + if (tag->GetKind() == "variable") { CxxVariableScanner scanner(normalize_pattern(tag), eCxxStandard::kCxx11, m_macros_table_map, false); auto _variables = scanner.GetVariables(false); variables.insert(variables.end(), _variables.begin(), _variables.end()); - } else if(file_tags && tag->GetKind() == "member") { + } else if (file_tags && tag->GetKind() == "member") { file_tags->add_static_member(tag); } } - if(file_tags) { + if (file_tags) { file_tags->set_file_scopes(unique_scopes); } - for(auto var : variables) { + for (auto var : variables) { __local local; wxString assignment_expr_raw = var->GetDefaultValue(); // strip it from any keywords etc and only keep interesting parts @@ -244,13 +247,13 @@ void CxxCodeCompletion::shrink_scope(const wxString& text, std::unordered_mapGetName()); local.set_pattern(var->ToString(CxxVariable::kToString_Name | CxxVariable::kToString_DefaultValue)); local.set_line_number(var->GetLineNumber()); - locals->insert({ var->GetName(), local }); + locals->insert({var->GetName(), local}); } } TagEntryPtr CxxCodeCompletion::lookup_operator_arrow(TagEntryPtr parent, const std::vector& visible_scopes) { - return lookup_child_symbol(parent, m_template_manager, "operator->", visible_scopes, { "function", "prototype" }); + return lookup_child_symbol(parent, m_template_manager, "operator->", visible_scopes, {"function", "prototype"}); } TagEntryPtr CxxCodeCompletion::lookup_subscript_operator(TagEntryPtr parent, @@ -258,24 +261,25 @@ TagEntryPtr CxxCodeCompletion::lookup_subscript_operator(TagEntryPtr parent, { CHECK_PTR_RET_NULL(m_lookup); std::vector scopes = get_scopes(parent, visible_scopes); - for(auto scope : scopes) { + for (auto scope : scopes) { std::vector tags; m_lookup->GetSubscriptOperator(scope->GetPath(), tags); - if(!tags.empty()) { + if (!tags.empty()) { return tags[0]; } } return nullptr; } -TagEntryPtr CxxCodeCompletion::lookup_child_symbol(TagEntryPtr parent, TemplateManager::ptr_t template_manager, +TagEntryPtr CxxCodeCompletion::lookup_child_symbol(TagEntryPtr parent, + TemplateManager::ptr_t template_manager, const wxString& child_symbol, const std::vector& visible_scopes, const std::vector& kinds) { CHECK_PTR_RET_NULL(m_lookup); auto resolved = lookup_symbol_by_kind(child_symbol, visible_scopes, kinds); - if(resolved) { + if (resolved) { return resolved; } @@ -289,7 +293,7 @@ TagEntryPtr CxxCodeCompletion::lookup_child_symbol(TagEntryPtr parent, TemplateM CxxLexerToken tok; CxxTokenizer tokenizer; tokenizer.Reset(child_symbol); - while(tokenizer.NextToken(tok)) { + while (tokenizer.NextToken(tok)) { requested_symbol_tokens.push_back(tok.GetWXString()); } } @@ -298,18 +302,18 @@ TagEntryPtr CxxCodeCompletion::lookup_child_symbol(TagEntryPtr parent, TemplateM CxxLexerToken tok; CxxTokenizer tokenizer; tokenizer.Reset(symbol_name); - for(const wxString& token : requested_symbol_tokens) { - if(!tokenizer.NextToken(tok)) { + for (const wxString& token : requested_symbol_tokens) { + if (!tokenizer.NextToken(tok)) { return false; } - if(tok.GetWXString() != token) { + if (tok.GetWXString() != token) { return false; } } // if we can read more tokens from the tokenizer, it means that // the comparison is not complete, it "contains" the requested name - if(tokenizer.NextToken(tok)) { + if (tokenizer.NextToken(tok)) { return false; } return true; @@ -319,19 +323,19 @@ TagEntryPtr CxxCodeCompletion::lookup_child_symbol(TagEntryPtr parent, TemplateM q.push_front(parent); wxStringSet_t visited; - while(!q.empty()) { + while (!q.empty()) { auto t = q.front(); q.pop_front(); // avoid visiting the same tag twice - if(!visited.insert(t->GetPath()).second) { + if (!visited.insert(t->GetPath()).second) { continue; } std::vector tags; m_lookup->GetTagsByScope(t->GetPath(), tags); - for(TagEntryPtr child : tags) { - if(compare_tokens_func(child->GetName())) { + for (TagEntryPtr child : tags) { + if (compare_tokens_func(child->GetName())) { return child; } } @@ -343,23 +347,24 @@ TagEntryPtr CxxCodeCompletion::lookup_child_symbol(TagEntryPtr parent, TemplateM return nullptr; } -TagEntryPtr CxxCodeCompletion::lookup_symbol_by_kind(const wxString& name, const std::vector& visible_scopes, +TagEntryPtr CxxCodeCompletion::lookup_symbol_by_kind(const wxString& name, + const std::vector& visible_scopes, const std::vector& kinds) { std::vector tags; std::vector scopes_to_check = visible_scopes; - if(scopes_to_check.empty()) { + if (scopes_to_check.empty()) { scopes_to_check.push_back(wxEmptyString); } - for(const wxString& scope : scopes_to_check) { + for (const wxString& scope : scopes_to_check) { wxString path; - if(!scope.empty()) { + if (!scope.empty()) { path << scope << "::"; } path << name; m_lookup->GetTagsByPathAndKind(path, tags, kinds); - if(tags.size() == 1) { + if (tags.size() == 1) { // we got a match return tags[0]; } @@ -367,17 +372,19 @@ TagEntryPtr CxxCodeCompletion::lookup_symbol_by_kind(const wxString& name, const return tags.empty() ? nullptr : tags[0]; } -void CxxCodeCompletion::update_template_table(TagEntryPtr resolved, CxxExpression& curexpr, - const std::vector& visible_scopes, wxStringSet_t& visited) +void CxxCodeCompletion::update_template_table(TagEntryPtr resolved, + CxxExpression& curexpr, + const std::vector& visible_scopes, + wxStringSet_t& visited) { CHECK_PTR_RET(resolved); - if(!visited.insert(resolved->GetPath()).second) { + if (!visited.insert(resolved->GetPath()).second) { // already visited this node return; } // simple template instantiation line - if(curexpr.is_template()) { + if (curexpr.is_template()) { curexpr.parse_template_placeholders(resolved->GetTemplateDefinition()); wxStringMap_t M = curexpr.get_template_placeholders_map(); m_template_manager->add_placeholders(M, visible_scopes); @@ -388,57 +395,64 @@ void CxxCodeCompletion::update_template_table(TagEntryPtr resolved, CxxExpressio CxxExpression::split_subclass_expression(normalize_pattern(resolved)); for (const wxString& inherit : inheritance_expressions) { std::vector more_expressions = from_expression(inherit + ".", nullptr); - if(more_expressions.empty()) { + if (more_expressions.empty()) { continue; } - auto match = lookup_symbol_by_kind(more_expressions[0].type_name(), visible_scopes, { "class", "struct" }); - if(match) { + auto match = lookup_symbol_by_kind(more_expressions[0].type_name(), visible_scopes, {"class", "struct"}); + if (match) { update_template_table(match, more_expressions[0], visible_scopes, visited); } } } -TagEntryPtr CxxCodeCompletion::lookup_symbol(CxxExpression& curexpr, const std::vector& visible_scopes, +TagEntryPtr CxxCodeCompletion::lookup_symbol(CxxExpression& curexpr, + const std::vector& visible_scopes, TagEntryPtr parent) { wxString name_to_find = curexpr.type_name(); auto resolved_name = m_template_manager->resolve(name_to_find, visible_scopes); - if(resolved_name != name_to_find) { + if (resolved_name != name_to_find) { name_to_find = resolved_name; auto expressions = from_expression(name_to_find + curexpr.operand_string(), nullptr); return resolve_compound_expression(expressions, visible_scopes, curexpr); } // try classes first - auto resolved = lookup_child_symbol(parent, m_template_manager, name_to_find, visible_scopes, - { "typedef", "class", "struct", "namespace", "enum", "union" }); - if(!resolved) { + auto resolved = lookup_child_symbol(parent, + m_template_manager, + name_to_find, + visible_scopes, + {"typedef", "class", "struct", "namespace", "enum", "union"}); + if (!resolved) { // try methods // `lookup_child_symbol` takes inheritance into consideration - resolved = lookup_child_symbol(parent, m_template_manager, name_to_find, visible_scopes, - { "function", "prototype", "member", "enumerator" }); + resolved = lookup_child_symbol(parent, + m_template_manager, + name_to_find, + visible_scopes, + {"function", "prototype", "member", "enumerator"}); } - if(resolved) { + if (resolved) { // update the template table wxStringSet_t visited; update_template_table(resolved, curexpr, visible_scopes, visited); // Check for operator-> overloading - if(curexpr.check_subscript_operator()) { + if (curexpr.check_subscript_operator()) { // we check for subscript before -> TagEntryPtr subscript_tag = lookup_subscript_operator(resolved, visible_scopes); - if(subscript_tag) { + if (subscript_tag) { resolved = subscript_tag; curexpr.pop_subscript_operator(); } } - if(curexpr.operand_string() == "->") { + if (curexpr.operand_string() == "->") { // search for operator-> overloading TagEntryPtr arrow_tag = lookup_operator_arrow(resolved, visible_scopes); - if(arrow_tag) { + if (arrow_tag) { resolved = arrow_tag; // change the operand from -> to . // to avoid extra resolving in case we are resolving expression like this: @@ -453,8 +467,8 @@ TagEntryPtr CxxCodeCompletion::lookup_symbol(CxxExpression& curexpr, const std:: } else { // still failed to resolve it, try macro // try macro - auto resolved = lookup_symbol_by_kind(curexpr.type_name(), {}, { "macro" }); - if(resolved && !resolved->GetMacrodef().empty()) { + auto resolved = lookup_symbol_by_kind(curexpr.type_name(), {}, {"macro"}); + if (resolved && !resolved->GetMacrodef().empty()) { // this is a macro auto expressions = from_expression(resolved->GetMacrodef() + curexpr.operand_string(), nullptr); return resolve_compound_expression(expressions, visible_scopes, curexpr); @@ -468,9 +482,9 @@ std::vector CxxCodeCompletion::update_visible_scope(const std::vector< std::vector scopes; scopes.insert(scopes.end(), curscopes.begin(), curscopes.end()); - if(tag && (tag->IsClass() || tag->IsStruct() || tag->IsNamespace() || tag->GetKind() == "union")) { + if (tag && (tag->IsClass() || tag->IsStruct() || tag->IsNamespace() || tag->GetKind() == "union")) { prepend_scope(scopes, tag->GetPath()); - } else if(tag && (tag->IsMethod() || tag->IsMember())) { + } else if (tag && (tag->IsMethod() || tag->IsMember())) { prepend_scope(scopes, tag->GetScope()); } return scopes; @@ -478,7 +492,7 @@ std::vector CxxCodeCompletion::update_visible_scope(const std::vector< TagEntryPtr CxxCodeCompletion::on_local(CxxExpression& curexp, const std::vector& visible_scopes) { // local member - if(m_locals.count(curexp.type_name()) == 0) { + if (m_locals.count(curexp.type_name()) == 0) { return nullptr; } @@ -490,7 +504,7 @@ TagEntryPtr CxxCodeCompletion::on_local(CxxExpression& curexp, const std::vector TagEntryPtr CxxCodeCompletion::on_parameter(CxxExpression& curexp, const std::vector& visible_scopes) { // local member - if(!m_file_only_tags.is_function_parameter(curexp.type_name())) { + if (!m_file_only_tags.is_function_parameter(curexp.type_name())) { return nullptr; } @@ -500,11 +514,11 @@ TagEntryPtr CxxCodeCompletion::on_parameter(CxxExpression& curexp, const std::ve return resolve_compound_expression(expr_arr, visible_scopes, curexp); } -TagEntryPtr CxxCodeCompletion::on_extern_var(CxxExpression& curexp, TagEntryPtr var, - const std::vector& visible_scopes) +TagEntryPtr +CxxCodeCompletion::on_extern_var(CxxExpression& curexp, TagEntryPtr var, const std::vector& visible_scopes) { // local member - if(!var) { + if (!var) { return nullptr; } @@ -515,7 +529,7 @@ TagEntryPtr CxxCodeCompletion::on_extern_var(CxxExpression& curexp, TagEntryPtr TagEntryPtr CxxCodeCompletion::on_static_local(CxxExpression& curexp, const std::vector& visible_scopes) { - if(!m_file_only_tags.is_static_member(curexp.type_name())) { + if (!m_file_only_tags.is_static_member(curexp.type_name())) { return nullptr; } @@ -527,7 +541,7 @@ TagEntryPtr CxxCodeCompletion::on_static_local(CxxExpression& curexp, const std: TagEntryPtr CxxCodeCompletion::on_this(CxxExpression& curexp, const std::vector& visible_scopes) { // this can only work with -> - if(curexp.operand_string() != "->") { + if (curexp.operand_string() != "->") { return nullptr; } @@ -541,8 +555,8 @@ TagEntryPtr CxxCodeCompletion::on_this(CxxExpression& curexp, const std::vector< TagEntryPtr CxxCodeCompletion::find_scope_tag_externvar(CxxExpression& curexp, const std::vector& visible_scopes) { - auto extern_var = lookup_symbol_by_kind(curexp.type_name(), visible_scopes, { "externvar" }); - if(extern_var) { + auto extern_var = lookup_symbol_by_kind(curexp.type_name(), visible_scopes, {"externvar"}); + if (extern_var) { // we are inside a scope, use the scope as the parent // and call resolve_expression() again return extern_var; @@ -561,36 +575,36 @@ TagEntryPtr CxxCodeCompletion::find_scope_tag(CxxExpression& curexp, const std:: std::vector paths_to_try; std::vector parent_tags; wxStringSet_t visited; - if(m_current_container_tag) { + if (m_current_container_tag) { // get list of scopes to try (including parents) parent_tags = get_scopes(m_current_container_tag, visible_scopes); paths_to_try.reserve(parent_tags.size()); - for(auto parent : parent_tags) { + for (auto parent : parent_tags) { wxString fullpath = parent->GetPath() + "::" + curexp.type_name(); - if(visited.insert(fullpath).second) { + if (visited.insert(fullpath).second) { paths_to_try.push_back(fullpath); } } } // add the other scopes - for(auto scope : visible_scopes) { + for (auto scope : visible_scopes) { // build the path wxString path_to_try; - if(!scope.empty()) { + if (!scope.empty()) { path_to_try << scope << "::"; } path_to_try << curexp.type_name(); - if(visited.insert(path_to_try).second) { + if (visited.insert(path_to_try).second) { paths_to_try.push_back(path_to_try); } } - for(const auto& path_to_try : paths_to_try) { + for (const auto& path_to_try : paths_to_try) { // note that we pass here empty visible_scopes since we already prepended it earlier auto scope_tag = - lookup_symbol_by_kind(path_to_try, {}, { "class", "struct", "union", "prototype", "function", "member" }); - if(scope_tag) { + lookup_symbol_by_kind(path_to_try, {}, {"class", "struct", "union", "prototype", "function", "member"}); + if (scope_tag) { // we are inside a scope, use the scope as the parent // and call resolve_expression() again return scope_tag; @@ -599,30 +613,31 @@ TagEntryPtr CxxCodeCompletion::find_scope_tag(CxxExpression& curexp, const std:: return nullptr; } -TagEntryPtr CxxCodeCompletion::resolve_expression(CxxExpression& curexp, TagEntryPtr parent, +TagEntryPtr CxxCodeCompletion::resolve_expression(CxxExpression& curexp, + TagEntryPtr parent, const std::vector& visible_scopes) { // test locals first, if its empty, its the first time we are entering here - if(m_first_time && !parent) { - if(curexp.is_this()) { + if (m_first_time && !parent) { + if (curexp.is_this()) { return on_this(curexp, visible_scopes); - } else if(curexp.operand_string() == "." || curexp.operand_string() == "->") { - if(m_locals.count(curexp.type_name())) { + } else if (curexp.operand_string() == "." || curexp.operand_string() == "->") { + if (m_locals.count(curexp.type_name())) { return on_local(curexp, visible_scopes); - } else if(m_file_only_tags.is_static_member(curexp.type_name())) { + } else if (m_file_only_tags.is_static_member(curexp.type_name())) { // static member to this file return on_static_local(curexp, visible_scopes); - } else if(m_file_only_tags.is_function_parameter(curexp.type_name())) { + } else if (m_file_only_tags.is_function_parameter(curexp.type_name())) { // function parameter return on_parameter(curexp, visible_scopes); - } else if(is_scope_tag(curexp, visible_scopes)) { + } else if (is_scope_tag(curexp, visible_scopes)) { // scoped tag (static variable, anonymous namespace tag etc) return resolve_expression(curexp, find_scope_tag(curexp, visible_scopes), visible_scopes); } else { auto externvar_tag = find_scope_tag_externvar(curexp, visible_scopes); - if(externvar_tag) { + if (externvar_tag) { return on_extern_var(curexp, externvar_tag, visible_scopes); } } @@ -635,38 +650,38 @@ TagEntryPtr CxxCodeCompletion::resolve_expression(CxxExpression& curexp, TagEntr auto resolved = lookup_symbol(curexp, scopes, parent); CHECK_PTR_RET_NULL(resolved); - if(resolved->IsContainer()) { + if (resolved->IsContainer()) { // nothing more to be done here return resolved; } // continue only if one of 3: member, method or typedef - if(!resolved->IsMethod() && !resolved->IsMember() && !resolved->IsTypedef()) { + if (!resolved->IsMethod() && !resolved->IsMember() && !resolved->IsTypedef()) { return nullptr; } // after we resolved the expression, update the scope scopes = update_visible_scope(scopes, resolved); - if(resolved->IsMethod()) { + if (resolved->IsMethod()) { return on_method(curexp, resolved, scopes); - } else if(resolved->IsTypedef()) { + } else if (resolved->IsTypedef()) { return on_typedef(curexp, resolved, scopes); - } else if(resolved->IsMember()) { + } else if (resolved->IsMember()) { return on_member(curexp, resolved, scopes); } return nullptr; } -TagEntryPtr CxxCodeCompletion::on_typedef(CxxExpression& curexp, TagEntryPtr tag, - const std::vector& visible_scopes) +TagEntryPtr +CxxCodeCompletion::on_typedef(CxxExpression& curexp, TagEntryPtr tag, const std::vector& visible_scopes) { // substitute the type with the typedef wxString new_expr; - if(!resolve_user_type(tag->GetPath(), visible_scopes, &new_expr)) { + if (!resolve_user_type(tag->GetPath(), visible_scopes, &new_expr)) { new_expr = typedef_from_tag(tag); } new_expr += curexp.operand_string(); @@ -674,13 +689,13 @@ TagEntryPtr CxxCodeCompletion::on_typedef(CxxExpression& curexp, TagEntryPtr tag return resolve_compound_expression(expr_arr, visible_scopes, curexp); } -TagEntryPtr CxxCodeCompletion::on_member(CxxExpression& curexp, TagEntryPtr tag, - const std::vector& visible_scopes) +TagEntryPtr +CxxCodeCompletion::on_member(CxxExpression& curexp, TagEntryPtr tag, const std::vector& visible_scopes) { // replace the member variable by its type std::unordered_map locals_variables; - if((parse_locals(normalize_pattern(tag), &locals_variables) == 0) || - (locals_variables.count(tag->GetName()) == 0)) { + if ((parse_locals(normalize_pattern(tag), &locals_variables) == 0) || + (locals_variables.count(tag->GetName()) == 0)) { return nullptr; } @@ -689,8 +704,8 @@ TagEntryPtr CxxCodeCompletion::on_member(CxxExpression& curexp, TagEntryPtr tag, return resolve_compound_expression(expr_arr, visible_scopes, curexp); } -TagEntryPtr CxxCodeCompletion::on_method(CxxExpression& curexp, TagEntryPtr tag, - const std::vector& visible_scopes) +TagEntryPtr +CxxCodeCompletion::on_method(CxxExpression& curexp, TagEntryPtr tag, const std::vector& visible_scopes) { // parse the return value wxString new_expr = get_return_value(tag) + curexp.operand_string(); @@ -700,16 +715,13 @@ TagEntryPtr CxxCodeCompletion::on_method(CxxExpression& curexp, TagEntryPtr tag, const wxStringMap_t& CxxCodeCompletion::get_tokens_map() const { return m_macros_table_map; } -wxString CxxCodeCompletion::get_return_value(TagEntryPtr tag) const -{ - return tag->GetTypename(); -} +wxString CxxCodeCompletion::get_return_value(TagEntryPtr tag) const { return tag->GetTypename(); } void CxxCodeCompletion::prepend_scope(std::vector& scopes, const wxString& scope) const { auto find_and_erase_cb = [&scopes](const wxString& scope_name) { auto where = find_if(scopes.begin(), scopes.end(), [=](const wxString& __s) { return __s == scope_name; }); - if(where != scopes.end()) { + if (where != scopes.end()) { scopes.erase(where); } }; @@ -717,8 +729,8 @@ void CxxCodeCompletion::prepend_scope(std::vector& scopes, const wxStr // if this is a complex scope, break it and add all possible values wxArrayString parts = ::wxStringTokenize(scope, ":", wxStringTokenizerMode::wxTOKEN_STRTOK); wxString scope_name; - for(const wxString& part : parts) { - if(!scope_name.empty()) { + for (const wxString& part : parts) { + if (!scope_name.empty()) { scope_name << "::"; } scope_name << part; @@ -744,18 +756,18 @@ namespace wxString read_n_lines_from_file(size_t from_line, size_t line_count, const wxString& filepath) { wxString content; - if(!FileUtils::ReadFileContent(filepath, content)) { + if (!FileUtils::ReadFileContent(filepath, content)) { return wxEmptyString; } wxArrayString lines = ::wxStringTokenize(content, "\n", wxTOKEN_RET_EMPTY_ALL); - if(from_line >= lines.size()) { + if (from_line >= lines.size()) { return wxEmptyString; } size_t first_line = from_line; size_t last_line = wxMin(from_line + line_count, lines.size() - 1); content.Clear(); - for(size_t i = first_line; i < last_line; ++i) { + for (size_t i = first_line; i < last_line; ++i) { content << lines[i]; } return content; @@ -768,7 +780,7 @@ wxString CxxCodeCompletion::typedef_from_tag(TagEntryPtr tag) const CxxTokenizer tkzr; CxxLexerToken tk; - if(!tag->GetTypename().empty()) { + if (!tag->GetTypename().empty()) { typedef_str = tag->GetTypename(); return typedef_str.Trim(); } @@ -782,7 +794,7 @@ wxString CxxCodeCompletion::typedef_from_tag(TagEntryPtr tag) const tkzr.NextToken(tk); bool parse_succeeded = false; - if(tk.GetType() == T_TEMPLATE) { + if (tk.GetType() == T_TEMPLATE) { // instead of reading the pattern, read 10 lines from the source code and use that instead // (ctags is not that good at collecting typedef properly) pattern = read_n_lines_from_file(tag->GetLine() - 1, 10, tag->GetFile()); @@ -793,51 +805,51 @@ wxString CxxCodeCompletion::typedef_from_tag(TagEntryPtr tag) const tkzr.NextToken(tk); } - if(tk.GetType() == T_USING) { + if (tk.GetType() == T_USING) { // "using" syntax: // using element_type = _Tp; // read until the "="; // consume everything until we find the "=" - while(tkzr.NextToken(tk)) { - if(tk.GetType() == '=') { + while (tkzr.NextToken(tk)) { + if (tk.GetType() == '=') { break; } } // read until the ";" - while(tkzr.NextToken(tk)) { - if(tk.GetType() == ';') { + while (tkzr.NextToken(tk)) { + if (tk.GetType() == ';') { parse_succeeded = true; break; } - if(tk.is_keyword()) { + if (tk.is_keyword()) { // don't pick keywords continue; } - if(tk.is_builtin_type()) { + if (tk.is_builtin_type()) { V.push_back((V.empty() ? "" : " ") + tk.GetWXString() + " "); } else { V.push_back(tk.GetWXString()); } } - } else if(tk.GetType() == T_TYPEDEF) { + } else if (tk.GetType() == T_TYPEDEF) { // standard "typedef" syntax: // typedef wxString MyString; - while(tkzr.NextToken(tk)) { - if(tk.is_keyword()) { + while (tkzr.NextToken(tk)) { + if (tk.is_keyword()) { continue; } - if(tk.GetType() == ';') { + if (tk.GetType() == ';') { // end of typedef - if(!V.empty()) { + if (!V.empty()) { V.pop_back(); } parse_succeeded = true; break; } else { - if(tk.is_builtin_type()) { + if (tk.is_builtin_type()) { V.push_back((V.empty() ? "" : " ") + tk.GetWXString() + " "); } else { V.push_back(tk.GetWXString()); @@ -846,10 +858,10 @@ wxString CxxCodeCompletion::typedef_from_tag(TagEntryPtr tag) const } } - if(!parse_succeeded) { + if (!parse_succeeded) { return wxEmptyString; } else { - for(const wxString& s : V) { + for (const wxString& s : V) { typedef_str << s; } } @@ -862,7 +874,7 @@ std::vector CxxCodeCompletion::get_locals(const wxString& filter) c locals.reserve(m_locals.size()); wxString lowercase_filter = filter.Lower(); - for(const auto& vt : m_locals) { + for (const auto& vt : m_locals) { const auto& local = vt.second; TagEntryPtr tag(new TagEntry()); tag->SetName(local.name()); @@ -872,7 +884,7 @@ std::vector CxxCodeCompletion::get_locals(const wxString& filter) c tag->SetAccess("public"); tag->SetPattern("/^ " + local.pattern() + " $/"); tag->SetLine(local.line_number()); - if(!tag->GetName().Lower().StartsWith(lowercase_filter)) { + if (!tag->GetName().Lower().StartsWith(lowercase_filter)) { continue; } locals.push_back(tag); @@ -880,18 +892,30 @@ std::vector CxxCodeCompletion::get_locals(const wxString& filter) c return locals; } -size_t CxxCodeCompletion::get_completions(TagEntryPtr parent, const wxString& operand_string, const wxString& filter, +size_t CxxCodeCompletion::get_completions(TagEntryPtr parent, + const wxString& operand_string, + const wxString& filter, std::vector& candidates, - const std::vector& visible_scopes, size_t limit) + const std::vector& visible_scopes, + size_t limit) { - if(!parent) { + if (!parent) { return 0; } - std::vector kinds = { "function", "prototype", "member", "enum", "enumerator", "class", - "struct", "union", "namespace", "typedef", "variable" }; - if(operand_string == "." || operand_string == "->") { - kinds = { "prototype", "function", "member" }; + std::vector kinds = {"function", + "prototype", + "member", + "enum", + "enumerator", + "class", + "struct", + "union", + "namespace", + "typedef", + "variable"}; + if (operand_string == "." || operand_string == "->") { + kinds = {"prototype", "function", "member"}; } // the global scope candidates = get_children_of_scope(parent, kinds, filter, visible_scopes); @@ -906,8 +930,8 @@ size_t CxxCodeCompletion::get_completions(TagEntryPtr parent, const wxString& op // this is done in O(n) ordered_candidates.reserve(candidates.size()); functions_candidates.reserve(candidates.size()); - for(TagEntryPtr tag : candidates) { - if(tag->IsFunction()) { + for (TagEntryPtr tag : candidates) { + if (tag->IsFunction()) { functions_candidates.emplace_back(tag); } else { ordered_candidates.emplace_back(tag); @@ -921,16 +945,16 @@ size_t CxxCodeCompletion::get_completions(TagEntryPtr parent, const wxString& op std::vector unique_candidates; unique_candidates.reserve(candidates.size()); CompletionHelper helper; - for(TagEntryPtr tag : candidates) { + for (TagEntryPtr tag : candidates) { // by default, the path is enough // however, for methods, we also include the method // signature wxString unique_path = tag->GetPath(); - if(tag->IsMethod()) { + if (tag->IsMethod()) { unique_path = helper.normalize_function(tag); } - if(!visited.insert(unique_path).second) { + if (!visited.insert(unique_path).second) { // already seen this continue; } @@ -942,7 +966,7 @@ size_t CxxCodeCompletion::get_completions(TagEntryPtr parent, const wxString& op auto sort_cb = [=](TagEntryPtr a, TagEntryPtr b) { return a->GetName().CmpNoCase(b->GetName()) < 0; }; sort(unique_candidates.begin(), unique_candidates.end(), sort_cb); // truncate the list to match the limit - if(unique_candidates.size() > limit) { + if (unique_candidates.size() > limit) { unique_candidates.resize(limit); } candidates.swap(unique_candidates); @@ -963,12 +987,12 @@ std::vector CxxCodeCompletion::get_scopes(TagEntryPtr parent, const q.push_front(parent); wxStringSet_t visited; - while(!q.empty()) { + while (!q.empty()) { auto t = q.front(); q.pop_front(); // avoid visiting the same tag twice - if(!visited.insert(t->GetPath()).second) { + if (!visited.insert(t->GetPath()).second) { continue; } @@ -985,15 +1009,15 @@ std::vector CxxCodeCompletion::get_children_of_scope(TagEntryPtr pa const wxString& filter, const std::vector& visible_scopes) { - if(!m_lookup) { + if (!m_lookup) { return {}; } std::vector tags; auto parents = get_scopes(parent, visible_scopes); - for(auto tag : parents) { + for (auto tag : parents) { wxString scope = tag->GetPath(); - if(tag->IsMethod()) { + if (tag->IsMethod()) { scope = tag->GetScope(); } std::vector parent_tags; @@ -1020,12 +1044,13 @@ void CxxCodeCompletion::set_text(const wxString& text, const wxString& filename, namespace { -bool find_wild_match(const std::vector>& table, const wxString& find_what, +bool find_wild_match(const std::vector>& table, + const wxString& find_what, wxString* match) { - for(const auto& p : table) { + for (const auto& p : table) { // we support wildcard matching - if(::wxMatchWild(p.first, find_what)) { + if (::wxMatchWild(p.first, find_what)) { *match = p.second; return true; } @@ -1033,16 +1058,18 @@ bool find_wild_match(const std::vector>& table, co return false; } -bool try_resolve_user_type_with_scopes(const std::vector>& table, const wxString& type, - const std::vector& visible_scopes, wxString* resolved) +bool try_resolve_user_type_with_scopes(const std::vector>& table, + const wxString& type, + const std::vector& visible_scopes, + wxString* resolved) { - for(const wxString& scope : visible_scopes) { + for (const wxString& scope : visible_scopes) { wxString user_type = scope; - if(!user_type.empty()) { + if (!user_type.empty()) { user_type << "::"; } user_type << type; - if(find_wild_match(table, type, resolved)) { + if (find_wild_match(table, type, resolved)) { return true; } } @@ -1050,14 +1077,15 @@ bool try_resolve_user_type_with_scopes(const std::vector& visible_scopes, +bool CxxCodeCompletion::resolve_user_type(const wxString& type, + const std::vector& visible_scopes, wxString* resolved) const { bool match_found = false; wxStringSet_t visited; *resolved = type; - while(true) { - if(!visited.insert(*resolved).second) { + while (true) { + if (!visited.insert(*resolved).second) { // already tried this type break; } @@ -1068,7 +1096,7 @@ bool CxxCodeCompletion::resolve_user_type(const wxString& type, const std::vecto match_found = true; } - if(match_found) { + if (match_found) { return true; } return false; @@ -1082,14 +1110,17 @@ void TemplateManager::add_placeholders(const wxStringMap_t& table, const std::ve // try to resolve any of the template before we insert them // its important to do it now so we use the correct scope wxStringMap_t M; - for(const auto& vt : table) { + for (const auto& vt : table) { wxString name = vt.first; wxString value; auto resolved = m_completer->lookup_child_symbol( - nullptr, nullptr, vt.second, visible_scopes, - { "class", "struct", "typedef", "union", "namespace", "enum", "enumerator" }); - if(resolved) { + nullptr, + nullptr, + vt.second, + visible_scopes, + {"class", "struct", "typedef", "union", "namespace", "enum", "enumerator"}); + if (resolved) { // use the path found in the db value = resolved->GetPath(); } else { @@ -1102,7 +1133,7 @@ void TemplateManager::add_placeholders(const wxStringMap_t& table, const std::ve // if the resolve will fail, it will return vt.second unmodified value = this->resolve(vt.second, visible_scopes); } - M.insert({ name, value }); + M.insert({name, value}); } m_table.insert(m_table.begin(), M); } @@ -1120,7 +1151,7 @@ bool try_resolve_placeholder(const wxStringMap_t& table, const wxString& name, w wxString stripped_placeholder = name; STRIP_PLACEHOLDER(stripped_placeholder); - if(table.count(name)) { + if (table.count(name)) { *resolved = table.find(name)->second; return true; } @@ -1132,7 +1163,7 @@ wxString TemplateManager::resolve(const wxString& name, const std::vector& tags, std::vector& sorted_tags, - bool include_ctor_dtor, const wxStringSet_t& visible_files) +void CxxCodeCompletion::sort_tags(const std::vector& tags, + std::vector& sorted_tags, + bool include_ctor_dtor, + const wxStringSet_t& visible_files) { TagEntryPtrVector_t publicTags; TagEntryPtrVector_t protectedTags; @@ -1164,22 +1197,22 @@ void CxxCodeCompletion::sort_tags(const std::vector& tags, std::vec for (const auto& tag : tags) { // only include matches from the provided list of files - if(!visible_files.empty() && visible_files.count(tag->GetFile()) == 0) { + if (!visible_files.empty() && visible_files.count(tag->GetFile()) == 0) { continue; } - if(skip_tor && (tag->IsConstructor() || tag->IsDestructor())) { + if (skip_tor && (tag->IsConstructor() || tag->IsDestructor())) { continue; } bool is_local = tag->IsLocalVariable() || tag->GetScope() == "" || tag->GetParent() == ""; // we filter local tags by name - if(is_local && !visited_by_name.insert(tag->GetName()).second) { + if (is_local && !visited_by_name.insert(tag->GetName()).second) { continue; } // other tags (loaded from the db) are filtered by their ID - if(!is_local && !visited_by_id.insert(tag->GetId()).second) { + if (!is_local && !visited_by_id.insert(tag->GetId()).second) { continue; } @@ -1187,20 +1220,20 @@ void CxxCodeCompletion::sort_tags(const std::vector& tags, std::vec wxString access = tag->GetAccess(); wxString kind = tag->GetKind(); - if(kind == "variable") { + if (kind == "variable") { locals.push_back(tag); - } else if(kind == "member") { + } else if (kind == "member") { members.push_back(tag); - } else if(access == "private") { + } else if (access == "private") { privateTags.push_back(tag); - } else if(access == "protected") { + } else if (access == "protected") { protectedTags.push_back(tag); - } else if(access == "public") { - if(tag->GetName().StartsWith("_") || tag->GetName().Contains("operator")) { + } else if (access == "public") { + if (tag->GetName().StartsWith("_") || tag->GetName().Contains("operator")) { // methods starting with _ usually are meant to be private // and also, put the "operator" methods at the bottom privateTags.push_back(tag); @@ -1230,25 +1263,26 @@ void CxxCodeCompletion::sort_tags(const std::vector& tags, std::vec sorted_tags.insert(sorted_tags.end(), members.begin(), members.end()); } -size_t CxxCodeCompletion::get_file_completions(const wxString& user_typed, std::vector& files, +size_t CxxCodeCompletion::get_file_completions(const wxString& user_typed, + std::vector& files, const wxString& suffix) { - if(!m_lookup) { + if (!m_lookup) { return 0; } wxArrayString files_arr; m_lookup->GetFilesForCC(user_typed, files_arr); - + wxString prefix; if (user_typed.find('/') != user_typed.npos) { prefix = user_typed.BeforeLast('/').append('/'); } - + files.reserve(files_arr.size()); - for(const wxString& file : files_arr) { + for (const wxString& file : files_arr) { // exclude source file - if(FileExtManager::GetType(file) == FileExtManager::TypeSourceC || - FileExtManager::GetType(file) == FileExtManager::TypeSourceCpp) { + if (FileExtManager::GetType(file) == FileExtManager::TypeSourceC || + FileExtManager::GetType(file) == FileExtManager::TypeSourceCpp) { continue; } TagEntryPtr tag(new TagEntry()); @@ -1268,14 +1302,15 @@ size_t CxxCodeCompletion::get_file_completions(const wxString& user_typed, std:: return files.size(); } -size_t CxxCodeCompletion::get_children_of_current_scope(const std::vector& kinds, const wxString& filter, +size_t CxxCodeCompletion::get_children_of_current_scope(const std::vector& kinds, + const wxString& filter, const std::vector& visible_scopes, std::vector* current_scope_children, std::vector* other_scopes_children, std::vector* global_scope_children) { determine_current_scope(); - if(m_current_container_tag) { + if (m_current_container_tag) { *current_scope_children = get_children_of_scope(m_current_container_tag, kinds, filter, visible_scopes); } @@ -1289,7 +1324,8 @@ size_t CxxCodeCompletion::get_children_of_current_scope(const std::vectorsize() + other_scopes_children->size() + global_scope_children->size(); } -size_t CxxCodeCompletion::get_word_completions(const CxxRemainder& remainder, std::vector& candidates, +size_t CxxCodeCompletion::get_word_completions(const CxxRemainder& remainder, + std::vector& candidates, const std::vector& visible_scopes, const wxStringSet_t& visible_files) @@ -1316,25 +1352,44 @@ size_t CxxCodeCompletion::get_word_completions(const CxxRemainder& remainder, st // based on the lasts operand, build the list of items to fetch determine_current_scope(); bool add_keywords = false; - if(remainder.operand_string.empty()) { - kinds = { "function", "prototype", "class", "struct", "namespace", "union", "typedef", - "enum", "enumerator", "macro", "cenum", "variable", "externvar" }; - if(m_current_container_tag) { + if (remainder.operand_string.empty()) { + kinds = {"function", + "prototype", + "class", + "struct", + "namespace", + "union", + "typedef", + "enum", + "enumerator", + "macro", + "cenum", + "variable", + "externvar"}; + if (m_current_container_tag) { // if we are inside a scope, add member types kinds.push_back("member"); } add_keywords = true; - } else if(remainder.operand_string == "::") { - kinds = { "member", "function", "prototype", "class", "struct", - "namespace", "union", "typedef", "enum", "enumerator" }; + } else if (remainder.operand_string == "::") { + kinds = {"member", + "function", + "prototype", + "class", + "struct", + "namespace", + "union", + "typedef", + "enum", + "enumerator"}; } else { // contextual completions - kinds = { "member", "function", "prototype" }; + kinds = {"member", "function", "prototype"}; } // collect member variables if we are within a scope - get_children_of_current_scope(kinds, remainder.filter, scopes, &scope_members, &other_scopes_members, - &global_scopes_members); + get_children_of_current_scope( + kinds, remainder.filter, scopes, &scope_members, &other_scopes_members, &global_scopes_members); // sort the matches: sort_tags(locals, sorted_locals, true, {}); // locals are accepted, so don't pass list of files @@ -1342,7 +1397,7 @@ size_t CxxCodeCompletion::get_word_completions(const CxxRemainder& remainder, st sort_tags(other_scopes_members, sorted_other_scopes_members, true, visible_files); sort_tags(global_scopes_members, sorted_global_scopes_members, true, visible_files); - if(add_keywords) { + if (add_keywords) { get_keywords_tags(remainder.filter, keywords); } candidates.reserve(sorted_locals.size() + sorted_scope_members.size() + sorted_other_scopes_members.size() + @@ -1358,8 +1413,11 @@ size_t CxxCodeCompletion::get_word_completions(const CxxRemainder& remainder, st return candidates.size(); } -size_t CxxCodeCompletion::find_definition(const wxString& filepath, int line, const wxString& expression, - const wxString& text, const std::vector& visible_scopes, +size_t CxxCodeCompletion::find_definition(const wxString& filepath, + int line, + const wxString& expression, + const wxString& text, + const std::vector& visible_scopes, std::vector& matches) { std::vector candidates; @@ -1367,8 +1425,8 @@ size_t CxxCodeCompletion::find_definition(const wxString& filepath, int line, co // check if we are currently (file:line) on a function definition / declaration std::vector tmp_candidates; m_lookup->GetTagsByFileAndLine(filepath, line, tmp_candidates); - if((tmp_candidates.size() == 1) && (tmp_candidates[0]->GetName() == expression) && - (tmp_candidates[0]->IsMethod())) { + if ((tmp_candidates.size() == 1) && (tmp_candidates[0]->GetName() == expression) && + (tmp_candidates[0]->IsMethod())) { // we found our tag, now candidates.swap(tmp_candidates); } else { @@ -1376,11 +1434,11 @@ size_t CxxCodeCompletion::find_definition(const wxString& filepath, int line, co clDEBUG() << "find_definition(): calling word_complete(): is called for expression:" << expression << endl; word_complete(filepath, line, expression, text, visible_scopes, true, candidates); // filter all the tags - if(candidates.empty() || (candidates.size() == 1 && (candidates[0]->GetLine() == wxNOT_FOUND))) { + if (candidates.empty() || (candidates.size() == 1 && (candidates[0]->GetLine() == wxNOT_FOUND))) { clDEBUG() << "Unable to complete, checking on the current location" << endl; candidates.clear(); m_lookup->GetTagsByFileAndLine(filepath, line, candidates); - if(candidates.empty()) { + if (candidates.empty()) { return 0; } clDEBUG() << "find_definition(): on a tag:" << candidates[0]->GetFullDisplayName() << "." @@ -1391,60 +1449,60 @@ size_t CxxCodeCompletion::find_definition(const wxString& filepath, int line, co // filter tags with no line numbers std::vector good_tags; TagEntryPtr first; - for(auto tag : candidates) { - if(tag->GetLine() != wxNOT_FOUND && !tag->GetFile().empty()) { + for (auto tag : candidates) { + if (tag->GetLine() != wxNOT_FOUND && !tag->GetFile().empty()) { first = tag; break; } } - if(!first) { + if (!first) { return 0; } - if(first->IsMethod()) { + if (first->IsMethod()) { // we prefer the definition, unless we are already on it, and in that case, return the declaration // locate both declaration + implementation wxString path = first->GetPath(); std::vector impl_vec; std::vector decl_vec; clDEBUG() << "Searching for path:" << path << endl; - m_lookup->GetTagsByPathAndKind(path, impl_vec, { "function" }, 100); - m_lookup->GetTagsByPathAndKind(path, decl_vec, { "prototype" }, 100); + m_lookup->GetTagsByPathAndKind(path, impl_vec, {"function"}, 100); + m_lookup->GetTagsByPathAndKind(path, decl_vec, {"prototype"}, 100); clDEBUG() << "impl:" << impl_vec.size() << "decl:" << decl_vec.size() << endl; // if no impl found, return the decl vector - if(impl_vec.empty()) { + if (impl_vec.empty()) { matches.swap(decl_vec); return matches.size(); } // if no decl found, return the impl vector (a more rare case, but this can happen) - if(decl_vec.empty()) { + if (decl_vec.empty()) { matches.swap(impl_vec); return matches.size(); } auto is_on_line = [](const std::vector& tags_vec, int line, const wxString& file) { - for(auto tag : tags_vec) { - if(tag->GetLine() == line && tag->GetFile() == file) { + for (auto tag : tags_vec) { + if (tag->GetLine() == line && tag->GetFile() == file) { return true; } } return false; }; - if(is_on_line(impl_vec, line, filepath)) { + if (is_on_line(impl_vec, line, filepath)) { matches.swap(decl_vec); return matches.size(); } - if(is_on_line(decl_vec, line, filepath)) { + if (is_on_line(decl_vec, line, filepath)) { matches.swap(impl_vec); return matches.size(); } // by default we return the "impl" - if(!impl_vec.empty()) { + if (!impl_vec.empty()) { matches.swap(impl_vec); } else { matches.swap(decl_vec); @@ -1457,9 +1515,13 @@ size_t CxxCodeCompletion::find_definition(const wxString& filepath, int line, co } } -size_t CxxCodeCompletion::word_complete(const wxString& filepath, int line, const wxString& expression, - const wxString& text, const std::vector& visible_scopes, - bool exact_match, std::vector& candidates, +size_t CxxCodeCompletion::word_complete(const wxString& filepath, + int line, + const wxString& expression, + const wxString& text, + const std::vector& visible_scopes, + bool exact_match, + std::vector& candidates, const wxStringSet_t& visible_files) { // ---------------------------------- @@ -1472,18 +1534,18 @@ size_t CxxCodeCompletion::word_complete(const wxString& filepath, int line, cons TagEntryPtr resolved = code_complete(expression, visible_scopes, &remainder); wxString filter = remainder.filter; - if(!resolved) { + if (!resolved) { // check if this is a contextual text (A::B or a->b or a.b etc) // we only allow global completion of there is not expression list // and the remainder has something in it (r.type_name() is not empty) CxxRemainder r; auto expressions = from_expression(expression, &r); - if(expressions.size() == 0 && !r.filter.empty()) { + if (expressions.size() == 0 && !r.filter.empty()) { clDEBUG() << "code_complete failed to resolve:" << expression << endl; clDEBUG() << "filter:" << r.filter << endl; get_word_completions(remainder, candidates, visible_scopes, visible_files); } - } else if(resolved) { + } else if (resolved) { // it was resolved into something... clDEBUG() << "code_complete resolved:" << resolved->GetPath() << endl; clDEBUG() << "filter:" << remainder.filter << endl; @@ -1492,14 +1554,14 @@ size_t CxxCodeCompletion::word_complete(const wxString& filepath, int line, cons clDEBUG() << "Number of completion entries:" << candidates.size() << endl; // take the first one with the exact match - if(!exact_match) { + if (!exact_match) { return candidates.size(); } std::vector matches; matches.reserve(candidates.size()); - for(TagEntryPtr t : candidates) { - if(t->GetName() == filter) { + for (TagEntryPtr t : candidates) { + if (t->GetName() == filter) { matches.push_back(t); } } @@ -1514,18 +1576,18 @@ wxString CxxCodeCompletion::normalize_pattern(TagEntryPtr tag) const tokenizer.Reset(tag->GetPatternClean()); wxString pattern; - while(tokenizer.NextToken(tk)) { + while (tokenizer.NextToken(tk)) { wxString str = tk.GetWXString(); - switch(tk.GetType()) { + switch (tk.GetType()) { case T_IDENTIFIER: - if(m_macros_table_map.count(str) && m_macros_table_map.find(str)->second.empty()) { + if (m_macros_table_map.count(str) && m_macros_table_map.find(str)->second.empty()) { // skip this token } else { pattern << str << " "; } break; default: - if(tk.is_keyword() || tk.is_builtin_type()) { + if (tk.is_keyword() || tk.is_builtin_type()) { pattern << str << " "; } else { pattern << str; @@ -1536,10 +1598,11 @@ wxString CxxCodeCompletion::normalize_pattern(TagEntryPtr tag) const return pattern; } -size_t CxxCodeCompletion::get_anonymous_tags(const wxString& name, const wxArrayString& kinds, +size_t CxxCodeCompletion::get_anonymous_tags(const wxString& name, + const wxArrayString& kinds, std::vector& tags) const { - if(!m_lookup) { + if (!m_lookup) { return 0; } m_lookup->GetFileScopedTags(m_filename, name, kinds, tags); @@ -1553,8 +1616,8 @@ size_t CxxCodeCompletion::get_keywords_tags(const wxString& name, std::vectorSetName(keyword); tag->SetPath(keyword); @@ -1568,11 +1631,11 @@ size_t CxxCodeCompletion::get_keywords_tags(const wxString& name, std::vector& tags) { - if(!tag->IsClass() && !tag->IsStruct()) { + if (!tag->IsClass() && !tag->IsStruct()) { tags.clear(); return tags.size(); } - m_lookup->GetTagsByPathAndKind(tag->GetPath() + "::" + tag->GetName(), tags, { "prototype", "function" }, 250); + m_lookup->GetTagsByPathAndKind(tag->GetPath() + "::" + tag->GetName(), tags, {"prototype", "function"}, 250); std::vector sorted_tags; // filter duplicate @@ -1584,7 +1647,7 @@ size_t CxxCodeCompletion::get_class_constructors(TagEntryPtr tag, std::vector CxxCodeCompletion::from_expression(const wxString& expression, CxxRemainder* remainder) { auto arr = CxxExpression::from_expression(expression, remainder); - for(auto& exp : arr) { + for (auto& exp : arr) { simple_pre_process(exp.type_name()); } return arr; @@ -1594,13 +1657,13 @@ wxString& CxxCodeCompletion::simple_pre_process(wxString& name) const { wxStringSet_t visited; - while(true) { - if(!visited.insert(name).second) { + while (true) { + if (!visited.insert(name).second) { // entering a loop here... break; } - if(m_macros_table_map.count(name) == 0) { + if (m_macros_table_map.count(name) == 0) { // no match break; } @@ -1620,18 +1683,18 @@ std::vector CxxCodeCompletion::get_parents_of_tag_no_recurse(TagEnt std::vector parents; parents.reserve(inherits.size()); - for(size_t i = 0; i < inherits.size(); ++i) { + for (size_t i = 0; i < inherits.size(); ++i) { wxString& inherit = inherits[i]; wxString to_search = simple_pre_process(inherit); // run it in the template manager as well - if(template_manager) { + if (template_manager) { to_search = template_manager->resolve(to_search, visible_scopes); } - auto match = lookup_symbol_by_kind(to_search, visible_scopes, { "class", "struct" }); - if(match) { - if(template_manager && (inherits_with_template.size() == inherits.size()) && match->IsClassTemplate() && - (inherit != inherits_with_template[i])) { + auto match = lookup_symbol_by_kind(to_search, visible_scopes, {"class", "struct"}); + if (match) { + if (template_manager && (inherits_with_template.size() == inherits.size()) && match->IsClassTemplate() && + (inherit != inherits_with_template[i])) { // the goal of this `if` branch is to parse the template initialisation // line and update the template manager in case we need this information // later along the way @@ -1646,7 +1709,7 @@ std::vector CxxCodeCompletion::get_parents_of_tag_no_recurse(TagEnt // we want to extract the value `String` // auto exprs = CxxExpression::from_expression(inherits_with_template[i] + "::", nullptr); - if(!exprs.empty()) { + if (!exprs.empty()) { auto& expression = exprs[0]; expression.parse_template_placeholders(match->GetTemplateDefinition()); auto M = expression.get_template_placeholders_map(); @@ -1662,17 +1725,17 @@ std::vector CxxCodeCompletion::get_parents_of_tag_no_recurse(TagEnt std::vector CxxCodeCompletion::prepend_extra_scopes(const std::vector& visible_scopes) { std::vector scopes = m_file_only_tags.get_file_scopes(); - wxStringSet_t unique_scopes{ scopes.begin(), scopes.end() }; + wxStringSet_t unique_scopes{scopes.begin(), scopes.end()}; // append only unique scopes scopes.reserve(scopes.size() + visible_scopes.size() + 1); - for(const wxString& scope : visible_scopes) { - if(unique_scopes.insert(scope).second) { + for (const wxString& scope : visible_scopes) { + if (unique_scopes.insert(scope).second) { scopes.push_back(scope); } } - if(unique_scopes.count("") == 0) { + if (unique_scopes.count("") == 0) { // add the global scope scopes.push_back(wxEmptyString); } diff --git a/CodeLite/Cxx/CxxExpression.cpp b/CodeLite/Cxx/CxxExpression.cpp index 0a0d66ae58..d83de561ee 100644 --- a/CodeLite/Cxx/CxxExpression.cpp +++ b/CodeLite/Cxx/CxxExpression.cpp @@ -11,17 +11,17 @@ std::vector CxxExpression::from_expression(const wxString& expres wxString cast_type; tokenizer.Reset(expression); - if(handle_cxx_casting(tokenizer, &cast_type)) { + if (handle_cxx_casting(tokenizer, &cast_type)) { tokenizer.Reset(cast_type); } std::vector arr; CxxExpression curexpr; - while(tokenizer.NextToken(tk)) { - switch(tk.GetType()) { + while (tokenizer.NextToken(tk)) { + switch (tk.GetType()) { case T_IDENTIFIER: - if(curexpr.m_type_name.empty()) { + if (curexpr.m_type_name.empty()) { curexpr.m_type_name = tk.GetWXString(); } break; @@ -40,16 +40,16 @@ std::vector CxxExpression::from_expression(const wxString& expres parse_template(tokenizer, &curexpr.m_template_init_list); break; case '(': - if(curexpr.m_type_name.empty()) { + if (curexpr.m_type_name.empty()) { int delim_found = 0; wxString consumed; tokenizer.read_until_find(tk, ')', 0, &delim_found, &consumed); - if(delim_found == 0) { + if (delim_found == 0) { return {}; // unbalacned parenthesis } consumed += "."; auto parts = from_expression(consumed, nullptr); - if(!parts.empty()) { + if (!parts.empty()) { arr.insert(arr.end(), parts.begin(), parts.end() - 1); parts.back().set_operand(0); // remove the dummy operand curexpr = parts.back(); @@ -68,13 +68,13 @@ std::vector CxxExpression::from_expression(const wxString& expres } } - if(!curexpr.m_type_name.empty() && remainder) { + if (!curexpr.m_type_name.empty() && remainder) { // build the remainder remainder->filter = curexpr.type_name(); } // always copy the operand - if(remainder && !arr.empty()) { + if (remainder && !arr.empty()) { // copy the operand string from the last expression in the chain remainder->operand_string = arr.back().operand_string(); } @@ -85,16 +85,16 @@ bool CxxExpression::parse_list(CxxTokenizer& tokenizer, wxArrayString* params, i { #define ADD_IF_NOT_EMPTY(param) \ param.Trim().Trim(false); \ - if(!param.empty()) { \ + if (!param.empty()) { \ params->push_back(param); \ } CxxLexerToken tk; int depth = 0; wxString curparam; - while(tokenizer.NextToken(tk)) { - if(close_char == tk.GetType()) { - if(depth == 0) { + while (tokenizer.NextToken(tk)) { + if (close_char == tk.GetType()) { + if (depth == 0) { ADD_IF_NOT_EMPTY(curparam); return true; } else { @@ -103,15 +103,15 @@ bool CxxExpression::parse_list(CxxTokenizer& tokenizer, wxArrayString* params, i } continue; - } else if(open_char == tk.GetType()) { + } else if (open_char == tk.GetType()) { depth++; curparam << tk.GetWXString(); continue; - } else if(tk.is_keyword()) { + } else if (tk.is_keyword()) { continue; } else { - switch(tk.GetType()) { + switch (tk.GetType()) { case T_DOUBLE_COLONS: case T_IDENTIFIER: curparam << tk.GetWXString(); @@ -122,7 +122,7 @@ bool CxxExpression::parse_list(CxxTokenizer& tokenizer, wxArrayString* params, i // ignore these break; case ',': - if(depth == 0) { + if (depth == 0) { ADD_IF_NOT_EMPTY(curparam); curparam.clear(); } else { @@ -131,7 +131,7 @@ bool CxxExpression::parse_list(CxxTokenizer& tokenizer, wxArrayString* params, i break; default: - if(tk.is_builtin_type() || tk.GetType() == T_IDENTIFIER) { + if (tk.is_builtin_type() || tk.GetType() == T_IDENTIFIER) { curparam << " " << tk.GetWXString(); } else { @@ -163,7 +163,7 @@ bool CxxExpression::parse_func_call(CxxTokenizer& tokenizer, wxArrayString* func bool CxxExpression::handle_cxx_casting(CxxTokenizer& tokenizer, wxString* cast_type) { CxxLexerToken t; - if(!tokenizer.NextToken(t)) { + if (!tokenizer.NextToken(t)) { return false; } @@ -172,7 +172,7 @@ bool CxxExpression::handle_cxx_casting(CxxTokenizer& tokenizer, wxString* cast_t constexpr int STATE_C_CAST = 2; int state = STATE_NORMAL; - switch(t.GetType()) { + switch (t.GetType()) { case T_CONST_CAST: case T_DYNAMIC_CAST: case T_REINTERPRET_CAST: @@ -184,34 +184,34 @@ bool CxxExpression::handle_cxx_casting(CxxTokenizer& tokenizer, wxString* cast_t } // did not find cast expression - if(state == STATE_NORMAL) { + if (state == STATE_NORMAL) { tokenizer.UngetToken(); return false; - } else if(state == STATE_C_CAST) { + } else if (state == STATE_C_CAST) { // append the remainder - while(tokenizer.NextToken(t)) { + while (tokenizer.NextToken(t)) { cast_type->Append(t.GetWXString() + " "); } return true; } // we are expecting '<' - if(!tokenizer.NextToken(t) || t.GetType() != '<') { + if (!tokenizer.NextToken(t) || t.GetType() != '<') { return false; } // read the cast type int depth = 1; bool cast_found = false; - while(!cast_found && tokenizer.NextToken(t)) { - switch(t.GetType()) { + while (!cast_found && tokenizer.NextToken(t)) { + switch (t.GetType()) { case '<': depth++; cast_type->Append('<'); break; case '>': depth--; - if(depth == 0) { + if (depth == 0) { cast_found = true; } else { cast_type->Append('>'); @@ -222,23 +222,23 @@ bool CxxExpression::handle_cxx_casting(CxxTokenizer& tokenizer, wxString* cast_t break; } } - if(!cast_found) { + if (!cast_found) { return false; } // next token should be `(` - if(!tokenizer.NextToken(t) || t.GetType() != '(') { + if (!tokenizer.NextToken(t) || t.GetType() != '(') { return false; } // read the castee wxArrayString dummy; - if(!parse_func_call(tokenizer, &dummy)) { + if (!parse_func_call(tokenizer, &dummy)) { return false; } // append the remainder to the cast_type - while(tokenizer.NextToken(t)) { + while (tokenizer.NextToken(t)) { cast_type->Append(t.GetWXString() + " "); } return true; @@ -246,12 +246,12 @@ bool CxxExpression::handle_cxx_casting(CxxTokenizer& tokenizer, wxString* cast_t void CxxExpression::parse_template_placeholders(const wxString& expr) { -#define CHECK_TYPE(Type) \ - if(tk.GetType() != Type) \ +#define CHECK_TYPE(Type) \ + if (tk.GetType() != Type) \ return #define ADD_PLACHOLDER() \ placeholder.Trim().Trim(false); \ - if(!placeholder.empty()) { \ + if (!placeholder.empty()) { \ arr.Add(placeholder); \ placeholder.clear(); \ } @@ -263,7 +263,7 @@ void CxxExpression::parse_template_placeholders(const wxString& expr) tokenizer.NextToken(tk); // optionally, we expect `template` (depending of the source of the `expr`) - if(tk.GetType() != T_TEMPLATE) { + if (tk.GetType() != T_TEMPLATE) { tokenizer.UngetToken(); } @@ -279,15 +279,15 @@ void CxxExpression::parse_template_placeholders(const wxString& expr) constexpr int STATE_DEFAULT_VALUE = 1; int state = STATE_NORMAL; - while(cont && tokenizer.NextToken(tk)) { - if(tk.is_pp_keyword() || tk.is_keyword()) { + while (cont && tokenizer.NextToken(tk)) { + if (tk.is_pp_keyword() || tk.is_keyword()) { continue; } - switch(state) { + switch (state) { case STATE_NORMAL: - switch(tk.GetType()) { + switch (tk.GetType()) { case ',': - if(depth == 1) { + if (depth == 1) { ADD_PLACHOLDER(); } else { placeholder << ","; @@ -299,7 +299,7 @@ void CxxExpression::parse_template_placeholders(const wxString& expr) break; case '>': depth--; - if(depth == 0) { + if (depth == 0) { // we are done ADD_PLACHOLDER(); cont = false; @@ -308,7 +308,7 @@ void CxxExpression::parse_template_placeholders(const wxString& expr) } break; case '=': - if(depth == 1) { + if (depth == 1) { // default value -> skip it state = STATE_DEFAULT_VALUE; @@ -319,7 +319,7 @@ void CxxExpression::parse_template_placeholders(const wxString& expr) default: placeholder << tk.GetWXString(); - if(tk.is_builtin_type() || tk.GetType() == T_IDENTIFIER) { + if (tk.is_builtin_type() || tk.GetType() == T_IDENTIFIER) { placeholder << " "; } break; @@ -327,20 +327,20 @@ void CxxExpression::parse_template_placeholders(const wxString& expr) break; case STATE_DEFAULT_VALUE: // read until we find "," or end of template definition - switch(tk.GetType()) { + switch (tk.GetType()) { case '<': depth++; break; case '>': depth--; - if(depth == 0) { + if (depth == 0) { state = STATE_NORMAL; // let the default state handle this case tokenizer.UngetToken(); } break; case ',': - if(depth == 0) { + if (depth == 0) { state = STATE_NORMAL; // let the default state handle this case tokenizer.UngetToken(); @@ -362,8 +362,8 @@ wxStringMap_t CxxExpression::get_template_placeholders_map() const { wxStringMap_t M; size_t count = std::min(m_template_placeholder_list.size(), m_template_init_list.size()); - for(size_t i = 0; i < count; i++) { - M.insert({ m_template_placeholder_list[i], m_template_init_list[i] }); + for (size_t i = 0; i < count; i++) { + M.insert({m_template_placeholder_list[i], m_template_init_list[i]}); } return M; } @@ -373,7 +373,7 @@ const wxString& CxxExpression::operand_string() const { return m_operand_string; void CxxExpression::set_operand(int op) { m_operand = op; - switch(m_operand) { + switch (m_operand) { case T_DOUBLE_COLONS: m_operand_string = "::"; break; @@ -397,8 +397,8 @@ std::vector CxxExpression::split_subclass_expression(const wxString& s tokenizer.Reset(subclass_pattern); // consume everything until the `:` - while(tokenizer.NextToken(token)) { - if(token.GetType() == ':') { + while (tokenizer.NextToken(token)) { + if (token.GetType() == ':') { break; } } @@ -409,13 +409,13 @@ std::vector CxxExpression::split_subclass_expression(const wxString& s int depth = 0; bool cont = true; - while(cont && tokenizer.NextToken(token)) { - if(token.is_keyword()) { + while (cont && tokenizer.NextToken(token)) { + if (token.is_keyword()) { continue; } - switch(token.GetType()) { + switch (token.GetType()) { case ',': - if(depth == 0) { + if (depth == 0) { result.push_back(curexpr); curexpr.clear(); } else { @@ -423,7 +423,7 @@ std::vector CxxExpression::split_subclass_expression(const wxString& s } break; case '{': - if(depth == 0) { + if (depth == 0) { cont = false; } else { depth++; @@ -449,7 +449,7 @@ std::vector CxxExpression::split_subclass_expression(const wxString& s } } - if(!curexpr.empty()) { + if (!curexpr.empty()) { result.push_back(curexpr); } return result; diff --git a/CodeLite/Cxx/CxxExpression.hpp b/CodeLite/Cxx/CxxExpression.hpp index f37d0bffb4..7e558d1839 100644 --- a/CodeLite/Cxx/CxxExpression.hpp +++ b/CodeLite/Cxx/CxxExpression.hpp @@ -101,7 +101,7 @@ class WXDLLIMPEXP_CL CxxExpression bool check_subscript_operator() const { return !m_subscript_params.empty(); } void pop_subscript_operator() { - if(!m_subscript_params.empty()) { + if (!m_subscript_params.empty()) { m_subscript_params.erase(m_subscript_params.begin()); } } diff --git a/CodeLite/Cxx/CxxLexerAPI.cpp b/CodeLite/Cxx/CxxLexerAPI.cpp index c27b07f340..328924db7a 100644 --- a/CodeLite/Cxx/CxxLexerAPI.cpp +++ b/CodeLite/Cxx/CxxLexerAPI.cpp @@ -37,8 +37,19 @@ std::unordered_set set_operators_tokens = { }; std::unordered_set set_builtin_types = { - T_BOOL, T_CHAR, T_CHAR16_T, T_CHAR32_T, T_DOUBLE, T_FLOAT, T_INT, - T_LONG, T_SHORT, T_SIGNED, T_UNSIGNED, T_VOID, T_WCHAR_T, + T_BOOL, + T_CHAR, + T_CHAR16_T, + T_CHAR32_T, + T_DOUBLE, + T_FLOAT, + T_INT, + T_LONG, + T_SHORT, + T_SIGNED, + T_UNSIGNED, + T_VOID, + T_WCHAR_T, }; std::unordered_set set_keywords_tokens = { T_ALIGNAS, T_ALIGNOF, T_AND, T_AND_EQ, diff --git a/CodeLite/Cxx/CxxLexerAPI.h b/CodeLite/Cxx/CxxLexerAPI.h index ffa6c7ee46..46f3a7b878 100644 --- a/CodeLite/Cxx/CxxLexerAPI.h +++ b/CodeLite/Cxx/CxxLexerAPI.h @@ -70,7 +70,7 @@ struct WXDLLIMPEXP_CL CxxLexerToken { private: void deleteText() { - if(m_owned && text) { + if (m_owned && text) { free(text); } m_owned = false; @@ -121,7 +121,7 @@ struct WXDLLIMPEXP_CL CxxLexerToken { CxxLexerToken(const CxxLexerToken& other) { - if(this == &other) + if (this == &other) return; *this = other; } @@ -132,7 +132,7 @@ struct WXDLLIMPEXP_CL CxxLexerToken { lineNumber = other.lineNumber; column = other.column; type = other.type; - if(other.text) { + if (other.text) { m_owned = true; #ifdef __WXMSW__ text = _strdup(other.text); @@ -176,7 +176,7 @@ struct WXDLLIMPEXP_CL CppLexerUserData { public: void Clear() { - if(m_currentPF) { + if (m_currentPF) { ::fclose(m_currentPF); m_currentPF = NULL; } diff --git a/CodeLite/Cxx/CxxPreProcessor.cpp b/CodeLite/Cxx/CxxPreProcessor.cpp index b2a76c355e..59a2715c1e 100644 --- a/CodeLite/Cxx/CxxPreProcessor.cpp +++ b/CodeLite/Cxx/CxxPreProcessor.cpp @@ -16,7 +16,7 @@ void CxxPreProcessor::Parse(const wxFileName& filename, size_t options) // Remove the option so recursive scanner won't get it m_options &= ~kLexerOpt_DontCollectMacrosDefinedInThisFile; - if(!scanner.IsNull()) { + if (!scanner.IsNull()) { scanner.Parse(this); } } catch (const CxxLexerException& e) { @@ -27,19 +27,20 @@ void CxxPreProcessor::Parse(const wxFileName& filename, size_t options) CxxPreProcessorToken::Map_t filteredMap; filteredMap.reserve(m_tokens.size()); - for(const auto& p : m_tokens) { - if(!p.second.deleteOnExit) { + for (const auto& p : m_tokens) { + if (!p.second.deleteOnExit) { filteredMap.insert(std::make_pair(p.first, p.second)); } } m_tokens.swap(filteredMap); } -bool CxxPreProcessor::ExpandInclude(const wxFileName& currentFile, const wxString& includeStatement, +bool CxxPreProcessor::ExpandInclude(const wxFileName& currentFile, + const wxString& includeStatement, wxFileName& outFile) { // skip STL debug folders - if(includeStatement.StartsWith("IsTrue(); - } else if(m_next && m_operand == kOR) { + } else if (m_next && m_operand == kOR) { return DoIsTrue() || m_next->IsTrue(); - } else if(m_next && m_operand == kGreaterThan) { + } else if (m_next && m_operand == kGreaterThan) { return DoGetLong() > m_next->DoGetLong(); - } else if(m_next && m_operand == kGreaterThanEqual) { + } else if (m_next && m_operand == kGreaterThanEqual) { return DoGetLong() >= m_next->DoGetLong(); - - } else if(m_next && m_operand == kLowerThan) { + + } else if (m_next && m_operand == kLowerThan) { return DoGetLong() < m_next->DoGetLong(); - } else if(m_next && m_operand == kLowerThanEqual) { + } else if (m_next && m_operand == kLowerThanEqual) { return DoGetLong() <= m_next->DoGetLong(); } else { @@ -32,7 +32,7 @@ bool CxxPreProcessorExpression::IsTrue() bool CxxPreProcessorExpression::DoIsTrue() { - if(m_isNot) { + if (m_isNot) { return !m_valueLong; } else { return m_valueLong; @@ -47,10 +47,7 @@ CxxPreProcessorExpression* CxxPreProcessorExpression::SetNext(CxxPreProcessorExp return m_next.get(); } -void CxxPreProcessorExpression::SetNot() -{ - m_isNot = !m_isNot; -} +void CxxPreProcessorExpression::SetNot() { m_isNot = !m_isNot; } void CxxPreProcessorExpression::SetValue(bool value) { @@ -58,10 +55,7 @@ void CxxPreProcessorExpression::SetValue(bool value) m_valueSet = true; } -double CxxPreProcessorExpression::DoGetLong() -{ - return m_valueLong; -} +double CxxPreProcessorExpression::DoGetLong() { return m_valueLong; } void CxxPreProcessorExpression::SetValue(double value) { diff --git a/CodeLite/Cxx/CxxPreProcessorExpression.h b/CodeLite/Cxx/CxxPreProcessorExpression.h index 7f7ef50d99..7c05455b1f 100644 --- a/CodeLite/Cxx/CxxPreProcessorExpression.h +++ b/CodeLite/Cxx/CxxPreProcessorExpression.h @@ -50,17 +50,18 @@ class WXDLLIMPEXP_CL CxxPreProcessorExpression bool m_defined = false; bool m_valueSet = false; double m_valueLong; + private: /** * @brief return the value as 'bool' */ bool DoIsTrue(); - + /** * @brief return the value as 'long' */ double DoGetLong(); - + public: CxxPreProcessorExpression(bool value); virtual ~CxxPreProcessorExpression() = default; @@ -70,24 +71,15 @@ class WXDLLIMPEXP_CL CxxPreProcessorExpression /** * @brief return true if this expression already assigned with a value */ - bool IsValueSet() const - { - return m_valueSet; - } + bool IsValueSet() const { return m_valueSet; } /** * @brief the current expression is from a 'defined' condition? */ - void SetDefined(bool defined) - { - this->m_defined = defined; - } + void SetDefined(bool defined) { this->m_defined = defined; } /** * @brief is the current expression is from a 'defined' condition? */ - bool IsDefined() const - { - return m_defined; - } + bool IsDefined() const { return m_defined; } /** * @brief when encountering an expression of type * #if !(expression) => SetNot() marks the exclamation mark diff --git a/CodeLite/Cxx/CxxPreProcessorScanner.cpp b/CodeLite/Cxx/CxxPreProcessorScanner.cpp index 038e787134..39da500482 100644 --- a/CodeLite/Cxx/CxxPreProcessorScanner.cpp +++ b/CodeLite/Cxx/CxxPreProcessorScanner.cpp @@ -5,7 +5,8 @@ #include "CxxScannerTokens.h" #include "file_logger.h" -CxxPreProcessorScanner::CxxPreProcessorScanner(const wxFileName& filename, size_t options, +CxxPreProcessorScanner::CxxPreProcessorScanner(const wxFileName& filename, + size_t options, std::unordered_set& visitedFiles) : m_scanner(NULL) , m_filename(filename) @@ -18,7 +19,7 @@ CxxPreProcessorScanner::CxxPreProcessorScanner(const wxFileName& filename, size_ CxxPreProcessorScanner::~CxxPreProcessorScanner() { - if(m_scanner) { + if (m_scanner) { ::LexerDestroy(&m_scanner); } } @@ -28,14 +29,14 @@ wxString CxxPreProcessorScanner::GetRestOfPPLine(bool collectNumberOnly) wxString rest; CxxLexerToken token; bool numberFound = false; - while(m_scanner && ::LexerNext(m_scanner, token) && token.GetType() != T_PP_STATE_EXIT) { - if(!numberFound && collectNumberOnly) { - if(token.GetType() == T_PP_DEC_NUMBER || token.GetType() == T_PP_OCTAL_NUMBER || - token.GetType() == T_PP_HEX_NUMBER || token.GetType() == T_PP_FLOAT_NUMBER) { + while (m_scanner && ::LexerNext(m_scanner, token) && token.GetType() != T_PP_STATE_EXIT) { + if (!numberFound && collectNumberOnly) { + if (token.GetType() == T_PP_DEC_NUMBER || token.GetType() == T_PP_OCTAL_NUMBER || + token.GetType() == T_PP_HEX_NUMBER || token.GetType() == T_PP_FLOAT_NUMBER) { rest = token.GetWXString(); numberFound = true; } - } else if(!collectNumberOnly) { + } else if (!collectNumberOnly) { rest << " " << token.GetWXString(); } } @@ -47,11 +48,11 @@ bool CxxPreProcessorScanner::ConsumeBlock() { CxxLexerToken token; int depth = 1; - while(m_scanner && ::LexerNext(m_scanner, token)) { - switch(token.GetType()) { + while (m_scanner && ::LexerNext(m_scanner, token)) { + switch (token.GetType()) { case T_PP_ENDIF: depth--; - if(depth == 0) { + if (depth == 0) { return true; } break; @@ -73,18 +74,18 @@ void CxxPreProcessorScanner::Parse(CxxPreProcessor* pp) CxxLexerToken token; bool searchingForBranch = false; CxxPreProcessorToken::Map_t& ppTable = pp->GetTokens(); - while(m_scanner && ::LexerNext(m_scanner, token)) { + while (m_scanner && ::LexerNext(m_scanner, token)) { // Pre Processor state - switch(token.GetType()) { + switch (token.GetType()) { case T_PP_INCLUDE_FILENAME: { // we found an include statement, recurse into it wxFileName include; - if(pp->ExpandInclude(m_filename, token.GetWXString(), include) && - m_visitedFiles.count(include.GetFullPath()) == 0) { + if (pp->ExpandInclude(m_filename, token.GetWXString(), include) && + m_visitedFiles.count(include.GetFullPath()) == 0) { m_visitedFiles.insert(include.GetFullPath()); CxxPreProcessorScanner scanner(include, pp->GetOptions(), m_visitedFiles); try { - if(!scanner.IsNull()) { + if (!scanner.IsNull()) { scanner.Parse(pp); } } catch (const CxxLexerException& e) { @@ -100,14 +101,14 @@ void CxxPreProcessorScanner::Parse(CxxPreProcessor* pp) searchingForBranch = true; // read the identifier ReadUntilMatch(T_PP_IDENTIFIER, token); - if(IsTokenExists(ppTable, token)) { + if (IsTokenExists(ppTable, token)) { searchingForBranch = false; // condition is true Parse(pp); } else { // skip until we find the next: // else, elif, endif (but do not consume these tokens) - if(!ConsumeCurrentBranch()) + if (!ConsumeCurrentBranch()) return; } break; @@ -116,14 +117,14 @@ void CxxPreProcessorScanner::Parse(CxxPreProcessor* pp) searchingForBranch = true; // read the identifier ReadUntilMatch(T_PP_IDENTIFIER, token); - if(!IsTokenExists(ppTable, token)) { + if (!IsTokenExists(ppTable, token)) { searchingForBranch = false; // condition is true Parse(pp); } else { // skip until we find the next: // else, elif, endif (but do not consume these tokens) - if(!ConsumeCurrentBranch()) + if (!ConsumeCurrentBranch()) return; } break; @@ -131,12 +132,12 @@ void CxxPreProcessorScanner::Parse(CxxPreProcessor* pp) case T_PP_IF: searchingForBranch = true; case T_PP_ELIF: { - if(searchingForBranch) { + if (searchingForBranch) { // We expect a condition - if(!CheckIf(ppTable)) { + if (!CheckIf(ppTable)) { // skip until we find the next: // else, elif, endif (but do not consume these tokens) - if(!ConsumeCurrentBranch()) + if (!ConsumeCurrentBranch()) return; } else { @@ -151,7 +152,7 @@ void CxxPreProcessorScanner::Parse(CxxPreProcessor* pp) break; } case T_PP_ELSE: { - if(searchingForBranch) { + if (searchingForBranch) { // if we reached an else, it means that we could not match // a if/elif/ifdef condition until now - enter it Parse(pp); @@ -168,7 +169,7 @@ void CxxPreProcessorScanner::Parse(CxxPreProcessor* pp) return; } case T_PP_DEFINE: { - if(!::LexerNext(m_scanner, token) || token.GetType() != T_PP_IDENTIFIER) { + if (!::LexerNext(m_scanner, token) || token.GetType() != T_PP_IDENTIFIER) { // Recover GetRestOfPPLine(); break; @@ -191,7 +192,7 @@ void CxxPreProcessorScanner::Parse(CxxPreProcessor* pp) } #define SET_CUR_EXPR_VALUE_RET_FALSE(v) \ - if(cur->IsValueSet()) \ + if (cur->IsValueSet()) \ return false; \ else \ cur->SetValue((double)v); @@ -206,12 +207,12 @@ bool CxxPreProcessorScanner::CheckIf(const CxxPreProcessorToken::Map_t& table) CxxLexerToken token; auto head = std::make_unique(false); CxxPreProcessorExpression* cur = head.get(); - while(m_scanner && ::LexerNext(m_scanner, token)) { - if(token.GetType() == T_PP_STATE_EXIT) { + while (m_scanner && ::LexerNext(m_scanner, token)) { + if (token.GetType() == T_PP_STATE_EXIT) { bool res = head->IsTrue(); return res; } - switch(token.GetType()) { + switch (token.GetType()) { case '(': case ')': // ignore parenthesis @@ -240,21 +241,21 @@ bool CxxPreProcessorScanner::CheckIf(const CxxPreProcessorToken::Map_t& table) case T_PP_IDENTIFIER: { wxString identifier = token.GetWXString(); CxxPreProcessorToken::Map_t::const_iterator iter = table.find(identifier); - if(iter == table.end()) { + if (iter == table.end()) { SET_CUR_EXPR_VALUE_RET_FALSE(0); } else { - if(cur->IsDefined()) { + if (cur->IsDefined()) { // no need to test further, it exists (the current expression // if a 'defined' statement) SET_CUR_EXPR_VALUE_RET_FALSE(1); } else { wxString macroValue = iter->second.value; - if(macroValue.IsEmpty()) { + if (macroValue.IsEmpty()) { SET_CUR_EXPR_VALUE_RET_FALSE(0); } else { long v(0); bool res = macroValue.ToCLong(&v); - if(!res) { + if (!res) { SET_CUR_EXPR_VALUE_RET_FALSE(0); } else { @@ -280,13 +281,15 @@ bool CxxPreProcessorScanner::CheckIf(const CxxPreProcessorToken::Map_t& table) cur = cur->SetNext(CxxPreProcessorExpression::kGreaterThan, std::make_unique(0)); break; case T_PP_GTEQ: - cur = cur->SetNext(CxxPreProcessorExpression::kGreaterThanEqual, std::make_unique(0)); + cur = cur->SetNext( + CxxPreProcessorExpression::kGreaterThanEqual, std::make_unique(0)); break; case T_PP_LT: cur = cur->SetNext(CxxPreProcessorExpression::kLowerThan, std::make_unique(0)); break; case T_PP_LTEQ: - cur = cur->SetNext(CxxPreProcessorExpression::kLowerThanEqual, std::make_unique(0)); + cur = cur->SetNext( + CxxPreProcessorExpression::kLowerThanEqual, std::make_unique(0)); break; default: break; @@ -306,22 +309,22 @@ bool CxxPreProcessorScanner::ConsumeCurrentBranch() // T_PP_ELIF // T_PP_ELSE // T_PP_ENDIF - while(m_scanner && ::LexerNext(m_scanner, token)) { - switch(token.GetType()) { + while (m_scanner && ::LexerNext(m_scanner, token)) { + switch (token.GetType()) { case T_PP_IF: case T_PP_IFDEF: case T_PP_IFNDEF: depth++; break; case T_PP_ENDIF: - if(depth == 1) { + if (depth == 1) { return true; } depth--; break; case T_PP_ELIF: case T_PP_ELSE: - if(depth == 1) { + if (depth == 1) { ::LexerUnget(m_scanner); return true; } @@ -335,10 +338,10 @@ bool CxxPreProcessorScanner::ConsumeCurrentBranch() void CxxPreProcessorScanner::ReadUntilMatch(int type, CxxLexerToken& token) { - while(m_scanner && ::LexerNext(m_scanner, token)) { - if(token.GetType() == type) { + while (m_scanner && ::LexerNext(m_scanner, token)) { + if (token.GetType() == type) { return; - } else if(token.GetType() == T_PP_STATE_EXIT) { + } else if (token.GetType() == T_PP_STATE_EXIT) { throw CxxLexerException(wxString() << "Could not find a match for type: " << type); } } diff --git a/CodeLite/Cxx/CxxTemplateFunction.cpp b/CodeLite/Cxx/CxxTemplateFunction.cpp index 28d35863fd..5a87668a63 100644 --- a/CodeLite/Cxx/CxxTemplateFunction.cpp +++ b/CodeLite/Cxx/CxxTemplateFunction.cpp @@ -1,5 +1,7 @@ #include "CxxTemplateFunction.h" + #include "CxxScannerTokens.h" + #include CxxTemplateFunction::CxxTemplateFunction(TagEntryPtr tag) @@ -10,10 +12,10 @@ CxxTemplateFunction::CxxTemplateFunction(TagEntryPtr tag) CxxTemplateFunction::~CxxTemplateFunction() { - if(m_scanner) { + if (m_scanner) { ::LexerDestroy(&m_scanner); } - if(m_sigScanner) { + if (m_sigScanner) { ::LexerDestroy(&m_sigScanner); } } @@ -23,46 +25,48 @@ void CxxTemplateFunction::ParseDefinitionList() m_list.Clear(); int depth(0); CxxLexerToken token; - + // scan until we find 'template' keyword - while(::LexerNext(m_scanner, token)) { - if(token.GetType() == T_TEMPLATE) { + while (::LexerNext(m_scanner, token)) { + if (token.GetType() == T_TEMPLATE) { break; } } - - if(!token.GetType()) return; // EOF - + + if (!token.GetType()) + return; // EOF + // Loop until we found the open brace '<' - while(::LexerNext(m_scanner, token)) { - if(token.GetType() == '<') { + while (::LexerNext(m_scanner, token)) { + if (token.GetType() == '<') { ++depth; break; } } - + // could not find it - if(!depth) return; - + if (!depth) + return; + bool cont = true; wxString currentToken; - while(cont && ::LexerNext(m_scanner, token)) { - switch(token.GetType()) { + while (cont && ::LexerNext(m_scanner, token)) { + switch (token.GetType()) { case T_TYPENAME: case T_CLASS: // ignore these keywords break; case ',': - if(!currentToken.IsEmpty()) { + if (!currentToken.IsEmpty()) { m_list.Add(currentToken.Trim().Trim(false)); currentToken.Clear(); } break; case '>': --depth; - if(depth == 0) { + if (depth == 0) { // done - if(!currentToken.IsEmpty()) { + if (!currentToken.IsEmpty()) { m_list.Add(currentToken.Trim().Trim(false)); currentToken.Clear(); } @@ -85,21 +89,21 @@ void CxxTemplateFunction::ParseDefinitionList() bool CxxTemplateFunction::CanTemplateArgsDeduced() { ParseDefinitionList(); // Initializes the m_list array - + std::set words; CxxLexerToken token; - + // Collect all the identifiers and keep them inside a set - while(::LexerNext(m_sigScanner, token)) { - if(token.GetType() == T_IDENTIFIER) { + while (::LexerNext(m_sigScanner, token)) { + if (token.GetType() == T_IDENTIFIER) { words.insert(token.GetWXString()); } } - - // Loop over the function arguments list and check that all of them + + // Loop over the function arguments list and check that all of them // exists in the set we created from the function signature - for(size_t i=0; iIsInPreProcessorSection()) { + if (scannerData && scannerData->IsInPreProcessorSection()) { continue; } - switch(state) { + switch (state) { case SCP_STATE_NORMAL: - switch(token.GetType()) { + switch (token.GetType()) { case T_PP_STATE_EXIT: break; case '{': @@ -89,7 +89,7 @@ wxString CxxTokenizer::GetVisibleScope(const wxString& inputString) currentScope.clear(); break; case '}': - if(scopes.empty()) + if (scopes.empty()) return ""; // Invalid braces count currentScope = scopes.top(); scopes.pop(); @@ -117,7 +117,7 @@ wxString CxxTokenizer::GetVisibleScope(const wxString& inputString) // Handle lambda // If we are entering lambda function definition, collect the locals // this is exactly what we in 'catch' hence the state change to SCP_STATE_IN_CATCH - if(GetLastToken().GetType() == ']') { + if (GetLastToken().GetType() == ']') { state = SCP_STATE_IN_CATCH; } break; @@ -126,7 +126,7 @@ wxString CxxTokenizer::GetVisibleScope(const wxString& inputString) currentScope << ")"; break; default: - if(parenthesisDepth == 0) { + if (parenthesisDepth == 0) { currentScope << " " << token.GetWXString(); } break; @@ -134,7 +134,7 @@ wxString CxxTokenizer::GetVisibleScope(const wxString& inputString) break; case SCP_STATE_IN_WHILE: case SCP_STATE_IN_IF: - switch(token.GetType()) { + switch (token.GetType()) { case '(': parenthesisDepth++; currentScope << "("; @@ -142,14 +142,14 @@ wxString CxxTokenizer::GetVisibleScope(const wxString& inputString) case ')': parenthesisDepth--; currentScope << ")"; - if(parenthesisDepth == 0) { + if (parenthesisDepth == 0) { state = SCP_STATE_NORMAL; } break; } break; case SCP_STATE_IN_FOR_NO_SEMICOLON: - switch(token.GetType()) { + switch (token.GetType()) { case '(': parenthesisDepth++; currentScope << "("; @@ -157,7 +157,7 @@ wxString CxxTokenizer::GetVisibleScope(const wxString& inputString) case ')': parenthesisDepth--; currentScope << ")"; - if(parenthesisDepth == 0) { + if (parenthesisDepth == 0) { state = SCP_STATE_NORMAL; } break; @@ -171,7 +171,7 @@ wxString CxxTokenizer::GetVisibleScope(const wxString& inputString) } break; case SCP_STATE_IN_FOR: - switch(token.GetType()) { + switch (token.GetType()) { case '(': parenthesisDepth++; currentScope << "("; @@ -179,7 +179,7 @@ wxString CxxTokenizer::GetVisibleScope(const wxString& inputString) case ')': parenthesisDepth--; currentScope << ")"; - if(parenthesisDepth == 0) { + if (parenthesisDepth == 0) { state = SCP_STATE_NORMAL; } break; @@ -188,7 +188,7 @@ wxString CxxTokenizer::GetVisibleScope(const wxString& inputString) } break; case SCP_STATE_IN_CATCH: - switch(token.GetType()) { + switch (token.GetType()) { case '(': currentScope << "("; parenthesisDepth++; @@ -196,7 +196,7 @@ wxString CxxTokenizer::GetVisibleScope(const wxString& inputString) case ')': parenthesisDepth--; currentScope << ")"; - if(parenthesisDepth == 0) { + if (parenthesisDepth == 0) { state = SCP_STATE_NORMAL; } break; @@ -211,7 +211,7 @@ wxString CxxTokenizer::GetVisibleScope(const wxString& inputString) } wxString s; - while(!scopes.empty()) { + while (!scopes.empty()) { s.Prepend(scopes.top()); scopes.pop(); } @@ -221,40 +221,40 @@ wxString CxxTokenizer::GetVisibleScope(const wxString& inputString) CppLexerUserData* CxxTokenizer::GetUserData() const { - if(!m_scanner) + if (!m_scanner) return NULL; return ::LexerGetUserData(m_scanner); } -void CxxTokenizer::read_until_find(CxxLexerToken& token, int type_1, int type_2, int* what_was_found, - wxString* consumed) +void CxxTokenizer::read_until_find( + CxxLexerToken& token, int type_1, int type_2, int* what_was_found, wxString* consumed) { int depth = 0; consumed->clear(); *what_was_found = 0; consumed->reserve(256); // 256 bytes should be enough for most cases - while(NextToken(token)) { - if(depth == 0 && token.GetType() == type_1) { + while (NextToken(token)) { + if (depth == 0 && token.GetType() == type_1) { *what_was_found = type_1; consumed->Trim().Trim(false); return; - } else if(depth == 0 && token.GetType() == type_2) { + } else if (depth == 0 && token.GetType() == type_2) { *what_was_found = type_2; consumed->Trim().Trim(false); return; } - if(token.is_keyword() || token.is_builtin_type()) { + if (token.is_keyword() || token.is_builtin_type()) { consumed->Append(token.GetWXString() + " "); continue; - } else if(token.is_pp_keyword()) { + } else if (token.is_pp_keyword()) { continue; } // append it consumed->Append(token.GetWXString()); - switch(token.GetType()) { + switch (token.GetType()) { case '<': case '{': case '[': diff --git a/CodeLite/Cxx/CxxVariable.cpp b/CodeLite/Cxx/CxxVariable.cpp index 8c1d9d33b2..3d584a20b2 100644 --- a/CodeLite/Cxx/CxxVariable.cpp +++ b/CodeLite/Cxx/CxxVariable.cpp @@ -17,7 +17,7 @@ wxString CxxVariable::GetTypeAsString(const wxStringTable_t& table) const wxString CxxVariable::GetTypeAsCxxString(const wxStringTable_t& table) const { - if(IsUsing()) { + if (IsUsing()) { // A name of the real data type is parsed as assignment expression return m_defaultValue; } @@ -29,21 +29,23 @@ wxString CxxVariable::ToString(size_t flags) const wxString str; str << GetTypeAsString({}); - if(!GetPointerOrReference().IsEmpty()) { + if (!GetPointerOrReference().IsEmpty()) { str << GetPointerOrReference(); } - if(flags & kToString_Name) { + if (flags & kToString_Name) { str << " " << GetName(); } - if((flags & kToString_DefaultValue) && !GetDefaultValue().IsEmpty()) { + if ((flags & kToString_DefaultValue) && !GetDefaultValue().IsEmpty()) { str << " = " << GetDefaultValue(); } return str; } -wxString CxxVariable::PackType(const CxxVariable::LexerToken::Vec_t& type, eCxxStandard standard, bool omitClassKeyword, +wxString CxxVariable::PackType(const CxxVariable::LexerToken::Vec_t& type, + eCxxStandard standard, + bool omitClassKeyword, const wxStringTable_t& table) { CxxTokenizer tokenizer; @@ -51,20 +53,20 @@ wxString CxxVariable::PackType(const CxxVariable::LexerToken::Vec_t& type, eCxxS // create a string with spaces wxString packed; - for(const CxxVariable::LexerToken& tok : type) { + for (const CxxVariable::LexerToken& tok : type) { packed << tok.text << " "; } tokenizer.Reset(packed); wxString s; - while(tokenizer.NextToken(token)) { - if(s.empty() && (token.GetType() == T_CLASS || token.GetType() == T_STRUCT || token.GetType() == T_ENUM) && - omitClassKeyword) + while (tokenizer.NextToken(token)) { + if (s.empty() && (token.GetType() == T_CLASS || token.GetType() == T_STRUCT || token.GetType() == T_ENUM) && + omitClassKeyword) continue; - if(token.is_keyword() || token.is_builtin_type()) { + if (token.is_keyword() || token.is_builtin_type()) { s << token.GetWXString() << " "; - } else if(token.is_pp_keyword()) { + } else if (token.is_pp_keyword()) { continue; } else { s << token.GetWXString(); diff --git a/CodeLite/Cxx/CxxVariable.h b/CodeLite/Cxx/CxxVariable.h index a1d29395b6..8b91203190 100644 --- a/CodeLite/Cxx/CxxVariable.h +++ b/CodeLite/Cxx/CxxVariable.h @@ -83,8 +83,10 @@ class WXDLLIMPEXP_CL CxxVariable // @see ToString() for description about 'table' wxString GetTypeAsCxxString(const wxStringTable_t& table = wxStringTable_t()) const; - static wxString PackType(const CxxVariable::LexerToken::Vec_t& type, eCxxStandard standard, - bool omitClassKeyword = false, const wxStringTable_t& table = wxStringTable_t()); + static wxString PackType(const CxxVariable::LexerToken::Vec_t& type, + eCxxStandard standard, + bool omitClassKeyword = false, + const wxStringTable_t& table = wxStringTable_t()); /** * @brief return true if this variable was constructed from a statement like: diff --git a/CodeLite/Cxx/CxxVariableScanner.h b/CodeLite/Cxx/CxxVariableScanner.h index 2e0c0e2413..bde9b7e0a1 100644 --- a/CodeLite/Cxx/CxxVariableScanner.h +++ b/CodeLite/Cxx/CxxVariableScanner.h @@ -73,7 +73,9 @@ class WXDLLIMPEXP_CL CxxVariableScanner bool skip_parenthesis_block(Scanner_t scanner); public: - CxxVariableScanner(const wxString& buffer, eCxxStandard standard, const wxStringTable_t& macros, + CxxVariableScanner(const wxString& buffer, + eCxxStandard standard, + const wxStringTable_t& macros, bool isFuncSignature); virtual ~CxxVariableScanner() = default; diff --git a/CodeLite/Cxx/cpp_comment_creator.cpp b/CodeLite/Cxx/cpp_comment_creator.cpp index 177eefbc23..800b182359 100644 --- a/CodeLite/Cxx/cpp_comment_creator.cpp +++ b/CodeLite/Cxx/cpp_comment_creator.cpp @@ -22,10 +22,11 @@ // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// +#include "precompiled_header.h" + #include "cpp_comment_creator.h" #include "language.h" -#include "precompiled_header.h" #define trimMe(str) \ { \ @@ -41,9 +42,9 @@ CppCommentCreator::CppCommentCreator(TagEntryPtr tag, wxChar keyPrefix) wxString CppCommentCreator::CreateComment() { - if(m_tag->GetKind() == wxT("class") || m_tag->GetKind() == wxT("struct")) { + if (m_tag->GetKind() == wxT("class") || m_tag->GetKind() == wxT("struct")) { return wxT("$(ClassPattern)\n"); - } else if(m_tag->IsMethod()) { + } else if (m_tag->IsMethod()) { return FunctionComment(); } else { return wxEmptyString; @@ -70,8 +71,8 @@ wxString CppCommentCreator::FunctionComment() trimMe(type); trimMe(name); - if(type != wxT("void") // void has no return value - && name != type) { // and not a constructor + if (type != wxT("void") // void has no return value + && name != type) { // and not a constructor comment << wxT(" * ") << m_keyPrefix << wxT("return \n"); } } diff --git a/CodeLite/Cxx/cpp_comment_creator.h b/CodeLite/Cxx/cpp_comment_creator.h index 76b3bc236d..12b25c05b0 100644 --- a/CodeLite/Cxx/cpp_comment_creator.h +++ b/CodeLite/Cxx/cpp_comment_creator.h @@ -1,25 +1,25 @@ ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // -// copyright : (C) 2008 by Eran Ifrah -// file name : cpp_comment_creator.h -// +// copyright : (C) 2008 by Eran Ifrah +// file name : cpp_comment_creator.h +// // ------------------------------------------------------------------------- -// A -// _____ _ _ _ _ -// / __ \ | | | | (_) | -// | / \/ ___ __| | ___| | _| |_ ___ -// | | / _ \ / _ |/ _ \ | | | __/ _ ) -// | \__/\ (_) | (_| | __/ |___| | || __/ -// \____/\___/ \__,_|\___\_____/_|\__\___| -// -// F i l e -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation; either version 2 of the License, or -// (at your option) any later version. -// +// A +// _____ _ _ _ _ +// / __ \ | | | | (_) | +// | / \/ ___ __| | ___| | _| |_ ___ +// | | / _ \ / _ |/ _ \ | | | __/ _ ) +// | \__/\ (_) | (_| | __/ |___| | || __/ +// \____/\___/ \__,_|\___\_____/_|\__\___| +// +// F i l e +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; either version 2 of the License, or +// (at your option) any later version. +// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// #ifndef CPP_COMMENT_CREATOR_H diff --git a/CodeLite/Cxx/cpp_scanner.cpp b/CodeLite/Cxx/cpp_scanner.cpp index a6115a90dc..1aa4acde1a 100644 --- a/CodeLite/Cxx/cpp_scanner.cpp +++ b/CodeLite/Cxx/cpp_scanner.cpp @@ -23,60 +23,56 @@ ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// #include "precompiled_header.h" + #include "cpp_scanner.h" CppScanner::CppScanner() -: m_curr(0) + : m_curr(0) { - m_data = NULL; - m_pcurr = NULL; - m_keepComments = 0; - m_returnWhite = 0; - m_comment = wxEmptyString; + m_data = NULL; + m_pcurr = NULL; + m_keepComments = 0; + m_returnWhite = 0; + m_comment = wxEmptyString; } -CppScanner::~CppScanner() -{ - free(m_data); -} +CppScanner::~CppScanner() { free(m_data); } -int CppScanner::LexerInput(char *buf, int max_size) +int CppScanner::LexerInput(char* buf, int max_size) { - if( !m_data ) - return 0; + if (!m_data) + return 0; - memset(buf, 0, max_size); - char *pendData = m_data + strlen(m_data); - int n = (max_size < (pendData - m_pcurr)) ? max_size : (pendData - m_pcurr); - if(n > 0) - { - memcpy(buf, m_pcurr, n); - m_pcurr += n; - } - return n; + memset(buf, 0, max_size); + char* pendData = m_data + strlen(m_data); + int n = (max_size < (pendData - m_pcurr)) ? max_size : (pendData - m_pcurr); + if (n > 0) { + memcpy(buf, m_pcurr, n); + m_pcurr += n; + } + return n; } void CppScanner::SetText(const char* data) { - // release previous buffer - Reset(); + // release previous buffer + Reset(); - m_data = strdup(data); - m_pcurr = m_data; + m_data = strdup(data); + m_pcurr = m_data; } void CppScanner::Reset() { - if(m_data) - { - free(m_data); - m_data = NULL; - m_pcurr = NULL; - m_curr = 0; - } + if (m_data) { + free(m_data); + m_data = NULL; + m_pcurr = NULL; + m_curr = 0; + } - // Notify lex to restart its buffer - yy_flush_buffer(yy_current_buffer); - m_comment = wxEmptyString; - yylineno = 1; + // Notify lex to restart its buffer + yy_flush_buffer(yy_current_buffer); + m_comment = wxEmptyString; + yylineno = 1; } diff --git a/CodeLite/Cxx/cpp_scanner.h b/CodeLite/Cxx/cpp_scanner.h index ebdaee42d4..86c0c78f18 100644 --- a/CodeLite/Cxx/cpp_scanner.h +++ b/CodeLite/Cxx/cpp_scanner.h @@ -22,7 +22,7 @@ // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// - #ifndef CODELITE_CPPSCANNER_H +#ifndef CODELITE_CPPSCANNER_H #define CODELITE_CPPSCANNER_H #include "FlexLexer.h" @@ -33,31 +33,30 @@ class WXDLLIMPEXP_CL CppScanner : public flex::yyFlexLexer { public: - CppScanner(); - ~CppScanner(); - - /// Override the LexerInput function - int LexerInput(char *buf, int max_size); - void SetText(const char* data); - void Reset(); - - - /// Note about comment and line number: - /// If the last text consumed is a comment, the line number - /// returned is the line number of the last line of the comment - /// incase the comment spans over number of lines - /// (i.e. /* ... */ comment style) - - int LineNo() const { return yylineno; } - void ClearComment() { m_comment = wxEmptyString; } - const wxChar* GetComment() const { return m_comment.GetData(); } - void KeepComment(int keep) { m_keepComments = keep; } - void ReturnWhite(int rw) { m_returnWhite = rw; } + CppScanner(); + ~CppScanner(); + + /// Override the LexerInput function + int LexerInput(char* buf, int max_size); + void SetText(const char* data); + void Reset(); + + /// Note about comment and line number: + /// If the last text consumed is a comment, the line number + /// returned is the line number of the last line of the comment + /// incase the comment spans over number of lines + /// (i.e. /* ... */ comment style) + + int LineNo() const { return yylineno; } + void ClearComment() { m_comment = wxEmptyString; } + const wxChar* GetComment() const { return m_comment.GetData(); } + void KeepComment(int keep) { m_keepComments = keep; } + void ReturnWhite(int rw) { m_returnWhite = rw; } private: - char *m_data; - char *m_pcurr; - int m_curr; + char* m_data; + char* m_pcurr; + int m_curr; }; using CppScannerPtr = std::unique_ptr; diff --git a/CodeLite/Cxx/cpptoken.cpp b/CodeLite/Cxx/cpptoken.cpp index feafd67a8c..8e7a8558cf 100644 --- a/CodeLite/Cxx/cpptoken.cpp +++ b/CodeLite/Cxx/cpptoken.cpp @@ -26,10 +26,7 @@ CppToken::CppToken() { reset(); } -bool CppToken::operator<(const CppToken& rhs) const -{ - return this->getName() < rhs.getName(); -} +bool CppToken::operator<(const CppToken& rhs) const { return this->getName() < rhs.getName(); } void CppToken::reset() { @@ -61,7 +58,7 @@ void CppTokensMap::addToken(const CppToken& token) // try to locate an entry with this name std::unordered_map*>::iterator iter = m_tokens.find(token.getName()); std::vector* tokensList(NULL); - if(iter != m_tokens.end()) { + if (iter != m_tokens.end()) { tokensList = iter->second; } else { // create new list and add it to the map diff --git a/CodeLite/Cxx/cppwordscanner.cpp b/CodeLite/Cxx/cppwordscanner.cpp index 88baa466f3..d4a1853184 100644 --- a/CodeLite/Cxx/cppwordscanner.cpp +++ b/CodeLite/Cxx/cppwordscanner.cpp @@ -40,10 +40,10 @@ CppWordScanner::CppWordScanner(const wxString& fileName) wxCSConv fontEncConv(wxFONTENCODING_ISO8859_1); wxFFile thefile(m_filename, wxT("rb")); - if(thefile.IsOpened()) { + if (thefile.IsOpened()) { m_text.Clear(); thefile.ReadAll(&m_text, fontEncConv); - if(m_text.IsEmpty()) { + if (m_text.IsEmpty()) { // Try another converter fontEncConv = wxFONTENCODING_UTF8; thefile.ReadAll(&m_text, fontEncConv); @@ -74,73 +74,74 @@ void CppWordScanner::doFind(const wxString& filter, CppTokensMap& l, int from, i size_t t = (to == wxNOT_FOUND) ? m_text.size() : to; // sanity - if(f > m_text.size() || t > m_text.size()) return; + if (f > m_text.size() || t > m_text.size()) + return; - for(size_t i = f; i < t; i++) { + for (size_t i = f; i < t; i++) { char ch = accessor.safeAt(i); // Keep track of line numbers - if(accessor.match("\n", i) && (state == STATE_NORMAL || state == STATE_PRE_PROCESSING || - state == STATE_CPP_COMMENT || state == STATE_C_COMMENT)) { + if (accessor.match("\n", i) && (state == STATE_NORMAL || state == STATE_PRE_PROCESSING || + state == STATE_CPP_COMMENT || state == STATE_C_COMMENT)) { lineNo++; } - switch(state) { + switch (state) { case STATE_NORMAL: - if(accessor.match("#", i)) { + if (accessor.match("#", i)) { - if(i == 0 || // start of document - accessor.match("\n", i - 1)) { // we are at start of line + if (i == 0 || // start of document + accessor.match("\n", i - 1)) { // we are at start of line state = STATE_PRE_PROCESSING; } - } else if(accessor.match("//", i)) { + } else if (accessor.match("//", i)) { // C++ comment, advance i state = STATE_CPP_COMMENT; i++; - } else if(accessor.match("/*", i)) { + } else if (accessor.match("/*", i)) { // C comment state = STATE_C_COMMENT; i++; - } else if(accessor.match("'", i)) { + } else if (accessor.match("'", i)) { // single quoted string state = STATE_SINGLE_STRING; - } else if(accessor.match("\"", i)) { + } else if (accessor.match("\"", i)) { // double quoted string state = STATE_DQ_STRING; - } else if(accessor.isWordChar(ch)) { + } else if (accessor.isWordChar(ch)) { // is valid C++ word? token.append(ch); - if(token.getOffset() == wxString::npos) { + if (token.getOffset() == wxString::npos) { token.setOffset(i + m_offset); } } else { - if(token.getName().empty() == false) { + if (token.getName().empty() == false) { - if((int)token.getName().at(0) >= 48 && (int)token.getName().at(0) <= 57) { + if ((int)token.getName().at(0) >= 48 && (int)token.getName().at(0) <= 57) { token.reset(); } else { // don't add C++ key words wxString tmpName(token.getName()); - if(m_keywords.count(tmpName) == 0) { + if (m_keywords.count(tmpName) == 0) { token.setFilename(m_filename); token.setLineNumber(lineNo); // Ok, we are not a number! // filter out non matching words - if(filter.empty() || filter == token.getName()) { + if (filter.empty() || filter == token.getName()) { l.addToken(token); } } @@ -153,46 +154,46 @@ void CppWordScanner::doFind(const wxString& filter, CppTokensMap& l, int from, i case STATE_PRE_PROCESSING: // if the char before the \n is \ (backslash) or \r\ (CR followed by backslash) remain in pre-processing // state - if(accessor.match("\n", i) && (!accessor.match("\\", i - 1) && !accessor.match("\\\r", i - 2))) { + if (accessor.match("\n", i) && (!accessor.match("\\", i - 1) && !accessor.match("\\\r", i - 2))) { // no wrap state = STATE_NORMAL; - } else if(accessor.match("//", i)) { + } else if (accessor.match("//", i)) { // C++ comment, advance i state = STATE_CPP_COMMENT; i++; } break; case STATE_C_COMMENT: - if(accessor.match("*/", i)) { + if (accessor.match("*/", i)) { state = STATE_NORMAL; i++; } break; case STATE_CPP_COMMENT: - if(accessor.match("\n", i)) { + if (accessor.match("\n", i)) { state = STATE_NORMAL; } break; case STATE_DQ_STRING: - if(accessor.match("\\\"", i)) { + if (accessor.match("\\\"", i)) { // escaped string i++; - } else if(accessor.match("\\", i)) { + } else if (accessor.match("\\", i)) { i++; - } else if(accessor.match("\"", i)) { + } else if (accessor.match("\"", i)) { state = STATE_NORMAL; } break; case STATE_SINGLE_STRING: - if(accessor.match("\\'", i)) { + if (accessor.match("\\'", i)) { // escaped single string i++; - } else if(accessor.match("\\", i)) { + } else if (accessor.match("\\", i)) { i++; - } else if(accessor.match("'", i)) { + } else if (accessor.match("'", i)) { state = STATE_NORMAL; } break; diff --git a/CodeLite/Cxx/include_finder.h b/CodeLite/Cxx/include_finder.h index 103e545c7a..fbf1d62bda 100644 --- a/CodeLite/Cxx/include_finder.h +++ b/CodeLite/Cxx/include_finder.h @@ -26,18 +26,20 @@ #ifndef INCLUDE_FINDER_H #define INCLUDE_FINDER_H -#include -#include #include "codelite_exports.h" -class WXDLLIMPEXP_CL IncludeStatement { +#include +#include + +class WXDLLIMPEXP_CL IncludeStatement +{ public: - std::string file; - int line; - std::string includedFrom; - std::string pattern; + std::string file; + int line; + std::string includedFrom; + std::string pattern; }; -extern WXDLLIMPEXP_CL int IncludeFinder( const char* filePath, std::vector &includes ); +extern WXDLLIMPEXP_CL int IncludeFinder(const char* filePath, std::vector& includes); #endif diff --git a/CodeLite/Cxx/y.tab.h b/CodeLite/Cxx/y.tab.h index e8f235af25..e3b0cc3da7 100644 --- a/CodeLite/Cxx/y.tab.h +++ b/CodeLite/Cxx/y.tab.h @@ -1,28 +1,28 @@ -////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// -// -// copyright : (C) 2008 by Eran Ifrah -// file name : y.tab.h -// -// ------------------------------------------------------------------------- -// A -// _____ _ _ _ _ -// / __ \ | | | | (_) | -// | / \/ ___ __| | ___| | _| |_ ___ -// | | / _ \ / _ |/ _ \ | | | __/ _ ) -// | \__/\ (_) | (_| | __/ |___| | || __/ -// \____/\___/ \__,_|\___\_____/_|\__\___| -// -// F i l e -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation; either version 2 of the License, or -// (at your option) any later version. -// -////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// - /*#ifdef __cplusplus*/ +////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// +// +// copyright : (C) 2008 by Eran Ifrah +// file name : y.tab.h +// +// ------------------------------------------------------------------------- +// A +// _____ _ _ _ _ +// / __ \ | | | | (_) | +// | / \/ ___ __| | ___| | _| |_ ___ +// | | / _ \ / _ |/ _ \ | | | __/ _ ) +// | \__/\ (_) | (_| | __/ |___| | || __/ +// \____/\___/ \__,_|\___\_____/_|\__\___| +// +// F i l e +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; either version 2 of the License, or +// (at your option) any later version. +// +////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// +/*#ifdef __cplusplus*/ namespace flex { /*#endif*/ @@ -109,6 +109,6 @@ namespace flex #define CPPComment 336 #define POUNDPOUND 337 -//#ifdef __cplusplus +// #ifdef __cplusplus } // namespace flex -//#endif +// #endif diff --git a/CodeLite/FontUtils.cpp b/CodeLite/FontUtils.cpp index b73367c5c1..43e75e9101 100644 --- a/CodeLite/FontUtils.cpp +++ b/CodeLite/FontUtils.cpp @@ -17,7 +17,7 @@ constexpr int DEFAULT_FONT_SIZE = 14; #endif #ifdef __WXMSW__ -const std::unordered_set words = { "SemiBold", "Semibold", "Extended", "Semi Bold", "Semi bold" }; +const std::unordered_set words = {"SemiBold", "Semibold", "Extended", "Semi Bold", "Semi bold"}; #endif std::unordered_map fixed_fonts_cache; @@ -46,7 +46,7 @@ const wxString& GetFontInfo(const wxString& font_desc) #endif // update the cache - fixed_fonts_cache.insert({ font_desc, desc }); + fixed_fonts_cache.insert({font_desc, desc}); // return the cached entry return fixed_fonts_cache[font_desc]; } diff --git a/CodeLite/LSP/CodeActionRequest.cpp b/CodeLite/LSP/CodeActionRequest.cpp index 20e304f7d4..e2bcf94995 100644 --- a/CodeLite/LSP/CodeActionRequest.cpp +++ b/CodeLite/LSP/CodeActionRequest.cpp @@ -3,7 +3,8 @@ #include "LSP/LSPEvent.h" #include "event_notifier.h" -LSP::CodeActionRequest::CodeActionRequest(const LSP::TextDocumentIdentifier& textDocument, const LSP::Range& range, +LSP::CodeActionRequest::CodeActionRequest(const LSP::TextDocumentIdentifier& textDocument, + const LSP::Range& range, const std::vector& diags) { SetMethod("textDocument/codeAction"); @@ -20,7 +21,7 @@ void LSP::CodeActionRequest::OnResponse(const LSP::ResponseMessage& response, wx LSP_DEBUG() << "LSP::CodeActionRequest::OnResponse()" << endl; LSP_DEBUG() << response.ToString() << endl; auto result_arr = response.Get("result"); - if(!result_arr.isArray()) { + if (!result_arr.isArray()) { LSP_WARNING() << "CodeAction result is expected to be of type array" << endl; return; } @@ -28,11 +29,11 @@ void LSP::CodeActionRequest::OnResponse(const LSP::ResponseMessage& response, wx // expected array of commands size_t count = result_arr.arraySize(); - LSPEvent event{ wxEVT_LSP_CODE_ACTIONS }; + LSPEvent event{wxEVT_LSP_CODE_ACTIONS}; auto& commands = event.GetCommands(); commands.reserve(count); - for(size_t i = 0; i < count; ++i) { + for (size_t i = 0; i < count; ++i) { LSP::Command cmd; cmd.FromJSON(result_arr[i]); commands.push_back(cmd); diff --git a/CodeLite/LSP/CodeActionRequest.hpp b/CodeLite/LSP/CodeActionRequest.hpp index 283908fe65..a71fb40396 100644 --- a/CodeLite/LSP/CodeActionRequest.hpp +++ b/CodeLite/LSP/CodeActionRequest.hpp @@ -9,7 +9,8 @@ namespace LSP class WXDLLIMPEXP_CL CodeActionRequest : public Request { public: - CodeActionRequest(const LSP::TextDocumentIdentifier& textDocument, const LSP::Range& range, + CodeActionRequest(const LSP::TextDocumentIdentifier& textDocument, + const LSP::Range& range, const std::vector& diags = {}); ~CodeActionRequest() override = default; diff --git a/CodeLite/LSP/CompletionItem.cpp b/CodeLite/LSP/CompletionItem.cpp index 1db0747dad..53c297f9ce 100644 --- a/CodeLite/LSP/CompletionItem.cpp +++ b/CodeLite/LSP/CompletionItem.cpp @@ -10,8 +10,8 @@ void LSP::CompletionItem::FromJSON(const JSONItem& json) // parse the documentation auto doc = json.namedObject("documentation"); - if(doc.isOk()) { - if(doc.isString()) { + if (doc.isOk()) { + if (doc.isString()) { // plain string, nothing more to be done here m_documentation.SetKind("plaintext"); m_documentation.SetValue(doc.toString()); @@ -25,10 +25,10 @@ void LSP::CompletionItem::FromJSON(const JSONItem& json) m_insertText = json.namedObject("insertText").toString(); m_insertTextFormat = json.namedObject("insertTextFormat").toString(); m_vAdditionalText.clear(); - if(json.hasNamedObject("additionalTextEdits")) { + if (json.hasNamedObject("additionalTextEdits")) { JSONItem additionalTextEdits = json.namedObject("additionalTextEdits"); int count = additionalTextEdits.arraySize(); - for(int i = 0; i < count; ++i) { + for (int i = 0; i < count; ++i) { auto edit = std::make_shared(); edit->FromJSON(additionalTextEdits.arrayItem(i)); m_vAdditionalText.push_back(edit); @@ -39,7 +39,7 @@ void LSP::CompletionItem::FromJSON(const JSONItem& json) m_label.Trim().Trim(false); m_detail.Trim().Trim(false); m_documentation.SetValue(wxString(m_documentation.GetValue()).Trim().Trim(false)); - if(json.hasNamedObject("textEdit") && !json.namedObject("textEdit").isNull()) { + if (json.hasNamedObject("textEdit") && !json.namedObject("textEdit").isNull()) { m_textEdit.reset(new LSP::TextEdit()); m_textEdit->FromJSON(json.namedObject("textEdit")); } diff --git a/CodeLite/LSP/CompletionRequest.cpp b/CodeLite/LSP/CompletionRequest.cpp index b4815ea408..a86bd075e6 100644 --- a/CodeLite/LSP/CompletionRequest.cpp +++ b/CodeLite/LSP/CompletionRequest.cpp @@ -5,7 +5,8 @@ #include "LSP/basic_types.h" LSP::CompletionRequest::CompletionRequest(const LSP::TextDocumentIdentifier& textDocument, - const LSP::Position& position, bool userTriggered) + const LSP::Position& position, + bool userTriggered) { SetMethod("textDocument/completion"); m_userTrigger = userTriggered; @@ -17,21 +18,21 @@ LSP::CompletionRequest::CompletionRequest(const LSP::TextDocumentIdentifier& tex void LSP::CompletionRequest::OnResponse(const LSP::ResponseMessage& response, wxEvtHandler* owner) { JSONItem result = response.Get("result"); - if(!result.isOk()) { + if (!result.isOk()) { LSP_WARNING() << "LSP::CompletionRequest::OnResponse(): invalid 'result' object"; return; } // We now accept the 'items' array JSONItem items = result.namedObject("items"); - if(!items.isOk()) { + if (!items.isOk()) { LSP_WARNING() << "LSP::CompletionRequest::OnResponse(): invalid 'items' object"; // LSP_WARNING() << result.format() << clEndl; // return; } JSONItem* pItems = items.isOk() ? &items : &result; - if(!pItems->isArray()) { + if (!pItems->isArray()) { LSP_WARNING() << "LSP::CompletionRequest::OnResponse(): items is not of type array"; return; } @@ -39,17 +40,17 @@ void LSP::CompletionRequest::OnResponse(const LSP::ResponseMessage& response, wx CompletionItem::Vec_t completions; const int itemsCount = pItems->arraySize(); LSP_DEBUG() << "Read" << itemsCount << "completion items"; - for(int i = 0; i < itemsCount; ++i) { + for (int i = 0; i < itemsCount; ++i) { CompletionItem::Ptr_t completionItem(new CompletionItem()); completionItem->FromJSON(pItems->arrayItem(i)); - if(completionItem->GetInsertText().IsEmpty()) { + if (completionItem->GetInsertText().IsEmpty()) { completionItem->SetInsertText(completionItem->GetLabel()); } completions.push_back(completionItem); } LSP_DEBUG() << "Received:" << completions.size() << "completion items"; - if(!completions.empty()) { + if (!completions.empty()) { LSPEvent event(wxEVT_LSP_COMPLETION_READY); event.SetCompletions(completions); event.SetTriggerKind(m_userTrigger ? CompletionItem::kTriggerUser : CompletionItem::kTriggerKindInvoked); diff --git a/CodeLite/LSP/CompletionRequest.h b/CodeLite/LSP/CompletionRequest.h index 452cf27dd8..b6141748e1 100644 --- a/CodeLite/LSP/CompletionRequest.h +++ b/CodeLite/LSP/CompletionRequest.h @@ -10,7 +10,8 @@ namespace LSP class WXDLLIMPEXP_CL CompletionRequest : public LSP::Request { public: - CompletionRequest(const LSP::TextDocumentIdentifier& textDocument, const LSP::Position& position, + CompletionRequest(const LSP::TextDocumentIdentifier& textDocument, + const LSP::Position& position, bool userTriggered); ~CompletionRequest() override = default; void OnResponse(const LSP::ResponseMessage& response, wxEvtHandler* owner) override; diff --git a/CodeLite/LSP/DidChangeTextDocumentRequest.cpp b/CodeLite/LSP/DidChangeTextDocumentRequest.cpp index 2d21851bee..bd0b93b3ac 100644 --- a/CodeLite/LSP/DidChangeTextDocumentRequest.cpp +++ b/CodeLite/LSP/DidChangeTextDocumentRequest.cpp @@ -14,5 +14,5 @@ LSP::DidChangeTextDocumentRequest::DidChangeTextDocumentRequest(const wxString& TextDocumentContentChangeEvent changeEvent; changeEvent.SetText(fileContent); - m_params->As()->SetContentChanges({ changeEvent }); + m_params->As()->SetContentChanges({changeEvent}); } diff --git a/CodeLite/LSP/DidOpenTextDocumentRequest.cpp b/CodeLite/LSP/DidOpenTextDocumentRequest.cpp index 4b4c63ed9f..e24520ca0c 100644 --- a/CodeLite/LSP/DidOpenTextDocumentRequest.cpp +++ b/CodeLite/LSP/DidOpenTextDocumentRequest.cpp @@ -1,6 +1,7 @@ #include "DidOpenTextDocumentRequest.h" -LSP::DidOpenTextDocumentRequest::DidOpenTextDocumentRequest(const wxString& filename, const wxString& text, +LSP::DidOpenTextDocumentRequest::DidOpenTextDocumentRequest(const wxString& filename, + const wxString& text, const wxString& language) { SetMethod("textDocument/didOpen"); diff --git a/CodeLite/LSP/FilePath.cpp b/CodeLite/LSP/FilePath.cpp index 298d966c99..52d6f01f55 100644 --- a/CodeLite/LSP/FilePath.cpp +++ b/CodeLite/LSP/FilePath.cpp @@ -4,9 +4,8 @@ LSP::FilePath::FilePath(const wxString& path) : m_path(path) { #ifdef __WXMSW__ - if(!m_path.StartsWith("file://") && !m_path.StartsWith("/")) { + if (!m_path.StartsWith("file://") && !m_path.StartsWith("/")) { m_path.Replace("/", "\\"); } #endif } - diff --git a/CodeLite/LSP/FilePath.hpp b/CodeLite/LSP/FilePath.hpp index 9f7f01a66b..6c2304e6e7 100644 --- a/CodeLite/LSP/FilePath.hpp +++ b/CodeLite/LSP/FilePath.hpp @@ -2,6 +2,7 @@ #define FILEPATH_HPP #include "codelite_exports.h" + #include namespace LSP diff --git a/CodeLite/LSP/FindReferencesRequest.cpp b/CodeLite/LSP/FindReferencesRequest.cpp index a7bff5ef56..803799f95e 100644 --- a/CodeLite/LSP/FindReferencesRequest.cpp +++ b/CodeLite/LSP/FindReferencesRequest.cpp @@ -4,7 +4,9 @@ #include "LSP/LSPEvent.h" #include "event_notifier.h" -LSP::FindReferencesRequest::FindReferencesRequest(const wxString& filename, size_t line, size_t column, +LSP::FindReferencesRequest::FindReferencesRequest(const wxString& filename, + size_t line, + size_t column, bool includeDeclaration) { SetMethod("textDocument/references"); @@ -22,11 +24,11 @@ void LSP::FindReferencesRequest::OnResponse(const LSP::ResponseMessage& response // An array of locations int array_size = result.arraySize(); - LSPEvent references_event{ wxEVT_LSP_REFERENCES }; + LSPEvent references_event{wxEVT_LSP_REFERENCES}; std::vector& locations = references_event.GetLocations(); locations.reserve(array_size); - for(int i = 0; i < array_size; ++i) { + for (int i = 0; i < array_size; ++i) { auto d = result[i]; LSP::Location loc; loc.FromJSON(d); diff --git a/CodeLite/LSP/GotoDeclarationRequest.cpp b/CodeLite/LSP/GotoDeclarationRequest.cpp index b7713480e2..bc459ff3f9 100644 --- a/CodeLite/LSP/GotoDeclarationRequest.cpp +++ b/CodeLite/LSP/GotoDeclarationRequest.cpp @@ -4,7 +4,9 @@ #include "event_notifier.h" #include "file_logger.h" -LSP::GotoDeclarationRequest::GotoDeclarationRequest(const wxString& filename, size_t line, size_t column, +LSP::GotoDeclarationRequest::GotoDeclarationRequest(const wxString& filename, + size_t line, + size_t column, bool for_add_missing_header) : m_filename(filename) , m_line(line) @@ -21,12 +23,12 @@ void LSP::GotoDeclarationRequest::OnResponse(const LSP::ResponseMessage& respons { LOG_IF_TRACE { LSP_TRACE() << "GotoDeclarationRequest::OnResponse() is called" << endl; } JSONItem result = response.Get("result"); - if(!result.isOk()) { + if (!result.isOk()) { return; } LSP::Location loc; - if(result.isArray()) { + if (result.isArray()) { loc.FromJSON(result.arrayItem(0)); } else { loc.FromJSON(result); @@ -34,15 +36,15 @@ void LSP::GotoDeclarationRequest::OnResponse(const LSP::ResponseMessage& respons LOG_IF_TRACE { LSP_TRACE() << result.format() << endl; } - if(!loc.GetPath().IsEmpty()) { - if(m_for_add_missing_header) { - LSPEvent event{ wxEVT_LSP_SYMBOL_DECLARATION_FOUND }; + if (!loc.GetPath().IsEmpty()) { + if (m_for_add_missing_header) { + LSPEvent event{wxEVT_LSP_SYMBOL_DECLARATION_FOUND}; event.SetLocation(loc); event.SetFileName(m_filename); EventNotifier::Get()->AddPendingEvent(event); } else { // We send the same event for declaration as we do for definition - LSPEvent event{ wxEVT_LSP_DEFINITION }; + LSPEvent event{wxEVT_LSP_DEFINITION}; event.SetLocation(loc); event.SetFileName(m_filename); owner->AddPendingEvent(event); diff --git a/CodeLite/LSP/GotoDefinitionRequest.cpp b/CodeLite/LSP/GotoDefinitionRequest.cpp index e244ca31d7..1498101f31 100644 --- a/CodeLite/LSP/GotoDefinitionRequest.cpp +++ b/CodeLite/LSP/GotoDefinitionRequest.cpp @@ -16,15 +16,15 @@ LSP::GotoDefinitionRequest::GotoDefinitionRequest(const wxString& filename, size void LSP::GotoDefinitionRequest::OnResponse(const LSP::ResponseMessage& response, wxEvtHandler* owner) { JSONItem result = response.Get("result"); - if(!result.isOk()) { + if (!result.isOk()) { return; } std::vector locations; - if(result.isArray()) { + if (result.isArray()) { int count = result.arraySize(); locations.reserve(count); - for(int i = 0; i < count; ++i) { + for (int i = 0; i < count; ++i) { LSP::Location loc; loc.FromJSON(result.arrayItem(i)); locations.emplace_back(loc); @@ -35,7 +35,7 @@ void LSP::GotoDefinitionRequest::OnResponse(const LSP::ResponseMessage& response locations.push_back(loc); } - if(locations.empty()) { + if (locations.empty()) { return; } diff --git a/CodeLite/LSP/GotoImplementationRequest.cpp b/CodeLite/LSP/GotoImplementationRequest.cpp index 686fec846b..18c988428a 100644 --- a/CodeLite/LSP/GotoImplementationRequest.cpp +++ b/CodeLite/LSP/GotoImplementationRequest.cpp @@ -14,18 +14,18 @@ LSP::GotoImplementationRequest::GotoImplementationRequest(const wxString& filena void LSP::GotoImplementationRequest::OnResponse(const LSP::ResponseMessage& response, wxEvtHandler* owner) { JSONItem result = response.Get("result"); - if(!result.isOk()) { + if (!result.isOk()) { return; } LSP::Location loc; - if(result.isArray()) { + if (result.isArray()) { loc.FromJSON(result.arrayItem(0)); } else { loc.FromJSON(result); } // We send the same event for declaration as we do for definition - if(!loc.GetPath().IsEmpty()) { + if (!loc.GetPath().IsEmpty()) { LSPEvent definitionEvent(wxEVT_LSP_DEFINITION); definitionEvent.SetLocation(loc); owner->AddPendingEvent(definitionEvent); diff --git a/CodeLite/LSP/HoverRequest.cpp b/CodeLite/LSP/HoverRequest.cpp index 8432127bcf..45e76e0493 100644 --- a/CodeLite/LSP/HoverRequest.cpp +++ b/CodeLite/LSP/HoverRequest.cpp @@ -1,4 +1,5 @@ #include "HoverRequest.hpp" + #include "LSP/LSPEvent.h" LSP::HoverRequest::HoverRequest(const wxString& filename, size_t line, size_t column) @@ -11,7 +12,7 @@ LSP::HoverRequest::HoverRequest(const wxString& filename, size_t line, size_t co void LSP::HoverRequest::OnResponse(const LSP::ResponseMessage& response, wxEvtHandler* owner) { - if(!response.Has("result")) { + if (!response.Has("result")) { return; } JSONItem res = response.Get("result"); diff --git a/CodeLite/LSP/InitializedNotification.cpp b/CodeLite/LSP/InitializedNotification.cpp index fa42e3065a..9fc650db24 100644 --- a/CodeLite/LSP/InitializedNotification.cpp +++ b/CodeLite/LSP/InitializedNotification.cpp @@ -3,10 +3,7 @@ namespace LSP { struct InitializedParams : public Params { - JSONItem ToJSON() const override - { - return JSONItem::createObject(); - } + JSONItem ToJSON() const override { return JSONItem::createObject(); } void FromJSON(const JSONItem& json) override { wxUnusedVar(json); }; }; diff --git a/CodeLite/LSP/LSPEvent.h b/CodeLite/LSP/LSPEvent.h index 149a195180..9f57a9ef2c 100644 --- a/CodeLite/LSP/LSPEvent.h +++ b/CodeLite/LSP/LSPEvent.h @@ -38,7 +38,7 @@ class WXDLLIMPEXP_CL LSPEvent : public clCommandEvent public: LSPEvent(wxEventType commandType = wxEVT_NULL, int winid = 0); LSPEvent(const LSPEvent&) = default; - LSPEvent& operator=(const LSPEvent& ) = delete; + LSPEvent& operator=(const LSPEvent&) = delete; ~LSPEvent() override = default; void SetTriggerKind(LSP::CompletionItem::eTriggerKind triggerKind) { this->m_triggerKind = triggerKind; } @@ -119,7 +119,8 @@ using LSPEventFunction = void (wxEvtHandler::*)(LSPEvent&); wxDECLARE_EXPORTED_EVENT(WXDLLIMPEXP_CL, wxEVT_LSP_DEFINITION, LSPEvent); wxDECLARE_EXPORTED_EVENT(WXDLLIMPEXP_CL, wxEVT_LSP_INITIALIZED, LSPEvent); wxDECLARE_EXPORTED_EVENT(WXDLLIMPEXP_CL, wxEVT_LSP_COMPLETION_READY, LSPEvent); -wxDECLARE_EXPORTED_EVENT(WXDLLIMPEXP_CL, wxEVT_LSP_DOCUMENT_SYMBOLS_QUICK_OUTLINE, +wxDECLARE_EXPORTED_EVENT(WXDLLIMPEXP_CL, + wxEVT_LSP_DOCUMENT_SYMBOLS_QUICK_OUTLINE, LSPEvent); // fired twice: m_owner && EventNotifier wxDECLARE_EXPORTED_EVENT(WXDLLIMPEXP_CL, wxEVT_LSP_DOCUMENT_SYMBOLS_FOR_HIGHLIGHT, LSPEvent); wxDECLARE_EXPORTED_EVENT(WXDLLIMPEXP_CL, wxEVT_LSP_DOCUMENT_SYMBOLS_OUTLINE_VIEW, LSPEvent); diff --git a/CodeLite/LSP/Message.cpp b/CodeLite/LSP/Message.cpp index 6535aee955..a674dae140 100644 --- a/CodeLite/LSP/Message.cpp +++ b/CodeLite/LSP/Message.cpp @@ -18,18 +18,18 @@ bool HasCompleteMessage(const std::string& inbuf, unsigned long content_length, int ReadHeaders(const std::string& message, std::unordered_map& headers) { int where = message.find("\r\n\r\n"); - if(where == wxNOT_FOUND) { + if (where == wxNOT_FOUND) { return wxNOT_FOUND; } auto headerSection = message.substr(0, where); // excluding the "\r\n\r\n" wxArrayString lines = ::wxStringTokenize(headerSection, "\n", wxTOKEN_STRTOK); - for(wxString& header : lines) { + for (wxString& header : lines) { header.Trim().Trim(false); wxString name = header.BeforeFirst(':'); wxString value = header.AfterFirst(':'); headers.insert( - { name.Trim().Trim(false).mb_str(wxConvUTF8).data(), value.Trim().Trim(false).mb_str(wxConvUTF8).data() }); + {name.Trim().Trim(false).mb_str(wxConvUTF8).data(), value.Trim().Trim(false).mb_str(wxConvUTF8).data()}); } // return the headers section + the separator @@ -58,26 +58,26 @@ std::unique_ptr LSP::Message::GetJSONPayload(std::string& network_buffer) // Strip the headers std::unordered_map headers; int headersSize = ReadHeaders(network_buffer, headers); - if(headersSize == wxNOT_FOUND) { + if (headersSize == wxNOT_FOUND) { LSP_WARNING() << "Unable to read headers from buffer:" << endl; LSP_WARNING() << network_buffer << endl; return nullptr; } - if(headers.count(HEADER_CONTENT_LENGTH) == 0) { + if (headers.count(HEADER_CONTENT_LENGTH) == 0) { LSP_WARNING() << "LSP message header does not contain the Content-Length header!" << endl; return nullptr; } unsigned long contentLength = 0; wxString contentLengthValue = headers[HEADER_CONTENT_LENGTH]; - if(!contentLengthValue.ToCULong(&contentLength)) { + if (!contentLengthValue.ToCULong(&contentLength)) { LSP_WARNING() << "Failed to convert Content-Length header to number" << endl; LSP_WARNING() << "Content-Length:" << headers[HEADER_CONTENT_LENGTH] << endl; return nullptr; } - if(!HasCompleteMessage(network_buffer, contentLength, headersSize)) { + if (!HasCompleteMessage(network_buffer, contentLength, headersSize)) { LSP_DEBUG() << "Input buffer is too small" << endl; return nullptr; } @@ -94,7 +94,7 @@ std::unique_ptr LSP::Message::GetJSONPayload(std::string& network_buffer) LOG_IF_TRACE { - if(json_str.length() != payload.length()) { + if (json_str.length() != payload.length()) { LSP_TRACE() << "UTF8 chars detected" << endl; LSP_TRACE() << "wx.length()=" << json_str.length() << endl; LSP_TRACE() << "c.length()=" << payload.length() << endl; @@ -102,7 +102,7 @@ std::unique_ptr LSP::Message::GetJSONPayload(std::string& network_buffer) } } - if(!json_str.EndsWith("}")) { + if (!json_str.EndsWith("}")) { LSP_WARNING() << "JSON payload does not end with '}'" << endl; // for debugging purposes, dump the content @@ -116,7 +116,7 @@ std::unique_ptr LSP::Message::GetJSONPayload(std::string& network_buffer) } std::unique_ptr json(new JSON(json_str)); - if(!json->isOk()) { + if (!json->isOk()) { LSP_ERROR() << "Unable to parse JSON object from response!" << endl; return json; } diff --git a/CodeLite/LSP/Message.h b/CodeLite/LSP/Message.h index 9a80350149..09b1837db1 100644 --- a/CodeLite/LSP/Message.h +++ b/CodeLite/LSP/Message.h @@ -34,7 +34,11 @@ class WXDLLIMPEXP_CL Message : public LSP::Serializable */ static std::unique_ptr GetJSONPayload(std::string& network_buffer); - template T* As() const { return dynamic_cast(const_cast(this)); } + template + T* As() const + { + return dynamic_cast(const_cast(this)); + } }; } // namespace LSP diff --git a/CodeLite/LSP/RenameRequest.cpp b/CodeLite/LSP/RenameRequest.cpp index 4e3eb547c9..179b893a87 100644 --- a/CodeLite/LSP/RenameRequest.cpp +++ b/CodeLite/LSP/RenameRequest.cpp @@ -24,7 +24,7 @@ void LSP::RenameRequest::OnResponse(const LSP::ResponseMessage& response, wxEvtH std::unordered_map> modifications = ParseWorkspaceEdit(result); - LSPEvent event_edit_files{ wxEVT_LSP_EDIT_FILES }; + LSPEvent event_edit_files{wxEVT_LSP_EDIT_FILES}; event_edit_files.SetAnswer(true); // Prompt the user event_edit_files.SetChanges(modifications); owner->AddPendingEvent(event_edit_files); @@ -32,9 +32,9 @@ void LSP::RenameRequest::OnResponse(const LSP::ResponseMessage& response, wxEvtH LOG_IF_DEBUG { LSP_DEBUG() << "Updating" << modifications.size() << "files:" << endl; - for(const auto& [filepath, changes] : modifications) { + for (const auto& [filepath, changes] : modifications) { LSP_DEBUG() << " " << filepath << modifications.size() << "changes:" << endl; - for(const auto& change : changes) { + for (const auto& change : changes) { LSP_DEBUG() << " " << change.ToJSON().format(false) << endl; } } @@ -48,6 +48,6 @@ void LSP::RenameRequest::OnError(const LSP::ResponseMessage& response, wxEvtHand // {"error":{"code":-32001,"message":"invalid name: conflict with the symbol in // C:/msys64/home/eran/devl/test_cpp/main.cpp:9:17"},"id":111,"jsonrpc":"2.0"} LSP::ResponseError errMsg(response.ToString()); - wxMessageBox(wxString::Format(_("Rename symbol error:\n%s"), errMsg.GetMessage()), "CodeLite", - wxICON_ERROR | wxCENTER); + wxMessageBox( + wxString::Format(_("Rename symbol error:\n%s"), errMsg.GetMessage()), "CodeLite", wxICON_ERROR | wxCENTER); } diff --git a/CodeLite/LSP/ResponseError.cpp b/CodeLite/LSP/ResponseError.cpp index f55ceff180..1a4245cee2 100644 --- a/CodeLite/LSP/ResponseError.cpp +++ b/CodeLite/LSP/ResponseError.cpp @@ -8,7 +8,7 @@ LSP::ResponseError::ResponseError(const wxString& message) void LSP::ResponseError::FromJSON(const JSONItem& json) { - if(json.hasNamedObject("error")) { + if (json.hasNamedObject("error")) { // serialize the parent this->Message::FromJSON(json); diff --git a/CodeLite/LSP/ResponseError.h b/CodeLite/LSP/ResponseError.h index bf88736d57..6d8506ecce 100644 --- a/CodeLite/LSP/ResponseError.h +++ b/CodeLite/LSP/ResponseError.h @@ -11,7 +11,7 @@ class WXDLLIMPEXP_CL ResponseError : public Message { int m_errorCode = wxNOT_FOUND; wxString m_message; - + public: enum eErrorCodes { kErrorCodeParseError = -32700, diff --git a/CodeLite/LSP/ResponseMessage.cpp b/CodeLite/LSP/ResponseMessage.cpp index 33347d9c8e..6e05a27c9e 100644 --- a/CodeLite/LSP/ResponseMessage.cpp +++ b/CodeLite/LSP/ResponseMessage.cpp @@ -11,7 +11,7 @@ LSP::ResponseMessage::ResponseMessage(std::unique_ptr&& json) std::string LSP::ResponseMessage::ToString() const { - if(!m_json || !m_json->isOk()) { + if (!m_json || !m_json->isOk()) { return ""; } return StringUtils::ToStdString(m_json->toElement().format(false)); @@ -33,7 +33,7 @@ bool LSP::ResponseMessage::Has(const wxString& property) const JSONItem LSP::ResponseMessage::Get(const wxString& property) const { - if(!Has(property)) { + if (!Has(property)) { return JSONItem(nullptr); } return m_json->toElement().namedObject(property); @@ -42,14 +42,14 @@ JSONItem LSP::ResponseMessage::Get(const wxString& property) const std::vector LSP::ResponseMessage::GetDiagnostics() const { JSONItem params = Get("params"); - if(!params.isOk()) { + if (!params.isOk()) { return {}; } std::vector res; JSONItem arrDiags = params.namedObject("diagnostics"); int size = arrDiags.arraySize(); - for(int i = 0; i < size; ++i) { + for (int i = 0; i < size; ++i) { LSP::Diagnostic d; d.FromJSON(arrDiags.arrayItem(i)); res.push_back(d); @@ -60,7 +60,7 @@ std::vector LSP::ResponseMessage::GetDiagnostics() const wxString LSP::ResponseMessage::GetDiagnosticsUri() const { JSONItem params = Get("params"); - if(!params.isOk()) { + if (!params.isOk()) { return ""; } return params.namedObject("uri").toString(); diff --git a/CodeLite/LSP/SignatureHelpRequest.cpp b/CodeLite/LSP/SignatureHelpRequest.cpp index e260cef43b..4d18dabfc1 100644 --- a/CodeLite/LSP/SignatureHelpRequest.cpp +++ b/CodeLite/LSP/SignatureHelpRequest.cpp @@ -15,7 +15,7 @@ LSP::SignatureHelpRequest::SignatureHelpRequest(const wxString& filename, size_t void LSP::SignatureHelpRequest::OnResponse(const LSP::ResponseMessage& response, wxEvtHandler* owner) { - if(!response.Has("result")) { + if (!response.Has("result")) { return; } JSONItem res = response.Get("result"); diff --git a/CodeLite/LSP/WorkspaceSymbolRequest.cpp b/CodeLite/LSP/WorkspaceSymbolRequest.cpp index 9e36a4ff0e..9a09f9bedc 100644 --- a/CodeLite/LSP/WorkspaceSymbolRequest.cpp +++ b/CodeLite/LSP/WorkspaceSymbolRequest.cpp @@ -8,12 +8,12 @@ namespace { clModuleLogger& operator<<(clModuleLogger& logger, const std::vector& symbols) { - if(!logger.CanLog()) + if (!logger.CanLog()) return logger; wxString s; s << "\n[\n"; - for(const LSP::SymbolInformation& d : symbols) { + for (const LSP::SymbolInformation& d : symbols) { s << " " << d.GetContainerName() << "." << d.GetName() << ",\n"; } s << "]\n"; @@ -59,18 +59,18 @@ void LSP::WorkspaceSymbolRequest::OnResponse(const LSP::ResponseMessage& respons wxUnusedVar(owner); auto result = response.Get("result"); - if(!result.isOk()) { + if (!result.isOk()) { LSP_WARNING() << "LSP::WorkspaceSymbolRequest::OnResponse(): invalid 'result' object"; return; } - if(!result.isArray()) { + if (!result.isArray()) { LSP_WARNING() << "workspace/symbol: expected array result" << endl; return; } int size = result.arraySize(); - if(size == 0) { - LSPEvent symbols_event{ wxEVT_LSP_WORKSPACE_SYMBOLS }; + if (size == 0) { + LSPEvent symbols_event{wxEVT_LSP_WORKSPACE_SYMBOLS}; owner->QueueEvent(symbols_event.Clone()); return; } @@ -78,11 +78,11 @@ void LSP::WorkspaceSymbolRequest::OnResponse(const LSP::ResponseMessage& respons LOG_IF_TRACE { LSP_TRACE() << result.format() << endl; } // only SymbolInformation has the `location` property // fire an event with all the symbols - LSPEvent symbols_event{ wxEVT_LSP_WORKSPACE_SYMBOLS }; + LSPEvent symbols_event{wxEVT_LSP_WORKSPACE_SYMBOLS}; auto& symbols = symbols_event.GetSymbolsInformation(); symbols.reserve(size); - for(int i = 0; i < size; ++i) { + for (int i = 0; i < size; ++i) { SymbolInformation si; si.FromJSON(result[i]); symbols.push_back(si); diff --git a/CodeLite/LSP/basic_types.h b/CodeLite/LSP/basic_types.h index 0cf4067ecd..b9f3c410a2 100644 --- a/CodeLite/LSP/basic_types.h +++ b/CodeLite/LSP/basic_types.h @@ -87,7 +87,7 @@ class WXDLLIMPEXP_CL Position : public Serializable Position() = default; ~Position() override = default; bool operator==(const Position& rhs) const = default; - auto operator<=> (const Position& rhs) const = default; + auto operator<=>(const Position& rhs) const = default; Position& SetCharacter(int character) { diff --git a/CodeLite/LSP/json_rpc_params.cpp b/CodeLite/LSP/json_rpc_params.cpp index 1292089da8..08ae928d5e 100644 --- a/CodeLite/LSP/json_rpc_params.cpp +++ b/CodeLite/LSP/json_rpc_params.cpp @@ -67,10 +67,10 @@ void DidChangeTextDocumentParams::FromJSON(const JSONItem& json) { m_textDocument.FromJSON(json["textDocument"]); m_contentChanges.clear(); - if(json.hasNamedObject("contentChanges")) { + if (json.hasNamedObject("contentChanges")) { JSONItem arr = json.namedObject("contentChanges"); int count = arr.arraySize(); - for(int i = 0; i < count; ++i) { + for (int i = 0; i < count; ++i) { TextDocumentContentChangeEvent c; c.FromJSON(arr.arrayItem(i)); m_contentChanges.push_back(c); @@ -137,8 +137,8 @@ JSONItem ExecuteCommandParams::ToJSON() const json.addProperty("command", m_command); // parse the "arguments" // and add them - JSON root{ m_arguments }; - if(root.isOk()) { + JSON root{m_arguments}; + if (root.isOk()) { json.addProperty("arguments", std::move(root)); } return json; @@ -159,7 +159,7 @@ JSONItem CodeActionParams::ToJSON() const // add empty context auto context = json.AddObject("context"); auto diags_arr = context.AddArray("diagnostics"); // empty array - for(const auto& diag : m_diagnostics) { + for (const auto& diag : m_diagnostics) { diags_arr.arrayAppend(diag.ToJSON()); } return json; diff --git a/CodeLite/LSP/json_rpc_params.h b/CodeLite/LSP/json_rpc_params.h index bcf19ac63a..05c8f08f28 100644 --- a/CodeLite/LSP/json_rpc_params.h +++ b/CodeLite/LSP/json_rpc_params.h @@ -22,7 +22,11 @@ class WXDLLIMPEXP_CL Params : public Serializable public: Params() = default; virtual ~Params() = default; - template T* As() const { return dynamic_cast(const_cast(this)); } + template + T* As() const + { + return dynamic_cast(const_cast(this)); + } }; //===---------------------------------------------------------------------------------- diff --git a/CodeLite/LSP/json_rpc_results.h b/CodeLite/LSP/json_rpc_results.h index bef286b457..2869be4fd1 100644 --- a/CodeLite/LSP/json_rpc_results.h +++ b/CodeLite/LSP/json_rpc_results.h @@ -20,7 +20,11 @@ class WXDLLIMPEXP_CL Result : public Serializable public: Result() = default; ~Result() override = default; - template T* As() const { return dynamic_cast(const_cast(this)); } + template + T* As() const + { + return dynamic_cast(const_cast(this)); + } JSONItem ToJSON() const override { return JSONItem(nullptr); } }; diff --git a/CodeLite/MSWPrivate.h b/CodeLite/MSWPrivate.h index b861b7fd4e..4f01d1a472 100644 --- a/CodeLite/MSWPrivate.h +++ b/CodeLite/MSWPrivate.h @@ -2,19 +2,21 @@ #define MSWPRIVATE_H #define YY_NEVER_INTERACTIVE 1 -#define CURRENT_GCC_VERSION ((__GNUC__*1000)+(__GNUC_MINOR__*100)) -#define GCC_VERSION(major, minor) ((major*1000)+(minor*100)) +#define CURRENT_GCC_VERSION ((__GNUC__ * 1000) + (__GNUC_MINOR__ * 100)) +#define GCC_VERSION(major, minor) ((major * 1000) + (minor * 100)) -#if CURRENT_GCC_VERSION < GCC_VERSION(4,9) +#if CURRENT_GCC_VERSION < GCC_VERSION(4, 9) #include -namespace std { - template - std::string to_string(T x) { - std::stringstream ss; - ss << x; - return ss.str(); - } +namespace std +{ +template +std::string to_string(T x) +{ + std::stringstream ss; + ss << x; + return ss.str(); } +} // namespace std #endif #endif // MSWPRIVATE_H diff --git a/CodeLite/PHP/PHPDocComment.cpp b/CodeLite/PHP/PHPDocComment.cpp index 217870577f..528e58ce4d 100644 --- a/CodeLite/PHP/PHPDocComment.cpp +++ b/CodeLite/PHP/PHPDocComment.cpp @@ -13,7 +13,7 @@ PHPDocComment::PHPDocComment(PHPSourceFile& sourceFile, const wxString& comment) , m_returnNullable(false) { static std::unordered_set nativeTypes; - if(nativeTypes.empty()) { + if (nativeTypes.empty()) { // List taken from https://www.php.net/manual/en/language.types.intro.php // Native types nativeTypes.insert("bool"); @@ -39,15 +39,15 @@ PHPDocComment::PHPDocComment(PHPSourceFile& sourceFile, const wxString& comment) } static wxRegEx reReturnStatement(wxT("@(return)[ \t]+([\\?\\a-zA-Z_]{1}[\\|\\a-zA-Z0-9_]*)")); - if(reReturnStatement.IsValid() && reReturnStatement.Matches(m_comment)) { + if (reReturnStatement.IsValid() && reReturnStatement.Matches(m_comment)) { wxString returnValue = reReturnStatement.GetMatch(m_comment, 2); - if(returnValue.StartsWith("?")) { + if (returnValue.StartsWith("?")) { returnValue.Remove(0, 1); m_returnNullable = true; } wxArrayString types = ::wxStringTokenize(returnValue, "|", wxTOKEN_STRTOK); - if(types.size() > 1) { + if (types.size() > 1) { // Multiple return types, guess the best match wxString bestMatch; for (const auto& type : types) { @@ -57,23 +57,23 @@ PHPDocComment::PHPDocComment(PHPSourceFile& sourceFile, const wxString& comment) } } - if(bestMatch.IsEmpty()) { + if (bestMatch.IsEmpty()) { bestMatch = types.Item(0); // just get the first match } m_returnValue = sourceFile.MakeIdentifierAbsolute(bestMatch); - } else if(types.size() == 1) { + } else if (types.size() == 1) { m_returnValue = sourceFile.MakeIdentifierAbsolute(types.Item(0)); } } PHPDocVar var(sourceFile, m_comment); - if(var.IsOk()) { + if (var.IsOk()) { m_varType = var.GetType(); m_varName = var.GetName(); } // @param - if(m_comment.Contains("@param")) { + if (m_comment.Contains("@param")) { PHPDocParam params(sourceFile, m_comment); const PHPDocParam::Vec_t& paramsVec = params.Parse(); for (const auto& p : paramsVec) { @@ -83,7 +83,7 @@ PHPDocComment::PHPDocComment(PHPSourceFile& sourceFile, const wxString& comment) } // @property-read, @property-write, @property - if(m_comment.Contains("@property")) { + if (m_comment.Contains("@property")) { PHPDocProperty prop(sourceFile, m_comment); const PHPDocProperty::Tuple_t& properties = prop.ParseParams(); for (const auto& [type, name, desc] : properties) { @@ -101,7 +101,7 @@ PHPDocComment::PHPDocComment(PHPSourceFile& sourceFile, const wxString& comment) const wxString& PHPDocComment::GetParam(size_t n) const { - if(n >= m_paramsArr.GetCount()) { + if (n >= m_paramsArr.GetCount()) { static wxString emptyString; return emptyString; } @@ -116,7 +116,7 @@ const wxString& PHPDocComment::GetVar() const { return m_varType; } const wxString& PHPDocComment::GetParam(const wxString& name) const { - if(m_params.count(name) == 0) { + if (m_params.count(name) == 0) { static wxString emptyString; return emptyString; } @@ -137,7 +137,7 @@ void PHPDocComment::ProcessMethods() for (const auto& [returnType, methodName, signature] : methods) { wxString strBuffer; strBuffer << "GetChildren().empty()) { + if (!buffer.CurrentScope()->GetChildren().empty()) { PHPEntityBase::Ptr_t func = *buffer.CurrentScope()->GetChildren().begin(); - if(func && func->Is(kEntityTypeFunction)) { - if(func->Parent()) { + if (func && func->Is(kEntityTypeFunction)) { + if (func->Parent()) { func->Parent()->RemoveChild(func); } m_methods.push_back(func); diff --git a/CodeLite/PHP/PHPDocComment.h b/CodeLite/PHP/PHPDocComment.h index 06dfb7868c..27611fbd7b 100644 --- a/CodeLite/PHP/PHPDocComment.h +++ b/CodeLite/PHP/PHPDocComment.h @@ -26,16 +26,16 @@ #ifndef PHPDOCCOMMENT_H #define PHPDOCCOMMENT_H +#include "PHPSourceFile.h" #include "codelite_exports.h" -#include + #include -#include "PHPSourceFile.h" +#include class WXDLLIMPEXP_CL PHPDocComment { public: - struct Property - { + struct Property { wxString name; wxString type; wxString desc; diff --git a/CodeLite/PHP/PHPDocParam.cpp b/CodeLite/PHP/PHPDocParam.cpp index 0b4af2a46b..9ae7ed14de 100644 --- a/CodeLite/PHP/PHPDocParam.cpp +++ b/CodeLite/PHP/PHPDocParam.cpp @@ -15,18 +15,18 @@ const PHPDocParam::Vec_t& PHPDocParam::Parse() m_params.clear(); wxStringTokenizer tokenizer(m_comment, " \n\r", wxTOKEN_STRTOK); - while(tokenizer.HasMoreTokens()) { + while (tokenizer.HasMoreTokens()) { wxString word = tokenizer.GetNextToken(); - if(word == "@param") { + if (word == "@param") { // Next word should be the type - if(!tokenizer.HasMoreTokens()) { + if (!tokenizer.HasMoreTokens()) { break; } stype = tokenizer.GetNextToken(); // Next comes the name - if(!tokenizer.HasMoreTokens()) { + if (!tokenizer.HasMoreTokens()) { break; } sname = tokenizer.GetNextToken(); diff --git a/CodeLite/PHP/PHPDocProperty.cpp b/CodeLite/PHP/PHPDocProperty.cpp index f8c3e9f0fe..c76b88cb16 100644 --- a/CodeLite/PHP/PHPDocProperty.cpp +++ b/CodeLite/PHP/PHPDocProperty.cpp @@ -41,12 +41,12 @@ const PHPDocProperty::Tuple_t& PHPDocProperty::ParseMethods() m_params.clear(); wxArrayString lines = ::wxStringTokenize(m_comment, "\n\r", wxTOKEN_STRTOK); for (wxString& line : lines) { - if(line.Contains("@method")) { + if (line.Contains("@method")) { int where = line.Find("@method"); line = line.Mid(where + 7); // skip "@method" line.Replace("\t", " "); line.Trim().Trim(false); - + // @method [return type] [name]([[type] [parameter]<, …>]) [] wxString sig; sig = line.AfterFirst('('); @@ -56,9 +56,9 @@ const PHPDocProperty::Tuple_t& PHPDocProperty::ParseMethods() line = line.BeforeFirst('('); wxArrayString params = ::wxStringTokenize(line, " ", wxTOKEN_STRTOK); - if((params.size() == 2) && !sig.IsEmpty()) { + if ((params.size() == 2) && !sig.IsEmpty()) { m_params.push_back(std::make_tuple(m_sourceFile.MakeIdentifierAbsolute(params[0]), params[1], sig)); - } else if(params.size() == 1 && !sig.IsEmpty()) { + } else if (params.size() == 1 && !sig.IsEmpty()) { m_params.push_back(std::make_tuple(wxEmptyString, params[0], sig)); } } diff --git a/CodeLite/PHP/PHPDocVar.cpp b/CodeLite/PHP/PHPDocVar.cpp index 3f97136ad5..86d34473e3 100644 --- a/CodeLite/PHP/PHPDocVar.cpp +++ b/CodeLite/PHP/PHPDocVar.cpp @@ -27,18 +27,18 @@ void PHPDocVar::Parse(PHPSourceFile& sourceFile, const wxString& doc) // @var Type $name // @var Type // @var $Name Type - if(!tokenizer.HasMoreTokens() || tokenizer.GetNextToken() != "@var") { + if (!tokenizer.HasMoreTokens() || tokenizer.GetNextToken() != "@var") { return; } // Next word should be the type - if(!tokenizer.HasMoreTokens()) { + if (!tokenizer.HasMoreTokens()) { return; } stype = tokenizer.GetNextToken(); // Next comes the name - if(tokenizer.HasMoreTokens()) { + if (tokenizer.HasMoreTokens()) { sname = tokenizer.GetNextToken(); } diff --git a/CodeLite/PHP/PHPDocVisitor.cpp b/CodeLite/PHP/PHPDocVisitor.cpp index 52ad79a3c7..080cb2e58c 100644 --- a/CodeLite/PHP/PHPDocVisitor.cpp +++ b/CodeLite/PHP/PHPDocVisitor.cpp @@ -18,12 +18,12 @@ void PHPDocVisitor::OnEntity(PHPEntityBase::Ptr_t entity) // Locate a comment for this entity entity->SetFilename(m_sourceFile.GetFilename()); - if(!entity->GetDocComment().IsEmpty()) { + if (!entity->GetDocComment().IsEmpty()) { // PHPDoc was already assigned to this entity during the parsing phase - if(entity->Is(kEntityTypeClass)) { + if (entity->Is(kEntityTypeClass)) { // Process @property tags here PHPDocComment docComment(m_sourceFile, entity->GetDocComment()); - if(!docComment.GetProperties().empty()) { + if (!docComment.GetProperties().empty()) { // Got some @properties for (const auto& p : docComment.GetProperties()) { PHPEntityBase::Ptr_t child = entity->FindChild(p.second.name); @@ -40,7 +40,7 @@ void PHPDocVisitor::OnEntity(PHPEntityBase::Ptr_t entity) entity->AddChild(child); } } - } else if(!docComment.GetMethods().empty()) { + } else if (!docComment.GetMethods().empty()) { for (const auto& method : docComment.GetMethods()) { entity->AddChild(method); } @@ -56,36 +56,36 @@ void PHPDocVisitor::OnEntity(PHPEntityBase::Ptr_t entity) wxUnusedVar(entityName); std::map::iterator iter = m_comments.find(lineNum); - if(iter == m_comments.end()) { + if (iter == m_comments.end()) { // try to locate a comment on the same line ++lineNum; iter = m_comments.find(lineNum); } - if(iter != m_comments.end()) { + if (iter != m_comments.end()) { // we got a match entity->SetDocComment(iter->second.Text()); m_comments.erase(iter); PHPDocComment docComment(m_sourceFile, entity->GetDocComment()); - if(entity->Is(kEntityTypeFunction) && !docComment.GetReturn().IsEmpty()) { + if (entity->Is(kEntityTypeFunction) && !docComment.GetReturn().IsEmpty()) { entity->Cast()->SetReturnValue(docComment.GetReturn()); if (docComment.IsReturnNullable()) { entity->Cast()->SetFlag(kFunc_ReturnNullable); } - } else if(entity->Is(kEntityTypeVariable) && !entity->Cast()->IsFunctionArg()) { + } else if (entity->Is(kEntityTypeVariable) && !entity->Cast()->IsFunctionArg()) { // A global variable, const or a member entity->Cast()->SetTypeHint(docComment.GetVar()); } - } else if(entity->Is(kEntityTypeVariable) && entity->Parent() && entity->Parent()->Is(kEntityTypeFunction) && - entity->Cast()->IsFunctionArg()) { + } else if (entity->Is(kEntityTypeVariable) && entity->Parent() && entity->Parent()->Is(kEntityTypeFunction) && + entity->Cast()->IsFunctionArg()) { // A function argument PHPDocComment docComment(m_sourceFile, entity->Parent()->GetDocComment()); wxString typeHint = docComment.GetParam(entity->GetFullName()); const wxString& currentTypeHint = entity->Cast()->GetTypeHint(); - if(!typeHint.IsEmpty() && currentTypeHint.IsEmpty()) { + if (!typeHint.IsEmpty() && currentTypeHint.IsEmpty()) { // The typehint of a function argument should have more value than the one provided // in the documentation entity->Cast()->SetTypeHint(typeHint); diff --git a/CodeLite/PHP/PHPDocVisitor.h b/CodeLite/PHP/PHPDocVisitor.h index 328ead50df..f35e263af8 100644 --- a/CodeLite/PHP/PHPDocVisitor.h +++ b/CodeLite/PHP/PHPDocVisitor.h @@ -26,17 +26,18 @@ #ifndef PHPDOCVISITOR_H #define PHPDOCVISITOR_H -#include "codelite_exports.h" #include "PHPEntityVisitor.h" // Base class: PHPEntityVisitor +#include "PHPSourceFile.h" #include "PhpLexerAPI.h" +#include "codelite_exports.h" + #include -#include "PHPSourceFile.h" class WXDLLIMPEXP_CL PHPDocVisitor : public PHPEntityVisitor { std::map m_comments; PHPSourceFile& m_sourceFile; - + public: PHPDocVisitor(PHPSourceFile& sourceFile, const std::vector& comments); virtual ~PHPDocVisitor() = default; diff --git a/CodeLite/PHP/PHPEntityBase.cpp b/CodeLite/PHP/PHPEntityBase.cpp index b34aa46281..f9ad4267ab 100644 --- a/CodeLite/PHP/PHPEntityBase.cpp +++ b/CodeLite/PHP/PHPEntityBase.cpp @@ -1,4 +1,5 @@ #include "PHPEntityBase.h" + #include PHPEntityBase::PHPEntityBase() @@ -13,7 +14,7 @@ PHPEntityBase::PHPEntityBase() void PHPEntityBase::AddChild(PHPEntityBase::Ptr_t child) { // Add the child to this entity - if(m_childrenMap.count(child->GetFullName()) == 0) { + if (m_childrenMap.count(child->GetFullName()) == 0) { m_children.push_back(child); m_childrenMap.insert(std::make_pair(child->GetFullName(), child)); child->m_parent = this; @@ -23,18 +24,18 @@ void PHPEntityBase::AddChild(PHPEntityBase::Ptr_t child) PHPEntityBase::Ptr_t PHPEntityBase::FindChild(const wxString& name, bool tryPrependingDollar) const { PHPEntityBase::Map_t::const_iterator iter = m_childrenMap.find(name); - if(iter != m_childrenMap.end()) { + if (iter != m_childrenMap.end()) { return iter->second; } // Could not find an exact match, try prepending - if(tryPrependingDollar) { + if (tryPrependingDollar) { wxString modName = name; - if(!modName.StartsWith("$")) { + if (!modName.StartsWith("$")) { modName.Prepend("$"); } iter = m_childrenMap.find(modName); - if(iter != m_childrenMap.end()) { + if (iter != m_childrenMap.end()) { return iter->second; } } @@ -69,20 +70,20 @@ void PHPEntityBase::SetFullName(const wxString& fullname) void PHPEntityBase::RemoveChild(PHPEntityBase::Ptr_t child) { // Remove the child from the map - if(m_childrenMap.count(child->GetFullName())) { + if (m_childrenMap.count(child->GetFullName())) { m_childrenMap.erase(child->GetFullName()); } - + // Remove the child from the list as well PHPEntityBase::List_t::iterator iter = std::find_if(m_children.begin(), m_children.end(), [&](PHPEntityBase::Ptr_t c) { - if(c->GetFullName() == child->GetFullName()) { + if (c->GetFullName() == child->GetFullName()) { return true; } return false; }); - if(iter != m_children.end()) { + if (iter != m_children.end()) { m_children.erase(iter); } child->m_parent = NULL; diff --git a/CodeLite/PHP/PHPEntityBase.h b/CodeLite/PHP/PHPEntityBase.h index fde0d626e6..b9a6ca92f6 100644 --- a/CodeLite/PHP/PHPEntityBase.h +++ b/CodeLite/PHP/PHPEntityBase.h @@ -101,11 +101,11 @@ class WXDLLIMPEXP_CL PHPEntityBase // The database identifier wxLongLong m_dbId; - + protected: JSONItem BaseToJSON(const wxString& entityType) const; void BaseFromJSON(const JSONItem& json); - + public: PHPEntityBase(); virtual ~PHPEntityBase() = default; @@ -127,7 +127,7 @@ class WXDLLIMPEXP_CL PHPEntityBase * @brief generate a php doc comment that matches this entry */ virtual wxString FormatPhpDoc(const CommentConfigData& data) const = 0; - + /** * @brief serialization to JSON */ @@ -136,7 +136,7 @@ class WXDLLIMPEXP_CL PHPEntityBase * @brief serialization from JSON */ virtual void FromJSON(const JSONItem& json) = 0; - + // Setters / Getters void SetFlag(size_t flag, bool b = true) { b ? this->m_flags |= flag : this->m_flags &= ~flag; } bool HasFlag(size_t flag) const { return m_flags & flag; } @@ -206,7 +206,11 @@ class WXDLLIMPEXP_CL PHPEntityBase * @brief convert this base class to its concrete * @return */ - template T* Cast() const { return dynamic_cast(const_cast(this)); } + template + T* Cast() const + { + return dynamic_cast(const_cast(this)); + } /** * @brief store this object and all its children into the database diff --git a/CodeLite/PHP/PHPEntityClass.cpp b/CodeLite/PHP/PHPEntityClass.cpp index ea91013c65..92da5a6e88 100644 --- a/CodeLite/PHP/PHPEntityClass.cpp +++ b/CodeLite/PHP/PHPEntityClass.cpp @@ -9,12 +9,12 @@ void PHPEntityClass::PrintStdout(int indent) const { wxString indentString(' ', indent); wxPrintf("%sClass name: %s", indentString, GetFullName()); - if(!GetExtends().IsEmpty()) { + if (!GetExtends().IsEmpty()) { wxPrintf(", extends %s", GetExtends()); } - if(!GetImplements().IsEmpty()) { + if (!GetImplements().IsEmpty()) { wxPrintf(", implements: "); - for(size_t i = 0; i < GetImplements().GetCount(); ++i) { + for (size_t i = 0; i < GetImplements().GetCount(); ++i) { wxPrintf("%s ", GetImplements().Item(i)); } } @@ -29,11 +29,11 @@ void PHPEntityClass::Store(PHPLookupTable* lookup) { try { wxSQLite3Database& db = lookup->Database(); - wxSQLite3Statement statement = db.PrepareStatement( - "REPLACE INTO SCOPE_TABLE (ID, SCOPE_TYPE, SCOPE_ID, NAME, FULLNAME, EXTENDS, " - "IMPLEMENTS, USING_TRAITS, FLAGS, DOC_COMMENT, " - "LINE_NUMBER, FILE_NAME) VALUES (NULL, 1, :SCOPE_ID, :NAME, :FULLNAME, :EXTENDS, " - ":IMPLEMENTS, :USING_TRAITS, :FLAGS, :DOC_COMMENT, :LINE_NUMBER, :FILE_NAME)"); + wxSQLite3Statement statement = + db.PrepareStatement("REPLACE INTO SCOPE_TABLE (ID, SCOPE_TYPE, SCOPE_ID, NAME, FULLNAME, EXTENDS, " + "IMPLEMENTS, USING_TRAITS, FLAGS, DOC_COMMENT, " + "LINE_NUMBER, FILE_NAME) VALUES (NULL, 1, :SCOPE_ID, :NAME, :FULLNAME, :EXTENDS, " + ":IMPLEMENTS, :USING_TRAITS, :FLAGS, :DOC_COMMENT, :LINE_NUMBER, :FILE_NAME)"); statement.Bind(statement.GetParamIndex(":SCOPE_ID"), Parent()->GetDbId()); statement.Bind(statement.GetParamIndex(":NAME"), GetShortName()); @@ -79,8 +79,8 @@ wxArrayString PHPEntityClass::GetInheritanceArray() const arr.insert(arr.end(), GetImplements().begin(), GetImplements().end()); arr.insert(arr.end(), GetTraits().begin(), GetTraits().end()); - for(size_t i = 0; i < arr.GetCount(); ++i) { - if(uniqueArr.Index(arr.Item(i)) == wxNOT_FOUND) { + for (size_t i = 0; i < arr.GetCount(); ++i) { + if (uniqueArr.Index(arr.Item(i)) == wxNOT_FOUND) { uniqueArr.Add(arr.Item(i)); } } diff --git a/CodeLite/PHP/PHPEntityClass.h b/CodeLite/PHP/PHPEntityClass.h index 2e06603c23..5d5b619191 100644 --- a/CodeLite/PHP/PHPEntityClass.h +++ b/CodeLite/PHP/PHPEntityClass.h @@ -26,9 +26,9 @@ #ifndef PHPENTITYCLASSIMPL_H #define PHPENTITYCLASSIMPL_H -#include "codelite_exports.h" -#include "PHPEntityBase.h" // Base class: PHPEntityBase #include "PHPDocVar.h" +#include "PHPEntityBase.h" // Base class: PHPEntityBase +#include "codelite_exports.h" class WXDLLIMPEXP_CL PHPEntityClass : public PHPEntityBase { @@ -46,10 +46,10 @@ class WXDLLIMPEXP_CL PHPEntityClass : public PHPEntityBase virtual void Store(PHPLookupTable* lookup); virtual void FromResultSet(wxSQLite3ResultSet& res); virtual void PrintStdout(int indent) const; - + void FromJSON(const JSONItem& json); JSONItem ToJSON() const; - + /** * @brief return an array of inheritance (extends, implements and traits) */ diff --git a/CodeLite/PHP/PHPEntityFunction.cpp b/CodeLite/PHP/PHPEntityFunction.cpp index f9add70140..f661e7a1e3 100644 --- a/CodeLite/PHP/PHPEntityFunction.cpp +++ b/CodeLite/PHP/PHPEntityFunction.cpp @@ -23,7 +23,7 @@ void PHPEntityFunction::PrintStdout(int indent) const wxString PHPEntityFunction::GetSignature() const { - if(!m_strSignature.IsEmpty()) { + if (!m_strSignature.IsEmpty()) { return m_strSignature; } else { @@ -36,13 +36,13 @@ wxString PHPEntityFunction::GetSignature() const break; } } - if(strSignature.EndsWith(", ")) { + if (strSignature.EndsWith(", ")) { strSignature.RemoveLast(2); } strSignature << ")"; - if(!GetReturnValue().IsEmpty()) { + if (!GetReturnValue().IsEmpty()) { strSignature << ": "; - if(HasFlag(kFunc_ReturnNullable)) { + if (HasFlag(kFunc_ReturnNullable)) { strSignature << "?"; } strSignature << GetReturnValue(); @@ -55,7 +55,7 @@ void PHPEntityFunction::Store(PHPLookupTable* lookup) { wxString fullname; fullname << GetScope() << "\\" << GetShortName(); - while(fullname.Replace("\\\\", "\\")) {} + while (fullname.Replace("\\\\", "\\")) {} try { wxSQLite3Database& db = lookup->Database(); @@ -95,7 +95,7 @@ void PHPEntityFunction::FromResultSet(wxSQLite3ResultSet& res) wxString PHPEntityFunction::GetScope() const { - if(Parent()) { + if (Parent()) { return Parent()->GetFullName(); } return ""; @@ -112,25 +112,25 @@ wxString PHPEntityFunction::FormatPhpDoc(const CommentConfigData& data) const << " * @brief \n"; for (const auto& child : m_children) { const PHPEntityVariable* var = child->Cast(); - if(var) { + if (var) { hasParams = true; doc << " * @param "; - if(var->IsNullable() || var->GetDefaultValue().Matches("null")) { + if (var->IsNullable() || var->GetDefaultValue().Matches("null")) { doc << "?"; } doc << (var->GetTypeHint().IsEmpty() ? "mixed" : var->GetTypeHint()) << " " << var->GetFullName(); - if(!var->GetDefaultValue().IsEmpty()) { + if (!var->GetDefaultValue().IsEmpty()) { doc << " [" << var->GetDefaultValue() << "]"; } doc << " \n"; } } - if(!GetShortName().Matches("__construct")) { - if(hasParams) { + if (!GetShortName().Matches("__construct")) { + if (hasParams) { doc << " *\n"; } doc << " * @return "; - if(HasFlag(kFunc_ReturnNullable)) { + if (HasFlag(kFunc_ReturnNullable)) { doc << "?"; } doc << (GetReturnValue().IsEmpty() ? "mixed" : GetReturnValue()) << " \n"; @@ -143,10 +143,10 @@ wxString PHPEntityFunction::GetFullPath() const { wxString fullpath = GetFullName(); size_t where = fullpath.rfind(GetShortName()); - if(where != wxString::npos) { - if(where > 0) { + if (where != wxString::npos) { + if (where > 0) { fullpath = fullpath.Mid(0, where - 1); - if(fullpath.IsEmpty()) { + if (fullpath.IsEmpty()) { fullpath << "\\"; } else { fullpath << "::"; @@ -177,7 +177,7 @@ wxString PHPEntityFunction::ToTooltip() const { wxString tip; tip << GetShortName() << GetSignature(); - if(!GetReturnValue().IsEmpty()) { + if (!GetReturnValue().IsEmpty()) { tip << " : " << GetReturnValue(); } return tip; diff --git a/CodeLite/PHP/PHPEntityFunction.h b/CodeLite/PHP/PHPEntityFunction.h index 199d4611cd..46ca5dd93e 100644 --- a/CodeLite/PHP/PHPEntityFunction.h +++ b/CodeLite/PHP/PHPEntityFunction.h @@ -38,10 +38,10 @@ class WXDLLIMPEXP_CL PHPEntityFunction : public PHPEntityBase virtual wxString Type() const; virtual void FromResultSet(wxSQLite3ResultSet& res); virtual void PrintStdout(int indent) const; - + void FromJSON(const JSONItem& json); JSONItem ToJSON() const; - + protected: // The local variables defined in this function of type // PHPEntityVariable @@ -64,19 +64,19 @@ class WXDLLIMPEXP_CL PHPEntityFunction : public PHPEntityBase * @brief format function signature */ wxString GetSignature() const; - + /** * @brief return the full path for this function * Example: \path\toClass::functionName($a, $b) */ wxString GetFullPath() const; - + /** * @brief write this object into the database * @param db */ virtual void Store(PHPLookupTable* lookup); - + virtual wxString ToTooltip() const; }; diff --git a/CodeLite/PHP/PHPEntityFunctionAlias.cpp b/CodeLite/PHP/PHPEntityFunctionAlias.cpp index 87b786d5c9..e34851a78c 100644 --- a/CodeLite/PHP/PHPEntityFunctionAlias.cpp +++ b/CodeLite/PHP/PHPEntityFunctionAlias.cpp @@ -41,7 +41,7 @@ void PHPEntityFunctionAlias::Store(PHPLookupTable* lookup) wxString PHPEntityFunctionAlias::FormatPhpDoc(const CommentConfigData& data) const { - if(m_func) { + if (m_func) { return m_func->FormatPhpDoc(data); } return ""; @@ -53,7 +53,7 @@ void PHPEntityFunctionAlias::PrintStdout(int indent) const { wxUnusedVar(indent) wxString PHPEntityFunctionAlias::Type() const { - if(m_func) { + if (m_func) { return m_func->Type(); } return ""; @@ -64,7 +64,7 @@ void PHPEntityFunctionAlias::FromJSON(const JSONItem& json) BaseFromJSON(json); m_realname = json.namedObject("realName").toString(); m_scope = json.namedObject("scope").toString(); - if(json.hasNamedObject("func")) { + if (json.hasNamedObject("func")) { JSONItem func = json.namedObject("func"); m_func = std::make_shared(); m_func->FromJSON(func); @@ -76,7 +76,7 @@ JSONItem PHPEntityFunctionAlias::ToJSON() const JSONItem json = BaseToJSON("a"); json.addProperty("realName", m_realname); json.addProperty("scope", m_scope); - if(m_func) { + if (m_func) { JSONItem func = m_func->ToJSON(); json.addProperty("func", func); } diff --git a/CodeLite/PHP/PHPEntityFunctionAlias.h b/CodeLite/PHP/PHPEntityFunctionAlias.h index 7dc9153db9..cd57ff6392 100644 --- a/CodeLite/PHP/PHPEntityFunctionAlias.h +++ b/CodeLite/PHP/PHPEntityFunctionAlias.h @@ -26,8 +26,8 @@ #ifndef PHPENTITYFUNCTIONALIAS_H #define PHPENTITYFUNCTIONALIAS_H -#include "codelite_exports.h" #include "PHPEntityBase.h" +#include "codelite_exports.h" class WXDLLIMPEXP_CL PHPEntityFunctionAlias : public PHPEntityBase { @@ -44,9 +44,9 @@ class WXDLLIMPEXP_CL PHPEntityFunctionAlias : public PHPEntityBase PHPEntityFunctionAlias() = default; virtual ~PHPEntityFunctionAlias() = default; - void FromJSON(const JSONItem &json); + void FromJSON(const JSONItem& json); JSONItem ToJSON() const; - + public: virtual bool Is(eEntityType type) const; virtual void Store(PHPLookupTable* lookup); diff --git a/CodeLite/PHP/PHPEntityKeyword.h b/CodeLite/PHP/PHPEntityKeyword.h index eec7fefdb5..0df0b18132 100644 --- a/CodeLite/PHP/PHPEntityKeyword.h +++ b/CodeLite/PHP/PHPEntityKeyword.h @@ -27,6 +27,7 @@ #define PHPENTITYKEYWORD_H #include "PHPEntityBase.h" + #include class WXDLLIMPEXP_CL PHPEntityKeyword : public PHPEntityBase @@ -36,7 +37,7 @@ class WXDLLIMPEXP_CL PHPEntityKeyword : public PHPEntityBase virtual ~PHPEntityKeyword() = default; void FromJSON(const JSONItem& json); JSONItem ToJSON() const; - + public: virtual wxString FormatPhpDoc(const CommentConfigData& data) const; virtual void FromResultSet(wxSQLite3ResultSet& res); diff --git a/CodeLite/PHP/PHPEntityNamespace.cpp b/CodeLite/PHP/PHPEntityNamespace.cpp index 79364e323e..ea16e67b71 100644 --- a/CodeLite/PHP/PHPEntityNamespace.cpp +++ b/CodeLite/PHP/PHPEntityNamespace.cpp @@ -28,7 +28,7 @@ void PHPEntityNamespace::Store(PHPLookupTable* lookup) db.PrepareStatement("SELECT * FROM SCOPE_TABLE WHERE FULLNAME=:FULLNAME LIMIT 1"); statement.Bind(statement.GetParamIndex(":FULLNAME"), GetFullName()); wxSQLite3ResultSet res = statement.ExecuteQuery(); - if(res.NextRow()) { + if (res.NextRow()) { // we have a match, update this item database ID to match // what we have found in the database PHPEntityNamespace ns; @@ -83,12 +83,13 @@ wxString PHPEntityNamespace::FormatPhpDoc(const CommentConfigData& data) const void PHPEntityNamespace::DoEnsureNamespacePathExists(wxSQLite3Database& db, const wxString& path) { wxArrayString paths = ::wxStringTokenize(path, "\\", wxTOKEN_STRTOK); - if(paths.IsEmpty()) return; + if (paths.IsEmpty()) + return; wxString currentPath; try { - for(size_t i = 0; i < paths.GetCount(); ++i) { - if(!currentPath.EndsWith("\\")) { + for (size_t i = 0; i < paths.GetCount(); ++i) { + if (!currentPath.EndsWith("\\")) { currentPath << "\\"; } currentPath << paths.Item(i); @@ -110,12 +111,13 @@ void PHPEntityNamespace::DoEnsureNamespacePathExists(wxSQLite3Database& db, cons wxString PHPEntityNamespace::GetParentNamespace() const { - if(GetFullName() == "\\") { + if (GetFullName() == "\\") { // this is the global namespace return "\\"; } wxString parentPath = GetFullName().BeforeLast('\\'); - if(parentPath.IsEmpty()) return "\\"; + if (parentPath.IsEmpty()) + return "\\"; return parentPath; } @@ -123,15 +125,11 @@ wxString PHPEntityNamespace::BuildNamespace(const wxString& part1, const wxStrin { wxString ns; ns << part1 << "\\" << part2; - while(ns.Replace("\\\\", "\\")) { - } + while (ns.Replace("\\\\", "\\")) {} return ns; } -void PHPEntityNamespace::FromJSON(const JSONItem& json) -{ - BaseFromJSON(json); -} +void PHPEntityNamespace::FromJSON(const JSONItem& json) { BaseFromJSON(json); } JSONItem PHPEntityNamespace::ToJSON() const { diff --git a/CodeLite/PHP/PHPEntityNamespace.h b/CodeLite/PHP/PHPEntityNamespace.h index 695c583d84..d4e07491d9 100644 --- a/CodeLite/PHP/PHPEntityNamespace.h +++ b/CodeLite/PHP/PHPEntityNamespace.h @@ -26,8 +26,9 @@ #ifndef PHPENTITYNAMESPACE_H #define PHPENTITYNAMESPACE_H -#include "codelite_exports.h" #include "PHPEntityBase.h" // Base class: PHPEntityBase +#include "codelite_exports.h" + #include class WXDLLIMPEXP_CL PHPEntityNamespace : public PHPEntityBase @@ -38,7 +39,7 @@ class WXDLLIMPEXP_CL PHPEntityNamespace : public PHPEntityBase public: void FromJSON(const JSONItem& json); JSONItem ToJSON() const; - + wxString GetParentNamespace() const; virtual wxString FormatPhpDoc(const CommentConfigData& data) const; virtual wxString GetDisplayName() const; @@ -49,11 +50,11 @@ class WXDLLIMPEXP_CL PHPEntityNamespace : public PHPEntityBase virtual void PrintStdout(int indent) const; PHPEntityNamespace() = default; virtual ~PHPEntityNamespace() = default; - + /** * @brief build namespace from 2 strings */ - static wxString BuildNamespace(const wxString &part1, const wxString &part2); + static wxString BuildNamespace(const wxString& part1, const wxString& part2); }; #endif // PHPENTITYNAMESPACE_H diff --git a/CodeLite/PHP/PHPEntityVariable.cpp b/CodeLite/PHP/PHPEntityVariable.cpp index 8699db3937..d94771d8e2 100644 --- a/CodeLite/PHP/PHPEntityVariable.cpp +++ b/CodeLite/PHP/PHPEntityVariable.cpp @@ -10,16 +10,16 @@ void PHPEntityVariable::PrintStdout(int indent) const { wxString indentString(' ', indent); wxPrintf("%s%s: %s", indentString, IsMember() ? "Member" : "Variable", GetShortName()); - if(!GetTypeHint().IsEmpty()) { + if (!GetTypeHint().IsEmpty()) { wxPrintf(", TypeHint: %s", GetTypeHint()); } - if(!GetExpressionHint().IsEmpty()) { + if (!GetExpressionHint().IsEmpty()) { wxPrintf(", ExpressionHint: %s", GetExpressionHint()); } - if(IsReference()) { + if (IsReference()) { wxPrintf(", Reference"); } - if(!GetDefaultValue().IsEmpty()) { + if (!GetDefaultValue().IsEmpty()) { wxPrintf(", Default: %s", GetDefaultValue()); } @@ -33,7 +33,7 @@ void PHPEntityVariable::PrintStdout(int indent) const void PHPEntityVariable::SetVisibility(int visibility) { - switch(visibility) { + switch (visibility) { case kPHP_T_PUBLIC: m_flags &= ~kVar_Private; m_flags &= ~kVar_Protected; @@ -56,45 +56,45 @@ void PHPEntityVariable::SetVisibility(int visibility) wxString PHPEntityVariable::ToFuncArgString() const { - if(!IsFunctionArg()) { + if (!IsFunctionArg()) { return ""; } wxString str; - if(!GetTypeHint().IsEmpty()) { - if(IsNullable()) { + if (!GetTypeHint().IsEmpty()) { + if (IsNullable()) { str << "?"; } str << GetTypeHint() << " "; } - if(IsReference()) { + if (IsReference()) { str << "&"; } str << GetShortName(); - if(!GetDefaultValue().IsEmpty()) { + if (!GetDefaultValue().IsEmpty()) { str << " = " << GetDefaultValue(); } return str; } void PHPEntityVariable::Store(PHPLookupTable* lookup) { - if(IsFunctionArg() || IsMember() || IsDefine()) { + if (IsFunctionArg() || IsMember() || IsDefine()) { try { wxSQLite3Database& db = lookup->Database(); - wxSQLite3Statement statement = db.PrepareStatement( - "INSERT OR REPLACE INTO VARIABLES_TABLE VALUES (NULL, " - ":SCOPE_ID, :FUNCTION_ID, :NAME, :FULLNAME, :SCOPE, :TYPEHINT, :DEFAULT_VALUE, " - ":FLAGS, :DOC_COMMENT, :LINE_NUMBER, :FILE_NAME)"); + wxSQLite3Statement statement = + db.PrepareStatement("INSERT OR REPLACE INTO VARIABLES_TABLE VALUES (NULL, " + ":SCOPE_ID, :FUNCTION_ID, :NAME, :FULLNAME, :SCOPE, :TYPEHINT, :DEFAULT_VALUE, " + ":FLAGS, :DOC_COMMENT, :LINE_NUMBER, :FILE_NAME)"); wxLongLong functionId, scopeId; - if(IsFunctionArg()) { + if (IsFunctionArg()) { functionId = Parent()->GetDbId(); } else { functionId = -1; } - if(IsMember() || IsDefine()) { + if (IsMember() || IsDefine()) { scopeId = Parent()->GetDbId(); } else { scopeId = -1; @@ -135,13 +135,13 @@ void PHPEntityVariable::FromResultSet(wxSQLite3ResultSet& res) wxString PHPEntityVariable::GetScope() const { PHPEntityBase* parent = Parent(); - if(parent && parent->Is(kEntityTypeFunction) && IsFunctionArg()) { + if (parent && parent->Is(kEntityTypeFunction) && IsFunctionArg()) { return parent->Cast()->GetScope(); - } else if(parent && parent->Is(kEntityTypeClass) && IsMember()) { + } else if (parent && parent->Is(kEntityTypeClass) && IsMember()) { return parent->GetFullName(); - } else if(parent && parent->Is(kEntityTypeNamespace) && IsDefine()) { + } else if (parent && parent->Is(kEntityTypeNamespace) && IsDefine()) { return parent->GetFullName(); } else { @@ -156,7 +156,7 @@ wxString PHPEntityVariable::GetDisplayName() const { return GetFullName(); } wxString PHPEntityVariable::GetNameNoDollar() const { wxString name = GetShortName(); - if(name.StartsWith("$")) { + if (name.StartsWith("$")) { name.Remove(0, 1); } name.Trim().Trim(false); @@ -173,7 +173,7 @@ wxString PHPEntityVariable::FormatPhpDoc(const CommentConfigData& data) const wxString PHPEntityVariable::ToTooltip() const { - if(IsConst() && !GetDefaultValue().IsEmpty()) { + if (IsConst() && !GetDefaultValue().IsEmpty()) { return GetDefaultValue(); } else { return wxEmptyString; diff --git a/CodeLite/PHP/PHPEntityVariable.h b/CodeLite/PHP/PHPEntityVariable.h index 167eb95648..eb757b6397 100644 --- a/CodeLite/PHP/PHPEntityVariable.h +++ b/CodeLite/PHP/PHPEntityVariable.h @@ -26,8 +26,9 @@ #ifndef PHPENTITYVARIABLE_H #define PHPENTITYVARIABLE_H -#include "codelite_exports.h" #include "PHPEntityBase.h" // Base class: PHPEntityBase +#include "codelite_exports.h" + #include class WXDLLIMPEXP_CL PHPEntityVariable : public PHPEntityBase @@ -55,10 +56,10 @@ class WXDLLIMPEXP_CL PHPEntityVariable : public PHPEntityBase wxString GetScope() const; virtual void Store(PHPLookupTable* lookup); virtual void PrintStdout(int indent) const; - + void FromJSON(const JSONItem& json); JSONItem ToJSON() const; - + /** * @brief format this variable */ @@ -75,7 +76,7 @@ class WXDLLIMPEXP_CL PHPEntityVariable : public PHPEntityBase const wxString& GetDefaultValue() const { return m_defaultValue; } wxString GetNameNoDollar() const; virtual wxString ToTooltip() const; - + // Aliases void SetIsReference(bool isReference) { SetFlag(kVar_Reference, isReference); } void SetIsNullable(bool isNullable) { SetFlag(kVar_Nullable, isNullable); } diff --git a/CodeLite/PHP/PHPEntityVisitor.h b/CodeLite/PHP/PHPEntityVisitor.h index d749bd671e..177c0f6e07 100644 --- a/CodeLite/PHP/PHPEntityVisitor.h +++ b/CodeLite/PHP/PHPEntityVisitor.h @@ -26,8 +26,8 @@ #ifndef PHPENTITYVISITOR_H #define PHPENTITYVISITOR_H -#include "codelite_exports.h" #include "PHPEntityBase.h" +#include "codelite_exports.h" /** * @class PHPEntityVisitor @@ -40,7 +40,7 @@ class WXDLLIMPEXP_CL PHPEntityVisitor virtual ~PHPEntityVisitor() = default; void Visit(PHPEntityBase::Ptr_t parent); - + /** * @brief called whenever an entity is visited * @param entity diff --git a/CodeLite/PHP/PHPExpression.cpp b/CodeLite/PHP/PHPExpression.cpp index 7d2e471d46..f0f1f4a501 100644 --- a/CodeLite/PHP/PHPExpression.cpp +++ b/CodeLite/PHP/PHPExpression.cpp @@ -15,13 +15,13 @@ PHPExpression::PHPExpression(const wxString& fulltext, const wxString& exprText, , m_text(fulltext) , m_functionCalltipExpr(functionCalltipExpr) { - if(exprText.IsEmpty()) { + if (exprText.IsEmpty()) { // use the full text to extract the expression m_expression = CreateExpression(fulltext); } else { wxString phpExprText = exprText; - if(!exprText.StartsWith("push_back(token); + if (current) + current->push_back(token); break; // the following are tokens that once seen // we should start a new expression: @@ -128,27 +129,31 @@ phpLexerToken::Vet_t PHPExpression::CreateExpression(const wxString& text) case '@': case '<': case '*': - if(current) current->clear(); + if (current) + current->clear(); break; case '(': case '[': - if(current) current->push_back(token); + if (current) + current->push_back(token); stack.push(phpLexerToken::Vet_t()); current = &stack.top(); break; case ')': case ']': - if(stack.size() < 2) { + if (stack.size() < 2) { // parse error... return phpLexerToken::Vet_t(); } // switch back to the previous set of tokens stack.pop(); current = &stack.top(); - if(current) current->push_back(token); + if (current) + current->push_back(token); break; default: - if(current) current->push_back(token); + if (current) + current->push_back(token); break; } } @@ -156,19 +161,19 @@ phpLexerToken::Vet_t PHPExpression::CreateExpression(const wxString& text) ::phpLexerDestroy(&scanner); phpLexerToken::Vet_t result; - if(m_functionCalltipExpr) { + if (m_functionCalltipExpr) { // the expression parser was constructed for the purpose of // function-calltip so replace the current expression with the previous one from the stack // i.e. the one before the first open brace - if(stack.size() > 1) { + if (stack.size() > 1) { stack.pop(); // remove the last token sequence current = &stack.top(); } } - if(current && !current->empty()) { - if(current->at(0).type == kPHP_T_OPEN_TAG) { - if(current->at(0).Text() == "empty()) { + if (current->at(0).type == kPHP_T_OPEN_TAG) { + if (current->at(0).Text() == "erase(current->begin()); @@ -180,14 +185,15 @@ phpLexerToken::Vet_t PHPExpression::CreateExpression(const wxString& text) PHPEntityBase::Ptr_t PHPExpression::Resolve(PHPLookupTable& lookpTable, const wxString& sourceFileName) { - if(m_expression.empty()) return PHPEntityBase::Ptr_t(NULL); + if (m_expression.empty()) + return PHPEntityBase::Ptr_t(NULL); m_sourceFile.reset(new PHPSourceFile(m_text, &lookpTable)); m_sourceFile->SetParseFunctionBody(true); m_sourceFile->SetFilename(sourceFileName); m_sourceFile->Parse(); - if(m_expression.size() == 1 && m_expression.at(0).type == kPHP_T_NS_SEPARATOR) { + if (m_expression.size() == 1 && m_expression.at(0).type == kPHP_T_NS_SEPARATOR) { // user typed '\' return lookpTable.FindScope("\\"); } @@ -195,16 +201,16 @@ PHPEntityBase::Ptr_t PHPExpression::Resolve(PHPLookupTable& lookpTable, const wx wxString asString = DoSimplifyExpression(0, m_sourceFile); wxUnusedVar(asString); - if(m_parts.empty() && !m_filter.IsEmpty()) { + if (m_parts.empty() && !m_filter.IsEmpty()) { // We have no expression, but the user did type something... // Return the parent scope of what the user typed so far - if(m_filter.Contains("\\")) { + if (m_filter.Contains("\\")) { // A namespace separator was found in the filter, break // the filter into 2: // scope + filter wxString scopePart = m_filter.BeforeLast('\\'); - if(!scopePart.StartsWith("\\")) { + if (!scopePart.StartsWith("\\")) { scopePart.Prepend("\\"); } @@ -233,22 +239,22 @@ PHPEntityBase::Ptr_t PHPExpression::Resolve(PHPLookupTable& lookpTable, const wx if (!currentToken) { // first token // Check locks first - if(part.m_text.StartsWith("$") && m_sourceFile->CurrentScope()) { + if (part.m_text.StartsWith("$") && m_sourceFile->CurrentScope()) { // a variable currentToken = m_sourceFile->CurrentScope()->FindChild(part.m_text); } - if(!currentToken) { + if (!currentToken) { currentToken = lookpTable.FindScope(part.m_text); - if(!currentToken) { + if (!currentToken) { // If we are inside a namespace, try prepending the namespace // to the first token - if(m_sourceFile->Namespace() && m_sourceFile->Namespace()->GetFullName() != "\\") { + if (m_sourceFile->Namespace() && m_sourceFile->Namespace()->GetFullName() != "\\") { // Not the global namespace wxString fullns = PHPEntityNamespace::BuildNamespace(m_sourceFile->Namespace()->GetFullName(), part.m_text); // Check if it exists PHPEntityBase::Ptr_t pGuess = lookpTable.FindScope(fullns); - if(pGuess) { + if (pGuess) { currentToken = pGuess; part.m_text = fullns; } else { @@ -265,7 +271,7 @@ PHPEntityBase::Ptr_t PHPExpression::Resolve(PHPLookupTable& lookpTable, const wx } else { // load the children of the current token (optionally, filter by the text) currentToken = lookpTable.FindMemberOf(currentToken->GetDbId(), part.m_text); - if(currentToken && currentToken->Is(kEntityTypeFunctionAlias)) { + if (currentToken && currentToken->Is(kEntityTypeFunctionAlias)) { // If the member is a function-alias, use the actual function instead currentToken = currentToken->Cast()->GetFunc(); } @@ -275,35 +281,35 @@ PHPEntityBase::Ptr_t PHPExpression::Resolve(PHPLookupTable& lookpTable, const wx // an object operator ("->") we need to resolve the operator to the actual type ( // incase of a function it will be the return value, and in case of a variable it will be // the type hint) - if(currentToken) { - if(part.m_operator == kPHP_T_OBJECT_OPERATOR || part.m_operator == kPHP_T_PAAMAYIM_NEKUDOTAYIM) { + if (currentToken) { + if (part.m_operator == kPHP_T_OBJECT_OPERATOR || part.m_operator == kPHP_T_PAAMAYIM_NEKUDOTAYIM) { wxString actualType; - if(currentToken->Is(kEntityTypeFunction)) { + if (currentToken->Is(kEntityTypeFunction)) { // return the function return value actualType = currentToken->Cast()->GetReturnValue(); - - if((actualType == "self" || actualType == "\\self") && parentToken) { + + if ((actualType == "self" || actualType == "\\self") && parentToken) { // Resolve self to the actual class name actualType = parentToken->GetFullName(); } - - } else if(currentToken->Is(kEntityTypeVariable)) { + + } else if (currentToken->Is(kEntityTypeVariable)) { // return the type hint actualType = currentToken->Cast()->GetTypeHint(); } wxString fixedpath; - if(!actualType.IsEmpty() && FixReturnValueNamespace(lookpTable, parentToken, actualType, fixedpath)) { + if (!actualType.IsEmpty() && FixReturnValueNamespace(lookpTable, parentToken, actualType, fixedpath)) { actualType.swap(fixedpath); } - if(!actualType.IsEmpty()) { + if (!actualType.IsEmpty()) { currentToken = lookpTable.FindScope(actualType); } } } - if(!currentToken) { + if (!currentToken) { // return NULL return currentToken; } @@ -314,13 +320,13 @@ PHPEntityBase::Ptr_t PHPExpression::Resolve(PHPLookupTable& lookpTable, const wx wxString PHPExpression::DoSimplifyExpression(int depth, PHPSourceFile::Ptr_t sourceFile) { - if(depth > 5 || sourceFile == NULL) { + if (depth > 5 || sourceFile == NULL) { // avoid infinite recursion, by limiting the nest level to 5 return ""; } // Use the provided sourceFile if 'm_sourceFile' is NULL - if(!m_sourceFile) { + if (!m_sourceFile) { m_sourceFile = sourceFile; } @@ -337,35 +343,39 @@ wxString PHPExpression::DoSimplifyExpression(int depth, PHPSourceFile::Ptr_t sou wxString newExpr; wxString firstToken; int firstTokenType = wxNOT_FOUND; - for(size_t i = 0; i < m_expression.size(); ++i) { + for (size_t i = 0; i < m_expression.size(); ++i) { phpLexerToken token = m_expression.at(i); - if(i == 0) { + if (i == 0) { // Perform basic replacements that we can conduct here without the need of the global // lookup table - if(token.type == kPHP_T_PARENT) { - if(!innerClass) return ""; + if (token.type == kPHP_T_PARENT) { + if (!innerClass) + return ""; firstToken = innerClass->GetFullName(); firstTokenType = kPHP_T_PARENT; - } else if(token.type == kPHP_T_THIS) { + } else if (token.type == kPHP_T_THIS) { // the first token is $this // replace it with the current class absolute path - if(!innerClass) return ""; + if (!innerClass) + return ""; firstToken = innerClass->GetFullName(); // Is always in absolute path - } else if(token.type == kPHP_T_SELF) { + } else if (token.type == kPHP_T_SELF) { // Same as $this: replace it with the current class absolute path - if(!innerClass) return ""; + if (!innerClass) + return ""; firstToken = innerClass->GetFullName(); // Is always in absolute path firstTokenType = kPHP_T_SELF; - } else if(token.type == kPHP_T_STATIC) { + } else if (token.type == kPHP_T_STATIC) { // Same as $this: replace it with the current class absolute path - if(!innerClass) return ""; + if (!innerClass) + return ""; firstToken = innerClass->GetFullName(); // Is always in absolute path firstTokenType = kPHP_T_STATIC; - } else if(token.type == kPHP_T_VARIABLE) { + } else if (token.type == kPHP_T_VARIABLE) { // the expression being evaluated starts with a variable (e.g. $a->something()->) // in this case, use the current scope ('scope') and replace it with the real type // Note that the type can be another expression @@ -379,18 +389,18 @@ wxString PHPExpression::DoSimplifyExpression(int depth, PHPSourceFile::Ptr_t sou // \MyClass->getQuery->fetchAll-> and this is something that we can evaluate easily using // our lookup tables (note that the parenthesis are missing on purpose) PHPEntityBase::Ptr_t local = scope->FindChild(token.Text()); - if(local && local->Cast()) { - if(!local->Cast()->GetTypeHint().IsEmpty()) { + if (local && local->Cast()) { + if (!local->Cast()->GetTypeHint().IsEmpty()) { // we have type hint! - use it firstToken = local->Cast()->GetTypeHint(); - } else if(!local->Cast()->GetExpressionHint().IsEmpty()) { + } else if (!local->Cast()->GetExpressionHint().IsEmpty()) { // we have an expression hint - use it // append the "->" to the expression to make sure that the parser will understand it // as an expression PHPExpression e(m_text, local->Cast()->GetExpressionHint() + "->"); firstToken = e.DoSimplifyExpression(depth + 1, m_sourceFile); - if(firstToken.EndsWith("->")) { + if (firstToken.EndsWith("->")) { // remove the last 2 characters firstToken.RemoveLast(2); } @@ -402,13 +412,13 @@ wxString PHPExpression::DoSimplifyExpression(int depth, PHPSourceFile::Ptr_t sou return ""; } - } else if(token.type == kPHP_T_IDENTIFIER) { + } else if (token.type == kPHP_T_IDENTIFIER) { // an identifier, convert it to the fullpath firstToken = sourceFile->MakeIdentifierAbsolute(token.Text()); } } - if(!firstToken.IsEmpty()) { + if (!firstToken.IsEmpty()) { newExpr = firstToken; firstToken.Clear(); } else { @@ -427,11 +437,11 @@ wxString PHPExpression::DoSimplifyExpression(int depth, PHPSourceFile::Ptr_t sou wxString currentText; for (const auto& token : m_expression) { // Remove any braces and split by object kPHP_T_OBJECT_OPERATOR and kPHP_T_PAAMAYIM_NEKUDOTAYIM - switch(token.type) { + switch (token.type) { case kPHP_T_OPEN_TAG: break; case '(': - if(!currentText.IsEmpty()) { + if (!currentText.IsEmpty()) { part.m_text = currentText; } break; @@ -440,8 +450,8 @@ wxString PHPExpression::DoSimplifyExpression(int depth, PHPSourceFile::Ptr_t sou break; case kPHP_T_PAAMAYIM_NEKUDOTAYIM: case kPHP_T_OBJECT_OPERATOR: - if(!currentText.IsEmpty() && part.m_text.IsEmpty()) { - if(m_parts.empty() && token.type == kPHP_T_PAAMAYIM_NEKUDOTAYIM) { + if (!currentText.IsEmpty() && part.m_text.IsEmpty()) { + if (m_parts.empty() && token.type == kPHP_T_PAAMAYIM_NEKUDOTAYIM) { // The first token in the "parts" list has a scope resolving operator ("::") // we need to make sure that the identifier is provided in fullpath part.m_text = sourceFile->MakeIdentifierAbsolute(currentText); @@ -450,7 +460,7 @@ wxString PHPExpression::DoSimplifyExpression(int depth, PHPSourceFile::Ptr_t sou } } - if(m_parts.empty()) { + if (m_parts.empty()) { // If the first token before the simplification was 'parent' // keyword, we need to carry this over part.m_textType = firstTokenType; @@ -478,7 +488,7 @@ wxString PHPExpression::DoSimplifyExpression(int depth, PHPSourceFile::Ptr_t sou } } - if(!currentText.IsEmpty()) { + if (!currentText.IsEmpty()) { m_filter = currentText; } @@ -501,17 +511,18 @@ wxString PHPExpression::GetExpressionAsString() const size_t PHPExpression::GetLookupFlags() const { size_t flags(0); - if(m_parts.empty()) return flags; + if (m_parts.empty()) + return flags; - if(m_parts.size() == 1 && m_parts.back().m_textType == kPHP_T_PARENT) { + if (m_parts.size() == 1 && m_parts.back().m_textType == kPHP_T_PARENT) { Part firstPart = m_parts.back(); - if(firstPart.m_textType == kPHP_T_PARENT) { + if (firstPart.m_textType == kPHP_T_PARENT) { flags |= PHPLookupTable::kLookupFlags_Parent; } } else { Part lastExpressionPart = m_parts.back(); - if(lastExpressionPart.m_operator == kPHP_T_PAAMAYIM_NEKUDOTAYIM) { - if(lastExpressionPart.m_textType == kPHP_T_SELF) + if (lastExpressionPart.m_operator == kPHP_T_PAAMAYIM_NEKUDOTAYIM) { + if (lastExpressionPart.m_textType == kPHP_T_SELF) flags |= PHPLookupTable::kLookupFlags_Self; else flags |= PHPLookupTable::kLookupFlags_Static; @@ -523,7 +534,8 @@ size_t PHPExpression::GetLookupFlags() const void PHPExpression::Suggest(PHPEntityBase::Ptr_t resolved, PHPLookupTable& lookup, PHPEntityBase::List_t& matches) { // sanity - if(!resolved) return; + if (!resolved) + return; PHPEntityBase::Ptr_t currentScope = GetSourceFile()->CurrentScope(); // GetCount() == 0 && !GetFilter().IsEmpty() i.e. a word completion is required. @@ -534,7 +546,7 @@ void PHPExpression::Suggest(PHPEntityBase::Ptr_t resolved, PHPLookupTable& looku // - Function arguments // - Local variables (of the current scope) // - And aliases e.g. 'use foo\bar as Bar;' - if(GetCount() == 0 && !GetFilter().IsEmpty()) { + if (GetCount() == 0 && !GetFilter().IsEmpty()) { // For functions and constants, PHP will fall back to global functions or constants if a // namespaced function or constant does not exist. @@ -542,12 +554,12 @@ void PHPExpression::Suggest(PHPEntityBase::Ptr_t resolved, PHPLookupTable& looku lookup.FindGlobalFunctionAndConsts(PHPLookupTable::kLookupFlags_Contains, GetFilter()); matches.insert(matches.end(), globals.begin(), globals.end()); - if(currentScope && (currentScope->Is(kEntityTypeFunction) || currentScope->Is(kEntityTypeNamespace))) { + if (currentScope && (currentScope->Is(kEntityTypeFunction) || currentScope->Is(kEntityTypeNamespace))) { // If the current scope is a function // add the local variables + function arguments to the current list of matches for (const auto& child : currentScope->GetChildren()) { if (child->Is(kEntityTypeVariable) && child->GetShortName().Contains(GetFilter()) && - child->GetShortName() != GetFilter()) { + child->GetShortName() != GetFilter()) { matches.push_back(child); } } @@ -565,7 +577,7 @@ void PHPExpression::Suggest(PHPEntityBase::Ptr_t resolved, PHPLookupTable& looku { // Add $this incase we are inside a class (but only if '$this' contains the filter string) wxString lcFilter = GetFilter().Lower(); - if(GetSourceFile()->Class() && wxString("$this").Contains(lcFilter)) { + if (GetSourceFile()->Class() && wxString("$this").Contains(lcFilter)) { PHPEntityBase::Ptr_t thiz(new PHPEntityVariable()); thiz->SetFullName("$this"); thiz->SetShortName("$this"); @@ -578,17 +590,17 @@ void PHPExpression::Suggest(PHPEntityBase::Ptr_t resolved, PHPLookupTable& looku // Add the scoped matches // for the code completion size_t flags = PHPLookupTable::kLookupFlags_Contains | GetLookupFlags(); - if(resolved->Is(kEntityTypeClass)) { - if(resolved->Cast()->IsInterface() || resolved->Cast()->IsAbstractClass()) { + if (resolved->Is(kEntityTypeClass)) { + if (resolved->Cast()->IsInterface() || resolved->Cast()->IsAbstractClass()) { flags |= PHPLookupTable::kLookupFlags_IncludeAbstractMethods; } } - + PHPEntityBase::List_t scopeChildren = lookup.FindChildren(resolved->GetDbId(), flags, GetFilter()); matches.insert(matches.end(), scopeChildren.begin(), scopeChildren.end()); // Incase the resolved is a namespace, suggest all children namespaces - if(resolved->Is(kEntityTypeNamespace)) { + if (resolved->Is(kEntityTypeNamespace)) { PHPEntityBase::List_t namespaces = lookup.FindNamespaces(resolved->GetFullName(), GetFilter()); matches.insert(matches.end(), namespaces.begin(), namespaces.end()); } @@ -615,9 +627,10 @@ bool PHPExpression::FixReturnValueNamespace(PHPLookupTable& lookup, const wxString& classFullpath, wxString& fixedpath) { - if(!parent) return false; + if (!parent) + return false; PHPEntityBase::Ptr_t pClass = lookup.FindClass(classFullpath); - if(!pClass) { + if (!pClass) { // classFullpath does not exist // prepend the parent namespace to its path and check again wxString parentNamespace = parent->GetFullName().BeforeLast('\\'); @@ -626,7 +639,7 @@ bool PHPExpression::FixReturnValueNamespace(PHPLookupTable& lookup, wxString newType = PHPEntityNamespace::BuildNamespace(parentNamespace, returnValueNamespace); newType << "\\" << returnValueName; pClass = lookup.FindClass(newType); - if(pClass) { + if (pClass) { fixedpath = newType; return true; } diff --git a/CodeLite/PHP/PHPExpression.h b/CodeLite/PHP/PHPExpression.h index d7921c122d..cf6925b7ea 100644 --- a/CodeLite/PHP/PHPExpression.h +++ b/CodeLite/PHP/PHPExpression.h @@ -82,8 +82,10 @@ class WXDLLIMPEXP_CL PHPExpression /** * @brief fix the return value full path */ - bool FixReturnValueNamespace( - PHPLookupTable& lookup, PHPEntityBase::Ptr_t parent, const wxString& classFullpath, wxString& fixedpath); + bool FixReturnValueNamespace(PHPLookupTable& lookup, + PHPEntityBase::Ptr_t parent, + const wxString& classFullpath, + wxString& fixedpath); public: PHPExpression(const wxString& fulltext, const wxString& exprText = wxString(), bool functionCalltipExpr = false); @@ -102,12 +104,12 @@ class WXDLLIMPEXP_CL PHPExpression * @param matches [output] */ void Suggest(PHPEntityBase::Ptr_t resolved, PHPLookupTable& lookup, PHPEntityBase::List_t& matches); - + /** * @brief return true of the token before the expression is "Cast()) { + if (scope && scope->Cast()) { std::vector parents; std::set parentsVisited; @@ -178,7 +178,7 @@ PHPEntityBase::Ptr_t PHPLookupTable::FindMemberOf(wxLongLong parentDbId, const w // Parents should now contain an ordered list of all the inheritance for (const auto& parentId : parents) { PHPEntityBase::Ptr_t match = DoFindMemberOf(parentId, exactName); - if(match) { + if (match) { PHPEntityBase::List_t matches; matches.push_back(match); DoFixVarsDocComment(matches, parentDbId); @@ -196,7 +196,7 @@ PHPEntityBase::Ptr_t PHPLookupTable::FindScope(const wxString& fullname) { wxString scopeName = fullname; scopeName.Trim().Trim(false); - if(scopeName.EndsWith("\\") && scopeName.length() > 1) { + if (scopeName.EndsWith("\\") && scopeName.length() > 1) { scopeName.RemoveLast(); } return DoFindScope(scopeName); @@ -206,7 +206,7 @@ void PHPLookupTable::Open(const wxFileName& dbfile) { try { - if(dbfile.Exists()) { + if (dbfile.Exists()) { // Check for its integrity. If the database is corrupted, // it will be deleted EnsureIntegrity(dbfile); @@ -251,14 +251,14 @@ void PHPLookupTable::CreateSchema() m_db.PrepareStatement("select SCHEMA_VERSION from METADATA_TABLE where SCHEMA_NAME=:SCHEMA_NAME"); st.Bind(st.GetParamIndex(":SCHEMA_NAME"), "CODELITEPHP"); wxSQLite3ResultSet res = st.ExecuteQuery(); - if(res.NextRow()) { + if (res.NextRow()) { schemaVersion = res.GetString("SCHEMA_VERSION"); } } catch (const wxSQLite3Exception& e) { wxUnusedVar(e); } - if(schemaVersion != PHP_SCHEMA_VERSION) { + if (schemaVersion != PHP_SCHEMA_VERSION) { // Drop the tables and recreate the schema from scratch m_db.ExecuteUpdate("drop table if exists SCHEMA_VERSION"); m_db.ExecuteUpdate("drop table if exists SCOPE_TABLE"); @@ -330,7 +330,7 @@ void PHPLookupTable::CreateSchema() void PHPLookupTable::UpdateSourceFile(PHPSourceFile& source, bool autoCommit) { try { - if(autoCommit) + if (autoCommit) m_db.Begin(); // Delete all entries for this file @@ -338,7 +338,7 @@ void PHPLookupTable::UpdateSourceFile(PHPSourceFile& source, bool autoCommit) // Store new entries PHPEntityBase::Ptr_t topNamespace = source.Namespace(); - if(topNamespace) { + if (topNamespace) { topNamespace->StoreRecursive(this); UpdateFileLastParsedTimestamp(source.GetFilename()); } @@ -357,7 +357,7 @@ void PHPLookupTable::UpdateSourceFile(PHPSourceFile& source, bool autoCommit) // For this reason, we need get the list of defined parsed in the source file and associate them // with their namespace (we either load the namespace from the database or create one) - if(!source.GetDefines().empty()) { + if (!source.GetDefines().empty()) { PHPEntityBase::Map_t nsMap; for (const auto& pDefine : source.GetDefines()) { PHPEntityBase::Ptr_t pNamespace(NULL); @@ -366,7 +366,7 @@ void PHPLookupTable::UpdateSourceFile(PHPSourceFile& source, bool autoCommit) DoSplitFullname(pDefine->GetFullName(), nameSpaceName, shortName); PHPEntityBase::Map_t::iterator nsIter = nsMap.find(nameSpaceName); - if(nsIter == nsMap.end()) { + if (nsIter == nsMap.end()) { // we did not load this namespace yet => load and cache it pNamespace = CreateNamespaceForDefine(pDefine); nsMap.insert(std::make_pair(pNamespace->GetFullName(), pNamespace)); @@ -384,18 +384,18 @@ void PHPLookupTable::UpdateSourceFile(PHPSourceFile& source, bool autoCommit) } } - if(autoCommit) + if (autoCommit) m_db.Commit(); } catch (const wxSQLite3Exception& e) { - if(autoCommit) + if (autoCommit) m_db.Rollback(); clWARNING() << "PHPLookupTable::SaveSourceFile" << e.GetMessage() << endl; } } -PHPEntityBase::Ptr_t PHPLookupTable::DoFindMemberOf(wxLongLong parentDbId, const wxString& exactName, - bool parentIsNamespace) +PHPEntityBase::Ptr_t +PHPLookupTable::DoFindMemberOf(wxLongLong parentDbId, const wxString& exactName, bool parentIsNamespace) { // Find members of of parentDbID try { @@ -406,14 +406,14 @@ PHPEntityBase::Ptr_t PHPLookupTable::DoFindMemberOf(wxLongLong parentDbId, const wxSQLite3Statement st = m_db.PrepareStatement(sql); wxSQLite3ResultSet res = st.ExecuteQuery(); - while(res.NextRow()) { + while (res.NextRow()) { PHPEntityBase::Ptr_t match(new PHPEntityFunction()); match->FromResultSet(res); matches.push_back(match); } } - if(matches.empty()) { + if (matches.empty()) { // Search functions alias table wxString sql; sql << "SELECT * from FUNCTION_ALIAS_TABLE WHERE SCOPE_ID=" << parentDbId << " AND NAME='" << exactName @@ -421,43 +421,43 @@ PHPEntityBase::Ptr_t PHPLookupTable::DoFindMemberOf(wxLongLong parentDbId, const wxSQLite3Statement st = m_db.PrepareStatement(sql); wxSQLite3ResultSet res = st.ExecuteQuery(); - while(res.NextRow()) { + while (res.NextRow()) { PHPEntityBase::Ptr_t match(new PHPEntityFunctionAlias()); match->FromResultSet(res); PHPEntityBase::Ptr_t pFunc = FindFunction(match->Cast()->GetRealname()); - if(pFunc) { + if (pFunc) { match->Cast()->SetFunc(pFunc); matches.push_back(match); } } } - if(matches.empty() && parentIsNamespace) { + if (matches.empty() && parentIsNamespace) { // search the scope table as well wxString sql; sql << "SELECT * from SCOPE_TABLE WHERE SCOPE_ID=" << parentDbId << " AND NAME='" << exactName << "'"; wxSQLite3Statement st = m_db.PrepareStatement(sql); wxSQLite3ResultSet res = st.ExecuteQuery(); - while(res.NextRow()) { + while (res.NextRow()) { ePhpScopeType st = kPhpScopeTypeAny; st = res.GetInt("SCOPE_TYPE", 1) == kPhpScopeTypeNamespace ? kPhpScopeTypeNamespace : kPhpScopeTypeClass; PHPEntityBase::Ptr_t match = NewEntity("SCOPE_TABLE", st); - if(match) { + if (match) { match->FromResultSet(res); matches.push_back(match); } } } - if(matches.empty()) { + if (matches.empty()) { // Could not find a match in the function table, check the variable table wxString sql; wxString nameWDollar, namwWODollar; nameWDollar = exactName; - if(exactName.StartsWith("$")) { + if (exactName.StartsWith("$")) { namwWODollar = exactName.Mid(1); } else { namwWODollar = exactName; @@ -469,7 +469,7 @@ PHPEntityBase::Ptr_t PHPLookupTable::DoFindMemberOf(wxLongLong parentDbId, const wxSQLite3Statement st = m_db.PrepareStatement(sql); wxSQLite3ResultSet res = st.ExecuteQuery(); - while(res.NextRow()) { + while (res.NextRow()) { PHPEntityBase::Ptr_t match(new PHPEntityVariable()); match->FromResultSet(res); matches.push_back(match); @@ -478,12 +478,12 @@ PHPEntityBase::Ptr_t PHPLookupTable::DoFindMemberOf(wxLongLong parentDbId, const // Fix variables type using the PHPDOC_VAR_TABLE content for this class DoFixVarsDocComment(matches, parentDbId); - if(matches.empty() || matches.size() > 1) { + if (matches.empty() || matches.size() > 1) { return PHPEntityBase::Ptr_t(NULL); } else { return (*matches.begin()); } - } else if(matches.size() > 1) { + } else if (matches.size() > 1) { // we found more than 1 match in the function table // return NULL return PHPEntityBase::Ptr_t(NULL); @@ -499,18 +499,20 @@ PHPEntityBase::Ptr_t PHPLookupTable::DoFindMemberOf(wxLongLong parentDbId, const return PHPEntityBase::Ptr_t(NULL); } -void PHPLookupTable::DoGetInheritanceParentIDs(PHPEntityBase::Ptr_t cls, std::vector& parents, - std::set& parentsVisited, bool excludeSelf) +void PHPLookupTable::DoGetInheritanceParentIDs(PHPEntityBase::Ptr_t cls, + std::vector& parents, + std::set& parentsVisited, + bool excludeSelf) { - if(!excludeSelf) { + if (!excludeSelf) { parents.push_back(cls->GetDbId()); } parentsVisited.insert(cls->GetDbId()); wxArrayString parentsArr = cls->Cast()->GetInheritanceArray(); - for(size_t i = 0; i < parentsArr.GetCount(); ++i) { + for (size_t i = 0; i < parentsArr.GetCount(); ++i) { PHPEntityBase::Ptr_t parent = FindClass(parentsArr.Item(i)); - if(parent && !parentsVisited.count(parent->GetDbId())) { + if (parent && !parentsVisited.count(parent->GetDbId())) { DoGetInheritanceParentIDs(parent, parents, parentsVisited, false); } } @@ -525,7 +527,7 @@ PHPEntityBase::Ptr_t PHPLookupTable::DoFindScope(const wxString& fullname, ePhpS // limit by 2 for performance reason // we will return NULL incase the number of matches is greater than 1... sql << "SELECT * from SCOPE_TABLE WHERE FULLNAME='" << fullname << "'"; - if(scopeType != kPhpScopeTypeAny) { + if (scopeType != kPhpScopeTypeAny) { sql << " AND SCOPE_TYPE = " << static_cast(scopeType); } sql << " LIMIT 2 "; @@ -534,14 +536,14 @@ PHPEntityBase::Ptr_t PHPLookupTable::DoFindScope(const wxString& fullname, ePhpS wxSQLite3ResultSet res = st.ExecuteQuery(); PHPEntityBase::Ptr_t match(NULL); - while(res.NextRow()) { - if(match) { + while (res.NextRow()) { + if (match) { // only one match return PHPEntityBase::Ptr_t(NULL); } int scopeType = res.GetInt("SCOPE_TYPE", 1); - if(scopeType == 0) { + if (scopeType == 0) { // namespace match = std::make_shared(); } else { @@ -572,7 +574,7 @@ PHPEntityBase::Ptr_t PHPLookupTable::DoFindScope(wxLongLong id, ePhpScopeType sc // limit by 2 for performance reason // we will return NULL incase the number of matches is greater than 1... sql << "SELECT * from SCOPE_TABLE WHERE ID=" << id; - if(scopeType != kPhpScopeTypeAny) { + if (scopeType != kPhpScopeTypeAny) { sql << " AND SCOPE_TYPE = " << static_cast(scopeType); } sql << " LIMIT 1"; @@ -580,10 +582,10 @@ PHPEntityBase::Ptr_t PHPLookupTable::DoFindScope(wxLongLong id, ePhpScopeType sc wxSQLite3Statement st = m_db.PrepareStatement(sql); wxSQLite3ResultSet res = st.ExecuteQuery(); - if(res.NextRow()) { + if (res.NextRow()) { PHPEntityBase::Ptr_t match(NULL); int scopeType = res.GetInt("SCOPE_TYPE", 1); - if(scopeType == kPhpScopeTypeNamespace) { + if (scopeType == kPhpScopeTypeNamespace) { // namespace match = std::make_shared(); } else { @@ -603,7 +605,7 @@ PHPEntityBase::List_t PHPLookupTable::FindChildren(wxLongLong parentId, size_t f { PHPEntityBase::List_t matches, matchesNoAbstracts; PHPEntityBase::Ptr_t scope = DoFindScope(parentId); - if(scope && scope->Is(kEntityTypeClass)) { + if (scope && scope->Is(kEntityTypeClass)) { std::vector parents; std::set parentsVisited; @@ -616,15 +618,15 @@ PHPEntityBase::List_t PHPLookupTable::FindChildren(wxLongLong parentId, size_t f } // Filter out abstract functions - if(!(flags & kLookupFlags_IncludeAbstractMethods)) { + if (!(flags & kLookupFlags_IncludeAbstractMethods)) { for (const auto& child : matches) { - if(child->Is(kEntityTypeFunction) && child->HasFlag(kFunc_Abstract)) + if (child->Is(kEntityTypeFunction) && child->HasFlag(kFunc_Abstract)) continue; matchesNoAbstracts.push_back(child); } matches.swap(matchesNoAbstracts); } - } else if(scope && scope->Is(kEntityTypeNamespace)) { + } else if (scope && scope->Is(kEntityTypeNamespace)) { DoFindChildren(matches, parentId, flags | kLookupFlags_NameHintIsScope, nameHint); } return matches; @@ -643,7 +645,7 @@ PHPEntityBase::List_t PHPLookupTable::LoadFunctionArguments(wxLongLong parentId) wxSQLite3Statement st = m_db.PrepareStatement(sql); wxSQLite3ResultSet res = st.ExecuteQuery(); - while(res.NextRow()) { + while (res.NextRow()) { PHPEntityBase::Ptr_t match(new PHPEntityVariable()); match->FromResultSet(res); matches.push_back(match); @@ -669,22 +671,22 @@ void PHPLookupTable::DoAddNameFilter(wxString& sql, const wxString& nameHint, si wxString name = nameHint; name.Trim().Trim(false); - if(name.IsEmpty()) { + if (name.IsEmpty()) { sql.Trim(); - if(sql.EndsWith("AND") || sql.EndsWith("and")) { + if (sql.EndsWith("AND") || sql.EndsWith("and")) { sql.RemoveLast(3); } sql << " "; return; } - if(flags & kLookupFlags_ExactMatch && !name.IsEmpty()) { + if (flags & kLookupFlags_ExactMatch && !name.IsEmpty()) { sql << " NAME = '" << name << "'"; - } else if(flags & kLookupFlags_Contains && !name.IsEmpty()) { + } else if (flags & kLookupFlags_Contains && !name.IsEmpty()) { sql << " NAME LIKE '%%" << EscapeWildCards(name) << "%%' ESCAPE '^'"; - } else if(flags & kLookupFlags_StartsWith && !name.IsEmpty()) { + } else if (flags & kLookupFlags_StartsWith && !name.IsEmpty()) { sql << " NAME LIKE '" << EscapeWildCards(name) << "%%' ESCAPE '^'"; } } @@ -703,31 +705,33 @@ void PHPLookupTable::LoadAllByFilter(PHPEntityBase::List_t& matches, const wxStr PHPEntityBase::Ptr_t PHPLookupTable::NewEntity(const wxString& tableName, ePhpScopeType scopeType) { - if(tableName == "FUNCTION_TABLE") { + if (tableName == "FUNCTION_TABLE") { return PHPEntityBase::Ptr_t(new PHPEntityFunction()); - } else if(tableName == "VARIABLES_TABLE") { + } else if (tableName == "VARIABLES_TABLE") { return PHPEntityBase::Ptr_t(new PHPEntityVariable()); - } else if(tableName == "SCOPE_TABLE" && scopeType == kPhpScopeTypeNamespace) { + } else if (tableName == "SCOPE_TABLE" && scopeType == kPhpScopeTypeNamespace) { return PHPEntityBase::Ptr_t(new PHPEntityNamespace()); - } else if(tableName == "SCOPE_TABLE" && scopeType == kPhpScopeTypeClass) { + } else if (tableName == "SCOPE_TABLE" && scopeType == kPhpScopeTypeClass) { return PHPEntityBase::Ptr_t(new PHPEntityClass()); } else { return PHPEntityBase::Ptr_t(NULL); } } -void PHPLookupTable::LoadFromTableByNameHint(PHPEntityBase::List_t& matches, const wxString& tableName, - const wxString& nameHint, eLookupFlags flags) +void PHPLookupTable::LoadFromTableByNameHint(PHPEntityBase::List_t& matches, + const wxString& tableName, + const wxString& nameHint, + eLookupFlags flags) { wxArrayString parts = ::wxStringTokenize(nameHint, " \t", wxTOKEN_STRTOK); - if(parts.IsEmpty()) { + if (parts.IsEmpty()) { return; } // Build the filter query wxString filterQuery = "where "; wxString sql; - for(size_t i = 0; i < parts.size(); ++i) { + for (size_t i = 0; i < parts.size(); ++i) { wxString tmpName = parts.Item(i); tmpName.Replace(wxT("_"), wxT("^_")); filterQuery << "fullname like '%%" << tmpName << "%%' " << ((i == (parts.size() - 1)) ? "" : "AND "); @@ -739,15 +743,15 @@ void PHPLookupTable::LoadFromTableByNameHint(PHPEntityBase::List_t& matches, con wxSQLite3Statement st = m_db.PrepareStatement(sql); wxSQLite3ResultSet res = st.ExecuteQuery(); - while(res.NextRow()) { + while (res.NextRow()) { ePhpScopeType st = kPhpScopeTypeAny; - if(tableName == "SCOPE_TABLE") { + if (tableName == "SCOPE_TABLE") { st = res.GetInt("SCOPE_TYPE", 1) == kPhpScopeTypeNamespace ? kPhpScopeTypeNamespace : kPhpScopeTypeClass; } PHPEntityBase::Ptr_t match = NewEntity(tableName, st); - if(match) { + if (match) { match->FromResultSet(res); matches.push_back(match); } @@ -760,7 +764,7 @@ void PHPLookupTable::LoadFromTableByNameHint(PHPEntityBase::List_t& matches, con void PHPLookupTable::DeleteFileEntries(const wxFileName& filename, bool autoCommit) { try { - if(autoCommit) + if (autoCommit) m_db.Begin(); { // When deleting from the 'SCOPE_TABLE' don't remove namespaces @@ -813,10 +817,10 @@ void PHPLookupTable::DeleteFileEntries(const wxFileName& filename, bool autoComm st.ExecuteUpdate(); } - if(autoCommit) + if (autoCommit) m_db.Commit(); } catch (const wxSQLite3Exception& e) { - if(autoCommit) + if (autoCommit) m_db.Rollback(); clWARNING() << "PHPLookupTable::DeleteFileEntries" << e.GetMessage() << endl; } @@ -825,7 +829,7 @@ void PHPLookupTable::DeleteFileEntries(const wxFileName& filename, bool autoComm void PHPLookupTable::Close() { try { - if(m_db.IsOpen()) { + if (m_db.IsOpen()) { m_db.Close(); } m_filename.Clear(); @@ -838,13 +842,15 @@ void PHPLookupTable::Close() bool PHPLookupTable::IsOpened() const { return m_db.IsOpen(); } -void PHPLookupTable::DoFindChildren(PHPEntityBase::List_t& matches, wxLongLong parentId, size_t flags, +void PHPLookupTable::DoFindChildren(PHPEntityBase::List_t& matches, + wxLongLong parentId, + size_t flags, const wxString& nameHint) { // Find members of of parentDbID try { // Load classes - if(!(flags & kLookupFlags_FunctionsAndConstsOnly)) { + if (!(flags & kLookupFlags_FunctionsAndConstsOnly)) { wxString sql; sql << "SELECT * from SCOPE_TABLE WHERE SCOPE_ID=" << parentId << " AND SCOPE_TYPE = 1 AND "; DoAddNameFilter(sql, nameHint, flags); @@ -853,7 +859,7 @@ void PHPLookupTable::DoFindChildren(PHPEntityBase::List_t& matches, wxLongLong p wxSQLite3Statement st = m_db.PrepareStatement(sql); wxSQLite3ResultSet res = st.ExecuteQuery(); - while(res.NextRow()) { + while (res.NextRow()) { PHPEntityBase::Ptr_t match(new PHPEntityClass()); match->FromResultSet(res); matches.push_back(match); @@ -870,17 +876,17 @@ void PHPLookupTable::DoFindChildren(PHPEntityBase::List_t& matches, wxLongLong p wxSQLite3Statement st = m_db.PrepareStatement(sql); wxSQLite3ResultSet res = st.ExecuteQuery(); - while(res.NextRow()) { + while (res.NextRow()) { PHPEntityBase::Ptr_t match(new PHPEntityFunction()); match->FromResultSet(res); bool isStaticFunction = match->HasFlag(kFunc_Static); - if(isStaticFunction) { + if (isStaticFunction) { // always return static functions matches.push_back(match); } else { // Non static function. - if(!(flags & kLookupFlags_Static)) { + if (!(flags & kLookupFlags_Static)) { matches.push_back(match); } } @@ -896,13 +902,13 @@ void PHPLookupTable::DoFindChildren(PHPEntityBase::List_t& matches, wxLongLong p wxSQLite3Statement st = m_db.PrepareStatement(sql); wxSQLite3ResultSet res = st.ExecuteQuery(); - while(res.NextRow()) { + while (res.NextRow()) { PHPEntityBase::Ptr_t match(new PHPEntityFunctionAlias()); match->FromResultSet(res); const wxString& realFuncName = match->Cast()->GetRealname(); // Load the function pointed by this reference PHPEntityBase::Ptr_t pFunc = FindFunction(realFuncName); - if(pFunc) { + if (pFunc) { // Keep the reference to the real function match->Cast()->SetFunc(pFunc); matches.push_back(match); @@ -920,13 +926,13 @@ void PHPLookupTable::DoFindChildren(PHPEntityBase::List_t& matches, wxLongLong p wxSQLite3Statement st = m_db.PrepareStatement(sql); wxSQLite3ResultSet res = st.ExecuteQuery(); - while(res.NextRow()) { + while (res.NextRow()) { PHPEntityBase::Ptr_t match(new PHPEntityVariable()); match->FromResultSet(res); - if(flags & kLookupFlags_FunctionsAndConstsOnly) { + if (flags & kLookupFlags_FunctionsAndConstsOnly) { // Filter non consts from the list - if(!match->Cast()->IsConst() && !match->Cast()->IsDefine()) { + if (!match->Cast()->IsConst() && !match->Cast()->IsDefine()) { continue; } } @@ -935,7 +941,7 @@ void PHPLookupTable::DoFindChildren(PHPEntityBase::List_t& matches, wxLongLong p bool isStatic = match->Cast()->IsStatic(); bool bAddIt = ((isStatic || isConst) && CollectingStatics(flags)) || (!isStatic && !isConst && !CollectingStatics(flags)); - if(bAddIt) { + if (bAddIt) { matches.push_back(match); } } @@ -954,7 +960,7 @@ wxLongLong PHPLookupTable::GetFileLastParsedTimestamp(const wxFileName& filename m_db.PrepareStatement("SELECT LAST_UPDATED FROM FILES_TABLE WHERE FILE_NAME=:FILE_NAME"); st.Bind(st.GetParamIndex(":FILE_NAME"), filename.GetFullPath()); wxSQLite3ResultSet res = st.ExecuteQuery(); - if(res.NextRow()) { + if (res.NextRow()) { return res.GetInt64("LAST_UPDATED"); } } catch (const wxSQLite3Exception& e) { @@ -980,7 +986,7 @@ void PHPLookupTable::UpdateFileLastParsedTimestamp(const wxFileName& filename) void PHPLookupTable::ClearAll(bool autoCommit) { try { - if(autoCommit) + if (autoCommit) m_db.Begin(); { wxString sql; @@ -1017,10 +1023,10 @@ void PHPLookupTable::ClearAll(bool autoCommit) st.ExecuteUpdate(); } - if(autoCommit) + if (autoCommit) m_db.Commit(); } catch (const wxSQLite3Exception& e) { - if(autoCommit) + if (autoCommit) m_db.Rollback(); clWARNING() << "PHPLookupTable::ClearAll" << e.GetMessage() << endl; } @@ -1041,8 +1047,8 @@ PHPEntityBase::Ptr_t PHPLookupTable::FindFunction(const wxString& fullname) wxSQLite3ResultSet res = st.ExecuteQuery(); PHPEntityBase::Ptr_t match(NULL); - while(res.NextRow()) { - if(match) { + while (res.NextRow()) { + if (match) { // only one match return PHPEntityBase::Ptr_t(NULL); } @@ -1062,11 +1068,11 @@ PHPEntityBase::List_t PHPLookupTable::FindGlobalFunctionAndConsts(size_t flags, { PHPEntityBase::List_t matches; // Sanity - if(nameHint.IsEmpty()) + if (nameHint.IsEmpty()) return matches; // First, locate the global namespace in the database PHPEntityBase::Ptr_t globalNs = FindScope("\\"); - if(!globalNs) + if (!globalNs) return matches; DoFindChildren(matches, globalNs->GetDbId(), kLookupFlags_FunctionsAndConstsOnly | flags, nameHint); return matches; @@ -1078,7 +1084,7 @@ PHPEntityBase::Ptr_t PHPLookupTable::CreateNamespaceForDefine(PHPEntityBase::Ptr DoSplitFullname(define->GetFullName(), nameSpaceName, shortName); PHPEntityBase::Ptr_t pNamespace = DoFindScope(nameSpaceName, kPhpScopeTypeNamespace); - if(!pNamespace) { + if (!pNamespace) { // Create it pNamespace = std::make_shared(); pNamespace->SetFullName(nameSpaceName); @@ -1094,7 +1100,7 @@ void PHPLookupTable::DoSplitFullname(const wxString& fullname, wxString& ns, wxS { // get the namespace part ns = fullname.BeforeLast('\\'); - if(!ns.StartsWith("\\")) { + if (!ns.StartsWith("\\")) { // This means that the fullname contained a single '\' // and we removed it ns.Prepend("\\"); @@ -1117,18 +1123,18 @@ PHPEntityBase::List_t PHPLookupTable::FindNamespaces(const wxString& fullnameSta wxSQLite3ResultSet res = st.ExecuteQuery(); wxString fullpath = fullnameStartsWith; - if(!shortNameContains.IsEmpty()) { - if(!fullpath.EndsWith("\\")) { + if (!shortNameContains.IsEmpty()) { + if (!fullpath.EndsWith("\\")) { fullpath << "\\"; } fullpath << shortNameContains; } - while(res.NextRow()) { + while (res.NextRow()) { PHPEntityBase::Ptr_t match(new PHPEntityNamespace()); match->FromResultSet(res); - if(match->Cast()->GetParentNamespace() == fullnameStartsWith && - match->GetShortName().StartsWith(shortNameContains)) { + if (match->Cast()->GetParentNamespace() == fullnameStartsWith && + match->GetShortName().StartsWith(shortNameContains)) { matches.push_back(match); } } @@ -1143,10 +1149,10 @@ void PHPLookupTable::ResetDatabase() wxFileName curfile = m_filename; Close(); // Close the database releasing any file capture we have // Delete the file - if(curfile.IsOk() && curfile.Exists()) { + if (curfile.IsOk() && curfile.Exists()) { // Delete it from the file system wxLogNull noLog; - if(!clRemoveFile(curfile.GetFullPath())) { + if (!clRemoveFile(curfile.GetFullPath())) { // ?? } } @@ -1157,7 +1163,7 @@ bool PHPLookupTable::CheckDiskImage(wxSQLite3Database& db, const wxFileName& fil { try { wxSQLite3ResultSet res = db.ExecuteQuery("PRAGMA integrity_check"); - if(res.NextRow()) { + if (res.NextRow()) { wxString value = res.GetString(0); clDEBUG() << "PHP: 'PRAGMA integrity_check' returned:" << value << clEndl; return (value.Lower() == "ok"); @@ -1176,8 +1182,8 @@ void PHPLookupTable::EnsureIntegrity(const wxFileName& filename) { wxSQLite3Database db; db.Open(filename.GetFullPath()); - if(db.IsOpen()) { - if(!CheckDiskImage(db, filename)) { + if (db.IsOpen()) { + if (!CheckDiskImage(db, filename)) { // disk image is malformed db.Close(); wxLogNull noLog; @@ -1201,13 +1207,13 @@ PHPEntityBase::List_t PHPLookupTable::FindSymbol(const wxString& name) wxSQLite3Statement st = m_db.PrepareStatement(sql); wxSQLite3ResultSet res = st.ExecuteQuery(); - while(res.NextRow()) { + while (res.NextRow()) { ePhpScopeType st = kPhpScopeTypeAny; st = res.GetInt("SCOPE_TYPE", 1) == kPhpScopeTypeNamespace ? kPhpScopeTypeNamespace : kPhpScopeTypeClass; PHPEntityBase::Ptr_t match = NewEntity("SCOPE_TABLE", st); - if(match) { + if (match) { match->FromResultSet(res); matches.push_back(match); } @@ -1224,7 +1230,7 @@ PHPEntityBase::List_t PHPLookupTable::FindSymbol(const wxString& name) wxSQLite3Statement st = m_db.PrepareStatement(sql); wxSQLite3ResultSet res = st.ExecuteQuery(); - while(res.NextRow()) { + while (res.NextRow()) { PHPEntityBase::Ptr_t match(new PHPEntityFunction()); match->FromResultSet(res); matches.push_back(match); @@ -1241,7 +1247,7 @@ PHPEntityBase::List_t PHPLookupTable::FindSymbol(const wxString& name) wxSQLite3Statement st = m_db.PrepareStatement(sql); wxSQLite3ResultSet res = st.ExecuteQuery(); - while(res.NextRow()) { + while (res.NextRow()) { PHPEntityBase::Ptr_t match(new PHPEntityFunction()); match->FromResultSet(res); matches.push_back(match); @@ -1258,7 +1264,7 @@ PHPEntityBase::List_t PHPLookupTable::FindSymbol(const wxString& name) wxSQLite3Statement st = m_db.PrepareStatement(sql); wxSQLite3ResultSet res = st.ExecuteQuery(); - while(res.NextRow()) { + while (res.NextRow()) { PHPEntityBase::Ptr_t match = NewEntity("VARIABLES_TABLE", kPhpScopeTypeAny); match->FromResultSet(res); matches.push_back(match); @@ -1281,7 +1287,7 @@ void PHPLookupTable::DoFixVarsDocComment(PHPEntityBase::List_t& matches, wxLongL wxSQLite3Statement st = m_db.PrepareStatement(sql); wxSQLite3ResultSet res = st.ExecuteQuery(); - while(res.NextRow()) { + while (res.NextRow()) { PHPDocVar::Ptr_t var(new PHPDocVar()); var->FromResultSet(res); docs.insert(std::make_pair(var->GetName(), var)); @@ -1289,10 +1295,10 @@ void PHPLookupTable::DoFixVarsDocComment(PHPEntityBase::List_t& matches, wxLongL // Let the PHPDOC table content override the matches' type for (auto& match : matches) { - if(match->Is(kEntityTypeVariable)) { - if(docs.count(match->GetShortName())) { + if (match->Is(kEntityTypeVariable)) { + if (docs.count(match->GetShortName())) { PHPDocVar::Ptr_t docvar = docs.find(match->GetShortName())->second; - if(!docvar->GetType().IsEmpty()) { + if (!docvar->GetType().IsEmpty()) { match->Cast()->SetTypeHint(docvar->GetType()); } } @@ -1302,7 +1308,7 @@ void PHPLookupTable::DoFixVarsDocComment(PHPEntityBase::List_t& matches, wxLongL void PHPLookupTable::UpdateClassCache(const wxString& classname) { - if(m_allClasses.count(classname) == 0) { + if (m_allClasses.count(classname) == 0) { m_allClasses.insert(classname); } } @@ -1320,7 +1326,7 @@ void PHPLookupTable::RebuildClassCache() sql << "SELECT FULLNAME from SCOPE_TABLE WHERE SCOPE_TYPE=1"; wxSQLite3ResultSet res = m_db.ExecuteQuery(sql); - while(res.NextRow()) { + while (res.NextRow()) { UpdateClassCache(res.GetString("FULLNAME")); ++count; } @@ -1345,7 +1351,7 @@ size_t PHPLookupTable::FindFunctionsByFile(const wxFileName& filename, PHPEntity << "' order by LINE_NUMBER ASC"; wxSQLite3Statement st = m_db.PrepareStatement(sql); wxSQLite3ResultSet res = st.ExecuteQuery(); - while(res.NextRow()) { + while (res.NextRow()) { PHPEntityBase::Ptr_t func(new PHPEntityFunction()); func->FromResultSet(res); functions.push_back(func); diff --git a/CodeLite/PHP/PHPLookupTable.h b/CodeLite/PHP/PHPLookupTable.h index 3729924560..8035ae43e5 100644 --- a/CodeLite/PHP/PHPLookupTable.h +++ b/CodeLite/PHP/PHPLookupTable.h @@ -95,12 +95,14 @@ class WXDLLIMPEXP_CL PHPLookupTable void DoAddNameFilter(wxString& sql, const wxString& nameHint, size_t flags); void CreateSchema(); - PHPEntityBase::Ptr_t DoFindMemberOf(wxLongLong parentDbId, const wxString& exactName, - bool parentIsNamespace = false); + PHPEntityBase::Ptr_t + DoFindMemberOf(wxLongLong parentDbId, const wxString& exactName, bool parentIsNamespace = false); void DoFixVarsDocComment(PHPEntityBase::List_t& matches, wxLongLong parentId); - void DoGetInheritanceParentIDs(PHPEntityBase::Ptr_t cls, std::vector& parents, - std::set& parentsVisited, bool excludeSelf); + void DoGetInheritanceParentIDs(PHPEntityBase::Ptr_t cls, + std::vector& parents, + std::set& parentsVisited, + bool excludeSelf); /** * @brief find namespace by fullname. If it does not exist, add it and return a pointer to it @@ -126,7 +128,9 @@ class WXDLLIMPEXP_CL PHPLookupTable * @brief load entities from table and name hint * if nameHint is empty, return empty list */ - void LoadFromTableByNameHint(PHPEntityBase::List_t& matches, const wxString& tableName, const wxString& nameHint, + void LoadFromTableByNameHint(PHPEntityBase::List_t& matches, + const wxString& tableName, + const wxString& nameHint, eLookupFlags flags); /** @@ -137,7 +141,9 @@ class WXDLLIMPEXP_CL PHPLookupTable /** * @brief return children of parentId _WITHOUT_ taking inheritance into consideration */ - void DoFindChildren(PHPEntityBase::List_t& matches, wxLongLong parentId, size_t flags = kLookupFlags_None, + void DoFindChildren(PHPEntityBase::List_t& matches, + wxLongLong parentId, + size_t flags = kLookupFlags_None, const wxString& nameHint = ""); /** @@ -236,8 +242,8 @@ class WXDLLIMPEXP_CL PHPLookupTable /** * @brief find children of a scope by its database ID. */ - PHPEntityBase::List_t FindChildren(wxLongLong parentId, size_t flags = kLookupFlags_None, - const wxString& nameHint = ""); + PHPEntityBase::List_t + FindChildren(wxLongLong parentId, size_t flags = kLookupFlags_None, const wxString& nameHint = ""); /** * @brief find list of symbols with a given name (regardless of the type / scope) @@ -260,7 +266,8 @@ class WXDLLIMPEXP_CL PHPLookupTable * @brief load list of entities from all the tables that matches 'nameHint' * if nameHint is empty, return an empty list */ - void LoadAllByFilter(PHPEntityBase::List_t& matches, const wxString& nameHint, + void LoadAllByFilter(PHPEntityBase::List_t& matches, + const wxString& nameHint, eLookupFlags flags = kLookupFlags_Contains); /** * @brief save source file into the database @@ -271,7 +278,9 @@ class WXDLLIMPEXP_CL PHPLookupTable * @brief update list of source files */ template - void RecreateSymbolsDatabase(const wxArrayString& files, eUpdateMode updateMode, GoindDownFunc pFuncGoingDown, + void RecreateSymbolsDatabase(const wxArrayString& files, + eUpdateMode updateMode, + GoindDownFunc pFuncGoingDown, bool parseFuncBodies = true); /** @@ -294,8 +303,10 @@ class WXDLLIMPEXP_CL PHPLookupTable }; template -void PHPLookupTable::RecreateSymbolsDatabase(const wxArrayString& files, eUpdateMode updateMode, - GoindDownFunc pFuncGoingDown, bool parseFuncBodies) +void PHPLookupTable::RecreateSymbolsDatabase(const wxArrayString& files, + eUpdateMode updateMode, + GoindDownFunc pFuncGoingDown, + bool parseFuncBodies) { try { @@ -311,8 +322,8 @@ void PHPLookupTable::RecreateSymbolsDatabase(const wxArrayString& files, eUpdate m_allClasses.clear(); // clear the cache m_db.Begin(); - for(size_t i = 0; i < files.GetCount(); ++i) { - if(pFuncGoingDown()) { + for (size_t i = 0; i < files.GetCount(); ++i) { + if (pFuncGoingDown()) { break; } { @@ -326,36 +337,36 @@ void PHPLookupTable::RecreateSymbolsDatabase(const wxArrayString& files, eUpdate wxFileName fnFile(files.Item(i)); bool reParseNeeded(true); - if(updateMode == kUpdateMode_Fast) { + if (updateMode == kUpdateMode_Fast) { // Check to see if we need to re-parse this file // and store it to the database - if(!fnFile.Exists()) { + if (!fnFile.Exists()) { reParseNeeded = false; } else { time_t lastModifiedOnDisk = fnFile.GetModificationTime().GetTicks(); wxLongLong lastModifiedInDB = GetFileLastParsedTimestamp(fnFile); - if(lastModifiedOnDisk <= lastModifiedInDB.ToLong()) { + if (lastModifiedOnDisk <= lastModifiedInDB.ToLong()) { reParseNeeded = false; } } } // Ensure that the file exists - if(!fnFile.Exists()) { + if (!fnFile.Exists()) { reParseNeeded = false; } // Parse only valid PHP files - if(FileExtManager::GetType(fnFile.GetFullName()) != FileExtManager::TypePhp) { + if (FileExtManager::GetType(fnFile.GetFullName()) != FileExtManager::TypePhp) { reParseNeeded = false; } - if(reParseNeeded) { + if (reParseNeeded) { // For performance reasons, load the file into memory and then parse it wxFileName fnSourceFile(files.Item(i)); wxString content; - if(!FileUtils::ReadFileContent(fnSourceFile, content, wxConvISO8859_1)) { + if (!FileUtils::ReadFileContent(fnSourceFile, content, wxConvISO8859_1)) { clWARNING() << "PHP: Failed to read file:" << fnSourceFile << "for parsing" << clEndl; continue; } diff --git a/CodeLite/PHP/PHPScannerTokens.h b/CodeLite/PHP/PHPScannerTokens.h index e22d244047..250afd8452 100644 --- a/CodeLite/PHP/PHPScannerTokens.h +++ b/CodeLite/PHP/PHPScannerTokens.h @@ -1,28 +1,28 @@ -////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// -// -// Copyright : (C) 2015 Eran Ifrah -// File name : PHPScannerTokens.h -// -// ------------------------------------------------------------------------- -// A -// _____ _ _ _ _ -// / __ \ | | | | (_) | -// | / \/ ___ __| | ___| | _| |_ ___ -// | | / _ \ / _ |/ _ \ | | | __/ _ ) -// | \__/\ (_) | (_| | __/ |___| | || __/ -// \____/\___/ \__,_|\___\_____/_|\__\___| -// -// F i l e -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation; either version 2 of the License, or -// (at your option) any later version. -// -////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// - +////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// +// +// Copyright : (C) 2015 Eran Ifrah +// File name : PHPScannerTokens.h +// +// ------------------------------------------------------------------------- +// A +// _____ _ _ _ _ +// / __ \ | | | | (_) | +// | / \/ ___ __| | ___| | _| |_ ___ +// | | / _ \ / _ |/ _ \ | | | __/ _ ) +// | \__/\ (_) | (_| | __/ |___| | || __/ +// \____/\___/ \__,_|\___\_____/_|\__\___| +// +// F i l e +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; either version 2 of the License, or +// (at your option) any later version. +// +////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + #ifndef PHPScannerTokens_H #define PHPScannerTokens_H @@ -128,8 +128,8 @@ enum { kPHP_T_ISSET, kPHP_T_EMPTY, kPHP_T_HALT_COMPILER, - kPHP_T_CLASS, - kPHP_T_TRAIT, + kPHP_T_CLASS, + kPHP_T_TRAIT, kPHP_T_ENUM, kPHP_T_INTERFACE, kPHP_T_EXTENDS, diff --git a/CodeLite/PHP/PHPSourceFile.cpp b/CodeLite/PHP/PHPSourceFile.cpp index b41242f2d4..bd1da040e9 100644 --- a/CodeLite/PHP/PHPSourceFile.cpp +++ b/CodeLite/PHP/PHPSourceFile.cpp @@ -15,9 +15,9 @@ #define NEXT_TOKEN_BREAK_IF_NOT(t, action) \ { \ - if(!NextToken(token)) \ + if (!NextToken(token)) \ break; \ - if(token.type != t) { \ + if (token.type != t) { \ action; \ break; \ } \ @@ -46,7 +46,7 @@ PHPSourceFile::PHPSourceFile(const wxFileName& filename, PHPLookupTable* lookup) m_filename.MakeAbsolute(); wxString content; - if(FileUtils::ReadFileContent(filename, content, wxConvISO8859_1)) { + if (FileUtils::ReadFileContent(filename, content, wxConvISO8859_1)) { m_text.swap(content); } m_scanner = ::phpLexerNew(m_text, kPhpLexerOpt_ReturnComments); @@ -54,7 +54,7 @@ PHPSourceFile::PHPSourceFile(const wxFileName& filename, PHPLookupTable* lookup) PHPSourceFile::~PHPSourceFile() { - if(m_scanner) { + if (m_scanner) { ::phpLexerDestroy(&m_scanner); } } @@ -62,12 +62,12 @@ PHPSourceFile::~PHPSourceFile() bool PHPSourceFile::IsInPHPSection(const wxString& buffer) { PHPScanner_t scanner = ::phpLexerNew(buffer); - if(!scanner) + if (!scanner) return false; phpLexerToken tok; bool inPhp = false; - while(::phpLexerNext(scanner, tok)) { - if(::phpLexerIsPHPCode(scanner)) { + while (::phpLexerNext(scanner, tok)) { + if (::phpLexerIsPHPCode(scanner)) { inPhp = true; } else { inPhp = false; @@ -81,8 +81,8 @@ void PHPSourceFile::Parse(int exitDepth) { int retDepth = exitDepth; phpLexerToken token; - while(NextToken(token)) { - switch(token.type) { + while (NextToken(token)) { + switch (token.type) { case '=': m_lookBackTokens.clear(); break; @@ -91,7 +91,7 @@ void PHPSourceFile::Parse(int exitDepth) break; case '}': m_lookBackTokens.clear(); - if(m_depth == retDepth) { + if (m_depth == retDepth) { return; } break; @@ -99,7 +99,7 @@ void PHPSourceFile::Parse(int exitDepth) m_lookBackTokens.clear(); break; case kPHP_T_VARIABLE: - if(!CurrentScope()->Is(kEntityTypeClass)) { + if (!CurrentScope()->Is(kEntityTypeClass)) { // A global variable OnVariable(token); } @@ -113,7 +113,7 @@ void PHPSourceFile::Parse(int exitDepth) case kPHP_T_PROTECTED: { int visibility = token.type; PHPEntityClass* cls = CurrentScope()->Cast(); - if(cls) { + if (cls) { /// keep the current token m_lookBackTokens.push_back(token); @@ -122,7 +122,7 @@ void PHPSourceFile::Parse(int exitDepth) // we let the lexer run forward until it finds kPHP_T_VARIABLE (for variable) // or kPHP_T_IDENTIFIER int what = ReadUntilFoundOneOf(kPHP_T_VARIABLE, kPHP_T_FUNCTION, token); - if(what == kPHP_T_VARIABLE) { + if (what == kPHP_T_VARIABLE) { // A variable PHPEntityBase::Ptr_t member(new PHPEntityVariable()); member->SetFilename(m_filename.GetFullPath()); @@ -139,20 +139,20 @@ void PHPSourceFile::Parse(int exitDepth) // public $memberVar = new Something(); // for such cases, assign $memberVar type of Something() phpLexerToken t; - if(!NextToken(t)) { + if (!NextToken(t)) { // EOF return; } - if(t.type == '=') { + if (t.type == '=') { // assignment wxString expr; - if(!ReadExpression(expr)) { + if (!ReadExpression(expr)) { return; } // Optimize 'new ClassName(..)' expression - if(expr.StartsWith("new")) { + if (expr.StartsWith("new")) { expr = expr.Mid(3); expr.Trim().Trim(false); expr = expr.BeforeFirst('('); @@ -167,11 +167,11 @@ void PHPSourceFile::Parse(int exitDepth) } else { // restore the token UngetToken(t); - if(!ConsumeUntil(';')) + if (!ConsumeUntil(';')) return; } - } else if(what == kPHP_T_FUNCTION) { + } else if (what == kPHP_T_FUNCTION) { // A function... OnFunction(); m_lookBackTokens.clear(); @@ -187,7 +187,7 @@ void PHPSourceFile::Parse(int exitDepth) OnConstant(token); break; case kPHP_T_CASE: - if(Class() == CurrentScope().get()) { + if (Class() == CurrentScope().get()) { // in class cope, this means that this is an enum case OnEnumCase(token); } @@ -206,7 +206,7 @@ void PHPSourceFile::Parse(int exitDepth) break; case kPHP_T_USE: // Found outer 'use' statement - construct the alias table - if(Class()) { + if (Class()) { // inside a class, this means that this is a 'use ;' OnUseTrait(); } else { @@ -246,24 +246,24 @@ void PHPSourceFile::OnUse() wxString fullname, alias, temp; phpLexerToken token; bool cont = true; - while(cont && NextToken(token)) { - switch(token.type) { + while (cont && NextToken(token)) { + switch (token.type) { case ',': case ';': { - if(fullname.IsEmpty()) { + if (fullname.IsEmpty()) { // no full name yet fullname.swap(temp); - } else if(alias.IsEmpty()) { + } else if (alias.IsEmpty()) { alias.swap(temp); } - if(alias.IsEmpty()) { + if (alias.IsEmpty()) { // no alias provided, use the last part of the fullname alias = fullname.AfterLast('\\'); } - if(!fullname.IsEmpty() && !alias.IsEmpty()) { + if (!fullname.IsEmpty() && !alias.IsEmpty()) { // Use namespace is always referred as fullpath namespace // So writing: // use Zend\Mvc\Controll\Action; @@ -271,7 +271,7 @@ void PHPSourceFile::OnUse() // use \Zend\Mvc\Controll\Action; // For simplicity, we change it to fully qualified path // so parsing is easier - if(!fullname.StartsWith("\\")) { + if (!fullname.StartsWith("\\")) { fullname.Prepend("\\"); } m_aliases.insert(std::make_pair(alias, MakeIdentifierAbsolute(fullname))); @@ -279,7 +279,7 @@ void PHPSourceFile::OnUse() temp.clear(); fullname.clear(); alias.clear(); - if(token.type == ';') { + if (token.type == ';') { cont = false; } } break; @@ -299,24 +299,24 @@ void PHPSourceFile::OnNamespace() // Read until we find the line delimiter ';' or EOF found wxString path; phpLexerToken token; - while(NextToken(token)) { - if(token.type == ';') { + while (NextToken(token)) { + if (token.type == ';') { break; } // Make sure that the namespace path is always set in absolute path // i.e. starts with kPHP_T_NS_SEPARATOR - if(path.IsEmpty() && token.type != kPHP_T_NS_SEPARATOR) { + if (path.IsEmpty() && token.type != kPHP_T_NS_SEPARATOR) { path << "\\"; } path << token.Text(); } - if(m_scopes.empty()) { + if (m_scopes.empty()) { // no scope is set, push the global scope m_scopes.push_back(PHPEntityBase::Ptr_t(new PHPEntityNamespace())); PHPEntityNamespace* ns = CurrentScope()->Cast(); - if(ns) { + if (ns) { ns->SetFullName(path); // Global namespace } } else { @@ -328,37 +328,37 @@ void PHPSourceFile::OnFunction() { // read the next token phpLexerToken token; - if(!NextToken(token)) { + if (!NextToken(token)) { return; } bool funcReturnRef = false; - if(token.type == '&') { + if (token.type == '&') { funcReturnRef = true; - if(!NextToken(token)) { + if (!NextToken(token)) { return; } } PHPEntityFunction* func(NULL); int funcDepth(0); - if(token.type == kPHP_T_IDENTIFIER) { + if (token.type == kPHP_T_IDENTIFIER) { // the function name func = new PHPEntityFunction(); func->SetFullName(token.Text()); func->SetLine(token.lineNumber); - } else if(token.type == '(') { + } else if (token.type == '(') { funcDepth = 1; // Since we already consumed the open brace // anonymous function func = new PHPEntityFunction(); func->SetLine(token.lineNumber); } - if(!func) + if (!func) return; PHPEntityBase::Ptr_t funcPtr(func); - if(funcReturnRef) { + if (funcReturnRef) { funcPtr->SetFlag(kFunc_ReturnReference); } @@ -371,32 +371,32 @@ void PHPSourceFile::OnFunction() // update function attributes ParseFunctionSignature(funcDepth); func->SetFlags(LookBackForFunctionFlags()); - if(LookBackTokensContains(kPHP_T_ABSTRACT) || // The 'abstract modifier was found for this function - (funcPtr->Parent() && funcPtr->Parent()->Is(kEntityTypeClass) && - funcPtr->Parent()->Cast()->IsInterface())) // We are inside an interface + if (LookBackTokensContains(kPHP_T_ABSTRACT) || // The 'abstract modifier was found for this function + (funcPtr->Parent() && funcPtr->Parent()->Is(kEntityTypeClass) && + funcPtr->Parent()->Cast()->IsInterface())) // We are inside an interface { // Mark this function as an abstract function func->SetFlags(func->GetFlags() | kFunc_Abstract); } - if(func->HasFlag(kFunc_Abstract)) { + if (func->HasFlag(kFunc_Abstract)) { // an abstract function - it has no body - if(!ConsumeUntil(';')) { + if (!ConsumeUntil(';')) { // could not locate the function delimiter, remove it from the stack // we probably reached EOF here m_scopes.pop_back(); } } else { - if(!NextToken(token)) + if (!NextToken(token)) return; - if(token.type == ':') { + if (token.type == ':') { // PHP 7 signature type // function foobar(...) : RETURN_TYPE - if(!NextToken(token)) + if (!NextToken(token)) return; - if(token.type == '?') { + if (token.type == '?') { // PHP 7.1 nullable return funcPtr->SetFlag(kFunc_ReturnNullable); } else { @@ -404,7 +404,7 @@ void PHPSourceFile::OnFunction() } wxString returnValuetype = ReadFunctionReturnValueFromSignature(); - if(returnValuetype.IsEmpty()) + if (returnValuetype.IsEmpty()) return; // parse error func->SetReturnValue(returnValuetype); @@ -413,9 +413,9 @@ void PHPSourceFile::OnFunction() UngetToken(token); } - if(ReadUntilFound('{', token)) { + if (ReadUntilFound('{', token)) { // found the function body starting point - if(IsParseFunctionBody()) { + if (IsParseFunctionBody()) { ParseFunctionBody(); } else { // Consume the function body @@ -429,7 +429,7 @@ void PHPSourceFile::OnFunction() } // Remove the current function from the scope list - if(!m_reachedEOF) { + if (!m_reachedEOF) { m_scopes.pop_back(); } m_lookBackTokens.clear(); @@ -437,7 +437,7 @@ void PHPSourceFile::OnFunction() PHPEntityBase::Ptr_t PHPSourceFile::CurrentScope() { - if(m_scopes.empty()) { + if (m_scopes.empty()) { // no scope is set, push the global scope m_scopes.push_back(PHPEntityBase::Ptr_t(new PHPEntityNamespace())); CurrentScope()->SetFullName("\\"); // Global namespace @@ -449,25 +449,25 @@ size_t PHPSourceFile::LookBackForFunctionFlags() { size_t flags(0); for (const phpLexerToken& tok : m_lookBackTokens) { - if(tok.type == kPHP_T_ABSTRACT) { + if (tok.type == kPHP_T_ABSTRACT) { flags |= kFunc_Abstract; - } else if(tok.type == kPHP_T_FINAL) { + } else if (tok.type == kPHP_T_FINAL) { flags |= kFunc_Final; - } else if(tok.type == kPHP_T_STATIC) { + } else if (tok.type == kPHP_T_STATIC) { flags |= kFunc_Static; - } else if(tok.type == kPHP_T_PUBLIC) { + } else if (tok.type == kPHP_T_PUBLIC) { flags |= kFunc_Public; flags &= ~kFunc_Private; flags &= ~kFunc_Protected; - } else if(tok.type == kPHP_T_PRIVATE) { + } else if (tok.type == kPHP_T_PRIVATE) { flags |= kFunc_Private; flags &= ~kFunc_Public; flags &= ~kFunc_Protected; - } else if(tok.type == kPHP_T_PROTECTED) { + } else if (tok.type == kPHP_T_PROTECTED) { flags |= kFunc_Protected; flags &= ~kFunc_Public; flags &= ~kFunc_Private; @@ -479,15 +479,15 @@ size_t PHPSourceFile::LookBackForFunctionFlags() void PHPSourceFile::ParseFunctionSignature(int startingDepth) { phpLexerToken token; - if(startingDepth == 0) { + if (startingDepth == 0) { // loop until we find the open brace - while(NextToken(token)) { - if(token.type == '(') { + while (NextToken(token)) { + if (token.type == '(') { ++startingDepth; break; } } - if(startingDepth == 0) + if (startingDepth == 0) return; } @@ -498,10 +498,10 @@ void PHPSourceFile::ParseFunctionSignature(int startingDepth) wxString name; PHPEntityVariable* var(NULL); bool collectingDefaultValue = false; - while(NextToken(token)) { - switch(token.type) { + while (NextToken(token)) { + switch (token.type) { case kPHP_T_VARIABLE: - if(!var) { + if (!var) { // var can be non null if we are parsing PHP-7 function arguments // with type-hinting var = new PHPEntityVariable(); @@ -512,10 +512,10 @@ void PHPSourceFile::ParseFunctionSignature(int startingDepth) var->SetFilename(m_filename); // Mark this variable as function argument var->SetFlag(kVar_FunctionArg); - if(name.StartsWith("&")) { + if (name.StartsWith("&")) { var->SetIsReference(true); name.Remove(0, 1); - } else if(typeHint.EndsWith("&")) { + } else if (typeHint.EndsWith("&")) { var->SetIsReference(true); typeHint.RemoveLast(); } @@ -524,21 +524,21 @@ void PHPSourceFile::ParseFunctionSignature(int startingDepth) break; case '(': depth++; - if(collectingDefaultValue) { + if (collectingDefaultValue) { defaultValue << "("; } break; case ')': depth--; // if the depth goes under 1 - we are done - if(depth < 1) { - if(var) { + if (depth < 1) { + if (var) { var->SetDefaultValue(defaultValue); CurrentScope()->AddChild(PHPEntityBase::Ptr_t(var)); } return; - } else if(depth) { + } else if (depth) { defaultValue << token.Text(); } break; @@ -547,7 +547,7 @@ void PHPSourceFile::ParseFunctionSignature(int startingDepth) collectingDefaultValue = true; break; case ',': - if(var) { + if (var) { var->SetDefaultValue(defaultValue); CurrentScope()->AddChild(PHPEntityBase::Ptr_t(var)); } @@ -557,25 +557,25 @@ void PHPSourceFile::ParseFunctionSignature(int startingDepth) collectingDefaultValue = false; break; case '?': - if(!var) { + if (!var) { var = new PHPEntityVariable(); } var->SetIsNullable(true); break; case kPHP_T_NS_SEPARATOR: case kPHP_T_IDENTIFIER: - if(!var) { + if (!var) { // PHP-7 type hinting function arguments var = new PHPEntityVariable(); UngetToken(token); typeHint = ReadType(); - if(!typeHint.IsEmpty()) { + if (!typeHint.IsEmpty()) { break; } } // all "else" cases simply fall into the default case default: - if(collectingDefaultValue) { + if (collectingDefaultValue) { defaultValue << token.Text(); } else { typeHint << token.Text(); @@ -588,8 +588,8 @@ void PHPSourceFile::ParseFunctionSignature(int startingDepth) bool PHPSourceFile::ReadUntilFound(int delim, phpLexerToken& token) { // loop until we find the open brace - while(NextToken(token)) { - if(token.type == delim) { + while (NextToken(token)) { + if (token.type == delim) { return true; } } @@ -600,10 +600,10 @@ void PHPSourceFile::ConsumeFunctionBody() { int depth = m_depth; phpLexerToken token; - while(NextToken(token)) { - switch(token.type) { + while (NextToken(token)) { + switch (token.type) { case '}': - if(m_depth < depth) { + if (m_depth < depth) { return; } break; @@ -621,14 +621,14 @@ void PHPSourceFile::ParseFunctionBody() int exitDepth = m_depth - 1; phpLexerToken token; PHPEntityBase::Ptr_t var(NULL); - while(NextToken(token)) { - switch(token.type) { + while (NextToken(token)) { + switch (token.type) { case '{': m_lookBackTokens.clear(); break; case '}': m_lookBackTokens.clear(); - if(m_depth == exitDepth) { + if (m_depth == exitDepth) { return; } break; @@ -654,8 +654,8 @@ wxString PHPSourceFile::ReadType() wxString type; phpLexerToken token; - while(cont && NextToken(token)) { - switch(token.type) { + while (cont && NextToken(token)) { + switch (token.type) { case kPHP_T_IDENTIFIER: type << token.Text(); break; @@ -678,7 +678,7 @@ wxString PHPSourceFile::ReadType() PHPEntityBase::Ptr_t PHPSourceFile::Namespace() { - if(m_scopes.empty()) { + if (m_scopes.empty()) { return CurrentScope(); } return *m_scopes.begin(); @@ -696,12 +696,12 @@ void PHPSourceFile::PhaseTwo() bool PHPSourceFile::NextToken(phpLexerToken& token) { bool res = ::phpLexerNext(m_scanner, token); - if(res && (token.type == kPHP_T_C_COMMENT)) { + if (res && (token.type == kPHP_T_C_COMMENT)) { m_comments.push_back(token); // We keep comments made in the class body - if(!m_scopes.empty() && CurrentScope()->Is(kEntityTypeClass)) { + if (!m_scopes.empty() && CurrentScope()->Is(kEntityTypeClass)) { PHPDocVar::Ptr_t var(new PHPDocVar(*this, token.Text())); - if(var->IsOk()) { + if (var->IsOk()) { var->SetLineNumber(token.lineNumber); // this comment is a @var comment CurrentScope()->Cast()->AddVarPhpDoc(var); @@ -709,16 +709,16 @@ bool PHPSourceFile::NextToken(phpLexerToken& token) } } - if(token.type == '{') { + if (token.type == '{') { m_depth++; - } else if(token.type == '}') { + } else if (token.type == '}') { m_depth--; - } else if(token.type == ';') { + } else if (token.type == ';') { m_lookBackTokens.clear(); } - if(!res) + if (!res) m_reachedEOF = true; - if(res) + if (res) m_lookBackTokens.push_back(token); return res; } @@ -729,7 +729,7 @@ void PHPSourceFile::OnClass(const phpLexerToken& tok) { wxString classDoc; const phpLexerToken& prevToken = GetPreviousToken(); - if(!prevToken.IsNull() && prevToken.IsDocComment()) { + if (!prevToken.IsNull() && prevToken.IsDocComment()) { classDoc = prevToken.Text(); } @@ -739,10 +739,10 @@ void PHPSourceFile::OnClass(const phpLexerToken& tok) // Read until we get the class name wxString name; phpLexerToken token; - while(NextToken(token)) { - if(token.IsAnyComment()) + while (NextToken(token)) { + if (token.IsAnyComment()) continue; - if(token.type != kPHP_T_IDENTIFIER) { + if (token.type != kPHP_T_IDENTIFIER) { // Anonymous classes name = "@anonymous/" + m_filename.GetFullPath() + "/" + wxString::Format(wxT("%i"), token.lineNumber); break; @@ -789,14 +789,14 @@ void PHPSourceFile::OnClass(const phpLexerToken& tok) pClass->SetImplements(implements); } - while(NextToken(token)) { - if(token.IsAnyComment()) + while (NextToken(token)) { + if (token.IsAnyComment()) continue; - switch(token.type) { + switch (token.type) { case kPHP_T_EXTENDS: { // inheritance wxString extends = ReadExtends(); - if(extends.IsEmpty()) + if (extends.IsEmpty()) return; // No need to call 'MakeIdentifierAbsolute' it was called internally by pClass->SetExtends(extends); @@ -812,7 +812,7 @@ void PHPSourceFile::OnClass(const phpLexerToken& tok) CurrentScope()->AddChild(klass); m_scopes.push_back(klass); Parse(m_depth - 1); - if(!m_reachedEOF) { + if (!m_reachedEOF) { m_scopes.pop_back(); } return; @@ -826,8 +826,8 @@ void PHPSourceFile::OnClass(const phpLexerToken& tok) bool PHPSourceFile::ConsumeUntil(int delim) { phpLexerToken token; - while(NextToken(token)) { - if(token.type == delim) { + while (NextToken(token)) { + if (token.type == delim) { return true; } } @@ -839,16 +839,16 @@ bool PHPSourceFile::ReadExpression(wxString& expression) expression.clear(); phpLexerToken token; int depth(0); - while(NextToken(token)) { - if(token.type == ';') { + while (NextToken(token)) { + if (token.type == ';') { return true; - } else if(token.type == '{') { + } else if (token.type == '{') { UngetToken(token); return true; } - switch(token.type) { + switch (token.type) { case kPHP_T_FUNCTION: OnFunction(); break; @@ -869,17 +869,17 @@ bool PHPSourceFile::ReadExpression(wxString& expression) break; case ')': depth--; - if(depth == 0) { + if (depth == 0) { expression << ")"; } break; case kPHP_T_NEW: - if(depth == 0) { + if (depth == 0) { expression << token.Text() << " "; } break; default: - if(depth == 0) { + if (depth == 0) { expression << token.Text(); } break; @@ -893,11 +893,11 @@ void PHPSourceFile::UngetToken(const phpLexerToken& token) { ::phpLexerUnget(m_scanner); // undo any depth / comments - if(token.type == '{') { + if (token.type == '{') { m_depth--; - } else if(token.type == '}') { + } else if (token.type == '}') { m_depth++; - } else if(token.type == kPHP_T_C_COMMENT && !m_comments.empty()) { + } else if (token.type == kPHP_T_C_COMMENT && !m_comments.empty()) { m_comments.erase(m_comments.begin() + m_comments.size() - 1); } } @@ -906,9 +906,9 @@ const PHPEntityBase* PHPSourceFile::Class() { PHPEntityBase::Ptr_t curScope = CurrentScope(); PHPEntityBase* pScope = curScope.get(); - while(pScope) { + while (pScope) { PHPEntityClass* cls = pScope->Cast(); - if(cls) { + if (cls) { // this scope is a class return pScope; } @@ -920,10 +920,10 @@ const PHPEntityBase* PHPSourceFile::Class() int PHPSourceFile::ReadUntilFoundOneOf(int delim1, int delim2, phpLexerToken& token) { // loop until we find the open brace - while(NextToken(token)) { - if(token.type == delim1) { + while (NextToken(token)) { + if (token.type == delim1) { return delim1; - } else if(token.type == delim2) { + } else if (token.type == delim2) { return delim2; } } @@ -943,23 +943,23 @@ size_t PHPSourceFile::LookBackForVariablesFlags() { size_t flags(kVar_Public); for (const phpLexerToken& tok : m_lookBackTokens) { - if(tok.type == kPHP_T_STATIC) { + if (tok.type == kPHP_T_STATIC) { flags |= kVar_Static; - } else if(tok.type == kPHP_T_CONST) { + } else if (tok.type == kPHP_T_CONST) { flags |= kVar_Const; - } else if(tok.type == kPHP_T_PUBLIC) { + } else if (tok.type == kPHP_T_PUBLIC) { flags |= kVar_Public; flags &= ~kVar_Private; flags &= ~kVar_Protected; - } else if(tok.type == kPHP_T_PRIVATE) { + } else if (tok.type == kPHP_T_PRIVATE) { flags |= kVar_Private; flags &= ~kVar_Public; flags &= ~kVar_Protected; - } else if(tok.type == kPHP_T_PROTECTED) { + } else if (tok.type == kPHP_T_PROTECTED) { flags |= kVar_Protected; flags &= ~kVar_Private; flags &= ~kVar_Public; @@ -974,11 +974,11 @@ void PHPSourceFile::OnVariable(const phpLexerToken& tok) var->SetFullName(tok.Text()); var->SetFilename(m_filename.GetFullPath()); var->SetLine(tok.lineNumber); - if(!CurrentScope()->FindChild(var->GetFullName(), true)) { + if (!CurrentScope()->FindChild(var->GetFullName(), true)) { CurrentScope()->AddChild(var); } - if(!ReadVariableInitialization(var)) { + if (!ReadVariableInitialization(var)) { m_lookBackTokens.clear(); return; } @@ -987,23 +987,23 @@ void PHPSourceFile::OnVariable(const phpLexerToken& tok) bool PHPSourceFile::ReadVariableInitialization(PHPEntityBase::Ptr_t var) { phpLexerToken token; - if(!NextToken(token)) { + if (!NextToken(token)) { return false; } - if(token.type != '=') { + if (token.type != '=') { // restore the token UngetToken(token); return false; } wxString expr; - if(!ReadExpression(expr)) { + if (!ReadExpression(expr)) { return false; // EOF } // Optimize 'new ClassName(..)' expression - if(expr.StartsWith("new")) { + if (expr.StartsWith("new")) { expr = expr.Mid(3); expr.Trim().Trim(false); expr = expr.BeforeFirst('('); @@ -1035,21 +1035,21 @@ PHPEntityBase::List_t PHPSourceFile::GetAliases() const void PHPSourceFile::OnDefine(const phpLexerToken& tok) { phpLexerToken token; - if(!NextToken(token)) + if (!NextToken(token)) return; // EOF - if(token.type != '(') { + if (token.type != '(') { ConsumeUntil(';'); return; } - if(!NextToken(token)) + if (!NextToken(token)) return; // EOF - if(token.type != kPHP_T_CONSTANT_ENCAPSED_STRING) { + if (token.type != kPHP_T_CONSTANT_ENCAPSED_STRING) { ConsumeUntil(';'); return; } // Remove the quotes wxString varName = token.Text(); - if((varName.StartsWith("\"") && varName.EndsWith("\"")) || (varName.StartsWith("'") && varName.EndsWith("'"))) { + if ((varName.StartsWith("\"") && varName.EndsWith("\"")) || (varName.StartsWith("'") && varName.EndsWith("'"))) { varName.Remove(0, 1); varName.RemoveLast(); // define() defines constants exactly as it was instructed @@ -1057,7 +1057,7 @@ void PHPSourceFile::OnDefine(const phpLexerToken& tok) PHPEntityBase::Ptr_t var(new PHPEntityVariable()); // Convert the variable into fullpath + relative name - if(!varName.StartsWith("\\")) { + if (!varName.StartsWith("\\")) { varName.Prepend("\\"); } wxString shortName = varName.AfterLast('\\'); @@ -1078,17 +1078,17 @@ void PHPSourceFile::OnDefine(const phpLexerToken& tok) void PHPSourceFile::OnUseTrait() { PHPEntityBase::Ptr_t clas = CurrentScope(); - if(!clas) + if (!clas) return; // Collect the identifiers followed the 'use' statement wxArrayString identifiers; wxString tempname; phpLexerToken token; - while(NextToken(token)) { - switch(token.type) { + while (NextToken(token)) { + switch (token.type) { case ',': { - if(!tempname.IsEmpty()) { + if (!tempname.IsEmpty()) { identifiers.Add(MakeIdentifierAbsolute(tempname)); } tempname.clear(); @@ -1096,7 +1096,7 @@ void PHPSourceFile::OnUseTrait() case '{': { // we are looking at a case like: // use A, B { ... } - if(!tempname.IsEmpty()) { + if (!tempname.IsEmpty()) { identifiers.Add(MakeIdentifierAbsolute(tempname)); ParseUseTraitsBody(); } @@ -1106,7 +1106,7 @@ void PHPSourceFile::OnUseTrait() return; } break; case ';': { - if(!tempname.IsEmpty()) { + if (!tempname.IsEmpty()) { identifiers.Add(MakeIdentifierAbsolute(tempname)); } tempname.clear(); @@ -1129,8 +1129,8 @@ void PHPSourceFile::OnCatch() phpLexerToken token; wxString typehint; wxString varname; - while(cont && NextToken(token)) { - switch(token.type) { + while (cont && NextToken(token)) { + switch (token.type) { case kPHP_T_VARIABLE: cont = false; varname = token.Text(); @@ -1144,7 +1144,7 @@ void PHPSourceFile::OnCatch() } } - if(!varname.IsEmpty()) { + if (!varname.IsEmpty()) { // we found the variable PHPEntityBase::Ptr_t var(new PHPEntityVariable()); var->SetFullName(varname); @@ -1153,7 +1153,7 @@ void PHPSourceFile::OnCatch() var->Cast()->SetTypeHint(MakeIdentifierAbsolute(typehint)); // add the variable to the current scope - if(!CurrentScope()->FindChild(var->GetFullName(), true)) { + if (!CurrentScope()->FindChild(var->GetFullName(), true)) { CurrentScope()->AddChild(var); } } @@ -1163,8 +1163,8 @@ wxString PHPSourceFile::ReadExtends() { wxString type; phpLexerToken token; - while(NextToken(token)) { - if(token.type == kPHP_T_IDENTIFIER || token.type == kPHP_T_NS_SEPARATOR) { + while (NextToken(token)) { + if (token.type == kPHP_T_IDENTIFIER || token.type == kPHP_T_NS_SEPARATOR) { type << token.Text(); } else { UngetToken(token); @@ -1179,17 +1179,17 @@ void PHPSourceFile::ReadImplements(wxArrayString& impls) { wxString type; phpLexerToken token; - while(NextToken(token)) { - switch(token.type) { + while (NextToken(token)) { + switch (token.type) { case kPHP_T_IDENTIFIER: case kPHP_T_NS_SEPARATOR: type << token.Text(); break; case ',': // More to come - if(!type.IsEmpty()) { + if (!type.IsEmpty()) { wxString fullyQualifiedType = MakeIdentifierAbsolute(type); - if(impls.Index(fullyQualifiedType) == wxNOT_FOUND) { + if (impls.Index(fullyQualifiedType) == wxNOT_FOUND) { impls.Add(fullyQualifiedType); } type.clear(); @@ -1197,9 +1197,9 @@ void PHPSourceFile::ReadImplements(wxArrayString& impls) break; default: // unexpected token - if(!type.IsEmpty()) { + if (!type.IsEmpty()) { wxString fullyQualifiedType = MakeIdentifierAbsolute(type); - if(impls.Index(fullyQualifiedType) == wxNOT_FOUND) { + if (impls.Index(fullyQualifiedType) == wxNOT_FOUND) { impls.Add(fullyQualifiedType); } type.clear(); @@ -1218,19 +1218,19 @@ void PHPSourceFile::OnForEach() { // read until the "as" keyword phpLexerToken token; - if(!ReadUntilFound(kPHP_T_AS, token)) + if (!ReadUntilFound(kPHP_T_AS, token)) return; // Found the "as" key word and consumed it - if(!NextToken(token)) + if (!NextToken(token)) return; phpLexerToken peekToken; - if(!NextToken(peekToken)) + if (!NextToken(peekToken)) return; // Ensure we got a variable - if(token.type != kPHP_T_VARIABLE) + if (token.type != kPHP_T_VARIABLE) return; // Add the key @@ -1239,14 +1239,14 @@ void PHPSourceFile::OnForEach() var->SetFullName(token.Text()); var->SetFilename(m_filename.GetFullPath()); var->SetLine(token.lineNumber); - if(!CurrentScope()->FindChild(var->GetFullName(), true)) { + if (!CurrentScope()->FindChild(var->GetFullName(), true)) { CurrentScope()->AddChild(var); } } // Check to see if we are using the syntax of: // foreach (array_expression as $key => $value) - if(peekToken.type == kPHP_T_DOUBLE_ARROW) { - if(!NextToken(token) || token.type != kPHP_T_VARIABLE) { + if (peekToken.type == kPHP_T_DOUBLE_ARROW) { + if (!NextToken(token) || token.type != kPHP_T_VARIABLE) { return; } @@ -1257,7 +1257,7 @@ void PHPSourceFile::OnForEach() var->SetFilename(m_filename.GetFullPath()); var->SetLine(token.lineNumber); - if(!CurrentScope()->FindChild(var->GetFullName(), true)) { + if (!CurrentScope()->FindChild(var->GetFullName(), true)) { CurrentScope()->AddChild(var); } @@ -1271,27 +1271,27 @@ void PHPSourceFile::ParseUseTraitsBody() wxString fullname, alias, temp; phpLexerToken token; bool cont = true; - while(cont && NextToken(token)) { - switch(token.type) { + while (cont && NextToken(token)) { + switch (token.type) { case '}': { cont = false; } break; case ',': case ';': { - if(fullname.IsEmpty()) { + if (fullname.IsEmpty()) { // no full name yet fullname.swap(temp); - } else if(alias.IsEmpty()) { + } else if (alias.IsEmpty()) { alias.swap(temp); } - if(alias.IsEmpty()) { + if (alias.IsEmpty()) { // no alias provided, use the last part of the fullname alias = fullname.AfterLast('\\'); } - if(!fullname.IsEmpty() && !alias.IsEmpty()) { + if (!fullname.IsEmpty() && !alias.IsEmpty()) { // Use namespace is always referred as fullpath namespace // So writing: // use Zend\Mvc\Controll\Action; @@ -1299,7 +1299,7 @@ void PHPSourceFile::ParseUseTraitsBody() // use \Zend\Mvc\Controll\Action; // For simplicity, we change it to fully qualified path // so parsing is easier - if(!fullname.StartsWith("\\")) { + if (!fullname.StartsWith("\\")) { fullname.Prepend("\\"); } PHPEntityBase::Ptr_t funcAlias(new PHPEntityFunctionAlias()); @@ -1330,7 +1330,7 @@ void PHPSourceFile::ParseUseTraitsBody() fullname.clear(); temp.clear(); alias.clear(); - if(!ConsumeUntil(';')) + if (!ConsumeUntil(';')) return; } break; default: @@ -1345,37 +1345,37 @@ void PHPSourceFile::OnConstant(const phpLexerToken& tok) // Parse constant line (possibly multiple constants) phpLexerToken token; PHPEntityBase::Ptr_t member; - while(NextToken(token)) { - if(token.type == '=') { + while (NextToken(token)) { + if (token.type == '=') { // The next value should contain the constant value wxString constantValue; - while(NextToken(token)) { - if(token.type == ';') { + while (NextToken(token)) { + if (token.type == ';') { UngetToken(token); break; - } else if(token.type == ',') { + } else if (token.type == ',') { break; } constantValue << token.Text(); } - if(member && !constantValue.IsEmpty()) { + if (member && !constantValue.IsEmpty()) { // Keep the constant value, we will be using it later for tooltip member->Cast()->SetDefaultValue(constantValue); } } - if(token.type == ';') { - if(member) { + if (token.type == ';') { + if (member) { CurrentScope()->AddChild(member); break; } - } else if(token.type == ',') { - if(member) { + } else if (token.type == ',') { + if (member) { CurrentScope()->AddChild(member); member = nullptr; } - } else if(token.type == kPHP_T_IDENTIFIER) { + } else if (token.type == kPHP_T_IDENTIFIER) { // found the constant name member = std::make_shared(); member->Cast()->SetFlag(kVar_Const); @@ -1394,30 +1394,30 @@ void PHPSourceFile::OnEnumCase(const phpLexerToken& tok) // Parse enum case phpLexerToken token; PHPEntityBase::Ptr_t member; - while(NextToken(token)) { - if(token.type == '=') { + while (NextToken(token)) { + if (token.type == '=') { // The next value should contain the value wxString constantValue; - while(NextToken(token)) { - if(token.type == ';') { + while (NextToken(token)) { + if (token.type == ';') { UngetToken(token); break; } constantValue << token.Text(); } - if(member && !constantValue.IsEmpty()) { + if (member && !constantValue.IsEmpty()) { // Keep the constant value, we will be using it later for tooltip member->Cast()->SetDefaultValue(constantValue); } } - if(token.type == ';') { - if(member) { + if (token.type == ';') { + if (member) { CurrentScope()->AddChild(member); break; } - } else if(token.type == kPHP_T_IDENTIFIER) { + } else if (token.type == kPHP_T_IDENTIFIER) { // found the constant name member = std::make_shared(); member->Cast()->SetFlag(kVar_Const); @@ -1433,7 +1433,7 @@ void PHPSourceFile::OnEnumCase(const phpLexerToken& tok) phpLexerToken& PHPSourceFile::GetPreviousToken() { static phpLexerToken NullToken; - if(m_lookBackTokens.size() >= 2) { + if (m_lookBackTokens.size() >= 2) { // The last token in the list is the current one. We want the previous one return m_lookBackTokens.at(m_lookBackTokens.size() - 2); } @@ -1446,8 +1446,8 @@ wxString PHPSourceFile::ReadFunctionReturnValueFromSignature() wxString type; phpLexerToken token; - while(cont && NextToken(token)) { - switch(token.type) { + while (cont && NextToken(token)) { + switch (token.type) { case kPHP_T_SELF: case kPHP_T_ARRAY: return token.Text(); @@ -1475,7 +1475,7 @@ wxString PHPSourceFile::ReadFunctionReturnValueFromSignature() wxString PHPSourceFile::PrependCurrentScope(const wxString& className) { wxString currentScope = Namespace()->GetFullName(); - if(!currentScope.EndsWith("\\")) { + if (!currentScope.EndsWith("\\")) { currentScope << "\\"; } return currentScope + className; @@ -1485,12 +1485,12 @@ wxString PHPSourceFile::MakeTypehintAbsolute(const wxString& type) { return DoMa wxString PHPSourceFile::DoMakeIdentifierAbsolute(const wxString& type, bool exactMatch) { - if(m_converter) { + if (m_converter) { return m_converter->MakeIdentifierAbsolute(type); } static std::unordered_set phpKeywords; - if(phpKeywords.empty()) { + if (phpKeywords.empty()) { // List taken from https://www.php.net/manual/en/language.types.intro.php // Native types phpKeywords.insert("bool"); @@ -1517,16 +1517,16 @@ wxString PHPSourceFile::DoMakeIdentifierAbsolute(const wxString& type, bool exac wxString typeWithNS(type); typeWithNS.Trim().Trim(false); - if(phpKeywords.count(type.ToStdString())) { + if (phpKeywords.count(type.ToStdString())) { // primitives, don't bother... return typeWithNS; } - if(typeWithNS.IsEmpty()) + if (typeWithNS.IsEmpty()) return ""; // A fully qualified type? don't touch it - if(typeWithNS.StartsWith("\\")) { + if (typeWithNS.StartsWith("\\")) { return typeWithNS; } @@ -1534,15 +1534,15 @@ wxString PHPSourceFile::DoMakeIdentifierAbsolute(const wxString& type, bool exac // use Zend\Form; // create an alias entry: Form => Zend\Form // class A extends Form\Form {} // The extends should be expanded to Zend\Form\Form - if(typeWithNS.Contains("\\")) { + if (typeWithNS.Contains("\\")) { wxString scopePart = typeWithNS.BeforeLast('\\'); wxString className = typeWithNS.AfterLast('\\'); - if(m_aliases.find(scopePart) != m_aliases.end()) { + if (m_aliases.find(scopePart) != m_aliases.end()) { typeWithNS.clear(); typeWithNS << m_aliases.find(scopePart)->second << "\\" << className; // Remove duplicate NS separators typeWithNS.Replace("\\\\", "\\"); - if(!typeWithNS.StartsWith("\\")) { + if (!typeWithNS.StartsWith("\\")) { typeWithNS << "\\"; } return typeWithNS; @@ -1550,16 +1550,16 @@ wxString PHPSourceFile::DoMakeIdentifierAbsolute(const wxString& type, bool exac } // Use the alias table first - if(m_aliases.find(type) != m_aliases.end()) { + if (m_aliases.find(type) != m_aliases.end()) { return m_aliases.find(type)->second; } wxString ns = Namespace()->GetFullName(); - if(!ns.EndsWith("\\")) { + if (!ns.EndsWith("\\")) { ns << "\\"; } - if(exactMatch && m_lookup && !typeWithNS.Contains("\\") && !m_lookup->ClassExists(ns + typeWithNS)) { + if (exactMatch && m_lookup && !typeWithNS.Contains("\\") && !m_lookup->ClassExists(ns + typeWithNS)) { // Only when "exactMatch" apply this logic, otherwise, we might be getting a partially typed string // which we will not find by calling FindChild() typeWithNS.Prepend("\\"); // Use the global NS @@ -1571,23 +1571,23 @@ wxString PHPSourceFile::DoMakeIdentifierAbsolute(const wxString& type, bool exac const PHPEntityBase::List_t& PHPSourceFile::GetAllMatchesInOrder() { - if(m_allMatchesInorder.empty()) { + if (m_allMatchesInorder.empty()) { auto ns = Namespace(); - if(!ns) { + if (!ns) { return m_allMatchesInorder; } - if(ns->GetChildren().empty()) { + if (ns->GetChildren().empty()) { return m_allMatchesInorder; } PHPEntityBase::List_t Q; Q.insert(Q.end(), ns->GetChildren().begin(), ns->GetChildren().end()); - while(!Q.empty()) { + while (!Q.empty()) { auto cur = Q.front(); Q.erase(Q.begin()); m_allMatchesInorder.push_back(cur); - if(!cur->GetChildren().empty()) { + if (!cur->GetChildren().empty()) { // we want to process these children on the next iteration // so we prepend them to the queue Q.reserve(Q.size() + cur->GetChildren().size()); diff --git a/CodeLite/PHP/PhpLexerAPI.h b/CodeLite/PHP/PhpLexerAPI.h index 54b42b8409..3826b72651 100644 --- a/CodeLite/PHP/PhpLexerAPI.h +++ b/CodeLite/PHP/PhpLexerAPI.h @@ -26,13 +26,13 @@ #ifndef PhpLexerAPI_H__ #define PhpLexerAPI_H__ +#include "PHPScannerTokens.h" +#include "codelite_exports.h" + #include #include #include -#include "codelite_exports.h" -#include "PHPScannerTokens.h" - enum ePhpLexerOptions { kPhpLexerOpt_None = 0x00000000, kPhpLexerOpt_ReturnComments = 0x00000001, @@ -112,7 +112,7 @@ struct WXDLLIMPEXP_CL phpLexerUserData { public: void Clear() { - if(m_fp) { + if (m_fp) { ::fclose(m_fp); } m_fp = NULL; @@ -141,7 +141,7 @@ struct WXDLLIMPEXP_CL phpLexerUserData { bool IsCollectingAllNonPhp() const { return m_flags & kPhpLexerOpt_ReturnAllNonPhp; } void SetCollectingWhitespace(bool b) { - if(b) { + if (b) { m_flags |= kPhpLexerOpt_ReturnWhitespace; } else { m_flags &= ~kPhpLexerOpt_ReturnWhitespace; @@ -237,7 +237,7 @@ struct WXDLLIMPEXP_CL PHPScannerLocker { ~PHPScannerLocker() { - if(scanner) { + if (scanner) { ::phpLexerDestroy(&scanner); } } diff --git a/CodeLite/Platform/LINUX.cpp b/CodeLite/Platform/LINUX.cpp index 56452e280b..3463936481 100644 --- a/CodeLite/Platform/LINUX.cpp +++ b/CodeLite/Platform/LINUX.cpp @@ -44,10 +44,7 @@ std::optional LINUX::get_rustup_bin_folder() return RUST_TOOLCHAIN_BIN; } -std::optional LINUX::FindInstallDir() -{ - return "/"; -} +std::optional LINUX::FindInstallDir() { return "/"; } std::optional LINUX::FindHomeDir() { @@ -154,7 +151,7 @@ LINUX* LINUX::Get() { return &instance; } std::optional LINUX::MacFindApp(const wxString& appname, bool new_instance) { #ifdef __WXMAC__ - wxFileName path{ "/Applications", wxEmptyString }; + wxFileName path{"/Applications", wxEmptyString}; path.AppendDir(appname + ".app"); // search for app name diff --git a/CodeLite/Platform/PlatformCommon.cpp b/CodeLite/Platform/PlatformCommon.cpp index 6f9abe68b1..75b851bb8e 100644 --- a/CodeLite/Platform/PlatformCommon.cpp +++ b/CodeLite/Platform/PlatformCommon.cpp @@ -21,7 +21,7 @@ std::optional PlatformCommon::WhichWithVersion(const wxString& command // executable without number should come first names.Add(command); - for(auto ver : sorted_versions) { + for (auto ver : sorted_versions) { names.Add(wxString() << command << "-" << ver); } for (const wxString& name : names) { @@ -49,10 +49,10 @@ std::optional PlatformCommon::FindRustupToolchainBinDir() } // locate the default toolchain - wxString toolchain_name = ProcUtils::GrepCommandOutput({ rustup_exe, "toolchain", "list" }, "(default)"); + wxString toolchain_name = ProcUtils::GrepCommandOutput({rustup_exe, "toolchain", "list"}, "(default)"); toolchain_name = toolchain_name.BeforeLast('('); toolchain_name.Trim().Trim(false); - if(toolchain_name.empty()) { + if (toolchain_name.empty()) { return std::nullopt; } diff --git a/CodeLite/SocketAPI/clConnectionString.cpp b/CodeLite/SocketAPI/clConnectionString.cpp index 3d5b357040..c5186b75bd 100644 --- a/CodeLite/SocketAPI/clConnectionString.cpp +++ b/CodeLite/SocketAPI/clConnectionString.cpp @@ -1,4 +1,5 @@ #include "clConnectionString.h" + #include "file_logger.h" clConnectionString::clConnectionString(const wxString& connectionString) @@ -14,9 +15,9 @@ void clConnectionString::DoParse(const wxString& connectionString) // get the protocol part clDEBUG() << "Parsing connection string:" << connectionString << clEndl; wxString protocol = connectionString.BeforeFirst(':'); - if(protocol == "tcp") { + if (protocol == "tcp") { m_protocol = kTcp; - } else if(protocol == "unix") { + } else if (protocol == "unix") { #ifdef __WXMSW__ clWARNING() << "unix protocol is not supported on Windows" << clEndl; return; @@ -30,7 +31,7 @@ void clConnectionString::DoParse(const wxString& connectionString) wxString address = connectionString.AfterFirst(':'); address = address.Mid(2); // Skip the "//" - if(m_protocol == kUnixLocalSocket) { + if (m_protocol == kUnixLocalSocket) { // The rest is the file path m_path = address; m_isOK = !m_path.IsEmpty(); @@ -38,7 +39,7 @@ void clConnectionString::DoParse(const wxString& connectionString) // we now expect host[:port] m_host = address.BeforeFirst(':'); wxString port = address.AfterFirst(':'); - if(!port.IsEmpty()) { + if (!port.IsEmpty()) { port.ToCLong(&m_port); } m_isOK = !m_host.IsEmpty() && (m_port != wxNOT_FOUND); diff --git a/CodeLite/SocketAPI/clSocketBase.cpp b/CodeLite/SocketAPI/clSocketBase.cpp index 841fddff00..0225e18e23 100644 --- a/CodeLite/SocketAPI/clSocketBase.cpp +++ b/CodeLite/SocketAPI/clSocketBase.cpp @@ -63,21 +63,21 @@ int clSocketBase::Read(wxMemoryBuffer& content, long timeout) char buffer[4096]; timeout = (timeout * 1000); // convert to MS - while(true && timeout) { + while (true && timeout) { int rc = SelectReadMS(10); timeout -= 10; - if(rc == kSuccess) { + if (rc == kSuccess) { memset(buffer, 0x0, sizeof(buffer)); int bytesRead = recv(m_socket, buffer, sizeof(buffer), 0); - if(bytesRead < 0) { + if (bytesRead < 0) { const int err = GetLastError(); - if(eWouldBlock != err) { + if (eWouldBlock != err) { // Error throw clSocketException("Read failed: " + error(err)); } - } else if(bytesRead == 0) { + } else if (bytesRead == 0) { // connection closed return kError; @@ -86,7 +86,7 @@ int clSocketBase::Read(wxMemoryBuffer& content, long timeout) continue; } } else { - if(content.IsEmpty()) + if (content.IsEmpty()) continue; // keep waiting until time ends else return kSuccess; // we already read our content @@ -99,7 +99,7 @@ int clSocketBase::Read(wxString& content, const wxMBConv& conv, long timeout) { wxMemoryBuffer mb; int rc = Read(mb, timeout); - if(rc == kSuccess) { + if (rc == kSuccess) { content = wxString((const char*)mb.GetData(), conv, mb.GetDataLen()); } return rc; @@ -107,20 +107,20 @@ int clSocketBase::Read(wxString& content, const wxMBConv& conv, long timeout) int clSocketBase::Read(char* buffer, size_t bufferSize, size_t& bytesRead, long timeout) { - if(SelectRead(timeout) == kTimeout) { + if (SelectRead(timeout) == kTimeout) { return kTimeout; } memset(buffer, 0, bufferSize); const int res = ::recv(m_socket, buffer, bufferSize, 0); - if(res < 0) { + if (res < 0) { const int err = GetLastError(); - if(eWouldBlock == err) { + if (eWouldBlock == err) { return kTimeout; } throw clSocketException("Read failed: " + error(err)); - } else if(0 == res) { + } else if (0 == res) { throw clSocketException("Read failed: " + error()); } @@ -130,25 +130,25 @@ int clSocketBase::Read(char* buffer, size_t bufferSize, size_t& bytesRead, long int clSocketBase::SelectRead(long seconds) { - if(seconds == -1) { + if (seconds == -1) { return kSuccess; } - if(m_socket == INVALID_SOCKET) { + if (m_socket == INVALID_SOCKET) { throw clSocketException("Invalid socket!"); } - struct timeval tv = { seconds, 0 }; + struct timeval tv = {seconds, 0}; fd_set readfds; FD_ZERO(&readfds); FD_SET(m_socket, &readfds); int rc = select(m_socket + 1, &readfds, NULL, NULL, &tv); - if(rc == 0) { + if (rc == 0) { // timeout return kTimeout; - } else if(rc < 0) { + } else if (rc < 0) { // an error occurred throw clSocketException("SelectRead failed: " + error()); @@ -161,7 +161,7 @@ int clSocketBase::SelectRead(long seconds) // Send API void clSocketBase::Send(const wxString& msg, const wxMBConv& conv) { - if(m_socket == INVALID_SOCKET) { + if (m_socket == INVALID_SOCKET) { throw clSocketException("Invalid socket!"); } wxCharBuffer cb = msg.mb_str(conv).data(); @@ -172,7 +172,7 @@ void clSocketBase::Send(const wxString& msg, const wxMBConv& conv) void clSocketBase::Send(const std::string& msg) { - if(m_socket == INVALID_SOCKET) { + if (m_socket == INVALID_SOCKET) { throw clSocketException("Invalid socket!"); } wxMemoryBuffer mb; @@ -182,7 +182,7 @@ void clSocketBase::Send(const std::string& msg) void clSocketBase::Send(const wxMemoryBuffer& msg) { - if(m_socket == INVALID_SOCKET) { + if (m_socket == INVALID_SOCKET) { throw clSocketException("Invalid socket!"); } char* pdata = (char*)msg.GetData(); @@ -194,14 +194,14 @@ void clSocketBase::Send(const wxMemoryBuffer& msg) clDEBUG1() << "Sending buffer:" << str << endl; clDEBUG1() << "Message length:" << str.length() << endl; } - while(bytesLeft) { - if(SelectWriteMS(100) == kTimeout) { + while (bytesLeft) { + if (SelectWriteMS(100) == kTimeout) { continue; } int bytesSent = ::send(m_socket, (const char*)pdata, bytesLeft, 0); LOG_IF_TRACE { clDEBUG1() << "::send() completed. number of bytes sent:" << bytesSent << endl; } - if(bytesSent <= 0) { + if (bytesSent <= 0) { throw clSocketException("Send error: " + error()); } pdata += bytesSent; @@ -225,13 +225,18 @@ std::string clSocketBase::error(const int errorCode) std::string err; #ifdef _WIN32 // Get the error message, if any. - if(errorCode == 0) + if (errorCode == 0) return "No error message has been recorded"; LPSTR messageBuffer = nullptr; size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, errorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL); + NULL, + errorCode, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + (LPSTR)&messageBuffer, + 0, + NULL); std::string message(messageBuffer, size); @@ -246,8 +251,8 @@ std::string clSocketBase::error(const int errorCode) void clSocketBase::DestroySocket() { - if(IsCloseOnExit()) { - if(m_socket != INVALID_SOCKET) { + if (IsCloseOnExit()) { + if (m_socket != INVALID_SOCKET) { #ifdef _WIN32 ::shutdown(m_socket, 2); ::closesocket(m_socket); @@ -269,7 +274,7 @@ int clSocketBase::ReadMessage(wxString& message, int timeout) size_t message_len(0); size_t bytesRead(0); int rc = Read((char*)msglen, sizeof(msglen) - 1, bytesRead, timeout); - if(rc != kSuccess) { + if (rc != kSuccess) { // timeout return rc; } @@ -283,9 +288,9 @@ int clSocketBase::ReadMessage(wxString& message, int timeout) // read the entire amount we need int bytesLeft = message_len; int totalRead = 0; - while(bytesLeft > 0) { + while (bytesLeft > 0) { rc = Read(pBuff.get() + totalRead, bytesLeft, bytesRead, timeout); - if(rc != kSuccess) { + if (rc != kSuccess) { return rc; } else { @@ -301,7 +306,7 @@ int clSocketBase::ReadMessage(wxString& message, int timeout) void clSocketBase::WriteMessage(const wxString& message) { - if(m_socket == INVALID_SOCKET) { + if (m_socket == INVALID_SOCKET) { throw clSocketException("Invalid socket!"); } @@ -314,7 +319,7 @@ void clSocketBase::WriteMessage(const wxString& message) memset(msglen, 0, sizeof(msglen)); sprintf(msglen, "%010d", len); // send it without the NULL byte - if(::send(m_socket, msglen, sizeof(msglen) - 1, 0) < 0) { + if (::send(m_socket, msglen, sizeof(msglen) - 1, 0) < 0) { throw clSocketException("Send error: " + error(errno)); } @@ -335,7 +340,7 @@ void clSocketBase::MakeSocketBlocking(bool blocking) // set socket to non-blocking mode int flags; flags = ::fcntl(m_socket, F_GETFL); - if(blocking) { + if (blocking) { flags &= ~O_NONBLOCK; } else { flags |= O_NONBLOCK; @@ -349,11 +354,11 @@ void clSocketBase::MakeSocketBlocking(bool blocking) int clSocketBase::SelectWriteMS(long milliSeconds) { - if(milliSeconds == -1) { + if (milliSeconds == -1) { return kSuccess; } - if(m_socket == INVALID_SOCKET) { + if (m_socket == INVALID_SOCKET) { throw clSocketException("Invalid socket!"); } @@ -366,11 +371,11 @@ int clSocketBase::SelectWriteMS(long milliSeconds) FD_SET(m_socket, &write_set); errno = 0; int rc = select(m_socket + 1, NULL, &write_set, NULL, &tv); - if(rc == 0) { + if (rc == 0) { // timeout return kTimeout; - } else if(rc < 0) { + } else if (rc < 0) { // an error occurred throw clSocketException("SelectWriteMS failed: " + error()); @@ -382,26 +387,26 @@ int clSocketBase::SelectWriteMS(long milliSeconds) int clSocketBase::SelectWrite(long seconds) { - if(seconds == -1) { + if (seconds == -1) { return kSuccess; } - if(m_socket == INVALID_SOCKET) { + if (m_socket == INVALID_SOCKET) { throw clSocketException("Invalid socket!"); } - struct timeval tv = { seconds, 0 }; + struct timeval tv = {seconds, 0}; fd_set write_set; FD_ZERO(&write_set); FD_SET(m_socket, &write_set); errno = 0; int rc = select(m_socket + 1, NULL, &write_set, NULL, &tv); - if(rc == 0) { + if (rc == 0) { // timeout return kTimeout; - } else if(rc < 0) { + } else if (rc < 0) { // an error occurred throw clSocketException("SelectRead failed: " + error()); @@ -413,27 +418,27 @@ int clSocketBase::SelectWrite(long seconds) int clSocketBase::SelectReadMS(long milliSeconds) { - if(milliSeconds == -1) { + if (milliSeconds == -1) { return kSuccess; } - if(m_socket == INVALID_SOCKET) { + if (m_socket == INVALID_SOCKET) { throw clSocketException("Invalid socket!"); } int seconds = milliSeconds / 1000; // convert the number into seconds int ms = milliSeconds % 1000; // the remainder is less than a second - struct timeval tv = { seconds, ms * 1000 }; + struct timeval tv = {seconds, ms * 1000}; fd_set readfds; FD_ZERO(&readfds); FD_SET(m_socket, &readfds); int rc = select(m_socket + 1, &readfds, NULL, NULL, &tv); - if(rc == 0) { + if (rc == 0) { // timeout return kTimeout; - } else if(rc < 0) { + } else if (rc < 0) { // an error occurred throw clSocketException("SelectRead failed: " + error()); diff --git a/CodeLite/SocketAPI/clSocketClient.cpp b/CodeLite/SocketAPI/clSocketClient.cpp index 00a08e25df..cd9bc77622 100644 --- a/CodeLite/SocketAPI/clSocketClient.cpp +++ b/CodeLite/SocketAPI/clSocketClient.cpp @@ -23,15 +23,16 @@ ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// -#include "clConnectionString.h" #include "clSocketClient.h" +#include "clConnectionString.h" + #ifndef _WIN32 -#include #include #include #include #include /* superset of previous */ +#include #include #include #include @@ -54,7 +55,9 @@ bool clSocketClient::ConnectLocal(const wxString& socketPath) #endif server.sun_family = AF_UNIX; strcpy(server.sun_path, socketPath.mb_str(wxConvUTF8).data()); - if(::connect(m_socket, (struct sockaddr*)&server, sizeof(struct sockaddr_un)) < 0) { return false; } + if (::connect(m_socket, (struct sockaddr*)&server, sizeof(struct sockaddr_un)) < 0) { + return false; + } return true; #else return false; @@ -66,7 +69,9 @@ bool clSocketClient::ConnectRemote(const wxString& address, int port, bool& woul wouldBlock = false; DestroySocket(); m_socket = ::socket(AF_INET, SOCK_STREAM, 0); - if(nonBlockingMode) { MakeSocketBlocking(false); } + if (nonBlockingMode) { + MakeSocketBlocking(false); + } const char* ip_addr = address.mb_str(wxConvUTF8).data(); struct sockaddr_in serv_addr; @@ -77,9 +82,11 @@ bool clSocketClient::ConnectRemote(const wxString& address, int port, bool& woul serv_addr.sin_port = htons(port); #ifndef __WXMSW__ - if(inet_pton(AF_INET, ip_addr, &serv_addr.sin_addr) <= 0) { + if (inet_pton(AF_INET, ip_addr, &serv_addr.sin_addr) <= 0) { // restore socket to blocking mode - if(nonBlockingMode) { MakeSocketBlocking(true); } + if (nonBlockingMode) { + MakeSocketBlocking(true); + } return false; } #else @@ -95,15 +102,19 @@ bool clSocketClient::ConnectRemote(const wxString& address, int port, bool& woul #endif // restore socket to blocking mode - if(nonBlockingMode) { MakeSocketBlocking(true); } + if (nonBlockingMode) { + MakeSocketBlocking(true); + } return rc == 0; } bool clSocketClient::Connect(const wxString& connectionString, bool nonBlockingMode) { clConnectionString cs(connectionString); - if(!cs.IsOK()) { return false; } - if(cs.GetProtocol() == clConnectionString::kUnixLocalSocket) { + if (!cs.IsOK()) { + return false; + } + if (cs.GetProtocol() == clConnectionString::kUnixLocalSocket) { return ConnectLocal(cs.GetPath()); } else { // TCP @@ -116,8 +127,10 @@ bool clSocketClient::ConnectNonBlocking(const wxString& connectionString, bool& { wouldBlock = false; clConnectionString cs(connectionString); - if(!cs.IsOK()) { return false; } - if(cs.GetProtocol() == clConnectionString::kUnixLocalSocket) { + if (!cs.IsOK()) { + return false; + } + if (cs.GetProtocol() == clConnectionString::kUnixLocalSocket) { return ConnectLocal(cs.GetPath()); } else { // TCP diff --git a/CodeLite/SocketAPI/clSocketClient.h b/CodeLite/SocketAPI/clSocketClient.h index 487d2f40f6..cf2a4d1ea1 100644 --- a/CodeLite/SocketAPI/clSocketClient.h +++ b/CodeLite/SocketAPI/clSocketClient.h @@ -27,6 +27,7 @@ #define CLSOCKETCLIENT_H #include "clSocketBase.h" + #include class WXDLLIMPEXP_CL clSocketClient : public clSocketBase diff --git a/CodeLite/SocketAPI/clSocketClientAsync.cpp b/CodeLite/SocketAPI/clSocketClientAsync.cpp index dc84cf7859..7ec7540966 100644 --- a/CodeLite/SocketAPI/clSocketClientAsync.cpp +++ b/CodeLite/SocketAPI/clSocketClientAsync.cpp @@ -33,7 +33,7 @@ void clAsyncSocket::Stop() { wxDELETE(m_thread); } void clAsyncSocket::Send(const std::string& buffer) { - if(m_thread) { + if (m_thread) { clSocketAsyncThread::MyRequest req; req.m_command = clSocketAsyncThread::kSend; req.m_buffer = buffer; @@ -46,7 +46,9 @@ void clAsyncSocket::Send(const wxString& buffer) { Send(StringUtils::ToStdString //----------------------------------------------------------------------------------------------- // The helper thread //----------------------------------------------------------------------------------------------- -clSocketAsyncThread::clSocketAsyncThread(wxEvtHandler* sink, const wxString& connectionString, size_t mode, +clSocketAsyncThread::clSocketAsyncThread(wxEvtHandler* sink, + const wxString& connectionString, + size_t mode, const wxString& keepAliveMessage) : wxThread(wxTHREAD_JOINABLE) , m_sink(sink) @@ -60,7 +62,7 @@ clSocketAsyncThread::~clSocketAsyncThread() { Stop(); } void* clSocketAsyncThread::Entry() { - if(m_mode & kAsyncSocketClient) { + if (m_mode & kAsyncSocketClient) { return ClientMain(); } else { return ServerMain(); @@ -72,23 +74,23 @@ void* clSocketAsyncThread::ServerMain() try { clSocketServer server; int port = server.Start(m_connectionString); - + // Notify that we are ready to accept connections clCommandEvent eventReady(wxEVT_ASYNC_SOCKET_SERVER_READY); eventReady.SetInt(port); m_sink->AddPendingEvent(eventReady); clSocketBase::Ptr_t conn; - while(!TestDestroy()) { + while (!TestDestroy()) { conn = server.WaitForNewConnection(1); - if(conn) { + if (conn) { clCommandEvent event(wxEVT_ASYNC_SOCKET_CONNECTED); m_sink->AddPendingEvent(event); break; } } - if(m_mode & kAsyncSocketMessage) { + if (m_mode & kAsyncSocketMessage) { MessageLoop(conn); } else { BufferLoop(conn); @@ -110,18 +112,18 @@ void* clSocketAsyncThread::ClientMain() bool connected = false; // Try to connect and wait up to 5 seconds - if(m_mode & kAsyncSocketNonBlocking) { + if (m_mode & kAsyncSocketNonBlocking) { bool wouldBlock = false; connected = client->ConnectNonBlocking(m_connectionString, wouldBlock); - if(!connected && wouldBlock) { + if (!connected && wouldBlock) { // We should select here (wait for the socket to be writable) - for(size_t i = 0; i < 5; ++i) { + for (size_t i = 0; i < 5; ++i) { int rc = client->SelectWrite(1); - if(rc == clSocketBase::kSuccess) { + if (rc == clSocketBase::kSuccess) { // we are connected connected = true; break; - } else if(rc == clSocketBase::kError) { + } else if (rc == clSocketBase::kError) { // an error occurred break; } else { @@ -130,14 +132,18 @@ void* clSocketAsyncThread::ClientMain() } // Test for thread shutdown before we continue - if(TestDestroy()) { break; } + if (TestDestroy()) { + break; + } } } } else { - for(size_t i = 0; i < 10; ++i) { + for (size_t i = 0; i < 10; ++i) { connected = client->Connect(m_connectionString, false); - if(connected) { break; } - if(TestDestroy()) { + if (connected) { + break; + } + if (TestDestroy()) { // We were requested to go down during connect phase return NULL; } @@ -146,7 +152,7 @@ void* clSocketAsyncThread::ClientMain() } // Connected? - if(!connected) { + if (!connected) { // report error and go out clCommandEvent event(wxEVT_ASYNC_SOCKET_CONNECT_ERROR); event.SetString(socket->error()); @@ -158,7 +164,7 @@ void* clSocketAsyncThread::ClientMain() clCommandEvent event(wxEVT_ASYNC_SOCKET_CONNECTED); m_sink->AddPendingEvent(event); - if(m_mode & kAsyncSocketMessage) { + if (m_mode & kAsyncSocketMessage) { MessageLoop(socket); } else { BufferLoop(socket); @@ -170,19 +176,19 @@ void clSocketAsyncThread::MessageLoop(clSocketBase::Ptr_t socket) { try { int counter = 0; - while(!TestDestroy()) { + while (!TestDestroy()) { MyRequest req; - if(m_queue.ReceiveTimeout(100, req) == wxMSGQUEUE_NO_ERROR) { + if (m_queue.ReceiveTimeout(100, req) == wxMSGQUEUE_NO_ERROR) { // got something - if(req.m_command == kDisconnect) { + if (req.m_command == kDisconnect) { socket.reset(); return; - } else if(req.m_command == kSend) { + } else if (req.m_command == kSend) { socket->WriteMessage(req.m_buffer); wxString replyMessage; - while(socket->ReadMessage(replyMessage, 1) == clSocketBase::kTimeout) { - if(TestDestroy()) { + while (socket->ReadMessage(replyMessage, 1) == clSocketBase::kTimeout) { + if (TestDestroy()) { // Going down return; } @@ -194,7 +200,7 @@ void clSocketAsyncThread::MessageLoop(clSocketBase::Ptr_t socket) } } else { // Make sure that the socket is still alive - if((counter % 10) == 0) { + if ((counter % 10) == 0) { socket->WriteMessage(""); counter = 0; } @@ -213,37 +219,37 @@ void clSocketAsyncThread::BufferLoop(clSocketBase::Ptr_t socket) { try { int counter = 0; - while(!TestDestroy()) { + while (!TestDestroy()) { // Wait for request from the user ++counter; - if(!m_keepAliveMessage.IsEmpty() && (counter % 10) == 0) { + if (!m_keepAliveMessage.IsEmpty() && (counter % 10) == 0) { // Fire the keep alive message // if we lost the socket, it will raise an exception socket->Send(m_keepAliveMessage); } MyRequest req; - if(m_queue.ReceiveTimeout(1, req) == wxMSGQUEUE_NO_ERROR) { + if (m_queue.ReceiveTimeout(1, req) == wxMSGQUEUE_NO_ERROR) { // got something - if(req.m_command == kDisconnect) { + if (req.m_command == kDisconnect) { socket.reset(); return; - } else if(req.m_command == kSend) { + } else if (req.m_command == kSend) { socket->Send(req.m_buffer); } } // timeout, test to see if we got something on the socket wxString buffer; - if(socket->SelectReadMS(5) == clSocketBase::kSuccess) { + if (socket->SelectReadMS(5) == clSocketBase::kSuccess) { int rc = socket->Read(buffer); - if(rc == clSocketBase::kSuccess) { + if (rc == clSocketBase::kSuccess) { clCommandEvent event(wxEVT_ASYNC_SOCKET_INPUT); event.SetString(buffer); m_sink->AddPendingEvent(event); - } else if(rc == clSocketBase::kError) { + } else if (rc == clSocketBase::kError) { // Connection lost clCommandEvent event(wxEVT_ASYNC_SOCKET_CONNECTION_LOST); m_sink->AddPendingEvent(event); diff --git a/CodeLite/SocketAPI/clSocketClientAsync.h b/CodeLite/SocketAPI/clSocketClientAsync.h index eb6339ff3b..6c294a0542 100644 --- a/CodeLite/SocketAPI/clSocketClientAsync.h +++ b/CodeLite/SocketAPI/clSocketClientAsync.h @@ -94,7 +94,7 @@ class WXDLLIMPEXP_CL clSocketAsyncThread : public wxThread */ void Stop() { - if(IsAlive()) { + if (IsAlive()) { Delete(NULL, wxTHREAD_WAIT_BLOCK); } else { @@ -102,7 +102,9 @@ class WXDLLIMPEXP_CL clSocketAsyncThread : public wxThread } } - clSocketAsyncThread(wxEvtHandler* sink, const wxString& connectionString, size_t mode, + clSocketAsyncThread(wxEvtHandler* sink, + const wxString& connectionString, + size_t mode, const wxString& keepAliveMessage = ""); virtual ~clSocketAsyncThread(); }; @@ -117,8 +119,7 @@ class WXDLLIMPEXP_CL clAsyncSocket : public wxEvtHandler using Ptr_t = std::shared_ptr; public: - clAsyncSocket(const wxString& connectionString, - size_t mode = (kAsyncSocketClient | kAsyncSocketBuffer)); + clAsyncSocket(const wxString& connectionString, size_t mode = (kAsyncSocketClient | kAsyncSocketBuffer)); virtual ~clAsyncSocket(); /** diff --git a/CodeLite/SocketAPI/clSocketServer.cpp b/CodeLite/SocketAPI/clSocketServer.cpp index c578f7dce0..49a0f99a8d 100644 --- a/CodeLite/SocketAPI/clSocketServer.cpp +++ b/CodeLite/SocketAPI/clSocketServer.cpp @@ -23,14 +23,15 @@ ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// -#include "clConnectionString.h" #include "clSocketServer.h" +#include "clConnectionString.h" + #ifndef _WIN32 -#include #include #include #include +#include #include #include #include @@ -46,7 +47,7 @@ int clSocketServer::CreateServer(const std::string& pipePath) unlink(pipePath.c_str()); // Create a socket - if((m_socket = ::socket(AF_UNIX, SOCK_STREAM, 0)) == INVALID_SOCKET) { + if ((m_socket = ::socket(AF_UNIX, SOCK_STREAM, 0)) == INVALID_SOCKET) { throw clSocketException("Could not create socket: " + error()); } @@ -66,7 +67,7 @@ int clSocketServer::CreateServer(const std::string& pipePath) strcpy(server.sun_path, pipePath.c_str()); // Bind - if(::bind(m_socket, (struct sockaddr*)&server, sizeof(server)) == -1) { + if (::bind(m_socket, (struct sockaddr*)&server, sizeof(server)) == -1) { throw clSocketException("CreateServer: bind operation failed: " + error()); } @@ -86,7 +87,7 @@ int clSocketServer::CreateServer(const std::string& pipePath) int clSocketServer::CreateServer(const std::string& address, int port) { // Create a socket - if((m_socket = ::socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) { + if ((m_socket = ::socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) { throw clSocketException("Could not create socket: " + error()); } @@ -111,24 +112,26 @@ int clSocketServer::CreateServer(const std::string& address, int port) server.sin_port = htons(port); // Bind - if(::bind(m_socket, (struct sockaddr*)&server, sizeof(server)) != 0) { + if (::bind(m_socket, (struct sockaddr*)&server, sizeof(server)) != 0) { throw clSocketException("CreateServer: bind() error: " + error()); } - if(port == 0) { + if (port == 0) { struct sockaddr_in socket_name; #ifdef __WXMSW__ int name_len = sizeof(socket_name); #else socklen_t name_len = sizeof(socket_name); #endif - if(::getsockname(m_socket, (struct sockaddr*)&socket_name, &name_len) != 0) { + if (::getsockname(m_socket, (struct sockaddr*)&socket_name, &name_len) != 0) { throw clSocketException("CreateServer: getsockname() error: " + error()); } port = ntohs(socket_name.sin_port); } // define the accept queue size - if(::listen(m_socket, 10) != 0) { throw clSocketException("CreateServer: listen() error: " + error()); } + if (::listen(m_socket, 10) != 0) { + throw clSocketException("CreateServer: listen() error: " + error()); + } // return the bound port number return port; @@ -137,8 +140,10 @@ int clSocketServer::CreateServer(const std::string& address, int port) int clSocketServer::Start(const wxString& connectionString) { clConnectionString cs(connectionString); - if(!cs.IsOK()) { throw clSocketException("Invalid connection string provided"); } - if(cs.GetProtocol() == clConnectionString::kTcp) { + if (!cs.IsOK()) { + throw clSocketException("Invalid connection string provided"); + } + if (cs.GetProtocol() == clConnectionString::kTcp) { return CreateServer(cs.GetHost().mb_str(wxConvUTF8).data(), cs.GetPort()); } else { return CreateServer(cs.GetPath().mb_str(wxConvUTF8).data()); @@ -152,8 +157,12 @@ clSocketBase::Ptr_t clSocketServer::WaitForNewConnection(long timeout) clSocketBase* clSocketServer::WaitForNewConnectionRaw(long timeout) { - if(SelectRead(timeout) == kTimeout) { return NULL; } + if (SelectRead(timeout) == kTimeout) { + return NULL; + } int fd = ::accept(m_socket, 0, 0); - if(fd < 0) { throw clSocketException("accept error: " + error()); } + if (fd < 0) { + throw clSocketException("accept error: " + error()); + } return new clSocketBase(fd); } diff --git a/CodeLite/StdToWX.cpp b/CodeLite/StdToWX.cpp index 25daa33dfd..ca2830d326 100644 --- a/CodeLite/StdToWX.cpp +++ b/CodeLite/StdToWX.cpp @@ -3,14 +3,11 @@ void StdToWX::Trim(std::string& str, bool fromRight) { static const std::string trimString = " \t\r\n"; - if(fromRight) { + if (fromRight) { str.erase(str.find_last_not_of(trimString) + 1); } else { str.erase(0, str.find_first_not_of(trimString)); } } -wxArrayString StdToWX::ToArrayString(const std::vector& vec) -{ - return { vec.size(), vec.data() }; -} +wxArrayString StdToWX::ToArrayString(const std::vector& vec) { return {vec.size(), vec.data()}; } diff --git a/CodeLite/archive.cpp b/CodeLite/archive.cpp index 778bf16f5e..d58c9a0454 100644 --- a/CodeLite/archive.cpp +++ b/CodeLite/archive.cpp @@ -72,7 +72,7 @@ bool Archive::Write(const wxString& name, SerializedObject* obj) { Archive arch; wxXmlNode* node = XmlUtils::FindNodeByName(m_root, wxT("SerializedObject"), name); - if(node) { + if (node) { m_root->RemoveChild(node); delete node; } @@ -90,7 +90,7 @@ bool Archive::Read(const wxString& name, SerializedObject* obj) { Archive arch; wxXmlNode* node = XmlUtils::FindNodeByName(m_root, wxT("SerializedObject"), name); - if(node) { + if (node) { arch.SetXmlNode(node); obj->DeSerialize(arch); return true; @@ -100,7 +100,7 @@ bool Archive::Read(const wxString& name, SerializedObject* obj) bool Archive::Write(const wxString& name, const wxArrayString& arr) { - if(!m_root) { + if (!m_root) { return false; } wxXmlNode* node = new wxXmlNode(NULL, wxXML_ELEMENT_NODE, wxT("wxArrayString")); @@ -108,7 +108,7 @@ bool Archive::Write(const wxString& name, const wxArrayString& arr) node->AddAttribute(wxT("Name"), name); // add an entry for each wxString in the array - for(size_t i = 0; i < arr.GetCount(); i++) { + for (size_t i = 0; i < arr.GetCount(); i++) { wxXmlNode* child = new wxXmlNode(NULL, wxXML_ELEMENT_NODE, wxT("wxString")); node->AddChild(child); child->AddAttribute(wxT("Value"), arr.Item(i)); @@ -118,7 +118,7 @@ bool Archive::Write(const wxString& name, const wxArrayString& arr) bool Archive::Write(const wxString& name, std::vector& _vTabInfoArr) { - if(!m_root) { + if (!m_root) { return false; } wxXmlNode* node = new wxXmlNode(NULL, wxXML_ELEMENT_NODE, wxT("TabInfoArray")); @@ -138,7 +138,7 @@ bool Archive::Write(const wxString& name, std::vector& _vTabInfoArr) bool Archive::Write(const wxString& name, std::vector& _vInt) { - if(!m_root) { + if (!m_root) { return false; } wxXmlNode* node = new wxXmlNode(NULL, wxXML_ELEMENT_NODE, wxT("IntVector")); @@ -156,7 +156,7 @@ bool Archive::Write(const wxString& name, std::vector& _vInt) bool Archive::Write(const wxString& name, const StringMap& str_map) { - if(!m_root) { + if (!m_root) { return false; } @@ -177,7 +177,7 @@ bool Archive::Write(const wxString& name, const StringMap& str_map) #if wxUSE_GUI bool Archive::Write(const wxString& name, wxSize size) { - if(!m_root) { + if (!m_root) { return false; } @@ -195,7 +195,7 @@ bool Archive::Write(const wxString& name, wxSize size) } bool Archive::Write(const wxString& name, wxPoint pt) { - if(!m_root) { + if (!m_root) { return false; } @@ -215,17 +215,17 @@ bool Archive::Write(const wxString& name, wxPoint pt) bool Archive::Read(const wxString& name, wxArrayString& arr) { - if(!m_root) { + if (!m_root) { return false; } wxXmlNode* node = XmlUtils::FindNodeByName(m_root, wxT("wxArrayString"), name); - if(node) { + if (node) { // fill the output array with the values arr.Clear(); wxXmlNode* child = node->GetChildren(); - while(child) { - if(child->GetName() == wxT("wxString")) { + while (child) { + if (child->GetName() == wxT("wxString")) { wxString value; value = child->GetAttribute(wxT("Value"), wxEmptyString); arr.Add(value); @@ -239,18 +239,18 @@ bool Archive::Read(const wxString& name, wxArrayString& arr) bool Archive::Read(const wxString& name, std::vector& _vTabInfoArr) { - if(!m_root) { + if (!m_root) { return false; } Archive arch; wxXmlNode* node = XmlUtils::FindNodeByName(m_root, wxT("TabInfoArray"), name); - if(node) { + if (node) { // fill the output array with the values _vTabInfoArr.clear(); wxXmlNode* child = node->GetChildren(); - while(child) { - if(child->GetName() == wxT("TabInfo")) { + while (child) { + if (child->GetName() == wxT("TabInfo")) { arch.SetXmlNode(child); TabInfo oTabInfo; oTabInfo.DeSerialize(arch); @@ -265,20 +265,20 @@ bool Archive::Read(const wxString& name, std::vector& _vTabInfoArr) bool Archive::Read(const wxString& name, std::vector& _vInt) { - if(!m_root) { + if (!m_root) { return false; } wxXmlNode* node = XmlUtils::FindNodeByName(m_root, wxT("IntVector"), name); - if(node) { + if (node) { // fill the output array with the values _vInt.clear(); wxXmlNode* child = node->GetChildren(); - while(child) { - if(child->GetName() == wxT("IntVectorItem")) { + while (child) { + if (child->GetName() == wxT("IntVectorItem")) { long value; wxString stringvalue = child->GetAttribute(wxT("Value"), wxEmptyString); - if(stringvalue.ToLong(&value)) { + if (stringvalue.ToLong(&value)) { _vInt.push_back(value); } } @@ -291,17 +291,17 @@ bool Archive::Read(const wxString& name, std::vector& _vInt) bool Archive::Read(const wxString& name, StringMap& str_map) { - if(!m_root) { + if (!m_root) { return false; } wxXmlNode* node = XmlUtils::FindNodeByName(m_root, wxT("StringMap"), name); - if(node) { + if (node) { // fill the output array with the values str_map.clear(); wxXmlNode* child = node->GetChildren(); - while(child) { - if(child->GetName() == wxT("MapEntry")) { + while (child) { + if (child->GetName() == wxT("MapEntry")) { wxString value; wxString key; key = child->GetAttribute(wxT("Key"), wxEmptyString); @@ -317,12 +317,12 @@ bool Archive::Read(const wxString& name, StringMap& str_map) #if wxUSE_GUI bool Archive::Read(const wxString& name, wxSize& size) { - if(!m_root) { + if (!m_root) { return false; } wxXmlNode* node = XmlUtils::FindNodeByName(m_root, wxT("wxSize"), name); - if(node) { + if (node) { long v; wxString value; value = node->GetAttribute(wxT("x"), wxEmptyString); @@ -339,12 +339,12 @@ bool Archive::Read(const wxString& name, wxSize& size) bool Archive::Read(const wxString& name, wxPoint& pt) { - if(!m_root) { + if (!m_root) { return false; } wxXmlNode* node = XmlUtils::FindNodeByName(m_root, wxT("wxPoint"), name); - if(node) { + if (node) { long v; wxString value; value = node->GetAttribute(wxT("x"), wxEmptyString); @@ -364,13 +364,13 @@ bool Archive::Write(const wxString& name, int value) { return WriteSimple(value, bool Archive::Read(const wxString& name, int& value) { - if(!m_root) { + if (!m_root) { return false; } long v; bool res = ReadSimple(v, wxT("int"), name); - if(res) { + if (res) { value = v; } return res; @@ -386,7 +386,7 @@ bool Archive::Read(const wxString& name, bool& value) { long v; bool res = ReadSimple(v, wxT("bool"), name); - if(res) { + if (res) { v == 0 ? value = false : value = true; } return res; @@ -394,7 +394,7 @@ bool Archive::Read(const wxString& name, bool& value) bool Archive::Write(const wxString& name, const wxString& str) { - if(!m_root) { + if (!m_root) { return false; } wxXmlNode* node = new wxXmlNode(NULL, wxXML_ELEMENT_NODE, wxT("wxString")); @@ -406,7 +406,7 @@ bool Archive::Write(const wxString& name, const wxString& str) bool Archive::WriteCData(const wxString& name, const wxString& str) { - if(!m_root) { + if (!m_root) { return false; } @@ -420,12 +420,12 @@ bool Archive::WriteCData(const wxString& name, const wxString& str) bool Archive::ReadCData(const wxString& name, wxString& value) { - if(!m_root) { + if (!m_root) { return false; } wxXmlNode* node = XmlUtils::FindNodeByName(m_root, wxT("CData"), name); - if(node) { + if (node) { // get the content node value = node->GetNodeContent(); value.Trim().Trim(false); @@ -436,11 +436,11 @@ bool Archive::ReadCData(const wxString& name, wxString& value) bool Archive::Read(const wxString& name, wxString& value) { - if(!m_root) { + if (!m_root) { return false; } wxXmlNode* node = XmlUtils::FindNodeByName(m_root, wxT("wxString"), name); - if(node) { + if (node) { value = node->GetAttribute(wxT("Value"), value); return true; } @@ -451,7 +451,7 @@ bool Archive::Read(const wxString& name, size_t& value) { long v = 0; bool res = Read(name, v); - if(res) { + if (res) { value = v; } return res; @@ -461,7 +461,7 @@ bool Archive::Read(const wxString& name, wxFileName& fileName) { wxString value; bool res = Read(name, value); - if(res) { + if (res) { fileName = wxFileName(value); } return res; @@ -475,7 +475,7 @@ void Archive::SetXmlNode(wxXmlNode* node) { m_root = node; } bool Archive::WriteSimple(long value, const wxString& typeName, const wxString& name) { - if(!m_root) + if (!m_root) return false; wxString propValue; @@ -490,12 +490,12 @@ bool Archive::WriteSimple(long value, const wxString& typeName, const wxString& bool Archive::ReadSimple(long& value, const wxString& typeName, const wxString& name) { - if(!m_root) + if (!m_root) return false; value = 0; wxXmlNode* node = XmlUtils::FindNodeByName(m_root, typeName, name); - if(node) { + if (node) { wxString val = node->GetAttribute(wxT("Value"), wxEmptyString); val.ToLong(&value); return true; @@ -506,17 +506,17 @@ bool Archive::ReadSimple(long& value, const wxString& typeName, const wxString& #if wxUSE_GUI bool Archive::Read(const wxString& name, wxColour& colour) { - if(!m_root) { + if (!m_root) { return false; } wxXmlNode* node = XmlUtils::FindNodeByName(m_root, wxT("wxColour"), name); wxString value; - if(node) { + if (node) { value = node->GetAttribute(wxT("Value"), wxEmptyString); } - if(value.IsEmpty()) { + if (value.IsEmpty()) { return false; } @@ -525,7 +525,7 @@ bool Archive::Read(const wxString& name, wxColour& colour) } bool Archive::Write(const wxString& name, const wxColour& colour) { - if(!m_root) { + if (!m_root) { return false; } wxXmlNode* node = new wxXmlNode(NULL, wxXML_ELEMENT_NODE, wxT("wxColour")); @@ -538,7 +538,7 @@ bool Archive::Write(const wxString& name, const wxColour& colour) bool Archive::Write(const wxString& name, const wxStringMap_t& stringMap) { - if(!m_root) { + if (!m_root) { return false; } @@ -558,17 +558,17 @@ bool Archive::Write(const wxString& name, const wxStringMap_t& stringMap) bool Archive::Read(const wxString& name, wxStringMap_t& stringMap) { - if(!m_root) { + if (!m_root) { return false; } wxXmlNode* node = XmlUtils::FindNodeByName(m_root, wxT("std_string_map"), name); - if(node) { + if (node) { // fill the output array with the values stringMap.clear(); wxXmlNode* child = node->GetChildren(); - while(child) { - if(child->GetName() == wxT("MapEntry")) { + while (child) { + if (child->GetName() == wxT("MapEntry")) { wxString value; wxString key; key = child->GetAttribute(wxT("Key"), wxEmptyString); @@ -584,17 +584,17 @@ bool Archive::Read(const wxString& name, wxStringMap_t& stringMap) bool Archive::Read(const wxString& name, wxStringSet_t& s) { - if(!m_root) { + if (!m_root) { return false; } wxXmlNode* node = XmlUtils::FindNodeByName(m_root, wxT("std_string_set"), name); - if(node) { + if (node) { // fill the output array with the values s.clear(); wxXmlNode* child = node->GetChildren(); - while(child) { - if(child->GetName() == wxT("SetEntry")) { + while (child) { + if (child->GetName() == wxT("SetEntry")) { wxString value; value = child->GetNodeContent(); s.insert(value); @@ -608,7 +608,7 @@ bool Archive::Read(const wxString& name, wxStringSet_t& s) bool Archive::Write(const wxString& name, const wxStringSet_t& s) { - if(!m_root) { + if (!m_root) { return false; } @@ -629,7 +629,7 @@ bool Archive::Read(const wxString& name, wxFont& font, const wxFont& defaultFont { wxString strFont; bool res = Read(name, strFont); - if(!res || strFont.IsEmpty()) { + if (!res || strFont.IsEmpty()) { font = defaultFont; return false; } diff --git a/CodeLite/clAnagram.cpp b/CodeLite/clAnagram.cpp index 81f8307d08..ad9ddd7434 100644 --- a/CodeLite/clAnagram.cpp +++ b/CodeLite/clAnagram.cpp @@ -12,7 +12,9 @@ clAnagram::clAnagram(const wxString& needle, size_t flags) bool clAnagram::MatchesInOrder(const wxString& haystack) const { - if(m_needle.IsEmpty()) { return true; } + if (m_needle.IsEmpty()) { + return true; + } size_t index = 0; size_t maxIndex = m_needle.size(); for (wxChar ch : haystack) { @@ -44,7 +46,7 @@ void clAnagram::Reset(const wxString& needle, size_t flags) m_charCounts.clear(); for (wxChar ch : m_needle) { - if(m_charCounts.count(ch) == 0) { + if (m_charCounts.count(ch) == 0) { m_charCounts[ch] = 1; } else { m_charCounts[ch]++; diff --git a/CodeLite/clBitset.cpp b/CodeLite/clBitset.cpp index 2e4c46bec7..4b40eb8df5 100644 --- a/CodeLite/clBitset.cpp +++ b/CodeLite/clBitset.cpp @@ -3,11 +3,11 @@ #include #define CHECK_SIZE_RET_FALSE(pos) \ - if(pos >= BITS_SIZE) \ + if (pos >= BITS_SIZE) \ return false #define CHECK_SIZE_RET(pos) \ - if(pos >= BITS_SIZE) \ + if (pos >= BITS_SIZE) \ return clBitset::clBitset() { memset(bits, 0, sizeof(bits)); } @@ -27,7 +27,7 @@ bool clBitset::test(size_t pos) const wxString clBitset::to_string() const { wxString str; - for(auto ch : bits) { + for (auto ch : bits) { str << (ch == 1 ? "1" : "0"); } return str; @@ -35,10 +35,10 @@ wxString clBitset::to_string() const void clBitset::from_string(const wxString& str) { - if(str.length() < BITS_SIZE) + if (str.length() < BITS_SIZE) return; - for(size_t i = 0; i < BITS_SIZE; ++i) { + for (size_t i = 0; i < BITS_SIZE; ++i) { bits[i] = (str[i] == '1' ? 1 : 0); } } diff --git a/CodeLite/clDebuggerBreakpoint.cpp b/CodeLite/clDebuggerBreakpoint.cpp index 244da52982..51ed4b31eb 100644 --- a/CodeLite/clDebuggerBreakpoint.cpp +++ b/CodeLite/clDebuggerBreakpoint.cpp @@ -8,16 +8,16 @@ clDebuggerBreakpoint::clDebuggerBreakpoint(const clDebuggerBreakpoint& BI) { - if(this == &BI) { + if (this == &BI) { return; } // call operator= *this = BI; - if(!is_windows || !file.Contains("/")) { + if (!is_windows || !file.Contains("/")) { // Normalize the file name - if(!file.IsEmpty()) { + if (!file.IsEmpty()) { wxFileName fn(file); fn.Normalize(wxPATH_NORM_ALL & ~wxPATH_NORM_LONG); file = fn.GetFullPath(); @@ -27,7 +27,7 @@ clDebuggerBreakpoint::clDebuggerBreakpoint(const clDebuggerBreakpoint& BI) clDebuggerBreakpoint& clDebuggerBreakpoint::operator=(const clDebuggerBreakpoint& BI) { - if(this == &BI) { + if (this == &BI) { return *this; } diff --git a/CodeLite/clDirChanger.hpp b/CodeLite/clDirChanger.hpp index 1a18e753dd..501d3c1909 100644 --- a/CodeLite/clDirChanger.hpp +++ b/CodeLite/clDirChanger.hpp @@ -15,7 +15,7 @@ class WXDLLIMPEXP_CL clDirChanger clDirChanger(const wxString& newDirectory) { m_oldDirectory = ::wxGetCwd(); - if(!newDirectory.IsEmpty()) { + if (!newDirectory.IsEmpty()) { ::wxSetWorkingDirectory(newDirectory); } } diff --git a/CodeLite/clEditorConfig.cpp b/CodeLite/clEditorConfig.cpp index aa3da54fac..6e0f4ea3ad 100644 --- a/CodeLite/clEditorConfig.cpp +++ b/CodeLite/clEditorConfig.cpp @@ -15,19 +15,19 @@ bool clEditorConfig::LoadForFile(const wxFileName& filename, wxFileName& editorC editorConfigFile = wxFileName(filename.GetPath(), ".editorconfig"); bool foundFile = false; - while(editorConfigFile.GetDirCount()) { - if(editorConfigFile.FileExists()) { + while (editorConfigFile.GetDirCount()) { + if (editorConfigFile.FileExists()) { foundFile = true; break; } editorConfigFile.RemoveLastDir(); } - if(!foundFile) + if (!foundFile) return false; wxString content; - if(!FileUtils::ReadFileContent(editorConfigFile, content)) { + if (!FileUtils::ReadFileContent(editorConfigFile, content)) { clDEBUG() << "Failed to read file:" << editorConfigFile << clEndl; return false; } @@ -44,11 +44,11 @@ bool clEditorConfig::LoadForFile(const wxFileName& filename, wxFileName& editorC strLine.Trim().Trim(false); - if(strLine.IsEmpty()) + if (strLine.IsEmpty()) continue; // Process the line - if(strLine.StartsWith("[") && strLine.EndsWith("]")) { + if (strLine.StartsWith("[") && strLine.EndsWith("]")) { strLine.RemoveLast().Remove(0, 1); // remove the [] clEditorConfigSection section; section.patterns = ProcessSection(strLine); @@ -116,7 +116,7 @@ struct clEditorConfigTreeNode { private: void DoGetLeaves(clEditorConfigTreeNode* node, clEditorConfigTreeNode::Vec_t& leaves) { - if(node->children.empty()) { + if (node->children.empty()) { // leaf node leaves.push_back(node); } else { @@ -131,7 +131,7 @@ struct clEditorConfigTreeNode { */ void DoGetPatterns(clEditorConfigTreeNode* node, wxArrayString& patterns, const wxString& curpattern) { - if(node->children.empty()) { + if (node->children.empty()) { // leaf node patterns.Add(curpattern + node->data); } else { @@ -146,7 +146,7 @@ struct clEditorConfigTreeNode { */ void DoAddToAllLeaves(clEditorConfigTreeNode* node, const wxString& pattern) { - if(node->children.empty()) { + if (node->children.empty()) { // leaf node node->data << pattern; } else { @@ -172,12 +172,12 @@ wxArrayString clEditorConfig::ProcessSection(wxString& strLine) trees.push_back(tree); wxString curpattern; - while(!strLine.IsEmpty()) { - switch(state) { + while (!strLine.IsEmpty()) { + switch (state) { case kEC_STATE_NORMAL: { wxChar ch = strLine.at(0); strLine.Remove(0, 1); - switch(ch) { + switch (ch) { case '{': state = kEC_STATE_IN_CURLYGRP; break; @@ -186,7 +186,7 @@ wxArrayString clEditorConfig::ProcessSection(wxString& strLine) break; case ',': // new pattern - if(!curpattern.IsEmpty()) { + if (!curpattern.IsEmpty()) { tree->Add(curpattern); tree = new clEditorConfigTreeNode; @@ -202,14 +202,14 @@ wxArrayString clEditorConfig::ProcessSection(wxString& strLine) } case kEC_STATE_IN_CURLYGRP: { // if we got something so far, add it before we continue - if(!curpattern.IsEmpty()) { + if (!curpattern.IsEmpty()) { tree->Add(curpattern); curpattern.clear(); } // read the buffer until we hit the closing brace wxString buffer; - if(!ReadUntil('}', strLine, buffer)) { + if (!ReadUntil('}', strLine, buffer)) { return wxArrayString(); } state = kEC_STATE_NORMAL; @@ -219,7 +219,7 @@ wxArrayString clEditorConfig::ProcessSection(wxString& strLine) } case kEC_STATE_IN_SQUAREGRP: { wxString buffer; - if(!ReadUntil(']', strLine, buffer)) { + if (!ReadUntil(']', strLine, buffer)) { return wxArrayString(); } state = kEC_STATE_NORMAL; @@ -229,7 +229,7 @@ wxArrayString clEditorConfig::ProcessSection(wxString& strLine) } // Remainder - if(!curpattern.IsEmpty()) { + if (!curpattern.IsEmpty()) { tree->Add(curpattern); } @@ -256,42 +256,42 @@ void clEditorConfig::ProcessDirective(wxString& strLine) key.Trim().Trim(false); value.Trim().Trim(false); - if(key == "indent_style") { + if (key == "indent_style") { cursection->SetIndentStyle(value.Lower()); - } else if(key == "indent_size") { + } else if (key == "indent_size") { long lv = 4; value.ToCLong(&lv); cursection->SetIndentSize(lv); - } else if(key == "tab_width") { + } else if (key == "tab_width") { long lv = 4; value.ToCLong(&lv); cursection->SetTabWidth(lv); - } else if(key == "charset") { + } else if (key == "charset") { cursection->SetCharset(value.Lower()); - } else if(key == "trim_trailing_whitespace") { + } else if (key == "trim_trailing_whitespace") { cursection->SetTrimTrailingWhitespace(IS_TRUE(value)); - } else if(key == "insert_final_newline") { + } else if (key == "insert_final_newline") { cursection->SetInsertFinalNewline(IS_TRUE(value)); - } else if(key == "end_of_line") { + } else if (key == "end_of_line") { cursection->SetEndOfLine(value.Lower()); - } else if(key == "root") { + } else if (key == "root") { m_rootFileFound = IS_TRUE(value); } } bool clEditorConfig::ReadUntil(wxChar delim, wxString& strLine, wxString& output) { - while(!strLine.IsEmpty()) { + while (!strLine.IsEmpty()) { wxChar ch = strLine.at(0); strLine.Remove(0, 1); - if(ch == delim) { + if (ch == delim) { return true; } else { output << ch; @@ -303,7 +303,7 @@ bool clEditorConfig::ReadUntil(wxChar delim, wxString& strLine, wxString& output bool clEditorConfig::GetSectionForFile(const wxFileName& filename, clEditorConfigSection& section) { wxFileName editorConfigFile; - if(!LoadForFile(filename, editorConfigFile)) + if (!LoadForFile(filename, editorConfigFile)) return false; section = clEditorConfigSection(); section.filename = editorConfigFile; @@ -315,27 +315,27 @@ bool clEditorConfig::GetSectionForFile(const wxFileName& filename, clEditorConfi wxString fullpath = filename.GetFullPath(wxPATH_UNIX); wxString fullname = filename.GetFullName(); - if((is_wild && ::wxMatchWild(pattern, fullpath, false)) || (!is_wild && fullname == pattern)) { + if ((is_wild && ::wxMatchWild(pattern, fullpath, false)) || (!is_wild && fullname == pattern)) { match_found = true; - if(sec.IsCharsetSet()) { + if (sec.IsCharsetSet()) { section.SetCharset(sec.GetCharset()); } - if(sec.IsIndentSizeSet()) { + if (sec.IsIndentSizeSet()) { section.SetIndentSize(sec.GetIndentSize()); } - if(sec.IsIndentStyleSet()) { + if (sec.IsIndentStyleSet()) { section.SetIndentStyle(sec.GetIndentStyle()); } - if(sec.IsInsertFinalNewlineSet()) { + if (sec.IsInsertFinalNewlineSet()) { section.SetInsertFinalNewline(sec.IsInsertFinalNewline()); } - if(sec.IsSetEndOfLineSet()) { + if (sec.IsSetEndOfLineSet()) { section.SetEndOfLine(sec.GetEndOfLine()); } - if(sec.IsTabWidthSet()) { + if (sec.IsTabWidthSet()) { section.SetTabWidth(sec.GetTabWidth()); } - if(sec.IsTrimTrailingWhitespaceSet()) { + if (sec.IsTrimTrailingWhitespaceSet()) { section.SetTrimTrailingWhitespace(sec.IsTrimTrailingWhitespace()); } break; @@ -344,7 +344,7 @@ bool clEditorConfig::GetSectionForFile(const wxFileName& filename, clEditorConfi } // Print the match to the log file - if(match_found) { + if (match_found) { section.PrintToLog(); } return match_found; @@ -355,25 +355,25 @@ void clEditorConfigSection::PrintToLog() LOG_IF_TRACE { clDEBUG1() << ".editorconfig (" << filename << ") :" << clEndl; - if(IsCharsetSet()) { + if (IsCharsetSet()) { clDEBUG1() << "charset:" << GetCharset() << clEndl; } - if(IsIndentSizeSet()) { + if (IsIndentSizeSet()) { clDEBUG1() << "indent_size:" << GetIndentSize() << clEndl; } - if(IsIndentStyleSet()) { + if (IsIndentStyleSet()) { clDEBUG1() << "indent_style:" << GetIndentStyle() << clEndl; } - if(IsInsertFinalNewlineSet()) { + if (IsInsertFinalNewlineSet()) { clDEBUG1() << "insert_final_newline:" << IsInsertFinalNewline() << clEndl; } - if(IsSetEndOfLineSet()) { + if (IsSetEndOfLineSet()) { clDEBUG1() << "end_of_line:" << GetEndOfLine() << clEndl; } - if(IsTabWidthSet()) { + if (IsTabWidthSet()) { clDEBUG1() << "tab_width:" << GetTabWidth() << clEndl; } - if(IsTrimTrailingWhitespaceSet()) { + if (IsTrimTrailingWhitespaceSet()) { clDEBUG1() << "trim_trailing_whitespace:" << IsTrimTrailingWhitespace() << clEndl; } } diff --git a/CodeLite/clEditorConfig.h b/CodeLite/clEditorConfig.h index 9502700438..814d17b4df 100644 --- a/CodeLite/clEditorConfig.h +++ b/CodeLite/clEditorConfig.h @@ -44,15 +44,15 @@ class WXDLLIMPEXP_CL clEditorConfigSection , insert_final_newline(false) { } - + /** * @brief print this section properties to the log file */ void PrintToLog(); - - void SetFilename(const wxFileName& filename) {this->filename = filename;} - const wxFileName& GetFilename() const {return filename;} - + + void SetFilename(const wxFileName& filename) { this->filename = filename; } + const wxFileName& GetFilename() const { return filename; } + void SetCharset(const wxString& charset) { this->charset = charset; diff --git a/CodeLite/clEnvironment.cpp b/CodeLite/clEnvironment.cpp index 7e9ce30867..c278aa4c79 100644 --- a/CodeLite/clEnvironment.cpp +++ b/CodeLite/clEnvironment.cpp @@ -23,31 +23,31 @@ static const wxString VARIABLE_REG_EXPR = R"#(\$[\(\{]?([\w]+)[\\/\)\}]?)#"; /// pattern -> `${HOME}` std::vector> FindVariablesInString(wxString str) { - wxRegEx re{ VARIABLE_REG_EXPR }; + wxRegEx re{VARIABLE_REG_EXPR}; std::vector> result; bool cont = true; - while(cont) { + while (cont) { cont = false; - if(re.Matches(str)) { + if (re.Matches(str)) { wxString pattern; wxString varname; size_t offset = wxString::npos; { size_t start, len; - if(re.GetMatch(&start, &len, 0)) { + if (re.GetMatch(&start, &len, 0)) { pattern = str.Mid(start, len); offset = start + len; } } { size_t start, len; - if(re.GetMatch(&start, &len, 1)) { + if (re.GetMatch(&start, &len, 1)) { varname = str.Mid(start, len); } } - if(!varname.empty() && !pattern.empty()) { - result.push_back({ varname, pattern }); + if (!varname.empty() && !pattern.empty()) { + result.push_back({varname, pattern}); cont = true; str = str.Mid(offset); } @@ -61,27 +61,27 @@ std::vector> FindVariablesInString(wxString str) clEnvironment::clEnvironment() { wxXmlDocument doc; - wxFileName config{ clStandardPaths::Get().GetUserDataDir(), "environment_variables.xml" }; + wxFileName config{clStandardPaths::Get().GetUserDataDir(), "environment_variables.xml"}; config.AppendDir("config"); - if(!doc.Load(config.GetFullPath())) + if (!doc.Load(config.GetFullPath())) return; wxXmlNode* node = XmlUtils::FindFirstByTagName(doc.GetRoot(), "ArchiveObject"); - if(node) { + if (node) { Archive arc; arc.SetXmlNode(node); wxString activeSet; clEnvList_t list; - if(arc.Read("m_activeSet", activeSet)) { + if (arc.Read("m_activeSet", activeSet)) { wxStringMap_t global_env_map; - if(arc.Read("m_envVarSets", global_env_map) && global_env_map.count(activeSet)) { + if (arc.Read("m_envVarSets", global_env_map) && global_env_map.count(activeSet)) { wxString envstr = global_env_map[activeSet]; list = FileUtils::CreateEnvironment(envstr); } } - if(!list.empty()) { + if (!list.empty()) { ApplyFromList(&list); } } @@ -95,13 +95,13 @@ clEnvironment::clEnvironment(const clEnvList_t* envlist) clEnvironment::~clEnvironment() { - for(const auto& p : m_old_env) { - if(p.second.IsNull()) { + for (const auto& p : m_old_env) { + if (p.second.IsNull()) { // remove this environment ::wxUnsetEnv(p.first); } else { wxString strvalue; - if(p.second.GetAs(&strvalue)) { + if (p.second.GetAs(&strvalue)) { ::wxSetEnv(p.first, strvalue); } } @@ -110,29 +110,29 @@ clEnvironment::~clEnvironment() void clEnvironment::ApplyFromList(const clEnvList_t* envlist) { - if(!envlist) { + if (!envlist) { return; } std::unordered_set V; // keep track of the previous values - for(const auto& [varname, varvalue] : *envlist) { + for (const auto& [varname, varvalue] : *envlist) { const auto& [iter, succeeded] = V.insert(varname); - if(succeeded) { + if (succeeded) { wxString old_value; - if(wxGetEnv(varname, &old_value)) { - m_old_env.push_back({ varname, old_value }); + if (wxGetEnv(varname, &old_value)) { + m_old_env.push_back({varname, old_value}); } else { - m_old_env.push_back({ varname, wxAny{} }); + m_old_env.push_back({varname, wxAny{}}); } } } - for(auto [varname, varvalue] : *envlist) { + for (auto [varname, varvalue] : *envlist) { auto vars = FindVariablesInString(varvalue); - for(const auto& p : vars) { + for (const auto& p : vars) { // the variable name, e.g. "HOME" const wxString& name = p.first; diff --git a/CodeLite/clFileName.cpp b/CodeLite/clFileName.cpp index dc23043984..0db62a984f 100644 --- a/CodeLite/clFileName.cpp +++ b/CodeLite/clFileName.cpp @@ -22,15 +22,15 @@ const wxString& __uname() static wxString uname_output; static bool firstTime = true; - if(firstTime) { + if (firstTime) { firstTime = false; wxFileName uname; - if(FileUtils::FindExe("uname", uname)) { + if (FileUtils::FindExe("uname", uname)) { firstTime = false; clDEBUG() << "Running `uname -s`..." << endl; wxString cmd; cmd << uname.GetFullPath(); - if(cmd.Contains(" ")) { + if (cmd.Contains(" ")) { cmd.Prepend("\"").Append("\""); } cmd << " -s"; @@ -65,15 +65,15 @@ clFileName::clFileName(const wxString& dir, const wxString& name) wxString clFileName::FromCygwin(const wxString& fullpath) { - if(!is_cygwin_env()) { + if (!is_cygwin_env()) { return fullpath; } wxString tmppath; - if(fullpath.StartsWith("/cygdrive/")) { + if (fullpath.StartsWith("/cygdrive/")) { // "/cygdrive/c/Users/eran/devl/codelite/CodeLite/clFileName.cpp" tmppath = fullpath; tmppath.Replace("/cygdrive/", ""); - if(tmppath.IsEmpty()) { + if (tmppath.IsEmpty()) { return fullpath; } @@ -91,17 +91,17 @@ wxString clFileName::FromCygwin(const wxString& fullpath) wxString clFileName::ToCygwin(const wxString& fullpath) { return ToCygwin(wxFileName(fullpath)); } wxString clFileName::ToCygwin(const wxFileName& fullpath) { - if(!is_cygwin_env()) { + if (!is_cygwin_env()) { return fullpath.GetFullPath(); } wxFileName fn(fullpath); - if(fn.GetVolume().empty()) { + if (fn.GetVolume().empty()) { // non windows path return fullpath.GetFullPath(); } wxString drive = fn.GetVolume(); wxString cygwin_path = fn.GetFullPath(); - if(cygwin_path.size() < 2) { + if (cygwin_path.size() < 2) { return fullpath.GetFullPath(); } diff --git a/CodeLite/clFileSystemEvent.h b/CodeLite/clFileSystemEvent.h index e27a6e8e2c..00a8da72a1 100644 --- a/CodeLite/clFileSystemEvent.h +++ b/CodeLite/clFileSystemEvent.h @@ -43,7 +43,7 @@ class WXDLLIMPEXP_CL clFileSystemEvent : public clCommandEvent protected: void SetBit(bool b, size_t bit) { - if(b) { + if (b) { m_flags |= bit; } else { m_flags &= ~bit; diff --git a/CodeLite/clFileSystemWatcher.cpp b/CodeLite/clFileSystemWatcher.cpp index 19ee91d418..7ddddc219d 100644 --- a/CodeLite/clFileSystemWatcher.cpp +++ b/CodeLite/clFileSystemWatcher.cpp @@ -38,7 +38,7 @@ clFileSystemWatcher::~clFileSystemWatcher() void clFileSystemWatcher::SetFile(const wxFileName& filename) { #if CL_FSW_USE_TIMER - if(filename.Exists()) { + if (filename.Exists()) { m_files.clear(); File f; f.filename = filename; @@ -69,7 +69,7 @@ void clFileSystemWatcher::Start() void clFileSystemWatcher::Stop() { #if CL_FSW_USE_TIMER - if(m_timer) { + if (m_timer) { m_timer->Stop(); } wxDELETE(m_timer); @@ -94,10 +94,10 @@ void clFileSystemWatcher::OnTimer(wxTimerEvent& event) std::set nonExistingFiles; for (const auto& [_, f] : m_files) { const wxFileName& fn = f.filename; - if(!fn.Exists()) { + if (!fn.Exists()) { // fire file not found event - if(GetOwner()) { + if (GetOwner()) { clFileSystemEvent evt(wxEVT_FILE_NOT_FOUND); evt.SetPath(fn.GetFullPath()); GetOwner()->AddPendingEvent(evt); @@ -106,7 +106,7 @@ void clFileSystemWatcher::OnTimer(wxTimerEvent& event) // add the missing file to a set nonExistingFiles.insert(fn.GetFullPath()); } else { - + #ifdef __WXMSW__ size_t prev_value = f.file_size; size_t curr_value = FileUtils::GetFileSize(fn); @@ -115,9 +115,9 @@ void clFileSystemWatcher::OnTimer(wxTimerEvent& event) time_t curr_value = FileUtils::GetFileModificationTime(fn); #endif - if(prev_value != curr_value) { + if (prev_value != curr_value) { // Fire a modified event - if(GetOwner()) { + if (GetOwner()) { clFileSystemEvent evt(wxEVT_FILE_MODIFIED); evt.SetPath(fn.GetFullPath()); GetOwner()->AddPendingEvent(evt); @@ -140,7 +140,7 @@ void clFileSystemWatcher::OnTimer(wxTimerEvent& event) m_files.erase(fn); } - if(m_timer) { + if (m_timer) { m_timer->Start(FILE_CHECK_INTERVAL, true); } } @@ -149,10 +149,10 @@ void clFileSystemWatcher::OnTimer(wxTimerEvent& event) #if !CL_FSW_USE_TIMER void clFileSystemWatcher::OnFileModified(wxFileSystemWatcherEvent& event) { - if(event.GetChangeType() == wxFSW_EVENT_MODIFY) { + if (event.GetChangeType() == wxFSW_EVENT_MODIFY) { const wxFileName& modpath = event.GetPath(); - if(modpath == m_watchedFile) { - if(GetOwner()) { + if (modpath == m_watchedFile) { + if (GetOwner()) { clFileSystemEvent evt(wxEVT_FILE_MODIFIED); evt.SetPath(modpath.GetFullPath()); GetOwner()->AddPendingEvent(evt); @@ -165,7 +165,7 @@ void clFileSystemWatcher::OnFileModified(wxFileSystemWatcherEvent& event) void clFileSystemWatcher::RemoveFile(const wxFileName& filename) { #if CL_FSW_USE_TIMER - if(m_files.count(filename.GetFullPath())) { + if (m_files.count(filename.GetFullPath())) { m_files.erase(filename.GetFullPath()); } #endif diff --git a/CodeLite/clFilesCollector.h b/CodeLite/clFilesCollector.h index 73c5b7336c..23e51061f0 100644 --- a/CodeLite/clFilesCollector.h +++ b/CodeLite/clFilesCollector.h @@ -45,25 +45,38 @@ class WXDLLIMPEXP_CL clFilesScanner * @param excludeFolders list of folder to exclude from the search * @return number of files found */ - size_t Scan(const wxString& rootFolder, std::vector& filesOutput, const wxString& filespec = "*", - const wxString& excludeFilespec = "", const wxStringSet_t& excludeFolders = wxStringSet_t()); + size_t Scan(const wxString& rootFolder, + std::vector& filesOutput, + const wxString& filespec = "*", + const wxString& excludeFilespec = "", + const wxStringSet_t& excludeFolders = wxStringSet_t()); /** * @brief same as above, but accepts the ignore directories list in a spec format */ - size_t Scan(const wxString& rootFolder, std::vector& filesOutput, const wxString& filespec, - const wxString& excludeFilespec, const wxString& excludeFoldersSpec); - size_t Scan(const wxString& rootFolder, wxArrayString& filesOutput, const wxString& filespec, - const wxString& excludeFilespec, const wxString& excludeFoldersSpec); + size_t Scan(const wxString& rootFolder, + std::vector& filesOutput, + const wxString& filespec, + const wxString& excludeFilespec, + const wxString& excludeFoldersSpec); + size_t Scan(const wxString& rootFolder, + wxArrayString& filesOutput, + const wxString& filespec, + const wxString& excludeFilespec, + const wxString& excludeFoldersSpec); /** * @brief similar to the above, however, whenever a method is found, collect_cb is invoked */ - size_t Scan(const wxString& rootFolder, const wxString& filespec, const wxString& excludeFilespec, - const wxString& excludeFoldersSpec, std::function&& collect_cb); + size_t Scan(const wxString& rootFolder, + const wxString& filespec, + const wxString& excludeFilespec, + const wxString& excludeFoldersSpec, + std::function&& collect_cb); /** * @brief scan folder for files and folders. This function does not recurse into folders. Everything that matches * "matchSpec" will get collected. */ - size_t ScanNoRecurse(const wxString& rootFolder, clFilesScanner::EntryData::Vec_t& results, + size_t ScanNoRecurse(const wxString& rootFolder, + clFilesScanner::EntryData::Vec_t& results, const wxString& matchSpec = "*"); /** @@ -73,8 +86,10 @@ class WXDLLIMPEXP_CL clFilesScanner * it * @param on_file_cb called when a file is found. */ - void ScanWithCallbacks(const wxString& rootFolder, std::function&& on_folder_cb, - std::function&& on_file_cb, size_t search_flags = SF_DEFAULT); + void ScanWithCallbacks(const wxString& rootFolder, + std::function&& on_folder_cb, + std::function&& on_file_cb, + size_t search_flags = SF_DEFAULT); }; #endif // CLFILESCOLLECTOR_H diff --git a/CodeLite/clFilesFinder.cpp b/CodeLite/clFilesFinder.cpp index e8b27d5dcc..476454f060 100644 --- a/CodeLite/clFilesFinder.cpp +++ b/CodeLite/clFilesFinder.cpp @@ -131,8 +131,8 @@ wxArrayString clFilesFinder::CollectFiles(const wxString& root_folder, const clF clFilesScanner scanner; // Use the Scan method with file spec and exclusions. Skip hidden folders. - scanner.Scan(root_folder, files, options.file_spec, options.exclude_file_spec, - options.exclude_folders_spec + ",.*"); + scanner.Scan( + root_folder, files, options.file_spec, options.exclude_file_spec, options.exclude_folders_spec + ",.*"); return files; } diff --git a/CodeLite/clFontHelper.cpp b/CodeLite/clFontHelper.cpp index 4a505fcbe5..edc684414d 100644 --- a/CodeLite/clFontHelper.cpp +++ b/CodeLite/clFontHelper.cpp @@ -5,7 +5,8 @@ wxFont clFontHelper::FromString(const wxString& str) { wxArrayString parts = ::wxStringTokenize(str, ";", wxTOKEN_STRTOK); - if(parts.size() != 5) return wxNullFont; + if (parts.size() != 5) + return wxNullFont; long iPointSize, iFamily, iWeight, iStyle; wxString facename = parts.Item(0); @@ -22,7 +23,7 @@ wxFont clFontHelper::FromString(const wxString& str) wxString clFontHelper::ToString(const wxFont& font) { - if(!font.IsOk()) { + if (!font.IsOk()) { return ""; } wxString str; diff --git a/CodeLite/clINIParser.cpp b/CodeLite/clINIParser.cpp index 784020bc58..70fbb9518c 100644 --- a/CodeLite/clINIParser.cpp +++ b/CodeLite/clINIParser.cpp @@ -231,8 +231,9 @@ const clINISection& clINIParser::operator[](const char* section) const const clINISection& clINIParser::operator[](const wxString& section_name) const { - auto where = std::find_if(m_sections.begin(), m_sections.end(), - [§ion_name](const clINISection& d) -> bool { return d.GetName() == section_name; }); + auto where = std::find_if(m_sections.begin(), m_sections.end(), [§ion_name](const clINISection& d) -> bool { + return d.GetName() == section_name; + }); if (where == m_sections.end()) { return clNullINISection; } @@ -241,7 +242,8 @@ const clINISection& clINIParser::operator[](const wxString& section_name) const bool clINIParser::HasSection(const wxString& section_name) const { - auto where = std::find_if(m_sections.begin(), m_sections.end(), - [§ion_name](const clINISection& d) -> bool { return d.GetName() == section_name; }); + auto where = std::find_if(m_sections.begin(), m_sections.end(), [§ion_name](const clINISection& d) -> bool { + return d.GetName() == section_name; + }); return where != m_sections.end(); } diff --git a/CodeLite/clJoinableThread.cpp b/CodeLite/clJoinableThread.cpp index f43177bfb1..7f7789dbf7 100644 --- a/CodeLite/clJoinableThread.cpp +++ b/CodeLite/clJoinableThread.cpp @@ -11,7 +11,7 @@ void clJoinableThread::Stop() { // Notify the thread to exit and // wait for it - if(IsAlive()) { + if (IsAlive()) { Delete(NULL, wxTHREAD_WAIT_BLOCK); } else { diff --git a/CodeLite/clModuleLogger.cpp b/CodeLite/clModuleLogger.cpp index 3ed655b96c..839bf27cfb 100644 --- a/CodeLite/clModuleLogger.cpp +++ b/CodeLite/clModuleLogger.cpp @@ -11,11 +11,11 @@ bool clModuleLogger::CanLog() const { return FileLogger::CanLog(m_current_log_le void clModuleLogger::Flush() { - if(m_buffer.empty()) { + if (m_buffer.empty()) { return; } - if(m_buffer.Last() != '\n') { + if (m_buffer.Last() != '\n') { m_buffer.Append('\n'); } FileUtils::AppendFileContent(m_logfile, m_buffer, wxConvUTF8); @@ -26,7 +26,7 @@ void clModuleLogger::Open(const wxFileName& filepath) { m_logfile = filepath; } clModuleLogger& clModuleLogger::SetCurrentLogLevel(int level) { - if(!m_buffer.empty()) { + if (!m_buffer.empty()) { // flush the current content Flush(); } @@ -36,7 +36,7 @@ clModuleLogger& clModuleLogger::SetCurrentLogLevel(int level) wxString clModuleLogger::Prefix() { - if(!CanLog()) { + if (!CanLog()) { return wxEmptyString; } @@ -48,7 +48,7 @@ wxString clModuleLogger::Prefix() // add the thread ID prefix << wxT(" T:") << wxThread::GetCurrentId(); - switch(m_current_log_level) { + switch (m_current_log_level) { case FileLogger::System: prefix << wxT(" SYSTEM]"); break; @@ -66,7 +66,7 @@ wxString clModuleLogger::Prefix() break; } - if(!m_module.empty()) { + if (!m_module.empty()) { prefix << " " << m_module << ">"; } return prefix; diff --git a/CodeLite/clModuleLogger.hpp b/CodeLite/clModuleLogger.hpp index 03eb011c0c..92f518aa52 100644 --- a/CodeLite/clModuleLogger.hpp +++ b/CodeLite/clModuleLogger.hpp @@ -54,11 +54,11 @@ class WXDLLIMPEXP_CL clModuleLogger // special types printing clModuleLogger& operator<<(const std::vector& arr) { - if(!CanLog()) { + if (!CanLog()) { return *this; } - if(!m_buffer.empty()) { + if (!m_buffer.empty()) { m_buffer << " "; } @@ -75,15 +75,15 @@ class WXDLLIMPEXP_CL clModuleLogger clModuleLogger& operator<<(const wxStringSet_t& S) { - if(!CanLog()) { + if (!CanLog()) { return *this; } - if(!m_buffer.empty()) { + if (!m_buffer.empty()) { m_buffer << " "; } m_buffer << "{"; - if(!S.empty()) { - for(const wxString& s : S) { + if (!S.empty()) { + for (const wxString& s : S) { m_buffer << s << ", "; } m_buffer.RemoveLast(2); @@ -94,15 +94,15 @@ class WXDLLIMPEXP_CL clModuleLogger clModuleLogger& operator<<(const wxStringMap_t& M) { - if(!CanLog()) { + if (!CanLog()) { return *this; } - if(!m_buffer.empty()) { + if (!m_buffer.empty()) { m_buffer << " "; } m_buffer << "{"; - if(!M.empty()) { - for(const auto& vt : M) { + if (!M.empty()) { + for (const auto& vt : M) { m_buffer << "{" << vt.first << ", " << vt.second << "}, "; } m_buffer.RemoveLast(2); @@ -113,17 +113,17 @@ class WXDLLIMPEXP_CL clModuleLogger clModuleLogger& operator<<(const wxArrayString& arr) { - if(!CanLog()) { + if (!CanLog()) { return *this; } - std::vector v{ arr.begin(), arr.end() }; + std::vector v{arr.begin(), arr.end()}; *this << v; return *this; } clModuleLogger& operator<<(const wxColour& colour) { - if(!CanLog()) { + if (!CanLog()) { return *this; } @@ -133,7 +133,7 @@ class WXDLLIMPEXP_CL clModuleLogger clModuleLogger& operator<<(const wxPoint& point) { - if(!CanLog()) { + if (!CanLog()) { return *this; } @@ -145,7 +145,7 @@ class WXDLLIMPEXP_CL clModuleLogger clModuleLogger& operator<<(const wxSize& size) { - if(!CanLog()) { + if (!CanLog()) { return *this; } @@ -157,7 +157,7 @@ class WXDLLIMPEXP_CL clModuleLogger clModuleLogger& operator<<(const wxRect& rect) { - if(!CanLog()) { + if (!CanLog()) { return *this; } @@ -172,10 +172,10 @@ class WXDLLIMPEXP_CL clModuleLogger */ clModuleLogger& operator<<(const wxString& str) { - if(!CanLog()) { + if (!CanLog()) { return *this; } - if(!m_buffer.empty()) { + if (!m_buffer.empty()) { m_buffer << " "; } m_buffer << str; @@ -186,7 +186,7 @@ class WXDLLIMPEXP_CL clModuleLogger */ clModuleLogger& operator<<(const char* str) { - if(!CanLog()) { + if (!CanLog()) { return *this; } wxString s(str); @@ -198,10 +198,10 @@ class WXDLLIMPEXP_CL clModuleLogger */ clModuleLogger& operator<<(const wxFileName& fn) { - if(!CanLog()) { + if (!CanLog()) { return *this; } - if(!m_buffer.empty()) { + if (!m_buffer.empty()) { m_buffer << " "; } m_buffer << fn.GetFullPath(); @@ -211,9 +211,10 @@ class WXDLLIMPEXP_CL clModuleLogger /** * @brief append any type to the buffer, take log level into consideration */ - template clModuleLogger& Append(const T& elem) + template + clModuleLogger& Append(const T& elem) { - if(!m_buffer.empty()) { + if (!m_buffer.empty()) { m_buffer << " "; } m_buffer << elem; @@ -232,9 +233,10 @@ inline clModuleLogger& endl(clModuleLogger& d) return d; } -template clModuleLogger& operator<<(clModuleLogger& logger, const T& obj) +template +clModuleLogger& operator<<(clModuleLogger& logger, const T& obj) { - if(!logger.CanLog()) { + if (!logger.CanLog()) { return logger; } @@ -249,22 +251,22 @@ template clModuleLogger& operator<<(clModuleLogger& logger, const T #define LOG_TRACE(LOG) LOG.SetCurrentLogLevel(FileLogger::Developer) << LOG.Prefix() /// place this at the top of the C++ file you want to have custom logger -#define INITIALISE_MODULE_LOG(LOG, MODULE_NAME, FILE_NAME) \ - namespace \ - { \ - clModuleLogger& LOG() \ - { \ - thread_local static clModuleLogger instance = []() { \ - wxFileName logfile{ clStandardPaths::Get().GetUserDataDir(), FILE_NAME }; \ - logfile.AppendDir("logs"); \ - logfile.Mkdir(wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL); \ - clModuleLogger logger; \ - logger.SetModule(MODULE_NAME); \ - logger.Open(logfile.GetFullPath()); \ - return logger; \ - }(); \ - return instance; \ - } \ +#define INITIALISE_MODULE_LOG(LOG, MODULE_NAME, FILE_NAME) \ + namespace \ + { \ + clModuleLogger& LOG() \ + { \ + thread_local static clModuleLogger instance = []() { \ + wxFileName logfile{clStandardPaths::Get().GetUserDataDir(), FILE_NAME}; \ + logfile.AppendDir("logs"); \ + logfile.Mkdir(wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL); \ + clModuleLogger logger; \ + logger.SetModule(MODULE_NAME); \ + logger.Open(logfile.GetFullPath()); \ + return logger; \ + }(); \ + return instance; \ + } \ } #endif // CLMODULELOGGER_HPP diff --git a/CodeLite/clStringView.cpp b/CodeLite/clStringView.cpp index ae5402fb6d..c63eb17176 100644 --- a/CodeLite/clStringView.cpp +++ b/CodeLite/clStringView.cpp @@ -4,7 +4,7 @@ wxString clStringView::MakeString() const { - if(!m_pdata) { + if (!m_pdata) { return wxString(); } else { return wxString(m_pdata, m_length); @@ -21,7 +21,7 @@ bool clStringView::Advance(size_t count) { // sanity: if the requested count is more than the current length // clear the string - if(count > m_length) { + if (count > m_length) { return false; } @@ -32,11 +32,11 @@ bool clStringView::Advance(size_t count) int clStringView::Find(const wxString& what) const { - if(empty()) { + if (empty()) { return wxNOT_FOUND; } const wxChar* match = ::wxStrstr(m_pdata, what); - if(match == nullptr) { + if (match == nullptr) { return wxNOT_FOUND; } return match - m_pdata; diff --git a/CodeLite/clWildMatch.cpp b/CodeLite/clWildMatch.cpp index 86afed2da7..9f0c22e072 100644 --- a/CodeLite/clWildMatch.cpp +++ b/CodeLite/clWildMatch.cpp @@ -8,14 +8,14 @@ namespace void split_mask(const wxString& maskString, std::vector<_Mask>& includeMask, std::vector<_Mask>& excludeMask) { wxArrayString masks = ::wxStringTokenize(maskString, ";,", wxTOKEN_STRTOK); - for(wxString& mask : masks) { + for (wxString& mask : masks) { mask.Trim().Trim(false); // exclude mask starts with "!" or "-" - if((mask[0] == '!') || (mask[0] == '-')) { + if ((mask[0] == '!') || (mask[0] == '-')) { mask.Remove(0, 1); - excludeMask.push_back({ mask, ::wxIsWild(mask) }); + excludeMask.push_back({mask, ::wxIsWild(mask)}); } else { - includeMask.push_back({ mask, ::wxIsWild(mask) }); + includeMask.push_back({mask, ::wxIsWild(mask)}); } } } @@ -26,21 +26,21 @@ clFileExtensionMatcher::clFileExtensionMatcher(const wxString& mask) { std::vector<_Mask> dummy; wxArrayString masks = ::wxStringTokenize(m_mask, ";,", wxTOKEN_STRTOK); - for(wxString& mask : masks) { + for (wxString& mask : masks) { mask.Replace("*", wxEmptyString); - m_include_mask.push_back({ mask, false }); + m_include_mask.push_back({mask, false}); } m_always_matches = false; } bool clFileExtensionMatcher::matches(const wxString& filename) const { - if(m_always_matches) { + if (m_always_matches) { return true; } - for(const _Mask& d : m_include_mask) { - if(!d.is_wild && filename.EndsWith(d.pattern)) { + for (const _Mask& d : m_include_mask) { + if (!d.is_wild && filename.EndsWith(d.pattern)) { return true; } } @@ -52,8 +52,8 @@ bool clFileExtensionMatcher::matches(const wxString& filename) const clPathExcluder::clPathExcluder(const wxArrayString& patterns) { m_exclude_mask.reserve(patterns.size()); - for(const auto& pattern : patterns) { - m_exclude_mask.push_back({ pattern, ::wxIsWild(pattern) }); + for (const auto& pattern : patterns) { + m_exclude_mask.push_back({pattern, ::wxIsWild(pattern)}); } } @@ -66,13 +66,13 @@ clPathExcluder::clPathExcluder(const wxString& mask) bool clPathExcluder::is_exclude_path(const wxString& str) const { - if(m_exclude_mask.empty()) { + if (m_exclude_mask.empty()) { return false; } - for(const auto& d : m_exclude_mask) { - if((!d.is_wild && str.Contains(d.pattern)) || // use Contains match - (d.is_wild && ::wxMatchWild(d.pattern, str))) // pattern matching + for (const auto& d : m_exclude_mask) { + if ((!d.is_wild && str.Contains(d.pattern)) || // use Contains match + (d.is_wild && ::wxMatchWild(d.pattern, str))) // pattern matching { return true; } diff --git a/CodeLite/cl_calltip.cpp b/CodeLite/cl_calltip.cpp index 38cc7a7643..13a74571e4 100644 --- a/CodeLite/cl_calltip.cpp +++ b/CodeLite/cl_calltip.cpp @@ -22,10 +22,11 @@ // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// +#include "precompiled_header.h" + #include "cl_calltip.h" #include "ctags_manager.h" -#include "precompiled_header.h" #include @@ -34,10 +35,7 @@ struct tagCallTipInfo { std::vector> paramLen; }; -clCallTip::clCallTip(const std::vector& tips) -{ - Initialize(tips); -} +clCallTip::clCallTip(const std::vector& tips) { Initialize(tips); } wxString clCallTip::First() { @@ -165,7 +163,7 @@ void clCallTip::FormatTagsToTips(const TagEntryPtrVector_t& tags, std::vector #include "codelite_exports.h" +#include + class WXDLLIMPEXP_CL clException { wxString m_message; - int m_errorCode; + int m_errorCode; + public: - clException(const wxString& message) : m_message(message), m_errorCode(0) {} - clException(const wxString& message, int errorCode) : m_message(message), m_errorCode(errorCode) {} - virtual ~clException() = default; - - const wxString& What() const { - return m_message; + clException(const wxString& message) + : m_message(message) + , m_errorCode(0) + { } - int ErrorCode() const { - return m_errorCode; + clException(const wxString& message, int errorCode) + : m_message(message) + , m_errorCode(errorCode) + { } + virtual ~clException() = default; + + const wxString& What() const { return m_message; } + int ErrorCode() const { return m_errorCode; } }; #endif // CLEXCEPTION_H diff --git a/CodeLite/cl_process.cpp b/CodeLite/cl_process.cpp index 9c49aefcbd..1a201c7d8d 100644 --- a/CodeLite/cl_process.cpp +++ b/CodeLite/cl_process.cpp @@ -52,12 +52,12 @@ void clProcess::Terminate(wxSignal signalNo) long clProcess::Start(bool hide) { - if(m_redirect) { + if (m_redirect) { Redirect(); } long flags = wxEXEC_ASYNC | wxEXEC_MAKE_GROUP_LEADER; - if(!hide) { + if (!hide) { flags |= wxEXEC_NOHIDE; } @@ -67,27 +67,27 @@ long clProcess::Start(bool hide) bool clProcess::HasInput(wxString& input, wxString& errors) { - if(m_redirect == false) { + if (m_redirect == false) { wxASSERT_MSG(false, wxT("Process is not redirected")); return false; } bool hasInput = false; - while(IsInputAvailable()) { + while (IsInputAvailable()) { wxTextInputStream tis(*GetInputStream()); wxChar ch = tis.GetChar(); input << ch; hasInput = true; - if(ch == wxT('\n')) + if (ch == wxT('\n')) break; } - while(IsErrorAvailable()) { + while (IsErrorAvailable()) { wxTextInputStream tis(*GetErrorStream()); wxChar ch = tis.GetChar(); errors << ch; hasInput = true; - if(ch == wxT('\n')) + if (ch == wxT('\n')) break; } return hasInput; @@ -95,19 +95,19 @@ bool clProcess::HasInput(wxString& input, wxString& errors) bool clProcess::ReadAll(wxString& input, wxString& errors) { - if(m_redirect == false) { + if (m_redirect == false) { wxASSERT_MSG(false, wxT("Process is not redirected")); return false; } bool hasInput = false; - while(IsInputAvailable()) { + while (IsInputAvailable()) { wxTextInputStream tis(*GetInputStream()); input << tis.GetChar(); hasInput = true; } - while(IsErrorAvailable()) { + while (IsErrorAvailable()) { wxTextInputStream tis(*GetErrorStream()); errors << tis.GetChar(); hasInput = true; @@ -117,7 +117,7 @@ bool clProcess::ReadAll(wxString& input, wxString& errors) bool clProcess::Write(const wxString& text) { - if(m_redirect == false) { + if (m_redirect == false) { wxASSERT_MSG(false, wxT("Process is not redirected")); return false; } diff --git a/CodeLite/cl_standard_paths.cpp b/CodeLite/cl_standard_paths.cpp index 63b3e4ebfc..9c4b8e8d8a 100644 --- a/CodeLite/cl_standard_paths.cpp +++ b/CodeLite/cl_standard_paths.cpp @@ -44,9 +44,9 @@ static wxString __get_user_name() // So try to make it more suitable to be an extension name.MakeLower(); name.Replace(wxT(" "), wxT("_")); - for(size_t i = 0; i < name.Len(); ++i) { + for (size_t i = 0; i < name.Len(); ++i) { wxChar ch = name.GetChar(i); - if((ch < wxT('a') || ch > wxT('z')) && ch != wxT('_')) { + if ((ch < wxT('a') || ch > wxT('z')) && ch != wxT('_')) { // Non [a-z_] character: skip it } else { squashedname << ch; @@ -69,26 +69,26 @@ namespace { void copy_directory(const wxString& from, const wxString& to) { - if(!wxDirExists(from)) { + if (!wxDirExists(from)) { return; } wxString source_dir = from; wxString target_dir = to; - if(!source_dir.EndsWith("/")) { + if (!source_dir.EndsWith("/")) { source_dir << "/"; } - if(!target_dir.EndsWith("/")) { + if (!target_dir.EndsWith("/")) { target_dir << "/"; } wxDir dir(source_dir); wxString filename; bool bla = dir.GetFirst(&filename); - if(bla) { + if (bla) { do { - if(wxDirExists(source_dir + filename)) { + if (wxDirExists(source_dir + filename)) { // a directory wxFileName::Mkdir(target_dir + filename, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL); copy_directory(source_dir + filename, target_dir + filename); @@ -96,7 +96,7 @@ void copy_directory(const wxString& from, const wxString& to) // a file, copy it wxCopyFile(source_dir + filename, target_dir + filename); } - } while(dir.GetNext(&filename)); + } while (dir.GetNext(&filename)); } } } // namespace @@ -105,7 +105,7 @@ void copy_directory(const wxString& from, const wxString& to) wxString clStandardPaths::GetUserDataDir() const { // If the user has provided an alternative datadir, use it - if(!m_path.empty()) { + if (!m_path.empty()) { return m_path; } @@ -124,15 +124,15 @@ wxString clStandardPaths::GetUserDataDir() const return wxStandardPaths::Get().GetUserDataDir(); #else // use ~/.codelite on macOS as well - wxFileName path{ wxGetHomeDir(), wxEmptyString }; + wxFileName path{wxGetHomeDir(), wxEmptyString}; path.AppendDir(".codelite"); // upgrade path static bool upgrade_needed = true; - if(upgrade_needed) { + if (upgrade_needed) { upgrade_needed = false; - if(wxFileName::DirExists(wxStandardPaths::Get().GetUserDataDir()) && !path.DirExists()) { + if (wxFileName::DirExists(wxStandardPaths::Get().GetUserDataDir()) && !path.DirExists()) { // we have an old setting directory but not a new one // copy the content copy_directory(wxStandardPaths::Get().GetUserDataDir(), path.GetPath()); @@ -162,7 +162,7 @@ wxString clStandardPaths::GetPluginsDirectory() const wxString clStandardPaths::GetDataDir() const { - if(!m_dataDir.IsEmpty()) { + if (!m_dataDir.IsEmpty()) { return m_dataDir; } @@ -189,7 +189,7 @@ wxString clStandardPaths::GetBinaryFullPath(const wxString& toolname, bool unixS #endif wxString fullpath = binary.GetFullPath(); - if(unixStylePath) { + if (unixStylePath) { fullpath.Replace("\\", "/"); } return fullpath; @@ -231,7 +231,7 @@ wxString clStandardPaths::GetTempDir() const { static bool once = true; static wxString tmpdir; - if(once) { + if (once) { wxString username = __get_user_name(); #if defined(__WXGTK__) || defined(__WXOSX__) tmpdir << "/tmp/codelite/"; @@ -254,7 +254,7 @@ wxString clStandardPaths::GetDocumentsDir() const // but what we really want is ~/Documents wxFileName fp(path, ""); fp.AppendDir("Documents"); - if(fp.DirExists()) { + if (fp.DirExists()) { return fp.GetPath(); } #endif diff --git a/CodeLite/codelite_exports.h b/CodeLite/codelite_exports.h index 8e185796ad..2bb521c358 100644 --- a/CodeLite/codelite_exports.h +++ b/CodeLite/codelite_exports.h @@ -35,13 +35,13 @@ ////////////////////////////////////// // CodeLite ////////////////////////////////////// - -#ifdef WXMAKINGDLL_CL -# define WXDLLIMPEXP_CL __declspec(dllexport) -#elif defined(WXUSINGDLL_CL) -# define WXDLLIMPEXP_CL __declspec(dllimport) -#else // not making nor using DLL -# define WXDLLIMPEXP_CL + +#ifdef WXMAKINGDLL_CL +#define WXDLLIMPEXP_CL __declspec(dllexport) +#elif defined(WXUSINGDLL_CL) +#define WXDLLIMPEXP_CL __declspec(dllimport) +#else // not making nor using DLL +#define WXDLLIMPEXP_CL #endif ////////////////////////////////////// @@ -50,20 +50,18 @@ #ifdef WXDLLIMPEXP_SDK #undef WXDLLIMPEXP_SDK #endif - -#ifdef WXMAKINGDLL_SDK -# define WXDLLIMPEXP_SDK __declspec(dllexport) -#elif defined(WXUSINGDLL_SDK) -# define WXDLLIMPEXP_SDK __declspec(dllimport) -#else // not making nor using DLL -# define WXDLLIMPEXP_SDK + +#ifdef WXMAKINGDLL_SDK +#define WXDLLIMPEXP_SDK __declspec(dllexport) +#elif defined(WXUSINGDLL_SDK) +#define WXDLLIMPEXP_SDK __declspec(dllimport) +#else // not making nor using DLL +#define WXDLLIMPEXP_SDK #endif #else // !MSW -# define WXDLLIMPEXP_CL -# define WXDLLIMPEXP_SDK +#define WXDLLIMPEXP_CL +#define WXDLLIMPEXP_SDK #endif #endif // CODELITE_EXPORTS - - diff --git a/CodeLite/compiler_command_line_parser.cpp b/CodeLite/compiler_command_line_parser.cpp index 6e35a82469..cfb658a122 100644 --- a/CodeLite/compiler_command_line_parser.cpp +++ b/CodeLite/compiler_command_line_parser.cpp @@ -48,7 +48,7 @@ CompilerCommandLineParser::CompilerCommandLineParser(const wxString& cmdline, co c.Replace("@@GERESH@@", "\\\""); // Check for makefile directory changes lines - if(cmdline.Contains("Entering directory `")) { + if (cmdline.Contains("Entering directory `")) { wxString currentDir = cmdline.AfterFirst('`'); m_directory = currentDir.BeforeLast('\''); @@ -56,12 +56,12 @@ CompilerCommandLineParser::CompilerCommandLineParser(const wxString& cmdline, co m_argv = StringUtils::BuildArgv(c, m_argc); - for(int i = 0; i < m_argc; i++) { + for (int i = 0; i < m_argc; i++) { wxString opt = wxString(m_argv[i], wxConvUTF8); opt.Trim().Trim(false); wxString rest; - if(opt.StartsWith("`") && opt.EndsWith("`")) { + if (opt.StartsWith("`") && opt.EndsWith("`")) { // backtick opt = opt.Mid(1); opt.RemoveLast(); @@ -72,21 +72,22 @@ CompilerCommandLineParser::CompilerCommandLineParser(const wxString& cmdline, co // Parse the result CompilerCommandLineParser cclp(result, workingDirectory); m_includes.insert(m_includes.end(), cclp.GetIncludes().begin(), cclp.GetIncludes().end()); - m_includesWithPrefix.insert(m_includesWithPrefix.end(), cclp.GetIncludesWithPrefix().begin(), + m_includesWithPrefix.insert(m_includesWithPrefix.end(), + cclp.GetIncludesWithPrefix().begin(), cclp.GetIncludesWithPrefix().end()); m_macros.insert(m_macros.end(), cclp.GetMacros().begin(), cclp.GetMacros().end()); - m_macrosWithPrefix.insert(m_macrosWithPrefix.end(), cclp.GetMacrosWithPrefix().begin(), - cclp.GetMacrosWithPrefix().end()); + m_macrosWithPrefix.insert( + m_macrosWithPrefix.end(), cclp.GetMacrosWithPrefix().begin(), cclp.GetMacrosWithPrefix().end()); m_frameworks.insert(m_frameworks.end(), cclp.GetFrameworks().begin(), cclp.GetFrameworks().end()); - } else if(opt.StartsWith("@") && (opt.Contains("includes_C.rsp") || opt.Contains("includes_CXX.rsp"))) { + } else if (opt.StartsWith("@") && (opt.Contains("includes_C.rsp") || opt.Contains("includes_CXX.rsp"))) { // The include folders are inside the file - read the file and process its content wxFileName fnIncludes(workingDirectory + "/" + opt.Mid(1)); - if(fnIncludes.Exists()) { + if (fnIncludes.Exists()) { AddIncludesFromFile(fnIncludes); } - } else if(opt == "-isystem" && (i + 1 < m_argc)) { + } else if (opt == "-isystem" && (i + 1 < m_argc)) { // the next arg is the include folder wxString include_path = m_argv[i + 1]; @@ -96,13 +97,13 @@ CompilerCommandLineParser::CompilerCommandLineParser(const wxString& cmdline, co m_includesWithPrefix.Add(wxString() << "-I" << include_path); ++i; - } else if(opt.StartsWith("-I", &rest)) { + } else if (opt.StartsWith("-I", &rest)) { rest.Replace("\"", wxEmptyString); wxFileName path(rest, wxEmptyString); m_includes.Add(path.GetPath()); m_includesWithPrefix.Add("-I" + path.GetPath()); - } else if(opt.StartsWith("/I", &rest)) { + } else if (opt.StartsWith("/I", &rest)) { rest.Replace("\"", wxEmptyString); wxFileName path(rest, wxEmptyString); m_includes.Add(path.GetPath()); @@ -110,36 +111,36 @@ CompilerCommandLineParser::CompilerCommandLineParser(const wxString& cmdline, co } - else if(opt.StartsWith("-D", &rest) || opt.StartsWith("/D", &rest)) { + else if (opt.StartsWith("-D", &rest) || opt.StartsWith("/D", &rest)) { m_macros.Add(rest); m_macrosWithPrefix.Add(opt); } - else if(opt.StartsWith("-include-path ", &rest)) { + else if (opt.StartsWith("-include-path ", &rest)) { m_includesWithPrefix.Add(rest); rest.Trim().Trim(false); m_pchFile = rest; } - else if((opt == "-include") && (i + 1 < m_argc)) { + else if ((opt == "-include") && (i + 1 < m_argc)) { wxString include_path = m_argv[i + 1]; include_path.Trim().Trim(false); m_pchFile = include_path; ++i; - } else if((opt == "-isysroot") && (i + 1 < m_argc)) { + } else if ((opt == "-isysroot") && (i + 1 < m_argc)) { wxString include_path = m_argv[i + 1]; include_path.Trim().Trim(false); m_sysroots.Add(include_path); ++i; } - else if(opt.StartsWith("/FI", &rest)) { + else if (opt.StartsWith("/FI", &rest)) { rest.Trim().Trim(false); m_pchFile = rest; } // Support for Apple's Framework include paths - else if(opt.StartsWith("-F", &rest)) { + else if (opt.StartsWith("-F", &rest)) { m_includesWithPrefix.Add(opt); rest.Trim().Trim(false); @@ -148,10 +149,10 @@ CompilerCommandLineParser::CompilerCommandLineParser(const wxString& cmdline, co } // std - else if(opt.StartsWith("-std=", &rest) || opt.StartsWith("/std:", &rest)) { + else if (opt.StartsWith("-std=", &rest) || opt.StartsWith("/std:", &rest)) { rest.Trim().Trim(false); - if(!rest.IsEmpty()) { + if (!rest.IsEmpty()) { m_standard = rest; } // keep the std as an option as well @@ -172,7 +173,7 @@ CompilerCommandLineParser::~CompilerCommandLineParser() wxString CompilerCommandLineParser::GetStandardWithPrefix() const { - if(m_standard.IsEmpty()) { + if (m_standard.IsEmpty()) { return ""; } return "-std=" + m_standard; @@ -181,14 +182,14 @@ wxString CompilerCommandLineParser::GetStandardWithPrefix() const void CompilerCommandLineParser::AddIncludesFromFile(const wxFileName& includeFile) { wxFFile fp(includeFile.GetFullPath(), "rb"); - if(fp.IsOpened()) { + if (fp.IsOpened()) { wxString content; fp.ReadAll(&content); content.Replace("\n", " "); CompilerCommandLineParser cclp(content); m_includes.insert(m_includes.end(), cclp.GetIncludes().begin(), cclp.GetIncludes().end()); - m_includesWithPrefix.insert(m_includesWithPrefix.end(), cclp.GetIncludesWithPrefix().begin(), - cclp.GetIncludesWithPrefix().end()); + m_includesWithPrefix.insert( + m_includesWithPrefix.end(), cclp.GetIncludesWithPrefix().begin(), cclp.GetIncludesWithPrefix().end()); fp.Close(); } } diff --git a/CodeLite/compiler_command_line_parser.h b/CodeLite/compiler_command_line_parser.h index ba40be27c9..2365bab5b0 100644 --- a/CodeLite/compiler_command_line_parser.h +++ b/CodeLite/compiler_command_line_parser.h @@ -27,6 +27,7 @@ #define COMMANDLINEPARSER_H #include "codelite_exports.h" + #include #include #include diff --git a/CodeLite/ctags_manager.cpp b/CodeLite/ctags_manager.cpp index f251ee67ca..e295ab13a3 100644 --- a/CodeLite/ctags_manager.cpp +++ b/CodeLite/ctags_manager.cpp @@ -22,6 +22,8 @@ // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// +#include "precompiled_header.h" + #include "ctags_manager.h" #include "CTags.hpp" @@ -35,7 +37,6 @@ #include "fileextmanager.h" #include "fileutils.h" #include "language.h" -#include "precompiled_header.h" #include #include @@ -60,7 +61,7 @@ static TagsManager* gs_TagsManager = NULL; void TagsManagerST::Free() { - if(gs_TagsManager) { + if (gs_TagsManager) { delete gs_TagsManager; } gs_TagsManager = NULL; @@ -68,7 +69,7 @@ void TagsManagerST::Free() TagsManager* TagsManagerST::Get() { - if(gs_TagsManager == NULL) + if (gs_TagsManager == NULL) gs_TagsManager = new TagsManager(); return gs_TagsManager; @@ -103,7 +104,7 @@ TagTreePtr TagsManager::Load(const wxFileName& fileName, TagEntryPtrVector_t* ta TagTreePtr tree; TagEntryPtrVector_t tagsByFile; - if(tags) { + if (tags) { tagsByFile.insert(tagsByFile.end(), tags->begin(), tags->end()); } else { @@ -145,16 +146,16 @@ void TagsManager::FindByNameAndScope(const wxString& name, const wxString& scope void TagsManager::DoFindByNameAndScope(const wxString& name, const wxString& scope, std::vector& tags) { wxString sql; - if(scope == wxT("")) { + if (scope == wxT("")) { // try the workspace database for match GetDatabase()->GetTagsByNameAndParent(name, wxT(""), tags); } else { std::vector> derivationList; - derivationList.push_back({ scope, 0 }); + derivationList.push_back({scope, 0}); std::unordered_set visited; GetDerivationList(scope, NULL, derivationList, visited, 1); wxArrayString paths; - for(size_t i = 0; i < derivationList.size(); i++) { + for (size_t i = 0; i < derivationList.size(); i++) { wxString path_; path_ << derivationList.at(i).first << wxT("::") << name; paths.Add(path_); @@ -173,12 +174,12 @@ bool TagsManager::IsTypeAndScopeExists(wxString& typeName, wxString& scope) // we search the cache first, note that the cache // is used only for the external database std::map::iterator iter = m_typeScopeCache.find(cacheKey); - if(iter != m_typeScopeCache.end()) { + if (iter != m_typeScopeCache.end()) { return iter->second; } // First try the fast query to save some time - if(GetDatabase()->IsTypeAndScopeExistLimitOne(typeName, scope)) { + if (GetDatabase()->IsTypeAndScopeExistLimitOne(typeName, scope)) { return true; } @@ -190,45 +191,50 @@ bool TagsManager::IsTypeAndScopeExists(wxString& typeName, wxString& scope) return GetDatabase()->IsTypeAndScopeExist(typeName, scope); } -bool TagsManager::GetDerivationList(const wxString& path, TagEntryPtr derivedClassTag, +bool TagsManager::GetDerivationList(const wxString& path, + TagEntryPtr derivedClassTag, std::vector>& derivationList, - std::unordered_set& visited, int depth) + std::unordered_set& visited, + int depth) { bool res = GetDerivationListInternal(path, derivedClassTag, derivationList, visited, depth); std::sort( - derivationList.begin(), derivationList.end(), + derivationList.begin(), + derivationList.end(), [](const std::pair& a, const std::pair& b) { return a.second < b.second; }); return res; } -bool TagsManager::GetDerivationListInternal(const wxString& path, TagEntryPtr derivedClassTag, +bool TagsManager::GetDerivationListInternal(const wxString& path, + TagEntryPtr derivedClassTag, std::vector>& derivationList, - std::unordered_set& visited, int depth) + std::unordered_set& visited, + int depth) { std::vector tags; TagEntryPtr tag; - const wxArrayString kind = { wxT("class"), wxT("struct") }; + const wxArrayString kind = {wxT("class"), wxT("struct")}; GetDatabase()->GetTagsByKindAndPath(kind, path, tags); - if(tags.size() == 1) { + if (tags.size() == 1) { tag = tags.at(0); } else { return false; } - if(tag && tag->IsOk()) { + if (tag && tag->IsOk()) { // Get the template instantiation list from the child class wxArrayString inheritsList = tag->GetInheritsAsArrayNoTemplates(); wxString templateInstantiationLine; - if(derivedClassTag) { + if (derivedClassTag) { wxArrayString p_inheritsListT = derivedClassTag->GetInheritsAsArrayWithTemplates(); wxArrayString p_inheritsList = derivedClassTag->GetInheritsAsArrayNoTemplates(); - for(size_t i = 0; i < p_inheritsList.GetCount(); i++) { - if(p_inheritsList.Item(i) == tag->GetName()) { + for (size_t i = 0; i < p_inheritsList.GetCount(); i++) { + if (p_inheritsList.Item(i) == tag->GetName()) { templateInstantiationLine = p_inheritsListT.Item(i); templateInstantiationLine = templateInstantiationLine.AfterFirst(wxT('<')); templateInstantiationLine.Prepend(wxT("<")); @@ -237,7 +243,7 @@ bool TagsManager::GetDerivationListInternal(const wxString& path, TagEntryPtr de } } - for(size_t i = 0; i < inheritsList.GetCount(); i++) { + for (size_t i = 0; i < inheritsList.GetCount(); i++) { wxString inherits = inheritsList.Item(i); wxString tagName = tag->GetName(); wxString tmpInhr = inherits; @@ -247,18 +253,18 @@ bool TagsManager::GetDerivationListInternal(const wxString& path, TagEntryPtr de tmpInhr.MakeLower(); // Make sure that inherits != the current name or we will end up in an infinite loop - if(tmpInhr != tagName) { + if (tmpInhr != tagName) { wxString possibleScope(wxT("")); // if the 'inherits' already contains a scope // don't attempt to fix it - if(inherits.Contains(wxT("::")) == false) { + if (inherits.Contains(wxT("::")) == false) { // Correct the type/scope bool testForTemplate = !IsTypeAndScopeExists(inherits, possibleScope); // If the type does not exists, check for templates - if(testForTemplate && derivedClassTag && isTemplate) { + if (testForTemplate && derivedClassTag && isTemplate) { TemplateHelper th; // e.g. template class MyClass @@ -270,11 +276,11 @@ bool TagsManager::GetDerivationListInternal(const wxString& path, TagEntryPtr de // Locate the new type by name in the database // this is done to make sure that the new type is not a macro... - if(!newType.IsEmpty() && newType != inherits) { + if (!newType.IsEmpty() && newType != inherits) { // check the user defined types for a replacement token wxString replacement = DoReplaceMacros(newType); - if(replacement == newType) { + if (replacement == newType) { // No match was found in the user defined replacements // try the database replacement = DoReplaceMacrosFromDatabase(newType); @@ -283,15 +289,15 @@ bool TagsManager::GetDerivationListInternal(const wxString& path, TagEntryPtr de } } - if(possibleScope != wxT("")) { + if (possibleScope != wxT("")) { inherits = possibleScope + wxT("::") + inherits; } } // Make sure that this parent was not scanned already - if(visited.count(inherits) == 0) { + if (visited.count(inherits) == 0) { visited.insert(inherits); - derivationList.push_back({ inherits, depth }); + derivationList.push_back({inherits, depth}); GetDerivationList(inherits, tag, derivationList, visited, depth + 1); } } @@ -318,10 +324,7 @@ DoxygenComment TagsManager::DoCreateDoxygenComment(TagEntryPtr tag, wxChar keyPr return dc; } -void TagsManager::SetCtagsOptions(const TagsOptionsData& options) -{ - m_tagsOptions = options; -} +void TagsManager::SetCtagsOptions(const TagsOptionsData& options) { m_tagsOptions = options; } wxString TagsManager::GetScopeName(const wxString& scope) { @@ -331,7 +334,7 @@ wxString TagsManager::GetScopeName(const wxString& scope) void TagsManager::GetFiles(const wxString& partialName, std::vector& files) { - if(GetDatabase()) { + if (GetDatabase()) { GetDatabase()->GetFiles(partialName, files); } } @@ -348,11 +351,11 @@ void TagsManager::GetFiles(const wxString& partialName, std::vector& TagEntryPtr TagsManager::FunctionFromFileLine(const wxFileName& fileName, int lineno) { - if(!GetDatabase()) { + if (!GetDatabase()) { return NULL; } - if(!IsFileCached(fileName.GetFullPath())) { + if (!IsFileCached(fileName.GetFullPath())) { CacheFile(fileName.GetFullPath()); } @@ -368,7 +371,7 @@ void TagsManager::SetLanguage(Language* lang) { m_lang = lang; } Language* TagsManager::GetLanguage() { - if(!m_lang) { + if (!m_lang) { // for backward compatibility allows access to the tags manager using // the singleton call return LanguageST::Get(); @@ -396,8 +399,8 @@ void TagsManager::TagsByScope(const wxString& scopeName, const wxArrayString& ki std::sort(tags.begin(), tags.end(), SAscendingSort()); } -wxString TagsManager::NormalizeFunctionSig(const wxString& sig, size_t flags, - std::vector>* paramLen) +wxString +TagsManager::NormalizeFunctionSig(const wxString& sig, size_t flags, std::vector>* paramLen) { // FIXME: make the standard configurable CxxVariableScanner varScanner(sig, eCxxStandard::kCxx11, {}, true); @@ -407,38 +410,38 @@ wxString TagsManager::NormalizeFunctionSig(const wxString& sig, size_t flags, wxString str_output; str_output << wxT("("); - if(paramLen) { + if (paramLen) { paramLen->clear(); } - if(flags & Normalize_Func_Arg_Per_Line && !vars.empty()) { + if (flags & Normalize_Func_Arg_Per_Line && !vars.empty()) { str_output << wxT("\n "); } - for(const auto& var : vars) { + for (const auto& var : vars) { int start_offset = str_output.length(); // FIXME: the standard should be configurable size_t toStringFlags = CxxVariable::kToString_None; - if(flags & Normalize_Func_Name) { + if (flags & Normalize_Func_Name) { toStringFlags |= CxxVariable::kToString_Name; } - if(flags & Normalize_Func_Default_value) { + if (flags & Normalize_Func_Default_value) { toStringFlags |= CxxVariable::kToString_DefaultValue; } str_output << var->ToString(toStringFlags); // keep the length of this argument - if(paramLen) { - paramLen->push_back({ start_offset, str_output.length() - start_offset }); + if (paramLen) { + paramLen->push_back({start_offset, str_output.length() - start_offset}); } str_output << ", "; - if((flags & Normalize_Func_Arg_Per_Line) && !vars.empty()) { + if ((flags & Normalize_Func_Arg_Per_Line) && !vars.empty()) { str_output << wxT("\n "); } } - if(vars.empty() == false) { + if (vars.empty() == false) { str_output = str_output.BeforeLast(','); } @@ -448,7 +451,7 @@ wxString TagsManager::NormalizeFunctionSig(const wxString& sig, size_t flags, void TagsManager::CacheFile(const wxString& fileName) { - if(!GetDatabase()) { + if (!GetDatabase()) { return; } @@ -458,15 +461,15 @@ void TagsManager::CacheFile(const wxString& fileName) const wxArrayString kinds = {wxT("function"), wxT("prototype")}; // disable the cache GetDatabase()->SetUseCache(false); - GetDatabase()->GetTagsByKindAndFile(kinds, fileName, wxT("line"), ITagsStorage::OrderDesc, - m_cachedFileFunctionsTags); + GetDatabase()->GetTagsByKindAndFile( + kinds, fileName, wxT("line"), ITagsStorage::OrderDesc, m_cachedFileFunctionsTags); // re-enable it GetDatabase()->SetUseCache(true); } void TagsManager::ClearCachedFile(const wxString& fileName) { - if(fileName == m_cachedFile) { + if (fileName == m_cachedFile) { m_cachedFile.Clear(); m_cachedFileFunctionsTags.clear(); } @@ -484,8 +487,8 @@ wxString TagsManager::DoReplaceMacros(const wxString& name) wxStringTable_t::const_iterator it; it = iTokens.find(_name); - if(it != iTokens.end()) { - if(it->second.empty() == false) { + if (it != iTokens.end()) { + if (it->second.empty() == false) { _name = it->second; } } @@ -502,21 +505,21 @@ void TagsManager::FilterNonNeededFilesForRetaging(wxArrayString& strFiles, ITags files_set.insert(filename); } - for (const FileEntryPtr& fe : files_entries) { + for (const FileEntryPtr& fe : files_entries) { // does the file exist in both lists? std::unordered_set::iterator iter = files_set.find(fe->GetFile()); - if(iter != files_set.end()) { + if (iter != files_set.end()) { // get the actual modification time of the file from the disk struct stat buff; int modified(0); const wxCharBuffer cname = _C((*iter)); - if(stat(cname.data(), &buff) == 0) { + if (stat(cname.data(), &buff) == 0) { modified = (int)buff.st_mtime; } // if the timestamp from the database < then the actual timestamp, re-tag the file - if(fe->GetLastRetaggedTimestamp() >= modified) { + if (fe->GetLastRetaggedTimestamp() >= modified) { files_set.erase(iter); } } @@ -536,7 +539,7 @@ void TagsManager::GetDereferenceOperator(const wxString& scope, std::vector visited; GetDerivationList(_scopeName, NULL, derivationList, visited, 1); @@ -545,7 +548,7 @@ void TagsManager::GetDereferenceOperator(const wxString& scope, std::vectorGetDereferenceOperator(tmpScope, tags); - if(!tags.empty()) { + if (!tags.empty()) { // No need to further check break; } @@ -558,7 +561,7 @@ void TagsManager::GetSubscriptOperator(const wxString& scope, std::vector visited; GetDerivationList(_scopeName, NULL, derivationList, visited, 1); @@ -567,7 +570,7 @@ void TagsManager::GetSubscriptOperator(const wxString& scope, std::vectorGetSubscriptOperator(tmpScope, tags); - if(!tags.empty()) { + if (!tags.empty()) { // No need to further check break; @@ -579,29 +582,29 @@ bool TagsManager::IsBinaryFile(const wxString& filepath, const TagsOptionsData& { // If the file is a C++ file, avoid testing the content return false based on the extension FileExtManager::FileType type = FileExtManager::GetType(filepath); - if(type == FileExtManager::TypeHeader || type == FileExtManager::TypeSourceC || - type == FileExtManager::TypeSourceCpp) + if (type == FileExtManager::TypeHeader || type == FileExtManager::TypeSourceC || + type == FileExtManager::TypeSourceCpp) return false; // If this file matches any of the c++ patterns defined in the configuration // don't consider it as a binary file - if(FileUtils::WildMatch(tod.GetFileSpec(), filepath)) { + if (FileUtils::WildMatch(tod.GetFileSpec(), filepath)) { return false; } // examine the file based on the content of the first 4K (max) bytes FILE* fp = fopen(filepath.To8BitData(), "rb"); - if(fp) { + if (fp) { char buffer[1]; int textLen(0); const int maxTextToExamine(4096); // examine up to maxTextToExamine first chars in the file and search for '\0' - while(fread(buffer, sizeof(char), sizeof(buffer), fp) == 1 && textLen < maxTextToExamine) { + while (fread(buffer, sizeof(char), sizeof(buffer), fp) == 1 && textLen < maxTextToExamine) { textLen++; // if we found a NULL, return true - if(buffer[0] == 0) { + if (buffer[0] == 0) { fclose(fp); return true; } @@ -621,11 +624,11 @@ wxString TagsManager::DoReplaceMacrosFromDatabase(const wxString& name) { std::set scannedMacros; wxString newName = name; - while(true) { + while (true) { TagEntryPtr matchedTag = GetDatabase()->GetTagsByNameLimitOne(newName); - if(matchedTag && matchedTag->IsMacro() && scannedMacros.find(matchedTag->GetName()) == scannedMacros.end()) { + if (matchedTag && matchedTag->IsMacro() && scannedMacros.find(matchedTag->GetName()) == scannedMacros.end()) { TagEntryPtr realTag = matchedTag->ReplaceSimpleMacro(); - if(realTag) { + if (realTag) { newName = realTag->GetName(); scannedMacros.insert(newName); @@ -641,7 +644,9 @@ wxString TagsManager::DoReplaceMacrosFromDatabase(const wxString& name) return newName; } -bool TagsManager::InsertFunctionDecl(const wxString& clsname, const wxString& functionDecl, wxString& sourceContent, +bool TagsManager::InsertFunctionDecl(const wxString& clsname, + const wxString& functionDecl, + wxString& sourceContent, int visibility) { return GetLanguage()->InsertFunctionDecl(clsname, functionDecl, sourceContent, visibility); @@ -653,7 +658,7 @@ void TagsManager::GetScopesByScopeName(const wxString& scopeName, wxArrayString& // add this scope as well to the derivation list wxString _scopeName = DoReplaceMacros(scopeName); - derivationList.push_back({ _scopeName, 0 }); + derivationList.push_back({_scopeName, 0}); std::unordered_set visited; GetDerivationList(_scopeName, NULL, derivationList, visited, 1); @@ -663,11 +668,11 @@ void TagsManager::GetScopesByScopeName(const wxString& scopeName, wxArrayString& } } -void TagsManager::InsertForwardDeclaration(const wxString& classname, const wxString& fileContent, wxString& lineToAdd, - int& line, const wxString& impExpMacro) +void TagsManager::InsertForwardDeclaration( + const wxString& classname, const wxString& fileContent, wxString& lineToAdd, int& line, const wxString& impExpMacro) { lineToAdd << "class "; - if(!impExpMacro.IsEmpty()) { + if (!impExpMacro.IsEmpty()) { lineToAdd << impExpMacro << " "; } lineToAdd << classname << ";"; @@ -737,8 +742,11 @@ void TagsManager::GetCXXKeywords(wxArrayString& words) TagEntryPtrVector_t TagsManager::ParseBuffer(const wxString& content, const wxString& filename, const wxString& kinds) { TagEntryPtrVector_t tagsVec; - CTags::ParseBuffer(filename, content, clStandardPaths::Get().GetBinaryFullPath("codelite-ctags"), - GetCtagsOptions().GetTokensWxMap(), tagsVec); + CTags::ParseBuffer(filename, + content, + clStandardPaths::Get().GetBinaryFullPath("codelite-ctags"), + GetCtagsOptions().GetTokensWxMap(), + tagsVec); return tagsVec; } @@ -750,7 +758,7 @@ void TagsManager::GetTagsByPartialNames(const wxArrayString& partialNames, std:: void TagsManager::ParseWorkspaceIncremental() { // restart ctagsd (this way we ensure that new settings are loaded) - clLanguageServerEvent stop_event{ wxEVT_LSP_RESTART }; + clLanguageServerEvent stop_event{wxEVT_LSP_RESTART}; stop_event.SetLspName("ctagsd"); EventNotifier::Get()->AddPendingEvent(stop_event); } @@ -758,20 +766,20 @@ void TagsManager::ParseWorkspaceIncremental() void TagsManager::ParseWorkspaceFull(const wxString& workspace_dir) { // stop ctagsd - clLanguageServerEvent stop_event{ wxEVT_LSP_STOP }; + clLanguageServerEvent stop_event{wxEVT_LSP_STOP}; stop_event.SetLspName("ctagsd"); EventNotifier::Get()->ProcessEvent(stop_event); // delete the tags.db file - wxFileName tags_db{ workspace_dir, "tags.db" }; + wxFileName tags_db{workspace_dir, "tags.db"}; tags_db.AppendDir(".ctagsd"); - if(tags_db.FileExists()) { + if (tags_db.FileExists()) { FileUtils::RemoveFile(tags_db, wxEmptyString); } // start ctagsd again - clLanguageServerEvent start_event{ wxEVT_LSP_START }; + clLanguageServerEvent start_event{wxEVT_LSP_START}; start_event.SetLspName("ctagsd"); EventNotifier::Get()->ProcessEvent(start_event); } diff --git a/CodeLite/ctags_manager.h b/CodeLite/ctags_manager.h index 82a366b37d..37dd31206d 100644 --- a/CodeLite/ctags_manager.h +++ b/CodeLite/ctags_manager.h @@ -29,8 +29,8 @@ #include "codelite_exports.h" #include "database/istorage.h" #include "macros.h" -#include "tags_options_data.h" #include "tag_tree.h" +#include "tags_options_data.h" #include @@ -168,7 +168,8 @@ class WXDLLIMPEXP_CL TagsManager : public wxEvtHandler * @brief parse source file (from memory) and return list of tags * If "filename" is passed, each returned TagEntryPtr will have it as its "File" attribute */ - TagEntryPtrVector_t ParseBuffer(const wxString& content, const wxString& filename = wxEmptyString, + TagEntryPtrVector_t ParseBuffer(const wxString& content, + const wxString& filename = wxEmptyString, const wxString& kinds = "cdefgmnpstuv"); /** @@ -303,7 +304,8 @@ class WXDLLIMPEXP_CL TagsManager : public wxEvtHandler * set to false * @return stripped functions signature */ - wxString NormalizeFunctionSig(const wxString& sig, size_t flags = Normalize_Func_Name, + wxString NormalizeFunctionSig(const wxString& sig, + size_t flags = Normalize_Func_Name, std::vector>* paramLen = NULL); /** @@ -318,7 +320,9 @@ class WXDLLIMPEXP_CL TagsManager : public wxEvtHandler * to place the function body. set visibility to 0 for 'public' function, 1 for 'protected' and 2 for private * return true if this function succeeded, false otherwise */ - bool InsertFunctionDecl(const wxString& clsname, const wxString& functionDecl, wxString& sourceContent, + bool InsertFunctionDecl(const wxString& clsname, + const wxString& functionDecl, + wxString& sourceContent, int visibility = 0); /** @@ -329,8 +333,11 @@ class WXDLLIMPEXP_CL TagsManager : public wxEvtHandler * @param line [output] line number where to add the forward declaration * @param impExpMacro [optional/input] Windows DLL Imp/Exp macro */ - void InsertForwardDeclaration(const wxString& classname, const wxString& fileContent, wxString& lineToAdd, - int& line, const wxString& impExpMacro = ""); + void InsertForwardDeclaration(const wxString& classname, + const wxString& fileContent, + wxString& lineToAdd, + int& line, + const wxString& impExpMacro = ""); protected: std::map m_typeScopeCache; @@ -352,13 +359,17 @@ class WXDLLIMPEXP_CL TagsManager : public wxEvtHandler * @param derivationList * @param scannedInherits */ - bool GetDerivationList(const wxString& path, TagEntryPtr parentTag, - std::vector>& derivationList, std::unordered_set& visited, + bool GetDerivationList(const wxString& path, + TagEntryPtr parentTag, + std::vector>& derivationList, + std::unordered_set& visited, int depth); - bool GetDerivationListInternal(const wxString& path, TagEntryPtr parentTag, + bool GetDerivationListInternal(const wxString& path, + TagEntryPtr parentTag, std::vector>& derivationList, - std::unordered_set& visited, int depth); + std::unordered_set& visited, + int depth); public: /** diff --git a/CodeLite/database/entry.cpp b/CodeLite/database/entry.cpp index 65a46ff376..9c5d2bcc38 100644 --- a/CodeLite/database/entry.cpp +++ b/CodeLite/database/entry.cpp @@ -23,6 +23,8 @@ ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// +#include "precompiled_header.h" + #include "entry.h" #include "CompletionHelper.hpp" @@ -31,7 +33,6 @@ #include "ctags_manager.h" #include "macros.h" #include "pptable.h" -#include "precompiled_header.h" #include "tokenizer.h" #include @@ -89,8 +90,12 @@ bool TagEntry::operator==(const TagEntry& rhs) const return res; } -void TagEntry::Create(const wxString& fileName, const wxString& name, int lineNumber, const wxString& pattern, - const wxString& kind, wxStringMap_t& extFields) +void TagEntry::Create(const wxString& fileName, + const wxString& name, + int lineNumber, + const wxString& pattern, + const wxString& kind, + wxStringMap_t& extFields) { m_flags = 0; m_extFields = extFields; @@ -104,10 +109,10 @@ void TagEntry::Create(const wxString& fileName, const wxString& name, int lineNu wxString path; // Check if we can get full name (including path) - static std::vector scope_fields = { "class", "struct", "namespace", "interface", "enum", "function" }; - for(const wxString& scope_field : scope_fields) { + static std::vector scope_fields = {"class", "struct", "namespace", "interface", "enum", "function"}; + for (const wxString& scope_field : scope_fields) { path = GetExtField(scope_field); - if(!path.IsEmpty()) { + if (!path.IsEmpty()) { UpdatePath(path); break; } @@ -115,11 +120,11 @@ void TagEntry::Create(const wxString& fileName, const wxString& name, int lineNu // still no path? // try union - if(path.empty()) { + if (path.empty()) { path = GetExtField("union"); wxString tmpname = path.AfterLast(':'); - if(!path.IsEmpty()) { - if(!tmpname.StartsWith("__anon")) { + if (!path.IsEmpty()) { + if (!tmpname.StartsWith("__anon")) { UpdatePath(path); } else { // anonymous union, remove the anonymous part from its name @@ -132,14 +137,14 @@ void TagEntry::Create(const wxString& fileName, const wxString& name, int lineNu // update the method properties SetTagProperties(GetExtField("properties")); - if(!path.IsEmpty()) { + if (!path.IsEmpty()) { SetScope(path); } else { SetScope(""); } // If there is no path, path is set to name - if(GetPath().IsEmpty()) { + if (GetPath().IsEmpty()) { SetPath(GetName()); } @@ -152,10 +157,10 @@ void TagEntry::Create(const wxString& fileName, const wxString& name, int lineNu // parse auto m_assignment = TypenameFromPattern(this); - if(IsAuto(this)) { + if (IsAuto(this)) { m_tag_properties_flags |= TAG_PROP_AUTO_VARIABLE; } - if(IsFunction() && GetName().StartsWith("__anon")) { + if (IsFunction() && GetName().StartsWith("__anon")) { m_tag_properties_flags |= TAG_PROP_INLINE; } } @@ -180,7 +185,7 @@ void TagEntry::Print() wxString TagEntry::Key() const { wxString key; - if(IsPrototype() || IsMacro()) { + if (IsPrototype() || IsMacro()) { key << GetKind() << ": "; } @@ -199,7 +204,7 @@ wxString TagEntry::GetFullDisplayName() const { wxString name; - if(GetParent() == "") { + if (GetParent() == "") { name << GetDisplayName(); } else { name << GetParent() << "::" << GetName() << GetSignature(); @@ -226,14 +231,11 @@ wxString TagEntry::GetKind() const return kind; } -bool TagEntry::IsContainer() const -{ - return IsClass() || IsStruct() || IsUnion() || IsNamespace() || IsEnumClass(); -} +bool TagEntry::IsContainer() const { return IsClass() || IsStruct() || IsUnion() || IsNamespace() || IsEnumClass(); } void TagEntry::UpdatePath(wxString& path) { - if(!path.IsEmpty()) { + if (!path.IsEmpty()) { wxString name(path); name += "::"; name += GetName(); @@ -244,7 +246,7 @@ void TagEntry::UpdatePath(wxString& path) const wxString& TagEntry::GetExtField(const wxString& extField) const { static wxString empty_string; - if(m_extFields.count(extField) == 0) { + if (m_extFields.count(extField) == 0) { return empty_string; } return m_extFields.find(extField)->second; @@ -281,12 +283,12 @@ void TagEntry::FromLine(const wxString& line) // or // line number followed by ;" int end = strLine.Find(";\""); - if(end == wxNOT_FOUND) { + if (end == wxNOT_FOUND) { // invalid pattern found return; } - if(strLine.StartsWith("/^")) { + if (strLine.StartsWith("/^")) { // regular expression pattern found pattern = strLine.Mid(0, end); strLine = strLine.Right(strLine.Length() - (end + 2)); @@ -302,16 +304,16 @@ void TagEntry::FromLine(const wxString& line) } // next is the kind of the token - if(strLine.StartsWith("\t")) { + if (strLine.StartsWith("\t")) { strLine = strLine.AfterFirst('\t'); } kind = strLine.BeforeFirst('\t'); strLine = strLine.AfterFirst('\t'); - if(strLine.IsEmpty() == false) { + if (strLine.IsEmpty() == false) { wxStringTokenizer tkz(strLine, '\t'); - while(tkz.HasMoreTokens()) { + while (tkz.HasMoreTokens()) { wxString token = tkz.NextToken(); wxString key = token.BeforeFirst(':'); wxString val = token.AfterFirst(':'); @@ -320,21 +322,21 @@ void TagEntry::FromLine(const wxString& line) val = val.Trim(); val = val.Trim(false); - if(key == "line" && !val.IsEmpty()) { + if (key == "line" && !val.IsEmpty()) { val.ToLong(&lineNumber); } else { - if(key == "union" || key == "struct") { + if (key == "union" || key == "struct") { // remove the anonymous part of the struct / union - if(!val.StartsWith("__anon")) { + if (!val.StartsWith("__anon")) { // an internal anonymous union / struct // remove all parts of the wxArrayString scopeArr; wxString tmp, new_val; scopeArr = wxStringTokenize(val, ":", wxTOKEN_STRTOK); - for(size_t i = 0; i < scopeArr.GetCount(); i++) { - if(scopeArr.Item(i).StartsWith("__anon") == false) { + for (size_t i = 0; i < scopeArr.GetCount(); i++) { + if (scopeArr.Item(i).StartsWith("__anon") == false) { tmp << scopeArr.Item(i) << "::"; } } @@ -343,7 +345,7 @@ void TagEntry::FromLine(const wxString& line) val.swap(new_val); } } - extFields.insert({ key, val }); + extFields.insert({key, val}); } } } @@ -357,7 +359,7 @@ void TagEntry::FromLine(const wxString& line) bool TagEntry::IsConstructor() const { - if(GetKind() != "function" && GetKind() != "prototype") { + if (GetKind() != "function" && GetKind() != "prototype") { return false; } return GetName() == GetScope(); @@ -365,7 +367,7 @@ bool TagEntry::IsConstructor() const bool TagEntry::IsDestructor() const { - if(GetKind() != "function" && GetKind() != "prototype") { + if (GetKind() != "function" && GetKind() != "prototype") { return false; } return GetName().StartsWith("~"); @@ -417,12 +419,12 @@ wxArrayString TagEntry::GetInheritsAsArrayNoTemplates() const wxArrayString parentsArr; int depth(0); - for(size_t i = 0; i < inherits.Length(); i++) { + for (size_t i = 0; i < inherits.Length(); i++) { wxChar ch = inherits.GetChar(i); - switch(ch) { + switch (ch) { case '<': - if(depth == 0 && parent.IsEmpty() == false) { + if (depth == 0 && parent.IsEmpty() == false) { parent.Trim().Trim(false); parentsArr.Add(parent); parent.Clear(); @@ -435,7 +437,7 @@ wxArrayString TagEntry::GetInheritsAsArrayNoTemplates() const break; case ',': - if(depth == 0 && parent.IsEmpty() == false) { + if (depth == 0 && parent.IsEmpty() == false) { parent.Trim().Trim(false); parentsArr.Add(parent); parent.Clear(); @@ -443,14 +445,14 @@ wxArrayString TagEntry::GetInheritsAsArrayNoTemplates() const break; default: - if(depth == 0) { + if (depth == 0) { parent << ch; } break; } } - if(parent.IsEmpty() == false) { + if (parent.IsEmpty() == false) { parent.Trim().Trim(false); parentsArr.Add(parent); } @@ -465,10 +467,10 @@ wxArrayString TagEntry::GetInheritsAsArrayWithTemplates() const wxArrayString parentsArr; int depth(0); - for(size_t i = 0; i < inherits.Length(); i++) { + for (size_t i = 0; i < inherits.Length(); i++) { wxChar ch = inherits.GetChar(i); - switch(ch) { + switch (ch) { case '<': depth++; parent << ch; @@ -480,12 +482,12 @@ wxArrayString TagEntry::GetInheritsAsArrayWithTemplates() const break; case ',': - if(depth == 0 && parent.IsEmpty() == false) { + if (depth == 0 && parent.IsEmpty() == false) { parent.Trim().Trim(false); parentsArr.Add(parent); parent.Clear(); - } else if(depth != 0) { + } else if (depth != 0) { parent << ch; } break; @@ -496,7 +498,7 @@ wxArrayString TagEntry::GetInheritsAsArrayWithTemplates() const } } - if(parent.IsEmpty() == false) { + if (parent.IsEmpty() == false) { parent.Trim().Trim(false); parentsArr.Add(parent); } @@ -505,12 +507,12 @@ wxArrayString TagEntry::GetInheritsAsArrayWithTemplates() const TagEntryPtr TagEntry::ReplaceSimpleMacro() { - if(IsMacro()) { + if (IsMacro()) { PPToken tok = TagsManagerST::Get()->GetDatabase()->GetMacro(GetName()); - if(tok.flags & PPToken::IsValid && !(tok.flags & PPToken::IsFunctionLike)) { + if (tok.flags & PPToken::IsValid && !(tok.flags & PPToken::IsFunctionLike)) { std::vector tags; TagsManagerST::Get()->FindByNameAndScope(tok.replacement, GetScopeName(), tags); - if(tags.size() == 1) { + if (tags.size() == 1) { // replace the current tag content with the new match return tags.at(0); } @@ -530,11 +532,11 @@ wxString TagEntry::GetPatternClean() const { wxString p = GetPattern(); p.Trim(); - if(p.StartsWith("/^")) { + if (p.StartsWith("/^")) { p.Replace("/^", ""); } - if(p.EndsWith("$/")) { + if (p.EndsWith("$/")) { p.Replace("$/", ""); } return p; @@ -546,7 +548,7 @@ namespace { void enable_function_flag_if_exists(const wxStringSet_t& S, const wxString& propname, const size_t flag, size_t& flags) { - if(S.count(propname)) { + if (S.count(propname)) { flags |= flag; } else { flags &= ~flag; @@ -559,7 +561,7 @@ void TagEntry::SetTagProperties(const wxString& props) m_tag_properties = props; auto tokens = wxStringTokenize(m_tag_properties, ",", wxTOKEN_STRTOK); wxStringSet_t S; - for(auto& token : tokens) { + for (auto& token : tokens) { token.Trim().Trim(false); S.insert(token); } @@ -575,7 +577,7 @@ void TagEntry::SetTagProperties(const wxString& props) enable_function_flag_if_exists(S, "scopedenum", TAG_PROP_SCOPEDENUM, m_tag_properties_flags); // change the kind to "enum class" - if(is_scoped_enum()) { + if (is_scoped_enum()) { m_tag_kind = eTagKind::TAG_KIND_CENUM; } } @@ -594,25 +596,25 @@ bool TagEntry::is_lambda() const { return m_tag_properties_flags & TAG_PROP_LAMB wxString TagEntry::GetFunctionDeclaration() const { - if(!IsMethod()) { + if (!IsMethod()) { return wxEmptyString; } wxString decl; - if(is_func_inline()) { + if (is_func_inline()) { decl << "inline "; } - if(is_func_virtual()) { + if (is_func_virtual()) { decl << "virtual "; } decl << GetTypename() << " "; - if(!GetScope().empty()) { + if (!GetScope().empty()) { decl << GetScope() << "::"; } decl << GetName() << GetSignature(); - if(is_const()) { + if (is_const()) { decl << " const"; } - if(is_func_pure()) { + if (is_func_pure()) { decl << " = 0"; } decl << ";"; @@ -622,11 +624,11 @@ wxString TagEntry::GetFunctionDeclaration() const wxString TagEntry::GetFunctionDefinition() const { wxString impl; - if(!IsMethod()) { + if (!IsMethod()) { return wxEmptyString; } impl << GetTypename() << " "; - if(!GetScope().empty()) { + if (!GetScope().empty()) { impl << GetScope() << "::"; } @@ -640,14 +642,22 @@ wxString TagEntry::GetFunctionDefinition() const namespace { std::unordered_map g_kind_table = { - { "class", eTagKind::TAG_KIND_CLASS }, { "struct", eTagKind::TAG_KIND_STRUCT }, - { "namespace", eTagKind::TAG_KIND_NAMESPACE }, { "union", eTagKind::TAG_KIND_UNION }, - { "enum", eTagKind::TAG_KIND_ENUM }, { "member", eTagKind::TAG_KIND_MEMBER }, - { "variable", eTagKind::TAG_KIND_VARIABLE }, { "macro", eTagKind::TAG_KIND_MACRO }, - { "typedef", eTagKind::TAG_KIND_TYPEDEF }, { "local", eTagKind::TAG_KIND_LOCAL }, - { "parameter", eTagKind::TAG_KIND_PARAMETER }, { "prototype", eTagKind::TAG_KIND_PROTOTYPE }, - { "cpp_keyword", eTagKind::TAG_KIND_KEYWORD }, { "keyword", eTagKind::TAG_KIND_KEYWORD }, - { "function", eTagKind::TAG_KIND_FUNCTION }, { "enumerator", eTagKind::TAG_KIND_ENUMERATOR }, + {"class", eTagKind::TAG_KIND_CLASS}, + {"struct", eTagKind::TAG_KIND_STRUCT}, + {"namespace", eTagKind::TAG_KIND_NAMESPACE}, + {"union", eTagKind::TAG_KIND_UNION}, + {"enum", eTagKind::TAG_KIND_ENUM}, + {"member", eTagKind::TAG_KIND_MEMBER}, + {"variable", eTagKind::TAG_KIND_VARIABLE}, + {"macro", eTagKind::TAG_KIND_MACRO}, + {"typedef", eTagKind::TAG_KIND_TYPEDEF}, + {"local", eTagKind::TAG_KIND_LOCAL}, + {"parameter", eTagKind::TAG_KIND_PARAMETER}, + {"prototype", eTagKind::TAG_KIND_PROTOTYPE}, + {"cpp_keyword", eTagKind::TAG_KIND_KEYWORD}, + {"keyword", eTagKind::TAG_KIND_KEYWORD}, + {"function", eTagKind::TAG_KIND_FUNCTION}, + {"enumerator", eTagKind::TAG_KIND_ENUMERATOR}, }; } @@ -657,15 +667,15 @@ void TagEntry::SetKind(const wxString& kind) m_kind = kind; // turn on bits m_tag_kind = eTagKind::TAG_KIND_UNKNOWN; - if(g_kind_table.count(m_kind)) { + if (g_kind_table.count(m_kind)) { m_tag_kind = g_kind_table[m_kind]; } } namespace { -void read_until_find(CxxTokenizer& tokenizer, CxxLexerToken& token, int type_1, int type_2, int* what_was_found, - wxString* consumed) +void read_until_find( + CxxTokenizer& tokenizer, CxxLexerToken& token, int type_1, int type_2, int* what_was_found, wxString* consumed) { // search until we find the `=` int depth = 0; @@ -673,27 +683,27 @@ void read_until_find(CxxTokenizer& tokenizer, CxxLexerToken& token, int type_1, *what_was_found = 0; consumed->reserve(256); // 256 bytes should be enough for most cases - while(tokenizer.NextToken(token)) { - if(depth == 0 && token.GetType() == type_1) { + while (tokenizer.NextToken(token)) { + if (depth == 0 && token.GetType() == type_1) { *what_was_found = type_1; consumed->Trim().Trim(false); return; - } else if(depth == 0 && token.GetType() == type_2) { + } else if (depth == 0 && token.GetType() == type_2) { *what_was_found = type_2; consumed->Trim().Trim(false); return; } - if(token.is_keyword() || token.is_builtin_type()) { + if (token.is_keyword() || token.is_builtin_type()) { consumed->Append(token.GetWXString() + " "); continue; - } else if(token.is_pp_keyword()) { + } else if (token.is_pp_keyword()) { continue; } // append it consumed->Append(token.GetWXString()); - switch(token.GetType()) { + switch (token.GetType()) { case '<': case '{': case '[': @@ -717,12 +727,12 @@ void read_until_find(CxxTokenizer& tokenizer, CxxLexerToken& token, int type_1, } // namespace #define CHECK_FOUND(What, Expected) \ - if(What != Expected) \ + if (What != Expected) \ return wxEmptyString wxString TagEntry::TypenameFromPattern(const TagEntry* tag) { - if(!tag->IsLocalVariable() && !tag->IsVariable()) { + if (!tag->IsLocalVariable() && !tag->IsVariable()) { return wxEmptyString; } CxxTokenizer tokenizer; @@ -734,11 +744,11 @@ wxString TagEntry::TypenameFromPattern(const TagEntry* tag) int what_was_found = 0; wxString consumed; read_until_find(tokenizer, token, T_FOR, '=', &what_was_found, &consumed); - if(what_was_found == 0) { + if (what_was_found == 0) { return wxEmptyString; } - if(what_was_found == '=') { + if (what_was_found == '=') { // read until we reach eof or ';' read_until_find(tokenizer, token, ';', 0, &what_was_found, &consumed); return consumed; @@ -780,8 +790,8 @@ void TagEntry::SetMacrodef(const wxString& value) { set_extra_field("macrodef", void TagEntry::set_extra_field(const wxString& name, const wxString& value) { - if(m_extFields.count(name)) { + if (m_extFields.count(name)) { m_extFields.erase(name); } - m_extFields.insert({ name, value }); + m_extFields.insert({name, value}); } diff --git a/CodeLite/database/entry.h b/CodeLite/database/entry.h index 94be4656db..4b06e7775b 100644 --- a/CodeLite/database/entry.h +++ b/CodeLite/database/entry.h @@ -148,7 +148,7 @@ class WXDLLIMPEXP_CL TagEntry } void operator()(TagEntryPtr tag) { - if(tag->IsConstructor()) { + if (tag->IsConstructor()) { m_matches.push_back(tag); } } @@ -253,8 +253,12 @@ class WXDLLIMPEXP_CL TagEntry * \param extFields Map of extension fields (key:value) * \param project Project name */ - void Create(const wxString& fileName, const wxString& name, int lineNumber, const wxString& pattern, - const wxString& kind, wxStringMap_t& extFields); + void Create(const wxString& fileName, + const wxString& name, + int lineNumber, + const wxString& pattern, + const wxString& kind, + wxStringMap_t& extFields); /** * Test if this entry has been initialised. diff --git a/CodeLite/database/fileentry.cpp b/CodeLite/database/fileentry.cpp index 8b93e7aaff..0e45439b49 100644 --- a/CodeLite/database/fileentry.cpp +++ b/CodeLite/database/fileentry.cpp @@ -28,8 +28,8 @@ #include FileEntry::FileEntry() - : m_id (wxNOT_FOUND) - , m_file (wxEmptyString) - , m_lastRetaggedTimestamp((int)time(NULL)) + : m_id(wxNOT_FOUND) + , m_file(wxEmptyString) + , m_lastRetaggedTimestamp((int)time(NULL)) { } diff --git a/CodeLite/database/fileentry.h b/CodeLite/database/fileentry.h index 36bf150e1a..fed82a998e 100644 --- a/CodeLite/database/fileentry.h +++ b/CodeLite/database/fileentry.h @@ -31,25 +31,21 @@ class FileEntry { - long m_id; - wxString m_file; - int m_lastRetaggedTimestamp; + long m_id; + wxString m_file; + int m_lastRetaggedTimestamp; public: - FileEntry(); - ~FileEntry() = default; + FileEntry(); + ~FileEntry() = default; public: - void SetFile(const wxString& file) { - this->m_file = file; - } - void SetLastRetaggedTimestamp(int lastRetaggedTimestamp) { this->m_lastRetaggedTimestamp = lastRetaggedTimestamp; } - const wxString& GetFile() const { - return m_file; - } - int GetLastRetaggedTimestamp() const { return m_lastRetaggedTimestamp; } - void SetId(long id) { this->m_id = id; } - long GetId() const { return m_id; } + void SetFile(const wxString& file) { this->m_file = file; } + void SetLastRetaggedTimestamp(int lastRetaggedTimestamp) { this->m_lastRetaggedTimestamp = lastRetaggedTimestamp; } + const wxString& GetFile() const { return m_file; } + int GetLastRetaggedTimestamp() const { return m_lastRetaggedTimestamp; } + void SetId(long id) { this->m_id = id; } + long GetId() const { return m_id; } }; using FileEntryPtr = std::unique_ptr; diff --git a/CodeLite/database/istorage.h b/CodeLite/database/istorage.h index 1e11fa430f..4ded6177d3 100644 --- a/CodeLite/database/istorage.h +++ b/CodeLite/database/istorage.h @@ -80,7 +80,7 @@ class ITagsStorage void SetSingleSearchLimit(int singleSearchLimit) { - if(singleSearchLimit < 0) { + if (singleSearchLimit < 0) { singleSearchLimit = MAX_SEARCH_LIMIT; } this->m_singleSearchLimit = singleSearchLimit; @@ -98,9 +98,13 @@ class ITagsStorage * @param name * @param partialNameAllowed */ - virtual void GetTagsByScopeAndName(const wxString& scope, const wxString& name, bool partialNameAllowed, + virtual void GetTagsByScopeAndName(const wxString& scope, + const wxString& name, + bool partialNameAllowed, std::vector& tags) = 0; - virtual void GetTagsByScopeAndName(const wxArrayString& scope, const wxString& name, bool partialNameAllowed, + virtual void GetTagsByScopeAndName(const wxArrayString& scope, + const wxString& name, + bool partialNameAllowed, std::vector& tags) = 0; /** @@ -120,7 +124,9 @@ class ITagsStorage * @param order OrderAsc, OrderDesc or use OrderNone for no ordering the results * @param tags */ - virtual void GetTagsByKind(const wxArrayString& kinds, const wxString& orderingColumn, int order, + virtual void GetTagsByKind(const wxArrayString& kinds, + const wxString& orderingColumn, + int order, std::vector& tags) = 0; /** @@ -130,16 +136,18 @@ class ITagsStorage */ virtual void GetTagsByPath(const wxArrayString& path, std::vector& tags) = 0; virtual void GetTagsByPath(const wxString& path, std::vector& tags, int limit = 1) = 0; - virtual void GetTagsByPathAndKind(const wxString& path, std::vector& tags, - const std::vector& kinds, int limit = 1) = 0; + virtual void GetTagsByPathAndKind(const wxString& path, + std::vector& tags, + const std::vector& kinds, + int limit = 1) = 0; /** * @brief return array of items by name and parent * @param path * @param tags */ - virtual void GetTagsByNameAndParent(const wxString& name, const wxString& parent, - std::vector& tags) = 0; + virtual void + GetTagsByNameAndParent(const wxString& name, const wxString& parent, std::vector& tags) = 0; /** * @brief return array of tags by kind and path @@ -147,8 +155,8 @@ class ITagsStorage * @param path * @param tags [output] */ - virtual void GetTagsByKindAndPath(const wxArrayString& kinds, const wxString& path, - std::vector& tags) = 0; + virtual void + GetTagsByKindAndPath(const wxArrayString& kinds, const wxString& path, std::vector& tags) = 0; /** * @brief return tags by file and line number @@ -164,7 +172,9 @@ class ITagsStorage * @param kinds * @param tags [output] */ - virtual void GetTagsByScopeAndKind(const wxString& scope, const wxArrayString& kinds, const wxString& filter, + virtual void GetTagsByScopeAndKind(const wxString& scope, + const wxArrayString& kinds, + const wxString& filter, std::vector& tags) = 0; /** @@ -174,8 +184,11 @@ class ITagsStorage * @param order OrderAsc, OrderDesc or use OrderNone for no ordering the results * @param tags */ - virtual void GetTagsByKindAndFile(const wxArrayString& kind, const wxString& fileName, - const wxString& orderingColumn, int order, std::vector& tags) = 0; + virtual void GetTagsByKindAndFile(const wxArrayString& kind, + const wxString& fileName, + const wxString& orderingColumn, + int order, + std::vector& tags) = 0; /** * @brief @@ -222,8 +235,8 @@ class ITagsStorage * @param path Database file name * @return result set */ - virtual void SelectTagsByFile(const wxString& file, std::vector& tags, - const wxFileName& path = wxFileName()) = 0; + virtual void + SelectTagsByFile(const wxString& file, std::vector& tags, const wxFileName& path = wxFileName()) = 0; /** * @brief return true if type exist under a given scope. @@ -320,8 +333,8 @@ class ITagsStorage * @param kinds array of possible kinds * @param tags [output] */ - virtual void GetTagsByScopesAndKind(const wxArrayString& scopes, const wxArrayString& kinds, - std::vector& tags) = 0; + virtual void + GetTagsByScopesAndKind(const wxArrayString& scopes, const wxArrayString& kinds, std::vector& tags) = 0; /** * @brief return macro evaluation @@ -354,7 +367,9 @@ class ITagsStorage * this usually includes static members, or any entity * in an anonymous namespace */ - virtual size_t GetFileScopedTags(const wxString& filepath, const wxString& name, const wxArrayString& kinds, + virtual size_t GetFileScopedTags(const wxString& filepath, + const wxString& name, + const wxArrayString& kinds, std::vector& tags) = 0; /** diff --git a/CodeLite/database/tags_storage_sqlite3.cpp b/CodeLite/database/tags_storage_sqlite3.cpp index 4f2ffdcaa9..d586a510ad 100644 --- a/CodeLite/database/tags_storage_sqlite3.cpp +++ b/CodeLite/database/tags_storage_sqlite3.cpp @@ -22,12 +22,13 @@ // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// +#include "precompiled_header.h" + #include "tags_storage_sqlite3.h" #include "file_logger.h" #include "fileutils.h" #include "macros.h" -#include "precompiled_header.h" #include #include @@ -46,7 +47,7 @@ TagsStorageSQLite::TagsStorageSQLite() TagsStorageSQLite::~TagsStorageSQLite() { - if(m_db) { + if (m_db) { m_db->Close(); delete m_db; m_db = NULL; @@ -55,20 +56,20 @@ TagsStorageSQLite::~TagsStorageSQLite() void TagsStorageSQLite::OpenDatabase(const wxFileName& fileName) { - if(m_fileName.GetFullPath() == fileName.GetFullPath()) + if (m_fileName.GetFullPath() == fileName.GetFullPath()) return; // Did we get a file name to use? - if(!fileName.IsOk() && !m_fileName.IsOk()) + if (!fileName.IsOk() && !m_fileName.IsOk()) return; // We did not get any file name to use BUT we // do have an open database, so we will use it - if(!fileName.IsOk()) + if (!fileName.IsOk()) return; try { - if(!m_fileName.IsOk()) { + if (!m_fileName.IsOk()) { // First time we open the db m_db->Open(fileName.GetFullPath()); m_db->SetBusyTimeout(10); @@ -214,7 +215,7 @@ wxString TagsStorageSQLite::GetSchemaVersion() const sql = wxT("SELECT * FROM TAGS_VERSION"); wxSQLite3ResultSet rs = m_db->ExecuteQuery(sql); - if(rs.NextRow()) + if (rs.NextRow()) version = rs.GetString(0); return version; } catch (const wxSQLite3Exception& e) { @@ -225,7 +226,7 @@ wxString TagsStorageSQLite::GetSchemaVersion() const #define SAFE_ROLLBACK_IF_NEEDED(Auto_Commit) \ try { \ - if(Auto_Commit) \ + if (Auto_Commit) \ m_db->Rollback(); \ } catch (const wxSQLite3Exception&) { \ } @@ -233,7 +234,7 @@ wxString TagsStorageSQLite::GetSchemaVersion() const void TagsStorageSQLite::Store(const std::vector& tags, bool auto_commit) { try { - if(auto_commit) + if (auto_commit) m_db->Begin(); } catch (const wxSQLite3Exception& e) { clWARNING() << "failed to start tx." << e.GetMessage() << endl; @@ -243,13 +244,13 @@ void TagsStorageSQLite::Store(const std::vector& tags, bool auto_co // build list of files wxStringSet_t files; - for(auto tag : tags) { + for (auto tag : tags) { files.insert(tag->GetFile()); } try { // delete all tags owned by these files - for(const wxString& file : files) { + for (const wxString& file : files) { DeleteByFileName({}, file, false); } } catch (const wxSQLite3Exception& e) { @@ -260,9 +261,9 @@ void TagsStorageSQLite::Store(const std::vector& tags, bool auto_co // store the tags try { - for(auto tag : tags) { + for (auto tag : tags) { // we don't store local variables - if(tag->IsLocalVariable()) + if (tag->IsLocalVariable()) continue; DoInsertTagEntry(*tag); } @@ -273,7 +274,7 @@ void TagsStorageSQLite::Store(const std::vector& tags, bool auto_co // commit try { - if(auto_commit) + if (auto_commit) m_db->Commit(); } catch (const wxSQLite3Exception& e) { clWARNING() << "failed to commit tx." << e.GetMessage() << endl; @@ -307,18 +308,18 @@ void TagsStorageSQLite::DeleteByFileName(const wxFileName& path, const wxString& try { OpenDatabase(path); - if(autoCommit) { + if (autoCommit) { m_db->Begin(); } wxString sql; sql << "delete from tags where File='" << fileName << "'"; m_db->ExecuteUpdate(sql); - if(autoCommit) + if (autoCommit) m_db->Commit(); } catch (const wxSQLite3Exception& e) { wxUnusedVar(e); - if(autoCommit) { + if (autoCommit) { m_db->Rollback(); } } @@ -334,7 +335,7 @@ wxSQLite3ResultSet TagsStorageSQLite::Query(const wxString& sql, const wxFileNam return m_db->ExecuteQuery(sql); } catch (const wxSQLite3Exception& e) { clWARNING() << "Query error:" << sql << "." << e.GetMessage(); - if(e.GetMessage().Contains("disk I/O error")) { + if (e.GetMessage().Contains("disk I/O error")) { ReOpenDatabase(); } } @@ -371,13 +372,13 @@ void TagsStorageSQLite::GetFilesForCC(const wxString& userTyped, wxArrayString& pattern.Replace("\\", "/"); wxSQLite3ResultSet res = m_db->ExecuteQuery(query); - while(res.NextRow()) { + while (res.NextRow()) { // Keep the part from where the user typed and until the end of the file name wxString matchedFile = res.GetString(1); matchedFile.Replace("\\", "/"); int where = matchedFile.Find(pattern); - if(where == wxNOT_FOUND) + if (where == wxNOT_FOUND) continue; matchedFile = matchedFile.Mid(where); matches.Add(matchedFile); @@ -400,7 +401,7 @@ void TagsStorageSQLite::GetFiles(const wxString& partialName, std::vectorExecuteQuery(query); - while(res.NextRow()) { + while (res.NextRow()) { FileEntryPtr fe(new FileEntry()); fe->SetId(res.GetInt(0)); @@ -419,7 +420,7 @@ void TagsStorageSQLite::GetFiles(const wxString& partialName, std::vector& files) // Pre allocate a reasonable amount of entries files.reserve(5000); - while(res.NextRow()) { + while (res.NextRow()) { FileEntryPtr fe(new FileEntry()); fe->SetId(res.GetInt(0)); fe->SetFile(res.GetString(1)); @@ -462,7 +463,7 @@ void TagsStorageSQLite::PPTokenFromSQlite3ResultSet(wxSQLite3ResultSet& rs, PPTo // set the flags token.flags = PPToken::IsValid; - if(isFunctionLike) + if (isFunctionLike) token.flags |= PPToken::IsFunctionLike; token.line = rs.GetInt(2); @@ -498,7 +499,7 @@ TagEntry* TagsStorageSQLite::FromSQLite3ResultSet(wxSQLite3ResultSet& rs) void TagsStorageSQLite::DoFetchTags(const wxString& sql, std::vector& tags) { - if(GetUseCache() && m_cache.Get(sql, tags)) { + if (GetUseCache() && m_cache.Get(sql, tags)) { return; } @@ -510,7 +511,7 @@ void TagsStorageSQLite::DoFetchTags(const wxString& sql, std::vector& tags, const wxArrayString& kinds) { - if(GetUseCache() && m_cache.Get(sql, kinds, tags)) + if (GetUseCache() && m_cache.Get(sql, kinds, tags)) return; wxStringSet_t set_kinds; @@ -546,9 +547,9 @@ void TagsStorageSQLite::DoFetchTags(const wxString& sql, std::vector& tags) { - if(name.IsEmpty()) + if (name.IsEmpty()) return; wxString sql; sql << wxT("select * from tags where "); // did we get scope? - if(scope.IsEmpty() || scope == wxT("")) { + if (scope.IsEmpty() || scope == wxT("")) { sql << wxT("ID IN (select tag_id from global_tags where "); DoAddNamePartToQuery(sql, name, partialNameAllowed, false); sql << wxT(" ) "); @@ -608,20 +611,22 @@ void TagsStorageSQLite::GetTagsByScope(const wxString& scope, std::vector& tags) { wxString sql; sql << wxT("select * from tags where kind in ("); - for(size_t i = 0; i < kinds.GetCount(); i++) { + for (size_t i = 0; i < kinds.GetCount(); i++) { sql << wxT("'") << kinds.Item(i) << wxT("',"); } sql.RemoveLast(); sql << wxT(") "); - if(orderingColumn.IsEmpty() == false) { + if (orderingColumn.IsEmpty() == false) { sql << wxT("order by ") << orderingColumn; - switch(order) { + switch (order) { case ITagsStorage::OrderAsc: sql << wxT(" ASC"); break; @@ -639,13 +644,13 @@ void TagsStorageSQLite::GetTagsByKind(const wxArrayString& kinds, const wxString void TagsStorageSQLite::GetTagsByPath(const wxArrayString& path, std::vector& tags) { - if(path.empty()) + if (path.empty()) return; wxString sql; sql << wxT("select * from tags where path IN("); - for(size_t i = 0; i < path.GetCount(); i++) { + for (size_t i = 0; i < path.GetCount(); i++) { sql << wxT("'") << path.Item(i) << wxT("',"); } sql.RemoveLast(); @@ -653,7 +658,8 @@ void TagsStorageSQLite::GetTagsByPath(const wxArrayString& path, std::vector& tags) { wxString sql; @@ -670,10 +676,11 @@ void TagsStorageSQLite::GetTagsByNameAndParent(const wxString& name, const wxStr } } -void TagsStorageSQLite::GetTagsByKindAndPath(const wxArrayString& kinds, const wxString& path, +void TagsStorageSQLite::GetTagsByKindAndPath(const wxArrayString& kinds, + const wxString& path, std::vector& tags) { - if(kinds.empty()) { + if (kinds.empty()) { return; } @@ -690,25 +697,28 @@ void TagsStorageSQLite::GetTagsByFileAndLine(const wxString& file, int line, std DoFetchTags(sql, tags); } -void TagsStorageSQLite::GetTagsByKindAndFile(const wxArrayString& kind, const wxString& fileName, - const wxString& orderingColumn, int order, std::vector& tags) +void TagsStorageSQLite::GetTagsByKindAndFile(const wxArrayString& kind, + const wxString& fileName, + const wxString& orderingColumn, + int order, + std::vector& tags) { - if(kind.empty()) { + if (kind.empty()) { return; } wxString sql; sql << wxT("select * from tags where file='") << fileName << wxT("' and kind in ("); - for(size_t i = 0; i < kind.GetCount(); i++) { + for (size_t i = 0; i < kind.GetCount(); i++) { sql << wxT("'") << kind.Item(i) << wxT("',"); } sql.RemoveLast(); sql << wxT(")"); - if(orderingColumn.IsEmpty() == false) { + if (orderingColumn.IsEmpty() == false) { sql << wxT("order by ") << orderingColumn; - switch(order) { + switch (order) { case ITagsStorage::OrderAsc: sql << wxT(" ASC"); break; @@ -731,7 +741,7 @@ int TagsStorageSQLite::DeleteFileEntry(const wxString& filename) statement.ExecuteUpdate(); } catch (const wxSQLite3Exception& exc) { - if(exc.ErrorCodeAsString(exc.GetErrorCode()) == wxT("SQLITE_CONSTRAINT")) + if (exc.ErrorCodeAsString(exc.GetErrorCode()) == wxT("SQLITE_CONSTRAINT")) return TagExist; return TagError; } @@ -771,11 +781,11 @@ int TagsStorageSQLite::UpdateFileEntry(const wxString& filename, int timestamp) int TagsStorageSQLite::DoInsertTagEntry(const TagEntry& tag) { // If this node is a dummy, (IsOk() == false) we don't insert it to database - if(!tag.IsOk()) + if (!tag.IsOk()) return TagOk; // does not matter if we insert or update, the cache must be cleared for any related tags - if(GetUseCache()) { + if (GetUseCache()) { ClearCache(); } @@ -816,10 +826,10 @@ bool TagsStorageSQLite::IsTypeAndScopeExist(wxString& typeName, wxString& scope) strippedName = typeName.AfterLast(wxT(':')); secondScope = typeName.BeforeLast(wxT(':')); - if(secondScope.EndsWith(wxT(":"))) + if (secondScope.EndsWith(wxT(":"))) secondScope.RemoveLast(); - if(strippedName.IsEmpty()) + if (strippedName.IsEmpty()) return false; sql << wxT("select scope,parent from tags where name='") << strippedName @@ -828,25 +838,25 @@ bool TagsStorageSQLite::IsTypeAndScopeExist(wxString& typeName, wxString& scope) wxString scopeFounded; wxString parentFounded; - if(secondScope.IsEmpty() == false) + if (secondScope.IsEmpty() == false) tmpScope << wxT("::") << secondScope; parent = tmpScope.AfterLast(wxT(':')); try { wxSQLite3ResultSet rs = Query(sql); - while(rs.NextRow()) { + while (rs.NextRow()) { scopeFounded = rs.GetString(0); parentFounded = rs.GetString(1); - if(scopeFounded == tmpScope) { + if (scopeFounded == tmpScope) { // exact match scope = scopeFounded; typeName = strippedName; return true; - } else if(parentFounded == parent) { + } else if (parentFounded == parent) { bestScope = scopeFounded; } else { @@ -859,12 +869,12 @@ bool TagsStorageSQLite::IsTypeAndScopeExist(wxString& typeName, wxString& scope) } // if we reached here, it means we did not find any exact match - if(bestScope.IsEmpty() == false) { + if (bestScope.IsEmpty() == false) { scope = bestScope; typeName = strippedName; return true; - } else if(foundOther == 1) { + } else if (foundOther == 1) { scope = scopeFounded; typeName = strippedName; return true; @@ -872,15 +882,16 @@ bool TagsStorageSQLite::IsTypeAndScopeExist(wxString& typeName, wxString& scope) return false; } -void TagsStorageSQLite::GetTagsByScopesAndKind(const wxArrayString& scopes, const wxArrayString& kinds, +void TagsStorageSQLite::GetTagsByScopesAndKind(const wxArrayString& scopes, + const wxArrayString& kinds, std::vector& tags) { - if(kinds.empty() || scopes.empty()) { + if (kinds.empty() || scopes.empty()) { return; } // fetch from the scopes, in-order (i.e. first scope tags and so on) - for(const wxString& scope : scopes) { + for (const wxString& scope : scopes) { wxString sql; sql << "select * from tags where scope = '" << scope << "' ORDER BY NAME"; DoAddLimitPartToQuery(sql, tags); @@ -889,7 +900,7 @@ void TagsStorageSQLite::GetTagsByScopesAndKind(const wxArrayString& scopes, cons DoFetchTags(sql, scope_results, kinds); tags.reserve(tags.size() + scope_results.size()); tags.insert(tags.end(), scope_results.begin(), scope_results.end()); - if((GetSingleSearchLimit() > 0) && (static_cast(tags.size()) > GetSingleSearchLimit())) { + if ((GetSingleSearchLimit() > 0) && (static_cast(tags.size()) > GetSingleSearchLimit())) { break; } } @@ -897,7 +908,7 @@ void TagsStorageSQLite::GetTagsByScopesAndKind(const wxArrayString& scopes, cons void TagsStorageSQLite::GetTagsByPath(const wxString& path, std::vector& tags, int limit) { - if(path.empty()) + if (path.empty()) return; wxString sql; @@ -905,12 +916,14 @@ void TagsStorageSQLite::GetTagsByPath(const wxString& path, std::vector& tags) { - if(scope.empty()) + if (scope.empty()) return; - if(name.IsEmpty()) + if (name.IsEmpty()) return; wxArrayString scopes = scope; @@ -919,16 +932,16 @@ void TagsStorageSQLite::GetTagsByScopeAndName(const wxArrayString& scope, const // we use the more specialized method for the scope by querying the // GLOBAL_TAGS table int where = scopes.Index(wxT("")); - if(where != wxNOT_FOUND) { + if (where != wxNOT_FOUND) { scopes.RemoveAt(where); GetTagsByScopeAndName(wxString(wxT("")), name, partialNameAllowed, tags); } - if(scopes.IsEmpty() == false) { + if (scopes.IsEmpty() == false) { wxString sql; sql << wxT("select * from tags where scope in("); - for(size_t i = 0; i < scopes.GetCount(); i++) { + for (size_t i = 0; i < scopes.GetCount(); i++) { sql << wxT("'") << scopes.Item(i) << wxT("',"); } sql.RemoveLast(); @@ -941,24 +954,26 @@ void TagsStorageSQLite::GetTagsByScopeAndName(const wxArrayString& scope, const } } -void TagsStorageSQLite::GetTagsByScopeAndKind(const wxString& scope, const wxArrayString& kinds, const wxString& filter, +void TagsStorageSQLite::GetTagsByScopeAndKind(const wxString& scope, + const wxArrayString& kinds, + const wxString& filter, std::vector& tags) { - if(kinds.empty()) { + if (kinds.empty()) { return; } wxString sql; sql << "select * from tags where scope='" << scope << "' "; - if(!filter.empty()) { + if (!filter.empty()) { sql << "and name LIKE '" << filter << "%%' ESCAPE '^' "; } - if(!kinds.empty()) { + if (!kinds.empty()) { sql << " and KIND IN("; wxString kinds_buffer; - for(const wxString& kind : kinds) { - if(!kinds_buffer.empty()) { + for (const wxString& kind : kinds) { + if (!kinds_buffer.empty()) { kinds_buffer << ","; } kinds_buffer << "'" << kind << "'"; @@ -977,7 +992,7 @@ bool TagsStorageSQLite::IsTypeAndScopeExistLimitOne(const wxString& typeName, co wxString path; // Build the path - if(scope.IsEmpty() == false && scope != wxT("")) + if (scope.IsEmpty() == false && scope != wxT("")) path << scope << wxT("::"); path << typeName; @@ -986,7 +1001,7 @@ bool TagsStorageSQLite::IsTypeAndScopeExistLimitOne(const wxString& typeName, co try { wxSQLite3ResultSet rs = Query(sql); - if(rs.NextRow()) { + if (rs.NextRow()) { return true; } @@ -1022,7 +1037,7 @@ bool TagsStorageSQLiteCache::Get(const wxString& sql, const wxArrayString& kind, { wxString key; key << sql; - for(size_t i = 0; i < kind.GetCount(); i++) { + for (size_t i = 0; i < kind.GetCount(); i++) { key << wxT("@") << kind.Item(i); } @@ -1037,7 +1052,7 @@ void TagsStorageSQLiteCache::Store(const wxString& sql, const wxArrayString& kin { wxString key; key << sql; - for(size_t i = 0; i < kind.GetCount(); i++) { + for (size_t i = 0; i < kind.GetCount(); i++) { key << wxT("@") << kind.Item(i); } DoStore(key, tags); @@ -1046,7 +1061,7 @@ void TagsStorageSQLiteCache::Store(const wxString& sql, const wxArrayString& kin bool TagsStorageSQLiteCache::DoGet(const wxString& key, std::vector& tags) { auto iter = m_cache.find(key); - if(iter != m_cache.end()) { + if (iter != m_cache.end()) { // Append the results to the output tags tags.reserve(tags.size() + iter->second.size()); tags.insert(tags.end(), iter->second.begin(), iter->second.end()); @@ -1057,7 +1072,7 @@ bool TagsStorageSQLiteCache::DoGet(const wxString& key, std::vector void TagsStorageSQLiteCache::DoStore(const wxString& key, const std::vector& tags) { - if(m_cache.count(key)) { + if (m_cache.count(key)) { m_cache.erase(key); } @@ -1065,15 +1080,15 @@ void TagsStorageSQLiteCache::DoStore(const wxString& key, const std::vectorGetScope().StartsWith("__anon")) { + for (auto tag : tags) { + if (tag->GetScope().StartsWith("__anon")) { can_cache = false; break; } } - if(can_cache) { - m_cache.insert({ key, tags }); + if (can_cache) { + m_cache.insert({key, tags}); } } @@ -1090,7 +1105,7 @@ PPToken TagsStorageSQLite::GetMacro(const wxString& name) wxString sql; sql << wxT("select * from MACROS where name = '") << name << wxT("'"); wxSQLite3ResultSet res = m_db->ExecuteQuery(sql); - if(res.NextRow()) { + if (res.NextRow()) { PPTokenFromSQlite3ResultSet(res, token); return token; } @@ -1106,7 +1121,7 @@ void TagsStorageSQLite::SetUseCache(bool useCache) { ITagsStorage::SetUseCache(u void TagsStorageSQLite::GetTagsByName(const wxString& prefix, std::vector& tags, bool exactMatch) { try { - if(prefix.IsEmpty()) + if (prefix.IsEmpty()) return; wxString sql; @@ -1122,16 +1137,16 @@ void TagsStorageSQLite::GetTagsByName(const wxString& prefix, std::vector= '") << from << wxT("' AND name < '") << until << wxT("'"); } else { sql << wxT(" name ='") << name << wxT("' "); @@ -1155,7 +1170,7 @@ void TagsStorageSQLite::DoAddNamePartToQuery(wxString& sql, const wxString& name void TagsStorageSQLite::DoAddLimitPartToQuery(wxString& sql, const std::vector& tags) { - if(tags.size() >= (size_t)GetSingleSearchLimit()) { + if (tags.size() >= (size_t)GetSingleSearchLimit()) { sql << wxT(" LIMIT 1 "); } else { sql << wxT(" LIMIT ") << (size_t)GetSingleSearchLimit() - tags.size(); @@ -1165,7 +1180,7 @@ void TagsStorageSQLite::DoAddLimitPartToQuery(wxString& sql, const std::vector tags; @@ -1175,7 +1190,7 @@ TagEntryPtr TagsStorageSQLite::GetTagsByNameLimitOne(const wxString& name) sql << wxT(" LIMIT 1 "); DoFetchTags(sql, tags); - if(tags.size() == 1) + if (tags.size() == 1) return tags.at(0); else return NULL; @@ -1189,7 +1204,7 @@ TagEntryPtr TagsStorageSQLite::GetTagsByNameLimitOne(const wxString& name) void TagsStorageSQLite::GetTagsByPartName(const wxString& partname, std::vector& tags) { try { - if(partname.IsEmpty()) + if (partname.IsEmpty()) return; wxString tmpName(partname); @@ -1215,12 +1230,12 @@ void TagsStorageSQLite::GetTagsByPartName(const wxArrayString& parts, std::vecto { wxString sql; try { - if(parts.IsEmpty()) { + if (parts.IsEmpty()) { return; } wxString filterQuery = "where "; - for(size_t i = 0; i < parts.size(); ++i) { + for (size_t i = 0; i < parts.size(); ++i) { wxString tmpName = parts.Item(i); tmpName.Replace(wxT("_"), wxT("^_")); filterQuery << "path like '%%" << tmpName << "%%' " << ((i == (parts.size() - 1)) ? "" : "AND "); @@ -1238,14 +1253,14 @@ void TagsStorageSQLite::GetTagsByPartName(const wxArrayString& parts, std::vecto void TagsStorageSQLite::ReOpenDatabase() { // Did we get a file name to use? - if(!m_fileName.IsOk()) + if (!m_fileName.IsOk()) return; clDEBUG() << "ReOpenDatabase called for file:" << m_fileName; // Close database first clDEBUG() << "Closing database first"; try { - if(m_db) { + if (m_db) { m_db->Close(); delete m_db; m_db = nullptr; @@ -1265,18 +1280,20 @@ void TagsStorageSQLite::ReOpenDatabase() clDEBUG() << "Database reopened successfully"; } -void TagsStorageSQLite::GetTagsByPathAndKind(const wxString& path, std::vector& tags, - const std::vector& kinds, int limit) +void TagsStorageSQLite::GetTagsByPathAndKind(const wxString& path, + std::vector& tags, + const std::vector& kinds, + int limit) { - if(path.empty()) + if (path.empty()) return; wxString sql; sql << "select * from tags where path='" << path << "'"; - if(!kinds.empty()) { + if (!kinds.empty()) { sql << " and kind in ("; - for(const wxString& kind : kinds) { + for (const wxString& kind : kinds) { sql << "'" << kind << "',"; } sql.RemoveLast(); @@ -1291,7 +1308,7 @@ void TagsStorageSQLite::GetTagsByPathAndKind(const wxString& path, std::vector tags; DoFetchTags(sql, tags); - if(tags.size() == 1) { + if (tags.size() == 1) { return tags[0]; } return nullptr; } -size_t TagsStorageSQLite::GetFileScopedTags(const wxString& filepath, const wxString& name, const wxArrayString& kinds, +size_t TagsStorageSQLite::GetFileScopedTags(const wxString& filepath, + const wxString& name, + const wxArrayString& kinds, std::vector& tags) { - if(filepath.empty()) + if (filepath.empty()) return 0; // get anonymous tags first @@ -1319,7 +1338,7 @@ size_t TagsStorageSQLite::GetFileScopedTags(const wxString& filepath, const wxSt std::vector tags_1; std::vector tags_2; sql << "select * from tags where file='" << filepath << "' and scope like '__anon%'"; - if(!name.empty()) { + if (!name.empty()) { sql << " and name like '" << name << "%'"; } LOG_IF_TRACE { clDEBUG1() << "Running SQL:" << sql << endl; } @@ -1330,7 +1349,7 @@ size_t TagsStorageSQLite::GetFileScopedTags(const wxString& filepath, const wxSt sql.Clear(); sql << "select * from tags where file='" << filepath << "' and kind in ('member','variable','class','struct','enum')"; - if(!name.empty()) { + if (!name.empty()) { sql << " and name like '" << name << "%'"; } LOG_IF_TRACE { clDEBUG1() << "Running SQL:" << sql << endl; } @@ -1340,14 +1359,14 @@ size_t TagsStorageSQLite::GetFileScopedTags(const wxString& filepath, const wxSt // filter duplicate tags.reserve(tags_2.size() + tags_1.size()); std::unordered_set visited; - for(auto tag : tags_1) { - if(!visited.insert(tag->GetId()).second) + for (auto tag : tags_1) { + if (!visited.insert(tag->GetId()).second) continue; tags.emplace_back(tag); } - for(auto tag : tags_2) { - if(!visited.insert(tag->GetId()).second) + for (auto tag : tags_2) { + if (!visited.insert(tag->GetId()).second) continue; tags.emplace_back(tag); } diff --git a/CodeLite/database/tags_storage_sqlite3.h b/CodeLite/database/tags_storage_sqlite3.h index 6165f23eac..a0fb32ac9d 100644 --- a/CodeLite/database/tags_storage_sqlite3.h +++ b/CodeLite/database/tags_storage_sqlite3.h @@ -120,7 +120,7 @@ class WXDLLIMPEXP_CL clSqliteDB : public wxSQLite3Database void Close() { - if(IsOpen()) + if (IsOpen()) wxSQLite3Database::Close(); m_statements.clear(); @@ -213,8 +213,8 @@ class WXDLLIMPEXP_CL TagsStorageSQLite : public ITagsStorage * @param path Database file name * @return result set */ - virtual void SelectTagsByFile(const wxString& file, std::vector& tags, - const wxFileName& path = wxFileName()); + virtual void + SelectTagsByFile(const wxString& file, std::vector& tags, const wxFileName& path = wxFileName()); /** * Delete all entries from database that are related to filename. @@ -342,9 +342,13 @@ class WXDLLIMPEXP_CL TagsStorageSQLite : public ITagsStorage * @param partialNameAllowed * @param tags [output] */ - virtual void GetTagsByScopeAndName(const wxString& scope, const wxString& name, bool partialNameAllowed, + virtual void GetTagsByScopeAndName(const wxString& scope, + const wxString& name, + bool partialNameAllowed, std::vector& tags); - virtual void GetTagsByScopeAndName(const wxArrayString& scope, const wxString& name, bool partialNameAllowed, + virtual void GetTagsByScopeAndName(const wxArrayString& scope, + const wxString& name, + bool partialNameAllowed, std::vector& tags); /** @@ -362,7 +366,9 @@ class WXDLLIMPEXP_CL TagsStorageSQLite : public ITagsStorage * @param order OrderAsc, OrderDesc or use OrderNone for no ordering the results * @param tags [output] */ - virtual void GetTagsByKind(const wxArrayString& kinds, const wxString& orderingColumn, int order, + virtual void GetTagsByKind(const wxArrayString& kinds, + const wxString& orderingColumn, + int order, std::vector& tags); /** @@ -372,8 +378,10 @@ class WXDLLIMPEXP_CL TagsStorageSQLite : public ITagsStorage */ virtual void GetTagsByPath(const wxArrayString& path, std::vector& tags); virtual void GetTagsByPath(const wxString& path, std::vector& tags, int limit = 1); - virtual void GetTagsByPathAndKind(const wxString& path, std::vector& tags, - const std::vector& kinds, int limit = 1); + virtual void GetTagsByPathAndKind(const wxString& path, + std::vector& tags, + const std::vector& kinds, + int limit = 1); /** * @brief return array of items by name and parent * @param path @@ -419,8 +427,8 @@ class WXDLLIMPEXP_CL TagsStorageSQLite : public ITagsStorage * @param kinds array of possible kinds * @param tags [output] */ - virtual void GetTagsByScopesAndKind(const wxArrayString& scopes, const wxArrayString& kinds, - std::vector& tags); + virtual void + GetTagsByScopesAndKind(const wxArrayString& scopes, const wxArrayString& kinds, std::vector& tags); /** * @brief get list of tags by kind and file @@ -429,8 +437,11 @@ class WXDLLIMPEXP_CL TagsStorageSQLite : public ITagsStorage * @param order OrderAsc, OrderDesc or use OrderNone for no ordering the results * @param tags */ - virtual void GetTagsByKindAndFile(const wxArrayString& kind, const wxString& fileName, - const wxString& orderingColumn, int order, std::vector& tags); + virtual void GetTagsByKindAndFile(const wxArrayString& kind, + const wxString& fileName, + const wxString& orderingColumn, + int order, + std::vector& tags); /** * @brief delete an entry by file name @@ -492,7 +503,9 @@ class WXDLLIMPEXP_CL TagsStorageSQLite : public ITagsStorage */ void GetTagsByPartName(const wxArrayString& parts, std::vector& tags); - virtual size_t GetFileScopedTags(const wxString& filepath, const wxString& name, const wxArrayString& kinds, + virtual size_t GetFileScopedTags(const wxString& filepath, + const wxString& name, + const wxArrayString& kinds, std::vector& tags); virtual size_t GetParameters(const wxString& function_path, std::vector& tags); diff --git a/CodeLite/dirtraverser.cpp b/CodeLite/dirtraverser.cpp index 6ba00d08e1..dd19903a3f 100644 --- a/CodeLite/dirtraverser.cpp +++ b/CodeLite/dirtraverser.cpp @@ -29,7 +29,7 @@ #include #include -DirTraverser::DirTraverser(const wxString &filespec) +DirTraverser::DirTraverser(const wxString& filespec) : wxDirTraverser() , m_filespec(filespec) { @@ -47,9 +47,9 @@ wxDirTraverseResult DirTraverser::OnFile(const wxString& filename) return wxDIR_CONTINUE; } -wxDirTraverseResult DirTraverser::OnDir(const wxString &dirname) +wxDirTraverseResult DirTraverser::OnDir(const wxString& dirname) { - for (size_t i=0; im_excludeDirs = excludeDirs; - } - const wxArrayString& GetExcludeDirs() const { - return m_excludeDirs; - } - - /** - * Return list of files found - * \return Return list of files found - */ - wxArrayString& GetFiles() { - return m_files; - } -}; - -#endif //DIRTRAVERSER_H + wxArrayString m_excludeDirs; + +public: + /** + * Construct a DirTraverser with a given file spec + */ + DirTraverser(const wxString& filespec); + virtual ~DirTraverser() = default; + + /** + * This function is called once a file is found. The traverse of the directories + * can be stopped based on the return value from this function: + * - wxDIR_IGNORE = -1, // ignore this directory but continue with others + * - wxDIR_STOP, // stop traversing + * - wxDIR_CONTINUE // continue into this directory + * \param filename name of the file that was found + * \return one of the values wxDIR_STOP, wxDIR_IGNORE or wxDIR_CONTINUE + */ + virtual wxDirTraverseResult OnFile(const wxString& filename); + + /** + * This function is called once a directory is found. The traverse of the directories + * can be stopped based on the return value from this function: + * - wxDIR_IGNORE = -1, // ignore this directory but continue with others + * - wxDIR_STOP, // stop traversing + * - wxDIR_CONTINUE // continue into this directory + * \param dirname name of the directory that was found + * \return one of the values wxDIR_STOP, wxDIR_IGNORE or wxDIR_CONTINUE + */ + virtual wxDirTraverseResult OnDir(const wxString& dirname); + + void SetExcludeDirs(const wxArrayString& excludeDirs) { this->m_excludeDirs = excludeDirs; } + const wxArrayString& GetExcludeDirs() const { return m_excludeDirs; } + + /** + * Return list of files found + * \return Return list of files found + */ + wxArrayString& GetFiles() { return m_files; } +}; + +#endif // DIRTRAVERSER_H diff --git a/CodeLite/fileutils.cpp b/CodeLite/fileutils.cpp index 95ba1f5ff2..2d80d361b4 100644 --- a/CodeLite/fileutils.cpp +++ b/CodeLite/fileutils.cpp @@ -23,13 +23,14 @@ ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// +#include "precompiled_header.h" + #include "fileutils.h" #include "Console/clConsoleBase.h" #include "StringUtils.h" #include "file_logger.h" #include "macros.h" -#include "precompiled_header.h" #include "procutils.h" #include diff --git a/CodeLite/json_utils.h b/CodeLite/json_utils.h index 03922d49cd..7eb940f9cf 100644 --- a/CodeLite/json_utils.h +++ b/CodeLite/json_utils.h @@ -64,10 +64,7 @@ inline wxStringMap_t ToStringMap(const nlohmann::json& json) return res; } -inline std::string ToJsonValue(const wxSize& sz) -{ - return std::to_string(sz.x) + "," + std::to_string(sz.y); -} +inline std::string ToJsonValue(const wxSize& sz) { return std::to_string(sz.x) + "," + std::to_string(sz.y); } inline nlohmann::json ToJson(const wxStringMap_t& map) { diff --git a/CodeLite/language.cpp b/CodeLite/language.cpp index 2f2b75831a..be85efd878 100644 --- a/CodeLite/language.cpp +++ b/CodeLite/language.cpp @@ -22,13 +22,14 @@ // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// +#include "precompiled_header.h" + #include "language.h" #include "Cxx/CxxVariableScanner.h" #include "Cxx/y.tab.h" #include "code_completion_api.h" #include "ctags_manager.h" -#include "precompiled_header.h" Language::Language() : m_expression(wxEmptyString) @@ -44,35 +45,35 @@ void Language::ParseTemplateArgs(const wxString& argListStr, wxArrayString& args wxString word = _U(scanner.YYText()); // Eof? - if(type == 0) { + if (type == 0) { return; } - if(type != (int)'<') { + if (type != (int)'<') { return; } bool nextIsArg(false); bool cont(true); - while(cont) { + while (cont) { type = scanner.yylex(); - if(type == 0) { + if (type == 0) { break; } - switch(type) { + switch (type) { case lexCLASS: case IDENTIFIER: { wxString word = _U(scanner.YYText()); - if(word == wxT("class") || word == wxT("typename")) { + if (word == wxT("class") || word == wxT("typename")) { nextIsArg = true; - } else if(nextIsArg) { + } else if (nextIsArg) { argsList.Add(word); nextIsArg = false; } break; } - case(int)'>': + case (int)'>': cont = false; break; default: @@ -89,48 +90,48 @@ void Language::ParseTemplateInitList(const wxString& argListStr, wxArrayString& wxString word = _U(scanner.YYText()); // Eof? - if(type == 0) { + if (type == 0) { return; } - if(type != (int)'<') { + if (type != (int)'<') { return; } int depth(1); wxString typeName; - while(depth > 0) { + while (depth > 0) { type = scanner.yylex(); - if(type == 0) { + if (type == 0) { break; } - switch(type) { - case(int)',': { - if(depth == 1) { + switch (type) { + case (int)',': { + if (depth == 1) { argsList.Add(typeName.Trim().Trim(false)); typeName.Empty(); } break; } - case(int)'>': + case (int)'>': depth--; break; - case(int)'<': + case (int)'<': depth++; break; - case(int)'*': - case(int)'&': + case (int)'*': + case (int)'&': // ignore pointers & references break; default: - if(depth == 1) { + if (depth == 1) { typeName << _U(scanner.YYText()); } break; } } - if(typeName.Trim().Trim(false).IsEmpty() == false) { + if (typeName.Trim().Trim(false).IsEmpty() == false) { argsList.Add(typeName.Trim().Trim(false)); } typeName.Empty(); @@ -147,7 +148,7 @@ wxString Language::GetScopeName(const wxString& in) std::string scope_name = get_scope_name(buf.data(), moreNS, ignoreTokens); wxString scope = _U(scope_name.c_str()); - if(scope.IsEmpty()) { + if (scope.IsEmpty()) { scope = wxT(""); } return scope; @@ -163,8 +164,8 @@ bool Language::VariableFromPattern(const wxString& in, const wxString& name, Var // remove C++11 angle bracket to use C++98 wxString fixed_pattern; - for(const wxChar& ch : pattern) { - switch(ch) { + for (const wxChar& ch : pattern) { + switch (ch) { case '>': fixed_pattern << " >"; break; @@ -187,7 +188,7 @@ bool Language::VariableFromPattern(const wxString& in, const wxString& name, Var get_variables(patbuf.data(), li, ignoreTokens, false); for (Variable v : li) { - if(name == _U(v.m_name.c_str())) { + if (name == _U(v.m_name.c_str())) { var = v; var.m_pattern = pattern.mb_str(wxConvUTF8).data(); return true; @@ -201,12 +202,12 @@ std::vector Language::GetLocalVariables(const wxString& in) wxString pattern(in); pattern = pattern.Trim().Trim(false); - CxxVariableScanner scanner(pattern, eCxxStandard::kCxx11, GetTagsManager()->GetCtagsOptions().GetTokensWxMap(), - true); + CxxVariableScanner scanner( + pattern, eCxxStandard::kCxx11, GetTagsManager()->GetCtagsOptions().GetTokensWxMap(), true); CxxVariable::Vec_t locals = scanner.GetVariables(false); std::vector tags; - for(CxxVariable::Ptr_t local : locals) { + for (CxxVariable::Ptr_t local : locals) { const wxString& tagName = local->GetName(); TagEntryPtr tag(new TagEntry()); @@ -225,7 +226,7 @@ void Language::SetTagsManager(TagsManager* tm) { m_tm = tm; } TagsManager* Language::GetTagsManager() { - if(!m_tm) { + if (!m_tm) { // for backward compatibility allows access to the tags manager using // the singleton call return TagsManagerST::Get(); @@ -245,31 +246,31 @@ wxArrayString Language::DoExtractTemplateDeclarationArgs(TagEntryPtr tag) declScanner.SetText(_C(pattern)); bool foundTemplate(false); int type(0); - while(true) { + while (true) { type = declScanner.yylex(); - if(type == 0) // eof + if (type == 0) // eof break; wxString word = _U(declScanner.YYText()); - switch(type) { + switch (type) { case IDENTIFIER: - if(word == wxT("template")) { + if (word == wxT("template")) { foundTemplate = true; - } else if(foundTemplate) { + } else if (foundTemplate) { templateString << word; } break; default: - if(foundTemplate) { + if (foundTemplate) { templateString << word; } break; } } - if(foundTemplate) { + if (foundTemplate) { wxArrayString ar; ParseTemplateArgs(templateString, ar); return ar; @@ -295,12 +296,12 @@ wxString TemplateHelper::Substitute(const wxString& name) { // for(size_t i=0; i(templateInstantiationVector.size()); - for(int i = count - 1; i >= 0; i--) { + for (int i = count - 1; i >= 0; i--) { int where = templateDeclaration.Index(name); - if(where != wxNOT_FOUND) { + if (where != wxNOT_FOUND) { // it exists, return the name in the templateInstantiation list - if(templateInstantiationVector.at(i).GetCount() > (size_t)where && - templateInstantiationVector.at(i).Item(where) != name) + if (templateInstantiationVector.at(i).GetCount() > (size_t)where && + templateInstantiationVector.at(i).Item(where) != name) return templateInstantiationVector.at(i).Item(where); } } @@ -318,7 +319,7 @@ void TemplateHelper::Clear() wxString TemplateHelper::GetPath() const { wxString path; - if(typeScope != wxT("")) + if (typeScope != wxT("")) path << typeScope << wxT("::"); path << typeName; @@ -329,7 +330,7 @@ wxString TemplateHelper::GetPath() const static Language* gs_Language = NULL; void LanguageST::Free() { - if(gs_Language) { + if (gs_Language) { delete gs_Language; } gs_Language = NULL; @@ -337,7 +338,7 @@ void LanguageST::Free() Language* LanguageST::Get() { - if(gs_Language == NULL) + if (gs_Language == NULL) gs_Language = new Language(); return gs_Language; } @@ -347,18 +348,18 @@ int Language::DoReadClassName(CppScanner& scanner, wxString& clsname) const clsname.clear(); int type = 0; - while(true) { + while (true) { type = scanner.yylex(); - if(type == 0) + if (type == 0) return 0; - if(type == IDENTIFIER) { + if (type == IDENTIFIER) { clsname = scanner.YYText(); - } else if(type == '{' || type == ':') { + } else if (type == '{' || type == ':') { return type; - } else if(type == ';') { + } else if (type == ';') { // we probably encountered a forward declaration or 'friend' statement clsname.Clear(); return (int)';'; @@ -367,13 +368,15 @@ int Language::DoReadClassName(CppScanner& scanner, wxString& clsname) const return 0; } -bool Language::InsertFunctionDecl(const wxString& clsname, const wxString& functionDecl, wxString& sourceContent, +bool Language::InsertFunctionDecl(const wxString& clsname, + const wxString& functionDecl, + wxString& sourceContent, int visibility) { // determine the visibility requested int typeVisibility = lexPUBLIC; wxString strVisibility = wxT("public:\n"); - switch(visibility) { + switch (visibility) { default: case 0: typeVisibility = lexPUBLIC; @@ -397,20 +400,20 @@ bool Language::InsertFunctionDecl(const wxString& clsname, const wxString& funct bool success = false; int type = 0; - while(true) { + while (true) { type = scanner.yylex(); - if(type == 0) { + if (type == 0) { return false; // EOF } - if(type == lexCLASS) { + if (type == lexCLASS) { wxString name; type = DoReadClassName(scanner, name); - if(type == 0) { + if (type == 0) { return false; } - if(name == clsname) { + if (name == clsname) { // We found the lex success = true; break; @@ -418,31 +421,31 @@ bool Language::InsertFunctionDecl(const wxString& clsname, const wxString& funct } } - if(!success) + if (!success) return false; // scanner is pointing on the class // We now need to find the first opening curly brace success = false; - if(type == '{') { + if (type == '{') { // DoReadClassName already consumed the '{' character // mark this as a success and continue success = true; } else { - while(true) { + while (true) { type = scanner.yylex(); - if(type == 0) + if (type == 0) return false; // EOF - if(type == '{') { + if (type == '{') { success = true; break; } } } - if(!success) + if (!success) return false; // search for requested visibility, if we could not locate it @@ -451,23 +454,23 @@ bool Language::InsertFunctionDecl(const wxString& clsname, const wxString& funct int depth = 1; int visibilityLine = wxNOT_FOUND; int closingCurlyBraceLine = wxNOT_FOUND; - while(true) { + while (true) { type = scanner.yylex(); - if(type == 0) + if (type == 0) break; - if(type == typeVisibility) { + if (type == typeVisibility) { visibilityLine = scanner.LineNo(); break; } - if(type == '{') { + if (type == '{') { depth++; - } else if(type == '}') { + } else if (type == '}') { depth--; - if(depth == 0) { + if (depth == 0) { // reached end of class closingCurlyBraceLine = scanner.LineNo(); break; @@ -477,7 +480,7 @@ bool Language::InsertFunctionDecl(const wxString& clsname, const wxString& funct wxString strToInsert; int insertLine = visibilityLine; - if(visibilityLine == wxNOT_FOUND) { + if (visibilityLine == wxNOT_FOUND) { // could not locate the visibility line insertLine = closingCurlyBraceLine; strToInsert << strVisibility << functionDecl; @@ -487,14 +490,14 @@ bool Language::InsertFunctionDecl(const wxString& clsname, const wxString& funct strToInsert << functionDecl; } - if(insertLine == wxNOT_FOUND) + if (insertLine == wxNOT_FOUND) // could not find any of the two return false; wxString newContent; wxArrayString lines = ::wxStringTokenize(sourceContent, wxT("\n"), wxTOKEN_RET_DELIMS); - for(size_t i = 0; i < lines.GetCount(); i++) { - if(insertLine == (int)i) { + for (size_t i = 0; i < lines.GetCount(); i++) { + if (insertLine == (int)i) { newContent << strToInsert; } newContent << lines.Item(i); @@ -510,9 +513,9 @@ int Language::GetBestLineForForwardDecl(const wxString& fileContent) const // ) CppLexer lexer(fileContent.mb_str(wxConvISO8859_1).data()); - while(true) { + while (true) { int type = lexer.lex(); - if(type == 0) { + if (type == 0) { // EOF return wxNOT_FOUND; } @@ -520,7 +523,7 @@ int Language::GetBestLineForForwardDecl(const wxString& fileContent) const } // stc is 0 based int line = lexer.line_number(); - if(line) + if (line) --line; return line; } diff --git a/CodeLite/language.h b/CodeLite/language.h index 77e90fcc6c..cdfe767446 100644 --- a/CodeLite/language.h +++ b/CodeLite/language.h @@ -87,7 +87,6 @@ class WXDLLIMPEXP_CL Language CxxVariable::Map_t m_locals; public: - /** * @brief given fileContent, locate the best line to place a class forward declaration * statement @@ -132,7 +131,9 @@ class WXDLLIMPEXP_CL Language * to place the function body. set visibility to 0 for 'public' function, 1 for 'protected' and 2 for private * return true if this function succeeded, false otherwise */ - bool InsertFunctionDecl(const wxString& clsname, const wxString& functionDecl, wxString& sourceContent, + bool InsertFunctionDecl(const wxString& clsname, + const wxString& functionDecl, + wxString& sourceContent, int visibility = 0); private: diff --git a/CodeLite/macros.h b/CodeLite/macros.h index ff97b49d35..c84eedb90f 100644 --- a/CodeLite/macros.h +++ b/CodeLite/macros.h @@ -38,38 +38,38 @@ // wxWidgets Connect macros //------------------------------------------------------- -#define ConnectChoice(ctrl, fn) \ +#define ConnectChoice(ctrl, fn) \ ctrl->Connect(ctrl->GetId(), wxEVT_COMMAND_CHOICE_SELECTED, wxCommandEventHandler(fn), NULL, this); -#define ConnectButton(ctrl, fn) \ +#define ConnectButton(ctrl, fn) \ ctrl->Connect(ctrl->GetId(), wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(fn), NULL, this); -#define ConnectListBoxDClick(ctrl, fn) \ +#define ConnectListBoxDClick(ctrl, fn) \ ctrl->Connect(ctrl->GetId(), wxEVT_COMMAND_LISTBOX_DOUBLECLICKED, wxCommandEventHandler(fn), NULL, this); -#define ConnectCheckBox(ctrl, fn) \ +#define ConnectCheckBox(ctrl, fn) \ ctrl->Connect(ctrl->GetId(), wxEVT_COMMAND_CHECKBOX_CLICKED, wxCommandEventHandler(fn), NULL, this); -#define ConnectListCtrlItemSelected(ctrl, fn) \ +#define ConnectListCtrlItemSelected(ctrl, fn) \ ctrl->Connect(ctrl->GetId(), wxEVT_COMMAND_LIST_ITEM_SELECTED, wxListEventHandler(fn), NULL, this); -#define ConnectListCtrlItemActivated(ctrl, fn) \ +#define ConnectListCtrlItemActivated(ctrl, fn) \ ctrl->Connect(ctrl->GetId(), wxEVT_COMMAND_LIST_ITEM_ACTIVATED, wxListEventHandler(fn), NULL, this); #define ConnectKeyDown(ctrl, fn) ctrl->Connect(ctrl->GetId(), wxEVT_KEY_DOWN, wxKeyEventHandler(fn), NULL, this); #define ConnectCharEvent(ctrl, fn) ctrl->Connect(ctrl->GetId(), wxEVT_CHAR, wxKeyEventHandler(fn), NULL, this); -#define ConnectCmdTextEntered(ctrl, fn) \ +#define ConnectCmdTextEntered(ctrl, fn) \ ctrl->Connect(ctrl->GetId(), wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler(fn), NULL, this); -#define ConnectCmdTextUpdated(ctrl, fn) \ +#define ConnectCmdTextUpdated(ctrl, fn) \ ctrl->Connect(ctrl->GetId(), wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler(fn), NULL, this); -#define ConnectCombo(ctrl, fn) \ +#define ConnectCombo(ctrl, fn) \ ctrl->Connect(ctrl->GetId(), wxEVT_COMMAND_COMBOBOX_SELECTED, wxCommandEventHandler(fn), NULL, this); -#define ConnectCheckList(ctrl, fn) \ +#define ConnectCheckList(ctrl, fn) \ ctrl->Connect(ctrl->GetId(), wxEVT_COMMAND_CHECKLISTBOX_TOGGLED, wxCommandEventHandler(fn), NULL, this); #define TrimString(str) \ @@ -104,8 +104,8 @@ // terminal macro #ifdef __WXGTK__ -#define TERMINAL_CMD \ - wxString::Format(wxT("%s/codelite_xterm '$(TITLE)' '$(CMD)'"), \ +#define TERMINAL_CMD \ + wxString::Format(wxT("%s/codelite_xterm '$(TITLE)' '$(CMD)'"), \ wxFileName(clStandardPaths::Get().GetExecutablePath()).GetPath().c_str()) #elif defined(__WXMAC__) #define TERMINAL_CMD wxString::Format(wxT("%s/OpenTerm '$(CMD)'"), clStandardPaths::Get().GetDataDir().c_str()) diff --git a/CodeLite/performance.h b/CodeLite/performance.h index 2d26a8f408..6b41adc514 100644 --- a/CodeLite/performance.h +++ b/CodeLite/performance.h @@ -1,28 +1,28 @@ -////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// -// -// copyright : (C) 2009 by Eran Ifrah -// file name : performance.h -// -// ------------------------------------------------------------------------- -// A -// _____ _ _ _ _ -// / __ \ | | | | (_) | -// | / \/ ___ __| | ___| | _| |_ ___ -// | | / _ \ / _ |/ _ \ | | | __/ _ ) -// | \__/\ (_) | (_| | __/ |___| | || __/ -// \____/\___/ \__,_|\___\_____/_|\__\___| -// -// F i l e -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation; either version 2 of the License, or -// (at your option) any later version. -// -////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// - +////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// +// +// copyright : (C) 2009 by Eran Ifrah +// file name : performance.h +// +// ------------------------------------------------------------------------- +// A +// _____ _ _ _ _ +// / __ \ | | | | (_) | +// | / \/ ___ __| | ___| | _| |_ ___ +// | | / _ \ / _ |/ _ \ | | | __/ _ ) +// | \__/\ (_) | (_| | __/ |___| | || __/ +// \____/\___/ \__,_|\___\_____/_|\__\___| +// +// F i l e +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; either version 2 of the License, or +// (at your option) any later version. +// +////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// + #ifndef __PERFORMANCE_H__ #define __PERFORMANCE_H__ @@ -35,13 +35,12 @@ // // PERF_FUNCTION(); -- put this at the very top of any function to profile the whole function. // -// PERF_BLOCK("Your Comment Here") { -- put this around parts of a function you want to profile +// PERF_BLOCK("Your Comment Here") { -- put this around parts of a function you want to profile // [your code here] // } // -// PERF_START("Your Comment Here"); -- use this instead when the braces of PERF_BLOCK won't work for you because of scoping issues -// [your code here] -// PERF_END(); +// PERF_START("Your Comment Here"); -- use this instead when the braces of PERF_BLOCK won't work for you because of +// scoping issues [your code here] PERF_END(); // // Output is sent to file "codelite.perf" in the startup directory. The file is opened automatically for you. It is // overwritten on each run. @@ -58,45 +57,49 @@ // The element shows the time spent for the entire block it is in, and includes an optional "unaccounted" // attribute for any ticks not counted by inner blocks (so you know how much time you're missing from profiled // subfunctions). - -#include "codelite_exports.h" + +#include "codelite_exports.h" #ifdef __PERFORMANCE - #ifdef __WXMSW__ - //Uncomment this to globally disable all profiling - //#undef __PERFORMANCE - #else - // Don't change this - #undef __PERFORMANCE - #endif +#ifdef __WXMSW__ +// Uncomment this to globally disable all profiling +// #undef __PERFORMANCE +#else +// Don't change this +#undef __PERFORMANCE +#endif #endif #ifdef __PERFORMANCE - extern WXDLLIMPEXP_CL void PERF_START(const char* func_name); - extern WXDLLIMPEXP_CL void PERF_END(); - extern WXDLLIMPEXP_CL void PERF_OUTPUT(const char* path); - - struct WXDLLIMPEXP_CL PERF_CLASS { - PERF_CLASS(const char *name) : count(0) { PERF_START(name); } - ~PERF_CLASS() { PERF_END(); } - - int count; - }; +extern WXDLLIMPEXP_CL void PERF_START(const char* func_name); +extern WXDLLIMPEXP_CL void PERF_END(); +extern WXDLLIMPEXP_CL void PERF_OUTPUT(const char* path); + +struct WXDLLIMPEXP_CL PERF_CLASS { + PERF_CLASS(const char* name) + : count(0) + { + PERF_START(name); + } + ~PERF_CLASS() { PERF_END(); } + + int count; +}; + +#define PERF_FUNCTION() PERF_CLASS PERF_OBJ(__PRETTY_FUNCTION__) +#define PERF_REPEAT(nm, n) for (PERF_CLASS PERF_OBJ(nm); PERF_OBJ.count < (n); PERF_OBJ.count++) +#define PERF_BLOCK(nm) PERF_REPEAT(nm, 1) - #define PERF_FUNCTION() PERF_CLASS PERF_OBJ(__PRETTY_FUNCTION__) - #define PERF_REPEAT(nm,n) for (PERF_CLASS PERF_OBJ(nm); PERF_OBJ.count < (n); PERF_OBJ.count++) - #define PERF_BLOCK(nm) PERF_REPEAT(nm,1) +#else -#else +#define PERF_START(func_name) +#define PERF_END() +#define PERF_OUTPUT(path) +#define PERF_FUNCTION() +#define PERF_REPEAT(nm, n) +#define PERF_BLOCK(nm) - #define PERF_START(func_name) - #define PERF_END() - #define PERF_OUTPUT(path) - #define PERF_FUNCTION() - #define PERF_REPEAT(nm,n) - #define PERF_BLOCK(nm) - #endif #endif // __PERFORMANCE_H__ diff --git a/CodeLite/precompiled_header.h b/CodeLite/precompiled_header.h index 06f9e63131..6b81680b38 100644 --- a/CodeLite/precompiled_header.h +++ b/CodeLite/precompiled_header.h @@ -29,13 +29,12 @@ // A proxy to the right PCH file // we need to so we will get a different flags compiled per file #if !defined(_WIN64) -# include "../PCH/precompiled_header_release_32.h" +#include "../PCH/precompiled_header_release_32.h" #else #ifdef NDEBUG -# include "../PCH/precompiled_header_release.h" +#include "../PCH/precompiled_header_release.h" #else -# include "../PCH/precompiled_header_dbg.h" +#include "../PCH/precompiled_header_dbg.h" #endif #endif #endif - diff --git a/CodeLite/progress_dialog.cpp b/CodeLite/progress_dialog.cpp index a8026439cb..3da8abfe11 100644 --- a/CodeLite/progress_dialog.cpp +++ b/CodeLite/progress_dialog.cpp @@ -34,7 +34,7 @@ clProgressDlg::clProgressDlg(wxWindow* parent, const wxString& title, const wxSt SetTitle(title); m_staticLabel->SetLabel(msg); m_gauge->SetRange(maxValue); - GetSizer()->Fit(this); + GetSizer()->Fit(this); CenterOnParent(); Show(); wxYieldIfNeeded(); @@ -45,7 +45,9 @@ bool clProgressDlg::Update(int value, const wxString& msg) m_staticLabel->SetLabel(msg); m_gauge->SetValue(value); - if(value % 20 == 0) { wxSafeYield(this, true); } + if (value % 20 == 0) { + wxSafeYield(this, true); + } return true; } @@ -53,7 +55,8 @@ bool clProgressDlg::Pulse(const wxString& msg) { int curval = m_gauge->GetValue(); m_gauge->SetValue(curval + 1); - if(!msg.IsEmpty()) m_staticLabel->SetLabel(msg); + if (!msg.IsEmpty()) + m_staticLabel->SetLabel(msg); return true; } diff --git a/CodeLite/search_thread.h b/CodeLite/search_thread.h index 51874c9192..743d01fcbd 100644 --- a/CodeLite/search_thread.h +++ b/CodeLite/search_thread.h @@ -77,7 +77,7 @@ class WXDLLIMPEXP_CL SearchData : public ThreadRequest // An internal helper function that set/remove an option bit void SetOption(int option, bool set) { - if(set) { + if (set) { m_flags |= option; } else { m_flags &= ~(option); @@ -169,7 +169,7 @@ class WXDLLIMPEXP_CL SearchResult : public wxObject SearchResult& operator=(const SearchResult& rhs) { - if(this == &rhs) + if (this == &rhs) return *this; m_position = rhs.m_position; m_column = rhs.m_column; @@ -229,7 +229,7 @@ class WXDLLIMPEXP_CL SearchResult : public wxObject const wxArrayString& GetRegexCaptures() const { return m_regexCaptures; } wxString GetRegexCapture(size_t backref) const { - if(m_regexCaptures.size() > backref) { + if (m_regexCaptures.size() > backref) { return m_regexCaptures[backref]; } else { return wxEmptyString; @@ -283,7 +283,7 @@ class WXDLLIMPEXP_CL SearchSummary : public wxObject wxString GetMessage() const { wxString msg; - if(m_fileScanned) { + if (m_fileScanned) { msg << _("====== Number of files scanned: ") << m_fileScanned << _(", Matches found: "); } else { msg << _("====== Matches found: "); @@ -293,7 +293,7 @@ class WXDLLIMPEXP_CL SearchSummary : public wxObject int msecs = m_elapsed % 1000; msg << _(", elapsed time: ") << secs << wxT(".") << msecs << _(" seconds") << wxT(" ======"); - if(!m_failedFiles.IsEmpty()) { + if (!m_failedFiles.IsEmpty()) { msg << "\n"; msg << "====== " << _("Failed to open the following files for scan:") << "\n"; for (const auto& filename : m_failedFiles) { @@ -370,11 +370,19 @@ class WXDLLIMPEXP_CL SearchThread : public WorkerThread void DoSearchFile(const wxString& fileName, const SearchData* data); // Perform search on a line - void DoSearchLine(const wxString& line, const int lineNum, const int lineOffset, const wxString& fileName, - const SearchData* data, const wxString& findWhat, const wxArrayString& filters); + void DoSearchLine(const wxString& line, + const int lineNum, + const int lineOffset, + const wxString& fileName, + const SearchData* data, + const wxString& findWhat, + const wxArrayString& filters); // Perform search on a line using regular expression - void DoSearchLineRE(const wxString& line, const int lineNum, const int lineOffset, const wxString& fileName, + void DoSearchLineRE(const wxString& line, + const int lineNum, + const int lineOffset, + const wxString& fileName, const SearchData* data); // Send an event to the notified window diff --git a/CodeLite/singleton.h b/CodeLite/singleton.h index 9cb7e8afb0..540cfdcb29 100644 --- a/CodeLite/singleton.h +++ b/CodeLite/singleton.h @@ -1,86 +1,92 @@ ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // -// copyright : (C) 2008 by Eran Ifrah -// file name : singleton.h -// +// copyright : (C) 2008 by Eran Ifrah +// file name : singleton.h +// // ------------------------------------------------------------------------- -// A -// _____ _ _ _ _ -// / __ \ | | | | (_) | -// | / \/ ___ __| | ___| | _| |_ ___ -// | | / _ \ / _ |/ _ \ | | | __/ _ ) -// | \__/\ (_) | (_| | __/ |___| | || __/ -// \____/\___/ \__,_|\___\_____/_|\__\___| -// -// F i l e -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation; either version 2 of the License, or -// (at your option) any later version. -// +// A +// _____ _ _ _ _ +// / __ \ | | | | (_) | +// | / \/ ___ __| | ___| | _| |_ ___ +// | | / _ \ / _ |/ _ \ | | | __/ _ ) +// | \__/\ (_) | (_| | __/ |___| | || __/ +// \____/\___/ \__,_|\___\_____/_|\__\___| +// +// F i l e +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; either version 2 of the License, or +// (at your option) any later version. +// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// - #ifndef SINGLETON_H -#define SINGLETON_H - -/** - * A template class that implements the Singleton pattern. - * - * \date 08-23-2006 - * \author eran - */ -template class Singleton -{ - static T* ms_instance; -public: - /** - * Static method to access the only pointer of this instance. - * \return a pointer to the only instance of this - */ - static T* Get(); - - /** - * Release resources. - */ - static void Free(); - -protected: - /** - * Default constructor. - */ - Singleton(); - - /** - * Destructor. - */ - virtual ~Singleton(); -}; -template T* Singleton::ms_instance = 0; - -template Singleton::Singleton() -{ -} - -template Singleton::~Singleton() -{ -} - -template T* Singleton::Get() -{ - if(!ms_instance) - ms_instance = new T(); - return ms_instance; -} - -template void Singleton::Free() -{ - if( ms_instance ) - { - delete ms_instance; - ms_instance = 0; - } -} - -#endif // SINGLETON_H +#ifndef SINGLETON_H +#define SINGLETON_H + +/** + * A template class that implements the Singleton pattern. + * + * \date 08-23-2006 + * \author eran + */ +template +class Singleton +{ + static T* ms_instance; + +public: + /** + * Static method to access the only pointer of this instance. + * \return a pointer to the only instance of this + */ + static T* Get(); + + /** + * Release resources. + */ + static void Free(); + +protected: + /** + * Default constructor. + */ + Singleton(); + + /** + * Destructor. + */ + virtual ~Singleton(); +}; +template +T* Singleton::ms_instance = 0; + +template +Singleton::Singleton() +{ +} + +template +Singleton::~Singleton() +{ +} + +template +T* Singleton::Get() +{ + if (!ms_instance) + ms_instance = new T(); + return ms_instance; +} + +template +void Singleton::Free() +{ + if (ms_instance) { + delete ms_instance; + ms_instance = 0; + } +} + +#endif // SINGLETON_H diff --git a/CodeLite/ssh/clSFTPEvent.cpp b/CodeLite/ssh/clSFTPEvent.cpp index 88368795b5..09e628ed89 100644 --- a/CodeLite/ssh/clSFTPEvent.cpp +++ b/CodeLite/ssh/clSFTPEvent.cpp @@ -12,4 +12,3 @@ clSFTPEvent::clSFTPEvent(wxEventType commandType, int winid) : clCommandEvent(commandType, winid) { } - diff --git a/CodeLite/ssh/clSSHAgent.cpp b/CodeLite/ssh/clSSHAgent.cpp index 69f22aaddc..5b10b1bf39 100644 --- a/CodeLite/ssh/clSSHAgent.cpp +++ b/CodeLite/ssh/clSSHAgent.cpp @@ -40,8 +40,8 @@ void clSSHAgent::Start() PidVec_t P = ProcUtils::PS("ssh-agent"); if (P.empty()) { clDEBUG() << "Could not find a running instance of ssh-agent, starting one..."; - m_process = ::CreateAsyncProcess(nullptr, sshAgent.GetFullPath(), - IProcessCreateWithHiddenConsole | IProcessCreateDefault); + m_process = ::CreateAsyncProcess( + nullptr, sshAgent.GetFullPath(), IProcessCreateWithHiddenConsole | IProcessCreateDefault); if (m_process) { clDEBUG() << "Started" << sshAgent << "with process ID:" << m_process->GetPid() << clEndl; } else { diff --git a/CodeLite/ssh/clSSHChannel.cpp b/CodeLite/ssh/clSSHChannel.cpp index 2625aad388..0256fbc682 100644 --- a/CodeLite/ssh/clSSHChannel.cpp +++ b/CodeLite/ssh/clSSHChannel.cpp @@ -207,7 +207,7 @@ IProcess::Ptr_t clSSHChannel::Execute( channel->m_thread = new clSSHChannelReader(channel, channel->m_channel, channel->m_wantStderr); channel->m_thread->Start(); - return IProcess::Ptr_t{ channel }; + return IProcess::Ptr_t{channel}; } wxString clSSHChannel::BuildError(const wxString& prefix) diff --git a/CodeLite/ssh/clSSHInteractiveChannel.hpp b/CodeLite/ssh/clSSHInteractiveChannel.hpp index ff8a492a10..4d5fbca4aa 100644 --- a/CodeLite/ssh/clSSHInteractiveChannel.hpp +++ b/CodeLite/ssh/clSSHInteractiveChannel.hpp @@ -36,9 +36,12 @@ class WXDLLIMPEXP_CL clSSHInteractiveChannel : public IProcess public: virtual ~clSSHInteractiveChannel(); - static clSSHInteractiveChannel::Ptr_t Create(wxEvtHandler* parent, clSSH::Ptr_t ssh, - const std::vector& args, size_t flags, - const wxString& workingDir, const clEnvList_t* env); + static clSSHInteractiveChannel::Ptr_t Create(wxEvtHandler* parent, + clSSH::Ptr_t ssh, + const std::vector& args, + size_t flags, + const wxString& workingDir, + const clEnvList_t* env); /// Stop notifying the parent window about input/output from the process /// this is useful when we wish to terminate the process onExit but we don't want diff --git a/CodeLite/ssh/cl_sftp.cpp b/CodeLite/ssh/cl_sftp.cpp index 2a41f8c3eb..ebae523d3c 100644 --- a/CodeLite/ssh/cl_sftp.cpp +++ b/CodeLite/ssh/cl_sftp.cpp @@ -163,9 +163,9 @@ void clSFTP::Write(const wxMemoryBuffer& fileContent, const wxString& remotePath auto cb = tmpRemoteFile.mb_str(wxConvUTF8); file = sftp_open(m_sftp, cb.data(), access_type, 0644); if (file == NULL) { - throw clException(wxString() << _("Can't open file: ") << tmpRemoteFile << ". " - << ssh_get_error(m_ssh->GetSession()), - sftp_get_error(m_sftp)); + throw clException( + wxString() << _("Can't open file: ") << tmpRemoteFile << ". " << ssh_get_error(m_ssh->GetSession()), + sftp_get_error(m_sftp)); } char* p = (char*)fileContent.GetData(); @@ -191,9 +191,9 @@ void clSFTP::Write(const wxMemoryBuffer& fileContent, const wxString& remotePath SFTPAttribute::Ptr_t pattr(new SFTPAttribute(sftp_stat(m_sftp, char_buffer_remote.data()))); if (pattr->IsOk() && sftp_unlink(m_sftp, char_buffer_remote.data()) < 0) { - throw clException(wxString() << _("Failed to unlink file: ") << remotePath << ". " - << ssh_get_error(m_ssh->GetSession()), - sftp_get_error(m_sftp)); + throw clException( + wxString() << _("Failed to unlink file: ") << remotePath << ". " << ssh_get_error(m_ssh->GetSession()), + sftp_get_error(m_sftp)); } // Rename the file @@ -219,9 +219,9 @@ SFTPAttribute::List_t clSFTP::List(const wxString& folder, size_t flags, const w dir = sftp_opendir(m_sftp, folder.mb_str(wxConvUTF8).data()); if (!dir) { - throw clException(wxString() << _("Failed to list directory: ") << folder << ". " - << ssh_get_error(m_ssh->GetSession()), - sftp_get_error(m_sftp)); + throw clException( + wxString() << _("Failed to list directory: ") << folder << ". " << ssh_get_error(m_ssh->GetSession()), + sftp_get_error(m_sftp)); } // Keep the current folder name @@ -277,16 +277,16 @@ SFTPAttribute::Ptr_t clSFTP::Read(const wxString& remotePath, wxMemoryBuffer& bu sftp_file file = sftp_open(m_sftp, remotePath.mb_str(wxConvUTF8).data(), O_RDONLY, 0); if (file == NULL) { - throw clException(wxString() << _("Failed to open remote file: ") << remotePath << ". " - << ssh_get_error(m_ssh->GetSession()), - sftp_get_error(m_sftp)); + throw clException( + wxString() << _("Failed to open remote file: ") << remotePath << ". " << ssh_get_error(m_ssh->GetSession()), + sftp_get_error(m_sftp)); } SFTPAttribute::Ptr_t fileAttr = Stat(remotePath); if (!fileAttr) { - throw clException(wxString() << _("Could not stat file:") << remotePath << ". " - << ssh_get_error(m_ssh->GetSession()), - sftp_get_error(m_sftp)); + throw clException( + wxString() << _("Could not stat file:") << remotePath << ". " << ssh_get_error(m_ssh->GetSession()), + sftp_get_error(m_sftp)); } wxInt64 fileSize = fileAttr->GetSize(); if (fileSize == 0) @@ -311,9 +311,9 @@ SFTPAttribute::Ptr_t clSFTP::Read(const wxString& remotePath, wxMemoryBuffer& bu if (bytesRead != fileSize) { sftp_close(file); buffer.Clear(); - throw clException(wxString() << _("Could not read file:") << remotePath << ". " - << ssh_get_error(m_ssh->GetSession()), - sftp_get_error(m_sftp)); + throw clException( + wxString() << _("Could not read file:") << remotePath << ". " << ssh_get_error(m_ssh->GetSession()), + sftp_get_error(m_sftp)); } sftp_close(file); return fileAttr; @@ -355,8 +355,8 @@ void clSFTP::Rename(const wxString& oldpath, const wxString& newpath) rc = sftp_rename(m_sftp, oldpath.mb_str(wxConvUTF8).data(), newpath.mb_str(wxConvUTF8).data()); if (rc != SSH_OK) { - throw clException(wxString() << _("Failed to rename path. ") << ssh_get_error(m_ssh->GetSession()), - sftp_get_error(m_sftp)); + throw clException( + wxString() << _("Failed to rename path. ") << ssh_get_error(m_ssh->GetSession()), sftp_get_error(m_sftp)); } } @@ -384,9 +384,9 @@ void clSFTP::UnlinkFile(const wxString& path) rc = sftp_unlink(m_sftp, path.mb_str(wxConvUTF8).data()); if (rc != SSH_OK) { - throw clException(wxString() << _("Failed to unlink path: ") << path << ". " - << ssh_get_error(m_ssh->GetSession()), - sftp_get_error(m_sftp)); + throw clException( + wxString() << _("Failed to unlink path: ") << path << ". " << ssh_get_error(m_ssh->GetSession()), + sftp_get_error(m_sftp)); } } @@ -480,9 +480,9 @@ void clSFTP::Chmod(const wxString& remotePath, size_t permissions) int rc = sftp_chmod(m_sftp, remotePath.mb_str(wxConvUTF8).data(), permissions); if (rc != SSH_OK) { - throw clException(wxString() << _("Failed to chmod file: ") << remotePath << ". " - << ssh_get_error(m_ssh->GetSession()), - sftp_get_error(m_sftp)); + throw clException( + wxString() << _("Failed to chmod file: ") << remotePath << ". " << ssh_get_error(m_ssh->GetSession()), + sftp_get_error(m_sftp)); } } diff --git a/CodeLite/ssh/cl_sftp.h b/CodeLite/ssh/cl_sftp.h index fb30510c45..69b6fcd55c 100644 --- a/CodeLite/ssh/cl_sftp.h +++ b/CodeLite/ssh/cl_sftp.h @@ -33,6 +33,7 @@ #include "cl_ssh.h" #include "codelite_exports.h" #include "ssh_account_info.h" + #include #include #include @@ -73,8 +74,8 @@ class WXDLLIMPEXP_CL clSFTP * @brief given a remote file path, return the path to the local * file used by SFTP */ - static wxFileName GetLocalFileName(const SSHAccountInfo& accountInfo, const wxString& remotePath, - bool mkdirRecrusive = false); + static wxFileName + GetLocalFileName(const SSHAccountInfo& accountInfo, const wxString& remotePath, bool mkdirRecrusive = false); /** * @brief return the underlying ssh session diff --git a/CodeLite/ssh/cl_sftp_attribute.cpp b/CodeLite/ssh/cl_sftp_attribute.cpp index 8beb33dc59..5cb76fd179 100644 --- a/CodeLite/ssh/cl_sftp_attribute.cpp +++ b/CodeLite/ssh/cl_sftp_attribute.cpp @@ -26,6 +26,7 @@ #if USE_SFTP #include "cl_sftp_attribute.h" + #include SFTPAttribute::SFTPAttribute(SFTPAttribute_t attr) @@ -46,7 +47,7 @@ void SFTPAttribute::Assign(SFTPAttribute_t attr) void SFTPAttribute::DoClear() { - if(m_attributes) { + if (m_attributes) { sftp_attributes_free(m_attributes); } m_attributes = NULL; @@ -58,7 +59,7 @@ void SFTPAttribute::DoClear() void SFTPAttribute::DoConstruct() { - if(!m_attributes) + if (!m_attributes) return; m_name = m_attributes->name; @@ -66,7 +67,7 @@ void SFTPAttribute::DoConstruct() m_permissions = m_attributes->permissions; m_flags = 0; - switch(m_attributes->type) { + switch (m_attributes->type) { case SSH_FILEXFER_TYPE_DIRECTORY: m_flags |= TYPE_FOLDER; break; @@ -90,20 +91,20 @@ void SFTPAttribute::DoConstruct() wxString SFTPAttribute::GetTypeAsString() const { - if(IsSymlink()) { - if(IsFolder()) { + if (IsSymlink()) { + if (IsFolder()) { return " -> " + GetSymlinkPath(); - } else if(IsFile()) { + } else if (IsFile()) { return " -> " + GetSymlinkPath(); } else { return "Symlink"; } } else { - if(IsSpecial()) { + if (IsSpecial()) { return "Special"; - } else if(IsFolder()) { + } else if (IsFolder()) { return "Folder"; - } else if(IsFile()) { + } else if (IsFile()) { return "File"; } else { return "Unknown"; @@ -113,10 +114,10 @@ wxString SFTPAttribute::GetTypeAsString() const bool SFTPAttribute::Compare(SFTPAttribute::Ptr_t one, SFTPAttribute::Ptr_t two) { - if(one->IsFolder() && !two->IsFolder()) { + if (one->IsFolder() && !two->IsFolder()) { return true; - } else if(!one->IsFolder() && two->IsFolder()) { + } else if (!one->IsFolder() && two->IsFolder()) { return false; } else { diff --git a/CodeLite/stringaccessor.cpp b/CodeLite/stringaccessor.cpp index 4746c3dc22..ad3bb000b1 100644 --- a/CodeLite/stringaccessor.cpp +++ b/CodeLite/stringaccessor.cpp @@ -24,14 +24,14 @@ ////////////////////////////////////////////////////////////////////////////// #include "stringaccessor.h" -StringAccessor::StringAccessor(const wxString &str) +StringAccessor::StringAccessor(const wxString& str) : m_str(str.c_str()) { } char StringAccessor::safeAt(size_t pos) { - if( pos >= m_str.size() ) { + if (pos >= m_str.size()) { return 0; } @@ -41,8 +41,8 @@ char StringAccessor::safeAt(size_t pos) bool StringAccessor::isWordChar(char ch) { int ascii_value = (int)ch; - if( (ascii_value >= 48 && ascii_value <= 57) || // 0-9 - (ascii_value >= 65 && ascii_value <= 90) || // A-Z + if ((ascii_value >= 48 && ascii_value <= 57) || // 0-9 + (ascii_value >= 65 && ascii_value <= 90) || // A-Z (ascii_value >= 97 && ascii_value <= 122) || // a-z (ascii_value == 95)) { // _ return true; @@ -53,8 +53,8 @@ bool StringAccessor::isWordChar(char ch) bool StringAccessor::match(const char* str, size_t from) { size_t size = strlen(str); - for(size_t i=0; i #include "codelite_exports.h" + #include +#include class WXDLLIMPEXP_CL StringAccessor { std::wstring m_str; public: - StringAccessor(const wxString &str); + StringAccessor(const wxString& str); virtual ~StringAccessor() = default; - size_t length() { - return m_str.size(); - } + size_t length() { return m_str.size(); } char safeAt(size_t pos); bool isWordChar(char ch); - void setStr(const wxString& str) { - this->m_str = str.c_str(); - } - wxChar* getStr() const { - return (wchar_t*)m_str.c_str(); - } - bool match(const char *str, size_t from); + void setStr(const wxString& str) { this->m_str = str.c_str(); } + wxChar* getStr() const { return (wchar_t*)m_str.c_str(); } + bool match(const char* str, size_t from); }; #endif // __stringaccessor__ diff --git a/CodeLite/tag_tree.cpp b/CodeLite/tag_tree.cpp index 23eb935d02..24367480be 100644 --- a/CodeLite/tag_tree.cpp +++ b/CodeLite/tag_tree.cpp @@ -1,82 +1,78 @@ ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // -// copyright : (C) 2008 by Eran Ifrah -// file name : tag_tree.cpp -// +// copyright : (C) 2008 by Eran Ifrah +// file name : tag_tree.cpp +// // ------------------------------------------------------------------------- -// A -// _____ _ _ _ _ -// / __ \ | | | | (_) | -// | / \/ ___ __| | ___| | _| |_ ___ -// | | / _ \ / _ |/ _ \ | | | __/ _ ) -// | \__/\ (_) | (_| | __/ |___| | || __/ -// \____/\___/ \__,_|\___\_____/_|\__\___| -// -// F i l e -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation; either version 2 of the License, or -// (at your option) any later version. -// +// A +// _____ _ _ _ _ +// / __ \ | | | | (_) | +// | / \/ ___ __| | ___| | _| |_ ___ +// | | / _ \ / _ |/ _ \ | | | __/ _ ) +// | \__/\ (_) | (_| | __/ |___| | || __/ +// \____/\___/ \__,_|\___\_____/_|\__\___| +// +// F i l e +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; either version 2 of the License, or +// (at your option) any later version. +// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// - #include "precompiled_header.h" - -#include "tag_tree.h" -#include "tokenizer.h" - -TagTree::TagTree(const wxString& key, const TagEntry& data) -: Tree(key, data) -{ -} - -/// Util function to help us to build a tree from tags -TagNode* TagTree::AddEntry(TagEntry& tag) -{ - // If a node with thig tag already exist, we simply updating the - // data - wxString key(tag.Key()); - - TagNode* newNode = Find(key); - if( newNode ) - { - if( tag.IsOk() ) - newNode->SetData(tag); - return newNode; - - } - - // To add an entry to the tree, we first must make sure - // that all path to it exist - wxString name = tag.GetPath(); - StringTokenizer tok(name, wxT("::")); - - wxString parentPath; - TagNode* node = GetRoot(); - TagNode* lastFoundNode = GetRoot(); - for(int i=0; i(key, data) +{ +} + +/// Util function to help us to build a tree from tags +TagNode* TagTree::AddEntry(TagEntry& tag) +{ + // If a node with thig tag already exist, we simply updating the + // data + wxString key(tag.Key()); + + TagNode* newNode = Find(key); + if (newNode) { + if (tag.IsOk()) + newNode->SetData(tag); + return newNode; + } + + // To add an entry to the tree, we first must make sure + // that all path to it exist + wxString name = tag.GetPath(); + StringTokenizer tok(name, wxT("::")); + + wxString parentPath; + TagNode* node = GetRoot(); + TagNode* lastFoundNode = GetRoot(); + for (int i = 0; i < tok.Count() - 1; i++) { + parentPath += tok[i]; + + // Try to find this node in the tree + node = Find(parentPath); + if (!node) { + // Node does not exist add it, we copy key values + // from 'tag' + TagEntry ee; + ee.SetPath(parentPath); + ee.SetName(tok[i]); + node = AddChild(parentPath, ee, lastFoundNode); + } + + lastFoundNode = node; + if (i < tok.Count() - 2) + parentPath += _T("::"); + } + + return AddChild(key, tag, node); +} diff --git a/CodeLite/tag_tree.h b/CodeLite/tag_tree.h index 2def8e3fce..50bd31ac26 100644 --- a/CodeLite/tag_tree.h +++ b/CodeLite/tag_tree.h @@ -22,54 +22,52 @@ // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// -#ifndef CODELITE_TAG_TREE_H -#define CODELITE_TAG_TREE_H +#ifndef CODELITE_TAG_TREE_H +#define CODELITE_TAG_TREE_H #include "codelite_exports.h" -#include "database/entry.h" -#include "tree.h" - -#include -#include - -using TagNode = TreeNode; - -/** - * Tree representation of tags. - * This is basically a data structure representing the GUI symbol tree. - * - * \date 08-23-2006 - * \author eran - * - */ -class WXDLLIMPEXP_CL TagTree : public Tree -{ -public: - /** - * Construct a tree with roots' values key & data. - * \param key Root's key - * \param data Root's data - */ - TagTree(const wxString& key, const TagEntry& data); - - - /** - * Destructor - */ - virtual ~TagTree() = default; - - /** - * Add an entry to the tree. - * This functions will add all parents of the tag to the tree if non exist (or some of some exist). - * For example: if TagName is box::m_string, this functions will make sure that a node 'box' exists. - * If not, it will add it and then will add m_string to it as its child. - * \param tag Tag to add - * \return new node that was added to the tree. - */ - TagNode* AddEntry(TagEntry& tag); - -}; - -using TagTreePtr = std::shared_ptr; - -#endif // CODELITE_TAG_TREE_H +#include "database/entry.h" +#include "tree.h" + +#include +#include + +using TagNode = TreeNode; + +/** + * Tree representation of tags. + * This is basically a data structure representing the GUI symbol tree. + * + * \date 08-23-2006 + * \author eran + * + */ +class WXDLLIMPEXP_CL TagTree : public Tree +{ +public: + /** + * Construct a tree with roots' values key & data. + * \param key Root's key + * \param data Root's data + */ + TagTree(const wxString& key, const TagEntry& data); + + /** + * Destructor + */ + virtual ~TagTree() = default; + + /** + * Add an entry to the tree. + * This functions will add all parents of the tag to the tree if non exist (or some of some exist). + * For example: if TagName is box::m_string, this functions will make sure that a node 'box' exists. + * If not, it will add it and then will add m_string to it as its child. + * \param tag Tag to add + * \return new node that was added to the tree. + */ + TagNode* AddEntry(TagEntry& tag); +}; + +using TagTreePtr = std::shared_ptr; + +#endif // CODELITE_TAG_TREE_H diff --git a/CodeLite/tags_options_data.cpp b/CodeLite/tags_options_data.cpp index 3ee143d7a1..faa34c339e 100644 --- a/CodeLite/tags_options_data.cpp +++ b/CodeLite/tags_options_data.cpp @@ -22,11 +22,12 @@ // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// +#include "precompiled_header.h" + #include "tags_options_data.h" #include "cl_config.h" #include "ctags_manager.h" -#include "precompiled_header.h" #include #include @@ -37,16 +38,16 @@ size_t TagsOptionsData::CURRENT_VERSION = 7100; static bool _IsValidCppIdentifier(const wxString& id) { - if(id.IsEmpty()) { + if (id.IsEmpty()) { return false; } // first char can be only _A-Za-z wxString first(id.Mid(0, 1)); - if(first.find_first_not_of("_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") != wxString::npos) { + if (first.find_first_not_of("_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") != wxString::npos) { return false; } // make sure that rest of the id contains only a-zA-Z0-9_ - if(id.find_first_not_of("_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") != wxString::npos) { + if (id.find_first_not_of("_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") != wxString::npos) { return false; } return true; @@ -55,7 +56,7 @@ static bool _IsValidCppIdentifier(const wxString& id) static bool _IsCppKeyword(const wxString& word) { static wxStringSet_t words; - if(words.empty()) { + if (words.empty()) { TagsManager::GetCXXKeywords(words); } return words.count(word); @@ -447,7 +448,7 @@ TagsOptionsData::TagsOptionsData() void TagsOptionsData::AddDefaultTokens() { m_tokens.reserve(m_tokens.size() + DEFAULT_TOKENS.size()); - for(const auto& token : DEFAULT_TOKENS) { + for (const auto& token : DEFAULT_TOKENS) { m_tokens.Add(token); } } @@ -459,9 +460,9 @@ wxString TagsOptionsData::ToString() const static wxString file_name; wxString file_content; - if(file_name.IsEmpty()) { + if (file_name.IsEmpty()) { char* ctagsReplacement = getenv("CTAGS_REPLACEMENTS"); - if(ctagsReplacement) { + if (ctagsReplacement) { file_name = wxString(ctagsReplacement, wxConvUTF8).c_str(); } } @@ -474,7 +475,7 @@ wxString TagsOptionsData::ToString() const file_content << p.first << "=" << p.second << "\n"; } else { - if(options.IsEmpty()) { + if (options.IsEmpty()) { options = " -I"; } @@ -483,7 +484,7 @@ wxString TagsOptionsData::ToString() const } } - if(options.IsEmpty() == false) { + if (options.IsEmpty() == false) { options.RemoveLast(); } @@ -491,9 +492,9 @@ wxString TagsOptionsData::ToString() const } // write the file content - if(file_name.IsEmpty() == false) { + if (file_name.IsEmpty() == false) { wxFFile fp(file_name, "w+b"); - if(fp.IsOpened()) { + if (fp.IsOpened()) { fp.Write(file_content); fp.Close(); } @@ -510,7 +511,7 @@ wxString TagsOptionsData::ToString() const std::map TagsOptionsData::GetTokensMap() const { std::map tokens; - for(size_t i = 0; i < m_tokens.GetCount(); i++) { + for (size_t i = 0; i < m_tokens.GetCount(); i++) { // const wxCharBuffer bufKey = _C( wxString item = m_tokens.Item(i); item.Trim().Trim(false); @@ -520,7 +521,7 @@ std::map TagsOptionsData::GetTokensMap() const const wxCharBuffer bufKey = _C(k); std::string key = bufKey.data(); std::string value; - if(!v.empty()) { + if (!v.empty()) { const wxCharBuffer bufValue = _C(v); value = bufValue.data(); } @@ -541,7 +542,7 @@ void TagsOptionsData::SetTokens(const wxString& tokens) void TagsOptionsData::DoUpdateTokensWxMap() { m_tokensWxMap.clear(); - for(size_t i = 0; i < m_tokens.GetCount(); i++) { + for (size_t i = 0; i < m_tokens.GetCount(); i++) { wxString item = m_tokens.Item(i).Trim().Trim(false); wxString k = item.BeforeFirst('='); wxString v = item.AfterFirst('='); @@ -552,11 +553,11 @@ void TagsOptionsData::DoUpdateTokensWxMap() void TagsOptionsData::DoUpdateTokensWxMapReversed() { m_tokensWxMapReversed.clear(); - for(size_t i = 0; i < m_tokens.GetCount(); i++) { + for (size_t i = 0; i < m_tokens.GetCount(); i++) { wxString item = m_tokens.Item(i).Trim().Trim(false); wxString k = item.AfterFirst('='); wxString v = item.BeforeFirst('='); - if(_IsValidCppIdentifier(k) && !_IsCppKeyword(k)) { + if (_IsValidCppIdentifier(k) && !_IsCppKeyword(k)) { m_tokensWxMapReversed[k] = v; } } @@ -585,7 +586,7 @@ void TagsOptionsData::FromJSON(const JSONItem& json) m_clangCachePolicy = json.namedObject("m_clangCachePolicy").toString(); m_ccNumberOfDisplayItems = json.namedObject("m_ccNumberOfDisplayItems").toSize_t(m_ccNumberOfDisplayItems); - if(!m_fileSpec.Contains("*.hxx")) { + if (!m_fileSpec.Contains("*.hxx")) { m_fileSpec = "*.cpp;*.cc;*.cxx;*.h;*.hpp;*.c;*.c++;*.tcc;*.hxx;*.h++"; } @@ -623,11 +624,11 @@ JSONItem TagsOptionsData::ToJSON() const wxString TagsOptionsData::DoJoinArray(const wxArrayString& arr) const { wxString s; - for(size_t i = 0; i < arr.GetCount(); ++i) { + for (size_t i = 0; i < arr.GetCount(); ++i) { s << arr.Item(i) << "\n"; } - if(s.IsEmpty() == false) { + if (s.IsEmpty() == false) { s.RemoveLast(); } @@ -641,7 +642,7 @@ void TagsOptionsData::Merge(const TagsOptionsData& tod) m_types = conf.MergeArrays(m_types, tod.m_types); DoUpdateTokensWxMapReversed(); DoUpdateTokensWxMap(); - if(m_version != TagsOptionsData::CURRENT_VERSION) { + if (m_version != TagsOptionsData::CURRENT_VERSION) { m_ccNumberOfDisplayItems = tod.m_ccNumberOfDisplayItems; } m_version = TagsOptionsData::CURRENT_VERSION; diff --git a/CodeLite/tokenizer.cpp b/CodeLite/tokenizer.cpp index 038c9c5094..811bf1ce2e 100644 --- a/CodeLite/tokenizer.cpp +++ b/CodeLite/tokenizer.cpp @@ -1,94 +1,85 @@ ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // -// copyright : (C) 2008 by Eran Ifrah -// file name : tokenizer.cpp -// +// copyright : (C) 2008 by Eran Ifrah +// file name : tokenizer.cpp +// // ------------------------------------------------------------------------- -// A -// _____ _ _ _ _ -// / __ \ | | | | (_) | -// | / \/ ___ __| | ___| | _| |_ ___ -// | | / _ \ / _ |/ _ \ | | | __/ _ ) -// | \__/\ (_) | (_| | __/ |___| | || __/ -// \____/\___/ \__,_|\___\_____/_|\__\___| -// -// F i l e -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation; either version 2 of the License, or -// (at your option) any later version. -// +// A +// _____ _ _ _ _ +// / __ \ | | | | (_) | +// | / \/ ___ __| | ___| | _| |_ ___ +// | | / _ \ / _ |/ _ \ | | | __/ _ ) +// | \__/\ (_) | (_| | __/ |___| | || __/ +// \____/\___/ \__,_|\___\_____/_|\__\___| +// +// F i l e +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; either version 2 of the License, or +// (at your option) any later version. +// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// -// StringTokenizer.cpp: implementation of the StringTokenizer class. -// -////////////////////////////////////////////////////////////////////// -#include "precompiled_header.h" -#include "tokenizer.h" - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// - -StringTokenizer::StringTokenizer(const wxString& str, - const wxString& strDelimiter, - bool bAllowEmptyTokens /* false */) -{ - int nEnd = (int)str.find(strDelimiter, 0); - int nStart = 0; - wxString token; - while( nEnd != -1 ) - { - if( nEnd != nStart) - token = str.substr(nStart, nEnd-nStart); - else - token.Empty(); - - if(!token.empty()) - m_tokensArr.push_back(token); - else if( bAllowEmptyTokens ) - m_tokensArr.push_back(token); - - // next token - nStart = nEnd + (int)strDelimiter.length(); - nEnd = (int)str.find(strDelimiter, nStart ); - } - if( nStart != (int)str.length() ) - { - //We have another token which is not delimited - wxString token = str.substr(nStart); - m_tokensArr.push_back(token); - } -} - -StringTokenizer::StringTokenizer(const wxString& str, const wxArrayString& delimiterArr, bool allowEmptyTokens) -{ - wxString tmpStr( str ); - - // Replace all delimiters to the first one - if(delimiterArr.GetCount() >= 2) - { - size_t i=1; - for(; i=(int)m_tokensArr.size() || nIndex<0) - return wxEmptyString; - return m_tokensArr[nIndex]; -} - - +// StringTokenizer.cpp: implementation of the StringTokenizer class. +// +////////////////////////////////////////////////////////////////////// +#include "precompiled_header.h" + +#include "tokenizer.h" + +////////////////////////////////////////////////////////////////////// +// Construction/Destruction +////////////////////////////////////////////////////////////////////// + +StringTokenizer::StringTokenizer(const wxString& str, const wxString& strDelimiter, bool bAllowEmptyTokens /* false */) +{ + int nEnd = (int)str.find(strDelimiter, 0); + int nStart = 0; + wxString token; + while (nEnd != -1) { + if (nEnd != nStart) + token = str.substr(nStart, nEnd - nStart); + else + token.Empty(); + + if (!token.empty()) + m_tokensArr.push_back(token); + else if (bAllowEmptyTokens) + m_tokensArr.push_back(token); + + // next token + nStart = nEnd + (int)strDelimiter.length(); + nEnd = (int)str.find(strDelimiter, nStart); + } + if (nStart != (int)str.length()) { + // We have another token which is not delimited + wxString token = str.substr(nStart); + m_tokensArr.push_back(token); + } +} + +StringTokenizer::StringTokenizer(const wxString& str, const wxArrayString& delimiterArr, bool allowEmptyTokens) +{ + wxString tmpStr(str); + + // Replace all delimiters to the first one + if (delimiterArr.GetCount() >= 2) { + size_t i = 1; + for (; i < delimiterArr.GetCount(); i++) + tmpStr.Replace(delimiterArr[i], delimiterArr[0]); + } + *this = StringTokenizer(tmpStr, delimiterArr[0], allowEmptyTokens); +} + +int StringTokenizer::Count() const { return (int)m_tokensArr.size(); } + +wxString StringTokenizer::operator[](const int nIndex) +{ + if (m_tokensArr.size() == 0) + return wxEmptyString; + if (nIndex >= (int)m_tokensArr.size() || nIndex < 0) + return wxEmptyString; + return m_tokensArr[nIndex]; +} diff --git a/CodeLite/tokenizer.h b/CodeLite/tokenizer.h index 8991645911..fbe41b95cf 100644 --- a/CodeLite/tokenizer.h +++ b/CodeLite/tokenizer.h @@ -1,28 +1,28 @@ -////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// -// -// copyright : (C) 2008 by Eran Ifrah -// file name : tokenizer.h -// -// ------------------------------------------------------------------------- -// A -// _____ _ _ _ _ -// / __ \ | | | | (_) | -// | / \/ ___ __| | ___| | _| |_ ___ -// | | / _ \ / _ |/ _ \ | | | __/ _ ) -// | \__/\ (_) | (_| | __/ |___| | || __/ -// \____/\___/ \__,_|\___\_____/_|\__\___| -// -// F i l e -// -// This program is free software; you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation; either version 2 of the License, or -// (at your option) any later version. -// -////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// - // StringTokenizer.h: interface for the StringTokenizer class. +////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// +// +// copyright : (C) 2008 by Eran Ifrah +// file name : tokenizer.h +// +// ------------------------------------------------------------------------- +// A +// _____ _ _ _ _ +// / __ \ | | | | (_) | +// | / \/ ___ __| | ___| | _| |_ ___ +// | | / _ \ / _ |/ _ \ | | | __/ _ ) +// | \__/\ (_) | (_| | __/ |___| | || __/ +// \____/\___/ \__,_|\___\_____/_|\__\___| +// +// F i l e +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; either version 2 of the License, or +// (at your option) any later version. +// +////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// +// StringTokenizer.h: interface for the StringTokenizer class. // ////////////////////////////////////////////////////////////////////// @@ -56,8 +56,8 @@ * delimArr.Add("_T("-")); * delimArr.Add("_T(":")); * StringTokenizer tok(_T("first-second:third"), delimArr); - * \endcode - * + * \endcode + * * The above example will result with: first, second and third. * * \ingroup CodeLite @@ -69,62 +69,62 @@ */ class WXDLLIMPEXP_CL StringTokenizer { - std::vector m_tokensArr; + std::vector m_tokensArr; public: - /** - * Construct a tokenizer with given input string and delimiter - * \param str source string - * \param delimiter delimiter to use - * \param bAllowEmptyTokens if set to true, empty tokens will be returned as well. Default is no empty tokens - */ - StringTokenizer(const wxString& str, const wxString& delimiter = _T(" "), bool bAllowEmptyTokens = false); + /** + * Construct a tokenizer with given input string and delimiter + * \param str source string + * \param delimiter delimiter to use + * \param bAllowEmptyTokens if set to true, empty tokens will be returned as well. Default is no empty tokens + */ + StringTokenizer(const wxString& str, const wxString& delimiter = _T(" "), bool bAllowEmptyTokens = false); - /** - * Construct a tokenizer with given input string and array of delimiters - * \param str source string - * \param delimiterArr array of delimiters - * \param bAllowEmptyTokens if set to true, empty tokens will be returned as well. Default is no empty tokens - */ - StringTokenizer(const wxString& str,const wxArrayString& delimiterArr, bool bAllowEmptyTokens = false); - /** - * Copy constructor - * \param src source tokenizer - */ - StringTokenizer(const StringTokenizer&) = default; + /** + * Construct a tokenizer with given input string and array of delimiters + * \param str source string + * \param delimiterArr array of delimiters + * \param bAllowEmptyTokens if set to true, empty tokens will be returned as well. Default is no empty tokens + */ + StringTokenizer(const wxString& str, const wxArrayString& delimiterArr, bool bAllowEmptyTokens = false); + /** + * Copy constructor + * \param src source tokenizer + */ + StringTokenizer(const StringTokenizer&) = default; - /** - * Default constructor - */ - StringTokenizer() = default; + /** + * Default constructor + */ + StringTokenizer() = default; - /** - * Destructor - */ - virtual ~StringTokenizer() = default; + /** + * Destructor + */ + virtual ~StringTokenizer() = default; - //----------------------------------------------------- - // Operations - //----------------------------------------------------- + //----------------------------------------------------- + // Operations + //----------------------------------------------------- - /** - * Get the number of tokens - * \return number of tokens - */ - int Count() const; - /** - * Random access operator, starting from zero - * \param nIndex token index - * \return token at nIndex (copy of it) - */ - wxString operator[](int nIndex); + /** + * Get the number of tokens + * \return number of tokens + */ + int Count() const; + /** + * Random access operator, starting from zero + * \param nIndex token index + * \return token at nIndex (copy of it) + */ + wxString operator[](int nIndex); - /** - * Copy one tokenizer to another - * \param src source tokenizer to copy from - * \return this - */ - StringTokenizer& operator=(const StringTokenizer&) = default; + /** + * Copy one tokenizer to another + * \param src source tokenizer to copy from + * \return this + */ + StringTokenizer& operator=(const StringTokenizer&) = default; }; #endif // CODELITE_TOKENIZER_H diff --git a/CodeLite/tree.h b/CodeLite/tree.h index faf6eecfe5..15e57254d2 100644 --- a/CodeLite/tree.h +++ b/CodeLite/tree.h @@ -23,196 +23,200 @@ ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// -#ifndef CODELITE_TREE_H -#define CODELITE_TREE_H - +#ifndef CODELITE_TREE_H +#define CODELITE_TREE_H + #include "tree_node.h" - -template -class Tree -{ - std::map*> m_nodes; - TreeNode* m_root; -public: - /** - * Construct a tree with root node with Key and data. - * \param key Root node key - * \param data Root node data - */ - Tree(const TKey& key, const TData& data); - - /** - * Destructor, deletes all tree and its sub nodes. - */ - virtual ~Tree(); - - /** - * Find node in the tree with Key. - * \param key Search key - * \return node - */ - TreeNode* Find(const TKey& key) ; - - /** - * Remove node (and all its sub nodes) from the tree using key as the criteria. - * This function does not delete the removed node. - * \param key search key - * \return remove node - */ - TreeNode* Remove(const TKey& key); - - /** - * Add child node to the tree. - * \param key New node key - * \param data New node data - * \param parent New node parent, if left NULL parent is set to root - * \return newly added node - */ - TreeNode* AddChild(const TKey& key, const TData& data, TreeNode* parent = NULL) ; - - /** - * Returns tree root. - * \return root node - */ - TreeNode* GetRoot() { return m_root;} - - /** - * Prints the tree in tabulated format to stream. - * \param stream Output stream (default is set to stdout) - * \param depth Tab depth (for internal use) - */ - void Print(std::ostream& stream = std::cout , int depth = 0); - - /** - * Compare this tree against another tree. - * \param targetTree Target tree to compare with - * \param deletedItems Array of pairs of items which exist in this tree and not in target tree - * \param modifiedItems Array of pairs of items which have the same key but different data - * \param newItems Array of pairs of items which exist in the target tree but not in this tree - * \param fromNode If its set to null, comparison will start from this tree root node, if not null, - * comparison will compare sub-tree which root of its fromNode - */ - void Compare(Tree* targetTree, std::vector >& deletedItems, std::vector >& modifiedItems, std::vector >& newItems, TreeNode* fromNode = NULL); - -}; - -template -Tree::Tree(const TKey& key, const TData& data) -{ - m_root = new TreeNode(key, data); -} - -template -Tree::~Tree() -{ - delete m_root; -} - -template -TreeNode* Tree::Find(const TKey& key) -{ - typename std::map*>::const_iterator iter = m_nodes.find(key); - if(iter == m_nodes.end()) - return NULL; - return iter->second; -} - -template -TreeNode* Tree::AddChild(const TKey& key, const TData& data, TreeNode* parent /*NULL*/) -{ - TreeNode* parentNode; - (parent == NULL) ? parentNode = m_root : parentNode = parent; - TreeNode* node = parentNode->AddChild(key, data); - m_nodes[key] = node; - return node; -} - -template -TreeNode* Tree::Remove(const TKey& key) -{ - typename std::map*>::const_iterator iter = m_nodes.find(key); - if(iter == m_nodes.end()) - return NULL; - - // Remove from the map all sub-nodes of the tree - TreeWalker walker(iter->second); - - for(; !walker.End(); walker++) - { - typename std::map*>::iterator it = m_nodes.find(walker.GetNode()->GetKey()); - if(it != m_nodes.end()) - m_nodes.erase(it); - } - return m_root->Remove(key); -} -template -void Tree::Print(std::ostream& stream , int depth) -{ - m_root->Print(stream, depth); -} - -template -void Tree::Compare(Tree* targetTree, std::vector >& deletedItems, std::vector >& modifiedItems, std::vector >& newItems, TreeNode* fromNode) + +template +class Tree +{ + std::map*> m_nodes; + TreeNode* m_root; + +public: + /** + * Construct a tree with root node with Key and data. + * \param key Root node key + * \param data Root node data + */ + Tree(const TKey& key, const TData& data); + + /** + * Destructor, deletes all tree and its sub nodes. + */ + virtual ~Tree(); + + /** + * Find node in the tree with Key. + * \param key Search key + * \return node + */ + TreeNode* Find(const TKey& key); + + /** + * Remove node (and all its sub nodes) from the tree using key as the criteria. + * This function does not delete the removed node. + * \param key search key + * \return remove node + */ + TreeNode* Remove(const TKey& key); + + /** + * Add child node to the tree. + * \param key New node key + * \param data New node data + * \param parent New node parent, if left NULL parent is set to root + * \return newly added node + */ + TreeNode* AddChild(const TKey& key, const TData& data, TreeNode* parent = NULL); + + /** + * Returns tree root. + * \return root node + */ + TreeNode* GetRoot() { return m_root; } + + /** + * Prints the tree in tabulated format to stream. + * \param stream Output stream (default is set to stdout) + * \param depth Tab depth (for internal use) + */ + void Print(std::ostream& stream = std::cout, int depth = 0); + + /** + * Compare this tree against another tree. + * \param targetTree Target tree to compare with + * \param deletedItems Array of pairs of items which exist in this tree and not in target tree + * \param modifiedItems Array of pairs of items which have the same key but different data + * \param newItems Array of pairs of items which exist in the target tree but not in this tree + * \param fromNode If its set to null, comparison will start from this tree root node, if not null, + * comparison will compare sub-tree which root of its fromNode + */ + void Compare(Tree* targetTree, + std::vector>& deletedItems, + std::vector>& modifiedItems, + std::vector>& newItems, + TreeNode* fromNode = NULL); +}; + +template +Tree::Tree(const TKey& key, const TData& data) +{ + m_root = new TreeNode(key, data); +} + +template +Tree::~Tree() +{ + delete m_root; +} + +template +TreeNode* Tree::Find(const TKey& key) +{ + typename std::map*>::const_iterator iter = m_nodes.find(key); + if (iter == m_nodes.end()) + return NULL; + return iter->second; +} + +template +TreeNode* +Tree::AddChild(const TKey& key, const TData& data, TreeNode* parent /*NULL*/) { - // we break generic for the sake of thread safety: - // we explicitly calling TKey.c_str(), which means that we assume that TKey has such member - if(!targetTree){ - return; - } - - deletedItems.clear(); newItems.clear(); modifiedItems.clear(); - - TreeNode* node; - - fromNode == NULL ? node = GetRoot() : node = fromNode; - TreeWalker sourceTreeWalker(node); - TreeWalker targetTreeWalker(targetTree->GetRoot()); - - for(; !sourceTreeWalker.End(); sourceTreeWalker++) - { - if( sourceTreeWalker.GetNode()->IsRoot() ) - continue; - - TreeNode* node = targetTree->Find(sourceTreeWalker.GetNode()->GetKey()); - if(node == NULL) - { - // Item does not exist in target tree which means it must been deleted - std::pair itemPair; - - itemPair.first = sourceTreeWalker.GetNode()->GetKey().c_str(); - itemPair.second = sourceTreeWalker.GetNode()->GetData(); - deletedItems.push_back( itemPair ); - } - else - { - // Compare data - if(node->GetData() == sourceTreeWalker.GetNode()->GetData()) - continue; - - // Data was modified - std::pair itemPair; - itemPair.first = sourceTreeWalker.GetNode()->GetKey().c_str(); - itemPair.second = node->GetData(); - modifiedItems.push_back( itemPair ); - } - } - - for(; !targetTreeWalker.End(); targetTreeWalker++) - { - if(targetTreeWalker.GetNode()->IsRoot()) - continue; - - if(Find(targetTreeWalker.GetNode()->GetKey()) == NULL) - { - // Node from target tree does not exist in this tree - // which means that this node is new - // Data was modified - std::pair itemPair; - itemPair.first = targetTreeWalker.GetNode()->GetKey().c_str(); - itemPair.second = targetTreeWalker.GetNode()->GetData(); - newItems.push_back( itemPair ); - } - } -} - -#endif // CODELITE_TREE_H + TreeNode* parentNode; + (parent == NULL) ? parentNode = m_root : parentNode = parent; + TreeNode* node = parentNode->AddChild(key, data); + m_nodes[key] = node; + return node; +} + +template +TreeNode* Tree::Remove(const TKey& key) +{ + typename std::map*>::const_iterator iter = m_nodes.find(key); + if (iter == m_nodes.end()) + return NULL; + + // Remove from the map all sub-nodes of the tree + TreeWalker walker(iter->second); + + for (; !walker.End(); walker++) { + typename std::map*>::iterator it = m_nodes.find(walker.GetNode()->GetKey()); + if (it != m_nodes.end()) + m_nodes.erase(it); + } + return m_root->Remove(key); +} +template +void Tree::Print(std::ostream& stream, int depth) +{ + m_root->Print(stream, depth); +} + +template +void Tree::Compare(Tree* targetTree, + std::vector>& deletedItems, + std::vector>& modifiedItems, + std::vector>& newItems, + TreeNode* fromNode) +{ + // we break generic for the sake of thread safety: + // we explicitly calling TKey.c_str(), which means that we assume that TKey has such member + if (!targetTree) { + return; + } + + deletedItems.clear(); + newItems.clear(); + modifiedItems.clear(); + + TreeNode* node; + + fromNode == NULL ? node = GetRoot() : node = fromNode; + TreeWalker sourceTreeWalker(node); + TreeWalker targetTreeWalker(targetTree->GetRoot()); + + for (; !sourceTreeWalker.End(); sourceTreeWalker++) { + if (sourceTreeWalker.GetNode()->IsRoot()) + continue; + + TreeNode* node = targetTree->Find(sourceTreeWalker.GetNode()->GetKey()); + if (node == NULL) { + // Item does not exist in target tree which means it must been deleted + std::pair itemPair; + + itemPair.first = sourceTreeWalker.GetNode()->GetKey().c_str(); + itemPair.second = sourceTreeWalker.GetNode()->GetData(); + deletedItems.push_back(itemPair); + } else { + // Compare data + if (node->GetData() == sourceTreeWalker.GetNode()->GetData()) + continue; + + // Data was modified + std::pair itemPair; + itemPair.first = sourceTreeWalker.GetNode()->GetKey().c_str(); + itemPair.second = node->GetData(); + modifiedItems.push_back(itemPair); + } + } + + for (; !targetTreeWalker.End(); targetTreeWalker++) { + if (targetTreeWalker.GetNode()->IsRoot()) + continue; + + if (Find(targetTreeWalker.GetNode()->GetKey()) == NULL) { + // Node from target tree does not exist in this tree + // which means that this node is new + // Data was modified + std::pair itemPair; + itemPair.first = targetTreeWalker.GetNode()->GetKey().c_str(); + itemPair.second = targetTreeWalker.GetNode()->GetData(); + newItems.push_back(itemPair); + } + } +} + +#endif // CODELITE_TREE_H diff --git a/CodeLite/tree_node.h b/CodeLite/tree_node.h index dc63648857..be51944dc2 100644 --- a/CodeLite/tree_node.h +++ b/CodeLite/tree_node.h @@ -26,266 +26,245 @@ #ifndef CODELITE_TREE_NODE_H #define CODELITE_TREE_NODE_H - -#include #include +#include #include template class TreeNode { - TKey m_key; - TData m_data; - TreeNode* m_parent; - std::map m_children; - typename std::map::iterator m_pos; + TKey m_key; + TData m_data; + TreeNode* m_parent; + std::map m_children; + typename std::map::iterator m_pos; public: - /** - * Constructor, constructs a tree node with key and data. - * If parent is left NULL, node is assumed to be root. - * \param key Node key, must have operator =, < - * \param data Node data, this class must have operator= - * \param parent Parent node - */ - TreeNode(const TKey& key, const TData& data, TreeNode* parent = NULL); - - /** - * Destructor, deletes this node and all its children. - */ - virtual ~TreeNode(); - - //--------------------------------------------------- - // Setters / Getters - //--------------------------------------------------- - - /** - * Get node data. - * \return node data - */ - TData& GetData() - { - return m_data; - }; - - /** - * Get node key. - * \return key - */ - TKey& GetKey() - { - return m_key; - }; - - /** - * Set node data. - * \param data data - */ - void SetData(const TData& data) - { - m_data = data; - }; - - /** - * Set node key. - * \param key Key - */ - void SetKey(const TKey& key) - { - m_key = key; - }; - - /** - * Return the parent node of this node (or null if root). - * \return pointer to parent node - */ - TreeNode* GetParent() - { - return m_parent; - } - - //--------------------------------------------- - // Misc - //--------------------------------------------- - - /** - * Print the tree to stream (default is stdout). - */ - void Print(std::ostream& stream = std::cout , int depth = 0) const; - - /** - * Check if this node is root. - * \return true if node is root - */ - bool IsRoot() const - { - return m_parent == NULL; - }; - - //---------------------------------------------- - // Operations - //---------------------------------------------- - /** - * Add new child node to this node. - * Duplicate nodes are allowed. However, Remove() will remove the first occurrence of a node by a given key. - * \param key Node key - * \param data Node data - * \return newly added node - */ - TreeNode* AddChild(const TKey& key, const TData& data) ; - - /** - * \brief Append new child to this tree node - * \param newNode node to append, must be allocated on the heap - * \return the newly added tree node - */ - TreeNode* AddChild(TreeNode* newNode); - - /** - * Remove first occurrence of node with a given key. - * If the node to be removed is the root, a std::exception* is thrown, which must be deleted by caller. - * Remove does not delete the memory allocated for the node. The user must delete the removed node. - * \param key Node key - * \return removed node - */ - TreeNode* Remove(const TKey& key); - - /** - * Find a node by a key. - * \param key Node key - * \return node, or NULL if non exist - */ - TreeNode* Find(const TKey& key) ; - - /** - * Set the pointer to the first child of this node . - */ - void First(); - - /** - * Return the next child of this node. - */ - TreeNode* Next(); - - /** - * Test if this node has more children. - * This call is usually used before issuing a Next() call. - * \return true if the next call to Next() will return a valid child pointer - */ - bool HasMore() const; - std::map& GetChildren() { return m_children; } + /** + * Constructor, constructs a tree node with key and data. + * If parent is left NULL, node is assumed to be root. + * \param key Node key, must have operator =, < + * \param data Node data, this class must have operator= + * \param parent Parent node + */ + TreeNode(const TKey& key, const TData& data, TreeNode* parent = NULL); + + /** + * Destructor, deletes this node and all its children. + */ + virtual ~TreeNode(); + + //--------------------------------------------------- + // Setters / Getters + //--------------------------------------------------- + + /** + * Get node data. + * \return node data + */ + TData& GetData() { return m_data; }; + + /** + * Get node key. + * \return key + */ + TKey& GetKey() { return m_key; }; + + /** + * Set node data. + * \param data data + */ + void SetData(const TData& data) { m_data = data; }; + + /** + * Set node key. + * \param key Key + */ + void SetKey(const TKey& key) { m_key = key; }; + + /** + * Return the parent node of this node (or null if root). + * \return pointer to parent node + */ + TreeNode* GetParent() { return m_parent; } + + //--------------------------------------------- + // Misc + //--------------------------------------------- + + /** + * Print the tree to stream (default is stdout). + */ + void Print(std::ostream& stream = std::cout, int depth = 0) const; + + /** + * Check if this node is root. + * \return true if node is root + */ + bool IsRoot() const { return m_parent == NULL; }; + + //---------------------------------------------- + // Operations + //---------------------------------------------- + /** + * Add new child node to this node. + * Duplicate nodes are allowed. However, Remove() will remove the first occurrence of a node by a given key. + * \param key Node key + * \param data Node data + * \return newly added node + */ + TreeNode* AddChild(const TKey& key, const TData& data); + + /** + * \brief Append new child to this tree node + * \param newNode node to append, must be allocated on the heap + * \return the newly added tree node + */ + TreeNode* AddChild(TreeNode* newNode); + + /** + * Remove first occurrence of node with a given key. + * If the node to be removed is the root, a std::exception* is thrown, which must be deleted by caller. + * Remove does not delete the memory allocated for the node. The user must delete the removed node. + * \param key Node key + * \return removed node + */ + TreeNode* Remove(const TKey& key); + + /** + * Find a node by a key. + * \param key Node key + * \return node, or NULL if non exist + */ + TreeNode* Find(const TKey& key); + + /** + * Set the pointer to the first child of this node . + */ + void First(); + + /** + * Return the next child of this node. + */ + TreeNode* Next(); + + /** + * Test if this node has more children. + * This call is usually used before issuing a Next() call. + * \return true if the next call to Next() will return a valid child pointer + */ + bool HasMore() const; + std::map& GetChildren() { return m_children; } }; template TreeNode::TreeNode(const TKey& key, const TData& data, TreeNode* parent) -: m_key(key), m_data(data), m_parent(parent) + : m_key(key) + , m_data(data) + , m_parent(parent) { } template TreeNode::~TreeNode() { - for (const auto& [_, p] : m_children) - { - delete p; - } - m_children.clear(); + for (const auto& [_, p] : m_children) { + delete p; + } + m_children.clear(); } template TreeNode* TreeNode::AddChild(const TKey& key, const TData& data) { - TreeNode* newNode = new TreeNode(key, data, this); - m_children[newNode] = newNode; - return newNode; + TreeNode* newNode = new TreeNode(key, data, this); + m_children[newNode] = newNode; + return newNode; +} + +template +TreeNode* TreeNode::AddChild(TreeNode* newNode) +{ + m_children[newNode] = newNode; + return newNode; } - -template -TreeNode* TreeNode::AddChild(TreeNode* newNode) -{ - m_children[newNode] = newNode; - return newNode; -} template TreeNode* TreeNode::Remove(const TKey& key) { - TreeNode* node = Find(key); - if( node ) - { - if(NULL == node->m_parent) - { - // Cant remove root - return NULL; - } - - typename std::map::iterator iter = node->m_parent->m_children.find(node); - if (iter != node->m_parent->m_children.end()) - node->m_parent->m_children.erase(iter); - return node; - } - return NULL; + TreeNode* node = Find(key); + if (node) { + if (NULL == node->m_parent) { + // Cant remove root + return NULL; + } + + typename std::map::iterator iter = node->m_parent->m_children.find(node); + if (iter != node->m_parent->m_children.end()) + node->m_parent->m_children.erase(iter); + return node; + } + return NULL; } template TreeNode* TreeNode::Find(const TKey& key) { - if(m_key == key) - return this; - - typename std::map::iterator iter; - - // Scan first the children of this node - for (auto& [_, child] : m_children) - { - if (child->GetKey() == key) - return child; - } - - // Scan level below - for (auto& [_, child] : m_children) - { - TreeNode* node = child->Find(key); - if (node) return node; - } - return NULL; + if (m_key == key) + return this; + + typename std::map::iterator iter; + + // Scan first the children of this node + for (auto& [_, child] : m_children) { + if (child->GetKey() == key) + return child; + } + + // Scan level below + for (auto& [_, child] : m_children) { + TreeNode* node = child->Find(key); + if (node) + return node; + } + return NULL; } template void TreeNode::Print(std::ostream& stream, int depth) const { - std::string tab = " "; - for(int i=0; iPrint(stream, depth); + for (const auto& [_, child] : m_children) + child->Print(stream, depth); } /// Prepare for tree iteration in the current node template void TreeNode::First() { - m_pos = m_children.begin(); + m_pos = m_children.begin(); } template TreeNode* TreeNode::Next() { - if(!HasMore()) - return NULL; - TreeNode* nextElem = m_pos->second; - m_pos++; - return nextElem; + if (!HasMore()) + return NULL; + TreeNode* nextElem = m_pos->second; + m_pos++; + return nextElem; } template bool TreeNode::HasMore() const { - return m_pos != m_children.end(); + return m_pos != m_children.end(); } //---------------------------------------------------------------- @@ -296,29 +275,29 @@ template class TreeWalker { private: - void GetChildren(TreeNode* node); - std::vector* > m_children; - size_t m_pos; + void GetChildren(TreeNode* node); + std::vector*> m_children; + size_t m_pos; public: - TreeWalker(TreeNode* node); - virtual ~TreeWalker(); - bool End(); - void operator++(int); - TreeNode* GetNode() - { - if(m_pos < m_children.size()) - return m_children[m_pos]; - return NULL; - } + TreeWalker(TreeNode* node); + virtual ~TreeWalker(); + bool End(); + void operator++(int); + TreeNode* GetNode() + { + if (m_pos < m_children.size()) + return m_children[m_pos]; + return NULL; + } }; template TreeWalker::TreeWalker(TreeNode* node) -: m_pos(0) + : m_pos(0) { - m_children.push_back(node); - GetChildren(node); + m_children.push_back(node); + GetChildren(node); } template @@ -329,25 +308,24 @@ TreeWalker::~TreeWalker() template void TreeWalker::GetChildren(TreeNode* node) { - if(node == NULL) - return; - for (auto& [_, child] : node->GetChildren()) - { - m_children.push_back(child); - GetChildren(child); - } + if (node == NULL) + return; + for (auto& [_, child] : node->GetChildren()) { + m_children.push_back(child); + GetChildren(child); + } } template bool TreeWalker::End() { - return m_pos == m_children.size(); + return m_pos == m_children.size(); } template void TreeWalker::operator++(int) { - m_pos++; + m_pos++; } #endif // CODELITE_TREE_NODE_H diff --git a/CodeLite/winprocess.cpp b/CodeLite/winprocess.cpp index 9676835e16..9d2f04469e 100644 --- a/CodeLite/winprocess.cpp +++ b/CodeLite/winprocess.cpp @@ -35,7 +35,7 @@ WinProcess* WinProcess::Execute(const wxString& cmd, wxString& errMsg, const wxS BOOL fSuccess; wxString wd(workingDir); - if(workingDir.IsEmpty()) { + if (workingDir.IsEmpty()) { wd = wxGetCwd(); } @@ -58,21 +58,26 @@ WinProcess* WinProcess::Execute(const wxString& cmd, wxString& errMsg, const wxS prc->hSaveStdout = GetStdHandle(STD_OUTPUT_HANDLE); // Create a pipe for the child process's STDOUT. - if(!CreatePipe(&prc->hChildStdoutRd, &prc->hChildStdoutWr, &saAttr, 0)) { + if (!CreatePipe(&prc->hChildStdoutRd, &prc->hChildStdoutWr, &saAttr, 0)) { delete prc; return NULL; } // Set a write handle to the pipe to be STDOUT. - if(!SetStdHandle(STD_OUTPUT_HANDLE, prc->hChildStdoutWr)) { + if (!SetStdHandle(STD_OUTPUT_HANDLE, prc->hChildStdoutWr)) { delete prc; return NULL; } // Create noninheritable read handle and close the inheritable read handle. - fSuccess = DuplicateHandle(GetCurrentProcess(), prc->hChildStdoutRd, GetCurrentProcess(), &prc->hChildStdoutRdDup, - 0, FALSE, DUPLICATE_SAME_ACCESS); - if(!fSuccess) { + fSuccess = DuplicateHandle(GetCurrentProcess(), + prc->hChildStdoutRd, + GetCurrentProcess(), + &prc->hChildStdoutRdDup, + 0, + FALSE, + DUPLICATE_SAME_ACCESS); + if (!fSuccess) { delete prc; return NULL; } @@ -90,20 +95,24 @@ WinProcess* WinProcess::Execute(const wxString& cmd, wxString& errMsg, const wxS prc->hSaveStdin = GetStdHandle(STD_INPUT_HANDLE); // Create a pipe for the child process's STDIN. - if(!CreatePipe(&prc->hChildStdinRd, &prc->hChildStdinWr, &saAttr, 0)) { + if (!CreatePipe(&prc->hChildStdinRd, &prc->hChildStdinWr, &saAttr, 0)) { delete prc; return NULL; } // Set a read handle to the pipe to be STDIN. - if(!SetStdHandle(STD_INPUT_HANDLE, prc->hChildStdinRd)) { + if (!SetStdHandle(STD_INPUT_HANDLE, prc->hChildStdinRd)) { delete prc; return NULL; } // Duplicate the write handle to the pipe so it is not inherited. - fSuccess = DuplicateHandle(GetCurrentProcess(), prc->hChildStdinWr, GetCurrentProcess(), &prc->hChildStdinWrDup, 0, + fSuccess = DuplicateHandle(GetCurrentProcess(), + prc->hChildStdinWr, + GetCurrentProcess(), + &prc->hChildStdinWrDup, + 0, FALSE, // not inherited DUPLICATE_SAME_ACCESS); - if(!fSuccess) { + if (!fSuccess) { delete prc; return NULL; } @@ -123,7 +132,7 @@ WinProcess* WinProcess::Execute(const wxString& cmd, wxString& errMsg, const wxS // Set the window to hide siStartInfo.wShowWindow = SW_HIDE; BOOL ret = CreateProcess(NULL, - cmd.wchar_str(), // shell line execution command + cmd.wchar_str(), // shell line execution command NULL, // process security attributes NULL, // primary thread security attributes TRUE, // handles are inherited @@ -132,7 +141,7 @@ WinProcess* WinProcess::Execute(const wxString& cmd, wxString& errMsg, const wxS wd.c_str(), // CD to tmp dir &siStartInfo, // STARTUPINFO pointer &prc->piProcInfo); // receives PROCESS_INFORMATION - if(ret) { + if (ret) { prc->dwProcessId = prc->piProcInfo.dwProcessId; } else { int err = GetLastError(); @@ -142,11 +151,11 @@ WinProcess* WinProcess::Execute(const wxString& cmd, wxString& errMsg, const wxS } // After process creation, restore the saved STDIN and STDOUT. - if(!SetStdHandle(STD_INPUT_HANDLE, prc->hSaveStdin)) { + if (!SetStdHandle(STD_INPUT_HANDLE, prc->hSaveStdin)) { delete prc; return NULL; } - if(!SetStdHandle(STD_OUTPUT_HANDLE, prc->hSaveStdout)) { + if (!SetStdHandle(STD_OUTPUT_HANDLE, prc->hSaveStdout)) { delete prc; return NULL; @@ -167,7 +176,7 @@ WinProcess::WinProcess() bool WinProcess::Read(wxString& buff) { constexpr auto bufferSize = 65536; // 64K should be sufficient buffer - std::vector chBuf(bufferSize + 1, '\0'); + std::vector chBuf(bufferSize + 1, '\0'); // Make the pipe to non-blocking mode DWORD dwMode = PIPE_READMODE_BYTE | PIPE_NOWAIT; @@ -204,15 +213,15 @@ bool WinProcess::Write(const wxString& buff) SetNamedPipeHandleState(hChildStdinWrDup, &dwMode, NULL, NULL); // Timeout of 30 seconds DWORD dwWritten; - if(!WriteFile(hChildStdinWrDup, chBuf, (unsigned long)strlen(chBuf), &dwWritten, NULL)) + if (!WriteFile(hChildStdinWrDup, chBuf, (unsigned long)strlen(chBuf), &dwWritten, NULL)) return false; return true; } bool WinProcess::IsAlive() { - if(GetExitCodeProcess(piProcInfo.hProcess, &exit_code)) { - if(exit_code == STILL_ACTIVE) + if (GetExitCodeProcess(piProcInfo.hProcess, &exit_code)) { + if (exit_code == STILL_ACTIVE) return true; } return false; @@ -220,7 +229,7 @@ bool WinProcess::IsAlive() void WinProcess::Cleanup() { - if(IsAlive()) + if (IsAlive()) TerminateProcess(piProcInfo.hProcess, 255); CloseHandle(hChildStdinRd); diff --git a/CodeLite/winprocess.h b/CodeLite/winprocess.h index 772fb666e5..bee8d287d4 100644 --- a/CodeLite/winprocess.h +++ b/CodeLite/winprocess.h @@ -27,9 +27,9 @@ #ifdef __WXMSW__ +#include // Required for std::numeric_limits #include // includes windows.h #include -#include // Required for std::numeric_limits class WinProcess { diff --git a/CodeLite/worker_thread.cpp b/CodeLite/worker_thread.cpp index 7572690525..c002f47c5f 100644 --- a/CodeLite/worker_thread.cpp +++ b/CodeLite/worker_thread.cpp @@ -34,8 +34,8 @@ WorkerThread::~WorkerThread() { Stop(); } static ThreadRequest* QueueGet(std::mutex& m, std::queue& q, std::condition_variable& cv) { - std::unique_lock lock{ m }; // acquiring the mutex - while(q.empty()) { + std::unique_lock lock{m}; // acquiring the mutex + while (q.empty()) { cv.wait(lock); // waiting to be notified of new data } @@ -47,21 +47,22 @@ static ThreadRequest* QueueGet(std::mutex& m, std::queue& q, std static void QueuePut(std::mutex& m, std::queue& q, std::condition_variable& cv, ThreadRequest* req) { - std::unique_lock lock{ m }; // Acquires the mutex - q.push(req); // Forward the param to the - lock.unlock(); // operation on the wrapped collection + std::unique_lock lock{m}; // Acquires the mutex + q.push(req); // Forward the param to the + lock.unlock(); // operation on the wrapped collection cv.notify_one(); } void* WorkerThread::Entry() { - while(true) { + while (true) { // Did we get a request to terminate? - if(TestDestroy()) break; + if (TestDestroy()) + break; // Get the next entry from the queue ThreadRequest* request = QueueGet(m_mutex, m_Q, m_cv); - if(request == nullptr) { + if (request == nullptr) { // this dummy message was sent to tell us to exit break; } @@ -74,7 +75,9 @@ void* WorkerThread::Entry() void WorkerThread::Add(ThreadRequest* request) { - if(!request) { return; } + if (!request) { + return; + } QueuePut(m_mutex, m_Q, m_cv, request); } @@ -84,7 +87,7 @@ void WorkerThread::Stop() // wait for it QueuePut(m_mutex, m_Q, m_cv, nullptr); // Make sure that the thread wakes up - if(IsAlive()) { + if (IsAlive()) { Delete(NULL, wxTHREAD_WAIT_BLOCK); } else { @@ -102,7 +105,7 @@ void WorkerThread::Start(int priority) void WorkerThread::ClearQueue() { std::unique_lock lk(m_mutex); - while(!m_Q.empty()) { + while (!m_Q.empty()) { m_Q.pop(); } } diff --git a/CodeLite/worker_thread.h b/CodeLite/worker_thread.h index d01d46fb5d..d5872c6f49 100644 --- a/CodeLite/worker_thread.h +++ b/CodeLite/worker_thread.h @@ -87,7 +87,7 @@ class WXDLLIMPEXP_CL WorkerThread : public wxThread * @brief clear the request queue */ void ClearQueue(); - + /** * Set the window to be notified when a change was done * between current source file tree and the actual tree. diff --git a/CodeLite/wxCodeCompletionBoxEntry.hpp b/CodeLite/wxCodeCompletionBoxEntry.hpp index 63c43e1d82..b9e64e9123 100644 --- a/CodeLite/wxCodeCompletionBoxEntry.hpp +++ b/CodeLite/wxCodeCompletionBoxEntry.hpp @@ -67,7 +67,7 @@ class WXDLLIMPEXP_CL wxCodeCompletionBoxEntry protected: void EnableFlag(bool b, eFlags f) { - if(b) { + if (b) { this->m_flags |= f; } else { this->m_flags &= ~f; @@ -100,7 +100,9 @@ class WXDLLIMPEXP_CL wxCodeCompletionBoxEntry { } - wxCodeCompletionBoxEntry(const wxString& text, const wxBitmap& bmp, const wxString& helpText, + wxCodeCompletionBoxEntry(const wxString& text, + const wxBitmap& bmp, + const wxString& helpText, wxClientData* userData = NULL) : m_text(text) , m_comment(helpText) @@ -135,7 +137,7 @@ class WXDLLIMPEXP_CL wxCodeCompletionBoxEntry void SetSignature(const wxString& signature) { this->m_signature = signature; } const wxString& GetSignature() const { return m_signature; } - + void SetTriggerInclude(bool isTriggerInclude) { EnableFlag(isTriggerInclude, kTriggerInclude); } bool IsTriggerInclude() const { return HasFlag(kTriggerInclude); } @@ -147,8 +149,8 @@ class WXDLLIMPEXP_CL wxCodeCompletionBoxEntry /** * @brief helper method for allocating wxCodeCompletionBoxEntry::Ptr */ - static wxCodeCompletionBoxEntry::Ptr_t New(const wxString& text, int imgId = wxNOT_FOUND, - wxClientData* userData = NULL) + static wxCodeCompletionBoxEntry::Ptr_t + New(const wxString& text, int imgId = wxNOT_FOUND, wxClientData* userData = NULL) { wxCodeCompletionBoxEntry::Ptr_t pEntry(new wxCodeCompletionBoxEntry(text, imgId, userData)); return pEntry; @@ -166,8 +168,8 @@ class WXDLLIMPEXP_CL wxCodeCompletionBoxEntry /** * @brief helper method for allocating wxCodeCompletionBoxEntry::Ptr */ - static wxCodeCompletionBoxEntry::Ptr_t New(const wxString& text, const wxString& helpText, const wxBitmap& bmp, - wxClientData* userData = NULL) + static wxCodeCompletionBoxEntry::Ptr_t + New(const wxString& text, const wxString& helpText, const wxBitmap& bmp, wxClientData* userData = NULL) { wxCodeCompletionBoxEntry::Ptr_t pEntry(new wxCodeCompletionBoxEntry(text, bmp, helpText, userData)); return pEntry; diff --git a/CodeLite/xmlutils.cpp b/CodeLite/xmlutils.cpp index 40f4d071d0..9995eeae70 100644 --- a/CodeLite/xmlutils.cpp +++ b/CodeLite/xmlutils.cpp @@ -30,15 +30,15 @@ wxXmlNode* XmlUtils::FindNodeByName(const wxXmlNode* parent, const wxString& tagName, const wxString& name) { - if(!parent) { + if (!parent) { return nullptr; } wxXmlNode* child = parent->GetChildren(); - while(child) { - if(child->GetName() == tagName) { - if((child->GetAttribute(wxT("Name"), wxEmptyString) == name) || - (child->GetAttribute(wxT("name"), wxEmptyString) == name)) { + while (child) { + if (child->GetName() == tagName) { + if ((child->GetAttribute(wxT("Name"), wxEmptyString) == name) || + (child->GetAttribute(wxT("name"), wxEmptyString) == name)) { return child; } } @@ -49,13 +49,13 @@ wxXmlNode* XmlUtils::FindNodeByName(const wxXmlNode* parent, const wxString& tag wxXmlNode* XmlUtils::FindFirstByTagName(const wxXmlNode* parent, const wxString& tagName) { - if(!parent) { + if (!parent) { return nullptr; } wxXmlNode* child = parent->GetChildren(); - while(child) { - if(child->GetName() == tagName) { + while (child) { + if (child->GetName() == tagName) { return child; } child = child->GetNext(); @@ -67,8 +67,8 @@ wxXmlNode* XmlUtils::FindLastByTagName(const wxXmlNode* parent, const wxString& { wxXmlNode* last_node = nullptr; wxXmlNode* child = parent->GetChildren(); - while(child) { - if(child->GetName() == tagName) { + while (child) { + if (child->GetName() == tagName) { last_node = child; } child = child->GetNext(); @@ -79,8 +79,8 @@ wxXmlNode* XmlUtils::FindLastByTagName(const wxXmlNode* parent, const wxString& void XmlUtils::UpdateProperty(wxXmlNode* node, const wxString& name, const wxString& value) { auto prop = node->GetAttributes(); - while(prop) { - if(prop->GetName() == name) { + while (prop) { + if (prop->GetName() == name) { prop->SetValue(value); return; } @@ -104,14 +104,14 @@ bool XmlUtils::ReadStringIfExists(const wxXmlNode* node, const wxString& propNam long XmlUtils::ReadLong(const wxXmlNode* node, const wxString& propName, long defaultValue) { wxString val = node->GetAttribute(propName, wxEmptyString); - if(val.IsEmpty()) { + if (val.IsEmpty()) { return defaultValue; } - if(val.StartsWith(wxT("\""))) { + if (val.StartsWith(wxT("\""))) { val = val.AfterFirst(wxT('"')); } - if(val.EndsWith(wxT("\""))) { + if (val.EndsWith(wxT("\""))) { val = val.BeforeLast(wxT('"')); } long retVal = defaultValue; @@ -122,14 +122,14 @@ long XmlUtils::ReadLong(const wxXmlNode* node, const wxString& propName, long de bool XmlUtils::ReadLongIfExists(const wxXmlNode* node, const wxString& propName, long& answer) { wxString value; - if(!node->GetAttribute(propName, &value)) { + if (!node->GetAttribute(propName, &value)) { return false; } - if(value.StartsWith(wxT("\""))) { + if (value.StartsWith(wxT("\""))) { value = value.AfterFirst(wxT('"')); } - if(value.EndsWith(wxT("\""))) { + if (value.EndsWith(wxT("\""))) { value = value.BeforeLast(wxT('"')); } @@ -141,12 +141,12 @@ bool XmlUtils::ReadBool(const wxXmlNode* node, const wxString& propName, bool de { wxString val = node->GetAttribute(propName, wxEmptyString); - if(val.IsEmpty()) { + if (val.IsEmpty()) { return defaultValue; } bool retVal = defaultValue; - if(val.CmpNoCase(wxT("yes")) == 0) { + if (val.CmpNoCase(wxT("yes")) == 0) { retVal = true; } else { retVal = false; @@ -157,11 +157,11 @@ bool XmlUtils::ReadBool(const wxXmlNode* node, const wxString& propName, bool de bool XmlUtils::ReadBoolIfExists(const wxXmlNode* node, const wxString& propName, bool& answer) { wxString value; - if(!node->GetAttribute(propName, &value)) { + if (!node->GetAttribute(propName, &value)) { return false; } - if(value.CmpNoCase(wxT("yes")) == 0) { + if (value.CmpNoCase(wxT("yes")) == 0) { answer = true; } else { answer = false; @@ -173,13 +173,13 @@ wxArrayString XmlUtils::ChildNodesContentToArray(const wxXmlNode* node, const wx { wxArrayString arr; - if(!node) { + if (!node) { return arr; } wxXmlNode* child = node->GetChildren(); - while(child) { - if(tagName.empty() || child->GetName() == tagName) { + while (child) { + if (tagName.empty() || child->GetName() == tagName) { arr.Add(child->GetNodeContent()); } child = child->GetNext(); @@ -188,24 +188,25 @@ wxArrayString XmlUtils::ChildNodesContentToArray(const wxXmlNode* node, const wx return arr; } -wxString XmlUtils::ChildNodesContentToString(const wxXmlNode* node, const wxString& tagName /* = wxT("")*/, +wxString XmlUtils::ChildNodesContentToString(const wxXmlNode* node, + const wxString& tagName /* = wxT("")*/, const wxString& separator /* = wxT(";")*/) { wxString str; - if(!node) { + if (!node) { return str; } wxXmlNode* child = node->GetChildren(); - while(child) { - if(tagName.empty() || child->GetName() == tagName) { + while (child) { + if (tagName.empty() || child->GetName() == tagName) { str << child->GetNodeContent() << separator; } child = child->GetNext(); } - if(!str.empty()) { + if (!str.empty()) { str.RemoveLast(separator.Len()); } @@ -216,21 +217,21 @@ void XmlUtils::SetNodeContent(wxXmlNode* node, const wxString& text) { wxXmlNode* n = node->GetChildren(); wxXmlNode* contentNode = nullptr; - while(n) { - if(n->GetType() == wxXML_TEXT_NODE || n->GetType() == wxXML_CDATA_SECTION_NODE) { + while (n) { + if (n->GetType() == wxXML_TEXT_NODE || n->GetType() == wxXML_CDATA_SECTION_NODE) { contentNode = n; break; } n = n->GetNext(); } - if(contentNode) { + if (contentNode) { // remove old node node->RemoveChild(contentNode); delete contentNode; } - if(!text.IsEmpty()) { + if (!text.IsEmpty()) { contentNode = new wxXmlNode(wxXML_TEXT_NODE, wxEmptyString, text); node->AddChild(contentNode); } @@ -239,7 +240,7 @@ void XmlUtils::SetNodeContent(wxXmlNode* node, const wxString& text) void XmlUtils::RemoveChildren(wxXmlNode* node) { wxXmlNode* child = node->GetChildren(); - while(child) { + while (child) { wxXmlNode* nextChild = child->GetNext(); node->RemoveChild(child); delete child; @@ -251,21 +252,21 @@ void XmlUtils::SetCDATANodeContent(wxXmlNode* node, const wxString& text) { wxXmlNode* n = node->GetChildren(); wxXmlNode* contentNode = nullptr; - while(n) { - if(n->GetType() == wxXML_TEXT_NODE || n->GetType() == wxXML_CDATA_SECTION_NODE) { + while (n) { + if (n->GetType() == wxXML_TEXT_NODE || n->GetType() == wxXML_CDATA_SECTION_NODE) { contentNode = n; break; } n = n->GetNext(); } - if(contentNode) { + if (contentNode) { // remove old node node->RemoveChild(contentNode); delete contentNode; } - if(!text.IsEmpty()) { + if (!text.IsEmpty()) { contentNode = new wxXmlNode(wxXML_CDATA_SECTION_NODE, wxEmptyString, text); node->AddChild(contentNode); } @@ -276,12 +277,12 @@ bool XmlUtils::StaticReadObject(wxXmlNode* root, const wxString& name, Serialize // find the object node in the xml file wxXmlNode* node = XmlUtils::FindNodeByName(root, wxT("ArchiveObject"), name); - if(node) { + if (node) { // Check to see if we need a version check wxString objectVersion = obj->GetVersion(); - if(objectVersion.IsEmpty() == false) { - if(node->GetAttribute(wxT("Version"), wxT("")) != objectVersion) { + if (objectVersion.IsEmpty() == false) { + if (node->GetAttribute(wxT("Version"), wxT("")) != objectVersion) { return false; } } @@ -296,12 +297,12 @@ bool XmlUtils::StaticReadObject(wxXmlNode* root, const wxString& name, Serialize bool XmlUtils::StaticWriteObject(wxXmlNode* root, const wxString& name, SerializedObject* obj) { - if(!root) + if (!root) return false; Archive arch; wxXmlNode* child = XmlUtils::FindNodeByName(root, wxT("ArchiveObject"), name); - if(child) { + if (child) { wxXmlNode* n = root; n->RemoveChild(child); delete child; @@ -312,7 +313,7 @@ bool XmlUtils::StaticWriteObject(wxXmlNode* root, const wxString& name, Serializ root->AddChild(child); wxString objectVersion = obj->GetVersion(); - if(objectVersion.IsEmpty() == false) + if (objectVersion.IsEmpty() == false) child->AddAttribute(wxT("Version"), objectVersion); child->AddAttribute(wxT("Name"), name); @@ -323,7 +324,6 @@ bool XmlUtils::StaticWriteObject(wxXmlNode* root, const wxString& name, Serializ return true; } - bool XmlUtils::LoadXmlFile(wxXmlDocument* doc, const wxString& filepath) { CHECK_PTR_RET_FALSE(doc); diff --git a/CodeLite/xmlutils.h b/CodeLite/xmlutils.h index 6e05b27688..bbaf19954e 100644 --- a/CodeLite/xmlutils.h +++ b/CodeLite/xmlutils.h @@ -76,7 +76,8 @@ class WXDLLIMPEXP_CL XmlUtils * \param separator the string to use to separate each child's content, ';' by default * \return a wxString containing the content of each child, separated by 'separator' */ - static wxString ChildNodesContentToString(const wxXmlNode* node, const wxString& tagName = wxT(""), + static wxString ChildNodesContentToString(const wxXmlNode* node, + const wxString& tagName = wxT(""), const wxString& separator = wxT(";")); /** @@ -98,8 +99,8 @@ class WXDLLIMPEXP_CL XmlUtils * \param propName the property name * \param defaultValue default value to return if no property exist */ - static wxString ReadString(const wxXmlNode* node, const wxString& propName, - const wxString& defaultValue = wxEmptyString); + static wxString + ReadString(const wxXmlNode* node, const wxString& propName, const wxString& defaultValue = wxEmptyString); /** * Read long property from the given node diff --git a/CodeLite/xor_string.cpp b/CodeLite/xor_string.cpp index 10265eab69..0645d543fa 100644 --- a/CodeLite/xor_string.cpp +++ b/CodeLite/xor_string.cpp @@ -46,10 +46,10 @@ XORString::XORString(const wxString& value) { } -wxString XORString::toHexString(const wxString &value) const +wxString XORString::toHexString(const wxString& value) const { wxString output; - for(size_t i=0; i i; ++i) { - wxString dec = hexString.Mid(i*4, 4); + wxString dec = hexString.Mid(i * 4, 4); int hexVal; wxSscanf(dec, "%X", &hexVal); output << (wxChar)hexVal; @@ -73,8 +73,8 @@ wxString XORString::fromHexString(const wxString& hexString) const wxString XORString::XOR(const wxString& str, const wxChar KEY) const { wxString output; - for(size_t i=0; i + #include "windowattrmanager.h" +#include + GitApplyPatchDlg::GitApplyPatchDlg(wxWindow* parent) : GitApplyPatchDlgBase(parent) { diff --git a/git/GitDiffOutputParser.cpp b/git/GitDiffOutputParser.cpp index e5ab747608..d4e37cbdc8 100644 --- a/git/GitDiffOutputParser.cpp +++ b/git/GitDiffOutputParser.cpp @@ -1,4 +1,5 @@ #include "GitDiffOutputParser.h" + #include void GitDiffOutputParser::GetDiffMap(const wxString& rawDiff, wxStringMap_t& M, wxArrayString* commitMessage) const @@ -12,16 +13,16 @@ void GitDiffOutputParser::GetDiffMap(const wxString& rawDiff, wxStringMap_t& M, wxString empty; wxString& line = empty; bool nextToken = true; - while(tokenizer.HasMoreTokens() || nextToken == false) { - if(nextToken) { + while (tokenizer.HasMoreTokens() || nextToken == false) { + if (nextToken) { line = tokenizer.GetNextToken(); } nextToken = true; - if(commitMessage && !foundFirstDiff) { + if (commitMessage && !foundFirstDiff) { // The git blame and git CommitList need to display the commit message // This can be found at the top of the output, before the first "diff " - if(!line.StartsWith("diff ")) { + if (!line.StartsWith("diff ")) { commitMessage->Add(line + "\n"); continue; } else { @@ -29,13 +30,13 @@ void GitDiffOutputParser::GetDiffMap(const wxString& rawDiff, wxStringMap_t& M, } } - switch(state) { + switch (state) { case kLookingForFileName: { - if(line.StartsWith(diffPrefix)) { + if (line.StartsWith(diffPrefix)) { int where = line.Find(diffPrefix); line = line.Mid(where + diffPrefix.length()); where = line.Find(" b/"); - if(where != wxNOT_FOUND) { + if (where != wxNOT_FOUND) { line = line.Mid(0, where); } currentFile = line; @@ -43,7 +44,7 @@ void GitDiffOutputParser::GetDiffMap(const wxString& rawDiff, wxStringMap_t& M, } } break; case kLookingForDiff: { - if(line.StartsWith(diffPrefix)) { + if (line.StartsWith(diffPrefix)) { // Add the current outpt to the result output and continue M[currentFile] = currentDiff; currentDiff.Clear(); @@ -61,7 +62,7 @@ void GitDiffOutputParser::GetDiffMap(const wxString& rawDiff, wxStringMap_t& M, } // Add any leftovers - if(!currentFile.IsEmpty()) { + if (!currentFile.IsEmpty()) { M[currentFile] = currentDiff; } } diff --git a/git/GitDiffOutputParser.h b/git/GitDiffOutputParser.h index 66fc4fb9d8..52dcd1d9ba 100644 --- a/git/GitDiffOutputParser.h +++ b/git/GitDiffOutputParser.h @@ -2,6 +2,7 @@ #define GITDIFFOUTPUTPARSER_H #include "macros.h" + #include class GitDiffOutputParser { diff --git a/git/GitLocator.cpp b/git/GitLocator.cpp index e4c5d25ed3..70af6ab5de 100644 --- a/git/GitLocator.cpp +++ b/git/GitLocator.cpp @@ -14,11 +14,11 @@ bool GitLocator::GetExecutable(wxFileName& gitpath) const // Common to all platforms: // use the PATH environment variable to locate git executable wxString path; - if(::wxGetEnv("PATH", &path)) { + if (::wxGetEnv("PATH", &path)) { wxArrayString paths = ::wxStringTokenize(path, ";", wxTOKEN_STRTOK); - for(size_t i = 0; i < paths.GetCount(); ++i) { + for (size_t i = 0; i < paths.GetCount(); ++i) { wxString gitExeFullPath; - if(DoCheckGitInFolder(paths.Item(i), gitExeFullPath)) { + if (DoCheckGitInFolder(paths.Item(i), gitExeFullPath)) { gitpath = gitExeFullPath; return true; } @@ -30,11 +30,11 @@ bool GitLocator::GetExecutable(wxFileName& gitpath) const wxRegKey regGit(wxRegKey::HKLM, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Git_is1"); wxRegKey regGit2(wxRegKey::HKLM, "SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Git_is1"); wxString installLocation; - if(((regGit.Exists() && regGit.QueryValue("InstallLocation", installLocation)) || - (regGit2.Exists() && regGit2.QueryValue("InstallLocation", installLocation))) && + if (((regGit.Exists() && regGit.QueryValue("InstallLocation", installLocation)) || + (regGit2.Exists() && regGit2.QueryValue("InstallLocation", installLocation))) && ::wxDirExists(installLocation)) { wxString gitExeFullPath; - if(DoCheckGitInFolder(installLocation, gitExeFullPath)) { + if (DoCheckGitInFolder(installLocation, gitExeFullPath)) { gitpath = gitExeFullPath; return true; } @@ -46,14 +46,14 @@ bool GitLocator::GetExecutable(wxFileName& gitpath) const bool GitLocator::DoCheckGitInFolder(const wxString& folder, wxString& git) const { wxFileName gitExe(folder, "git.exe"); - if(gitExe.Exists()) { + if (gitExe.Exists()) { git = gitExe.GetFullPath(); return true; } // try to see if we have git.exe under an internal folder gitExe.AppendDir("bin"); - if(gitExe.Exists()) { + if (gitExe.Exists()) { git = gitExe.GetFullPath(); return true; } @@ -66,14 +66,14 @@ bool GitLocator::MSWGetGitShellCommand(wxString& bashCommand) const wxRegKey regGit(wxRegKey::HKLM, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Git_is1"); wxRegKey regGit2(wxRegKey::HKLM, "SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Git_is1"); wxString installLocation; - if(((regGit.Exists() && regGit.QueryValue("InstallLocation", installLocation)) || - (regGit2.Exists() && regGit2.QueryValue("InstallLocation", installLocation))) && + if (((regGit.Exists() && regGit.QueryValue("InstallLocation", installLocation)) || + (regGit2.Exists() && regGit2.QueryValue("InstallLocation", installLocation))) && ::wxDirExists(installLocation)) { wxString gitExeFullPath; - if(DoCheckGitInFolder(installLocation, gitExeFullPath)) { + if (DoCheckGitInFolder(installLocation, gitExeFullPath)) { wxFileName gitpath = gitExeFullPath; gitpath.SetName("bash"); - if(gitpath.Exists()) { + if (gitpath.Exists()) { bashCommand = gitpath.GetFullPath(); StringUtils::WrapWithQuotes(bashCommand); bashCommand << " --login -i"; diff --git a/git/GitLocator.h b/git/GitLocator.h index 84e6502bfc..ace93d54c2 100644 --- a/git/GitLocator.h +++ b/git/GitLocator.h @@ -30,11 +30,12 @@ class GitLocator { - bool DoCheckGitInFolder(const wxString &folder, wxString& git) const; + bool DoCheckGitInFolder(const wxString& folder, wxString& git) const; + public: GitLocator() = default; virtual ~GitLocator() = default; - + bool GetExecutable(wxFileName& gitpath) const; /** * @brief return the command required to open a git shell diff --git a/git/GitResetDlg.cpp b/git/GitResetDlg.cpp index 75ed481c15..d9a02773e0 100644 --- a/git/GitResetDlg.cpp +++ b/git/GitResetDlg.cpp @@ -1,4 +1,5 @@ #include "GitResetDlg.h" + #include "bitmap_loader.h" #include "globals.h" #include "imanager.h" @@ -9,11 +10,11 @@ GitResetDlg::GitResetDlg(wxWindow* parent, const wxArrayString& filesToRevert, c , m_toggleReverts(false) , m_toggleRemoves(false) { - for(size_t i = 0; i < filesToRevert.GetCount(); ++i) { + for (size_t i = 0; i < filesToRevert.GetCount(); ++i) { m_checkListBoxChanged->Append(filesToRevert.Item(i)); m_checkListBoxChanged->Check(i, true); } - for(size_t i = 0; i < filesToRemove.GetCount(); ++i) { + for (size_t i = 0; i < filesToRemove.GetCount(); ++i) { m_checkListBoxNew->Append(filesToRemove.Item(i)); m_checkListBoxNew->Check(i, true); } @@ -23,7 +24,7 @@ GitResetDlg::GitResetDlg(wxWindow* parent, const wxArrayString& filesToRevert, c m_clToolbarAltered->Bind(wxEVT_TOOL, &GitResetDlg::OnToggleAllRevert, this, XRCID("toggle-all-altered")); m_clToolbarAltered->Bind(wxEVT_UPDATE_UI, &GitResetDlg::OnToggleAllRevertUI, this, XRCID("toggle-all-altered")); m_clToolbarAltered->Realize(); - + images = m_clToolbarAdded->GetBitmapsCreateIfNeeded(); m_clToolbarAdded->AddTool(XRCID("toggle-all-added"), _("Toggle All"), images->Add("check-all")); m_clToolbarAdded->Bind(wxEVT_TOOL, &GitResetDlg::OnToggleAllRemove, this, XRCID("toggle-all-added")); @@ -35,8 +36,8 @@ GitResetDlg::GitResetDlg(wxWindow* parent, const wxArrayString& filesToRevert, c wxArrayString GitResetDlg::GetItemsToRevert() const { wxArrayString toRevert; - for(size_t i = 0; i < m_checkListBoxChanged->GetCount(); ++i) { - if(m_checkListBoxChanged->IsChecked(i)) { + for (size_t i = 0; i < m_checkListBoxChanged->GetCount(); ++i) { + if (m_checkListBoxChanged->IsChecked(i)) { toRevert.Add(m_checkListBoxChanged->GetString(i)); } } @@ -46,8 +47,8 @@ wxArrayString GitResetDlg::GetItemsToRevert() const wxArrayString GitResetDlg::GetItemsToRemove() const { wxArrayString toRemove; - for(size_t i = 0; i < m_checkListBoxNew->GetCount(); ++i) { - if(m_checkListBoxNew->IsChecked(i)) { + for (size_t i = 0; i < m_checkListBoxNew->GetCount(); ++i) { + if (m_checkListBoxNew->IsChecked(i)) { toRemove.Add(m_checkListBoxNew->GetString(i)); } } @@ -57,7 +58,7 @@ wxArrayString GitResetDlg::GetItemsToRemove() const void GitResetDlg::OnToggleAllRevert(wxCommandEvent& event) { - for(size_t i = 0; i < m_checkListBoxChanged->GetCount(); ++i) { + for (size_t i = 0; i < m_checkListBoxChanged->GetCount(); ++i) { m_checkListBoxChanged->Check(i, m_toggleReverts); } m_toggleReverts = !m_toggleReverts; @@ -65,7 +66,7 @@ void GitResetDlg::OnToggleAllRevert(wxCommandEvent& event) void GitResetDlg::OnToggleAllRemove(wxCommandEvent& event) { - for(size_t i = 0; i < m_checkListBoxNew->GetCount(); ++i) { + for (size_t i = 0; i < m_checkListBoxNew->GetCount(); ++i) { m_checkListBoxNew->Check(i, m_toggleRemoves); } m_toggleRemoves = !m_toggleRemoves; diff --git a/git/GitResetDlg.h b/git/GitResetDlg.h index 88e89fe15e..9dec1eabb6 100644 --- a/git/GitResetDlg.h +++ b/git/GitResetDlg.h @@ -5,12 +5,12 @@ class GitResetDlg : public GitResetDlgBase { public: - GitResetDlg(wxWindow* parent, const wxArrayString& filesToRemove, const wxArrayString& filesToRevert); + GitResetDlg(wxWindow* parent, const wxArrayString& filesToRemove, const wxArrayString& filesToRevert); virtual ~GitResetDlg() = default; - + wxArrayString GetItemsToRevert() const; wxArrayString GetItemsToRemove() const; - + protected: virtual void OnToggleAllRevert(wxCommandEvent& event); virtual void OnToggleAllRemove(wxCommandEvent& event); diff --git a/git/GitStatusCode.cpp b/git/GitStatusCode.cpp index 0cc12b5d32..5c68b96148 100644 --- a/git/GitStatusCode.cpp +++ b/git/GitStatusCode.cpp @@ -3,21 +3,21 @@ GitStatusCode::GitStatusCode(const wxString& message) { wxString msg = message.Lower(); - if(msg.Contains("username for")) { + if (msg.Contains("username for")) { m_code = Code::ERROR_USER_REQUIRED; - } else if(msg.Contains("commit-msg hook failure") || msg.Contains("pre-commit hook failure")) { + } else if (msg.Contains("commit-msg hook failure") || msg.Contains("pre-commit hook failure")) { m_code = Code::ERROR_HOOK; - } else if(msg.Contains("*** please tell me who you are")) { + } else if (msg.Contains("*** please tell me who you are")) { m_code = Code::ERROR_WHO_ARE_YOU; - } else if(msg.EndsWith("password:") || msg.Contains("password for") || msg.Contains("authentication failed")) { + } else if (msg.EndsWith("password:") || msg.Contains("password for") || msg.Contains("authentication failed")) { m_code = Code::ERROR_PASSWORD_REQUIRED; - } else if((msg.Contains("the authenticity of host") && msg.Contains("can't be established")) || - msg.Contains("key fingerprint")) { + } else if ((msg.Contains("the authenticity of host") && msg.Contains("can't be established")) || + msg.Contains("key fingerprint")) { m_code = Code::ERROR_AUTHENTICITY; - } else if(msg.Contains("fatal: unable to update url base from redirection")) { + } else if (msg.Contains("fatal: unable to update url base from redirection")) { m_code = Code::ERROR_REDIRECT; int where = message.Find("redirect:"); - if(where != wxNOT_FOUND) { + if (where != wxNOT_FOUND) { m_subText = message.Mid(where + wxStrlen("redirect:")); m_subText.Trim().Trim(false); } diff --git a/git/gitCloneDlg.cpp b/git/gitCloneDlg.cpp index 0b13772bc7..1352d876d9 100644 --- a/git/gitCloneDlg.cpp +++ b/git/gitCloneDlg.cpp @@ -24,7 +24,9 @@ ////////////////////////////////////////////////////////////////////////////// #include "gitCloneDlg.h" + #include "windowattrmanager.h" + #include gitCloneDlg::gitCloneDlg(wxWindow* parent) diff --git a/git/gitCommitEditor.cpp b/git/gitCommitEditor.cpp index 3177326d53..156ec17f45 100644 --- a/git/gitCommitEditor.cpp +++ b/git/gitCommitEditor.cpp @@ -26,14 +26,11 @@ #include "gitCommitEditor.h" #include "drawingutils.h" -#include "lexer_configuration.h" #include "editor_config.h" +#include "lexer_configuration.h" -GitCommitEditor::GitCommitEditor(wxWindow* parent, - wxWindowID id, - const wxPoint& position, - const wxSize& size, - long style) +GitCommitEditor::GitCommitEditor( + wxWindow* parent, wxWindowID id, const wxPoint& position, const wxSize& size, long style) : wxStyledTextCtrl(parent, id, position, size, style | wxBORDER_THEME) { InitStyles(); @@ -42,7 +39,7 @@ GitCommitEditor::GitCommitEditor(wxWindow* parent, void GitCommitEditor::InitStyles() { LexerConf::Ptr_t diffLexer = EditorConfigST::Get()->GetLexer("Diff"); - if(diffLexer) { + if (diffLexer) { diffLexer->Apply(this); this->SetLexer(wxSTC_LEX_DIFF); } diff --git a/git/gitCommitEditor.h b/git/gitCommitEditor.h index 8fda1bf3e1..e7dbda83e0 100644 --- a/git/gitCommitEditor.h +++ b/git/gitCommitEditor.h @@ -33,8 +33,8 @@ #ifndef __gitCommitEditor__ #define __gitCommitEditor__ -#include #include +#include class GitCommitEditor : public wxStyledTextCtrl { diff --git a/git/gitDiffDlg.cpp b/git/gitDiffDlg.cpp index 5c6e779c7a..c4bd9adf80 100644 --- a/git/gitDiffDlg.cpp +++ b/git/gitDiffDlg.cpp @@ -82,16 +82,16 @@ void GitDiffDlg::CreateDiff() wxString command = PrepareCommand(); m_plugin->DisplayMessage("GitDiff: " + command); - m_process = m_plugin->AsyncRunGit(this, command, IProcessCreateDefault | IProcessWrapInShell, - m_plugin->GetRepositoryPath()); + m_process = m_plugin->AsyncRunGit( + this, command, IProcessCreateDefault | IProcessWrapInShell, m_plugin->GetRepositoryPath()); } wxString GitDiffDlg::PrepareCommand() const { wxString commitsString = m_commits; - if(commitsString.empty()) { + if (commitsString.empty()) { // Standard diff of changes against HEAD, but which sort? - switch(m_radioBoxStaged->GetSelection()) { + switch (m_radioBoxStaged->GetSelection()) { case 0: commitsString = ""; break; // Unstaged only @@ -104,7 +104,7 @@ wxString GitDiffDlg::PrepareCommand() const } wxString command(" --no-pager diff "); - if(m_checkIgnoreSpace->GetValue()) { + if (m_checkIgnoreSpace->GetValue()) { command << "--ignore-all-space "; // -w } @@ -127,7 +127,7 @@ void GitDiffDlg::SetDiff(const wxString& diff) m_editor->SetReadOnly(false); m_editor->SetText(wxT("")); - if(m_diffMap.size() != 0) { + if (m_diffMap.size() != 0) { wxStringMap_t::iterator it = m_diffMap.begin(); m_editor->SetText((*it).second); m_fileListBox->Select(0); @@ -148,7 +148,7 @@ void GitDiffDlg::OnChangeFile(wxCommandEvent& e) void GitDiffDlg::OnChoseCommits(wxCommandEvent& event) { GitDiffChooseCommitishDlg dlg(this, m_plugin); - if(dlg.ShowModal() == wxID_OK) { + if (dlg.ShowModal() == wxID_OK) { wxString commit1 = dlg.GetFirstCommit(); wxString joiner = dlg.GetJoiner(); // May be ' ' or '...' wxString commit2 = dlg.GetSecondCommit(); diff --git a/git/gitDiffDlg.h b/git/gitDiffDlg.h index 3fe09a5f31..613672ae19 100644 --- a/git/gitDiffDlg.h +++ b/git/gitDiffDlg.h @@ -36,6 +36,7 @@ #include "cl_command_event.h" #include "gitui.h" #include "macros.h" + #include class GitCommitEditor; diff --git a/git/gitFileDiffDlg.cpp b/git/gitFileDiffDlg.cpp index db56f638f7..7ba85831c0 100644 --- a/git/gitFileDiffDlg.cpp +++ b/git/gitFileDiffDlg.cpp @@ -23,11 +23,12 @@ ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// -#include "gitCommitEditor.h" #include "gitFileDiffDlg.h" -#include "windowattrmanager.h" +#include "gitCommitEditor.h" #include "globals.h" +#include "windowattrmanager.h" + #include #include @@ -47,9 +48,9 @@ GitFileDiffDlg::GitFileDiffDlg(wxWindow* parent) /*******************************************************************************/ void GitFileDiffDlg::OnSaveAsPatch(wxCommandEvent& event) { - wxString path = ::wxFileSelector(_("Save as"), "", "untitled", "patch", wxFileSelectorDefaultWildcardStr, - wxFD_SAVE | wxFD_OVERWRITE_PROMPT); - if(!path.IsEmpty()) { + wxString path = ::wxFileSelector( + _("Save as"), "", "untitled", "patch", wxFileSelectorDefaultWildcardStr, wxFD_SAVE | wxFD_OVERWRITE_PROMPT); + if (!path.IsEmpty()) { ::WriteFileWithBackup(path, m_editor->GetText(), false); ::wxMessageBox("Diff written to:\n" + path, "CodeLite"); // Close the dialog diff --git a/git/gitLogDlg.cpp b/git/gitLogDlg.cpp index c93f7853b7..622885aaf0 100644 --- a/git/gitLogDlg.cpp +++ b/git/gitLogDlg.cpp @@ -24,6 +24,7 @@ ////////////////////////////////////////////////////////////////////////////// #include "gitLogDlg.h" + #include "windowattrmanager.h" #ifndef __WXMSW__ diff --git a/git/gitSettingsDlg.cpp b/git/gitSettingsDlg.cpp index 1ace334fcd..71d31f3761 100644 --- a/git/gitSettingsDlg.cpp +++ b/git/gitSettingsDlg.cpp @@ -30,7 +30,9 @@ #include "gitentry.h" #include "windowattrmanager.h" -GitSettingsDlg::GitSettingsDlg(wxWindow* parent, const wxString& localRepoPath, const wxString& userEnteredRepoPath, +GitSettingsDlg::GitSettingsDlg(wxWindow* parent, + const wxString& localRepoPath, + const wxString& userEnteredRepoPath, const wxString& projectNameHash) : GitSettingsDlgBase(parent) , m_userEnteredRepoPath(userEnteredRepoPath) @@ -66,14 +68,14 @@ void GitSettingsDlg::OnOK(wxCommandEvent& event) wxString repopath = m_dirPickerGitRepoPath->GetPath(); // Sanity-check the entered path: we don't want /foo/bar/.git/, just /foo/bar - if(repopath.Right(1) == "/") { + if (repopath.Right(1) == "/") { repopath.RemoveLast(); } - if(repopath.Right(5) == "/.git") { + if (repopath.Right(5) == "/.git") { repopath.RemoveLast(5); } - if(!m_projectNameHash.empty() && (repopath != m_userEnteredRepoPath)) { + if (!m_projectNameHash.empty() && (repopath != m_userEnteredRepoPath)) { m_userEnteredRepoPath = repopath; data.SetProjectUserEnteredRepoPath(repopath, m_projectNameHash); data.Save(); @@ -89,13 +91,13 @@ void GitSettingsDlg::OnOK(wxCommandEvent& event) data.SetDifftool(m_choiceDiffTools->GetStringSelection()); // can be an empty string size_t flags = 0; - if(m_checkBoxLog->IsChecked()) + if (m_checkBoxLog->IsChecked()) flags |= GitEntry::VerboseLog; - if(m_checkBoxTerminal->IsChecked()) + if (m_checkBoxTerminal->IsChecked()) flags |= GitEntry::ShowTerminal; - if(m_checkBoxShowBlameInStatusBar->IsChecked()) + if (m_checkBoxShowBlameInStatusBar->IsChecked()) flags |= GitEntry::ShowCommitInfo; data.SetFlags(flags); diff --git a/git/gitSettingsDlg.h b/git/gitSettingsDlg.h index f8c616aaad..5f6df252bc 100644 --- a/git/gitSettingsDlg.h +++ b/git/gitSettingsDlg.h @@ -42,9 +42,12 @@ class GitSettingsDlg : public GitSettingsDlgBase const wxString m_projectNameHash; public: - GitSettingsDlg(wxWindow* parent, const wxString& localRepoPath, const wxString& userEnteredRepoPath, const wxString& projectNameHash); + GitSettingsDlg(wxWindow* parent, + const wxString& localRepoPath, + const wxString& userEnteredRepoPath, + const wxString& projectNameHash); virtual ~GitSettingsDlg() = default; - + const wxString GetNewGitRepoPath() const { return m_userEnteredRepoPath; } protected: diff --git a/git/gitdiffchoosecommitishdlg.cpp b/git/gitdiffchoosecommitishdlg.cpp index 11ffd00d81..a4f49d2d5f 100644 --- a/git/gitdiffchoosecommitishdlg.cpp +++ b/git/gitdiffchoosecommitishdlg.cpp @@ -55,15 +55,15 @@ GitDiffChooseCommitishDlg::GitDiffChooseCommitishDlg(wxWindow* parent, GitPlugin m_selectedRadio1 = data.GetGitDiffChooseDlgRadioSel1(); m_selectedRadio2 = data.GetGitDiffChooseDlgRadioSel2(); - wxRadioButton* radiosL[] = { m_radioBranch1, m_radioTag1, m_radioCommit1, m_radioUserEntered1 }; - wxRadioButton* radiosR[] = { m_radioBranch2, m_radioTag2, m_radioCommit2, m_radioUserEntered2 }; - wxItemContainerImmutable* choicesL[] = { m_choiceBranch1, m_choiceTag1, m_choiceCommit1, m_comboCommitish1 }; - wxItemContainerImmutable* choicesR[] = { m_choiceBranch2, m_choiceTag2, m_choiceCommit2, m_comboCommitish2 }; - if(m_selectedRadio1 > -1 && m_selectedRadio1 < 4) { + wxRadioButton* radiosL[] = {m_radioBranch1, m_radioTag1, m_radioCommit1, m_radioUserEntered1}; + wxRadioButton* radiosR[] = {m_radioBranch2, m_radioTag2, m_radioCommit2, m_radioUserEntered2}; + wxItemContainerImmutable* choicesL[] = {m_choiceBranch1, m_choiceTag1, m_choiceCommit1, m_comboCommitish1}; + wxItemContainerImmutable* choicesR[] = {m_choiceBranch2, m_choiceTag2, m_choiceCommit2, m_comboCommitish2}; + if (m_selectedRadio1 > -1 && m_selectedRadio1 < 4) { radiosL[m_selectedRadio1]->SetValue(1); m_activeChoice1 = choicesL[m_selectedRadio1]; } - if(m_selectedRadio2 > -1 && m_selectedRadio2 < 4) { + if (m_selectedRadio2 > -1 && m_selectedRadio2 < 4) { radiosR[m_selectedRadio2]->SetValue(1); m_activeChoice2 = choicesR[m_selectedRadio2]; } @@ -77,7 +77,8 @@ GitDiffChooseCommitishDlg::GitDiffChooseCommitishDlg(wxWindow* parent, GitPlugin m_choiceBranch1->Set(items); m_choiceBranch1->Set(items); }, - IProcessCreateDefault | IProcessWrapInShell, m_plugin->GetRepositoryPath()); + IProcessCreateDefault | IProcessWrapInShell, + m_plugin->GetRepositoryPath()); m_plugin->AsyncRunGitWithCallback( " --no-pager tag", @@ -86,7 +87,8 @@ GitDiffChooseCommitishDlg::GitDiffChooseCommitishDlg(wxWindow* parent, GitPlugin m_choiceTag1->Set(items); m_choiceTag2->Set(items); }, - IProcessCreateDefault | IProcessWrapInShell, m_plugin->GetRepositoryPath()); + IProcessCreateDefault | IProcessWrapInShell, + m_plugin->GetRepositoryPath()); // Restrict the commits to 1000: filling a wxChoice with many more froze CodeLite for several minutes // and in any case, selecting one particular commit out of hundreds is not easy! @@ -97,26 +99,27 @@ GitDiffChooseCommitishDlg::GitDiffChooseCommitishDlg(wxWindow* parent, GitPlugin m_choiceCommit1->Set(items); m_choiceCommit2->Set(items); }, - IProcessCreateDefault | IProcessWrapInShell, m_plugin->GetRepositoryPath()); + IProcessCreateDefault | IProcessWrapInShell, + m_plugin->GetRepositoryPath()); } GitDiffChooseCommitishDlg::~GitDiffChooseCommitishDlg() { wxArrayString comboCommitish1Strings = m_comboCommitish1->GetStrings(); - if(m_selectedRadio1 == 3) { + if (m_selectedRadio1 == 3) { wxString sel = m_comboCommitish1->GetValue(); - if(!sel.empty()) { - if(comboCommitish1Strings.Index(sel) != wxNOT_FOUND) { + if (!sel.empty()) { + if (comboCommitish1Strings.Index(sel) != wxNOT_FOUND) { comboCommitish1Strings.Remove(sel); } comboCommitish1Strings.Insert(sel, 0); } } wxArrayString comboCommitish2Strings = m_comboCommitish2->GetStrings(); - if(m_selectedRadio1 == 3) { + if (m_selectedRadio1 == 3) { wxString sel = m_comboCommitish2->GetValue(); - if(!sel.empty()) { - if(comboCommitish2Strings.Index(sel) != wxNOT_FOUND) { + if (!sel.empty()) { + if (comboCommitish2Strings.Index(sel) != wxNOT_FOUND) { comboCommitish2Strings.Remove(sel); } comboCommitish2Strings.Insert(sel, 0); @@ -137,9 +140,9 @@ GitDiffChooseCommitishDlg::~GitDiffChooseCommitishDlg() wxString GitDiffChooseCommitishDlg::GetAncestorSetting(wxSpinCtrl* spin) const { wxString setting; - if(spin) { + if (spin) { int value = spin->GetValue(); - if(value > 0) { + if (value > 0) { setting = wxString::Format("~%i", value); } } @@ -204,10 +207,10 @@ void GitDiffChooseCommitishDlg::OnTextFirstUI(wxUpdateUIEvent& event) { wxString text = (m_activeChoice1 == m_comboCommitish1) ? m_comboCommitish1->GetValue() : m_activeChoice1->GetStringSelection(); - if(text.StartsWith("* ")) { + if (text.StartsWith("* ")) { text = text.Mid(2); // Remove the 'active branch' marker } - if(m_activeChoice1 == m_choiceCommit1) { + if (m_activeChoice1 == m_choiceCommit1) { text = text.BeforeFirst(' '); // We want only the commit hash, not the message } @@ -217,10 +220,10 @@ void GitDiffChooseCommitishDlg::OnTextSecondUI(wxUpdateUIEvent& event) { wxString text = (m_activeChoice2 == m_comboCommitish2) ? m_comboCommitish2->GetValue() : m_activeChoice2->GetStringSelection(); - if(text.StartsWith("* ")) { + if (text.StartsWith("* ")) { text = text.Mid(2); // Remove the 'active branch' marker } - if(m_activeChoice2 == m_choiceCommit2) { + if (m_activeChoice2 == m_choiceCommit2) { text = text.BeforeFirst(' '); // We want only the commit hash, not the message } @@ -229,7 +232,7 @@ void GitDiffChooseCommitishDlg::OnTextSecondUI(wxUpdateUIEvent& event) void GitDiffChooseCommitishDlg::OnBranch1Changed(wxCommandEvent& event) { wxString newBranch = m_choiceBranch1->GetString(event.GetInt()); - if(newBranch.StartsWith("* ")) { + if (newBranch.StartsWith("* ")) { newBranch = newBranch.Mid(2); // Remove the 'active branch' marker } m_plugin->AsyncRunGitWithCallback( @@ -238,12 +241,13 @@ void GitDiffChooseCommitishDlg::OnBranch1Changed(wxCommandEvent& event) wxArrayString items = wxStringTokenize(output, "\n", wxTOKEN_STRTOK); m_choiceCommit1->Set(items); }, - IProcessCreateDefault | IProcessWrapInShell, m_plugin->GetRepositoryPath()); + IProcessCreateDefault | IProcessWrapInShell, + m_plugin->GetRepositoryPath()); } void GitDiffChooseCommitishDlg::OnBranch2Changed(wxCommandEvent& event) { wxString newBranch = m_choiceBranch2->GetString(event.GetInt()); - if(newBranch.StartsWith("* ")) { + if (newBranch.StartsWith("* ")) { newBranch = newBranch.Mid(2); // Remove the 'active branch' marker } @@ -253,5 +257,6 @@ void GitDiffChooseCommitishDlg::OnBranch2Changed(wxCommandEvent& event) wxArrayString items = wxStringTokenize(output, "\n", wxTOKEN_STRTOK); m_choiceCommit2->Set(items); }, - IProcessCreateDefault | IProcessWrapInShell, m_plugin->GetRepositoryPath()); + IProcessCreateDefault | IProcessWrapInShell, + m_plugin->GetRepositoryPath()); } diff --git a/git/gitentry.cpp b/git/gitentry.cpp index f1e3384ead..1a54b5e059 100644 --- a/git/gitentry.cpp +++ b/git/gitentry.cpp @@ -293,7 +293,8 @@ void GitEntry::WriteGitProperties(const wxString& localRepoPath, const GitEntry: fpo.Close(); } } else { - ::wxMessageBox("Could not save GIT global configuration. Configuration is unmodified", "git", + ::wxMessageBox("Could not save GIT global configuration. Configuration is unmodified", + "git", wxICON_WARNING | wxOK | wxCENTER); } } @@ -323,7 +324,8 @@ void GitEntry::WriteGitProperties(const wxString& localRepoPath, const GitEntry: fpo.Close(); } } else { - ::wxMessageBox("Could not save GIT local configuration. Configuration is unmodified", "git", + ::wxMessageBox("Could not save GIT local configuration. Configuration is unmodified", + "git", wxICON_WARNING | wxOK | wxCENTER); } }