]> rtime.felk.cvut.cz Git - boost-statechart-viewer.git/blob - src/visualizer.cpp
0c7b7f74de2af76f125501c744a3e9c8a0f6506f
[boost-statechart-viewer.git] / src / visualizer.cpp
1
2 ////////////////////////////////////////////////////////////////////////////////////////  
3 //    
4 //    This file is part of Boost Statechart Viewer.
5 //
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.
10 //
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.
15 //
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/>.
18 //
19 ////////////////////////////////////////////////////////////////////////////////////////
20
21 //standard header files
22 #include <iostream>
23
24 //LLVM Header files
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Support/Host.h"
27 #include "llvm/Config/config.h"
28
29 //clang header files
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"
43
44 //my own header files
45 #include "iooper.h"
46
47 using namespace clang;
48 using namespace clang::driver;
49 using namespace std;
50
51 class MyDiagnosticClient : public TextDiagnosticPrinter // My diagnostic Client
52 {
53         int nwarnings;
54         int nnotes;
55         int nignored;
56         public:
57         MyDiagnosticClient(llvm::raw_ostream &os, const DiagnosticOptions &diags, bool OwnsOutputStream = false):TextDiagnosticPrinter(os, diags, OwnsOutputStream = false)
58         {
59                 nwarnings=0;
60                 nnotes=0;
61                 nignored=0;
62         }
63         virtual void HandleDiagnostic(Diagnostic::Level DiagLevel, const DiagnosticInfo &Info)
64         {
65                 TextDiagnosticPrinter::HandleDiagnostic(DiagLevel, Info); // print diagnostic information
66                 switch (DiagLevel)
67                 {
68                         case 0 : nignored+=1; break;
69                         case 1 : nnotes+=1; break;
70                         case 2 : nwarnings+=1; break;
71                         default : print_stats(); exit(1);
72                 }
73         }
74         
75         void print_stats()
76         {
77                 cout<<"\n--Diagnostic Info--\n";
78                 cout<<"Number of ignored: "<<nignored<<"\n";
79                 cout<<"Number of notes: "<<nnotes<<"\n";
80                 cout<<"Number of warnings: "<<nwarnings<<"\n";
81                 cout<<"Number of errors and fatal errors: "<<1<<"\n";
82         }
83         
84         int getNbrOfWarnings()
85         {
86                 return nwarnings;               
87         }
88         
89         int getNbrOfNotes()
90         {
91                 return nnotes;          
92         }
93
94         int getNbrOfIgnored()
95         {
96                 return nignored;                
97         }
98 };
99
100 class FindStates : public ASTConsumer
101 {
102         list<string> transitions;
103         list<string> cReactions;
104         list<string> events;
105         list<string> states;
106         string name_of_machine;
107         string name_of_start;
108         FullSourceLoc *fsloc;
109         
110         public:
111
112         list<string> getStates()
113         {
114                 return states;
115         }
116         
117         list<string> getTransitions()
118         {
119                 return transitions;
120         }
121                 
122         list<string> getEvents()
123         {
124                 return events;
125         }
126
127         string getStateMachine()
128         {
129                 return name_of_machine;
130         }
131
132         string getNameOfFirstState()
133         {
134                 return name_of_start;
135         }
136         
137         virtual void Initialize(ASTContext &ctx)//run after the AST is constructed before the consumer starts to work
138         {       
139                 fsloc = new FullSourceLoc(* new SourceLocation(), ctx.getSourceManager());
140                 name_of_start = "";
141                 name_of_machine = "";
142         }
143
144         virtual void HandleTopLevelDecl(DeclGroupRef DGR)// traverse all top level declarations
145         {
146                 SourceLocation loc;
147       string line, output, event;
148                 llvm::raw_string_ostream x(output);
149                 for (DeclGroupRef::iterator i = DGR.begin(), e = DGR.end(); i != e; ++i) 
150                 {
151                         const Decl *decl = *i;
152                         loc = decl->getLocation();
153                         if(loc.isValid())
154                         {
155                                 //cout<<decl->getKind()<<"ss\n";
156                                 if(decl->getKind()==35)
157                                 {                                       
158                                         method_decl(decl);
159                                 }
160                                 if (const TagDecl *tagDecl = dyn_cast<TagDecl>(decl))
161                                 {
162                                         if(tagDecl->isStruct() || tagDecl->isClass()) //is it a struct or class 
163                                         {
164                                                 struct_class(decl);
165                                         }
166                                 }       
167                                 if(const NamespaceDecl *namespaceDecl = dyn_cast<NamespaceDecl>(decl))
168                                 {
169                                         
170                                         DeclContext *declCont = namespaceDecl->castToDeclContext(namespaceDecl);
171                                         //cout<<namedDecl->getNameAsString()<<"   sss\n";
172                                         recursive_visit(declCont);
173                                 
174                                 }
175                         }
176                         output = "";
177                 }
178         }
179         void recursive_visit(const DeclContext *declCont) //recursively visit all decls hidden inside namespaces
180         {
181       string line, output, event;
182                 llvm::raw_string_ostream x(output);
183                 SourceLocation loc;
184                 for (DeclContext::decl_iterator i = declCont->decls_begin(), e = declCont->decls_end(); i != e; ++i)
185                 {
186                         const Decl *decl = *i;
187                         //std::cout<<"a "<<decl->getDeclKindName()<<"\n";
188                         loc = decl->getLocation();
189                         if(loc.isValid())
190                         {       
191                                 if(decl->getKind()==35)
192                                 {
193                                         method_decl(decl);
194                                 }
195                                 else if (const TagDecl *tagDecl = dyn_cast<TagDecl>(decl))
196                                 {
197                                         if(tagDecl->isStruct() || tagDecl->isClass()) //is it a structure or class      
198                                         {
199                                                 struct_class(decl);
200                                         }       
201                                 }
202                                 else if(const NamespaceDecl *namespaceDecl = dyn_cast<NamespaceDecl>(decl))
203                                 {
204                                         DeclContext *declCont = namespaceDecl->castToDeclContext(namespaceDecl);
205                                         //cout<<namedDecl->getNameAsString()<<"  sss\n";                        
206                                         recursive_visit(declCont);
207                                 }
208                         }
209                         output = "";
210                 } 
211         }
212                 
213         void struct_class(const Decl *decl) // works with struct or class decl
214         {
215                 string output, line, ret, trans, event; 
216                 llvm::raw_string_ostream x(output);
217                 decl->print(x);
218                 line = get_line_of_code(x.str());
219                 output = "";
220                 int pos;
221                 const NamedDecl *namedDecl = dyn_cast<NamedDecl>(decl);         
222                 if(is_derived(line))
223                 {
224                         const CXXRecordDecl *cRecDecl = dyn_cast<CXXRecordDecl>(decl);
225                                         
226                         if(find_events(cRecDecl, line))
227                         {
228                                 events.push_back(namedDecl->getNameAsString());
229                                 cout<<"New event: "<<namedDecl->getNameAsString()<<"\n";
230                         }
231                         else if(name_of_machine == "")
232                         {
233                                 ret = find_name_of_machine(cRecDecl, line);
234                                 if(!ret.empty())
235                                 {
236                                         pos = ret.find(",");
237                                         name_of_machine = ret.substr(0,pos);
238                                         name_of_start = ret.substr(pos+1);
239                                         cout<<"Name of the state machine: "<<name_of_machine<<"\n";
240                                         cout<<"Name of the first state: "<<name_of_start<<"\n";
241                                 }
242                         }
243                         else
244                         {
245                                 ret = find_states(cRecDecl, line);      
246                                 if(!ret.empty())
247                                 {       
248                                         cout << "New state: " << namedDecl->getNameAsString() << "\n";
249                                         states.push_back(ret);                  
250                                         methods_in_class(decl,namedDecl->getNameAsString());
251                                 }
252                         }
253                 }
254         }
255
256         void methods_in_class(const Decl *decl, const string state)
257         {
258                 string output, line, ret, trans, event; 
259                 llvm::raw_string_ostream x(output);
260                 int pos, num;
261                 const TagDecl *tagDecl = dyn_cast<TagDecl>(decl);
262                 const DeclContext *declCont = tagDecl->castToDeclContext(tagDecl);              
263                 //states.push_back(namedDecl->getNameAsString());
264                 
265                 output="";
266                 for (DeclContext::decl_iterator i = declCont->decls_begin(), e = declCont->decls_end(); i != e; ++i) 
267                 {
268                         if (i->getKind()==26) 
269                         {
270                                 i->print(x);
271                                 output = x.str();
272                                 line = clean_spaces(cut_type(output));          
273                                 ret = find_transitions(state,line);
274                                 if(!ret.empty()) 
275                                 {
276                                         num = count(ret,';')+1;
277                                         for(int i = 0;i<num;i++)
278                                         {
279                                                 pos = ret.find(";");
280                                                 if(pos == 0)
281                                                 {
282                                                         ret = ret.substr(1);
283                                                         pos = ret.find(";");
284                                                         if(pos==-1) cReactions.push_back(ret);
285                                                         else cReactions.push_back(ret.substr(0,pos));   
286                                                         num-=1;
287                                                 }
288                                                 else 
289                                                 {
290                                                         if(pos==-1) transitions.push_back(ret);
291                                                         else transitions.push_back(ret.substr(0,pos));
292                                                 }
293                                                 //cout<<ret<<"\n";
294                                                 if(i!=num-1) ret = ret.substr(pos+1);
295                                         }
296                                         output="";
297                                 }
298                         }
299                         if(i->getKind()==35) method_decl(decl);
300                 }
301         }
302
303         void method_decl(const Decl *decl)
304         {
305                 string output, line, event;     
306                 llvm::raw_string_ostream x(output);
307                 if(decl->hasBody())
308                 {
309                         decl->print(x);
310                         line = get_return(x.str());
311                         if(test_model(line,"result"))
312                         {
313                                 const FunctionDecl *fDecl = dyn_cast<FunctionDecl>(decl);
314                                 const ParmVarDecl *pvd = fDecl->getParamDecl(0);
315                                 QualType qt = pvd->getOriginalType();                           
316                                 event = qt.getAsString();
317                                 if(event[event.length()-1]=='&') event = event.substr(0,event.length()-2);
318                                 event = event.substr(event.rfind(" ")+1);
319                                 line = dyn_cast<NamedDecl>(decl)->getQualifiedNameAsString();
320                                 line = cut_namespaces(line.substr(0,line.rfind("::")));
321                                 line.append(",");
322                                 line.append(event);
323                                 find_return_stmt(decl->getBody(),line); 
324                                 for(list<string>::iterator i = cReactions.begin();i!=cReactions.end();i++)
325                                 {
326                                         event = *i;
327                                         if(line.compare(event)==0) 
328                                         {
329                                                 cReactions.erase(i);
330                                                 break;
331                                         }
332                                 }
333                         }
334                 }
335         }
336
337         void find_return_stmt(Stmt *statemt,string event)
338         {
339                 if(statemt->getStmtClass() == 99) test_stmt(dyn_cast<CaseStmt>(statemt)->getSubStmt(), event);
340                 else
341                 {
342                         for (Stmt::child_range range = statemt->children(); range; ++range)    
343                         {
344                                 test_stmt(*range, event);
345                         }
346                 }
347         }
348         
349         void test_stmt(Stmt *stmt, string event)
350         {
351                 const SourceManager &sman = fsloc->getManager();
352                 int type;
353                 string line, param;
354                 type = stmt->getStmtClass();
355                 switch(type)
356                 {       
357                         case 8 :                find_return_stmt(dyn_cast<DoStmt>(stmt)->getBody(), event); // do
358                                                         break;
359                         case 86 :       find_return_stmt(dyn_cast<ForStmt>(stmt)->getBody(), event); // for
360                                                         break;
361                         case 88 :   find_return_stmt(dyn_cast<IfStmt>(stmt)->getThen(), event); //if then
362                                                         find_return_stmt(dyn_cast<IfStmt>(stmt)->getElse(), event); //if else
363                                                         break;
364                         case 90 :       find_return_stmt(dyn_cast<LabelStmt>(stmt)->getSubStmt(), event); //label
365                                                         break;
366                         case 98 :       line = sman.getCharacterData(dyn_cast<ReturnStmt>(stmt)->getReturnLoc()); 
367                                                         line = get_line_of_code(line).substr(6);
368                                                         line = line.substr(0,line.find("("));
369                                                         if(test_model(line,"transit"))
370                                                         {
371                                                                 param = get_params(line);
372                                                                 transitions.push_back(event.append(",").append(param));
373                                                         }
374                                                         break;
375                         case 99 :       find_return_stmt(stmt, event);
376                                                         break;
377                         case 101 :      find_return_stmt(dyn_cast<SwitchStmt>(stmt)->getBody(), event); // switch
378                                                         break;
379                         case 102 :      find_return_stmt(dyn_cast<WhileStmt>(stmt)->getBody(), event); // while
380                                                         break;
381                 }
382         }
383
384 };
385
386 int main(int argc, char **argv)
387
388         string inputFilename = "";
389         string outputFilename = "graph.dot"; // initialize output Filename
390         DiagnosticOptions dopts;
391         dopts.ShowColors=1;
392         MyDiagnosticClient *mdc = new MyDiagnosticClient(llvm::errs(), dopts);
393         llvm::IntrusiveRefCntPtr<DiagnosticIDs> dis(new DiagnosticIDs());       
394         Diagnostic diag(dis,mdc);
395         FileManager fm( * new FileSystemOptions());
396         SourceManager sm (diag, fm);
397         HeaderSearch *headers = new HeaderSearch(fm);
398         
399         Driver TheDriver(LLVM_BINDIR, llvm::sys::getHostTriple(), "", false, false, diag);
400         TheDriver.setCheckInputsExist(true);
401         TheDriver.CCCIsCXX = 1; 
402         TheDriver.ResourceDir = LLVM_PREFIX "/lib/clang/" CLANG_VERSION_STRING;
403
404         CompilerInvocation compInv;
405         llvm::SmallVector<const char *, 16> Args(argv, argv + argc);
406         llvm::OwningPtr<Compilation> C(TheDriver.BuildCompilation(Args.size(),
407                                                             Args.data()));
408         const driver::JobList &Jobs = C->getJobs();
409         const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
410         const driver::ArgStringList &CCArgs = Cmd->getArguments();
411         for(unsigned i = 0; i<Args.size();i++) // find -o in ArgStringList
412         {       
413                 if(strncmp(Args[i],"-o",2)==0) 
414                 {
415                         if(strlen(Args[i])>2)
416                         {
417                                 string str = Args[i];
418                                 outputFilename = str.substr(2);
419                         }
420                         else outputFilename = Args[i+1];
421                         break;
422                 }
423         }
424                 
425         CompilerInvocation::CreateFromArgs(compInv,
426                                           const_cast<const char **>(CCArgs.data()),
427                                           const_cast<const char **>(CCArgs.data())+CCArgs.size(),
428                                           diag);
429
430         HeaderSearchOptions hsopts = compInv.getHeaderSearchOpts();
431         LangOptions lang = compInv.getLangOpts();
432         CompilerInvocation::setLangDefaults(lang, IK_ObjCXX);
433         TargetInfo *ti = TargetInfo::CreateTargetInfo(diag, compInv.getTargetOpts());
434         FrontendOptions f = compInv.getFrontendOpts();
435         inputFilename = f.Inputs[0].second;
436
437         cout<<"Input filename: "<<inputFilename<<"\n"; // print Input filename
438         cout<<"Output filename: "<<outputFilename<<"\n"; // print Output filename
439
440
441         Preprocessor pp(diag, lang, *ti, sm, *headers);
442         pp.getBuiltinInfo().InitializeBuiltins(pp.getIdentifierTable(), lang);
443                 
444         InitializePreprocessor(pp, compInv.getPreprocessorOpts(),hsopts,f);
445         
446         const FileEntry *file = fm.getFile(inputFilename);
447         sm.createMainFileID(file);
448         IdentifierTable tab(lang);
449         Builtin::Context builtins(*ti);
450         FindStates c;
451         ASTContext ctx(lang, sm, *ti, tab, * new SelectorTable(), builtins,0);
452         mdc->BeginSourceFile(lang, &pp);//start using diagnostic
453         ParseAST(pp, &c, ctx, false, false);
454         mdc->EndSourceFile(); //end using diagnostic
455         IO_operations *io = new IO_operations(outputFilename, c.getStateMachine(), c.getNameOfFirstState(), c.getTransitions(), c.getStates(), c.getEvents());  
456         io->save_to_file();
457         io->print_stats();
458         mdc->print_stats();
459         return 0;
460 }