]> rtime.felk.cvut.cz Git - boost-statechart-viewer.git/blob - src/visualizer.cpp
Support forward-declared states used as context
[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::mpl::list") {
281                 for (TemplateSpecializationType::iterator Arg = TST->begin(), End = TST->end(); Arg != End; ++Arg)
282                     HandleReaction(Arg->getAsType().getTypePtr(), Loc, SrcState);
283             } else
284                 Diag(Loc, diag_unhandled_reaction_type) << name;
285         } else
286             Diag(Loc, diag_unhandled_reaction_type) << T->getTypeClassName();
287     }
288
289     void HandleReaction(const NamedDecl *Decl, CXXRecordDecl *SrcState)
290     {
291         if (const TypedefDecl *r = dyn_cast<TypedefDecl>(Decl))
292             HandleReaction(r->getCanonicalDecl()->getUnderlyingType().getTypePtr(),
293                            r->getLocStart(), SrcState);
294         else
295             Diag(Decl->getLocation(), diag_unhandled_reaction_decl) << Decl->getDeclKindName();
296     }
297
298     CXXRecordDecl *getTemplateArgDecl(const Type *T, unsigned ArgNum)
299     {
300         if (const ElaboratedType *ET = dyn_cast<ElaboratedType>(T))
301             return getTemplateArgDecl(ET->getNamedType().getTypePtr(), ArgNum);
302         else if (const TemplateSpecializationType *TST = dyn_cast<TemplateSpecializationType>(T)) {
303             if (TST->getNumArgs() >= ArgNum+1)
304                 return TST->getArg(ArgNum).getAsType()->getAsCXXRecordDecl();
305         }
306         return 0;
307     }
308
309
310     bool VisitCXXRecordDecl(CXXRecordDecl *Declaration)
311     {
312         if (!Declaration->isCompleteDefinition())
313             return true;
314
315         MyCXXRecordDecl *RecordDecl = static_cast<MyCXXRecordDecl*>(Declaration);
316         const CXXBaseSpecifier *Base;
317
318         if (RecordDecl->isDerivedFrom("boost::statechart::simple_state", &Base))
319         {
320             string name(RecordDecl->getName()); //getQualifiedNameAsString());
321             Diag(RecordDecl->getLocStart(), diag_found_state) << name;
322
323             Model::State *state;
324             // Either we saw a reference to forward declared state
325             // before, or we create a new state.
326             if (!(state = model.removeFromUnknownContexts(name)))
327                 state = new Model::State(name);
328
329             CXXRecordDecl *Context = getTemplateArgDecl(Base->getType().getTypePtr(), 1);
330             Model::Context *c = model.findContext(Context->getName());
331             if (!c) {
332                 Model::State *s = new Model::State(Context->getName());
333                 model.addUnknownState(s);
334                 c = s;
335             }
336             c->add(state);
337
338             if (CXXRecordDecl *InnerInitialState = getTemplateArgDecl(Base->getType().getTypePtr(), 2))
339                 state->setInitialInnerState(InnerInitialState->getName());
340
341             IdentifierInfo& II = ASTCtx->Idents.get("reactions");
342             // TODO: Lookup for reactions even in base classes - probably by using Sema::LookupQualifiedName()
343             for (DeclContext::lookup_result Reactions = RecordDecl->lookup(DeclarationName(&II));
344                  Reactions.first != Reactions.second; ++Reactions.first)
345                 HandleReaction(*Reactions.first, RecordDecl);
346         }
347         else if (RecordDecl->isDerivedFrom("boost::statechart::state_machine", &Base))
348         {
349             Model::Machine m(RecordDecl->getName());
350             Diag(RecordDecl->getLocStart(), diag_found_statemachine) << m.name;
351
352             if (CXXRecordDecl *InitialState = getTemplateArgDecl(Base->getType().getTypePtr(), 1))
353                 m.setInitialState(InitialState->getName());
354             model.add(m);
355         }
356         else if (RecordDecl->isDerivedFrom("boost::statechart::event"))
357         {
358             //sc.events.push_back(RecordDecl->getNameAsString());
359         }
360         return true;
361     }
362 };
363
364
365 class VisualizeStatechartConsumer : public clang::ASTConsumer
366 {
367     Model::Model model;
368     Visitor visitor;
369     string destFileName;
370 public:
371     explicit VisualizeStatechartConsumer(ASTContext *Context, std::string destFileName,
372                                          DiagnosticsEngine &D)
373         : visitor(Context, model, D), destFileName(destFileName) {}
374
375     virtual void HandleTranslationUnit(clang::ASTContext &Context) {
376         visitor.TraverseDecl(Context.getTranslationUnitDecl());
377         model.write_as_dot_file(destFileName);
378     }
379 };
380
381 class VisualizeStatechartAction : public PluginASTAction
382 {
383 protected:
384   ASTConsumer *CreateASTConsumer(CompilerInstance &CI, llvm::StringRef) {
385     size_t dot = getCurrentFile().find_last_of('.');
386     std::string dest = getCurrentFile().substr(0, dot);
387     dest.append(".dot");
388     return new VisualizeStatechartConsumer(&CI.getASTContext(), dest, CI.getDiagnostics());
389   }
390
391   bool ParseArgs(const CompilerInstance &CI,
392                  const std::vector<std::string>& args) {
393     for (unsigned i = 0, e = args.size(); i != e; ++i) {
394       llvm::errs() << "Visualizer arg = " << args[i] << "\n";
395
396       // Example error handling.
397       if (args[i] == "-an-error") {
398         DiagnosticsEngine &D = CI.getDiagnostics();
399         unsigned DiagID = D.getCustomDiagID(
400           DiagnosticsEngine::Error, "invalid argument '" + args[i] + "'");
401         D.Report(DiagID);
402         return false;
403       }
404     }
405     if (args.size() && args[0] == "help")
406       PrintHelp(llvm::errs());
407
408     return true;
409   }
410   void PrintHelp(llvm::raw_ostream& ros) {
411     ros << "Help for Visualize Statechart plugin goes here\n";
412   }
413
414 };
415
416 static FrontendPluginRegistry::Add<VisualizeStatechartAction> X("visualize-statechart", "visualize statechart");
417
418 // Local Variables:
419 // c-basic-offset: 4
420 // End: