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 std::cout<<"Found state: "<<state<<std::endl;
292 for (DeclContext::decl_iterator i = declCont->decls_begin(), e = declCont->decls_end(); i != e; ++i)
294 if (i->getKind()==26) // typedefs
298 line = clean_spaces(cut_type(output));
299 ret = find_transitions(state,line);
302 num = count(ret,';')+1;
303 for(int i = 0;i<num;i++)
310 if(pos==-1) cReactions.push_back(ret);
311 else cReactions.push_back(ret.substr(0,pos));
316 if(pos==-1) transitions.push_back(ret);
317 else transitions.push_back(ret.substr(0,pos));
319 if(i!=num-1) ret = ret.substr(pos+1);
324 if(i->getKind()==35) method_decl(*i);// C++ method
330 * Traverse method declaration using classes with main class Stmt.
332 void method_decl(const Decl *decl)
334 string output, line, event;
335 llvm::raw_string_ostream x(output);
340 line = get_return(x.str());
341 if(get_model(line)==5)
343 //std::cout<<"metodass"<<std::endl;
344 const FunctionDecl *fDecl = dyn_cast<FunctionDecl>(decl);
345 const ParmVarDecl *pvd = fDecl->getParamDecl(0);
346 QualType qt = pvd->getOriginalType();
347 event = qt.getAsString();
348 if(event[event.length()-1]=='&') event = event.substr(0,event.length()-2);
349 event = event.substr(event.rfind(" ")+1);
350 line = dyn_cast<NamedDecl>(decl)->getQualifiedNameAsString();
351 line = cut_namespaces(line.substr(0,line.rfind("::")));
354 find_return_stmt(decl->getBody(),line);
355 for(list<string>::iterator i = cReactions.begin();i!=cReactions.end();i++) // erase info about it from list of custom reactions
358 if(line.compare(event)==0)
368 void find_return_stmt(Stmt *statemt,string event) /** Traverse all statements in function for finding all return Statements.*/
370 if(statemt->getStmtClass() == 99) test_stmt(dyn_cast<CaseStmt>(statemt)->getSubStmt(), event);
373 for (Stmt::child_range range = statemt->children(); range; ++range)
375 test_stmt(*range, event);
380 void test_stmt(Stmt *stmt, string event) /** test statement for its kind Using number as identifier for all Statement Classes.*/
382 const SourceManager &sman = fsloc->getManager();
385 type = stmt->getStmtClass();
388 case 8 : find_return_stmt(dyn_cast<DoStmt>(stmt)->getBody(), event); // do
390 case 86 : find_return_stmt(dyn_cast<ForStmt>(stmt)->getBody(), event); // for
392 case 88 : find_return_stmt(dyn_cast<IfStmt>(stmt)->getThen(), event); //if then
393 find_return_stmt(dyn_cast<IfStmt>(stmt)->getElse(), event); //if else
395 case 90 : find_return_stmt(dyn_cast<LabelStmt>(stmt)->getSubStmt(), event); //label
397 case 98 : line = sman.getCharacterData(dyn_cast<ReturnStmt>(stmt)->getReturnLoc());
398 line = get_line_of_code(line).substr(6);
399 line = line.substr(0,line.find("("));
400 if(get_model(line)==6)
402 param = get_params(line);
403 transitions.push_back(event.append(",").append(param));
405 if(get_model(line) == 7)
408 transitions.push_back(param.append(event));
411 case 99 : find_return_stmt(stmt, event);
413 case 101 : find_return_stmt(dyn_cast<SwitchStmt>(stmt)->getBody(), event); // switch
415 case 102 : find_return_stmt(dyn_cast<WhileStmt>(stmt)->getBody(), event); // while
422 * Main function provides all initialization before starting analysis of AST. Diagnostic Client is initialized,
423 * Command line options are processed.
425 int main(int argc, char **argv)
427 if(argc==1 || strncmp(argv[1],"-help",5)==0)
429 cout<<endl<<" Boost Statechart Viewer - help"<<endl;
430 cout<<"================================"<<endl;
431 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;
434 string inputFilename = "";
435 string outputFilename = "graph.dot"; // initialize output Filename
436 DiagnosticOptions dopts;
438 MyDiagnosticClient *mdc = new MyDiagnosticClient(llvm::errs(), dopts);
439 llvm::IntrusiveRefCntPtr<DiagnosticIDs> dis(new DiagnosticIDs());
440 Diagnostic diag(dis,mdc);
441 FileManager fm( * new FileSystemOptions());
442 SourceManager sm (diag, fm);
443 HeaderSearch *headers = new HeaderSearch(fm);
445 Driver TheDriver(LLVM_BINDIR, llvm::sys::getHostTriple(), "", false, false, diag);
446 TheDriver.setCheckInputsExist(true);
447 TheDriver.CCCIsCXX = 1;
448 TheDriver.ResourceDir = LLVM_PREFIX "/lib/clang/" CLANG_VERSION_STRING;
450 CompilerInvocation compInv;
451 llvm::SmallVector<const char *, 16> Args(argv, argv + argc);
452 llvm::OwningPtr<Compilation> C(TheDriver.BuildCompilation(Args.size(),
454 const driver::JobList &Jobs = C->getJobs();
455 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
456 const driver::ArgStringList &CCArgs = Cmd->getArguments();
457 for(unsigned i = 0; i<Args.size();i++) // find -o in ArgStringList
459 if(strncmp(Args[i],"-o",2)==0)
461 if(strlen(Args[i])>2)
463 string str = Args[i];
464 outputFilename = str.substr(2);
466 else outputFilename = Args[i+1];
471 CompilerInvocation::CreateFromArgs(compInv,
472 const_cast<const char **>(CCArgs.data()),
473 const_cast<const char **>(CCArgs.data())+CCArgs.size(),
476 HeaderSearchOptions hsopts = compInv.getHeaderSearchOpts();
477 LangOptions lang = compInv.getLangOpts();
478 CompilerInvocation::setLangDefaults(lang, IK_ObjCXX);
479 TargetInfo *ti = TargetInfo::CreateTargetInfo(diag, compInv.getTargetOpts());
480 FrontendOptions f = compInv.getFrontendOpts();
481 inputFilename = f.Inputs[0].second;
483 cout<<"Input filename: "<<inputFilename<<"\n"; // print Input filename
484 cout<<"Output filename: "<<outputFilename<<"\n\n\n"; // print Output filename
487 Preprocessor pp(diag, lang, *ti, sm, *headers);
488 pp.getBuiltinInfo().InitializeBuiltins(pp.getIdentifierTable(), lang);
490 InitializePreprocessor(pp, compInv.getPreprocessorOpts(),hsopts,f);
492 const FileEntry *file = fm.getFile(inputFilename);
493 sm.createMainFileID(file);
494 IdentifierTable tab(lang);
495 Builtin::Context builtins(*ti);
497 ASTContext ctx(lang, sm, *ti, tab, * new SelectorTable(), builtins,0);
498 mdc->BeginSourceFile(lang, &pp);//start using diagnostic
499 ParseAST(pp, &c, ctx, false, false);
500 mdc->EndSourceFile(); //end using diagnostic
501 IO_operations *io = new IO_operations(outputFilename, c.getStateMachine(), c.getNameOfFirstState(), c.getTransitions(), c.getStates(), c.getEvents());