]> git.saurik.com Git - wxWidgets.git/blob - utils/ifacecheck/src/ifacecheck.cpp
99054195e7d7dddcf7335adf1604867ff0023c01
[wxWidgets.git] / utils / ifacecheck / src / ifacecheck.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: ifacecheck.cpp
3 // Purpose: Interface headers <=> real headers coherence checker
4 // Author: Francesco Montorsi
5 // Created: 2008/03/17
6 // RCS-ID: $Id$
7 // Copyright: (c) 2008 Francesco Montorsi
8 // Licence: wxWindows licence
9 /////////////////////////////////////////////////////////////////////////////
10
11 // For compilers that support precompilation, includes "wx/wx.h".
12 #include "wx/wxprec.h"
13
14 #ifdef __BORLANDC__
15 #pragma hdrstop
16 #endif
17
18 // for all others, include the necessary headers
19 #ifndef WX_PRECOMP
20 #include "wx/app.h"
21 #endif
22
23 #include "wx/cmdline.h"
24 #include "wx/textfile.h"
25 #include "wx/filename.h"
26 #include "wx/stopwatch.h" // for wxGetLocalTime
27 #include "xmlparser.h"
28
29 // global verbosity flag
30 bool g_verbose = false;
31
32
33
34 // ----------------------------------------------------------------------------
35 // IfaceCheckApp
36 // ----------------------------------------------------------------------------
37
38 #define API_DUMP_FILE "dump.api.txt"
39 #define INTERFACE_DUMP_FILE "dump.interface.txt"
40
41 #define PROCESS_ONLY_OPTION "p"
42 #define USE_PREPROCESSOR_OPTION "u"
43
44 #define MODIFY_SWITCH "m"
45 #define DUMP_SWITCH "d"
46 #define HELP_SWITCH "h"
47 #define VERBOSE_SWITCH "v"
48
49 static const wxCmdLineEntryDesc g_cmdLineDesc[] =
50 {
51 { wxCMD_LINE_OPTION, USE_PREPROCESSOR_OPTION, "use-preproc",
52 "uses the preprocessor output to increase the checker accuracy",
53 wxCMD_LINE_VAL_STRING, wxCMD_LINE_NEEDS_SEPARATOR },
54 { wxCMD_LINE_OPTION, PROCESS_ONLY_OPTION, "process-only",
55 "processes only header files matching the given wildcard",
56 wxCMD_LINE_VAL_STRING, wxCMD_LINE_NEEDS_SEPARATOR },
57 { wxCMD_LINE_SWITCH, MODIFY_SWITCH, "modify",
58 "modify the interface headers to match the real ones" },
59 { wxCMD_LINE_SWITCH, DUMP_SWITCH, "dump",
60 "dump both interface and API to plain text dump.*.txt files" },
61 { wxCMD_LINE_SWITCH, HELP_SWITCH, "help",
62 "show help message", wxCMD_LINE_VAL_NONE, wxCMD_LINE_OPTION_HELP },
63 { wxCMD_LINE_SWITCH, VERBOSE_SWITCH, "verbose",
64 "be verbose" },
65 { wxCMD_LINE_PARAM, NULL, NULL,
66 "gccXML", wxCMD_LINE_VAL_STRING, wxCMD_LINE_OPTION_MANDATORY },
67 { wxCMD_LINE_PARAM, NULL, NULL,
68 "doxygenXML", wxCMD_LINE_VAL_STRING, wxCMD_LINE_OPTION_MANDATORY },
69 wxCMD_LINE_DESC_END
70 };
71
72 class IfaceCheckApp : public wxAppConsole
73 {
74 public:
75 // don't use builtin cmd line parsing:
76 virtual bool OnInit() { m_modify=false; return true; }
77 virtual int OnRun();
78
79 bool ParsePreprocessorOutput(const wxString& filename);
80
81 bool Compare();
82 int CompareClasses(const wxClass* iface, const wxClassPtrArray& api);
83 void FixMethod(const wxString& header, const wxMethod* iface, const wxMethod* api);
84
85 void ShowProgress();
86 void PrintStatistics(long secs);
87
88 bool IsToProcess(const wxString& headername) const
89 {
90 if (m_strToMatch.IsEmpty())
91 return true;
92 return wxMatchWild(m_strToMatch, headername, false);
93 }
94
95 protected:
96 wxXmlGccInterface m_gccInterface; // "real" headers API
97 wxXmlDoxygenInterface m_doxyInterface; // doxygen-commented headers API
98
99 // was the MODIFY_SWITCH passed?
100 bool m_modify;
101
102 // if non-empty, then PROCESS_ONLY_OPTION was passed and this is the
103 // wildcard expression to match
104 wxString m_strToMatch;
105 };
106
107 IMPLEMENT_APP_CONSOLE(IfaceCheckApp)
108
109 int IfaceCheckApp::OnRun()
110 {
111 long startTime = wxGetLocalTime(); // for timing purpose
112
113 wxCmdLineParser parser(g_cmdLineDesc, argc, argv);
114 parser.SetLogo(
115 wxString::Format("wxWidgets Interface checker utility (built %s against %s)",
116 __DATE__, wxVERSION_STRING));
117
118 // parse the command line...
119 bool ok = true;
120 wxString preprocFile;
121 switch (parser.Parse())
122 {
123 case 0:
124 if (parser.Found(VERBOSE_SWITCH))
125 g_verbose = true;
126
127 // IMPORTANT: parsing #define values must be done _before_ actually
128 // parsing the GCC/doxygen XML files
129 if (parser.Found(USE_PREPROCESSOR_OPTION, &preprocFile))
130 {
131 if (!ParsePreprocessorOutput(preprocFile))
132 return 1;
133 }
134
135 // in any case set basic std preprocessor #defines:
136 m_doxyInterface.AddPreprocessorValue("NULL", "0");
137
138 // parse the two XML files which contain the real and the doxygen interfaces
139 // for wxWidgets API:
140 if (!m_gccInterface.Parse(parser.GetParam(0)) ||
141 !m_doxyInterface.Parse(parser.GetParam(1)))
142 return 1;
143
144 if (parser.Found(DUMP_SWITCH))
145 {
146 LogMessage("Dumping real API to '%s'...", API_DUMP_FILE);
147 m_gccInterface.Dump(API_DUMP_FILE);
148
149 LogMessage("Dumping interface API to '%s'...", INTERFACE_DUMP_FILE);
150 m_doxyInterface.Dump(INTERFACE_DUMP_FILE);
151 }
152 else
153 {
154 if (parser.Found(MODIFY_SWITCH))
155 m_modify = true;
156
157 if (parser.Found(PROCESS_ONLY_OPTION, &m_strToMatch))
158 {
159 size_t len = m_strToMatch.Len();
160 if (m_strToMatch.StartsWith("\"") &&
161 m_strToMatch.EndsWith("\"") &&
162 len > 2)
163 m_strToMatch = m_strToMatch.Mid(1, len-2);
164 }
165
166 ok = Compare();
167 }
168
169 PrintStatistics(wxGetLocalTime() - startTime);
170 return ok ? 0 : 1;
171
172 default:
173 wxPrintf("\nThis utility checks that the interface XML files created by Doxygen are in\n");
174 wxPrintf("synch with the real headers (whose contents are extracted by the gcc XML file).\n\n");
175 wxPrintf("The 'gccXML' parameter should be the wxapi.xml file created by the 'rungccxml.sh'\n");
176 wxPrintf("script which resides in 'utils/ifacecheck'.\n");
177 wxPrintf("The 'doxygenXML' parameter should be the index.xml file created by Doxygen\n");
178 wxPrintf("for the wxWidgets 'interface' folder.\n\n");
179 wxPrintf("Since the gcc XML file does not contain info about #defines, if you use\n");
180 wxPrintf("the -%s option, you'll get a smaller number of false warnings.\n",
181 USE_PREPROCESSOR_OPTION);
182
183 // HELP_SWITCH was passed or a syntax error occurred
184 return 0;
185 }
186
187 return 1;
188 }
189
190 void IfaceCheckApp::ShowProgress()
191 {
192 wxPrint(".");
193 //fflush(stdout);
194 }
195
196 bool IfaceCheckApp::Compare()
197 {
198 const wxClassArray& interface = m_doxyInterface.GetClasses();
199 const wxClass* c;
200 wxClassPtrArray api;
201 int mcount = 0, ccount = 0;
202
203 LogMessage("Comparing the interface API to the real API (%d classes to compare)...",
204 interface.GetCount());
205
206 if (!m_strToMatch.IsEmpty())
207 LogMessage("Processing only header files matching '%s' expression.", m_strToMatch);
208
209 for (unsigned int i=0; i<interface.GetCount(); i++)
210 {
211 // only compare the methods which are available for the port
212 // for which the gcc XML was produced
213 if (interface[i].GetAvailability() != wxPORT_UNKNOWN &&
214 (interface[i].GetAvailability() & m_gccInterface.GetInterfacePort()) == 0) {
215
216 if (g_verbose)
217 LogMessage("skipping class '%s' since it's not available for the %s port.",
218 interface[i].GetName(), m_gccInterface.GetInterfacePortName());
219
220 continue; // skip this method
221 }
222
223 // shorten the name of the header so the log file is more readable
224 // and also for calling IsToProcess() against it
225 wxString header = wxFileName(interface[i].GetHeader()).GetFullName();
226
227 if (!IsToProcess(header))
228 continue; // skip this one
229
230 wxString cname = interface[i].GetName();
231
232 api.Empty();
233
234 // search in the real headers for i-th interface class; we search for
235 // both class cname and cnameBase since in wxWidgets world tipically
236 // class cname is platform-specific while the real public interface of
237 // that class is part of the cnameBase class.
238 c = m_gccInterface.FindClass(cname);
239 if (c) api.Add(c);
240 c = m_gccInterface.FindClass(cname + "Base");
241 if (c) api.Add(c);
242
243 // sometimes the platform-specific class is named "wxGeneric" + cname
244 // or similar:
245 c = m_gccInterface.FindClass("wxGeneric" + cname.Mid(2));
246 if (c) api.Add(c);
247 c = m_gccInterface.FindClass("wxGtk" + cname.Mid(2));
248 if (c) api.Add(c);
249
250 if (api.GetCount()>0) {
251
252 // there is a class with exactly the same name!
253 mcount += CompareClasses(&interface[i], api);
254
255 } else {
256
257 LogMessage("%s: couldn't find the real interface for the '%s' class",
258 header, cname);
259 ccount++;
260 }
261 }
262
263 LogMessage("%d methods (%.1f%%) of the interface headers do not exist in the real headers",
264 mcount, (float)(100.0 * mcount/m_doxyInterface.GetMethodCount()));
265 LogMessage("%d classes (%.1f%%) of the interface headers do not exist in the real headers",
266 ccount, (float)(100.0 * ccount/m_doxyInterface.GetClassesCount()));
267
268 return true;
269 }
270
271 int IfaceCheckApp::CompareClasses(const wxClass* iface, const wxClassPtrArray& api)
272 {
273 wxString searchedclasses;
274 const wxMethod *real;
275 int count = 0;
276
277 wxASSERT(iface && api.GetCount()>0);
278
279 // build a string with the names of the API classes compared to iface
280 for (unsigned int j=0; j<api.GetCount(); j++)
281 searchedclasses += "/" + api[j]->GetName();
282 searchedclasses.Remove(0, 1);
283
284 // shorten the name of the header so the log file is more readable
285 wxString header = wxFileName(iface->GetHeader()).GetFullName();
286
287 for (unsigned int i=0; i<iface->GetMethodCount(); i++)
288 {
289 const wxMethod& m = iface->GetMethod(i);
290 int matches = 0;
291
292 // only compare the methods which are available for the port
293 // for which the gcc XML was produced
294 if (m.GetAvailability() != wxPORT_UNKNOWN &&
295 (m.GetAvailability() & m_gccInterface.GetInterfacePort()) == 0) {
296
297 if (g_verbose)
298 LogMessage("skipping method '%s' since it's not available for the %s port.",
299 m.GetAsString(), m_gccInterface.GetInterfacePortName());
300
301 continue; // skip this method
302 }
303
304 // search in the methods of the api classes provided
305 for (unsigned int j=0; j<api.GetCount(); j++)
306 {
307 real = api[j]->FindMethod(m);
308 if (real)
309 matches++; // there is a real matching prototype! It's ok!
310 }
311
312 if (matches == 0)
313 {
314 wxMethodPtrArray overloads;
315
316 // try searching for methods with the same name but with
317 // different return type / arguments / qualifiers
318 for (unsigned int j=0; j<api.GetCount(); j++)
319 {
320 wxMethodPtrArray results = api[j]->FindMethodsNamed(m.GetName());
321
322 // append "results" array to "overloads"
323 WX_APPEND_ARRAY(overloads, results);
324 }
325
326 if (overloads.GetCount()==0)
327 {
328 /*
329 TODO: sometimes the interface headers re-document a method
330 inherited from a base class even if the real header does
331 not actually re-implement it.
332 To avoid false positives, we'd need to search in the base classes
333 of api[] classes and search for a matching method.
334 */
335 LogMessage("%s: real '%s' class has no method '%s'",
336 header, searchedclasses, m.GetAsString());
337 // we've found no overloads
338 }
339 else
340 {
341 // first, output a warning
342 wxString warning = header;
343 if (overloads.GetCount()>1)
344 warning += wxString::Format(": in the real headers there are %d overloads of '%s' for "
345 "'%s' all with different signatures:\n",
346 overloads.GetCount(), m.GetName(), searchedclasses);
347 else
348 warning += wxString::Format(": in the real headers there is a method '%s' for '%s'"
349 " but has different signature:\n",
350 m.GetName(), searchedclasses);
351
352 warning += "\tdoxy header: " + m.GetAsString();
353 for (unsigned int j=0; j<overloads.GetCount(); j++)
354 warning += "\n\treal header: " + overloads[j]->GetAsString();
355
356 wxPrint(warning + "\n");
357 count++;
358
359 if (overloads.GetCount()>1)
360 {
361 // TODO: decide which of these overloads is the most "similar" to m
362 // and eventually modify it
363 if (m_modify)
364 wxPrint("\tmanual fix is required\n");
365 }
366 else
367 {
368 wxASSERT(overloads.GetCount() == 1);
369
370 if (m_modify)
371 {
372 wxPrint("\tfixing it...\n");
373
374 // try to modify it!
375 FixMethod(iface->GetHeader(), &m, overloads[0]);
376 }
377 }
378 }
379
380 count++;
381 }
382 }
383
384 return count;
385 }
386
387 void IfaceCheckApp::FixMethod(const wxString& header, const wxMethod* iface, const wxMethod* api)
388 {
389 wxASSERT(iface && api);
390
391 wxTextFile file;
392 if (!file.Open(header)) {
393 LogError("\tcan't open the '%s' header file.", header);
394 return;
395 }
396
397 // GetLocation() returns the line where the last part of the prototype is placed:
398 int end = iface->GetLocation()-1;
399 if (end <= 0 || end >= (int)file.GetLineCount()) {
400 LogWarning("\tinvalid location info for method '%s': %d.",
401 iface->GetAsString(), iface->GetLocation());
402 return;
403 }
404
405 if (!file.GetLine(end).Contains(";")) {
406 LogWarning("\tinvalid location info for method '%s': %d.",
407 iface->GetAsString(), iface->GetLocation());
408 return;
409 }
410
411 // find the start point of this prototype declaration:
412 int start = end-1;
413 bool founddecl = false;
414 while (start > 0 &&
415 !file.GetLine(start).Contains(";") &&
416 !file.GetLine(start).Contains("*/"))
417 {
418 start--;
419
420 founddecl |= file.GetLine(start).Contains(iface->GetName());
421 }
422
423 if (start <= 0 || !founddecl)
424 {
425 LogError("\tcan't find the beginning of the declaration of '%s' method in '%s' header",
426 iface->GetAsString(), header);
427 return;
428 }
429
430 // start-th line contains either the declaration of another prototype
431 // or the closing tag */ of a doxygen comment; start one line below
432 start++;
433
434 // remove the old prototype
435 for (int i=start; i<=end; i++)
436 file.RemoveLine(start); // remove (end-start)-nth times the start-th line
437
438 #define INDENTATION_STR wxString(" ")
439
440 // if possible, add also the @deprecated tag in the doxygen comment if it's missing
441 int deprecationOffset = 0;
442 if (file.GetLine(start-1).Contains("*/") &&
443 (api->IsDeprecated() && !iface->IsDeprecated()))
444 {
445 file.RemoveLine(start-1);
446 file.InsertLine(INDENTATION_STR + INDENTATION_STR +
447 "@deprecated @todo provide deprecation description", start-1);
448 file.InsertLine(INDENTATION_STR + "*/", start++);
449
450 // we have added a new line in the final balance
451 deprecationOffset=1;
452 }
453
454 wxMethod tmp(*api);
455
456 // discard API argument names and replace them with those parsed from doxygen XML:
457 const wxArgumentTypeArray& doxygenargs = iface->GetArgumentTypes();
458 const wxArgumentTypeArray& realargs = api->GetArgumentTypes();
459 if (realargs.GetCount() == doxygenargs.GetCount())
460 {
461 for (unsigned int j=0; j<doxygenargs.GetCount(); j++)
462 if (doxygenargs[j]==realargs[j])
463 realargs[j].SetArgumentName(doxygenargs[j].GetArgumentName());
464
465 tmp.SetArgumentTypes(realargs);
466 }
467
468 #define WRAP_COLUMN 80
469
470 wxArrayString toinsert;
471 toinsert.Add(INDENTATION_STR + tmp.GetAsString() + ";");
472
473 int nStartColumn = toinsert[0].Find('(');
474 wxASSERT(nStartColumn != wxNOT_FOUND);
475
476 // wrap lines too long at comma boundaries
477 for (unsigned int i=0; i<toinsert.GetCount(); i++)
478 {
479 size_t len = toinsert[i].Len();
480 if (len > WRAP_COLUMN)
481 {
482 wxASSERT(i == toinsert.GetCount()-1);
483
484 // break this line
485 wxString tmpleft = toinsert[i].Left(WRAP_COLUMN);
486 int comma = tmpleft.Find(',', true /* from end */);
487 if (comma == wxNOT_FOUND)
488 break; // break out of the for cycle...
489
490 toinsert.Add(wxString(' ', nStartColumn+1) +
491 toinsert[i].Right(len-comma-2)); // exclude the comma and the space after it
492 toinsert[i] = tmpleft.Left(comma+1); // include the comma
493 }
494 }
495
496 // insert the new lines
497 for (unsigned int i=0; i<toinsert.GetCount(); i++)
498 file.InsertLine(toinsert[i], start+i);
499
500 // now save the modification
501 if (!file.Write()) {
502 LogError("\tcan't save the '%s' header file.", header);
503 return;
504 }
505
506 // how many lines did we add/remove in total?
507 int nOffset = toinsert.GetCount() + deprecationOffset - (end-start+1);
508 if (nOffset == 0)
509 return;
510
511 if (g_verbose)
512 LogMessage("\tthe final row offset for following methods is %d lines.", nOffset);
513
514 // update the other method's locations for those methods which belong to the modified header
515 // and are placed _below_ the modified method
516 wxClassPtrArray cToUpdate = m_doxyInterface.FindClassesDefinedIn(header);
517 for (unsigned int i=0; i < cToUpdate.GetCount(); i++)
518 {
519 for (unsigned int j=0; j < cToUpdate[i]->GetMethodCount(); j++)
520 {
521 wxMethod& m = cToUpdate[i]->GetMethod(j);
522 if (m.GetLocation() > iface->GetLocation())
523 {
524 // update the location of this method
525 m.SetLocation(m.GetLocation()+nOffset);
526 }
527 }
528 }
529 }
530
531 bool IfaceCheckApp::ParsePreprocessorOutput(const wxString& filename)
532 {
533 wxTextFile tf;
534 if (!tf.Open(filename)) {
535 LogError("can't open the '%s' preprocessor output file.", filename);
536 return false;
537 }
538
539 size_t useful = 0;
540 for (unsigned int i=0; i < tf.GetLineCount(); i++)
541 {
542 const wxString& line = tf.GetLine(i);
543 wxString defnameval = line.Mid(8); // what follows the "#define " string
544
545 // the format of this line should be:
546 // #define DEFNAME DEFVALUE
547 if (!line.StartsWith("#define ")) {
548 LogError("unexpected content in '%s' at line %d.", filename, i+1);
549 return false;
550 }
551
552 if (defnameval.Contains(" "))
553 {
554 // get DEFNAME
555 wxString defname = defnameval.BeforeFirst(' ');
556 if (defname.Contains("("))
557 continue; // this is a macro, skip it!
558
559 // get DEFVAL
560 wxString defval = defnameval.AfterFirst(' ').Strip(wxString::both);
561 if (defval.StartsWith("(") && defval.EndsWith(")"))
562 defval = defval.Mid(1, defval.Len()-2);
563
564 // store this pair in the doxygen interface, where it can be useful
565 m_doxyInterface.AddPreprocessorValue(defname, defval);
566 useful++;
567 }
568 else
569 {
570 // it looks like the format of this line is:
571 // #define DEFNAME
572 // we are not interested to symbols #defined to nothing,
573 // so we just ignore this line.
574 }
575 }
576
577 LogMessage("Parsed %d preprocessor #defines from '%s' which will be used later...",
578 useful, filename);
579
580 return true;
581 }
582
583 void IfaceCheckApp::PrintStatistics(long secs)
584 {
585 LogMessage("wx real headers contains declaration of %d classes (%d methods)",
586 m_gccInterface.GetClassesCount(), m_gccInterface.GetMethodCount());
587 LogMessage("wx interface headers contains declaration of %d classes (%d methods)",
588 m_doxyInterface.GetClassesCount(), m_doxyInterface.GetMethodCount());
589 LogMessage("total processing took %d seconds.", secs);
590 }
591