summaryrefslogtreecommitdiffstats
path: root/lib/Sema/CodeCompleteConsumer.cpp
blob: 88ac4e49cf9edb2d2fd412470be7846d4141e546 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
//===--- CodeCompleteConsumer.cpp - Code Completion Interface ---*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//  This file implements the CodeCompleteConsumer class.
//
//===----------------------------------------------------------------------===//
#include "clang/Sema/CodeCompleteConsumer.h"
#include "clang/AST/DeclCXX.h"
#include "clang/Parse/Scope.h"
#include "clang/Lex/Preprocessor.h"
#include "Sema.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cstring>
#include <functional>

using namespace clang;
using llvm::StringRef;

//===----------------------------------------------------------------------===//
// Code completion string implementation
//===----------------------------------------------------------------------===//
CodeCompletionString::Chunk::Chunk(ChunkKind Kind, llvm::StringRef Text) 
  : Kind(Kind), Text("")
{
  switch (Kind) {
  case CK_TypedText:
  case CK_Text:
  case CK_Placeholder:
  case CK_Informative:
  case CK_CurrentParameter: {
    char *New = new char [Text.size() + 1];
    std::memcpy(New, Text.data(), Text.size());
    New[Text.size()] = '\0';
    this->Text = New;
    break;
  }

  case CK_Optional:
    llvm::llvm_unreachable("Optional strings cannot be created from text");
    break;
      
  case CK_LeftParen:
    this->Text = "(";
    break;

  case CK_RightParen:
    this->Text = ")";
    break;

  case CK_LeftBracket:
    this->Text = "[";
    break;
    
  case CK_RightBracket:
    this->Text = "]";
    break;
    
  case CK_LeftBrace:
    this->Text = "{";
    break;

  case CK_RightBrace:
    this->Text = "}";
    break;

  case CK_LeftAngle:
    this->Text = "<";
    break;
    
  case CK_RightAngle:
    this->Text = ">";
    break;
      
  case CK_Comma:
    this->Text = ", ";
    break;
  }
}

CodeCompletionString::Chunk
CodeCompletionString::Chunk::CreateText(StringRef Text) {
  return Chunk(CK_Text, Text);
}

CodeCompletionString::Chunk 
CodeCompletionString::Chunk::CreateOptional(
                                 std::auto_ptr<CodeCompletionString> Optional) {
  Chunk Result;
  Result.Kind = CK_Optional;
  Result.Optional = Optional.release();
  return Result;
}

CodeCompletionString::Chunk 
CodeCompletionString::Chunk::CreatePlaceholder(StringRef Placeholder) {
  return Chunk(CK_Placeholder, Placeholder);
}

CodeCompletionString::Chunk 
CodeCompletionString::Chunk::CreateInformative(StringRef Informative) {
  return Chunk(CK_Informative, Informative);
}

CodeCompletionString::Chunk 
CodeCompletionString::Chunk::CreateCurrentParameter(
                                                StringRef CurrentParameter) {
  return Chunk(CK_CurrentParameter, CurrentParameter);
}


void
CodeCompletionString::Chunk::Destroy() {
  switch (Kind) {
  case CK_Optional: 
    delete Optional; 
    break;
      
  case CK_TypedText:
  case CK_Text: 
  case CK_Placeholder:
  case CK_Informative:
  case CK_CurrentParameter:
    delete [] Text;
    break;

  case CK_LeftParen:
  case CK_RightParen:
  case CK_LeftBracket:
  case CK_RightBracket:
  case CK_LeftBrace:
  case CK_RightBrace:
  case CK_LeftAngle:
  case CK_RightAngle:
  case CK_Comma:
    break;
  }
}

CodeCompletionString::~CodeCompletionString() {
  std::for_each(Chunks.begin(), Chunks.end(), 
                std::mem_fun_ref(&Chunk::Destroy));
}

