2 ////////////////////////////////////////////////////////////////////////////////////////
4 // This file is part of Boost Statechart Viewer.
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.
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.
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/>.
19 ////////////////////////////////////////////////////////////////////////////////////////
21 //standard header files
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Support/raw_os_ostream.h"
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"
38 using namespace clang;
44 inline int getIndentLevelIdx() {
45 static int i = ios_base::xalloc();
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; }
55 class Context : public map<string, State*> {
57 iterator add(State *state);
58 Context *findContext(const string &name);
61 class State : public Context
63 string initialInnerState;
64 list<string> defferedEvents;
67 explicit State(string name) : name(name) {}
68 void setInitialInnerState(string name) { initialInnerState = name; }
69 void addDeferredEvent(const string &name) { defferedEvents.push_back(name); }
70 friend ostream& operator<<(ostream& os, const State& s);
74 Context::iterator Context::add(State *state)
76 pair<iterator, bool> ret = insert(value_type(state->name, state));
80 Context *Context::findContext(const string &name)
82 iterator i = find(name), e;
85 for (i = begin(), e = end(); i != e; ++i) {
86 Context *c = i->second->findContext(name);
93 ostream& operator<<(ostream& os, const Context& c);
95 ostream& operator<<(ostream& os, const State& s)
97 string label = s.name;
98 for (list<string>::const_iterator i = s.defferedEvents.begin(), e = s.defferedEvents.end(); i != e; ++i)
99 label.append("<br />").append(*i).append(" / defer");
100 os << indent << s.name << " [label=<" << label << ">]\n";
102 os << indent << s.name << " -> " << s.initialInnerState << " [style = dashed]\n";
103 os << indent << "subgraph cluster_" << s.name << " {\n" << indent_inc;
104 os << indent << "label = \"" << s.name << "\"\n";
105 os << indent << s.initialInnerState << " [peripheries=2]\n";
106 os << static_cast<Context>(s);
107 os << indent_dec << indent << "}\n";
113 ostream& operator<<(ostream& os, const Context& c)
115 for (Context::const_iterator i = c.begin(), e = c.end(); i != e; i++) {
125 const string src, dst, event;
126 Transition(string src, string dst, string event) : src(src), dst(dst), event(event) {}
129 ostream& operator<<(ostream& os, const Transition& t)
131 os << indent << t.src << " -> " << t.dst << " [label = \"" << t.event << "\"]\n";
136 class Machine : public Context
139 string initial_state;
142 explicit Machine(string name) : name(name) {}
144 void setInitialState(string name) { initial_state = name; }
146 friend ostream& operator<<(ostream& os, const Machine& m);
149 ostream& operator<<(ostream& os, const Machine& m)
151 os << indent << "subgraph " << m.name << " {\n" << indent_inc;
152 os << indent << m.initial_state << " [peripheries=2]\n";
153 os << static_cast<Context>(m);
154 os << indent_dec << indent << "}\n";
159 class Model : public map<string, Machine>
161 Context undefined; // For forward-declared state classes
163 list< Transition*> transitions;
165 iterator add(const Machine &m)
167 pair<iterator, bool> ret = insert(value_type(m.name, m));
171 void addUndefinedState(State *m)
173 undefined[m->name] = m;
177 Context *findContext(const string &name)
179 Context::iterator ci = undefined.find(name);
180 if (ci != undefined.end())
182 iterator i = find(name), e;
185 for (i = begin(), e = end(); i != e; ++i) {
186 Context *c = i->second.findContext(name);
193 State *findState(const string &name)
195 for (iterator i = begin(), e = end(); i != e; ++i) {
196 Context *c = i->second.findContext(name);
198 return static_cast<State*>(c);
204 State *removeFromUndefinedContexts(const string &name)
206 Context::iterator ci = undefined.find(name);
207 if (ci == undefined.end())
213 void write_as_dot_file(string fn)
215 ofstream f(fn.c_str());
216 f << "digraph statecharts {\n" << indent_inc;
217 for (iterator i = begin(), e = end(); i != e; i++)
219 for (list<Transition*>::iterator t = transitions.begin(), e = transitions.end(); t != e; ++t)
221 f << indent_dec << "}\n";
227 class MyCXXRecordDecl : public CXXRecordDecl
229 static bool FindBaseClassString(const CXXBaseSpecifier *Specifier,
233 string qn(static_cast<const char*>(qualName));
234 const RecordType *rt = Specifier->getType()->getAs<RecordType>();
236 TagDecl *canon = rt->getDecl()->getCanonicalDecl();
237 return canon->getQualifiedNameAsString() == qn;
241 bool isDerivedFrom(const char *baseStr, CXXBaseSpecifier const **Base = 0) const {
242 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/!!Base, /*DetectVirtual=*/false);
243 Paths.setOrigin(const_cast<MyCXXRecordDecl*>(this));
244 if (!lookupInBases(&FindBaseClassString, const_cast<char*>(baseStr), Paths))
247 *Base = Paths.front().back().Base;
252 class FindTransitVisitor : public RecursiveASTVisitor<FindTransitVisitor>
255 const CXXRecordDecl *SrcState;
256 const Type *EventType;
258 explicit FindTransitVisitor(Model::Model &model, const CXXRecordDecl *SrcState, const Type *EventType)
259 : model(model), SrcState(SrcState), EventType(EventType) {}
261 bool VisitMemberExpr(MemberExpr *E) {
262 if (E->getMemberNameInfo().getAsString() != "transit")
264 if (E->hasExplicitTemplateArgs()) {
265 const Type *DstStateType = E->getExplicitTemplateArgs()[0].getArgument().getAsType().getTypePtr();
266 CXXRecordDecl *DstState = DstStateType->getAsCXXRecordDecl();
267 CXXRecordDecl *Event = EventType->getAsCXXRecordDecl();
268 Model::Transition *T = new Model::Transition(SrcState->getName(), DstState->getName(), Event->getName());
269 model.transitions.push_back(T);
275 class Visitor : public RecursiveASTVisitor<Visitor>
279 DiagnosticsEngine &Diags;
280 unsigned diag_unhandled_reaction_type, diag_unhandled_reaction_decl,
281 diag_found_state, diag_found_statemachine, diag_no_history, diag_warning;
284 bool shouldVisitTemplateInstantiations() const { return true; }
286 explicit Visitor(ASTContext *Context, Model::Model &model, DiagnosticsEngine &Diags)
287 : ASTCtx(Context), model(model), Diags(Diags)
289 diag_found_statemachine =
290 Diags.getCustomDiagID(DiagnosticsEngine::Note, "Found statemachine '%0'");
292 Diags.getCustomDiagID(DiagnosticsEngine::Note, "Found state '%0'");
293 diag_unhandled_reaction_type =
294 Diags.getCustomDiagID(DiagnosticsEngine::Error, "Unhandled reaction type '%0'");
295 diag_unhandled_reaction_decl =
296 Diags.getCustomDiagID(DiagnosticsEngine::Error, "Unhandled reaction decl '%0'");
297 diag_unhandled_reaction_decl =
298 Diags.getCustomDiagID(DiagnosticsEngine::Error, "History is not yet supported");
300 Diags.getCustomDiagID(DiagnosticsEngine::Warning, "'%0' %1");
303 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) { return Diags.Report(Loc, DiagID); }
305 void HandleCustomReaction(const CXXRecordDecl *SrcState, const Type *EventType)
307 IdentifierInfo& II = ASTCtx->Idents.get("react");
308 // TODO: Lookup for react even in base classes - probably by using Sema::LookupQualifiedName()
309 for (DeclContext::lookup_const_result ReactRes = SrcState->lookup(DeclarationName(&II));
310 ReactRes.first != ReactRes.second; ++ReactRes.first) {
311 if (CXXMethodDecl *React = dyn_cast<CXXMethodDecl>(*ReactRes.first)) {
312 if (React->getNumParams() >= 1) {
313 const ParmVarDecl *p = React->getParamDecl(0);
314 const Type *ParmType = p->getType().getTypePtr();
315 if (ParmType->isLValueReferenceType())
316 ParmType = dyn_cast<LValueReferenceType>(ParmType)->getPointeeType().getTypePtr();
317 if (ParmType == EventType)
318 FindTransitVisitor(model, SrcState, EventType).TraverseStmt(React->getBody());
320 Diag(React->getLocStart(), diag_warning)
321 << React << "has not a parameter";
323 Diag((*ReactRes.first)->getSourceRange().getBegin(), diag_warning)
324 << (*ReactRes.first)->getDeclKindName() << "is not supported as react method";
328 void HandleReaction(const Type *T, const SourceLocation Loc, CXXRecordDecl *SrcState)
330 // TODO: Improve Loc tracking
331 if (const ElaboratedType *ET = dyn_cast<ElaboratedType>(T))
332 HandleReaction(ET->getNamedType().getTypePtr(), Loc, SrcState);
333 else if (const TemplateSpecializationType *TST = dyn_cast<TemplateSpecializationType>(T)) {
334 string name = TST->getTemplateName().getAsTemplateDecl()->getQualifiedNameAsString();
335 if (name == "boost::statechart::transition") {
336 const Type *EventType = TST->getArg(0).getAsType().getTypePtr();
337 const Type *DstStateType = TST->getArg(1).getAsType().getTypePtr();
338 CXXRecordDecl *Event = EventType->getAsCXXRecordDecl();
339 CXXRecordDecl *DstState = DstStateType->getAsCXXRecordDecl();
341 Model::Transition *T = new Model::Transition(SrcState->getName(), DstState->getName(), Event->getName());
342 model.transitions.push_back(T);
343 } else if (name == "boost::statechart::custom_reaction") {
344 const Type *EventType = TST->getArg(0).getAsType().getTypePtr();
345 HandleCustomReaction(SrcState, EventType);
346 } else if (name == "boost::statechart::deferral") {
347 const Type *EventType = TST->getArg(0).getAsType().getTypePtr();
348 CXXRecordDecl *Event = EventType->getAsCXXRecordDecl();
350 Model::State *s = model.findState(SrcState->getName());
352 s->addDeferredEvent(Event->getName());
353 } else if (name == "boost::mpl::list") {
354 for (TemplateSpecializationType::iterator Arg = TST->begin(), End = TST->end(); Arg != End; ++Arg)
355 HandleReaction(Arg->getAsType().getTypePtr(), Loc, SrcState);
357 Diag(Loc, diag_unhandled_reaction_type) << name;
359 Diag(Loc, diag_unhandled_reaction_type) << T->getTypeClassName();
362 void HandleReaction(const NamedDecl *Decl, CXXRecordDecl *SrcState)
364 if (const TypedefDecl *r = dyn_cast<TypedefDecl>(Decl))
365 HandleReaction(r->getCanonicalDecl()->getUnderlyingType().getTypePtr(),
366 r->getLocStart(), SrcState);
368 Diag(Decl->getLocation(), diag_unhandled_reaction_decl) << Decl->getDeclKindName();
371 CXXRecordDecl *getTemplateArgDecl(const Type *T, unsigned ArgNum, const SourceLocation Loc)
373 if (const ElaboratedType *ET = dyn_cast<ElaboratedType>(T))
374 return getTemplateArgDecl(ET->getNamedType().getTypePtr(), ArgNum, Loc);
375 else if (const TemplateSpecializationType *TST = dyn_cast<TemplateSpecializationType>(T)) {
376 if (TST->getNumArgs() >= ArgNum+1)
377 return TST->getArg(ArgNum).getAsType()->getAsCXXRecordDecl();
379 Diag(Loc, diag_warning) << T->getTypeClassName() << "type as template argument is not supported";
383 CXXRecordDecl *getTemplateArgDeclOfBase(const CXXBaseSpecifier *Base, unsigned ArgNum) {
384 return getTemplateArgDecl(Base->getType().getTypePtr(), 1,
385 Base->getTypeSourceInfo()->getTypeLoc().getLocStart());
388 bool VisitCXXRecordDecl(CXXRecordDecl *Declaration)
390 if (!Declaration->isCompleteDefinition())
392 if (Declaration->getQualifiedNameAsString() == "boost::statechart::state")
393 return true; // This is an "abstract class" not a real state
395 MyCXXRecordDecl *RecordDecl = static_cast<MyCXXRecordDecl*>(Declaration);
396 const CXXBaseSpecifier *Base;
398 if (RecordDecl->isDerivedFrom("boost::statechart::simple_state", &Base))
400 string name(RecordDecl->getName()); //getQualifiedNameAsString());
401 Diag(RecordDecl->getLocStart(), diag_found_state) << name;
404 // Either we saw a reference to forward declared state
405 // before, or we create a new state.
406 if (!(state = model.removeFromUndefinedContexts(name)))
407 state = new Model::State(name);
409 CXXRecordDecl *Context = getTemplateArgDeclOfBase(Base, 1);
410 Model::Context *c = model.findContext(Context->getName());
412 Model::State *s = new Model::State(Context->getName());
413 model.addUndefinedState(s);
418 if (MyCXXRecordDecl *InnerInitialState =
419 static_cast<MyCXXRecordDecl*>(getTemplateArgDeclOfBase(Base, 2))) {
420 if (InnerInitialState->isDerivedFrom("boost::statechart::simple_state") ||
421 InnerInitialState->isDerivedFrom("boost::statechart::state_machine"))
422 state->setInitialInnerState(InnerInitialState->getName());
424 Diag(Base->getTypeSourceInfo()->getTypeLoc().getLocStart(), diag_warning)
425 << InnerInitialState->getQualifiedNameAsString() << " as inner initial state is not supported";
428 // if (CXXRecordDecl *History = getTemplateArgDecl(Base->getType().getTypePtr(), 3))
429 // Diag(History->getLocStart(), diag_no_history);
431 IdentifierInfo& II = ASTCtx->Idents.get("reactions");
432 // TODO: Lookup for reactions even in base classes - probably by using Sema::LookupQualifiedName()
433 for (DeclContext::lookup_result Reactions = RecordDecl->lookup(DeclarationName(&II));
434 Reactions.first != Reactions.second; ++Reactions.first)
435 HandleReaction(*Reactions.first, RecordDecl);
437 else if (RecordDecl->isDerivedFrom("boost::statechart::state_machine", &Base))
439 Model::Machine m(RecordDecl->getName());
440 Diag(RecordDecl->getLocStart(), diag_found_statemachine) << m.name;
442 if (MyCXXRecordDecl *InitialState =
443 static_cast<MyCXXRecordDecl*>(getTemplateArgDeclOfBase(Base, 1)))
444 m.setInitialState(InitialState->getName());
447 else if (RecordDecl->isDerivedFrom("boost::statechart::event"))
449 //sc.events.push_back(RecordDecl->getNameAsString());
456 class VisualizeStatechartConsumer : public clang::ASTConsumer
462 explicit VisualizeStatechartConsumer(ASTContext *Context, std::string destFileName,
463 DiagnosticsEngine &D)
464 : visitor(Context, model, D), destFileName(destFileName) {}
466 virtual void HandleTranslationUnit(clang::ASTContext &Context) {
467 visitor.TraverseDecl(Context.getTranslationUnitDecl());
468 model.write_as_dot_file(destFileName);
472 class VisualizeStatechartAction : public PluginASTAction
475 ASTConsumer *CreateASTConsumer(CompilerInstance &CI, llvm::StringRef) {
476 size_t dot = getCurrentFile().find_last_of('.');
477 std::string dest = getCurrentFile().substr(0, dot);
479 return new VisualizeStatechartConsumer(&CI.getASTContext(), dest, CI.getDiagnostics());
482 bool ParseArgs(const CompilerInstance &CI,
483 const std::vector<std::string>& args) {
484 for (unsigned i = 0, e = args.size(); i != e; ++i) {
485 llvm::errs() << "Visualizer arg = " << args[i] << "\n";
487 // Example error handling.
488 if (args[i] == "-an-error") {
489 DiagnosticsEngine &D = CI.getDiagnostics();
490 unsigned DiagID = D.getCustomDiagID(
491 DiagnosticsEngine::Error, "invalid argument '" + args[i] + "'");
496 if (args.size() && args[0] == "help")
497 PrintHelp(llvm::errs());
501 void PrintHelp(llvm::raw_ostream& ros) {
502 ros << "Help for Visualize Statechart plugin goes here\n";
507 static FrontendPluginRegistry::Add<VisualizeStatechartAction> X("visualize-statechart", "visualize statechart");