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