std::string CodeCompletionString::getAsString() const {
  std::string Result;
  llvm::raw_string_ostream OS(Result);
                          
  for (iterator C = begin(), CEnd = end(); C != CEnd; ++C) {
    switch (C->Kind) {
    case CK_Optional: OS << "{#" << C->Optional->getAsString() << "#}"; break;
    case CK_Placeholder: OS << "<#" << C->Text << "#>"; break;
    case CK_Informative: OS << "[#" << C->Text << "#]"; break;
    case CK_CurrentParameter: OS << "<#" << C->Text << "#>"; break;
    default: OS << C->Text; break;
    }
  }
  OS.flush();
  return Result;
}


namespace {
  // Escape a string for XML-like formatting.
  struct EscapedString {
    EscapedString(llvm::StringRef Str) : Str(Str) { }
    
    llvm::StringRef Str;
  };
  
  llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, EscapedString EStr) {
    llvm::StringRef Str = EStr.Str;
    while (!Str.empty()) {
      // Find the next escaped character.
      llvm::StringRef::size_type Pos = Str.find_first_of("<>&\"'");
      
      // Print everything before that escaped character.
      OS << Str.substr(0, Pos);

      // If we didn't find any escaped characters, we're done.
      if (Pos == llvm::StringRef::npos)
        break;
      
      // Print the appropriate escape sequence.
      switch (Str[Pos]) {
        case '<': OS << "&lt;"; break;
        case '>': OS << "&gt;"; break;
        case '&': OS << "&amp;"; break;
        case '"': OS << "&quot;"; break;
        case '\'': OS << "&apos;"; break;
      }
      
      // Remove everything up to and including that escaped character.
      Str = Str.substr(Pos + 1);
    }
    
    return OS;
  }
  
  /// \brief Remove XML-like escaping from a string.
  std::string UnescapeString(llvm::StringRef Str) {
    using llvm::StringRef;
    
    std::string Result;
    llvm::raw_string_ostream OS(Result);
    
    while (!Str.empty()) {
      StringRef::size_type Amp = Str.find('&');
      OS << Str.substr(0, Amp);
      
      if (Amp == StringRef::npos)
        break;
      
      StringRef::size_type Semi = Str.substr(Amp).find(';');
      if (Semi == StringRef::npos) {
        // Malformed input; do the best we can.
        OS << '&';
        Str = Str.substr(Amp + 1);
        continue;
      }
      
      char Unescaped = llvm::StringSwitch<char>(Str.substr(Amp + 1, Semi - 1))
        .Case("lt", '<')
        .Case("gt", '>')
        .Case("amp", '&')
        .Case("quot", '"')
        .Case("apos", '\'')
        .Default('\0');
      
      if (Unescaped)
        OS << Unescaped;
      else
        OS << Str.substr(Amp, Semi + 1);
      Str = Str.substr(Amp + Semi + 1);
    }
    
    return OS.str();
  }
}

void CodeCompletionString::Serialize(llvm::raw_ostream &OS) const {
  for (iterator C = begin(), CEnd = end(); C != CEnd; ++C) {
    switch (C->Kind) {
    case CK_TypedText:
      OS << "<typed-text>" << EscapedString(C->Text) << "</>";
      break;
    case CK_Text:
      OS << "<text>" << EscapedString(C->Text) << "</>";
      break;
    case CK_Optional:
      OS << "<optional>";
      C->Optional->Serialize(OS);
      OS << "</>";
      break;
    case CK_Placeholder:
      OS << "<placeholder>" << EscapedString(C->Text) << "</>";
      break;
    case CK_Informative:
      OS << "<informative>" << EscapedString(C->Text) << "</>";
      break;
    case CK_CurrentParameter:
      OS << "<current-parameter>" << EscapedString(C->Text) << "</>";
      break;
    case CK_LeftParen:
      OS << "<lparen/>";
      break;
    case CK_RightParen:
      OS << "<rparen/>";
      break;
    case CK_LeftBracket:
      OS << "<lbracket/>";
      break;
    case CK_RightBracket:
      OS << "<rbracket/>";
      break;
    case CK_LeftBrace:
      OS << "<lbrace/>";
      break;
    case CK_RightBrace:
      OS << "<rbrace/>";
      break;
    case CK_LeftAngle:
      OS << "<langle/>";
      break;
    case CK_RightAngle:
      OS << "<rangle/>";
      break;
    case CK_Comma:
      OS << "<comma/>";
      break;
    }  
  }
}

/// \brief Parse the next XML-ish tag of the form <blah>.
///
/// \param Str the string in which we're looking for the next tag.
///
/// \param TagPos if successful, will be set to the start of the tag we found.
///
/// \param Standalone will indicate whether this is a "standalone" tag that
/// has no associated data, e.g., <comma/>.
///
/// \param Terminator will indicate whether this is a terminating tag (that is
/// or starts with '/').
///
/// \returns the tag itself, without the angle brackets.
static llvm::StringRef ParseNextTag(llvm::StringRef Str, 
                                    llvm::StringRef::size_type &StartTag,
                                    llvm::StringRef::size_type &AfterTag,
                                    bool &Standalone, bool &Terminator) {
  using llvm::StringRef;
  
  Standalone = false;
  Terminator = false;
  AfterTag = StringRef::npos;
  
  // Find the starting '<'. 
  StartTag = Str.find('<');
  if (StartTag == StringRef::npos)
    return llvm::StringRef();
  
  // Find the corresponding '>'.
  llvm::StringRef::size_type EndTag = Str.substr(StartTag).find('>');
  if (EndTag == StringRef::npos)
    return llvm::StringRef();
  AfterTag = StartTag + EndTag + 1;
  
  // Determine whether this is a terminating tag.
  if (Str[StartTag + 1] == '/') {
    Terminator = true;
    Str = Str.substr(1);
    --EndTag;
  }
  
  // Determine whether this is a standalone tag.
  if (!Terminator && Str[StartTag + EndTag - 1] == '/') {
    Standalone = true;
    if (EndTag > 1)
      --EndTag;
  }

  return Str.substr(StartTag + 1, EndTag - 1);
}

CodeCompletionString *CodeCompletionString::Deserialize(llvm::StringRef &Str) {
  using llvm::StringRef;
  
  CodeCompletionString *Result = new CodeCompletionString;
  
  do {
    // Parse the next tag.
    StringRef::size_type StartTag, AfterTag;
    bool Standalone, Terminator;
    StringRef Tag = ParseNextTag(Str, StartTag, AfterTag, Standalone, 
                                 Terminator);
    
    if (StartTag == StringRef::npos)
      break;
    
    // Figure out what kind of chunk we have.
    const unsigned UnknownKind = 10000;
    unsigned Kind = llvm::StringSwitch<unsigned>(Tag)
      .Case("typed-text", CK_TypedText)
      .Case("text", CK_Text)
      .Case("optional", CK_Optional)
      .Case("placeholder", CK_Placeholder)
      .Case("informative", CK_Informative)
      .Case("current-parameter", CK_CurrentParameter)
      .Case("lparen", CK_LeftParen)
      .Case("rparen", CK_RightParen)
      .Case("lbracket", CK_LeftBracket)
      .Case("rbracket", CK_RightBracket)
      .Case("lbrace", CK_LeftBrace)
      .Case("rbrace", CK_RightBrace)
      .Case("langle", CK_LeftAngle)
      .Case("rangle", CK_RightAngle)
      .Case("comma", CK_Comma)
      .Default(UnknownKind);
    
    // If we've hit a terminator tag, we're done.
    if (Terminator)
      break;
    
    // Consume the tag.
    Str = Str.substr(AfterTag);

    // Handle standalone tags now, since they don't need to be matched to
    // anything.
    if (Standalone) {
      // Ignore anything we don't know about.
      if (Kind == UnknownKind)
        continue;
      
      switch ((ChunkKind)Kind) {
      case CK_TypedText:
      case CK_Text:
      case CK_Optional:
      case CK_Placeholder:
      case CK_Informative:
      case CK_CurrentParameter:
        // There is no point in creating empty chunks of these kinds.
        break;
        
      case CK_LeftParen:
      case CK_RightParen:
      case CK_LeftBracket:
      case CK_RightBracket:
      case CK_LeftBrace:
      case CK_RightBrace:
      case CK_LeftAngle:
      case CK_RightAngle:
      case CK_Comma:
        Result->AddChunk(Chunk((ChunkKind)Kind));
        break;
      }
      
      continue;
    }
    
    if (Kind == CK_Optional) {
      // Deserialize the optional code-completion string.
      std::auto_ptr<CodeCompletionString> Optional(Deserialize(Str));
      Result->AddOptionalChunk(Optional);
    }
    
    StringRef EndTag = ParseNextTag(Str, StartTag, AfterTag, Standalone, 
                                    Terminator);
    if (StartTag == StringRef::npos || !Terminator || Standalone)
      break; // Parsing failed; just give up.
    
    if (EndTag.empty() || Tag == EndTag) {
      // Found the matching end tag. Add this chunk based on the text
      // between the tags, then consume that input.
      StringRef Text = Str.substr(0, StartTag);
      switch ((ChunkKind)Kind) {
      case CK_TypedText:
      case CK_Text:
      case CK_Placeholder:
      case CK_Informative:
      case CK_CurrentParameter:
      case CK_LeftParen:
      case CK_RightParen:
      case CK_LeftBracket:
      case CK_RightBracket:
      case CK_LeftBrace:
      case CK_RightBrace:
      case CK_LeftAngle:
      case CK_RightAngle:
      case CK_Comma:
        Result->AddChunk(Chunk((ChunkKind)Kind, UnescapeString(Text)));
        break;
          
      case CK_Optional:
        // We've already added the optional chunk.
        break;
      }
    }
    
    // Remove this tag.
    Str = Str.substr(AfterTag);
  } while (!Str.empty());
  
  return Result;
}

//===----------------------------------------------------------------------===//
// Code completion overload candidate implementation
//===----------------------------------------------------------------------===//
FunctionDecl *
CodeCompleteConsumer::OverloadCandidate::getFunction() const {
  if (getKind() == CK_Function)
    return Function;
  else if (getKind() == CK_FunctionTemplate)
    return FunctionTemplate->getTemplatedDecl();
  else
    return 0;
}

const FunctionType *
CodeCompleteConsumer::OverloadCandidate::getFunctionType() const {
  switch (Kind) {
  case CK_Function:
    return Function->getType()->getAs<FunctionType>();
      
  case CK_FunctionTemplate:
    return FunctionTemplate->getTemplatedDecl()->getType()
             ->getAs<FunctionType>();
      
  case CK_FunctionType:
    return Type;
  }
  
  return 0;
}

//===----------------------------------------------------------------------===//
// Code completion consumer implementation
//===----------------------------------------------------------------------===//

CodeCompleteConsumer::~CodeCompleteConsumer() { }

void 
PrintingCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &SemaRef,
                                                         Result *Results, 
                                                         unsigned NumResults) {
  // Print the results.
  for (unsigned I = 0; I != NumResults; ++I) {
    OS << "COMPLETION: ";
    switch (Results[I].Kind) {
    case Result::RK_Declaration:
      OS << Results[I].Declaration->getNameAsString() << " : " 
         << Results[I].Rank;
      if (Results[I].Hidden)
        OS << " (Hidden)";
      if (CodeCompletionString *CCS 
            = Results[I].CreateCodeCompletionString(SemaRef)) {
        OS << " : " << CCS->getAsString();
        delete CCS;
      }
        
      OS << '\n';
      break;
      
    case Result::RK_Keyword:
      OS << Results[I].Keyword << " : " << Results[I].Rank << '\n';
      break;
        
    case Result::RK_Macro: {
      OS << Results[I].Macro->getName() << " : " << Results[I].Rank;
      if (CodeCompletionString *CCS 
          = Results[I].CreateCodeCompletionString(SemaRef)) {
        OS << " : " << CCS->getAsString();
        delete CCS;
      }
      OS << '\n';
      break;
    }
    }
  }
  
  // Once we've printed the code-completion results, suppress remaining
  // diagnostics.
  // FIXME: Move this somewhere else!
  SemaRef.PP.getDiagnostics().setSuppressAllDiagnostics();
}

