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 TemplateArgumentLoc getTemplateArgLoc(const TypeLoc &T, unsigned ArgNum)
373 if (const ElaboratedTypeLoc *ET = dyn_cast<ElaboratedTypeLoc>(&T))
374 return getTemplateArgLoc(ET->getNamedTypeLoc(), ArgNum);
375 else if (const TemplateSpecializationTypeLoc *TST = dyn_cast<TemplateSpecializationTypeLoc>(&T)) {
376 if (TST->getNumArgs() >= ArgNum+1) {
377 return TST->getArgLoc(ArgNum);
380 Diag(TST->getBeginLoc(), diag_warning) << TST->getType()->getTypeClassName() << "has not enough arguments" << TST->getSourceRange();
382 Diag(T.getBeginLoc(), diag_warning) << T.getType()->getTypeClassName() << "type as template argument is not supported" << T.getSourceRange();
383 return TemplateArgumentLoc();
386 TemplateArgumentLoc getTemplateArgLocOfBase(const CXXBaseSpecifier *Base, unsigned ArgNum) {
387 return getTemplateArgLoc(Base->getTypeSourceInfo()->getTypeLoc(), ArgNum);
390 CXXRecordDecl *getTemplateArgDeclOfBase(const CXXBaseSpecifier *Base, unsigned ArgNum, TemplateArgumentLoc &Loc) {
391 Loc = getTemplateArgLocOfBase(Base, ArgNum);
392 switch (Loc.getArgument().getKind()) {
393 case TemplateArgument::Type:
394 return Loc.getTypeSourceInfo()->getType()->getAsCXXRecordDecl();
395 case TemplateArgument::Null:
396 // Diag() was already called
399 Diag(Loc.getSourceRange().getBegin(), diag_warning) << Loc.getArgument().getKind() << "unsupported kind" << Loc.getSourceRange();
404 CXXRecordDecl *getTemplateArgDeclOfBase(const CXXBaseSpecifier *Base, unsigned ArgNum) {
405 TemplateArgumentLoc Loc;
406 return getTemplateArgDeclOfBase(Base, ArgNum, Loc);
409 void handleSimpleState(CXXRecordDecl *RecordDecl, const CXXBaseSpecifier *Base)
412 string name(RecordDecl->getName()); //getQualifiedNameAsString());
413 Diag(RecordDecl->getLocStart(), diag_found_state) << name;
416 // Either we saw a reference to forward declared state
417 // before, or we create a new state.
418 if (!(state = model.removeFromUndefinedContexts(name)))
419 state = new Model::State(name);
421 CXXRecordDecl *Context = getTemplateArgDeclOfBase(Base, 1);
423 Model::Context *c = model.findContext(Context->getName());
425 Model::State *s = new Model::State(Context->getName());
426 model.addUndefinedState(s);
432 TemplateArgumentLoc Loc;
433 if (MyCXXRecordDecl *InnerInitialState =
434 static_cast<MyCXXRecordDecl*>(getTemplateArgDeclOfBase(Base, 2, Loc))) {
435 if (InnerInitialState->isDerivedFrom("boost::statechart::simple_state") ||
436 InnerInitialState->isDerivedFrom("boost::statechart::state_machine"))
437 state->setInitialInnerState(InnerInitialState->getName());
439 Diag(Loc.getTypeSourceInfo()->getTypeLoc().getLocStart(), diag_warning)
440 << InnerInitialState->getName() << " as inner initial state is not supported" << Loc.getSourceRange();
443 // if (CXXRecordDecl *History = getTemplateArgDecl(Base->getType().getTypePtr(), 3))
444 // Diag(History->getLocStart(), diag_no_history);
446 IdentifierInfo& II = ASTCtx->Idents.get("reactions");
447 // TODO: Lookup for reactions even in base classes - probably by using Sema::LookupQualifiedName()
448 // TODO: Find when state has no reactions
449 for (DeclContext::lookup_result Reactions = RecordDecl->lookup(DeclarationName(&II));
450 Reactions.first != Reactions.second; ++Reactions.first)
452 HandleReaction(*Reactions.first, RecordDecl);
455 if(typedef_num == 0) {
456 Diag(RecordDecl->getLocStart(), diag_warning)
457 << " missing typedef for reactions in state : " << RecordDecl->getName();
461 void handleStateMachine(CXXRecordDecl *RecordDecl, const CXXBaseSpecifier *Base)
463 Model::Machine m(RecordDecl->getName());
464 Diag(RecordDecl->getLocStart(), diag_found_statemachine) << m.name;
466 if (MyCXXRecordDecl *InitialState =
467 static_cast<MyCXXRecordDecl*>(getTemplateArgDeclOfBase(Base, 1)))
468 m.setInitialState(InitialState->getName());
472 bool VisitCXXRecordDecl(CXXRecordDecl *Declaration)
474 if (!Declaration->isCompleteDefinition())
476 if (Declaration->getQualifiedNameAsString() == "boost::statechart::state" ||
477 Declaration->getQualifiedNameAsString() == "TimedState" ||
478 Declaration->getQualifiedNameAsString() == "TimedSimpleState")
479 return true; // This is an "abstract class" not a real state
481 MyCXXRecordDecl *RecordDecl = static_cast<MyCXXRecordDecl*>(Declaration);
482 const CXXBaseSpecifier *Base;
484 if (RecordDecl->isDerivedFrom("boost::statechart::simple_state", &Base))
485 handleSimpleState(RecordDecl, Base);
486 else if (RecordDecl->isDerivedFrom("boost::statechart::state_machine", &Base))
487 handleStateMachine(RecordDecl, Base);
488 else if (RecordDecl->isDerivedFrom("boost::statechart::event"))
490 //sc.events.push_back(RecordDecl->getNameAsString());
497 class VisualizeStatechartConsumer : public clang::ASTConsumer
503 explicit VisualizeStatechartConsumer(ASTContext *Context, std::string destFileName,
504 DiagnosticsEngine &D)
505 : visitor(Context, model, D), destFileName(destFileName) {}
507 virtual void HandleTranslationUnit(clang::ASTContext &Context) {
508 visitor.TraverseDecl(Context.getTranslationUnitDecl());
509 model.write_as_dot_file(destFileName);
513 class VisualizeStatechartAction : public PluginASTAction
516 ASTConsumer *CreateASTConsumer(CompilerInstance &CI, llvm::StringRef) {
517 size_t dot = getCurrentFile().find_last_of('.');
518 std::string dest = getCurrentFile().substr(0, dot);
520 return new VisualizeStatechartConsumer(&CI.getASTContext(), dest, CI.getDiagnostics());
523 bool ParseArgs(const CompilerInstance &CI,
524 const std::vector<std::string>& args) {
525 for (unsigned i = 0, e = args.size(); i != e; ++i) {
526 llvm::errs() << "Visualizer arg = " << args[i] << "\n";
528 // Example error handling.
529 if (args[i] == "-an-error") {
530 DiagnosticsEngine &D = CI.getDiagnostics();
531 unsigned DiagID = D.getCustomDiagID(
532 DiagnosticsEngine::Error, "invalid argument '" + args[i] + "'");
537 if (args.size() && args[0] == "help")
538 PrintHelp(llvm::errs());
542 void PrintHelp(llvm::raw_ostream& ros) {
543 ros << "Help for Visualize Statechart plugin goes here\n";
548 static FrontendPluginRegistry::Add<VisualizeStatechartAction> X("visualize-statechart", "visualize statechart");