]> rtime.felk.cvut.cz Git - boost-statechart-viewer.git/blob - src/visualizer.cpp
023976eca274458175dfb740f54dc968762bdb51
[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 #include <vector>
26
27 //LLVM Header files
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Support/raw_os_ostream.h"
30
31 //clang header files
32 #include "clang/AST/ASTConsumer.h"
33 #include "clang/AST/ASTContext.h"
34 #include "clang/AST/CXXInheritance.h"
35 #include "clang/AST/RecursiveASTVisitor.h"
36 #include "clang/Frontend/CompilerInstance.h"
37 #include "clang/Frontend/FrontendPluginRegistry.h"
38
39 using namespace clang;
40 using namespace std;
41
42 namespace Model
43 {
44
45     inline int getIndentLevelIdx() {
46         static int i = ios_base::xalloc();
47         return i;
48     }
49
50     ostream& indent(ostream& os) { os << setw(2*os.iword(getIndentLevelIdx())) << ""; return os; }
51     ostream& indent_inc(ostream& os) { os.iword(getIndentLevelIdx())++; return os; }
52     ostream& indent_dec(ostream& os) { os.iword(getIndentLevelIdx())--; return os; }
53
54     class State;
55
56     class Context : public map<string, State*> {
57     public:
58         iterator add(State *state);
59         Context *findContext(const string &name);
60     };
61
62     class State : public Context
63     {
64         string initialInnerState;
65         list<string> defferedEvents;
66         list<string> inStateEvents;
67         bool noTypedef;
68     public:
69         const string name;
70         explicit State(string name) : noTypedef(false), name(name) {}
71         void setInitialInnerState(string name) { initialInnerState = name; }
72         void addDeferredEvent(const string &name) { defferedEvents.push_back(name); }
73         void addInStateEvent(const string &name) { inStateEvents.push_back(name); }
74         void setNoTypedef() { noTypedef = true;}
75         friend ostream& operator<<(ostream& os, const State& s);
76     };
77
78
79     Context::iterator Context::add(State *state)
80     {
81         pair<iterator, bool> ret =  insert(value_type(state->name, state));
82         return ret.first;
83     }
84
85     Context *Context::findContext(const string &name)
86     {
87         iterator i = find(name), e;
88         if (i != end())
89             return i->second;
90         for (i = begin(), e = end(); i != e; ++i) {
91             Context *c = i->second->findContext(name);
92             if (c)
93                 return c;
94         }
95         return 0;
96     }
97
98     ostream& operator<<(ostream& os, const Context& c);
99
100     ostream& operator<<(ostream& os, const State& s)
101     {
102         string label = s.name;
103         for (list<string>::const_iterator i = s.defferedEvents.begin(), e = s.defferedEvents.end(); i != e; ++i)
104             label.append("<br />").append(*i).append(" / defer");
105         for (list<string>::const_iterator i = s.inStateEvents.begin(), e = s.inStateEvents.end(); i != e; ++i)
106             label.append("<br />").append(*i).append(" / in state");
107         if (s.noTypedef) os << indent << s.name << " [label=<" << label << ">, color=\"red\"]\n";
108         else os << indent << s.name << " [label=<" << label << ">]\n";
109         if (s.size()) {
110             os << indent << s.name << " -> " << s.initialInnerState << " [style = dashed]\n";
111             os << indent << "subgraph cluster_" << s.name << " {\n" << indent_inc;
112             os << indent << "label = \"" << s.name << "\"\n";
113             os << indent << s.initialInnerState << " [peripheries=2]\n";
114             os << static_cast<Context>(s);
115             os << indent_dec << indent << "}\n";
116         }
117         return os;
118     }
119
120
121     ostream& operator<<(ostream& os, const Context& c)
122     {
123         for (Context::const_iterator i = c.begin(), e = c.end(); i != e; i++) {
124             os << *i->second;
125         }
126         return os;
127     }
128
129
130     class Transition
131     {
132     public:
133         const string src, dst, event;
134         Transition(string src, string dst, string event) : src(src), dst(dst), event(event) {}
135     };
136
137     ostream& operator<<(ostream& os, const Transition& t)
138     {
139         os << indent << t.src << " -> " << t.dst << " [label = \"" << t.event << "\"]\n";
140         return os;
141     }
142
143
144     class Machine : public Context
145     {
146     protected:
147         string initial_state;
148     public:
149         const string name;
150         explicit Machine(string name) : name(name) {}
151
152         void setInitialState(string name) { initial_state = name; }
153
154         friend ostream& operator<<(ostream& os, const Machine& m);
155     };
156
157     ostream& operator<<(ostream& os, const Machine& m)
158     {
159         os << indent << "subgraph " << m.name << " {\n" << indent_inc;
160         os << indent << m.initial_state << " [peripheries=2]\n";
161         os << static_cast<Context>(m);
162         os << indent_dec << indent << "}\n";
163         return os;
164     }
165
166
167     class Model : public map<string, Machine>
168     {
169         Context undefined;      // For forward-declared state classes
170     public:
171         list< Transition*> transitions;
172
173         iterator add(const Machine &m)
174         {
175             pair<iterator, bool> ret =  insert(value_type(m.name, m));
176             return ret.first;
177         }
178
179         void addUndefinedState(State *m)
180         {
181             undefined[m->name] = m;
182         }
183
184
185         Context *findContext(const string &name)
186         {
187             Context::iterator ci = undefined.find(name);
188             if (ci != undefined.end())
189                 return ci->second;
190             iterator i = find(name), e;
191             if (i != end())
192                 return &i->second;
193             for (i = begin(), e = end(); i != e; ++i) {
194                 Context *c = i->second.findContext(name);
195                 if (c)
196                     return c;
197             }
198             return 0;
199         }
200
201         State *findState(const string &name)
202         {
203             for (iterator i = begin(), e = end(); i != e; ++i) {
204                 Context *c = i->second.findContext(name);
205                 if (c)
206                     return static_cast<State*>(c);
207             }
208             return 0;
209         }
210
211
212         State *removeFromUndefinedContexts(const string &name)
213         {
214             Context::iterator ci = undefined.find(name);
215             if (ci == undefined.end())
216                 return 0;
217             undefined.erase(ci);
218             return ci->second;
219         }
220
221         void write_as_dot_file(string fn)
222         {
223             ofstream f(fn.c_str());
224             f << "digraph statecharts {\n" << indent_inc;
225             for (iterator i = begin(), e = end(); i != e; i++)
226                 f << i->second;
227             for (list<Transition*>::iterator t = transitions.begin(), e = transitions.end(); t != e; ++t)
228                 f << **t;
229             f << indent_dec << "}\n";
230         }
231     };
232 };
233
234
235 class MyCXXRecordDecl : public CXXRecordDecl
236 {
237     static bool FindBaseClassString(const CXXBaseSpecifier *Specifier,
238                                     CXXBasePath &Path,
239                                     void *qualName)
240     {
241         string qn(static_cast<const char*>(qualName));
242         const RecordType *rt = Specifier->getType()->getAs<RecordType>();
243         assert(rt);
244         TagDecl *canon = rt->getDecl()->getCanonicalDecl();
245         return canon->getQualifiedNameAsString() == qn;
246     }
247
248 public:
249     bool isDerivedFrom(const char *baseStr, CXXBaseSpecifier const **Base = 0) const {
250         CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/!!Base, /*DetectVirtual=*/false);
251         Paths.setOrigin(const_cast<MyCXXRecordDecl*>(this));
252         if (!lookupInBases(&FindBaseClassString, const_cast<char*>(baseStr), Paths))
253             return false;
254         if (Base)
255             *Base = Paths.front().back().Base;
256         return true;
257     }
258 };
259
260 class FindTransitVisitor : public RecursiveASTVisitor<FindTransitVisitor>
261 {
262     Model::Model &model;
263     const CXXRecordDecl *SrcState;
264     const Type *EventType;
265 public:
266     explicit FindTransitVisitor(Model::Model &model, const CXXRecordDecl *SrcState, const Type *EventType)
267         : model(model), SrcState(SrcState), EventType(EventType) {}
268
269     bool VisitMemberExpr(MemberExpr *E) {
270         if (E->getMemberNameInfo().getAsString() == "defer_event") {
271                 CXXRecordDecl *Event = EventType->getAsCXXRecordDecl();
272
273                 Model::State *s = model.findState(SrcState->getName());
274                 assert(s);
275                 s->addDeferredEvent(Event->getName());
276         } else if (E->getMemberNameInfo().getAsString() != "transit")
277             return true;
278         if (E->hasExplicitTemplateArgs()) {
279             const Type *DstStateType = E->getExplicitTemplateArgs()[0].getArgument().getAsType().getTypePtr();
280             CXXRecordDecl *DstState = DstStateType->getAsCXXRecordDecl();
281             CXXRecordDecl *Event = EventType->getAsCXXRecordDecl();
282             Model::Transition *T = new Model::Transition(SrcState->getName(), DstState->getName(), Event->getName());
283             model.transitions.push_back(T);
284         }
285         return true;
286     }
287 };
288
289 class Visitor : public RecursiveASTVisitor<Visitor>
290 {
291     struct eventModel {
292         string name;
293         SourceLocation loc;
294         eventModel(string ev, SourceLocation sourceLoc) : name(ev), loc(sourceLoc){}
295     };
296
297     struct eventHasName {
298         string eventName;
299         eventHasName(string name) : eventName(name){}
300         bool operator() (const eventModel& model) { return (eventName.compare(model.name) == 0); }
301     };
302     ASTContext *ASTCtx;
303     Model::Model &model;
304     DiagnosticsEngine &Diags;
305     unsigned diag_unhandled_reaction_type, diag_unhandled_reaction_decl,
306         diag_found_state, diag_found_statemachine, diag_no_history, diag_missing_reaction, diag_warning;
307     std::vector<bool> reactMethodInReactions; // Indicates whether i-th react method is referenced from typedef reactions.
308     std::list<eventModel> unusedEvents;
309
310 public:
311     bool shouldVisitTemplateInstantiations() const { return true; }
312
313     explicit Visitor(ASTContext *Context, Model::Model &model, DiagnosticsEngine &Diags)
314         : ASTCtx(Context), model(model), Diags(Diags)
315     {
316         diag_found_statemachine =
317             Diags.getCustomDiagID(DiagnosticsEngine::Note, "Found statemachine '%0'");
318         diag_found_state =
319             Diags.getCustomDiagID(DiagnosticsEngine::Note, "Found state '%0'");
320         diag_unhandled_reaction_type =
321             Diags.getCustomDiagID(DiagnosticsEngine::Error, "Unhandled reaction type '%0'");
322         diag_unhandled_reaction_decl =
323             Diags.getCustomDiagID(DiagnosticsEngine::Error, "Unhandled reaction decl '%0'");
324         diag_no_history =
325             Diags.getCustomDiagID(DiagnosticsEngine::Error, "History is not yet supported");
326         diag_missing_reaction =
327             Diags.getCustomDiagID(DiagnosticsEngine::Error, "Missing react method for event '%0'");
328         diag_warning =
329             Diags.getCustomDiagID(DiagnosticsEngine::Warning, "'%0' %1");
330     }
331
332     DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) { return Diags.Report(Loc, DiagID); }
333
334     void checkAllReactMethods(const CXXRecordDecl *SrcState) 
335     {
336         unsigned i = 0;
337         IdentifierInfo& II = ASTCtx->Idents.get("react");
338         DeclContext::lookup_const_result ReactRes = SrcState->lookup(DeclarationName(&II));
339         DeclContext::lookup_const_result::iterator it, end;
340         for (it = ReactRes.begin(), end=ReactRes.end(); it != end; ++it, ++i) {
341             if (i >= reactMethodInReactions.size() || reactMethodInReactions[i] == false) {
342                 CXXMethodDecl *React = dyn_cast<CXXMethodDecl>(*it);
343                 Diag(React->getParamDecl(0)->getLocStart(), diag_warning)
344                     << React->getParamDecl(0)->getType().getAsString() << " missing in typedef reactions";
345             }
346         }
347     }
348     
349     bool HandleCustomReaction(const CXXRecordDecl *SrcState, const Type *EventType)
350     {
351         unsigned i = 0;
352         IdentifierInfo& II = ASTCtx->Idents.get("react");
353         // TODO: Lookup for react even in base classes - probably by using Sema::LookupQualifiedName()
354         DeclContext::lookup_const_result ReactRes = SrcState->lookup(DeclarationName(&II));
355         DeclContext::lookup_const_result::iterator it, end;
356         for (it = ReactRes.begin(), end=ReactRes.end(); it != end; ++it) {
357             if (CXXMethodDecl *React = dyn_cast<CXXMethodDecl>(*it)) {
358                 if (React->getNumParams() >= 1) {
359                     const ParmVarDecl *p = React->getParamDecl(0);
360                     const Type *ParmType = p->getType().getTypePtr();
361                     if (i == reactMethodInReactions.size()) reactMethodInReactions.push_back(false);
362                     if (ParmType->isLValueReferenceType())
363                         ParmType = dyn_cast<LValueReferenceType>(ParmType)->getPointeeType().getTypePtr();
364                     if (ParmType == EventType) {
365                         FindTransitVisitor(model, SrcState, EventType).TraverseStmt(React->getBody());
366                         reactMethodInReactions[i] = true;
367                         return true;
368                     }
369                 } else
370                     Diag(React->getLocStart(), diag_warning)
371                         << React << "has not a parameter";
372             } else
373                 Diag((*it)->getSourceRange().getBegin(), diag_warning)
374                     << (*it)->getDeclKindName() << "is not supported as react method";
375             i++;
376         }
377         return false;
378     }
379
380     void HandleReaction(const Type *T, const SourceLocation Loc, CXXRecordDecl *SrcState)
381     {
382         // TODO: Improve Loc tracking
383         if (const ElaboratedType *ET = dyn_cast<ElaboratedType>(T))
384             HandleReaction(ET->getNamedType().getTypePtr(), Loc, SrcState);
385         else if (const TemplateSpecializationType *TST = dyn_cast<TemplateSpecializationType>(T)) {
386             string name = TST->getTemplateName().getAsTemplateDecl()->getQualifiedNameAsString();
387             if (name == "boost::statechart::transition") {
388                 const Type *EventType = TST->getArg(0).getAsType().getTypePtr();
389                 const Type *DstStateType = TST->getArg(1).getAsType().getTypePtr();
390                 CXXRecordDecl *Event = EventType->getAsCXXRecordDecl();
391                 CXXRecordDecl *DstState = DstStateType->getAsCXXRecordDecl();
392                 unusedEvents.remove_if(eventHasName(Event->getNameAsString()));
393
394                 Model::Transition *T = new Model::Transition(SrcState->getName(), DstState->getName(), Event->getName());
395                 model.transitions.push_back(T);
396             } else if (name == "boost::statechart::custom_reaction") {
397                 const Type *EventType = TST->getArg(0).getAsType().getTypePtr();
398                 if (!HandleCustomReaction(SrcState, EventType)) {
399                     Diag(SrcState->getLocation(), diag_missing_reaction) << EventType->getAsCXXRecordDecl()->getName();
400                 }
401                 unusedEvents.remove_if(eventHasName(EventType->getAsCXXRecordDecl()->getNameAsString()));
402             } else if (name == "boost::statechart::deferral") {
403                 const Type *EventType = TST->getArg(0).getAsType().getTypePtr();
404                 CXXRecordDecl *Event = EventType->getAsCXXRecordDecl();
405                 unusedEvents.remove_if(eventHasName(Event->getNameAsString()));
406
407                 Model::State *s = model.findState(SrcState->getName());
408                 assert(s);
409                 s->addDeferredEvent(Event->getName());
410             } else if (name == "boost::mpl::list") {
411                 for (TemplateSpecializationType::iterator Arg = TST->begin(), End = TST->end(); Arg != End; ++Arg)
412                     HandleReaction(Arg->getAsType().getTypePtr(), Loc, SrcState);
413             } else if (name == "boost::statechart::in_state_reaction") {
414                 const Type *EventType = TST->getArg(0).getAsType().getTypePtr();
415                 CXXRecordDecl *Event = EventType->getAsCXXRecordDecl();
416                 unusedEvents.remove_if(eventHasName(Event->getNameAsString()));
417
418                 Model::State *s = model.findState(SrcState->getName());
419                 assert(s);
420                 s->addInStateEvent(Event->getName());
421               
422             } else
423                 Diag(Loc, diag_unhandled_reaction_type) << name;
424         } else
425             Diag(Loc, diag_unhandled_reaction_type) << T->getTypeClassName();
426     }
427
428     void HandleReaction(const NamedDecl *Decl, CXXRecordDecl *SrcState)
429     {
430         if (const TypedefDecl *r = dyn_cast<TypedefDecl>(Decl))
431             HandleReaction(r->getCanonicalDecl()->getUnderlyingType().getTypePtr(),
432                            r->getLocStart(), SrcState);
433         else
434             Diag(Decl->getLocation(), diag_unhandled_reaction_decl) << Decl->getDeclKindName();
435         checkAllReactMethods(SrcState);
436     }
437
438     TemplateArgumentLoc getTemplateArgLoc(const TypeLoc &T, unsigned ArgNum, bool ignore)
439     {
440         if (const ElaboratedTypeLoc ET = T.getAs<ElaboratedTypeLoc>())
441             return getTemplateArgLoc(ET.getNamedTypeLoc(), ArgNum, ignore);
442         else if (const TemplateSpecializationTypeLoc TST = T.getAs<TemplateSpecializationTypeLoc>()) {
443             if (TST.getNumArgs() >= ArgNum+1) {
444                 return TST.getArgLoc(ArgNum);
445             } else
446                 if (!ignore)
447                     Diag(TST.getBeginLoc(), diag_warning) << TST.getType()->getTypeClassName() << "has not enough arguments" << TST.getSourceRange();
448         } else
449             Diag(T.getBeginLoc(), diag_warning) << T.getType()->getTypeClassName() << "type as template argument is not supported" << T.getSourceRange();
450         return TemplateArgumentLoc();
451     }
452
453     TemplateArgumentLoc getTemplateArgLocOfBase(const CXXBaseSpecifier *Base, unsigned ArgNum, bool ignore) {
454         return getTemplateArgLoc(Base->getTypeSourceInfo()->getTypeLoc(), ArgNum, ignore);
455     }
456
457     CXXRecordDecl *getTemplateArgDeclOfBase(const CXXBaseSpecifier *Base, unsigned ArgNum, TemplateArgumentLoc &Loc, bool ignore = false) {
458         Loc = getTemplateArgLocOfBase(Base, ArgNum, ignore);
459         switch (Loc.getArgument().getKind()) {
460         case TemplateArgument::Type:
461             return Loc.getTypeSourceInfo()->getType()->getAsCXXRecordDecl();
462         case TemplateArgument::Null:
463             // Diag() was already called
464             break;
465         default:
466             Diag(Loc.getSourceRange().getBegin(), diag_warning) << Loc.getArgument().getKind() << "unsupported kind" << Loc.getSourceRange();
467         }
468         return 0;
469     }
470
471     CXXRecordDecl *getTemplateArgDeclOfBase(const CXXBaseSpecifier *Base, unsigned ArgNum, bool ignore = false) {
472         TemplateArgumentLoc Loc;
473         return getTemplateArgDeclOfBase(Base, ArgNum, Loc, ignore);
474     }
475
476     void handleSimpleState(CXXRecordDecl *RecordDecl, const CXXBaseSpecifier *Base)
477     {
478         int typedef_num = 0;
479         string name(RecordDecl->getName()); //getQualifiedNameAsString());
480         Diag(RecordDecl->getLocStart(), diag_found_state) << name;
481         reactMethodInReactions.clear();
482
483         Model::State *state;
484         // Either we saw a reference to forward declared state
485         // before, or we create a new state.
486         if (!(state = model.removeFromUndefinedContexts(name)))
487             state = new Model::State(name);
488
489         CXXRecordDecl *Context = getTemplateArgDeclOfBase(Base, 1);
490         if (Context) {
491             Model::Context *c = model.findContext(Context->getName());
492             if (!c) {
493                 Model::State *s = new Model::State(Context->getName());
494                 model.addUndefinedState(s);
495                 c = s;
496             }
497             c->add(state);
498         }
499         //TODO support more innitial states
500         TemplateArgumentLoc Loc;
501         if (MyCXXRecordDecl *InnerInitialState =
502             static_cast<MyCXXRecordDecl*>(getTemplateArgDeclOfBase(Base, 2, Loc, true))) {
503               if (InnerInitialState->isDerivedFrom("boost::statechart::simple_state") ||
504                 InnerInitialState->isDerivedFrom("boost::statechart::state_machine")) {
505                   state->setInitialInnerState(InnerInitialState->getName());
506             }
507             else if (!InnerInitialState->getNameAsString().compare("boost::mpl::list<>"))
508               Diag(Loc.getTypeSourceInfo()->getTypeLoc().getBeginLoc(), diag_warning)
509                     << InnerInitialState->getName() << " as inner initial state is not supported" << Loc.getSourceRange();
510         }
511
512 //          if (CXXRecordDecl *History = getTemplateArgDecl(Base->getType().getTypePtr(), 3))
513 //              Diag(History->getLocStart(), diag_no_history);
514
515         IdentifierInfo& II = ASTCtx->Idents.get("reactions");
516         // TODO: Lookup for reactions even in base classes - probably by using Sema::LookupQualifiedName()
517         DeclContext::lookup_result Reactions = RecordDecl->lookup(DeclarationName(&II));
518         DeclContext::lookup_result::iterator it, end;
519         for (it = Reactions.begin(), end = Reactions.end(); it != end; ++it, typedef_num++)
520             HandleReaction(*it, RecordDecl);
521         if(typedef_num == 0) {
522             Diag(RecordDecl->getLocStart(), diag_warning)
523                 << RecordDecl->getName() << "state has no typedef for reactions";
524             state->setNoTypedef();
525         }
526     }
527
528     void handleStateMachine(CXXRecordDecl *RecordDecl, const CXXBaseSpecifier *Base)
529     {
530         Model::Machine m(RecordDecl->getName());
531         Diag(RecordDecl->getLocStart(), diag_found_statemachine) << m.name;
532
533         if (MyCXXRecordDecl *InitialState =
534             static_cast<MyCXXRecordDecl*>(getTemplateArgDeclOfBase(Base, 1)))
535             m.setInitialState(InitialState->getName());
536         model.add(m);
537     }
538
539     bool VisitCXXRecordDecl(CXXRecordDecl *Declaration)
540     {
541         if (!Declaration->isCompleteDefinition())
542             return true;
543         if (Declaration->getQualifiedNameAsString() == "boost::statechart::state" ||
544             Declaration->getQualifiedNameAsString() == "TimedState" ||
545             Declaration->getQualifiedNameAsString() == "TimedSimpleState" ||
546             Declaration->getQualifiedNameAsString() == "boost::statechart::assynchronous_state_machine")
547             return true; // This is an "abstract class" not a real state or real state machine
548
549         MyCXXRecordDecl *RecordDecl = static_cast<MyCXXRecordDecl*>(Declaration);
550         const CXXBaseSpecifier *Base;
551
552         if (RecordDecl->isDerivedFrom("boost::statechart::simple_state", &Base))
553             handleSimpleState(RecordDecl, Base);
554         else if (RecordDecl->isDerivedFrom("boost::statechart::state_machine", &Base))
555             handleStateMachine(RecordDecl, Base);
556         else if (RecordDecl->isDerivedFrom("boost::statechart::event")) {
557             // Mark the event as unused until we found that somebody uses it
558             unusedEvents.push_back(eventModel(RecordDecl->getNameAsString(), RecordDecl->getLocation()));
559         }
560         return true;
561     }
562     void printUnusedEventDefinitions() {
563         for(list<eventModel>::iterator it = unusedEvents.begin(); it!=unusedEvents.end(); it++)
564             Diag((*it).loc, diag_warning)
565                 << (*it).name << "event defined but not used in any state";
566     }
567 };
568
569
570 class VisualizeStatechartConsumer : public clang::ASTConsumer
571 {
572     Model::Model model;
573     Visitor visitor;
574     string destFileName;
575 public:
576     explicit VisualizeStatechartConsumer(ASTContext *Context, std::string destFileName,
577                                          DiagnosticsEngine &D)
578         : visitor(Context, model, D), destFileName(destFileName) {}
579
580     virtual void HandleTranslationUnit(clang::ASTContext &Context) {
581         visitor.TraverseDecl(Context.getTranslationUnitDecl());
582         visitor.printUnusedEventDefinitions();
583         model.write_as_dot_file(destFileName);
584     }
585 };
586
587 class VisualizeStatechartAction : public PluginASTAction
588 {
589 protected:
590   ASTConsumer *CreateASTConsumer(CompilerInstance &CI, llvm::StringRef) {
591     size_t dot = getCurrentFile().find_last_of('.');
592     std::string dest = getCurrentFile().substr(0, dot);
593     dest.append(".dot");
594     return new VisualizeStatechartConsumer(&CI.getASTContext(), dest, CI.getDiagnostics());
595   }
596
597   bool ParseArgs(const CompilerInstance &CI,
598                  const std::vector<std::string>& args) {
599     for (unsigned i = 0, e = args.size(); i != e; ++i) {
600       llvm::errs() << "Visualizer arg = " << args[i] << "\n";
601
602       // Example error handling.
603       if (args[i] == "-an-error") {
604         DiagnosticsEngine &D = CI.getDiagnostics();
605         unsigned DiagID = D.getCustomDiagID(
606           DiagnosticsEngine::Error, "invalid argument '%0' expected '%1'");
607         D.Report(DiagID);
608         return false;
609       }
610     }
611     if (args.size() && args[0] == "help")
612       PrintHelp(llvm::errs());
613
614     return true;
615   }
616   void PrintHelp(llvm::raw_ostream& ros) {
617     ros << "Help for Visualize Statechart plugin goes here\n";
618   }
619
620 };
621
622 static FrontendPluginRegistry::Add<VisualizeStatechartAction> X("visualize-statechart", "visualize statechart");
623
624 // Local Variables:
625 // c-basic-offset: 4
626 // End: