CocoaConventions.cpp revision bb8fef382ad89b4bc202a1dbd4cd52ced7734479
1//===- CocoaConventions.h - Special handling of Cocoa conventions -*- 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// This file defines
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
15#include "clang/AST/Type.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclObjC.h"
18#include "llvm/ADT/StringExtras.h"
19
20using namespace clang;
21
22using llvm::StringRef;
23
24// The "fundamental rule" for naming conventions of methods:
25//  (url broken into two lines)
26//  http://developer.apple.com/documentation/Cocoa/Conceptual/
27//     MemoryMgmt/Tasks/MemoryManagementRules.html
28//
29// "You take ownership of an object if you create it using a method whose name
30//  begins with "alloc" or "new" or contains "copy" (for example, alloc,
31//  newObject, or mutableCopy), or if you send it a retain message. You are
32//  responsible for relinquishing ownership of objects you own using release
33//  or autorelease. Any other time you receive an object, you must
34//  not release it."
35//
36
37static bool isWordEnd(char ch, char prev, char next) {
38  return ch == '\0'
39      || (islower(prev) && isupper(ch)) // xxxC
40      || (isupper(prev) && isupper(ch) && islower(next)) // XXCreate
41      || !isalpha(ch);
42}
43
44static const char* parseWord(const char* s) {
45  char ch = *s, prev = '\0';
46  assert(ch != '\0');
47  char next = *(s+1);
48  while (!isWordEnd(ch, prev, next)) {
49    prev = ch;
50    ch = next;
51    next = *((++s)+1);
52  }
53  return s;
54}
55
56cocoa::NamingConvention cocoa::deriveNamingConvention(Selector S) {
57  IdentifierInfo *II = S.getIdentifierInfoForSlot(0);
58
59  if (!II)
60    return NoConvention;
61
62  const char *s = II->getNameStart();
63
64  // A method/function name may contain a prefix.  We don't know it is there,
65  // however, until we encounter the first '_'.
66  while (*s != '\0') {
67    // Skip '_', numbers, ':', etc.
68    if (*s == '_' || !isalpha(*s)) {
69      ++s;
70      continue;
71    }
72    break;
73  }
74
75  // Parse the first word, and look for specific keywords.
76  const char *wordEnd = parseWord(s);
77  assert(wordEnd > s);
78  unsigned len = wordEnd - s;
79
80  switch (len) {
81    default:
82      return NoConvention;
83    case 3:
84      // Methods starting with 'new' follow the create rule.
85      return (memcmp(s, "new", 3) == 0) ? CreateRule : NoConvention;
86    case 4:
87      // Methods starting with 'copy' follow the create rule.
88      if (memcmp(s, "copy", 4) == 0)
89        return CreateRule;
90      // Methods starting with 'init' follow the init rule.
91      if (memcmp(s, "init", 4) == 0)
92        return InitRule;
93      return NoConvention;
94    case 5:
95      return (memcmp(s, "alloc", 5) == 0) ? CreateRule : NoConvention;
96    case 7:
97      // Methods starting with 'mutableCopy' follow the create rule.
98      if (memcmp(s, "mutable", 7) == 0) {
99        // Look at the next word to see if it is "Copy".
100        s = wordEnd;
101        wordEnd = parseWord(s);
102        len = wordEnd - s;
103        if (len == 4 && memcmp(s, "Copy", 4) == 0)
104          return CreateRule;
105      }
106      return NoConvention;
107  }
108}
109
110bool cocoa::isRefType(QualType RetTy, llvm::StringRef Prefix,
111                      llvm::StringRef Name) {
112  // Recursively walk the typedef stack, allowing typedefs of reference types.
113  while (TypedefType* TD = dyn_cast<TypedefType>(RetTy.getTypePtr())) {
114    llvm::StringRef TDName = TD->getDecl()->getIdentifier()->getName();
115    if (TDName.startswith(Prefix) && TDName.endswith("Ref"))
116      return true;
117
118    RetTy = TD->getDecl()->getUnderlyingType();
119  }
120
121  if (Name.empty())
122    return false;
123
124  // Is the type void*?
125  const PointerType* PT = RetTy->getAs<PointerType>();
126  if (!(PT->getPointeeType().getUnqualifiedType()->isVoidType()))
127    return false;
128
129  // Does the name start with the prefix?
130  return Name.startswith(Prefix);
131}
132
133bool cocoa::isCFObjectRef(QualType T) {
134  return isRefType(T, "CF") || // Core Foundation.
135         isRefType(T, "CG") || // Core Graphics.
136         isRefType(T, "DADisk") || // Disk Arbitration API.
137         isRefType(T, "DADissenter") ||
138         isRefType(T, "DASessionRef");
139}
140
141
142bool cocoa::isCocoaObjectRef(QualType Ty) {
143  if (!Ty->isObjCObjectPointerType())
144    return false;
145
146  const ObjCObjectPointerType *PT = Ty->getAs<ObjCObjectPointerType>();
147
148  // Can be true for objects with the 'NSObject' attribute.
149  if (!PT)
150    return true;
151
152  // We assume that id<..>, id, Class, and Class<..> all represent tracked
153  // objects.
154  if (PT->isObjCIdType() || PT->isObjCQualifiedIdType() ||
155      PT->isObjCClassType() || PT->isObjCQualifiedClassType())
156    return true;
157
158  // Does the interface subclass NSObject?
159  // FIXME: We can memoize here if this gets too expensive.
160  const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
161
162  // Assume that anything declared with a forward declaration and no
163  // @interface subclasses NSObject.
164  if (ID->isForwardDecl())
165    return true;
166
167  for ( ; ID ; ID = ID->getSuperClass())
168    if (ID->getIdentifier()->getName() == "NSObject")
169      return true;
170
171  return false;
172}
173