]> git.saurik.com Git - wxWidgets.git/blob - utils/ifacecheck/src/ifacecheck.cpp
5e03123d2581574a6cc537aa470ab3fd350beff0
[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 bool 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 //g_bLogEnabled = false;
139
140 // parse the two XML files which contain the real and the doxygen interfaces
141 // for wxWidgets API:
142 if (!m_gccInterface.Parse(parser.GetParam(0)) ||
143 !m_doxyInterface.Parse(parser.GetParam(1)))
144 return 1;
145
146 g_bLogEnabled = true;
147
148 if (parser.Found(DUMP_SWITCH))
149 {
150 LogMessage("Dumping real API to '%s'...", API_DUMP_FILE);
151 m_gccInterface.Dump(API_DUMP_FILE);
152
153 LogMessage("Dumping interface API to '%s'...", INTERFACE_DUMP_FILE);
154 m_doxyInterface.Dump(INTERFACE_DUMP_FILE);
155 }
156 else
157 {
158 if (parser.Found(MODIFY_SWITCH))
159 m_modify = true;
160
161 if (parser.Found(PROCESS_ONLY_OPTION, &m_strToMatch))
162 {
163 size_t len = m_strToMatch.Len();
164 if (m_strToMatch.StartsWith("\"") &&
165 m_strToMatch.EndsWith("\"") &&
166 len > 2)
167 m_strToMatch = m_strToMatch.Mid(1, len-2);
168 }
169
170
171 ok = Compare();
172 }
173
174 PrintStatistics(wxGetLocalTime() - startTime);
175 return ok ? 0 : 1;
176
177 default:
178 wxPrintf("\nThis utility checks that the interface XML files created by Doxygen are in\n");
179 wxPrintf("synch with the real headers (whose contents are extracted by the gcc XML file).\n\n");
180 wxPrintf("The 'gccXML' parameter should be the wxapi.xml file created by the 'rungccxml.sh'\n");
181 wxPrintf("script which resides in 'utils/ifacecheck'.\n");
182 wxPrintf("The 'doxygenXML' parameter should be the index.xml file created by Doxygen\n");
183 wxPrintf("for the wxWidgets 'interface' folder.\n\n");
184 wxPrintf("Since the gcc XML file does not contain info about #defines, if you use\n");
185 wxPrintf("the -%s option, you'll get a smaller number of false warnings.\n",
186 USE_PREPROCESSOR_OPTION);
187
188 // HELP_SWITCH was passed or a syntax error occurred
189 return 0;
190 }
191 }
192
193 void IfaceCheckApp::ShowProgress()
194 {
195 wxPrint(".");
196 //fflush(stdout);
197 }
198
199 bool IfaceCheckApp::Compare()
200 {
201 const wxClassArray& interfaces = m_doxyInterface.GetClasses();
202 const wxClass* c;
203 wxClassPtrArray api;
204 int mcount = 0, ccount = 0;
205
206 LogMessage("Comparing the interface API to the real API (%d classes to compare)...",
207 interfaces.GetCount());
208
209 if (!m_strToMatch.IsEmpty())
210 LogMessage("Processing only header files matching '%s' expression.", m_strToMatch);
211
212 for (unsigned int i=0; i<interfaces.GetCount(); i++)
213 {
214 // only compare the methods which are available for the port
215 // for which the gcc XML was produced
216 if (interfaces[i].GetAvailability() != wxPORT_UNKNOWN &&
217 (interfaces[i].GetAvailability() & m_gccInterface.GetInterfacePort()) == 0) {
218
219 if (g_verbose)
220 LogMessage("skipping class '%s' since it's not available for the %s port.",
221 interfaces[i].GetName(), m_gccInterface.GetInterfacePortName());
222
223 continue; // skip this method
224 }
225
226 // shorten the name of the header so the log file is more readable
227 // and also for calling IsToProcess() against it
228 wxString header = wxFileName(interfaces[i].GetHeader()).GetFullName();
229
230 if (!IsToProcess(header))
231 continue; // skip this one
232
233 wxString cname = interfaces[i].GetName();
234
235 api.Empty();
236
237 // search in the real headers for i-th interface class; we search for
238 // both class cname and cnameBase since in wxWidgets world tipically
239 // class cname is platform-specific while the real public interface of
240 // that class is part of the cnameBase class.
241 c = m_gccInterface.FindClass(cname);
242 if (c) api.Add(c);
243 c = m_gccInterface.FindClass(cname + "Base");
244 if (c) api.Add(c);
245
246 // sometimes the platform-specific class is named "wxGeneric" + cname
247 // or similar:
248 c = m_gccInterface.FindClass("wxGeneric" + cname.Mid(2));
249 if (c) api.Add(c);
250 c = m_gccInterface.FindClass("wxGtk" + cname.Mid(2));
251 if (c) api.Add(c);
252
253 if (api.GetCount()>0) {
254
255 // there is a class with exactly the same name!
256 mcount += CompareClasses(&interfaces[i], api);
257
258 } else {
259
260 LogMessage("%s: couldn't find the real interface for the '%s' class",
261 header, cname);
262 ccount++;
263 }
264 }
265
266 LogMessage("%d methods (%.1f%%) of the interface headers do not exist in the real headers",
267 mcount, (float)(100.0 * mcount/m_doxyInterface.GetMethodCount()));
268 LogMessage("%d classes (%.1f%%) of the interface headers do not exist in the real headers",
269 ccount, (float)(100.0 * ccount/m_doxyInterface.GetClassesCount()));
270
271 return true;
272 }
273
274 int IfaceCheckApp::CompareClasses(const wxClass* iface, const wxClassPtrArray& api)
275 {
276 wxString searchedclasses;
277 const wxMethod *real;
278 int count = 0;
279
280 wxASSERT(iface && api.GetCount()>0);
281
282 // build a string with the names of the API classes compared to iface
283 for (unsigned int j=0; j<api.GetCount(); j++)
284 searchedclasses += "/" + api[j]->GetName();
285 searchedclasses.Remove(0, 1);
286
287 // shorten the name of the header so the log file is more readable
288 wxString header = wxFileName(iface->GetHeader()).GetFullName();
289
290 for (unsigned int i=0; i<iface->GetMethodCount(); i++)
291 {
292 const wxMethod& m = iface->GetMethod(i);
293 int matches = 0;
294
295 // only compare the methods which are available for the port
296 // for which the gcc XML was produced
297 if (m.GetAvailability() != wxPORT_UNKNOWN &&
298 (m.GetAvailability() & m_gccInterface.GetInterfacePort()) == 0) {
299
300 if (g_verbose)
301 LogMessage("skipping method '%s' since it's not available for the %s port.",
302 m.GetAsString(), m_gccInterface.GetInterfacePortName());
303
304 continue; // skip this method
305 }
306
307 // search in the methods of the api classes provided
308 for (unsigned int j=0; j<api.GetCount(); j++)
309 {
310 real = api[j]->FindMethod(m);
311 if (real)
312 matches++; // there is a real matching prototype! It's ok!
313 }
314
315 if (matches == 0)
316 {
317 bool exit = false;
318 wxMethodPtrArray overloads;
319
320 // try searching for methods with the same name but with
321 // different return type / arguments / qualifiers
322 for (unsigned int j=0; j<api.GetCount(); j++)
323 {
324 wxMethodPtrArray results = api[j]->FindMethodsNamed(m.GetName());
325
326 // append "results" array to "overloads"
327 WX_APPEND_ARRAY(overloads, results);
328
329
330 #define HACK_TO_AUTO_CORRECT_ONLY_METHOD_ATTRIBUTES 0
331 #if HACK_TO_AUTO_CORRECT_ONLY_METHOD_ATTRIBUTES
332 for (unsigned int k=0; k<results.GetCount(); k++)
333 if (results[k]->MatchesExceptForAttributes(m) &&
334 results[k]->IsPureVirtual() == m.IsPureVirtual())
335 {
336 // fix default values of results[k]:
337 wxMethod tmp(*results[k]);
338 tmp.SetArgumentTypes(m.GetArgumentTypes());
339
340 // modify interface header
341 if (FixMethod(iface->GetHeader(), &m, &tmp))
342 LogMessage("Adjusted attributes of '%s' method", m.GetAsString());
343
344 exit = true;
345 break;
346 }
347
348 if (exit)
349 break;
350 #endif
351 }
352
353 #if HACK_TO_AUTO_CORRECT_ONLY_METHOD_ATTRIBUTES
354 if (!exit)
355 {
356 #endif
357
358 if (overloads.GetCount()==0)
359 {
360 /*
361 TODO: sometimes the interface headers re-document a method
362 inherited from a base class even if the real header does
363 not actually re-implement it.
364 To avoid false positives, we'd need to search in the base classes
365 of api[] classes and search for a matching method.
366 */
367 LogMessage("%s: real '%s' class has no method '%s'",
368 header, searchedclasses, m.GetAsString());
369 // we've found no overloads
370 }
371 else
372 {
373 // first, output a warning
374 wxString warning = header;
375 if (overloads.GetCount()>1)
376 warning += wxString::Format(": in the real headers there are %d overloads of '%s' for "
377 "'%s' all with different signatures:\n",
378 overloads.GetCount(), m.GetName(), searchedclasses);
379 else
380 warning += wxString::Format(": in the real headers there is a method '%s' for '%s'"
381 " but has different signature:\n",
382 m.GetName(), searchedclasses);
383
384 // get a list of the prototypes with _all_ possible attributes:
385 warning += "\tdoxy header: " + m.GetAsString(true, true, true, true);
386 for (unsigned int j=0; j<overloads.GetCount(); j++)
387 warning += "\n\treal header: " + overloads[j]->GetAsString(true, true, true, true);
388
389 wxPrint(warning + "\n");
390 count++;
391
392 if (overloads.GetCount()>1)
393 {
394 // TODO: decide which of these overloads is the most "similar" to m
395 // and eventually modify it
396 if (m_modify)
397 wxPrint("\tmanual fix is required\n");
398 }
399 else
400 {
401 wxASSERT(overloads.GetCount() == 1);
402
403 if (m_modify)
404 {
405 wxPrint("\tfixing it...\n");
406
407 // try to modify it!
408 FixMethod(iface->GetHeader(), &m, overloads[0]);
409 }
410 }
411 }
412
413 count++;
414
415 #if HACK_TO_AUTO_CORRECT_ONLY_METHOD_ATTRIBUTES
416 }
417 #endif
418 }
419 }
420
421 return count;
422 }
423
424 bool IfaceCheckApp::FixMethod(const wxString& header, const wxMethod* iface, const wxMethod* api)
425 {
426 wxASSERT(iface && api);
427
428 wxTextFile file;
429 if (!file.Open(header)) {
430 LogError("\tcan't open the '%s' header file.", header);
431 return false;
432 }
433
434 // GetLocation() returns the line where the last part of the prototype is placed:
435 int end = iface->GetLocation()-1;
436 if (end <= 0 || end >= (int)file.GetLineCount()) {
437 LogWarning("\tinvalid location info for method '%s': %d.",
438 iface->GetAsString(), iface->GetLocation());
439 return false;
440 }
441
442 if (!file.GetLine(end).Contains(";")) {
443 LogWarning("\tinvalid location info for method '%s': %d.",
444 iface->GetAsString(), iface->GetLocation());
445 return false;
446 }
447
448 // is this a one-line prototype declaration?
449 bool founddecl = false;
450 int start;
451 if (file.GetLine(end).Contains(iface->GetName()))
452 {
453 // yes, this prototype is all on this line:
454 start = end;
455 founddecl = true;
456 }
457 else
458 {
459 start = end-1;
460
461 // find the start point of this prototype declaration:
462 while (start > 0 &&
463 !file.GetLine(start).Contains(";") &&
464 !file.GetLine(start).Contains("*/"))
465 {
466 start--;
467
468 founddecl |= file.GetLine(start).Contains(iface->GetName());
469 }
470
471 // start-th line contains either the declaration of another prototype
472 // or the closing tag */ of a doxygen comment; start one line below
473 start++;
474 }
475
476 if (start <= 0 || !founddecl)
477 {
478 LogError("\tcan't find the beginning of the declaration of '%s' method in '%s' header looking backwards from line %d",
479 iface->GetAsString(), header, end);
480 return false;
481 }
482
483 // remove the old prototype
484 for (int i=start; i<=end; i++)
485 file.RemoveLine(start); // remove (end-start)-nth times the start-th line
486
487 #define INDENTATION_STR wxString(" ")
488
489 // if possible, add also the @deprecated tag in the doxygen comment if it's missing
490 int deprecationOffset = 0;
491 if (file.GetLine(start-1).Contains("*/") &&
492 (api->IsDeprecated() && !iface->IsDeprecated()))
493 {
494 file.RemoveLine(start-1);
495 file.InsertLine(INDENTATION_STR + INDENTATION_STR +
496 "@deprecated @todo provide deprecation description", start-1);
497 file.InsertLine(INDENTATION_STR + "*/", start++);
498
499 // we have added a new line in the final balance
500 deprecationOffset=1;
501 }
502
503 wxMethod tmp(*api);
504
505 // discard API argument names and replace them with those parsed from doxygen XML:
506 const wxArgumentTypeArray& doxygenargs = iface->GetArgumentTypes();
507 const wxArgumentTypeArray& realargs = api->GetArgumentTypes();
508 if (realargs.GetCount() == doxygenargs.GetCount())
509 {
510 for (unsigned int j=0; j<doxygenargs.GetCount(); j++)
511 if (doxygenargs[j]==realargs[j])
512 realargs[j].SetArgumentName(doxygenargs[j].GetArgumentName());
513
514 tmp.SetArgumentTypes(realargs);
515 }
516
517 #define WRAP_COLUMN 80
518
519 wxArrayString toinsert;
520 toinsert.Add(INDENTATION_STR + tmp.GetAsString() + ";");
521
522 int nStartColumn = toinsert[0].Find('(');
523 wxASSERT(nStartColumn != wxNOT_FOUND);
524
525 // wrap lines too long at comma boundaries
526 for (unsigned int i=0; i<toinsert.GetCount(); i++)
527 {
528 size_t len = toinsert[i].Len();
529 if (len > WRAP_COLUMN)
530 {
531 wxASSERT(i == toinsert.GetCount()-1);
532
533 // break this line
534 wxString tmpleft = toinsert[i].Left(WRAP_COLUMN);
535 int comma = tmpleft.Find(',', true /* from end */);
536 if (comma == wxNOT_FOUND)
537 break; // break out of the for cycle...
538
539 toinsert.Add(wxString(' ', nStartColumn+1) +
540 toinsert[i].Right(len-comma-2)); // exclude the comma and the space after it
541 toinsert[i] = tmpleft.Left(comma+1); // include the comma
542 }
543 }
544
545 // insert the new lines
546 for (unsigned int i=0; i<toinsert.GetCount(); i++)
547 file.InsertLine(toinsert[i], start+i);
548
549 // now save the modification
550 if (!file.Write()) {
551 LogError("\tcan't save the '%s' header file.", header);
552 return false;
553 }
554
555 // how many lines did we add/remove in total?
556 int nOffset = toinsert.GetCount() + deprecationOffset - (end-start+1);
557 if (nOffset == 0)
558 return false;
559
560 if (g_verbose)
561 LogMessage("\tthe final row offset for following methods is %d lines.", nOffset);
562
563 // update the other method's locations for those methods which belong to the modified header
564 // and are placed _below_ the modified method
565 wxClassPtrArray cToUpdate = m_doxyInterface.FindClassesDefinedIn(header);
566 for (unsigned int i=0; i < cToUpdate.GetCount(); i++)
567 {
568 for (unsigned int j=0; j < cToUpdate[i]->GetMethodCount(); j++)
569 {
570 wxMethod& m = cToUpdate[i]->GetMethod(j);
571 if (m.GetLocation() > iface->GetLocation())
572 {
573 // update the location of this method
574 m.SetLocation(m.GetLocation()+nOffset);
575 }
576 }
577 }
578
579 return true;
580 }
581
582 bool IfaceCheckApp::ParsePreprocessorOutput(const wxString& filename)
583 {
584 wxTextFile tf;
585 if (!tf.Open(filename)) {
586 LogError("can't open the '%s' preprocessor output file.", filename);
587 return false;
588 }
589
590 size_t useful = 0;
591 for (unsigned int i=0; i < tf.GetLineCount(); i++)
592 {
593 const wxString& line = tf.GetLine(i);
594 wxString defnameval = line.Mid(8); // what follows the "#define " string
595
596 // the format of this line should be:
597 // #define DEFNAME DEFVALUE
598 if (!line.StartsWith("#define ")) {
599 LogError("unexpected content in '%s' at line %d.", filename, i+1);
600 return false;
601 }
602
603 if (defnameval.Contains(" "))
604 {
605 // get DEFNAME
606 wxString defname = defnameval.BeforeFirst(' ');
607 if (defname.Contains("("))
608 continue; // this is a macro, skip it!
609
610 // get DEFVAL
611 wxString defval = defnameval.AfterFirst(' ').Strip(wxString::both);
612 if (defval.StartsWith("(") && defval.EndsWith(")"))
613 defval = defval.Mid(1, defval.Len()-2);
614
615 // store this pair in the doxygen interface, where it can be useful
616 m_doxyInterface.AddPreprocessorValue(defname, defval);
617 useful++;
618 }
619 else
620 {
621 // it looks like the format of this line is:
622 // #define DEFNAME
623 // we are not interested to symbols #defined to nothing,
624 // so we just ignore this line.
625 }
626 }
627
628 LogMessage("Parsed %d preprocessor #defines from '%s' which will be used later...",
629 useful, filename);
630
631 return true;
632 }
633
634 void IfaceCheckApp::PrintStatistics(long secs)
635 {
636 LogMessage("wx real headers contains declaration of %d classes (%d methods)",
637 m_gccInterface.GetClassesCount(), m_gccInterface.GetMethodCount());
638 LogMessage("wx interface headers contains declaration of %d classes (%d methods)",
639 m_doxyInterface.GetClassesCount(), m_doxyInterface.GetMethodCount());
640 LogMessage("total processing took %d seconds.", secs);
641 }
642