blob: ff5ecc10de733d861ec0617be6fb72524c711471 [file] [log] [blame]
Argiris Kirtzidis970cfe12009-07-05 22:21:28 +00001//===--- ASTNode.h - A <Decl, Stmt> pair ------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// ASTNode is Decl or a Stmt and its immediate Decl parent.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTNode.h"
15#include "clang/AST/Decl.h"
16#include "clang/AST/Stmt.h"
17#include "clang/AST/Expr.h"
18using namespace clang;
19
20static bool isContainedInStatement(Stmt *Node, Stmt *Parent) {
21 assert(Node && Parent && "Passed null Node or Parent");
22
23 if (Node == Parent)
24 return true;
25
26 for (Stmt::child_iterator
27 I = Parent->child_begin(), E = Parent->child_end(); I != E; ++I) {
28 if (isContainedInStatement(Node, *I))
29 return true;
30 }
31
32 return false;
33}
34
35static Decl *FindImmediateParent(Decl *D, Stmt *Node) {
36 assert(D && Node && "Passed null Decl or null Stmt");
37
38 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
39 Expr *Init = VD->getInit();
40 if (Init == 0)
41 return 0;
42 return isContainedInStatement(Node, Init) ? D : 0;
43 }
44
45 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
46 if (!FD->isThisDeclarationADefinition())
47 return 0;
48
49 for (DeclContext::decl_iterator
50 I = FD->decls_begin(), E = FD->decls_end(); I != E; ++I) {
51 Decl *Child = FindImmediateParent(*I, Node);
52 if (Child)
53 return Child;
54 }
55
56 assert(FD->getBody() && "If not definition we should have exited already");
57 return isContainedInStatement(Node, FD->getBody()) ? D : 0;
58 }
59
60 return 0;
61}
62
63bool ASTNode::isImmediateParent(Decl *D, Stmt *Node) {
64 assert(D && Node && "Passed null Decl or null Stmt");
65 return D == FindImmediateParent(D, Node);
66}
67
68void ASTNode::print(llvm::raw_ostream &OS) {
69 assert(isValid() && "ASTNode is not valid");
70
71 OS << "[Decl: " << getDecl()->getDeclKindName() << " ";
72 if (NamedDecl *ND = dyn_cast<NamedDecl>(getDecl()))
73 OS << ND->getNameAsString();
74
75 if (getStmt()) {
76 ASTContext &Ctx = getDecl()->getASTContext();
77 OS << " | Stmt: " << getStmt()->getStmtClassName() << " ";
78 getStmt()->printPretty(OS, Ctx, 0, PrintingPolicy(Ctx.getLangOptions()));
79 }
80
81 OS << "] <";
82
83 SourceRange Range = hasStmt() ? getStmt()->getSourceRange()
84 : getDecl()->getSourceRange();
85 SourceManager &SourceMgr = getDecl()->getASTContext().getSourceManager();
86 Range.getBegin().print(OS, SourceMgr);
87 OS << ", ";
88 Range.getEnd().print(OS, SourceMgr);
89 OS << ">\n";
90}