]> rtime.felk.cvut.cz Git - boost-statechart-viewer.git/blob - src/visualizer.cpp
Add more error messages and TODOs (for Camera example)
[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         // TODO: Improve Loc tracking
249         if (const ElaboratedType *ET = dyn_cast<ElaboratedType>(T))
250             HandleReaction(ET->getNamedType().getTypePtr(), Loc, SrcState);
251         else if (const TemplateSpecializationType *TST = dyn_cast<TemplateSpecializationType>(T)) {
252             string name = TST->getTemplateName().getAsTemplateDecl()->getQualifiedNameAsString();
253             if (name == "boost::statechart::transition") {
254                 const Type *EventType = TST->getArg(0).getAsType().getTypePtr();
255                 const Type *DstStateType = TST->getArg(1).getAsType().getTypePtr();
256                 CXXRecordDecl *Event = EventType->getAsCXXRecordDecl();
257                 CXXRecordDecl *DstState = DstStateType->getAsCXXRecordDecl();
258
259                 Model::Transition *T = new Model::Transition(SrcState->getName(), DstState->getName(), Event->getName());
260                 model.transitions.push_back(T);
261             } else if (name == "boost::mpl::list") {
262                 for (TemplateSpecializationType::iterator Arg = TST->begin(), End = TST->end(); Arg != End; ++Arg)
263                     HandleReaction(Arg->getAsType().getTypePtr(), Loc, SrcState);
264             } else
265                 Diag(Loc, diag_unhandled_reaction_type) << name;
266         } else
267             Diag(Loc, diag_unhandled_reaction_type) << T->getTypeClassName();
268     }
269
270     void HandleReaction(const NamedDecl *Decl, CXXRecordDecl *SrcState)
271     {
272         if (const TypedefDecl *r = dyn_cast<TypedefDecl>(Decl))
273             HandleReaction(r->getCanonicalDecl()->getUnderlyingType().getTypePtr(),
274                            r->getLocStart(), SrcState);
275         else
276             Diag(Decl->getLocation(), diag_unhandled_reaction_decl) << Decl->getDeclKindName();
277     }
278
279     CXXRecordDecl *getTemplateArgDecl(const Type *T, unsigned ArgNum)
280     {
281         if (const ElaboratedType *ET = dyn_cast<ElaboratedType>(T))
282             return getTemplateArgDecl(ET->getNamedType().getTypePtr(), ArgNum);
283         else if (const TemplateSpecializationType *TST = dyn_cast<TemplateSpecializationType>(T)) {
284             if (TST->getNumArgs() >= ArgNum+1)
285                 return TST->getArg(ArgNum).getAsType()->getAsCXXRecordDecl();
286         }
287         return 0;
288     }
289
290
291     bool VisitCXXRecordDecl(CXXRecordDecl *Declaration)
292     {
293         if (!Declaration->isCompleteDefinition())
294             return true;
295
296         MyCXXRecordDecl *RecordDecl = static_cast<MyCXXRecordDecl*>(Declaration);
297         const CXXBaseSpecifier *Base;
298
299         if (RecordDecl->isDerivedFrom("boost::statechart::simple_state", &Base))
300         {
301             string name(RecordDecl->getName()); //getQualifiedNameAsString());
302             Diag(RecordDecl->getLocStart(), diag_found_state) << name;
303
304             Model::State *state = new Model::State(name);
305
306             CXXRecordDecl *Context = getTemplateArgDecl(Base->getType().getTypePtr(), 1);
307             Model::Context *c = model.findContext(Context->getName());
308             if (c)
309                 c->add(state);
310             // TODO: else
311
312             if (CXXRecordDecl *InnerInitialState = getTemplateArgDecl(Base->getType().getTypePtr(), 2))
313                 state->setInitialInnerState(InnerInitialState->getName());
314
315             IdentifierInfo& II = ASTCtx->Idents.get("reactions");
316             // TODO: Lookup for reactions even in base classes - probably by using Sema::LookupQualifiedName()
317             for (DeclContext::lookup_result Reactions = RecordDecl->lookup(DeclarationName(&II));
318                  Reactions.first != Reactions.second; ++Reactions.first)
319                 HandleReaction(*Reactions.first, RecordDecl);
320         }
321         else if (RecordDecl->isDerivedFrom("boost::statechart::state_machine", &Base))
322         {
323             Model::Machine m(RecordDecl->getName());
324             Diag(RecordDecl->getLocStart(), diag_found_statemachine) << m.name;
325
326             if (CXXRecordDecl *InitialState = getTemplateArgDecl(Base->getType().getTypePtr(), 1))
327                 m.setInitialState(InitialState->getName());
328             model.add(m);
329         }
330         else if (RecordDecl->isDerivedFrom("boost::statechart::event"))
331         {
332             //sc.events.push_back(RecordDecl->getNameAsString());
333         }
334         return true;
335     }
336 };
337
338
339 class VisualizeStatechartConsumer : public clang::ASTConsumer
340 {
341     Model::Model model;
342     Visitor visitor;
343     string destFileName;
344 public:
345     explicit VisualizeStatechartConsumer(ASTContext *Context, std::string destFileName,
346                                          DiagnosticsEngine &D)
347         : visitor(Context, model, D), destFileName(destFileName) {}
348
349     virtual void HandleTranslationUnit(clang::ASTContext &Context) {
350         visitor.TraverseDecl(Context.getTranslationUnitDecl());
351         model.write_as_dot_file(destFileName);
352     }
353 };
354
355 class VisualizeStatechartAction : public PluginASTAction
356 {
357 protected:
358   ASTConsumer *CreateASTConsumer(CompilerInstance &CI, llvm::StringRef) {
359     size_t dot = getCurrentFile().find_last_of('.');
360     std::string dest = getCurrentFile().substr(0, dot);
361     dest.append(".dot");
362     return new VisualizeStatechartConsumer(&CI.getASTContext(), dest, CI.getDiagnostics());
363   }
364
365   bool ParseArgs(const CompilerInstance &CI,
366                  const std::vector<std::string>& args) {
367     for (unsigned i = 0, e = args.size(); i != e; ++i) {
368       llvm::errs() << "Visualizer arg = " << args[i] << "\n";
369
370       // Example error handling.
371       if (args[i] == "-an-error") {
372         DiagnosticsEngine &D = CI.getDiagnostics();
373         unsigned DiagID = D.getCustomDiagID(
374           DiagnosticsEngine::Error, "invalid argument '" + args[i] + "'");
375         D.Report(DiagID);
376         return false;
377       }
378     }
379     if (args.size() && args[0] == "help")
380       PrintHelp(llvm::errs());
381
382     return true;
383   }
384   void PrintHelp(llvm::raw_ostream& ros) {
385     ros << "Help for Visualize Statechart plugin goes here\n";
386   }
387
388 };
389
390 static FrontendPluginRegistry::Add<VisualizeStatechartAction> X("visualize-statechart", "visualize statechart");
391
392 // Local Variables:
393 // c-basic-offset: 4
394 // End: