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
58 * Variables for saving numbers of warnings, errors, ...
66 * Initialize number of warnings, errors, ...
68 MyDiagnosticClient(llvm::raw_ostream &os, const DiagnosticOptions &diags, bool OwnsOutputStream = false):TextDiagnosticPrinter(os, diags, OwnsOutputStream = false)
76 * This method prints diagnostic and counts diagnostic types.
78 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel, const DiagnosticInfo &Info)
80 TextDiagnosticPrinter::HandleDiagnostic(DiagLevel, Info); // print diagnostic information using library implementation
81 switch (DiagLevel) // count number of all diagnostic information
83 case 0 : nignored+=1; break;
84 case 1 : nnotes+=1; break;
85 case 2 : nwarnings+=1; break;
92 * Print statistics about diagnostic
96 cout<<"\n--Diagnostic Info--\n";
97 cout<<"Number of ignored: "<<nignored<<"\n";
98 cout<<"Number of notes: "<<nnotes<<"\n";
99 cout<<"Number of warnings: "<<nwarnings<<"\n";
100 cout<<"Number of errors and fatal errors: "<<nerrors<<"\n";
103 int getNbrOfWarnings() /** Return number of warnings */
108 int getNbrOfNotes() /** Return number of notes */
113 int getNbrOfIgnored() /** Return number of ignored */
120 * My ASTConsumer provides interface for traversing AST. It uses recursive traversing in namespaces.
122 class FindStates : public ASTConsumer
124 list<string> transitions;
125 list<string> cReactions;
128 string name_of_machine;
129 string name_of_start;
130 FullSourceLoc *fsloc;
133 list<string> getStates() /** Return list of states. */
138 list<string> getTransitions() /** Return list of transitions. */
143 list<string> getEvents() /** Return list of events. */
148 string getStateMachine() /** Return name of the state machine. */
150 return name_of_machine;
153 string getNameOfFirstState() /** Return name of start state. */
155 return name_of_start;
158 virtual void Initialize(ASTContext &ctx)/** Run after the AST is constructed before the consumer starts to work. So this function works like constructor. */
160 fsloc = new FullSourceLoc(* new SourceLocation(), ctx.getSourceManager());
162 name_of_machine = "";
166 * Traverse global decls using DeclGroupRef for handling all global decls. But only interesting decls are processed. Interesting decls are Struct, Class, Method and Namespace.
167 * When Namespace is found it recursively traverse all decls inside this Namespace using method recursive_visit.
169 virtual void HandleTopLevelDecl(DeclGroupRef DGR)
172 string line, output, event;
173 llvm::raw_string_ostream x(output);
174 for (DeclGroupRef::iterator i = DGR.begin(), e = DGR.end(); i != e; ++i)
176 const Decl *decl = *i;
177 loc = decl->getLocation();
180 if(decl->getKind()==35)
184 if (const TagDecl *tagDecl = dyn_cast<TagDecl>(decl))
186 if(tagDecl->isStruct() || tagDecl->isClass()) //is it a struct or class
191 if(const NamespaceDecl *namespaceDecl = dyn_cast<NamespaceDecl>(decl))
194 DeclContext *declCont = namespaceDecl->castToDeclContext(namespaceDecl);
195 recursive_visit(declCont);
204 * It is used to recursive traverse decls in Namespaces. This method do the same as HandleTopLevelDecl.
206 void recursive_visit(const DeclContext *declCont)
208 string line, output, event;
209 llvm::raw_string_ostream x(output);
211 for (DeclContext::decl_iterator i = declCont->decls_begin(), e = declCont->decls_end(); i != e; ++i)
213 const Decl *decl = *i;
214 loc = decl->getLocation();
217 if(decl->getKind()==35)
221 else if (const TagDecl *tagDecl = dyn_cast<TagDecl>(decl))
223 if(tagDecl->isStruct() || tagDecl->isClass()) //is it a structure or class
228 else if(const NamespaceDecl *namespaceDecl = dyn_cast<NamespaceDecl>(decl))
230 DeclContext *declCont = namespaceDecl->castToDeclContext(namespaceDecl);
231 recursive_visit(declCont);
239 * This function works with class or struct. It splits the decl into 3 interesting parts.
240 * The state machine decl, state decl and event decl.
242 void struct_class(const Decl *decl)
244 string output, line, ret, trans, event;
245 llvm::raw_string_ostream x(output);
247 line = get_line_of_code(x.str());
250 const NamedDecl *namedDecl = dyn_cast<NamedDecl>(decl);
253 const CXXRecordDecl *cRecDecl = dyn_cast<CXXRecordDecl>(decl);
255 if(find_events(cRecDecl, line))
257 events.push_back(namedDecl->getNameAsString());
259 else if(name_of_machine == "")
261 ret = find_name_of_machine(cRecDecl, line);
265 name_of_machine = ret.substr(0,pos);
266 name_of_start = ret.substr(pos+1);
271 ret = find_states(cRecDecl, line);
274 states.push_back(ret);
275 methods_in_class(decl,namedDecl->getNameAsString());
282 * This function provides traversing all methods and other context indide class. If
283 * typedef or classic method decl is found. Transitions inside it are beiing founded.
285 void methods_in_class(const Decl *decl, const string state)
287 string output, line, ret, trans, event;
288 llvm::raw_string_ostream x(output);
290 const TagDecl *tagDecl = dyn_cast<TagDecl>(decl);
291 const DeclContext *declCont = tagDecl->castToDeclContext(tagDecl);
293 for (DeclContext::decl_iterator i = declCont->decls_begin(), e = declCont->decls_end(); i != e; ++i)
295 if (i->getKind()==26) // typedefs
299 line = clean_spaces(cut_type(output));
300 ret = find_transitions(state,line);
303 num = count(ret,';')+1;
304 for(int i = 0;i<num;i++)
311 if(pos==-1) cReactions.push_back(ret);
312 else cReactions.push_back(ret.substr(0,pos));
317 if(pos==-1) transitions.push_back(ret);
318 else transitions.push_back(ret.substr(0,pos));
320 if(i!=num-1) ret = ret.substr(pos+1);
325 if(i->getKind()==35) method_decl(decl);// C++ method
330 * Traverse Method declaration using classes Stmt.
332 void method_decl(const Decl *decl)
334 string output, line, event;
335 llvm::raw_string_ostream x(output);
339 line = get_return(x.str());
340 if(test_model(line,"result"))
342 const FunctionDecl *fDecl = dyn_cast<FunctionDecl>(decl);
343 const ParmVarDecl *pvd = fDecl->getParamDecl(0);
344 QualType qt = pvd->getOriginalType();
345 event = qt.getAsString();
346 if(event[event.length()-1]=='&') event = event.substr(0,event.length()-2);
347 event = event.substr(event.rfind(" ")+1);
348 line = dyn_cast<NamedDecl>(decl)->getQualifiedNameAsString();
349 line = cut_namespaces(line.substr(0,line.rfind("::")));
352 find_return_stmt(decl->getBody(),line);
353 for(list<string>::iterator i = cReactions.begin();i!=cReactions.end();i++) // erase info about it from list of custom reactions
356 if(line.compare(event)==0)
366 void find_return_stmt(Stmt *statemt,string event) /** Traverse all statements in function for finding return Statement*/
368 if(statemt->getStmtClass() == 99) test_stmt(dyn_cast<CaseStmt>(statemt)->getSubStmt(), event);
371 for (Stmt::child_range range = statemt->children(); range; ++range)
373 test_stmt(*range, event);
378 void test_stmt(Stmt *stmt, string event) /** test statement for its kind*/
380 const SourceManager &sman = fsloc->getManager();
383 type = stmt->getStmtClass();
386 case 8 : find_return_stmt(dyn_cast<DoStmt>(stmt)->getBody(), event); // do
388 case 86 : find_return_stmt(dyn_cast<ForStmt>(stmt)->getBody(), event); // for
390 case 88 : find_return_stmt(dyn_cast<IfStmt>(stmt)->getThen(), event); //if then
391 find_return_stmt(dyn_cast<IfStmt>(stmt)->getElse(), event); //if else
393 case 90 : find_return_stmt(dyn_cast<LabelStmt>(stmt)->getSubStmt(), event); //label
395 case 98 : line = sman.getCharacterData(dyn_cast<ReturnStmt>(stmt)->getReturnLoc());
396 line = get_line_of_code(line).substr(6);
397 line = line.substr(0,line.find("("));
398 if(test_model(line,"transit"))
400 param = get_params(line);
401 transitions.push_back(event.append(",").append(param));
404 case 99 : find_return_stmt(stmt, event);
406 case 101 : find_return_stmt(dyn_cast<SwitchStmt>(stmt)->getBody(), event); // switch
408 case 102 : find_return_stmt(dyn_cast<WhileStmt>(stmt)->getBody(), event); // while
415 * Main function provides all initialization before starting analysis of AST. Diagnostic Client is initialized,
416 * Command line options are processed.
418 int main(int argc, char **argv)
420 string inputFilename = "";
421 string outputFilename = "graph.dot"; // initialize output Filename
422 DiagnosticOptions dopts;
424 MyDiagnosticClient *mdc = new MyDiagnosticClient(llvm::errs(), dopts);
425 llvm::IntrusiveRefCntPtr<DiagnosticIDs> dis(new DiagnosticIDs());
426 Diagnostic diag(dis,mdc);
427 FileManager fm( * new FileSystemOptions());
428 SourceManager sm (diag, fm);
429 HeaderSearch *headers = new HeaderSearch(fm);
431 Driver TheDriver(LLVM_BINDIR, llvm::sys::getHostTriple(), "", false, false, diag);
432 TheDriver.setCheckInputsExist(true);
433 TheDriver.CCCIsCXX = 1;
434 TheDriver.ResourceDir = LLVM_PREFIX "/lib/clang/" CLANG_VERSION_STRING;
436 CompilerInvocation compInv;
437 llvm::SmallVector<const char *, 16> Args(argv, argv + argc);
438 llvm::OwningPtr<Compilation> C(TheDriver.BuildCompilation(Args.size(),
440 const driver::JobList &Jobs = C->getJobs();
441 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
442 const driver::ArgStringList &CCArgs = Cmd->getArguments();
443 for(unsigned i = 0; i<Args.size();i++) // find -o in ArgStringList
445 if(strncmp(Args[i],"-o",2)==0)
447 if(strlen(Args[i])>2)
449 string str = Args[i];
450 outputFilename = str.substr(2);
452 else outputFilename = Args[i+1];
457 CompilerInvocation::CreateFromArgs(compInv,
458 const_cast<const char **>(CCArgs.data()),
459 const_cast<const char **>(CCArgs.data())+CCArgs.size(),
462 HeaderSearchOptions hsopts = compInv.getHeaderSearchOpts();
463 LangOptions lang = compInv.getLangOpts();
464 CompilerInvocation::setLangDefaults(lang, IK_ObjCXX);
465 TargetInfo *ti = TargetInfo::CreateTargetInfo(diag, compInv.getTargetOpts());
466 FrontendOptions f = compInv.getFrontendOpts();
467 inputFilename = f.Inputs[0].second;
469 cout<<"Input filename: "<<inputFilename<<"\n"; // print Input filename
470 cout<<"Output filename: "<<outputFilename<<"\n"; // print Output filename
473 Preprocessor pp(diag, lang, *ti, sm, *headers);
474 pp.getBuiltinInfo().InitializeBuiltins(pp.getIdentifierTable(), lang);
476 InitializePreprocessor(pp, compInv.getPreprocessorOpts(),hsopts,f);
478 const FileEntry *file = fm.getFile(inputFilename);
479 sm.createMainFileID(file);
480 IdentifierTable tab(lang);
481 Builtin::Context builtins(*ti);
483 ASTContext ctx(lang, sm, *ti, tab, * new SelectorTable(), builtins,0);
484 mdc->BeginSourceFile(lang, &pp);//start using diagnostic
485 ParseAST(pp, &c, ctx, false, false);
486 mdc->EndSourceFile(); //end using diagnostic
487 IO_operations *io = new IO_operations(outputFilename, c.getStateMachine(), c.getNameOfFirstState(), c.getTransitions(), c.getStates(), c.getEvents());