2 ////////////////////////////////////////////////////////////////////////////////////////
4 // This file is part of Boost Statechart Viewer.
6 // Boost Statechart Viewer is free software: you can redistribute it and/or modify
7 // it under the terms of the GNU General Public License as published by
8 // the Free Software Foundation, either version 3 of the License, or
9 // (at your option) any later version.
11 // Boost Statechart Viewer is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with Boost Statechart Viewer. If not, see <http://www.gnu.org/licenses/>.
19 ////////////////////////////////////////////////////////////////////////////////////////
21 //standard header files
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Support/Host.h"
27 #include "llvm/Config/config.h"
30 #include "clang/Frontend/TextDiagnosticPrinter.h"
31 #include "clang/Lex/HeaderSearch.h"
32 #include "clang/Basic/FileManager.h"
33 #include "clang/Frontend/Utils.h"
34 #include "clang/Basic/TargetInfo.h"
35 #include "clang/Lex/Preprocessor.h"
36 #include "clang/Frontend/CompilerInstance.h"
37 #include "clang/AST/ASTConsumer.h"
38 #include "clang/Sema/Lookup.h"
39 #include "clang/Parse/ParseAST.h"
40 #include "clang/Basic/Version.h"
41 #include "clang/Driver/Driver.h"
42 #include "clang/Driver/Compilation.h"
47 using namespace clang;
48 using namespace clang::driver;
52 * This class provides Simple diagnostic Client. It uses implementation in library for printing diagnostci information.
53 * Also it counts number of warnings, errors, ... When an error occurs the program is stopped.
55 class MyDiagnosticClient : public TextDiagnosticPrinter
57 int nwarnings; /** Save number of Warnings occured during diagnostic */
63 * Initialize number of warnings, errors, ...
65 MyDiagnosticClient(llvm::raw_ostream &os, const DiagnosticOptions &diags, bool OwnsOutputStream = false):TextDiagnosticPrinter(os, diags, OwnsOutputStream = false)
73 * This method prints diagnostic and counts diagnostic types.
75 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel, const DiagnosticInfo &Info)
77 TextDiagnosticPrinter::HandleDiagnostic(DiagLevel, Info); // print diagnostic information using library implementation
78 switch (DiagLevel) // count number of all diagnostic information
80 case 0 : nignored+=1; break;
81 case 1 : nnotes+=1; break;
82 case 2 : nwarnings+=1; break;
89 * Print statistics about diagnostic.
93 cout<<"\n--Diagnostic Info--\n";
94 cout<<"Number of ignored: "<<nignored<<"\n";
95 cout<<"Number of notes: "<<nnotes<<"\n";
96 cout<<"Number of warnings: "<<nwarnings<<"\n";
97 cout<<"Number of errors and fatal errors: "<<nerrors<<"\n";
100 int getNbrOfWarnings() /** Return number of warnings */
105 int getNbrOfNotes() /** Return number of notes */
110 int getNbrOfIgnored() /** Return number of ignored */
117 * My ASTConsumer provides interface for traversing AST. It uses recursive traversing in namespaces.
119 class FindStates : public ASTConsumer
121 list<string> transitions;
122 list<string> cReactions; /** list of custom reactions. After all files are traversed this list should be empty. */
125 string name_of_machine;
126 string name_of_start;
127 FullSourceLoc *fsloc; /** Full Source Location instance for holding Source Manager. */
130 list<string> getStates() /** Return list of states of the state machine. */
135 list<string> getTransitions() /** Return list of transitions. */
140 list<string> getEvents() /** Return list of events. */
145 string getStateMachine() /** Return name of the state machine. */
147 return name_of_machine;
150 string getNameOfFirstState() /** Return name of start state. */
152 return name_of_start;
155 virtual void Initialize(ASTContext &ctx)/** Run after the AST is constructed before the consumer starts to work. So this function works like constructor. */
157 fsloc = new FullSourceLoc(* new SourceLocation(), ctx.getSourceManager());
159 name_of_machine = "";
163 * Traverse global decls using DeclGroupRef for handling all global decls. But only interesting decls are processed. Interesting decls are Struct, Class, C++ methods and Namespace.
164 * When Namespace is found it recursively traverse all decls inside this Namespace using method recursive_visit.
166 virtual void HandleTopLevelDecl(DeclGroupRef DGR)
169 string line, output, event;
170 llvm::raw_string_ostream x(output);
171 for (DeclGroupRef::iterator i = DGR.begin(), e = DGR.end(); i != e; ++i)
173 const Decl *decl = *i;
174 loc = decl->getLocation();
177 if(decl->getKind()==35)
181 if (const TagDecl *tagDecl = dyn_cast<TagDecl>(decl))
183 if(tagDecl->isStruct() || tagDecl->isClass()) //is it a struct or class
188 if(const NamespaceDecl *namespaceDecl = dyn_cast<NamespaceDecl>(decl))
191 DeclContext *declCont = namespaceDecl->castToDeclContext(namespaceDecl);
192 recursive_visit(declCont);
201 * It is used to recursive traverse decls in Namespaces. This method do the same as HandleTopLevelDecl.
203 void recursive_visit(const DeclContext *declCont)
205 string line, output, event;
206 llvm::raw_string_ostream x(output);
208 for (DeclContext::decl_iterator i = declCont->decls_begin(), e = declCont->decls_end(); i != e; ++i)
210 const Decl *decl = *i;
211 loc = decl->getLocation();
214 if(decl->getKind()==35)
218 else if (const TagDecl *tagDecl = dyn_cast<TagDecl>(decl))
220 if(tagDecl->isStruct() || tagDecl->isClass()) //is it a structure or class
225 else if(const NamespaceDecl *namespaceDecl = dyn_cast<NamespaceDecl>(decl))
227 DeclContext *declCont = namespaceDecl->castToDeclContext(namespaceDecl);
228 recursive_visit(declCont);
236 * This function works with class or struct. It splits the decl into 3 interesting parts.
237 * The state machine decl, state decl and event decl.
239 void struct_class(const Decl *decl)
241 string output, line, ret, trans, event;
242 llvm::raw_string_ostream x(output);
244 line = get_line_of_code(x.str());
248 const NamedDecl *namedDecl = dyn_cast<NamedDecl>(decl);
251 const CXXRecordDecl *cRecDecl = dyn_cast<CXXRecordDecl>(decl);
253 if(find_events(cRecDecl, line))
255 events.push_back(namedDecl->getNameAsString());
257 else if(name_of_machine == "")
259 ret = find_name_of_machine(cRecDecl, line);
263 name_of_machine = ret.substr(0,pos);
264 name_of_start = ret.substr(pos+1);
269 ret = find_states(cRecDecl, line);
272 states.push_back(ret);
273 methods_in_class(decl,namedDecl->getNameAsString());
280 * This function provides traversing all methods and other context indide class. If
281 * typedef or classic method decl is found. If typedef is found then it is being testted for transitions and custom reactions.
283 void methods_in_class(const Decl *decl, const string state)
285 string output, line, ret, trans, event;
286 llvm::raw_string_ostream x(output);
288 const TagDecl *tagDecl = dyn_cast<TagDecl>(decl);
289 const DeclContext *declCont = tagDecl->castToDeclContext(tagDecl);
291 for (DeclContext::decl_iterator i = declCont->decls_begin(), e = declCont->decls_end(); i != e; ++i)
293 if (i->getKind()==26) // typedefs
297 line = clean_spaces(cut_type(output));
298 ret = find_transitions(state,line);
301 num = count(ret,';')+1;
302 for(int i = 0;i<num;i++)
309 if(pos==-1) cReactions.push_back(ret);
310 else cReactions.push_back(ret.substr(0,pos));
315 if(pos==-1) transitions.push_back(ret);
316 else transitions.push_back(ret.substr(0,pos));
318 if(i!=num-1) ret = ret.substr(pos+1);
323 if(i->getKind()==35) method_decl(decl);// C++ method
328 * Traverse method declaration using classes with main class Stmt.
330 void method_decl(const Decl *decl)
332 string output, line, event;
333 llvm::raw_string_ostream x(output);
337 line = get_return(x.str());
338 if(get_model(line)==5)
340 const FunctionDecl *fDecl = dyn_cast<FunctionDecl>(decl);
341 const ParmVarDecl *pvd = fDecl->getParamDecl(0);
342 QualType qt = pvd->getOriginalType();
343 event = qt.getAsString();
344 if(event[event.length()-1]=='&') event = event.substr(0,event.length()-2);
345 event = event.substr(event.rfind(" ")+1);
346 line = dyn_cast<NamedDecl>(decl)->getQualifiedNameAsString();
347 line = cut_namespaces(line.substr(0,line.rfind("::")));
350 find_return_stmt(decl->getBody(),line);
351 for(list<string>::iterator i = cReactions.begin();i!=cReactions.end();i++) // erase info about it from list of custom reactions
354 if(line.compare(event)==0)
364 void find_return_stmt(Stmt *statemt,string event) /** Traverse all statements in function for finding all return Statements.*/
366 if(statemt->getStmtClass() == 99) test_stmt(dyn_cast<CaseStmt>(statemt)->getSubStmt(), event);
369 for (Stmt::child_range range = statemt->children(); range; ++range)
371 test_stmt(*range, event);
376 void test_stmt(Stmt *stmt, string event) /** test statement for its kind Using number as identifier for all Statement Classes.*/
378 const SourceManager &sman = fsloc->getManager();
381 type = stmt->getStmtClass();
384 case 8 : find_return_stmt(dyn_cast<DoStmt>(stmt)->getBody(), event); // do
386 case 86 : find_return_stmt(dyn_cast<ForStmt>(stmt)->getBody(), event); // for
388 case 88 : find_return_stmt(dyn_cast<IfStmt>(stmt)->getThen(), event); //if then
389 find_return_stmt(dyn_cast<IfStmt>(stmt)->getElse(), event); //if else
391 case 90 : find_return_stmt(dyn_cast<LabelStmt>(stmt)->getSubStmt(), event); //label
393 case 98 : line = sman.getCharacterData(dyn_cast<ReturnStmt>(stmt)->getReturnLoc());
394 line = get_line_of_code(line).substr(6);
395 line = line.substr(0,line.find("("));
396 if(get_model(line)==6)
398 param = get_params(line);
399 transitions.push_back(event.append(",").append(param));
401 if(get_model(line) == 7)
404 transitions.push_back(param.append(event));
407 case 99 : find_return_stmt(stmt, event);
409 case 101 : find_return_stmt(dyn_cast<SwitchStmt>(stmt)->getBody(), event); // switch
411 case 102 : find_return_stmt(dyn_cast<WhileStmt>(stmt)->getBody(), event); // while
418 * Main function provides all initialization before starting analysis of AST. Diagnostic Client is initialized,
419 * Command line options are processed.
421 int main(int argc, char **argv)
423 if(argc==1 || strncmp(argv[1],"-help",5)==0)
425 cout<<endl<<" Boost Statechart Viewer - help"<<endl;
426 cout<<"================================"<<endl;
427 cout<<"The program can be used almost the same way as a C compiler. You will typically need to specify locations for all header files except of the files stored in system folder(in Linux: /usr/...) using -I option. Of course you can specify the output filename (-o option). Program displays all diagnostic messages like compilers. If an error occurs the program stops."<<endl<<endl;
430 string inputFilename = "";
431 string outputFilename = "graph.dot"; // initialize output Filename
432 DiagnosticOptions dopts;
434 MyDiagnosticClient *mdc = new MyDiagnosticClient(llvm::errs(), dopts);
435 llvm::IntrusiveRefCntPtr<DiagnosticIDs> dis(new DiagnosticIDs());
436 Diagnostic diag(dis,mdc);
437 FileManager fm( * new FileSystemOptions());
438 SourceManager sm (diag, fm);
439 HeaderSearch *headers = new HeaderSearch(fm);
441 Driver TheDriver(LLVM_BINDIR, llvm::sys::getHostTriple(), "", false, false, diag);
442 TheDriver.setCheckInputsExist(true);
443 TheDriver.CCCIsCXX = 1;
444 TheDriver.ResourceDir = LLVM_PREFIX "/lib/clang/" CLANG_VERSION_STRING;
446 CompilerInvocation compInv;
447 llvm::SmallVector<const char *, 16> Args(argv, argv + argc);
448 llvm::OwningPtr<Compilation> C(TheDriver.BuildCompilation(Args.size(),
450 const driver::JobList &Jobs = C->getJobs();
451 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
452 const driver::ArgStringList &CCArgs = Cmd->getArguments();
453 for(unsigned i = 0; i<Args.size();i++) // find -o in ArgStringList
455 if(strncmp(Args[i],"-o",2)==0)
457 if(strlen(Args[i])>2)
459 string str = Args[i];
460 outputFilename = str.substr(2);
462 else outputFilename = Args[i+1];
467 CompilerInvocation::CreateFromArgs(compInv,
468 const_cast<const char **>(CCArgs.data()),
469 const_cast<const char **>(CCArgs.data())+CCArgs.size(),
472 HeaderSearchOptions hsopts = compInv.getHeaderSearchOpts();
473 LangOptions lang = compInv.getLangOpts();
474 CompilerInvocation::setLangDefaults(lang, IK_ObjCXX);
475 TargetInfo *ti = TargetInfo::CreateTargetInfo(diag, compInv.getTargetOpts());
476 FrontendOptions f = compInv.getFrontendOpts();
477 inputFilename = f.Inputs[0].second;
479 cout<<"Input filename: "<<inputFilename<<"\n"; // print Input filename
480 cout<<"Output filename: "<<outputFilename<<"\n"; // print Output filename
483 Preprocessor pp(diag, lang, *ti, sm, *headers);
484 pp.getBuiltinInfo().InitializeBuiltins(pp.getIdentifierTable(), lang);
486 InitializePreprocessor(pp, compInv.getPreprocessorOpts(),hsopts,f);
488 const FileEntry *file = fm.getFile(inputFilename);
489 sm.createMainFileID(file);
490 IdentifierTable tab(lang);
491 Builtin::Context builtins(*ti);
493 ASTContext ctx(lang, sm, *ti, tab, * new SelectorTable(), builtins,0);
494 mdc->BeginSourceFile(lang, &pp);//start using diagnostic
495 ParseAST(pp, &c, ctx, false, false);
496 mdc->EndSourceFile(); //end using diagnostic
497 IO_operations *io = new IO_operations(outputFilename, c.getStateMachine(), c.getNameOfFirstState(), c.getTransitions(), c.getStates(), c.getEvents());