]> rtime.felk.cvut.cz Git - boost-statechart-viewer.git/blob - src/visualizer.cpp
Preliminary support for custom reactions
[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         Context unknown;        // For forward-declared state classes
159     public:
160         list< Transition*> transitions;
161
162         iterator add(const Machine &m)
163         {
164             pair<iterator, bool> ret =  insert(value_type(m.name, m));
165             return ret.first;
166         }
167
168         void addUnknownState(State *m)
169         {
170             unknown[m->name] = m;
171         }
172
173
174         Context *findContext(const string &name)
175         {
176             Context::iterator ci = unknown.find(name);
177             if (ci != unknown.end())
178                 return ci->second;
179             iterator i = find(name), e;
180             if (i != end())
181                 return &i->second;
182             for (i = begin(), e = end(); i != e; ++i) {
183                 Context *c = i->second.findContext(name);
184                 if (c)
185                     return c;
186             }
187             return 0;
188         }
189
190         State *removeFromUnknownContexts(const string &name)
191         {
192             Context::iterator ci = unknown.find(name);
193             if (ci == unknown.end())
194                 return 0;
195             unknown.erase(ci);
196             return ci->second;
197         }
198
199         void write_as_dot_file(string fn)
200         {
201             ofstream f(fn.c_str());
202             f << "digraph statecharts {\n" << indent_inc;
203             for (iterator i = begin(), e = end(); i != e; i++)
204                 f << i->second;
205             for (list<Transition*>::iterator t = transitions.begin(), e = transitions.end(); t != e; ++t)
206                 f << **t;
207             f << indent_dec << "}\n";
208         }
209     };
210 };
211
212
213 class MyCXXRecordDecl : public CXXRecordDecl
214 {
215     static bool FindBaseClassString(const CXXBaseSpecifier *Specifier,
216                                     CXXBasePath &Path,
217                                     void *qualName)
218     {
219         string qn(static_cast<const char*>(qualName));
220         const RecordType *rt = Specifier->getType()->getAs<RecordType>();
221         assert(rt);
222         TagDecl *canon = rt->getDecl()->getCanonicalDecl();
223         return canon->getQualifiedNameAsString() == qn;
224     }
225
226 public:
227     bool isDerivedFrom(const char *baseStr, CXXBaseSpecifier const **Base = 0) const {
228         CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/!!Base, /*DetectVirtual=*/false);
229         Paths.setOrigin(const_cast<MyCXXRecordDecl*>(this));
230         if (!lookupInBases(&FindBaseClassString, const_cast<char*>(baseStr), Paths))
231             return false;
232         if (Base)
233             *Base = Paths.front().back().Base;
234         return true;
235     }
236 };
237
238
239 class Visitor : public RecursiveASTVisitor<Visitor>
240 {
241     ASTContext *ASTCtx;
242     Model::Model &model;
243     DiagnosticsEngine &Diags;
244     unsigned diag_unhandled_reaction_type, diag_unhandled_reaction_decl,
245         diag_found_state, diag_found_statemachine;
246
247 public:
248     bool shouldVisitTemplateInstantiations() const { return true; }
249
250     explicit Visitor(ASTContext *Context, Model::Model &model, DiagnosticsEngine &Diags)
251         : ASTCtx(Context), model(model), Diags(Diags)
252     {
253         diag_found_statemachine =
254             Diags.getCustomDiagID(DiagnosticsEngine::Note, "Found statemachine '%0'");
255         diag_found_state =
256             Diags.getCustomDiagID(DiagnosticsEngine::Note, "Found state '%0'");
257         diag_unhandled_reaction_type =
258             Diags.getCustomDiagID(DiagnosticsEngine::Error, "Unhandled reaction type '%0'");
259         diag_unhandled_reaction_decl =
260             Diags.getCustomDiagID(DiagnosticsEngine::Error, "Unhandled reaction decl '%0'");
261     }
262
263     DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) { return Diags.Report(Loc, DiagID); }
264
265     void HandleReaction(const Type *T, const SourceLocation Loc, CXXRecordDecl *SrcState)
266     {
267         // TODO: Improve Loc tracking
268         if (const ElaboratedType *ET = dyn_cast<ElaboratedType>(T))
269             HandleReaction(ET->getNamedType().getTypePtr(), Loc, SrcState);
270         else if (const TemplateSpecializationType *TST = dyn_cast<TemplateSpecializationType>(T)) {
271             string name = TST->getTemplateName().getAsTemplateDecl()->getQualifiedNameAsString();
272             if (name == "boost::statechart::transition") {
273                 const Type *EventType = TST->getArg(0).getAsType().getTypePtr();
274                 const Type *DstStateType = TST->getArg(1).getAsType().getTypePtr();
275                 CXXRecordDecl *Event = EventType->getAsCXXRecordDecl();
276                 CXXRecordDecl *DstState = DstStateType->getAsCXXRecordDecl();
277
278                 Model::Transition *T = new Model::Transition(SrcState->getName(), DstState->getName(), Event->getName());
279                 model.transitions.push_back(T);
280             } else if (name == "boost::statechart::custom_reaction") {
281                 const Type *EventType = TST->getArg(0).getAsType().getTypePtr();
282                 CXXRecordDecl *Event = EventType->getAsCXXRecordDecl();
283
284                 Model::Transition *T = new Model::Transition(SrcState->getName(), "\"???\"", Event->getName());
285                 model.transitions.push_back(T);
286             } else if (name == "boost::statechart::deferral") {
287                 const Type *EventType = TST->getArg(0).getAsType().getTypePtr();
288                 CXXRecordDecl *Event = EventType->getAsCXXRecordDecl();
289
290                 Model::Transition *T = new Model::Transition(SrcState->getName(), "\"??? deferral\"", Event->getName());
291                 model.transitions.push_back(T);
292             } else if (name == "boost::mpl::list") {
293                 for (TemplateSpecializationType::iterator Arg = TST->begin(), End = TST->end(); Arg != End; ++Arg)
294                     HandleReaction(Arg->getAsType().getTypePtr(), Loc, SrcState);
295             } else
296                 Diag(Loc, diag_unhandled_reaction_type) << name;
297         } else
298             Diag(Loc, diag_unhandled_reaction_type) << T->getTypeClassName();
299     }
300
301     void HandleReaction(const NamedDecl *Decl, CXXRecordDecl *SrcState)
302     {
303         if (const TypedefDecl *r = dyn_cast<TypedefDecl>(Decl))
304             HandleReaction(r->getCanonicalDecl()->getUnderlyingType().getTypePtr(),
305                            r->getLocStart(), SrcState);
306         else
307             Diag(Decl->getLocation(), diag_unhandled_reaction_decl) << Decl->getDeclKindName();
308     }
309
310     CXXRecordDecl *getTemplateArgDecl(const Type *T, unsigned ArgNum)
311     {
312         if (const ElaboratedType *ET = dyn_cast<ElaboratedType>(T))
313             return getTemplateArgDecl(ET->getNamedType().getTypePtr(), ArgNum);
314         else if (const TemplateSpecializationType *TST = dyn_cast<TemplateSpecializationType>(T)) {
315             if (TST->getNumArgs() >= ArgNum+1)
316                 return TST->getArg(ArgNum).getAsType()->getAsCXXRecordDecl();
317         }
318         return 0;
319     }
320
321
322     bool VisitCXXRecordDecl(CXXRecordDecl *Declaration)
323     {
324         if (!Declaration->isCompleteDefinition())
325             return true;
326
327         MyCXXRecordDecl *RecordDecl = static_cast<MyCXXRecordDecl*>(Declaration);
328         const CXXBaseSpecifier *Base;
329
330         if (RecordDecl->isDerivedFrom("boost::statechart::simple_state", &Base))
331         {
332             string name(RecordDecl->getName()); //getQualifiedNameAsString());
333             Diag(RecordDecl->getLocStart(), diag_found_state) << name;
334
335             Model::State *state;
336             // Either we saw a reference to forward declared state
337             // before, or we create a new state.
338             if (!(state = model.removeFromUnknownContexts(name)))
339                 state = new Model::State(name);
340
341             CXXRecordDecl *Context = getTemplateArgDecl(Base->getType().getTypePtr(), 1);
342             Model::Context *c = model.findContext(Context->getName());
343             if (!c) {
344                 Model::State *s = new Model::State(Context->getName());
345                 model.addUnknownState(s);
346                 c = s;
347             }
348             c->add(state);
349
350             if (CXXRecordDecl *InnerInitialState = getTemplateArgDecl(Base->getType().getTypePtr(), 2))
351                 state->setInitialInnerState(InnerInitialState->getName());
352
353             IdentifierInfo& II = ASTCtx->Idents.get("reactions");
354             // TODO: Lookup for reactions even in base classes - probably by using Sema::LookupQualifiedName()
355             for (DeclContext::lookup_result Reactions = RecordDecl->lookup(DeclarationName(&II));
356                  Reactions.first != Reactions.second; ++Reactions.first)
357                 HandleReaction(*Reactions.first, RecordDecl);
358         }
359         else if (RecordDecl->isDerivedFrom("boost::statechart::state_machine", &Base))
360         {
361             Model::Machine m(RecordDecl->getName());
362             Diag(RecordDecl->getLocStart(), diag_found_statemachine) << m.name;
363
364             if (CXXRecordDecl *InitialState = getTemplateArgDecl(Base->getType().getTypePtr(), 1))
365                 m.setInitialState(InitialState->getName());
366             model.add(m);
367         }
368         else if (RecordDecl->isDerivedFrom("boost::statechart::event"))
369         {
370             //sc.events.push_back(RecordDecl->getNameAsString());
371         }
372         return true;
373     }
374 };
375
376
377 class VisualizeStatechartConsumer : public clang::ASTConsumer
378 {
379     Model::Model model;
380     Visitor visitor;
381     string destFileName;
382 public:
383     explicit VisualizeStatechartConsumer(ASTContext *Context, std::string destFileName,
384                                          DiagnosticsEngine &D)
385         : visitor(Context, model, D), destFileName(destFileName) {}
386
387     virtual void HandleTranslationUnit(clang::ASTContext &Context) {
388         visitor.TraverseDecl(Context.getTranslationUnitDecl());
389         model.write_as_dot_file(destFileName);
390     }
391 };
392
393 class VisualizeStatechartAction : public PluginASTAction
394 {
395 protected:
396   ASTConsumer *CreateASTConsumer(CompilerInstance &CI, llvm::StringRef) {
397     size_t dot = getCurrentFile().find_last_of('.');
398     std::string dest = getCurrentFile().substr(0, dot);
399     dest.append(".dot");
400     return new VisualizeStatechartConsumer(&CI.getASTContext(), dest, CI.getDiagnostics());
401   }
402
403   bool ParseArgs(const CompilerInstance &CI,
404                  const std::vector<std::string>& args) {
405     for (unsigned i = 0, e = args.size(); i != e; ++i) {
406       llvm::errs() << "Visualizer arg = " << args[i] << "\n";
407
408       // Example error handling.
409       if (args[i] == "-an-error") {
410         DiagnosticsEngine &D = CI.getDiagnostics();
411         unsigned DiagID = D.getCustomDiagID(
412           DiagnosticsEngine::Error, "invalid argument '" + args[i] + "'");
413         D.Report(DiagID);
414         return false;
415       }
416     }
417     if (args.size() && args[0] == "help")
418       PrintHelp(llvm::errs());
419
420     return true;
421   }
422   void PrintHelp(llvm::raw_ostream& ros) {
423     ros << "Help for Visualize Statechart plugin goes here\n";
424   }
425
426 };
427
428 static FrontendPluginRegistry::Add<VisualizeStatechartAction> X("visualize-statechart", "visualize statechart");
429
430 // Local Variables:
431 // c-basic-offset: 4
432 // End: