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
54 MyDiagnosticClient(llvm::raw_ostream &os, const DiagnosticOptions &diags, bool OwnsOutputStream = false):TextDiagnosticPrinter(os, diags, OwnsOutputStream = false){}
55 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel, const DiagnosticInfo &Info)
57 TextDiagnosticPrinter::HandleDiagnostic(DiagLevel, Info); // print diagnostic information
58 if(DiagLevel > 2) // if error/fatal error stop the program
65 class FindStates : public ASTConsumer
67 list<string> transitions;
68 list<string> cReactions;
71 string name_of_machine;
77 list<string> getStates()
82 list<string> getTransitions()
87 list<string> getEvents()
92 string getStateMachine()
94 return name_of_machine;
97 string getNameOfFirstState()
102 virtual void Initialize(ASTContext &ctx)//run after the AST is constructed before the consumer starts to work
104 fsloc = new FullSourceLoc(* new SourceLocation(), ctx.getSourceManager());
106 name_of_machine = "";
109 virtual void HandleTopLevelDecl(DeclGroupRef DGR)// traverse all top level declarations
112 string line, output, event;
113 llvm::raw_string_ostream x(output);
114 for (DeclGroupRef::iterator i = DGR.begin(), e = DGR.end(); i != e; ++i)
116 const Decl *decl = *i;
117 loc = decl->getLocation();
120 //cout<<decl->getKind()<<"ss\n";
121 if(decl->getKind()==35)
125 if (const TagDecl *tagDecl = dyn_cast<TagDecl>(decl))
127 if(tagDecl->isStruct() || tagDecl->isClass()) //is it a struct or class
132 if(const NamespaceDecl *namespaceDecl = dyn_cast<NamespaceDecl>(decl))
135 DeclContext *declCont = namespaceDecl->castToDeclContext(namespaceDecl);
136 //cout<<namedDecl->getNameAsString()<<" sss\n";
137 recursive_visit(declCont);
144 void recursive_visit(const DeclContext *declCont) //recursively visit all decls hidden inside namespaces
146 string line, output, event;
147 llvm::raw_string_ostream x(output);
149 for (DeclContext::decl_iterator i = declCont->decls_begin(), e = declCont->decls_end(); i != e; ++i)
151 const Decl *decl = *i;
152 //std::cout<<"a "<<decl->getDeclKindName()<<"\n";
153 loc = decl->getLocation();
156 if(decl->getKind()==35)
160 else if (const TagDecl *tagDecl = dyn_cast<TagDecl>(decl))
162 if(tagDecl->isStruct() || tagDecl->isClass()) //is it a structure or class
167 else if(const NamespaceDecl *namespaceDecl = dyn_cast<NamespaceDecl>(decl))
169 DeclContext *declCont = namespaceDecl->castToDeclContext(namespaceDecl);
170 //cout<<namedDecl->getNameAsString()<<" sss\n";
171 recursive_visit(declCont);
178 void struct_class(const Decl *decl) // works with struct or class decl
180 string output, line, ret, trans, event;
181 llvm::raw_string_ostream x(output);
183 line = get_line_of_code(x.str());
186 const NamedDecl *namedDecl = dyn_cast<NamedDecl>(decl);
189 const CXXRecordDecl *cRecDecl = dyn_cast<CXXRecordDecl>(decl);
191 if(find_events(cRecDecl, line))
193 events.push_back(namedDecl->getNameAsString());
194 cout<<"New event: "<<namedDecl->getNameAsString()<<"\n";
196 else if(name_of_machine == "")
198 ret = find_name_of_machine(cRecDecl, line);
202 name_of_machine = ret.substr(0,pos);
203 name_of_start = ret.substr(pos+1);
204 cout<<"Name of the state machine: "<<name_of_machine<<"\n";
205 cout<<"Name of the first state: "<<name_of_start<<"\n";
210 ret = find_states(cRecDecl, line);
213 cout << "New state: " << namedDecl->getNameAsString() << "\n";
214 states.push_back(ret);
215 methods_in_class(decl,namedDecl->getNameAsString());
221 void methods_in_class(const Decl *decl, const string state)
223 string output, line, ret, trans, event;
224 llvm::raw_string_ostream x(output);
226 const TagDecl *tagDecl = dyn_cast<TagDecl>(decl);
227 const DeclContext *declCont = tagDecl->castToDeclContext(tagDecl);
228 //states.push_back(namedDecl->getNameAsString());
231 for (DeclContext::decl_iterator i = declCont->decls_begin(), e = declCont->decls_end(); i != e; ++i)
233 if (i->getKind()==26)
237 line = clean_spaces(cut_type(output));
238 ret = find_transitions(state,line);
241 num = count(ret,';')+1;
242 for(int i = 0;i<num;i++)
249 if(pos==-1) cReactions.push_back(ret);
250 else cReactions.push_back(ret.substr(0,pos));
255 if(pos==-1) transitions.push_back(ret);
256 else transitions.push_back(ret.substr(0,pos));
259 if(i!=num-1) ret = ret.substr(pos+1);
264 if(i->getKind()==35) method_decl(decl);
268 void method_decl(const Decl *decl)
270 string output, line, event;
271 llvm::raw_string_ostream x(output);
275 line = get_return(x.str());
276 if(test_model(line,"result"))
278 const FunctionDecl *fDecl = dyn_cast<FunctionDecl>(decl);
279 const ParmVarDecl *pvd = fDecl->getParamDecl(0);
280 QualType qt = pvd->getOriginalType();
281 event = qt.getAsString();
282 if(event[event.length()-1]=='&') event = event.substr(0,event.length()-2);
283 event = event.substr(event.rfind(" ")+1);
284 line = dyn_cast<NamedDecl>(decl)->getQualifiedNameAsString();
285 line = cut_namespaces(line.substr(0,line.rfind("::")));
288 find_return_stmt(decl->getBody(),line);
289 for(list<string>::iterator i = cReactions.begin();i!=cReactions.end();i++)
292 if(line.compare(event)==0)
302 void find_return_stmt(Stmt *statemt,string event)
304 if(statemt->getStmtClass() == 99) test_stmt(dyn_cast<CaseStmt>(statemt)->getSubStmt(), event);
307 for (Stmt::child_range range = statemt->children(); range; ++range)
309 test_stmt(*range, event);
314 void test_stmt(Stmt *stmt, string event)
316 const SourceManager &sman = fsloc->getManager();
319 type = stmt->getStmtClass();
322 case 8 : find_return_stmt(dyn_cast<DoStmt>(stmt)->getBody(), event); // do
324 case 86 : find_return_stmt(dyn_cast<ForStmt>(stmt)->getBody(), event); // for
326 case 88 : find_return_stmt(dyn_cast<IfStmt>(stmt)->getThen(), event); //if then
327 find_return_stmt(dyn_cast<IfStmt>(stmt)->getElse(), event); //if else
329 case 90 : find_return_stmt(dyn_cast<LabelStmt>(stmt)->getSubStmt(), event); //label
331 case 98 : line = sman.getCharacterData(dyn_cast<ReturnStmt>(stmt)->getReturnLoc());
332 line = get_line_of_code(line).substr(6);
333 line = line.substr(0,line.find("("));
334 if(test_model(line,"transit"))
336 param = get_params(line);
337 transitions.push_back(event.append(",").append(param));
340 case 99 : find_return_stmt(stmt, event);
342 case 101 : find_return_stmt(dyn_cast<SwitchStmt>(stmt)->getBody(), event); // switch
344 case 102 : find_return_stmt(dyn_cast<WhileStmt>(stmt)->getBody(), event); // while
351 int main(int argc, char **argv)
353 string inputFilename = "";
354 string outputFilename = "graph.dot"; // initialize output Filename
355 DiagnosticOptions dopts;
357 MyDiagnosticClient *mdc = new MyDiagnosticClient(llvm::errs(), dopts);
358 llvm::IntrusiveRefCntPtr<DiagnosticIDs> dis(new DiagnosticIDs());
359 Diagnostic diag(dis,mdc);
360 FileManager fm( * new FileSystemOptions());
361 SourceManager sm (diag, fm);
362 HeaderSearch *headers = new HeaderSearch(fm);
364 Driver TheDriver(LLVM_BINDIR, llvm::sys::getHostTriple(), "", false, false, diag);
365 TheDriver.setCheckInputsExist(true);
366 TheDriver.CCCIsCXX = 1;
367 TheDriver.ResourceDir = LLVM_PREFIX "/lib/clang/" CLANG_VERSION_STRING;
369 CompilerInvocation compInv;
370 llvm::SmallVector<const char *, 16> Args(argv, argv + argc);
371 llvm::OwningPtr<Compilation> C(TheDriver.BuildCompilation(Args.size(),
373 const driver::JobList &Jobs = C->getJobs();
374 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
375 const driver::ArgStringList &CCArgs = Cmd->getArguments();
376 for(unsigned i = 0; i<Args.size();i++) // find -o in ArgStringList
378 if(strncmp(Args[i],"-o",2)==0)
380 if(strlen(Args[i])>2)
382 string str = Args[i];
383 outputFilename = str.substr(2);
385 else outputFilename = Args[i+1];
390 CompilerInvocation::CreateFromArgs(compInv,
391 const_cast<const char **>(CCArgs.data()),
392 const_cast<const char **>(CCArgs.data())+CCArgs.size(),
395 HeaderSearchOptions hsopts = compInv.getHeaderSearchOpts();
396 LangOptions lang = compInv.getLangOpts();
397 CompilerInvocation::setLangDefaults(lang, IK_ObjCXX);
398 TargetInfo *ti = TargetInfo::CreateTargetInfo(diag, compInv.getTargetOpts());
399 FrontendOptions f = compInv.getFrontendOpts();
400 inputFilename = f.Inputs[0].second;
402 cout<<"Input filename: "<<inputFilename<<"\n"; // print Input filename
403 cout<<"Output filename: "<<outputFilename<<"\n"; // print Output filename
406 Preprocessor pp(diag, lang, *ti, sm, *headers);
407 pp.getBuiltinInfo().InitializeBuiltins(pp.getIdentifierTable(), lang);
409 InitializePreprocessor(pp, compInv.getPreprocessorOpts(),hsopts,f);
411 const FileEntry *file = fm.getFile(inputFilename);
412 sm.createMainFileID(file);
413 IdentifierTable tab(lang);
414 Builtin::Context builtins(*ti);
416 ASTContext ctx(lang, sm, *ti, tab, * new SelectorTable(), builtins,0);
417 mdc->BeginSourceFile(lang, &pp);//start using diagnostic
418 ParseAST(pp, &c, ctx, false, false);
419 mdc->EndSourceFile(); //end using diagnostic
420 IO_operations *io = new IO_operations(outputFilename, c.getStateMachine(), c.getNameOfFirstState(), c.getTransitions(), c.getStates(), c.getEvents());