void 
PrintingCodeCompleteConsumer::ProcessOverloadCandidates(Sema &SemaRef,
                                                        unsigned CurrentArg,
                                              OverloadCandidate *Candidates,
                                                     unsigned NumCandidates) {
  for (unsigned I = 0; I != NumCandidates; ++I) {
    if (CodeCompletionString *CCS
          = Candidates[I].CreateSignatureString(CurrentArg, SemaRef)) {
      OS << "OVERLOAD: " << CCS->getAsString() << "\n";
      delete CCS;
    }
  }

  // Once we've printed the code-completion results, suppress remaining
  // diagnostics.
  // FIXME: Move this somewhere else!
  SemaRef.PP.getDiagnostics().setSuppressAllDiagnostics();
}

void 
CIndexCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &SemaRef,
                                                       Result *Results, 
                                                       unsigned NumResults) {
  // Print the results.
  for (unsigned I = 0; I != NumResults; ++I) {
    OS << "COMPLETION:" << Results[I].Rank << ":";
    switch (Results[I].Kind) {
      case Result::RK_Declaration:
        if (RecordDecl *Record = dyn_cast<RecordDecl>(Results[I].Declaration)) {
          if (Record->isStruct())
            OS << "Struct:";
          else if (Record->isUnion())
            OS << "Union:";
          else
            OS << "Class:";
        } else if (ObjCMethodDecl *Method
                     = dyn_cast<ObjCMethodDecl>(Results[I].Declaration)) {
          if (Method->isInstanceMethod())
            OS << "ObjCInstanceMethod:";
          else
            OS << "ObjCClassMethod:";
        } else {
          OS << Results[I].Declaration->getDeclKindName() << ":";
        }
        if (CodeCompletionString *CCS 
              = Results[I].CreateCodeCompletionString(SemaRef)) {
          CCS->Serialize(OS);
          delete CCS;
        } else {
          OS << "<typed-text>" 
             << Results[I].Declaration->getNameAsString() 
             << "</>";
        }
        
        OS << '\n';
        break;
        
      case Result::RK_Keyword:
        OS << "Keyword:<typed-text>" << Results[I].Keyword << "</>\n";
        break;
        
      case Result::RK_Macro: {
        OS << "Macro:";
        if (CodeCompletionString *CCS 
              = Results[I].CreateCodeCompletionString(SemaRef)) {
          CCS->Serialize(OS);
          delete CCS;
        } else {
          OS << "<typed-text>" << Results[I].Macro->getName() << "</>";
        }
        OS << '\n';
        break;
      }
    }
  }
  
  // Once we've printed the code-completion results, suppress remaining
  // diagnostics.
  // FIXME: Move this somewhere else!
  SemaRef.PP.getDiagnostics().setSuppressAllDiagnostics();
}

void 
CIndexCodeCompleteConsumer::ProcessOverloadCandidates(Sema &SemaRef,
                                                      unsigned CurrentArg,
                                                OverloadCandidate *Candidates,
                                                       unsigned NumCandidates) {
  for (unsigned I = 0; I != NumCandidates; ++I) {
    if (CodeCompletionString *CCS
        = Candidates[I].CreateSignatureString(CurrentArg, SemaRef)) {
      OS << "OVERLOAD:";
      CCS->Serialize(OS);
      OS << '\n';
      delete CCS;
    }
  }
  
  // Once we've printed the code-completion results, suppress remaining
  // diagnostics.
  // FIXME: Move this somewhere else!
  SemaRef.PP.getDiagnostics().setSuppressAllDiagnostics();
}
OpenPOWER on IntegriCloud