1 /////////////////////////////////////////////////////////////////////////////
2 // Name: ifacecheck.cpp
3 // Purpose: Interface headers <=> real headers coherence checker
4 // Author: Francesco Montorsi
7 // Copyright: (c) 2008 Francesco Montorsi
8 // Licence: wxWindows licence
9 /////////////////////////////////////////////////////////////////////////////
11 // For compilers that support precompilation, includes "wx/wx.h".
12 #include "wx/wxprec.h"
18 // for all others, include the necessary headers
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"
29 // global verbosity flag
30 bool g_verbose
= false;
34 // ----------------------------------------------------------------------------
36 // ----------------------------------------------------------------------------
38 #define API_DUMP_FILE "dump.api.txt"
39 #define INTERFACE_DUMP_FILE "dump.interface.txt"
41 #define PROCESS_ONLY_OPTION "p"
42 #define USE_PREPROCESSOR_OPTION "u"
44 #define MODIFY_SWITCH "m"
45 #define DUMP_SWITCH "d"
46 #define HELP_SWITCH "h"
47 #define VERBOSE_SWITCH "v"
49 static const wxCmdLineEntryDesc g_cmdLineDesc
[] =
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",
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
},
72 class IfaceCheckApp
: public wxAppConsole
75 // don't use builtin cmd line parsing:
76 virtual bool OnInit() { m_modify
=false; return true; }
79 bool ParsePreprocessorOutput(const wxString
& filename
);
82 int CompareClasses(const wxClass
* iface
, const wxClassPtrArray
& api
);
83 void FixMethod(const wxString
& header
, const wxMethod
* iface
, const wxMethod
* api
);
86 void PrintStatistics(long secs
);
88 bool IsToProcess(const wxString
& headername
) const
90 if (m_strToMatch
.IsEmpty())
92 return wxMatchWild(m_strToMatch
, headername
, false);
96 wxXmlGccInterface m_api
; // "real" headers API
97 wxXmlDoxygenInterface m_interface
; // doxygen-commented headers API
99 // was the MODIFY_SWITCH passed?
102 // if non-empty, then PROCESS_ONLY_OPTION was passed and this is the
103 // wildcard expression to match
104 wxString m_strToMatch
;
107 IMPLEMENT_APP_CONSOLE(IfaceCheckApp
)
109 int IfaceCheckApp::OnRun()
111 long startTime
= wxGetLocalTime(); // for timing purpose
113 wxCmdLineParser
parser(g_cmdLineDesc
, argc
, argv
);
115 wxString::Format("wxWidgets Interface checker utility (built %s against %s)",
116 __DATE__
, wxVERSION_STRING
));
118 // parse the command line...
120 wxString preprocFile
;
121 switch (parser
.Parse())
124 if (parser
.Found(VERBOSE_SWITCH
))
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
))
131 if (!ParsePreprocessorOutput(preprocFile
))
135 // in any case set basic std preprocessor #defines:
136 m_interface
.AddPreprocessorValue("NULL", "0");
138 // parse the two XML files which contain the real and the doxygen interfaces
139 // for wxWidgets API:
140 if (!m_api
.Parse(parser
.GetParam(0)) ||
141 !m_interface
.Parse(parser
.GetParam(1)))
144 if (parser
.Found(DUMP_SWITCH
))
146 LogMessage("Dumping real API to '%s'...", API_DUMP_FILE
);
147 m_api
.Dump(API_DUMP_FILE
);
149 LogMessage("Dumping interface API to '%s'...", INTERFACE_DUMP_FILE
);
150 m_interface
.Dump(INTERFACE_DUMP_FILE
);
154 if (parser
.Found(MODIFY_SWITCH
))
157 if (parser
.Found(PROCESS_ONLY_OPTION
, &m_strToMatch
))
159 size_t len
= m_strToMatch
.Len();
160 if (m_strToMatch
.StartsWith("\"") &&
161 m_strToMatch
.EndsWith("\"") &&
163 m_strToMatch
= m_strToMatch
.Mid(1, len
-2);
169 PrintStatistics(wxGetLocalTime() - startTime
);
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
);
183 // HELP_SWITCH was passed or a syntax error occurred
190 void IfaceCheckApp::ShowProgress()
196 bool IfaceCheckApp::Compare()
198 const wxClassArray
& interface
= m_interface
.GetClasses();
201 int mcount
= 0, ccount
= 0;
203 LogMessage("Comparing the interface API to the real API (%d classes to compare)...",
204 interface
.GetCount());
206 if (!m_strToMatch
.IsEmpty())
207 LogMessage("Processing only header files matching '%s' expression.", m_strToMatch
);
209 for (unsigned int i
=0; i
<interface
.GetCount(); i
++)
211 // shorten the name of the header so the log file is more readable
212 // and also for calling IsToProcess() against it
213 wxString header
= wxFileName(interface
[i
].GetHeader()).GetFullName();
215 if (!IsToProcess(header
))
216 continue; // skip this one
218 wxString cname
= interface
[i
].GetName();
222 // search in the real headers for i-th interface class
223 // for both class cname and cnameBase as in wxWidgets world, most often
224 // class cname is platform-specific while the real public interface of
225 // that class is part of the cnameBase class.
226 c
= m_api
.FindClass(cname
);
228 c
= m_api
.FindClass(cname
+ "Base");
231 if (api
.GetCount()>0) {
233 // there is a class with exactly the same name!
234 mcount
+= CompareClasses(&interface
[i
], api
);
238 LogMessage("%s: couldn't find the real interface for the '%s' class",
244 LogMessage("%d methods (%.1f%%) of the interface headers do not exist in the real headers",
245 mcount
, (float)(100.0 * mcount
/m_interface
.GetMethodCount()));
246 LogMessage("%d classes (%.1f%%) of the interface headers do not exist in the real headers",
247 ccount
, (float)(100.0 * ccount
/m_interface
.GetClassesCount()));
252 int IfaceCheckApp::CompareClasses(const wxClass
* iface
, const wxClassPtrArray
& api
)
254 wxString searchedclasses
;
255 const wxMethod
*real
;
258 wxASSERT(iface
&& api
.GetCount()>0);
260 // build a string with the names of the API classes compared to iface
261 for (unsigned int j
=0; j
<api
.GetCount(); j
++)
262 searchedclasses
+= "/" + api
[j
]->GetName();
263 searchedclasses
.Remove(0, 1);
265 // shorten the name of the header so the log file is more readable
266 wxString header
= wxFileName(iface
->GetHeader()).GetFullName();
268 for (unsigned int i
=0; i
<iface
->GetMethodCount(); i
++)
270 const wxMethod
& m
= iface
->GetMethod(i
);
273 // search in the methods of the api classes provided
274 for (unsigned int j
=0; j
<api
.GetCount(); j
++)
276 real
= api
[j
]->FindMethod(m
);
278 matches
++; // there is a real matching prototype! It's ok!
283 wxMethodPtrArray overloads
;
285 // try searching for a method with the same name but with
286 // different return type / arguments / qualifiers
287 for (unsigned int j
=0; j
<api
.GetCount(); j
++)
289 wxMethodPtrArray results
= api
[j
]->FindMethodNamed(m
.GetName());
291 // append "results" array to "overloads"
292 WX_APPEND_ARRAY(overloads
, results
);
295 if (overloads
.GetCount()==0)
298 TODO: sometimes the interface headers re-document a method
299 inherited from a base class even if the real header does
300 not actually re-implement it.
301 To avoid false positives, we'd need to search in the base classes
302 of api[] classes and search for a matching method.
304 LogMessage("%s: real '%s' class has no method '%s'",
305 header
, searchedclasses
, m
.GetAsString());
306 // we've found no overloads
310 // first, output a warning
311 wxString warning
= header
;
312 if (overloads
.GetCount()>1)
313 warning
+= wxString::Format(": in the real headers there are %d overloads of '%s' for "
314 "'%s' all with different signatures:\n",
315 overloads
.GetCount(), m
.GetName(), searchedclasses
);
317 warning
+= wxString::Format(": in the real headers there is a method '%s' for '%s'"
318 " but has different signature:\n",
319 m
.GetName(), searchedclasses
);
321 warning
+= "\tdoxy header: " + m
.GetAsString();
322 for (unsigned int j
=0; j
<overloads
.GetCount(); j
++)
323 warning
+= "\n\treal header: " + overloads
[j
]->GetAsString();
325 wxPrint(warning
+ "\n");
328 if (overloads
.GetCount()>1)
330 // TODO: decide which of these overloads is the most "similar" to m
331 // and eventually modify it
333 wxPrint("\tmanual fix is required\n");
337 wxASSERT(overloads
.GetCount() == 1);
341 wxPrint("\tfixing it...\n");
344 FixMethod(iface
->GetHeader(), &m
, overloads
[0]);
356 void IfaceCheckApp::FixMethod(const wxString
& header
, const wxMethod
* iface
, const wxMethod
* api
)
358 wxASSERT(iface
&& api
);
361 if (!file
.Open(header
)) {
362 LogError("\tcan't open the '%s' header file.", header
);
366 // GetLocation() returns the line where the last part of the prototype is placed:
367 int end
= iface
->GetLocation()-1;
368 if (end
<= 0 || end
>= (int)file
.GetLineCount()) {
369 LogWarning("\tinvalid location info for method '%s': %d.",
370 iface
->GetAsString(), iface
->GetLocation());
374 if (!file
.GetLine(end
).Contains(";")) {
375 LogWarning("\tinvalid location info for method '%s': %d.",
376 iface
->GetAsString(), iface
->GetLocation());
380 // find the start point of this prototype declaration:
382 bool founddecl
= false;
384 !file
.GetLine(start
).Contains(";") &&
385 !file
.GetLine(start
).Contains("*/"))
389 founddecl
|= file
.GetLine(start
).Contains(iface
->GetName());
392 if (start
<= 0 || !founddecl
)
394 LogError("\tcan't find the beginning of the declaration of '%s' method in '%s' header",
395 iface
->GetAsString(), header
);
399 // start-th line contains either the declaration of another prototype
400 // or the closing tag */ of a doxygen comment; start one line below
403 // remove the old prototype
404 for (int i
=start
; i
<=end
; i
++)
405 file
.RemoveLine(start
); // remove (end-start)-nth times the start-th line
407 #define INDENTATION_STR wxString(" ")
409 // if possible, add also the @deprecated tag in the doxygen comment if it's missing
410 int deprecationOffset
= 0;
411 if (file
.GetLine(start
-1).Contains("*/") &&
412 (api
->IsDeprecated() && !iface
->IsDeprecated()))
414 file
.RemoveLine(start
-1);
415 file
.InsertLine(INDENTATION_STR
+ INDENTATION_STR
+
416 "@deprecated @todo provide deprecation description", start
-1);
417 file
.InsertLine(INDENTATION_STR
+ "*/", start
++);
419 // we have added a new line in the final balance
425 // discard API argument names and replace them with those parsed from doxygen XML:
426 const wxArgumentTypeArray
& doxygenargs
= iface
->GetArgumentTypes();
427 const wxArgumentTypeArray
& realargs
= api
->GetArgumentTypes();
428 if (realargs
.GetCount() == doxygenargs
.GetCount())
430 for (unsigned int j
=0; j
<doxygenargs
.GetCount(); j
++)
431 if (doxygenargs
[j
]==realargs
[j
])
432 realargs
[j
].SetArgumentName(doxygenargs
[j
].GetArgumentName());
434 tmp
.SetArgumentTypes(realargs
);
437 #define WRAP_COLUMN 80
439 wxArrayString toinsert
;
440 toinsert
.Add(INDENTATION_STR
+ tmp
.GetAsString() + ";");
442 int nStartColumn
= toinsert
[0].Find('(');
443 wxASSERT(nStartColumn
!= wxNOT_FOUND
);
445 // wrap lines too long at comma boundaries
446 for (unsigned int i
=0; i
<toinsert
.GetCount(); i
++)
448 size_t len
= toinsert
[i
].Len();
449 if (len
> WRAP_COLUMN
)
451 wxASSERT(i
== toinsert
.GetCount()-1);
454 wxString tmpleft
= toinsert
[i
].Left(WRAP_COLUMN
);
455 int comma
= tmpleft
.Find(',', true /* from end */);
456 if (comma
== wxNOT_FOUND
)
457 break; // break out of the for cycle...
459 toinsert
.Add(wxString(' ', nStartColumn
+1) +
460 toinsert
[i
].Right(len
-comma
-2)); // exclude the comma and the space after it
461 toinsert
[i
] = tmpleft
.Left(comma
+1); // include the comma
465 // insert the new lines
466 for (unsigned int i
=0; i
<toinsert
.GetCount(); i
++)
467 file
.InsertLine(toinsert
[i
], start
+i
);
469 // now save the modification
471 LogError("\tcan't save the '%s' header file.", header
);
475 // how many lines did we add/remove in total?
476 int nOffset
= toinsert
.GetCount() + deprecationOffset
- (end
-start
+1);
481 LogMessage("\tthe final row offset for following methods is %d lines.", nOffset
);
483 // update the other method's locations for those methods which belong to the modified header
484 // and are placed _below_ the modified method
485 wxClassPtrArray cToUpdate
= m_interface
.FindClassesDefinedIn(header
);
486 for (unsigned int i
=0; i
< cToUpdate
.GetCount(); i
++)
488 for (unsigned int j
=0; j
< cToUpdate
[i
]->GetMethodCount(); j
++)
490 wxMethod
& m
= cToUpdate
[i
]->GetMethod(j
);
491 if (m
.GetLocation() > iface
->GetLocation())
493 // update the location of this method
494 m
.SetLocation(m
.GetLocation()+nOffset
);
500 bool IfaceCheckApp::ParsePreprocessorOutput(const wxString
& filename
)
503 if (!tf
.Open(filename
)) {
504 LogError("can't open the '%s' preprocessor output file.", filename
);
509 for (unsigned int i
=0; i
< tf
.GetLineCount(); i
++)
511 const wxString
& line
= tf
.GetLine(i
);
512 wxString defnameval
= line
.Mid(8); // what follows the "#define " string
514 // the format of this line should be:
515 // #define DEFNAME DEFVALUE
516 if (!line
.StartsWith("#define ") || !defnameval
.Contains(" ")) {
517 LogError("unexpected content in '%s' at line %d.", filename
, i
);
522 wxString defname
= defnameval
.BeforeFirst(' ');
523 if (defname
.Contains("("))
524 continue; // this is a macro, skip it!
527 wxString defval
= defnameval
.AfterFirst(' ').Strip(wxString::both
);
528 if (defval
.StartsWith("(") && defval
.EndsWith(")"))
529 defval
= defval
.Mid(1, defval
.Len()-2);
531 // store this pair in the doxygen interface, where it can be useful
532 m_interface
.AddPreprocessorValue(defname
, defval
);
536 LogMessage("Parsed %d preprocessor #defines from '%s' which will be used later...",
542 void IfaceCheckApp::PrintStatistics(long secs
)
544 LogMessage("wx real headers contains declaration of %d classes (%d methods)",
545 m_api
.GetClassesCount(), m_api
.GetMethodCount());
546 LogMessage("wx interface headers contains declaration of %d classes (%d methods)",
547 m_interface
.GetClassesCount(), m_interface
.GetMethodCount());
548 LogMessage("total processing took %d seconds.", secs
);