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;
66 explicit State(string name) : name(name) {}
67 void setInitialInnerState(string name) { initialInnerState = name; }
68 friend ostream& operator<<(ostream& os, const State& s);
72 Context::iterator Context::add(State *state)
74 pair<iterator, bool> ret = insert(value_type(state->name, state));
78 Context *Context::findContext(const string &name)
80 iterator i = find(name), e;
83 for (i = begin(), e = end(); i != e; ++i) {
84 Context *c = i->second->findContext(name);
92 ostream& operator<<(ostream& os, const Context& c);
94 ostream& operator<<(ostream& os, const State& s)
97 os << indent << "subgraph cluster_" << s.name << " {\n" << indent_inc;
98 os << indent << "label = \"" << s.name << "\"\n";
100 os << indent << "" << s.name << "\n";
102 os << indent << s.initialInnerState << " [peripheries=2]\n";
103 os << static_cast<Context>(s);
104 os << indent_dec << indent << "}\n";
110 ostream& operator<<(ostream& os, const Context& c)
112 for (Context::const_iterator i = c.begin(), e = c.end(); i != e; i++) {
122 const string src, dst, event;
123 Transition(string src, string dst, string event) : src(src), dst(dst), event(event) {}
126 ostream& operator<<(ostream& os, const Transition& t)
128 os << indent << t.src << " -> " << t.dst << " [label = \"" << t.event << "\"]\n";
133 class Machine : public Context
136 string initial_state;
139 explicit Machine(string name) : name(name) {}
141 void setInitialState(string name) { initial_state = name; }
143 friend ostream& operator<<(ostream& os, const Machine& m);
146 ostream& operator<<(ostream& os, const Machine& m)
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";
156 class Model : public map<string, Machine>
159 list< Transition*> transitions;
161 iterator add(const Machine &m)
163 pair<iterator, bool> ret = insert(value_type(m.name, m));
167 Context *findContext(const string &name)
169 iterator i = find(name), e;
172 for (i = begin(), e = end(); i != e; ++i) {
173 Context *c = i->second.findContext(name);
180 void write_as_dot_file(string fn)
182 ofstream f(fn.c_str());
183 f << "digraph statecharts {\n" << indent_inc;
184 for (iterator i = begin(), e = end(); i != e; i++)
186 for (list<Transition*>::iterator t = transitions.begin(), e = transitions.end(); t != e; ++t)
188 f << indent_dec << "}\n";
194 class MyCXXRecordDecl : public CXXRecordDecl
196 static bool FindBaseClassString(const CXXBaseSpecifier *Specifier,
200 string qn(static_cast<const char*>(qualName));
201 const RecordType *rt = Specifier->getType()->getAs<RecordType>();
203 TagDecl *canon = rt->getDecl()->getCanonicalDecl();
204 return canon->getQualifiedNameAsString() == qn;
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))
214 *Base = Paths.front().back().Base;
220 class Visitor : public RecursiveASTVisitor<Visitor>
224 DiagnosticsEngine &Diags;
225 unsigned diag_unhandled_reaction_type, diag_unhandled_reaction_decl,
226 diag_found_state, diag_found_statemachine;
229 bool shouldVisitTemplateInstantiations() const { return true; }
231 explicit Visitor(ASTContext *Context, Model::Model &model, DiagnosticsEngine &Diags)
232 : ASTCtx(Context), model(model), Diags(Diags)
234 diag_found_statemachine =
235 Diags.getCustomDiagID(DiagnosticsEngine::Note, "Found statemachine '%0'");
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'");
244 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) { return Diags.Report(Loc, DiagID); }
246 void HandleReaction(const Type *T, const SourceLocation Loc, CXXRecordDecl *SrcState)
248 if (const ElaboratedType *ET = dyn_cast<ElaboratedType>(T))
249 HandleReaction(ET->getNamedType().getTypePtr(), Loc, SrcState);
250 else if (const TemplateSpecializationType *TST = dyn_cast<TemplateSpecializationType>(T)) {
251 string name = TST->getTemplateName().getAsTemplateDecl()->getQualifiedNameAsString();
252 if (name == "boost::statechart::transition") {
253 const Type *EventType = TST->getArg(0).getAsType().getTypePtr();
254 const Type *DstStateType = TST->getArg(1).getAsType().getTypePtr();
255 CXXRecordDecl *Event = EventType->getAsCXXRecordDecl();
256 CXXRecordDecl *DstState = DstStateType->getAsCXXRecordDecl();
258 Model::Transition *T = new Model::Transition(SrcState->getName(), DstState->getName(), Event->getName());
259 model.transitions.push_back(T);
260 } else if (name == "boost::mpl::list") {
261 for (TemplateSpecializationType::iterator Arg = TST->begin(), End = TST->end(); Arg != End; ++Arg)
262 HandleReaction(Arg->getAsType().getTypePtr(), Loc, SrcState);
264 //->getDecl()->getQualifiedNameAsString();
266 Diag(Loc, diag_unhandled_reaction_type) << T->getTypeClassName();
269 void HandleReaction(const NamedDecl *Decl, CXXRecordDecl *SrcState)
271 if (const TypedefDecl *r = dyn_cast<TypedefDecl>(Decl))
272 HandleReaction(r->getCanonicalDecl()->getUnderlyingType().getTypePtr(),
273 r->getLocStart(), SrcState);
275 Diag(Decl->getLocation(), diag_unhandled_reaction_decl) << Decl->getDeclKindName();
278 CXXRecordDecl *getTemplateArgDecl(const Type *T, unsigned ArgNum)
280 if (const ElaboratedType *ET = dyn_cast<ElaboratedType>(T))
281 return getTemplateArgDecl(ET->getNamedType().getTypePtr(), ArgNum);
282 else if (const TemplateSpecializationType *TST = dyn_cast<TemplateSpecializationType>(T)) {
283 if (TST->getNumArgs() >= ArgNum+1)
284 return TST->getArg(ArgNum).getAsType()->getAsCXXRecordDecl();
290 bool VisitCXXRecordDecl(CXXRecordDecl *Declaration)
292 if (!Declaration->isCompleteDefinition())
295 MyCXXRecordDecl *RecordDecl = static_cast<MyCXXRecordDecl*>(Declaration);
296 const CXXBaseSpecifier *Base;
298 if (RecordDecl->isDerivedFrom("boost::statechart::simple_state", &Base))
300 string name(RecordDecl->getName()); //getQualifiedNameAsString());
301 Diag(RecordDecl->getLocStart(), diag_found_state) << name;
303 Model::State *state = new Model::State(name);
305 CXXRecordDecl *Context = getTemplateArgDecl(Base->getType().getTypePtr(), 1);
306 Model::Context *c = model.findContext(Context->getName());
310 if (CXXRecordDecl *InnerInitialState = getTemplateArgDecl(Base->getType().getTypePtr(), 2))
311 state->setInitialInnerState(InnerInitialState->getName());
313 IdentifierInfo& II = ASTCtx->Idents.get("reactions");
314 // TODO: Lookup for reactions even in base classes - probably by using Sema::LookupQualifiedName()
315 for (DeclContext::lookup_result Reactions = RecordDecl->lookup(DeclarationName(&II));
316 Reactions.first != Reactions.second; ++Reactions.first)
317 HandleReaction(*Reactions.first, RecordDecl);
319 else if (RecordDecl->isDerivedFrom("boost::statechart::state_machine", &Base))
321 Model::Machine m(RecordDecl->getName());
322 Diag(RecordDecl->getLocStart(), diag_found_statemachine) << m.name;
324 if (CXXRecordDecl *InitialState = getTemplateArgDecl(Base->getType().getTypePtr(), 1))
325 m.setInitialState(InitialState->getName());
328 else if (RecordDecl->isDerivedFrom("boost::statechart::event"))
330 //sc.events.push_back(RecordDecl->getNameAsString());
337 class VisualizeStatechartConsumer : public clang::ASTConsumer
343 explicit VisualizeStatechartConsumer(ASTContext *Context, std::string destFileName,
344 DiagnosticsEngine &D)
345 : visitor(Context, model, D), destFileName(destFileName) {}
347 virtual void HandleTranslationUnit(clang::ASTContext &Context) {
348 visitor.TraverseDecl(Context.getTranslationUnitDecl());
349 model.write_as_dot_file(destFileName);
353 class VisualizeStatechartAction : public PluginASTAction
356 ASTConsumer *CreateASTConsumer(CompilerInstance &CI, llvm::StringRef) {
357 size_t dot = getCurrentFile().find_last_of('.');
358 std::string dest = getCurrentFile().substr(0, dot);
360 return new VisualizeStatechartConsumer(&CI.getASTContext(), dest, CI.getDiagnostics());
363 bool ParseArgs(const CompilerInstance &CI,
364 const std::vector<std::string>& args) {
365 for (unsigned i = 0, e = args.size(); i != e; ++i) {
366 llvm::errs() << "Visualizer arg = " << args[i] << "\n";
368 // Example error handling.
369 if (args[i] == "-an-error") {
370 DiagnosticsEngine &D = CI.getDiagnostics();
371 unsigned DiagID = D.getCustomDiagID(
372 DiagnosticsEngine::Error, "invalid argument '" + args[i] + "'");
377 if (args.size() && args[0] == "help")
378 PrintHelp(llvm::errs());
382 void PrintHelp(llvm::raw_ostream& ros) {
383 ros << "Help for Visualize Statechart plugin goes here\n";
388 static FrontendPluginRegistry::Add<VisualizeStatechartAction> X("visualize-statechart", "visualize statechart");