]> rtime.felk.cvut.cz Git - boost-statechart-viewer.git/blob - src/visualizer.cpp
Add support for inner states
[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     public:
65         const string name;
66         explicit State(string name) : name(name) {}
67         void setInitialInnerState(string name) { initialInnerState = name; }
68         friend ostream& operator<<(ostream& os, const State& s);
69     };
70
71
72     Context::iterator Context::add(State *state)
73     {
74         pair<iterator, bool> ret =  insert(value_type(state->name, state));
75         return ret.first;
76     }
77
78     Context *Context::findContext(const string &name)
79     {
80         iterator i = find(name), e;
81         if (i != end())
82             return i->second;
83         for (i = begin(), e = end(); i != e; ++i) {
84             Context *c = i->second->findContext(name);
85             if (c)
86                 return c;
87         }
88         return 0;
89     }
90
91
92     ostream& operator<<(ostream& os, const Context& c);
93
94     ostream& operator<<(ostream& os, const State& s)
95     {
96         if (s.size()) {
97             os << indent << "subgraph cluster_" << s.name << " {\n" << indent_inc;
98             os << indent << "label = \"" << s.name << "\"\n";
99         }
100         os << indent << "" << s.name << "\n";
101         if (s.size()) {
102             os << indent << s.initialInnerState << " [peripheries=2]\n";
103             os << static_cast<Context>(s);
104             os << indent_dec << indent << "}\n";
105         }
106         return os;
107     }
108
109
110     ostream& operator<<(ostream& os, const Context& c)
111     {
112         for (Context::const_iterator i = c.begin(), e = c.end(); i != e; i++) {
113             os << *i->second;
114         }
115         return os;
116     }
117
118
119     class Transition
120     {
121     public:
122         const string src, dst, event;
123         Transition(string src, string dst, string event) : src(src), dst(dst), event(event) {}
124     };
125
126     ostream& operator<<(ostream& os, const Transition& t)
127     {
128         os << indent << t.src << " -> " << t.dst << " [label = \"" << t.event << "\"]\n";
129         return os;
130     }
131
132
133     class Machine : public Context
134     {
135     protected:
136         string initial_state;
137     public:
138         const string name;
139         explicit Machine(string name) : name(name) {}
140
141         void setInitialState(string name) { initial_state = name; }
142
143         friend ostream& operator<<(ostream& os, const Machine& m);
144     };
145
146     ostream& operator<<(ostream& os, const Machine& m)
147     {
148         os << indent << "subgraph " << m.name << " {\n" << indent_inc;
149         os << indent << m.initial_state << " [peripheries=2]\n";
150         os << static_cast<Context>(m);
151         os << indent_dec << indent << "}\n";
152         return os;
153     }
154
155
156     class Model : public map<string, Machine>
157     {
158     public:
159         list< Transition*> transitions;
160
161         iterator add(const Machine &m)
162         {
163             pair<iterator, bool> ret =  insert(value_type(m.name, m));
164             return ret.first;
165         }
166
167         Context *findContext(const string &name)
168         {
169             iterator i = find(name), e;
170             if (i != end())
171                 return &i->second;
172             for (i = begin(), e = end(); i != e; ++i) {
173                 Context *c = i->second.findContext(name);
174                 if (c)
175                     return c;
176             }
177             return 0;
178         }
179
180         void write_as_dot_file(string fn)
181         {
182             ofstream f(fn.c_str());
183             f << "digraph statecharts {\n" << indent_inc;
184             for (iterator i = begin(), e = end(); i != e; i++)
185                 f << i->second;
186             for (list<Transition*>::iterator t = transitions.begin(), e = transitions.end(); t != e; ++t)
187                 f << **t;
188             f << indent_dec << "}\n";
189         }
190     };
191 };
192
193
194 class MyCXXRecordDecl : public CXXRecordDecl
195 {
196     static bool FindBaseClassString(const CXXBaseSpecifier *Specifier,
197                                     CXXBasePath &Path,
198                                     void *qualName)
199     {
200         string qn(static_cast<const char*>(qualName));
201         const RecordType *rt = Specifier->getType()->getAs<RecordType>();
202         assert(rt);
203         TagDecl *canon = rt->getDecl()->getCanonicalDecl();
204         return canon->getQualifiedNameAsString() == qn;
205     }
206
207 public:
208     bool isDerivedFrom(const char *baseStr, CXXBaseSpecifier const **Base = 0) const {
209         CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/!!Base, /*DetectVirtual=*/false);
210         Paths.setOrigin(const_cast<MyCXXRecordDecl*>(this));
211         if (!lookupInBases(&FindBaseClassString, const_cast<char*>(baseStr), Paths))
212             return false;
213         if (Base)
214             *Base = Paths.front().back().Base;
215         return true;
216     }
217 };
218
219
220 class Visitor : public RecursiveASTVisitor<Visitor>
221 {
222     ASTContext *ASTCtx;
223     Model::Model &model;
224     DiagnosticsEngine &Diags;
225     unsigned diag_unhandled_reaction_type, diag_unhandled_reaction_decl,
226         diag_found_state, diag_found_statemachine;
227
228 public:
229     bool shouldVisitTemplateInstantiations() const { return true; }
230
231     explicit Visitor(ASTContext *Context, Model::Model &model, DiagnosticsEngine &Diags)
232         : ASTCtx(Context), model(model), Diags(Diags)
233     {
234         diag_found_statemachine =
235             Diags.getCustomDiagID(DiagnosticsEngine::Note, "Found statemachine '%0'");
236         diag_found_state =
237             Diags.getCustomDiagID(DiagnosticsEngine::Note, "Found state '%0'");
238         diag_unhandled_reaction_type =
239             Diags.getCustomDiagID(DiagnosticsEngine::Error, "Unhandled reaction type '%0'");
240         diag_unhandled_reaction_decl =
241             Diags.getCustomDiagID(DiagnosticsEngine::Error, "Unhandled reaction decl '%0'");
242     }
243
244     DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) { return Diags.Report(Loc, DiagID); }
245
246     void HandleReaction(const Type *T, const SourceLocation Loc, CXXRecordDecl *SrcState)
247     {
248         if (const ElaboratedType *ET = dyn_cast<ElaboratedType>(T))
249             HandleReaction(ET->getNamedType().getTypePtr(), Loc, SrcState);
250         else if (const TemplateSpecializationType *TST = dyn_cast<TemplateSpecializationType>(T)) {
251             string name = TST->getTemplateName().getAsTemplateDecl()->getQualifiedNameAsString();
252             if (name == "boost::statechart::transition") {
253                 const Type *EventType = TST->getArg(0).getAsType().getTypePtr();
254                 const Type *DstStateType = TST->getArg(1).getAsType().getTypePtr();
255                 CXXRecordDecl *Event = EventType->getAsCXXRecordDecl();
256                 CXXRecordDecl *DstState = DstStateType->getAsCXXRecordDecl();
257
258                 Model::Transition *T = new Model::Transition(SrcState->getName(), DstState->getName(), Event->getName());
259                 model.transitions.push_back(T);
260             } else if (name == "boost::mpl::list") {
261                 for (TemplateSpecializationType::iterator Arg = TST->begin(), End = TST->end(); Arg != End; ++Arg)
262                     HandleReaction(Arg->getAsType().getTypePtr(), Loc, SrcState);
263             }
264             //->getDecl()->getQualifiedNameAsString();
265         } else
266             Diag(Loc, diag_unhandled_reaction_type) << T->getTypeClassName();
267     }
268
269     void HandleReaction(const NamedDecl *Decl, CXXRecordDecl *SrcState)
270     {
271         if (const TypedefDecl *r = dyn_cast<TypedefDecl>(Decl))
272             HandleReaction(r->getCanonicalDecl()->getUnderlyingType().getTypePtr(),
273                            r->getLocStart(), SrcState);
274         else
275             Diag(Decl->getLocation(), diag_unhandled_reaction_decl) << Decl->getDeclKindName();
276     }
277
278     CXXRecordDecl *getTemplateArgDecl(const Type *T, unsigned ArgNum)
279     {
280         if (const ElaboratedType *ET = dyn_cast<ElaboratedType>(T))
281             return getTemplateArgDecl(ET->getNamedType().getTypePtr(), ArgNum);
282         else if (const TemplateSpecializationType *TST = dyn_cast<TemplateSpecializationType>(T)) {
283             if (TST->getNumArgs() >= ArgNum+1)
284                 return TST->getArg(ArgNum).getAsType()->getAsCXXRecordDecl();
285         }
286         return 0;
287     }
288
289
290     bool VisitCXXRecordDecl(CXXRecordDecl *Declaration)
291     {
292         if (!Declaration->isCompleteDefinition())
293             return true;
294
295         MyCXXRecordDecl *RecordDecl = static_cast<MyCXXRecordDecl*>(Declaration);
296         const CXXBaseSpecifier *Base;
297
298         if (RecordDecl->isDerivedFrom("boost::statechart::simple_state", &Base))
299         {
300             string name(RecordDecl->getName()); //getQualifiedNameAsString());
301             Diag(RecordDecl->getLocStart(), diag_found_state) << name;
302
303             Model::State *state = new Model::State(name);
304
305             CXXRecordDecl *Context = getTemplateArgDecl(Base->getType().getTypePtr(), 1);
306             Model::Context *c = model.findContext(Context->getName());
307             if (c)
308                 c->add(state);
309
310             if (CXXRecordDecl *InnerInitialState = getTemplateArgDecl(Base->getType().getTypePtr(), 2))
311                 state->setInitialInnerState(InnerInitialState->getName());
312
313             IdentifierInfo& II = ASTCtx->Idents.get("reactions");
314             // TODO: Lookup for reactions even in base classes - probably by using Sema::LookupQualifiedName()
315             for (DeclContext::lookup_result Reactions = RecordDecl->lookup(DeclarationName(&II));
316                  Reactions.first != Reactions.second; ++Reactions.first)
317                 HandleReaction(*Reactions.first, RecordDecl);
318         }
319         else if (RecordDecl->isDerivedFrom("boost::statechart::state_machine", &Base))
320         {
321             Model::Machine m(RecordDecl->getName());
322             Diag(RecordDecl->getLocStart(), diag_found_statemachine) << m.name;
323
324             if (CXXRecordDecl *InitialState = getTemplateArgDecl(Base->getType().getTypePtr(), 1))
325                 m.setInitialState(InitialState->getName());
326             model.add(m);
327         }
328         else if (RecordDecl->isDerivedFrom("boost::statechart::event"))
329         {
330             //sc.events.push_back(RecordDecl->getNameAsString());
331         }
332         return true;
333     }
334 };
335
336
337 class VisualizeStatechartConsumer : public clang::ASTConsumer
338 {
339     Model::Model model;
340     Visitor visitor;
341     string destFileName;
342 public:
343     explicit VisualizeStatechartConsumer(ASTContext *Context, std::string destFileName,
344                                          DiagnosticsEngine &D)
345         : visitor(Context, model, D), destFileName(destFileName) {}
346
347     virtual void HandleTranslationUnit(clang::ASTContext &Context) {
348         visitor.TraverseDecl(Context.getTranslationUnitDecl());
349         model.write_as_dot_file(destFileName);
350     }
351 };
352
353 class VisualizeStatechartAction : public PluginASTAction
354 {
355 protected:
356   ASTConsumer *CreateASTConsumer(CompilerInstance &CI, llvm::StringRef) {
357     size_t dot = getCurrentFile().find_last_of('.');
358     std::string dest = getCurrentFile().substr(0, dot);
359     dest.append(".dot");
360     return new VisualizeStatechartConsumer(&CI.getASTContext(), dest, CI.getDiagnostics());
361   }
362
363   bool ParseArgs(const CompilerInstance &CI,
364                  const std::vector<std::string>& args) {
365     for (unsigned i = 0, e = args.size(); i != e; ++i) {
366       llvm::errs() << "Visualizer arg = " << args[i] << "\n";
367
368       // Example error handling.
369       if (args[i] == "-an-error") {
370         DiagnosticsEngine &D = CI.getDiagnostics();
371         unsigned DiagID = D.getCustomDiagID(
372           DiagnosticsEngine::Error, "invalid argument '" + args[i] + "'");
373         D.Report(DiagID);
374         return false;
375       }
376     }
377     if (args.size() && args[0] == "help")
378       PrintHelp(llvm::errs());
379
380     return true;
381   }
382   void PrintHelp(llvm::raw_ostream& ros) {
383     ros << "Help for Visualize Statechart plugin goes here\n";
384   }
385
386 };
387
388 static FrontendPluginRegistry::Add<VisualizeStatechartAction> X("visualize-statechart", "visualize statechart");
389
390 // Local Variables:
391 // c-basic-offset: 4
392 // End: