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