NestedNameSpecifier.cpp revision 561f81243f665cf2001caadc45df505f826b72d6
1//===--- NestedNameSpecifier.cpp - C++ nested name specifiers -----*- 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 the NestedNameSpecifier class, which represents
11//  a C++ nested-name-specifier.
12//
13//===----------------------------------------------------------------------===//
14#include "clang/AST/NestedNameSpecifier.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/PrettyPrinter.h"
19#include "clang/AST/Type.h"
20#include "clang/AST/TypeLoc.h"
21#include "llvm/Support/raw_ostream.h"
22#include <cassert>
23
24using namespace clang;
25
26NestedNameSpecifier *
27NestedNameSpecifier::FindOrInsert(const ASTContext &Context,
28                                  const NestedNameSpecifier &Mockup) {
29  llvm::FoldingSetNodeID ID;
30  Mockup.Profile(ID);
31
32  void *InsertPos = 0;
33  NestedNameSpecifier *NNS
34    = Context.NestedNameSpecifiers.FindNodeOrInsertPos(ID, InsertPos);
35  if (!NNS) {
36    NNS = new (Context, 4) NestedNameSpecifier(Mockup);
37    Context.NestedNameSpecifiers.InsertNode(NNS, InsertPos);
38  }
39
40  return NNS;
41}
42
43NestedNameSpecifier *
44NestedNameSpecifier::Create(const ASTContext &Context,
45                            NestedNameSpecifier *Prefix, IdentifierInfo *II) {
46  assert(II && "Identifier cannot be NULL");
47  assert((!Prefix || Prefix->isDependent()) && "Prefix must be dependent");
48
49  NestedNameSpecifier Mockup;
50  Mockup.Prefix.setPointer(Prefix);
51  Mockup.Prefix.setInt(StoredIdentifier);
52  Mockup.Specifier = II;
53  return FindOrInsert(Context, Mockup);
54}
55
56NestedNameSpecifier *
57NestedNameSpecifier::Create(const ASTContext &Context,
58                            NestedNameSpecifier *Prefix, NamespaceDecl *NS) {
59  assert(NS && "Namespace cannot be NULL");
60  assert((!Prefix ||
61          (Prefix->getAsType() == 0 && Prefix->getAsIdentifier() == 0)) &&
62         "Broken nested name specifier");
63  NestedNameSpecifier Mockup;
64  Mockup.Prefix.setPointer(Prefix);
65  Mockup.Prefix.setInt(StoredNamespaceOrAlias);
66  Mockup.Specifier = NS;
67  return FindOrInsert(Context, Mockup);
68}
69
70NestedNameSpecifier *
71NestedNameSpecifier::Create(const ASTContext &Context,
72                            NestedNameSpecifier *Prefix,
73                            NamespaceAliasDecl *Alias) {
74  assert(Alias && "Namespace alias cannot be NULL");
75  assert((!Prefix ||
76          (Prefix->getAsType() == 0 && Prefix->getAsIdentifier() == 0)) &&
77         "Broken nested name specifier");
78  NestedNameSpecifier Mockup;
79  Mockup.Prefix.setPointer(Prefix);
80  Mockup.Prefix.setInt(StoredNamespaceOrAlias);
81  Mockup.Specifier = Alias;
82  return FindOrInsert(Context, Mockup);
83}
84
85NestedNameSpecifier *
86NestedNameSpecifier::Create(const ASTContext &Context,
87                            NestedNameSpecifier *Prefix,
88                            bool Template, const Type *T) {
89  assert(T && "Type cannot be NULL");
90  NestedNameSpecifier Mockup;
91  Mockup.Prefix.setPointer(Prefix);
92  Mockup.Prefix.setInt(Template? StoredTypeSpecWithTemplate : StoredTypeSpec);
93  Mockup.Specifier = const_cast<Type*>(T);
94  return FindOrInsert(Context, Mockup);
95}
96
97NestedNameSpecifier *
98NestedNameSpecifier::Create(const ASTContext &Context, IdentifierInfo *II) {
99  assert(II && "Identifier cannot be NULL");
100  NestedNameSpecifier Mockup;
101  Mockup.Prefix.setPointer(0);
102  Mockup.Prefix.setInt(StoredIdentifier);
103  Mockup.Specifier = II;
104  return FindOrInsert(Context, Mockup);
105}
106
107NestedNameSpecifier *
108NestedNameSpecifier::GlobalSpecifier(const ASTContext &Context) {
109  if (!Context.GlobalNestedNameSpecifier)
110    Context.GlobalNestedNameSpecifier = new (Context, 4) NestedNameSpecifier();
111  return Context.GlobalNestedNameSpecifier;
112}
113
114NestedNameSpecifier::SpecifierKind NestedNameSpecifier::getKind() const {
115  if (Specifier == 0)
116    return Global;
117
118  switch (Prefix.getInt()) {
119  case StoredIdentifier:
120    return Identifier;
121
122  case StoredNamespaceOrAlias:
123    return isa<NamespaceDecl>(static_cast<NamedDecl *>(Specifier))? Namespace
124                                                            : NamespaceAlias;
125
126  case StoredTypeSpec:
127    return TypeSpec;
128
129  case StoredTypeSpecWithTemplate:
130    return TypeSpecWithTemplate;
131  }
132
133  return Global;
134}
135
136/// \brief Retrieve the namespace stored in this nested name
137/// specifier.
138NamespaceDecl *NestedNameSpecifier::getAsNamespace() const {
139  if (Prefix.getInt() == StoredNamespaceOrAlias)
140    return dyn_cast<NamespaceDecl>(static_cast<NamedDecl *>(Specifier));
141
142  return 0;
143}
144
145/// \brief Retrieve the namespace alias stored in this nested name
146/// specifier.
147NamespaceAliasDecl *NestedNameSpecifier::getAsNamespaceAlias() const {
148  if (Prefix.getInt() == StoredNamespaceOrAlias)
149    return dyn_cast<NamespaceAliasDecl>(static_cast<NamedDecl *>(Specifier));
150
151  return 0;
152}
153
154
155/// \brief Whether this nested name specifier refers to a dependent
156/// type or not.
157bool NestedNameSpecifier::isDependent() const {
158  switch (getKind()) {
159  case Identifier:
160    // Identifier specifiers always represent dependent types
161    return true;
162
163  case Namespace:
164  case NamespaceAlias:
165  case Global:
166    return false;
167
168  case TypeSpec:
169  case TypeSpecWithTemplate:
170    return getAsType()->isDependentType();
171  }
172
173  // Necessary to suppress a GCC warning.
174  return false;
175}
176
177/// \brief Whether this nested name specifier refers to a dependent
178/// type or not.
179bool NestedNameSpecifier::isInstantiationDependent() const {
180  switch (getKind()) {
181  case Identifier:
182    // Identifier specifiers always represent dependent types
183    return true;
184
185  case Namespace:
186  case NamespaceAlias:
187  case Global:
188    return false;
189
190  case TypeSpec:
191  case TypeSpecWithTemplate:
192    return getAsType()->isInstantiationDependentType();
193  }
194
195  // Necessary to suppress a GCC warning.
196  return false;
197}
198
199bool NestedNameSpecifier::containsUnexpandedParameterPack() const {
200  switch (getKind()) {
201  case Identifier:
202    return getPrefix() && getPrefix()->containsUnexpandedParameterPack();
203
204  case Namespace:
205  case NamespaceAlias:
206  case Global:
207    return false;
208
209  case TypeSpec:
210  case TypeSpecWithTemplate:
211    return getAsType()->containsUnexpandedParameterPack();
212  }
213
214  // Necessary to suppress a GCC warning.
215  return false;
216}
217
218/// \brief Print this nested name specifier to the given output
219/// stream.
220void
221NestedNameSpecifier::print(llvm::raw_ostream &OS,
222                           const PrintingPolicy &Policy) const {
223  if (getPrefix())
224    getPrefix()->print(OS, Policy);
225
226  switch (getKind()) {
227  case Identifier:
228    OS << getAsIdentifier()->getName();
229    break;
230
231  case Namespace:
232    OS << getAsNamespace()->getName();
233    break;
234
235  case NamespaceAlias:
236    OS << getAsNamespaceAlias()->getName();
237    break;
238
239  case Global:
240    break;
241
242  case TypeSpecWithTemplate:
243    OS << "template ";
244    // Fall through to print the type.
245
246  case TypeSpec: {
247    std::string TypeStr;
248    const Type *T = getAsType();
249
250    PrintingPolicy InnerPolicy(Policy);
251    InnerPolicy.SuppressScope = true;
252
253    // Nested-name-specifiers are intended to contain minimally-qualified
254    // types. An actual ElaboratedType will not occur, since we'll store
255    // just the type that is referred to in the nested-name-specifier (e.g.,
256    // a TypedefType, TagType, etc.). However, when we are dealing with
257    // dependent template-id types (e.g., Outer<T>::template Inner<U>),
258    // the type requires its own nested-name-specifier for uniqueness, so we
259    // suppress that nested-name-specifier during printing.
260    assert(!isa<ElaboratedType>(T) &&
261           "Elaborated type in nested-name-specifier");
262    if (const TemplateSpecializationType *SpecType
263          = dyn_cast<TemplateSpecializationType>(T)) {
264      // Print the template name without its corresponding
265      // nested-name-specifier.
266      SpecType->getTemplateName().print(OS, InnerPolicy, true);
267
268      // Print the template argument list.
269      TypeStr = TemplateSpecializationType::PrintTemplateArgumentList(
270                                                          SpecType->getArgs(),
271                                                       SpecType->getNumArgs(),
272                                                                 InnerPolicy);
273    } else {
274      // Print the type normally
275      TypeStr = QualType(T, 0).getAsString(InnerPolicy);
276    }
277    OS << TypeStr;
278    break;
279  }
280  }
281
282  OS << "::";
283}
284
285void NestedNameSpecifier::dump(const LangOptions &LO) {
286  print(llvm::errs(), PrintingPolicy(LO));
287}
288
289unsigned
290NestedNameSpecifierLoc::getLocalDataLength(NestedNameSpecifier *Qualifier) {
291  assert(Qualifier && "Expected a non-NULL qualifier");
292
293  // Location of the trailing '::'.
294  unsigned Length = sizeof(unsigned);
295
296  switch (Qualifier->getKind()) {
297  case NestedNameSpecifier::Global:
298    // Nothing more to add.
299    break;
300
301  case NestedNameSpecifier::Identifier:
302  case NestedNameSpecifier::Namespace:
303  case NestedNameSpecifier::NamespaceAlias:
304    // The location of the identifier or namespace name.
305    Length += sizeof(unsigned);
306    break;
307
308  case NestedNameSpecifier::TypeSpecWithTemplate:
309  case NestedNameSpecifier::TypeSpec:
310    // The "void*" that points at the TypeLoc data.
311    // Note: the 'template' keyword is part of the TypeLoc.
312    Length += sizeof(void *);
313    break;
314  }
315
316  return Length;
317}
318
319unsigned
320NestedNameSpecifierLoc::getDataLength(NestedNameSpecifier *Qualifier) {
321  unsigned Length = 0;
322  for (; Qualifier; Qualifier = Qualifier->getPrefix())
323    Length += getLocalDataLength(Qualifier);
324  return Length;
325}
326
327namespace {
328  /// \brief Load a (possibly unaligned) source location from a given address
329  /// and offset.
330  SourceLocation LoadSourceLocation(void *Data, unsigned Offset) {
331    unsigned Raw;
332    memcpy(&Raw, static_cast<char *>(Data) + Offset, sizeof(unsigned));
333    return SourceLocation::getFromRawEncoding(Raw);
334  }
335
336  /// \brief Load a (possibly unaligned) pointer from a given address and
337  /// offset.
338  void *LoadPointer(void *Data, unsigned Offset) {
339    void *Result;
340    memcpy(&Result, static_cast<char *>(Data) + Offset, sizeof(void*));
341    return Result;
342  }
343}
344
345SourceRange NestedNameSpecifierLoc::getSourceRange() const {
346  if (!Qualifier)
347    return SourceRange();
348
349  NestedNameSpecifierLoc First = *this;
350  while (NestedNameSpecifierLoc Prefix = First.getPrefix())
351    First = Prefix;
352
353  return SourceRange(First.getLocalSourceRange().getBegin(),
354                     getLocalSourceRange().getEnd());
355}
356
357SourceRange NestedNameSpecifierLoc::getLocalSourceRange() const {
358  if (!Qualifier)
359    return SourceRange();
360
361  unsigned Offset = getDataLength(Qualifier->getPrefix());
362  switch (Qualifier->getKind()) {
363  case NestedNameSpecifier::Global:
364    return LoadSourceLocation(Data, Offset);
365
366  case NestedNameSpecifier::Identifier:
367  case NestedNameSpecifier::Namespace:
368  case NestedNameSpecifier::NamespaceAlias:
369    return SourceRange(LoadSourceLocation(Data, Offset),
370                       LoadSourceLocation(Data, Offset + sizeof(unsigned)));
371
372  case NestedNameSpecifier::TypeSpecWithTemplate:
373  case NestedNameSpecifier::TypeSpec: {
374    // The "void*" that points at the TypeLoc data.
375    // Note: the 'template' keyword is part of the TypeLoc.
376    void *TypeData = LoadPointer(Data, Offset);
377    TypeLoc TL(Qualifier->getAsType(), TypeData);
378    return SourceRange(TL.getBeginLoc(),
379                       LoadSourceLocation(Data, Offset + sizeof(void*)));
380  }
381  }
382
383  return SourceRange();
384}
385
386TypeLoc NestedNameSpecifierLoc::getTypeLoc() const {
387  assert((Qualifier->getKind() == NestedNameSpecifier::TypeSpec ||
388          Qualifier->getKind() == NestedNameSpecifier::TypeSpecWithTemplate) &&
389         "Nested-name-specifier location is not a type");
390
391  // The "void*" that points at the TypeLoc data.
392  unsigned Offset = getDataLength(Qualifier->getPrefix());
393  void *TypeData = LoadPointer(Data, Offset);
394  return TypeLoc(Qualifier->getAsType(), TypeData);
395}
396
397namespace {
398  void Append(char *Start, char *End, char *&Buffer, unsigned &BufferSize,
399              unsigned &BufferCapacity) {
400    if (BufferSize + (End - Start) > BufferCapacity) {
401      // Reallocate the buffer.
402      unsigned NewCapacity
403      = std::max((unsigned)(BufferCapacity? BufferCapacity * 2
404                            : sizeof(void*) * 2),
405                 (unsigned)(BufferSize + (End - Start)));
406      char *NewBuffer = static_cast<char *>(malloc(NewCapacity));
407      memcpy(NewBuffer, Buffer, BufferSize);
408
409      if (BufferCapacity)
410        free(Buffer);
411      Buffer = NewBuffer;
412      BufferCapacity = NewCapacity;
413    }
414
415    memcpy(Buffer + BufferSize, Start, End - Start);
416    BufferSize += End-Start;
417  }
418
419  /// \brief Save a source location to the given buffer.
420  void SaveSourceLocation(SourceLocation Loc, char *&Buffer,
421                          unsigned &BufferSize, unsigned &BufferCapacity) {
422    unsigned Raw = Loc.getRawEncoding();
423    Append(reinterpret_cast<char *>(&Raw),
424           reinterpret_cast<char *>(&Raw) + sizeof(unsigned),
425           Buffer, BufferSize, BufferCapacity);
426  }
427
428  /// \brief Save a pointer to the given buffer.
429  void SavePointer(void *Ptr, char *&Buffer, unsigned &BufferSize,
430                   unsigned &BufferCapacity) {
431    Append(reinterpret_cast<char *>(&Ptr),
432           reinterpret_cast<char *>(&Ptr) + sizeof(void *),
433           Buffer, BufferSize, BufferCapacity);
434  }
435}
436
437NestedNameSpecifierLocBuilder::NestedNameSpecifierLocBuilder()
438  : Representation(0), Buffer(0), BufferSize(0), BufferCapacity(0) { }
439
440NestedNameSpecifierLocBuilder::
441NestedNameSpecifierLocBuilder(const NestedNameSpecifierLocBuilder &Other)
442  : Representation(Other.Representation), Buffer(0),
443    BufferSize(0), BufferCapacity(0)
444{
445  if (!Other.Buffer)
446    return;
447
448  if (Other.BufferCapacity == 0) {
449    // Shallow copy is okay.
450    Buffer = Other.Buffer;
451    BufferSize = Other.BufferSize;
452    return;
453  }
454
455  // Deep copy
456  BufferSize = Other.BufferSize;
457  BufferCapacity = Other.BufferSize;
458  Buffer = static_cast<char *>(malloc(BufferCapacity));
459  memcpy(Buffer, Other.Buffer, BufferSize);
460}
461
462NestedNameSpecifierLocBuilder &
463NestedNameSpecifierLocBuilder::
464operator=(const NestedNameSpecifierLocBuilder &Other) {
465  Representation = Other.Representation;
466
467  if (Buffer && Other.Buffer && BufferCapacity >= Other.BufferSize) {
468    // Re-use our storage.
469    BufferSize = Other.BufferSize;
470    memcpy(Buffer, Other.Buffer, BufferSize);
471    return *this;
472  }
473
474  // Free our storage, if we have any.
475  if (BufferCapacity) {
476    free(Buffer);
477    BufferCapacity = 0;
478  }
479
480  if (!Other.Buffer) {
481    // Empty.
482    Buffer = 0;
483    BufferSize = 0;
484    return *this;
485  }
486
487  if (Other.BufferCapacity == 0) {
488    // Shallow copy is okay.
489    Buffer = Other.Buffer;
490    BufferSize = Other.BufferSize;
491    return *this;
492  }
493
494  // Deep copy.
495  BufferSize = Other.BufferSize;
496  BufferCapacity = BufferSize;
497  Buffer = static_cast<char *>(malloc(BufferSize));
498  memcpy(Buffer, Other.Buffer, BufferSize);
499  return *this;
500}
501
502NestedNameSpecifierLocBuilder::~NestedNameSpecifierLocBuilder() {
503  if (BufferCapacity)
504    free(Buffer);
505}
506
507void NestedNameSpecifierLocBuilder::Extend(ASTContext &Context,
508                                           SourceLocation TemplateKWLoc,
509                                           TypeLoc TL,
510                                           SourceLocation ColonColonLoc) {
511  Representation = NestedNameSpecifier::Create(Context, Representation,
512                                               TemplateKWLoc.isValid(),
513                                               TL.getTypePtr());
514
515  // Push source-location info into the buffer.
516  SavePointer(TL.getOpaqueData(), Buffer, BufferSize, BufferCapacity);
517  SaveSourceLocation(ColonColonLoc, Buffer, BufferSize, BufferCapacity);
518}
519
520void NestedNameSpecifierLocBuilder::Extend(ASTContext &Context,
521                                           IdentifierInfo *Identifier,
522                                           SourceLocation IdentifierLoc,
523                                           SourceLocation ColonColonLoc) {
524  Representation = NestedNameSpecifier::Create(Context, Representation,
525                                               Identifier);
526
527  // Push source-location info into the buffer.
528  SaveSourceLocation(IdentifierLoc, Buffer, BufferSize, BufferCapacity);
529  SaveSourceLocation(ColonColonLoc, Buffer, BufferSize, BufferCapacity);
530}
531
532void NestedNameSpecifierLocBuilder::Extend(ASTContext &Context,
533                                           NamespaceDecl *Namespace,
534                                           SourceLocation NamespaceLoc,
535                                           SourceLocation ColonColonLoc) {
536  Representation = NestedNameSpecifier::Create(Context, Representation,
537                                               Namespace);
538
539  // Push source-location info into the buffer.
540  SaveSourceLocation(NamespaceLoc, Buffer, BufferSize, BufferCapacity);
541  SaveSourceLocation(ColonColonLoc, Buffer, BufferSize, BufferCapacity);
542}
543
544void NestedNameSpecifierLocBuilder::Extend(ASTContext &Context,
545                                           NamespaceAliasDecl *Alias,
546                                           SourceLocation AliasLoc,
547                                           SourceLocation ColonColonLoc) {
548  Representation = NestedNameSpecifier::Create(Context, Representation, Alias);
549
550  // Push source-location info into the buffer.
551  SaveSourceLocation(AliasLoc, Buffer, BufferSize, BufferCapacity);
552  SaveSourceLocation(ColonColonLoc, Buffer, BufferSize, BufferCapacity);
553}
554
555void NestedNameSpecifierLocBuilder::MakeGlobal(ASTContext &Context,
556                                               SourceLocation ColonColonLoc) {
557  assert(!Representation && "Already have a nested-name-specifier!?");
558  Representation = NestedNameSpecifier::GlobalSpecifier(Context);
559
560  // Push source-location info into the buffer.
561  SaveSourceLocation(ColonColonLoc, Buffer, BufferSize, BufferCapacity);
562}
563
564void NestedNameSpecifierLocBuilder::MakeTrivial(ASTContext &Context,
565                                                NestedNameSpecifier *Qualifier,
566                                                SourceRange R) {
567  Representation = Qualifier;
568
569  // Construct bogus (but well-formed) source information for the
570  // nested-name-specifier.
571  BufferSize = 0;
572  llvm::SmallVector<NestedNameSpecifier *, 4> Stack;
573  for (NestedNameSpecifier *NNS = Qualifier; NNS; NNS = NNS->getPrefix())
574    Stack.push_back(NNS);
575  while (!Stack.empty()) {
576    NestedNameSpecifier *NNS = Stack.back();
577    Stack.pop_back();
578    switch (NNS->getKind()) {
579      case NestedNameSpecifier::Identifier:
580      case NestedNameSpecifier::Namespace:
581      case NestedNameSpecifier::NamespaceAlias:
582        SaveSourceLocation(R.getBegin(), Buffer, BufferSize, BufferCapacity);
583        break;
584
585      case NestedNameSpecifier::TypeSpec:
586      case NestedNameSpecifier::TypeSpecWithTemplate: {
587        TypeSourceInfo *TSInfo
588        = Context.getTrivialTypeSourceInfo(QualType(NNS->getAsType(), 0),
589                                           R.getBegin());
590        SavePointer(TSInfo->getTypeLoc().getOpaqueData(), Buffer, BufferSize,
591                    BufferCapacity);
592        break;
593      }
594
595      case NestedNameSpecifier::Global:
596        break;
597    }
598
599    // Save the location of the '::'.
600    SaveSourceLocation(Stack.empty()? R.getEnd() : R.getBegin(),
601                       Buffer, BufferSize, BufferCapacity);
602  }
603}
604
605void NestedNameSpecifierLocBuilder::Adopt(NestedNameSpecifierLoc Other) {
606  if (BufferCapacity)
607    free(Buffer);
608
609  if (!Other) {
610    Representation = 0;
611    BufferSize = 0;
612    return;
613  }
614
615  // Rather than copying the data (which is wasteful), "adopt" the
616  // pointer (which points into the ASTContext) but set the capacity to zero to
617  // indicate that we don't own it.
618  Representation = Other.getNestedNameSpecifier();
619  Buffer = static_cast<char *>(Other.getOpaqueData());
620  BufferSize = Other.getDataLength();
621  BufferCapacity = 0;
622}
623
624NestedNameSpecifierLoc
625NestedNameSpecifierLocBuilder::getWithLocInContext(ASTContext &Context) const {
626  if (!Representation)
627    return NestedNameSpecifierLoc();
628
629  // If we adopted our data pointer from elsewhere in the AST context, there's
630  // no need to copy the memory.
631  if (BufferCapacity == 0)
632    return NestedNameSpecifierLoc(Representation, Buffer);
633
634  // FIXME: After copying the source-location information, should we free
635  // our (temporary) buffer and adopt the ASTContext-allocated memory?
636  // Doing so would optimize repeated calls to getWithLocInContext().
637  void *Mem = Context.Allocate(BufferSize, llvm::alignOf<void *>());
638  memcpy(Mem, Buffer, BufferSize);
639  return NestedNameSpecifierLoc(Representation, Mem);
640}
641
642