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;
51 class MyDiagnosticClient : public TextDiagnosticPrinter // My diagnostic Client
58 MyDiagnosticClient(llvm::raw_ostream &os, const DiagnosticOptions &diags, bool OwnsOutputStream = false):TextDiagnosticPrinter(os, diags, OwnsOutputStream = false)
65 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel, const DiagnosticInfo &Info)
67 TextDiagnosticPrinter::HandleDiagnostic(DiagLevel, Info); // print diagnostic information
70 case 0 : nignored+=1; break;
71 case 1 : nnotes+=1; break;
72 case 2 : nwarnings+=1; break;
81 cout<<"\n--Diagnostic Info--\n";
82 cout<<"Number of ignored: "<<nignored<<"\n";
83 cout<<"Number of notes: "<<nnotes<<"\n";
84 cout<<"Number of warnings: "<<nwarnings<<"\n";
85 cout<<"Number of errors and fatal errors: "<<nerrors<<"\n";
88 int getNbrOfWarnings()
104 class FindStates : public ASTConsumer
106 list<string> transitions;
107 list<string> cReactions;
110 string name_of_machine;
111 string name_of_start;
112 FullSourceLoc *fsloc;
116 list<string> getStates()
121 list<string> getTransitions()
126 list<string> getEvents()
131 string getStateMachine()
133 return name_of_machine;
136 string getNameOfFirstState()
138 return name_of_start;
141 virtual void Initialize(ASTContext &ctx)//run after the AST is constructed before the consumer starts to work
143 fsloc = new FullSourceLoc(* new SourceLocation(), ctx.getSourceManager());
145 name_of_machine = "";
148 virtual void HandleTopLevelDecl(DeclGroupRef DGR)// traverse all top level declarations
151 string line, output, event;
152 llvm::raw_string_ostream x(output);
153 for (DeclGroupRef::iterator i = DGR.begin(), e = DGR.end(); i != e; ++i)
155 const Decl *decl = *i;
156 loc = decl->getLocation();
159 //cout<<decl->getKind()<<"ss\n";
160 if(decl->getKind()==35)
164 if (const TagDecl *tagDecl = dyn_cast<TagDecl>(decl))
166 if(tagDecl->isStruct() || tagDecl->isClass()) //is it a struct or class
171 if(const NamespaceDecl *namespaceDecl = dyn_cast<NamespaceDecl>(decl))
174 DeclContext *declCont = namespaceDecl->castToDeclContext(namespaceDecl);
175 //cout<<namedDecl->getNameAsString()<<" sss\n";
176 recursive_visit(declCont);
183 void recursive_visit(const DeclContext *declCont) //recursively visit all decls hidden inside namespaces
185 string line, output, event;
186 llvm::raw_string_ostream x(output);
188 for (DeclContext::decl_iterator i = declCont->decls_begin(), e = declCont->decls_end(); i != e; ++i)
190 const Decl *decl = *i;
191 //std::cout<<"a "<<decl->getDeclKindName()<<"\n";
192 loc = decl->getLocation();
195 if(decl->getKind()==35)
199 else if (const TagDecl *tagDecl = dyn_cast<TagDecl>(decl))
201 if(tagDecl->isStruct() || tagDecl->isClass()) //is it a structure or class
206 else if(const NamespaceDecl *namespaceDecl = dyn_cast<NamespaceDecl>(decl))
208 DeclContext *declCont = namespaceDecl->castToDeclContext(namespaceDecl);
209 //cout<<namedDecl->getNameAsString()<<" sss\n";
210 recursive_visit(declCont);
217 void struct_class(const Decl *decl) // works with struct or class decl
219 string output, line, ret, trans, event;
220 llvm::raw_string_ostream x(output);
222 line = get_line_of_code(x.str());
225 const NamedDecl *namedDecl = dyn_cast<NamedDecl>(decl);
228 const CXXRecordDecl *cRecDecl = dyn_cast<CXXRecordDecl>(decl);
230 if(find_events(cRecDecl, line))
232 events.push_back(namedDecl->getNameAsString());
233 cout<<"New event: "<<namedDecl->getNameAsString()<<"\n";
235 else if(name_of_machine == "")
237 ret = find_name_of_machine(cRecDecl, line);
241 name_of_machine = ret.substr(0,pos);
242 name_of_start = ret.substr(pos+1);
243 cout<<"Name of the state machine: "<<name_of_machine<<"\n";
244 cout<<"Name of the first state: "<<name_of_start<<"\n";
249 ret = find_states(cRecDecl, line);
252 cout << "New state: " << namedDecl->getNameAsString() << "\n";
253 states.push_back(ret);
254 methods_in_class(decl,namedDecl->getNameAsString());
260 void methods_in_class(const Decl *decl, const string state)
262 string output, line, ret, trans, event;
263 llvm::raw_string_ostream x(output);
265 const TagDecl *tagDecl = dyn_cast<TagDecl>(decl);
266 const DeclContext *declCont = tagDecl->castToDeclContext(tagDecl);
267 //states.push_back(namedDecl->getNameAsString());
270 for (DeclContext::decl_iterator i = declCont->decls_begin(), e = declCont->decls_end(); i != e; ++i)
272 if (i->getKind()==26)
276 line = clean_spaces(cut_type(output));
277 ret = find_transitions(state,line);
280 num = count(ret,';')+1;
281 for(int i = 0;i<num;i++)
288 if(pos==-1) cReactions.push_back(ret);
289 else cReactions.push_back(ret.substr(0,pos));
294 if(pos==-1) transitions.push_back(ret);
295 else transitions.push_back(ret.substr(0,pos));
298 if(i!=num-1) ret = ret.substr(pos+1);
303 if(i->getKind()==35) method_decl(decl);
307 void method_decl(const Decl *decl)
309 string output, line, event;
310 llvm::raw_string_ostream x(output);
314 line = get_return(x.str());
315 if(test_model(line,"result"))
317 const FunctionDecl *fDecl = dyn_cast<FunctionDecl>(decl);
318 const ParmVarDecl *pvd = fDecl->getParamDecl(0);
319 QualType qt = pvd->getOriginalType();
320 event = qt.getAsString();
321 if(event[event.length()-1]=='&') event = event.substr(0,event.length()-2);
322 event = event.substr(event.rfind(" ")+1);
323 line = dyn_cast<NamedDecl>(decl)->getQualifiedNameAsString();
324 line = cut_namespaces(line.substr(0,line.rfind("::")));
327 find_return_stmt(decl->getBody(),line);
328 for(list<string>::iterator i = cReactions.begin();i!=cReactions.end();i++)
331 if(line.compare(event)==0)
341 void find_return_stmt(Stmt *statemt,string event)
343 if(statemt->getStmtClass() == 99) test_stmt(dyn_cast<CaseStmt>(statemt)->getSubStmt(), event);
346 for (Stmt::child_range range = statemt->children(); range; ++range)
348 test_stmt(*range, event);
353 void test_stmt(Stmt *stmt, string event)
355 const SourceManager &sman = fsloc->getManager();
358 type = stmt->getStmtClass();
361 case 8 : find_return_stmt(dyn_cast<DoStmt>(stmt)->getBody(), event); // do
363 case 86 : find_return_stmt(dyn_cast<ForStmt>(stmt)->getBody(), event); // for
365 case 88 : find_return_stmt(dyn_cast<IfStmt>(stmt)->getThen(), event); //if then
366 find_return_stmt(dyn_cast<IfStmt>(stmt)->getElse(), event); //if else
368 case 90 : find_return_stmt(dyn_cast<LabelStmt>(stmt)->getSubStmt(), event); //label
370 case 98 : line = sman.getCharacterData(dyn_cast<ReturnStmt>(stmt)->getReturnLoc());
371 line = get_line_of_code(line).substr(6);
372 line = line.substr(0,line.find("("));
373 if(test_model(line,"transit"))
375 param = get_params(line);
376 transitions.push_back(event.append(",").append(param));
379 case 99 : find_return_stmt(stmt, event);
381 case 101 : find_return_stmt(dyn_cast<SwitchStmt>(stmt)->getBody(), event); // switch
383 case 102 : find_return_stmt(dyn_cast<WhileStmt>(stmt)->getBody(), event); // while
390 int main(int argc, char **argv)
392 string inputFilename = "";
393 string outputFilename = "graph.dot"; // initialize output Filename
394 DiagnosticOptions dopts;
396 MyDiagnosticClient *mdc = new MyDiagnosticClient(llvm::errs(), dopts);
397 llvm::IntrusiveRefCntPtr<DiagnosticIDs> dis(new DiagnosticIDs());
398 Diagnostic diag(dis,mdc);
399 FileManager fm( * new FileSystemOptions());
400 SourceManager sm (diag, fm);
401 HeaderSearch *headers = new HeaderSearch(fm);
403 Driver TheDriver(LLVM_BINDIR, llvm::sys::getHostTriple(), "", false, false, diag);
404 TheDriver.setCheckInputsExist(true);
405 TheDriver.CCCIsCXX = 1;
406 TheDriver.ResourceDir = LLVM_PREFIX "/lib/clang/" CLANG_VERSION_STRING;
408 CompilerInvocation compInv;
409 llvm::SmallVector<const char *, 16> Args(argv, argv + argc);
410 llvm::OwningPtr<Compilation> C(TheDriver.BuildCompilation(Args.size(),
412 const driver::JobList &Jobs = C->getJobs();
413 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
414 const driver::ArgStringList &CCArgs = Cmd->getArguments();
415 for(unsigned i = 0; i<Args.size();i++) // find -o in ArgStringList
417 if(strncmp(Args[i],"-o",2)==0)
419 if(strlen(Args[i])>2)
421 string str = Args[i];
422 outputFilename = str.substr(2);
424 else outputFilename = Args[i+1];
429 CompilerInvocation::CreateFromArgs(compInv,
430 const_cast<const char **>(CCArgs.data()),
431 const_cast<const char **>(CCArgs.data())+CCArgs.size(),
434 HeaderSearchOptions hsopts = compInv.getHeaderSearchOpts();
435 LangOptions lang = compInv.getLangOpts();
436 CompilerInvocation::setLangDefaults(lang, IK_ObjCXX);
437 TargetInfo *ti = TargetInfo::CreateTargetInfo(diag, compInv.getTargetOpts());
438 FrontendOptions f = compInv.getFrontendOpts();
439 inputFilename = f.Inputs[0].second;
441 cout<<"Input filename: "<<inputFilename<<"\n"; // print Input filename
442 cout<<"Output filename: "<<outputFilename<<"\n"; // print Output filename
445 Preprocessor pp(diag, lang, *ti, sm, *headers);
446 pp.getBuiltinInfo().InitializeBuiltins(pp.getIdentifierTable(), lang);
448 InitializePreprocessor(pp, compInv.getPreprocessorOpts(),hsopts,f);
450 const FileEntry *file = fm.getFile(inputFilename);
451 sm.createMainFileID(file);
452 IdentifierTable tab(lang);
453 Builtin::Context builtins(*ti);
455 ASTContext ctx(lang, sm, *ti, tab, * new SelectorTable(), builtins,0);
456 mdc->BeginSourceFile(lang, &pp);//start using diagnostic
457 ParseAST(pp, &c, ctx, false, false);
458 mdc->EndSourceFile(); //end using diagnostic
459 IO_operations *io = new IO_operations(outputFilename, c.getStateMachine(), c.getNameOfFirstState(), c.getTransitions(), c.getStates(), c.getEvents());