]> rtime.felk.cvut.cz Git - boost-statechart-viewer.git/blob - src/visualizer.cpp
ea391489e0b3eb94b7c631651f622e150c4972ec
[boost-statechart-viewer.git] / src / visualizer.cpp
1 /** @file */
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 <iomanip>
23 #include <fstream>
24 #include <map>
25
26 //LLVM Header files
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Support/raw_os_ostream.h"
29
30 //clang header files
31 #include "clang/AST/ASTConsumer.h"
32 #include "clang/AST/ASTContext.h"
33 #include "clang/AST/CXXInheritance.h"
34 #include "clang/AST/RecursiveASTVisitor.h"
35 #include "clang/Frontend/CompilerInstance.h"
36 #include "clang/Frontend/FrontendPluginRegistry.h"
37
38 using namespace clang;
39 using namespace std;
40
41 namespace Model
42 {
43
44     inline int getIndentLevelIdx() {
45         static int i = ios_base::xalloc();
46         return i;
47     }
48
49     ostream& indent(ostream& os) { os << setw(2*os.iword(getIndentLevelIdx())) << ""; return os; }
50     ostream& indent_inc(ostream& os) { os.iword(getIndentLevelIdx())++; return os; }
51     ostream& indent_dec(ostream& os) { os.iword(getIndentLevelIdx())--; return os; }
52
53     class State;
54
55     class Context : public map<string, State*> {
56     public:
57         iterator add(State *state);
58         Context *findContext(const string &name);
59     };
60
61     class State : public Context
62     {
63         string initialInnerState;
64         list<string> defferedEvents;
65     public:
66         const string name;
67         explicit State(string name) : name(name) {}
68         void setInitialInnerState(string name) { initialInnerState = name; }
69         void addDeferredEvent(const string &name) { defferedEvents.push_back(name); }
70         friend ostream& operator<<(ostream& os, const State& s);
71     };
72
73
74     Context::iterator Context::add(State *state)
75     {
76         pair<iterator, bool> ret =  insert(value_type(state->name, state));
77         return ret.first;
78     }
79
80     Context *Context::findContext(const string &name)
81     {
82         iterator i = find(name), e;
83         if (i != end())
84             return i->second;
85         for (i = begin(), e = end(); i != e; ++i) {
86             Context *c = i->second->findContext(name);
87             if (c)
88                 return c;
89         }
90         return 0;
91     }
92
93     ostream& operator<<(ostream& os, const Context& c);
94
95     ostream& operator<<(ostream& os, const State& s)
96     {
97         string label = s.name;
98         for (list<string>::const_iterator i = s.defferedEvents.begin(), e = s.defferedEvents.end(); i != e; ++i)
99             label.append("<br />").append(*i).append(" / defer");
100         os << indent << s.name << " [label=<" << label << ">]\n";
101         if (s.size()) {
102             os << indent << s.name << " -> " << s.initialInnerState << " [style = dashed]\n";
103             os << indent << "subgraph cluster_" << s.name << " {\n" << indent_inc;
104             os << indent << "label = \"" << s.name << "\"\n";
105             os << indent << s.initialInnerState << " [peripheries=2]\n";
106             os << static_cast<Context>(s);
107             os << indent_dec << indent << "}\n";
108         }
109         return os;
110     }
111
112
113     ostream& operator<<(ostream& os, const Context& c)
114     {
115         for (Context::const_iterator i = c.begin(), e = c.end(); i != e; i++) {
116             os << *i->second;
117         }
118         return os;
119     }
120
121
122     class Transition
123     {
124     public:
125         const string src, dst, event;
126         Transition(string src, string dst, string event) : src(src), dst(dst), event(event) {}
127     };
128
129     ostream& operator<<(ostream& os, const Transition& t)
130     {
131         os << indent << t.src << " -> " << t.dst << " [label = \"" << t.event << "\"]\n";
132         return os;
133     }
134
135
136     class Machine : public Context
137     {
138     protected:
139         string initial_state;
140     public:
141         const string name;
142         explicit Machine(string name) : name(name) {}
143
144         void setInitialState(string name) { initial_state = name; }
145
146         friend ostream& operator<<(ostream& os, const Machine& m);
147     };
148
149     ostream& operator<<(ostream& os, const Machine& m)
150     {
151         os << indent << "subgraph " << m.name << " {\n" << indent_inc;
152         os << indent << m.initial_state << " [peripheries=2]\n";
153         os << static_cast<Context>(m);
154         os << indent_dec << indent << "}\n";
155         return os;
156     }
157
158
159     class Model : public map<string, Machine>
160     {
161         Context undefined;      // For forward-declared state classes
162     public:
163         list< Transition*> transitions;
164
165         iterator add(const Machine &m)
166         {
167             pair<iterator, bool> ret =  insert(value_type(m.name, m));
168             return ret.first;
169         }
170
171         void addUndefinedState(State *m)
172         {
173             undefined[m->name] = m;
174         }
175
176
177         Context *findContext(const string &name)
178         {
179             Context::iterator ci = undefined.find(name);
180             if (ci != undefined.end())
181                 return ci->second;
182             iterator i = find(name), e;
183             if (i != end())
184                 return &i->second;
185             for (i = begin(), e = end(); i != e; ++i) {
186                 Context *c = i->second.findContext(name);
187                 if (c)
188                     return c;
189             }
190             return 0;
191         }
192
193         State *findState(const string &name)
194         {
195             for (iterator i = begin(), e = end(); i != e; ++i) {
196                 Context *c = i->second.findContext(name);
197                 if (c)
198                     return static_cast<State*>(c);
199             }
200             return 0;
201         }
202
203
204         State *removeFromUndefinedContexts(const string &name)
205         {
206             Context::iterator ci = undefined.find(name);
207             if (ci == undefined.end())
208                 return 0;
209             undefined.erase(ci);
210             return ci->second;
211         }
212
213         void write_as_dot_file(string fn)
214         {
215             ofstream f(fn.c_str());
216             f << "digraph statecharts {\n" << indent_inc;
217             for (iterator i = begin(), e = end(); i != e; i++)
218                 f << i->second;
219             for (list<Transition*>::iterator t = transitions.begin(), e = transitions.end(); t != e; ++t)
220                 f << **t;
221             f << indent_dec << "}\n";
222         }
223     };
224 };
225
226
227 class MyCXXRecordDecl : public CXXRecordDecl
228 {
229     static bool FindBaseClassString(const CXXBaseSpecifier *Specifier,
230                                     CXXBasePath &Path,
231                                     void *qualName)
232     {
233         string qn(static_cast<const char*>(qualName));
234         const RecordType *rt = Specifier->getType()->getAs<RecordType>();
235         assert(rt);
236         TagDecl *canon = rt->getDecl()->getCanonicalDecl();
237         return canon->getQualifiedNameAsString() == qn;
238     }
239
240 public:
241     bool isDerivedFrom(const char *baseStr, CXXBaseSpecifier const **Base = 0) const {
242         CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/!!Base, /*DetectVirtual=*/false);
243         Paths.setOrigin(const_cast<MyCXXRecordDecl*>(this));
244         if (!lookupInBases(&FindBaseClassString, const_cast<char*>(baseStr), Paths))
245             return false;
246         if (Base)
247             *Base = Paths.front().back().Base;
248         return true;
249     }
250 };
251
252 class FindTransitVisitor : public RecursiveASTVisitor<FindTransitVisitor>
253 {
254     Model::Model &model;
255     const CXXRecordDecl *SrcState;
256     const Type *EventType;
257 public:
258     explicit FindTransitVisitor(Model::Model &model, const CXXRecordDecl *SrcState, const Type *EventType)
259         : model(model), SrcState(SrcState), EventType(EventType) {}
260
261     bool VisitMemberExpr(MemberExpr *E) {
262         if (E->getMemberNameInfo().getAsString() != "transit")
263             return true;
264         if (E->hasExplicitTemplateArgs()) {
265             const Type *DstStateType = E->getExplicitTemplateArgs()[0].getArgument().getAsType().getTypePtr();
266             CXXRecordDecl *DstState = DstStateType->getAsCXXRecordDecl();
267             CXXRecordDecl *Event = EventType->getAsCXXRecordDecl();
268             Model::Transition *T = new Model::Transition(SrcState->getName(), DstState->getName(), Event->getName());
269             model.transitions.push_back(T);
270         }
271         return true;
272     }
273 };
274
275 class Visitor : public RecursiveASTVisitor<Visitor>
276 {
277     ASTContext *ASTCtx;
278     Model::Model &model;
279     DiagnosticsEngine &Diags;
280     unsigned diag_unhandled_reaction_type, diag_unhandled_reaction_decl,
281         diag_found_state, diag_found_statemachine, diag_no_history, diag_warning;
282
283 public:
284     bool shouldVisitTemplateInstantiations() const { return true; }
285
286     explicit Visitor(ASTContext *Context, Model::Model &model, DiagnosticsEngine &Diags)
287         : ASTCtx(Context), model(model), Diags(Diags)
288     {
289         diag_found_statemachine =
290             Diags.getCustomDiagID(DiagnosticsEngine::Note, "Found statemachine '%0'");
291         diag_found_state =
292             Diags.getCustomDiagID(DiagnosticsEngine::Note, "Found state '%0'");
293         diag_unhandled_reaction_type =
294             Diags.getCustomDiagID(DiagnosticsEngine::Error, "Unhandled reaction type '%0'");
295         diag_unhandled_reaction_decl =
296             Diags.getCustomDiagID(DiagnosticsEngine::Error, "Unhandled reaction decl '%0'");
297         diag_unhandled_reaction_decl =
298             Diags.getCustomDiagID(DiagnosticsEngine::Error, "History is not yet supported");
299         diag_warning =
300             Diags.getCustomDiagID(DiagnosticsEngine::Warning, "'%0' %1");
301     }
302
303     DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) { return Diags.Report(Loc, DiagID); }
304
305     void HandleCustomReaction(const CXXRecordDecl *SrcState, const Type *EventType)
306     {
307         IdentifierInfo& II = ASTCtx->Idents.get("react");
308         // TODO: Lookup for react even in base classes - probably by using Sema::LookupQualifiedName()
309         for (DeclContext::lookup_const_result ReactRes = SrcState->lookup(DeclarationName(&II));
310              ReactRes.first != ReactRes.second; ++ReactRes.first) {
311             if (CXXMethodDecl *React = dyn_cast<CXXMethodDecl>(*ReactRes.first))
312                 if (const ParmVarDecl *p = React->getParamDecl(0)) {
313                     const Type *ParmType = p->getType().getTypePtr();
314                     if (ParmType->isLValueReferenceType())
315                         ParmType = dyn_cast<LValueReferenceType>(ParmType)->getPointeeType().getTypePtr();
316                     if (ParmType == EventType)
317                         FindTransitVisitor(model, SrcState, EventType).TraverseStmt(React->getBody());
318                 }
319         }
320     }
321
322     void HandleReaction(const Type *T, const SourceLocation Loc, CXXRecordDecl *SrcState)
323     {
324         // TODO: Improve Loc tracking
325         if (const ElaboratedType *ET = dyn_cast<ElaboratedType>(T))
326             HandleReaction(ET->getNamedType().getTypePtr(), Loc, SrcState);
327         else if (const TemplateSpecializationType *TST = dyn_cast<TemplateSpecializationType>(T)) {
328             string name = TST->getTemplateName().getAsTemplateDecl()->getQualifiedNameAsString();
329             if (name == "boost::statechart::transition") {
330                 const Type *EventType = TST->getArg(0).getAsType().getTypePtr();
331                 const Type *DstStateType = TST->getArg(1).getAsType().getTypePtr();
332                 CXXRecordDecl *Event = EventType->getAsCXXRecordDecl();
333                 CXXRecordDecl *DstState = DstStateType->getAsCXXRecordDecl();
334
335                 Model::Transition *T = new Model::Transition(SrcState->getName(), DstState->getName(), Event->getName());
336                 model.transitions.push_back(T);
337             } else if (name == "boost::statechart::custom_reaction") {
338                 const Type *EventType = TST->getArg(0).getAsType().getTypePtr();
339                 HandleCustomReaction(SrcState, EventType);
340             } else if (name == "boost::statechart::deferral") {
341                 const Type *EventType = TST->getArg(0).getAsType().getTypePtr();
342                 CXXRecordDecl *Event = EventType->getAsCXXRecordDecl();
343
344                 Model::State *s = model.findState(SrcState->getName());
345                 assert(s);
346                 s->addDeferredEvent(Event->getName());
347             } else if (name == "boost::mpl::list") {
348                 for (TemplateSpecializationType::iterator Arg = TST->begin(), End = TST->end(); Arg != End; ++Arg)
349                     HandleReaction(Arg->getAsType().getTypePtr(), Loc, SrcState);
350             } else
351                 Diag(Loc, diag_unhandled_reaction_type) << name;
352         } else
353             Diag(Loc, diag_unhandled_reaction_type) << T->getTypeClassName();
354     }
355
356     void HandleReaction(const NamedDecl *Decl, CXXRecordDecl *SrcState)
357     {
358         if (const TypedefDecl *r = dyn_cast<TypedefDecl>(Decl))
359             HandleReaction(r->getCanonicalDecl()->getUnderlyingType().getTypePtr(),
360                            r->getLocStart(), SrcState);
361         else
362             Diag(Decl->getLocation(), diag_unhandled_reaction_decl) << Decl->getDeclKindName();
363     }
364
365     CXXRecordDecl *getTemplateArgDecl(const Type *T, unsigned ArgNum, const SourceLocation Loc)
366     {
367         if (const ElaboratedType *ET = dyn_cast<ElaboratedType>(T))
368             return getTemplateArgDecl(ET->getNamedType().getTypePtr(), ArgNum, Loc);
369         else if (const TemplateSpecializationType *TST = dyn_cast<TemplateSpecializationType>(T)) {
370             if (TST->getNumArgs() >= ArgNum+1)
371                 return TST->getArg(ArgNum).getAsType()->getAsCXXRecordDecl();
372         } else
373             Diag(Loc, diag_warning) << T->getTypeClassName() << "type as template argument is not supported";
374         return 0;
375     }
376
377     CXXRecordDecl *getTemplateArgDeclOfBase(const CXXBaseSpecifier *Base, unsigned ArgNum) {
378         return getTemplateArgDecl(Base->getType().getTypePtr(), 1,
379                                   Base->getTypeSourceInfo()->getTypeLoc().getLocStart());
380     }
381
382     bool VisitCXXRecordDecl(CXXRecordDecl *Declaration)
383     {
384         if (!Declaration->isCompleteDefinition())
385             return true;
386         if (Declaration->getQualifiedNameAsString() == "boost::statechart::state")
387             return true; // This is an "abstract class" not a real state
388
389         MyCXXRecordDecl *RecordDecl = static_cast<MyCXXRecordDecl*>(Declaration);
390         const CXXBaseSpecifier *Base;
391
392         if (RecordDecl->isDerivedFrom("boost::statechart::simple_state", &Base))
393         {
394             string name(RecordDecl->getName()); //getQualifiedNameAsString());
395             Diag(RecordDecl->getLocStart(), diag_found_state) << name;
396
397             Model::State *state;
398             // Either we saw a reference to forward declared state
399             // before, or we create a new state.
400             if (!(state = model.removeFromUndefinedContexts(name)))
401                 state = new Model::State(name);
402
403             CXXRecordDecl *Context = getTemplateArgDeclOfBase(Base, 1);
404             Model::Context *c = model.findContext(Context->getName());
405             if (!c) {
406                 Model::State *s = new Model::State(Context->getName());
407                 model.addUndefinedState(s);
408                 c = s;
409             }
410             c->add(state);
411
412             if (MyCXXRecordDecl *InnerInitialState =
413                 static_cast<MyCXXRecordDecl*>(getTemplateArgDeclOfBase(Base, 2))) {
414                 if (InnerInitialState->isDerivedFrom("boost::statechart::simple_state") ||
415                     InnerInitialState->isDerivedFrom("boost::statechart::state_machine"))
416                     state->setInitialInnerState(InnerInitialState->getName());
417                 else
418                     Diag(Base->getTypeSourceInfo()->getTypeLoc().getLocStart(), diag_warning)
419                         << InnerInitialState->getQualifiedNameAsString() << " as inner initial state is not supported";
420             }
421
422 //          if (CXXRecordDecl *History = getTemplateArgDecl(Base->getType().getTypePtr(), 3))
423 //              Diag(History->getLocStart(), diag_no_history);
424
425             IdentifierInfo& II = ASTCtx->Idents.get("reactions");
426             // TODO: Lookup for reactions even in base classes - probably by using Sema::LookupQualifiedName()
427             for (DeclContext::lookup_result Reactions = RecordDecl->lookup(DeclarationName(&II));
428                  Reactions.first != Reactions.second; ++Reactions.first)
429                 HandleReaction(*Reactions.first, RecordDecl);
430         }
431         else if (RecordDecl->isDerivedFrom("boost::statechart::state_machine", &Base))
432         {
433             Model::Machine m(RecordDecl->getName());
434             Diag(RecordDecl->getLocStart(), diag_found_statemachine) << m.name;
435
436             if (MyCXXRecordDecl *InitialState =
437                 static_cast<MyCXXRecordDecl*>(getTemplateArgDeclOfBase(Base, 1)))
438                 m.setInitialState(InitialState->getName());
439             model.add(m);
440         }
441         else if (RecordDecl->isDerivedFrom("boost::statechart::event"))
442         {
443             //sc.events.push_back(RecordDecl->getNameAsString());
444         }
445         return true;
446     }
447 };
448
449
450 class VisualizeStatechartConsumer : public clang::ASTConsumer
451 {
452     Model::Model model;
453     Visitor visitor;
454     string destFileName;
455 public:
456     explicit VisualizeStatechartConsumer(ASTContext *Context, std::string destFileName,
457                                          DiagnosticsEngine &D)
458         : visitor(Context, model, D), destFileName(destFileName) {}
459
460     virtual void HandleTranslationUnit(clang::ASTContext &Context) {
461         visitor.TraverseDecl(Context.getTranslationUnitDecl());
462         model.write_as_dot_file(destFileName);
463     }
464 };
465
466 class VisualizeStatechartAction : public PluginASTAction
467 {
468 protected:
469   ASTConsumer *CreateASTConsumer(CompilerInstance &CI, llvm::StringRef) {
470     size_t dot = getCurrentFile().find_last_of('.');
471     std::string dest = getCurrentFile().substr(0, dot);
472     dest.append(".dot");
473     return new VisualizeStatechartConsumer(&CI.getASTContext(), dest, CI.getDiagnostics());
474   }
475
476   bool ParseArgs(const CompilerInstance &CI,
477                  const std::vector<std::string>& args) {
478     for (unsigned i = 0, e = args.size(); i != e; ++i) {
479       llvm::errs() << "Visualizer arg = " << args[i] << "\n";
480
481       // Example error handling.
482       if (args[i] == "-an-error") {
483         DiagnosticsEngine &D = CI.getDiagnostics();
484         unsigned DiagID = D.getCustomDiagID(
485           DiagnosticsEngine::Error, "invalid argument '" + args[i] + "'");
486         D.Report(DiagID);
487         return false;
488       }
489     }
490     if (args.size() && args[0] == "help")
491       PrintHelp(llvm::errs());
492
493     return true;
494   }
495   void PrintHelp(llvm::raw_ostream& ros) {
496     ros << "Help for Visualize Statechart plugin goes here\n";
497   }
498
499 };
500
501 static FrontendPluginRegistry::Add<VisualizeStatechartAction> X("visualize-statechart", "visualize statechart");
502
503 // Local Variables:
504 // c-basic-offset: 4
505 // End: