Debian Codegraph @

CodeLite/PHPLookupTable.h

raw
1 //////////////////////////////////////////////////////////////////////////////
2 //////////////////////////////////////////////////////////////////////////////
3 //
4 // Copyright : (C) 2015 Eran Ifrah
5 // File name : PHPLookupTable.h
6 //
7 // -------------------------------------------------------------------------
8 // A
9 // _____ _ _ _ _
10 // / __ \ | | | | (_) |
11 // | / \/ ___ __| | ___| | _| |_ ___
12 // | | / _ \ / _ |/ _ \ | | | __/ _ )
13 // | \__/\ (_) | (_| | __/ |___| | || __/
14 // \____/\___/ \__,_|\___\_____/_|\__\___|
15 //
16 // F i l e
17 //
18 // This program is free software; you can redistribute it and/or modify
19 // it under the terms of the GNU General Public License as published by
20 // the Free Software Foundation; either version 2 of the License, or
21 // (at your option) any later version.
22 //
23 //////////////////////////////////////////////////////////////////////////////
24 //////////////////////////////////////////////////////////////////////////////
25
26 #ifndef PHPLOOKUPTABLE_H
27 #define PHPLOOKUPTABLE_H
28
29 #include "PHPEntityBase.h"
30 #include "PHPSourceFile.h"
31 #include "cl_command_event.h"
32 #include "codelite_exports.h"
33 #include "event_notifier.h"
34 #include "file_logger.h"
35 #include "fileextmanager.h"
36 #include "fileutils.h"
37 #include "smart_ptr.h"
38 #include "wx/wxsqlite3.h"
39
40 #include <set>
41 #include <unordered_set>
42 #include <vector>
43 #include <wx/longlong.h>
44 #include <wx/stopwatch.h>
45 #include <wx/string.h>
46 #include <wxStringHash.h>
47
48 wxDECLARE_EXPORTED_EVENT(WXDLLIMPEXP_CL, wxPHP_PARSE_STARTED, clParseEvent);
49 wxDECLARE_EXPORTED_EVENT(WXDLLIMPEXP_CL, wxPHP_PARSE_ENDED, clParseEvent);
50 wxDECLARE_EXPORTED_EVENT(WXDLLIMPEXP_CL, wxPHP_PARSE_PROGRESS, clParseEvent);
51
52 enum ePhpScopeType {
53 kPhpScopeTypeAny = -1,
54 kPhpScopeTypeNamespace = 0,
55 kPhpScopeTypeClass = 1,
56 };
57
58 /**
59 * @class PHPLookupTable
60 * @brief a database lookup class which allows a quick access
61 * to all entities parsed in the workspace
62 */
63 class WXDLLIMPEXP_CL PHPLookupTable
64 {
65 wxSQLite3Database m_db;
66 wxFileName m_filename;
67 size_t m_sizeLimit;
68 std::unordered_set<wxString> m_allClasses;
69
70 public:
71 enum eLookupFlags {
72 kLookupFlags_None = 0,
73 kLookupFlags_ExactMatch = (1 << 1),
74 kLookupFlags_Contains = (1 << 2),
75 kLookupFlags_StartsWith = (1 << 3),
76 kLookupFlags_Members = (1 << 4), // Class members
77 kLookupFlags_Constants = (1 << 5), // 'const'
78 kLookupFlags_Static = (1 << 6), // include static members/functions (static::, class_type::)
79 kLookupFlags_Self = (1 << 7), // self::
80 kLookupFlags_NameHintIsScope = (1 << 8), // the namehint provided is of a class name. When enabled, the search
81 // will try to take "\" into consideration
82 kLookupFlags_Parent = (1 << 9), // Exclude 'this' from the results and return only
83 // its parents parent::
84 kLookupFlags_FunctionsAndConstsOnly = (1 << 10), // Fetch functions and consts ONLY
85 kLookupFlags_IncludeAbstractMethods = (1 << 11), // Include abstract functions in the result set
86 };
87
88 enum eUpdateMode {
89 kUpdateMode_Fast,
90 kUpdateMode_Full,
91 };
92 typedef SmartPtr<PHPLookupTable> Ptr_t;
93 static void DoSplitFullname(const wxString& fullname, wxString& ns, wxString& shortName);
94
95 private:
96 void EnsureIntegrity(const wxFileName& filename);
97 void DoAddNameFilter(wxString& sql, const wxString& nameHint, size_t flags);
98
99 void CreateSchema();
100 PHPEntityBase::Ptr_t DoFindMemberOf(wxLongLong parentDbId, const wxString& exactName,
101 bool parentIsNamespace = false);
102
103 void DoFixVarsDocComment(PHPEntityBase::List_t& matches, wxLongLong parentId);
104 void DoGetInheritanceParentIDs(PHPEntityBase::Ptr_t cls, std::vector<wxLongLong>& parents,
105 std::set<wxLongLong>& parentsVisited, bool excludeSelf);
106
107 /**
108 * @brief find namespace by fullname. If it does not exist, add it and return a pointer to it
109 */
110 PHPEntityBase::Ptr_t CreateNamespaceForDefine(PHPEntityBase::Ptr_t define);
111
112 PHPEntityBase::Ptr_t DoFindScope(const wxString& fullname, ePhpScopeType scopeType = kPhpScopeTypeAny);
113 PHPEntityBase::Ptr_t DoFindScope(wxLongLong id, ePhpScopeType scopeType = kPhpScopeTypeAny);
114 /**
115 * @brief sqlite uses '_' as a wildcard. escape it using '^'
116 * as our escape char
117 */
118 wxString EscapeWildCards(const wxString& str);
119
120 void DoAddLimit(wxString& sql);
121
122 /**
123 * @brief allocate new entity that matches the table name
124 */
125 PHPEntityBase::Ptr_t NewEntity(const wxString& tableName, ePhpScopeType scopeType = kPhpScopeTypeAny);
126
127 /**
128 * @brief load entities from table and name hint
129 * if nameHint is empty, return empty list
130 */
131 void LoadFromTableByNameHint(PHPEntityBase::List_t& matches, const wxString& tableName, const wxString& nameHint,
132 eLookupFlags flags);
133
134 /**
135 * @brief use typed: static::
136 */
137 bool CollectingStatics(size_t flags) const { return (flags & kLookupFlags_Static) || (flags & kLookupFlags_Self); }
138
139 /**
140 * @brief return children of parentId _WITHOUT_ taking inheritance into consideration
141 */
142 void DoFindChildren(PHPEntityBase::List_t& matches, wxLongLong parentId, size_t flags = kLookupFlags_None,
143 const wxString& nameHint = "");
144
145 /**
146 * @brief return the timestamp of the last parse for 'filename'
147 */
148 wxLongLong GetFileLastParsedTimestamp(const wxFileName& filename);
149
150 /**
151 * @brief update the file's last updated timestamp
152 */
153 void UpdateFileLastParsedTimestamp(const wxFileName& filename);
154
155 /**
156 * @brief check the database disk image to see if it corrupted
157 */
158 bool CheckDiskImage(wxSQLite3Database& db, const wxFileName& filename);
159
160 public:
161 PHPLookupTable();
162 virtual ~PHPLookupTable();
163
164 /**
165 * @brief rebuild the class cache
166 */
167 void RebuildClassCache();
168 /**
169 * @brief return the function closest to a given function and line number
170 */
171 PHPEntityBase::Ptr_t FindFunctionNearLine(const wxFileName& filename, int lineNumber);
172
173 /**
174 * @brief add class name to the class cache
175 * @param classname
176 */
177 void UpdateClassCache(const wxString& classname);
178
179 /**
180 * @brief check if a class exists in the cache
181 */
182 bool ClassExists(const wxString& classname) const;
183
184 void SetSizeLimit(size_t sizeLimit) { this->m_sizeLimit = sizeLimit; }
185 /**
186 * @brief return the entity at a given file/line
187 */
188 PHPEntityBase::Ptr_t FindFunctionByLineAndFile(const wxFileName& filename, int line);
189
190 /**
191 * @brief return list of functiosn from a given file
192 */
193 size_t FindFunctionsByFile(const wxFileName& filename, PHPEntityBase::List_t& functions);
194
195 /**
196 * @brief open the lookup table database
197 */
198 void Open(const wxString& workspacePath);
199
200 /**
201 * @brief open the symbols database
202 */
203 void Open(const wxFileName& dbfile);
204
205 /**
206 * @brief
207 * @return
208 */
209 bool IsOpened() const;
210
211 /**
212 * @brief close the lookup table database
213 */
214 void Close();
215
216 /**
217 * @brief delete the symbols database file from the file system and recreate an empty one
218 */
219 void ResetDatabase();
220
221 /**
222 * @brief clear all cached data from the database
223 */
224 void ClearAll(bool autoCommit = true);
225
226 /**
227 * @brief find a scope symbol (class or namespace) by its fullname
228 */
229 PHPEntityBase::Ptr_t FindScope(const wxString& fullname);
230
231 /**
232 * @brief find a function by its fullname (scope+name)
233 */
234 PHPEntityBase::Ptr_t FindFunction(const wxString& fullname);
235
236 /**
237 * @brief find a class with a given name
238 */
239 PHPEntityBase::Ptr_t FindClass(const wxString& fullname);
240
241 /**
242 * @brief find a class with a given database ID
243 */
244 PHPEntityBase::Ptr_t FindClass(wxLongLong id);
245
246 /**
247 * @brief find a member of parentDbId with name that matches 'exactName'
248 */
249 PHPEntityBase::Ptr_t FindMemberOf(wxLongLong parentDbId, const wxString& exactName, size_t flags = 0);
250
251 /**
252 * @brief find children of a scope by its database ID.
253 */
254 PHPEntityBase::List_t FindChildren(wxLongLong parentId, size_t flags = kLookupFlags_None,
255 const wxString& nameHint = "");
256
257 /**
258 * @brief find list of symbols with a given name (regardless of the type / scope)
259 * a "free style" search
260 */
261 PHPEntityBase::List_t FindSymbol(const wxString& name);
262
263 /**
264 * @brief load the global functions and consts that matches nameHint
265 * If nameHint is empty, return an empty list
266 */
267 PHPEntityBase::List_t FindGlobalFunctionAndConsts(size_t flags = PHPLookupTable::kLookupFlags_Contains,
268 const wxString& nameHint = "");
269
270 /**
271 * @brief load list of namespaces from the database that
272 */
273 PHPEntityBase::List_t FindNamespaces(const wxString& fullnameStartsWith, const wxString& shortNameContains = "");
274 /**
275 * @brief load list of entities from all the tables that matches 'nameHint'
276 * if nameHint is empty, return an empty list
277 */
278 void LoadAllByFilter(PHPEntityBase::List_t& matches, const wxString& nameHint,
279 eLookupFlags flags = kLookupFlags_Contains);
280 /**
281 * @brief save source file into the database
282 */
283 void UpdateSourceFile(PHPSourceFile& source, bool autoCommit = true);
284
285 /**
286 * @brief update list of source files
287 */
288 template <typename GoindDownFunc>
289 void RecreateSymbolsDatabase(const wxArrayString& files, eUpdateMode updateMode, GoindDownFunc pFuncGoingDown,
290 bool parseFuncBodies = true);
291
292 /**
293 * @brief parse folder
294 */
295 void ParseFolder(const wxString& folder, const wxString& filemask, eUpdateMode updateMode);
296
297 /**
298 * @brief delete all entries belonged to filename.
299 * @param filename the file name
300 * @param autoCommit when true, issue a begin/commit transcation commands
301 */
302 void DeleteFileEntries(const wxFileName& filename, bool autoCommit = true);
303
304 /**
305 * @brief load function arguments from the database
306 * @param parentId the function database ID
307 */
308 PHPEntityBase::List_t LoadFunctionArguments(wxLongLong parentId);
309
310 /**
311 * @brief return reference to the underlying database
312 */
313 wxSQLite3Database& Database() { return m_db; }
314 };
315
316 template <typename GoindDownFunc>
317 void PHPLookupTable::RecreateSymbolsDatabase(const wxArrayString& files, eUpdateMode updateMode,
318 GoindDownFunc pFuncGoingDown, bool parseFuncBodies)
319 {
320 try {
321
322 {
323 clParseEvent event(wxPHP_PARSE_STARTED);
324 event.SetTotalFiles(files.GetCount());
325 event.SetCurfileIndex(0);
326 EventNotifier::Get()->AddPendingEvent(event);
327 }
328
329 wxStopWatch sw;
330 sw.Start();
331
332 m_allClasses.clear(); // clear the cache
333 m_db.Begin();
334 for(size_t i = 0; i < files.GetCount(); ++i) {
335 if(pFuncGoingDown()) {
336 break;
337 }
338 {
339 clParseEvent event(wxPHP_PARSE_PROGRESS);
340 event.SetTotalFiles(files.GetCount());
341 event.SetCurfileIndex(i);
342 event.SetFileName(files.Item(i));
343 EventNotifier::Get()->AddPendingEvent(event);
344 }
345
346 wxFileName fnFile(files.Item(i));
347 bool reParseNeeded(true);
348
349 if(updateMode == kUpdateMode_Fast) {
350 // Check to see if we need to re-parse this file
351 // and store it to the database
352
353 if(!fnFile.Exists()) {
354 reParseNeeded = false;
355 } else {
356 time_t lastModifiedOnDisk = fnFile.GetModificationTime().GetTicks();
357 wxLongLong lastModifiedInDB = GetFileLastParsedTimestamp(fnFile);
358 if(lastModifiedOnDisk <= lastModifiedInDB.ToLong()) {
359 reParseNeeded = false;
360 }
361 }
362 }
363
364 // Ensure that the file exists
365 if(!fnFile.Exists()) {
366 reParseNeeded = false;
367 }
368
369 // Parse only valid PHP files
370 if(FileExtManager::GetType(fnFile.GetFullName()) != FileExtManager::TypePhp) {
371 reParseNeeded = false;
372 }
373
374 if(reParseNeeded) {
375 // For performance reaons, load the file into memory and then parse it
376 wxFileName fnSourceFile(files.Item(i));
377 wxString content;
378 if(!FileUtils::ReadFileContent(fnSourceFile, content, wxConvISO8859_1)) {
379 clWARNING() << "PHP: Failed to read file:" << fnSourceFile << "for parsing" << clEndl;
380 continue;
381 }
382 PHPSourceFile sourceFile(content, this);
383 sourceFile.SetFilename(fnSourceFile);
384 sourceFile.SetParseFunctionBody(parseFuncBodies);
385 sourceFile.Parse();
386 UpdateSourceFile(sourceFile, false);
387 }
388 }
389 m_db.Commit();
390 long elapsedMs = sw.Time();
391
392 LOG_IF_TRACE
393 {
394 clDEBUG1() << _("PHP: parsed ") << files.GetCount() << " in " << elapsedMs << " milliseconds" << clEndl;
395 }
396
397 {
398 clParseEvent event(wxPHP_PARSE_ENDED);
399 event.SetTotalFiles(files.GetCount());
400 event.SetCurfileIndex(files.GetCount());
401 EventNotifier::Get()->AddPendingEvent(event);
402 }
403
404 } catch(wxSQLite3Exception& e) {
405 try {
406 m_db.Rollback();
407
408 } catch(...) {
409 }
410
411 {
412 // always make sure that the end event is sent
413 clParseEvent event(wxPHP_PARSE_ENDED);
414 event.SetTotalFiles(files.GetCount());
415 event.SetCurfileIndex(files.GetCount());
416 EventNotifier::Get()->AddPendingEvent(event);
417 }
418
419 clWARNING() << "PHPLookupTable::UpdateSourceFiles:" << e.GetMessage() << clEndl;
420 }
421 }
422
423 #endif // PHPLOOKUPTABLE_H