summarylogtreecommitdiffstats
path: root/postfix-completion-trunk.patch
blob: f4095c1eb0f0499dbff7bd6ed912fd2be098e75b (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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
diff --git a/clang-tools-extra/clangd/CodeComplete.cpp b/clang-tools-extra/clangd/CodeComplete.cpp
index 9e321dce4c50..0e143e55087d 100644
--- a/clang-tools-extra/clangd/CodeComplete.cpp
+++ b/clang-tools-extra/clangd/CodeComplete.cpp
@@ -349,7 +349,12 @@ struct CodeCompletionBuilder {
     if (C.SemaResult) {
       assert(ASTCtx);
       Completion.Origin |= SymbolOrigin::AST;
-      Completion.Name = std::string(llvm::StringRef(SemaCCS->getTypedText()));
+      if (C.SemaResult->Name) {
+        Completion.Name = C.SemaResult->Name;
+        Completion.AbstractName = true;
+      } else {
+        Completion.Name = std::string(llvm::StringRef(SemaCCS->getTypedText()));
+      }
       Completion.FilterText = SemaCCS->getAllTypedText();
       if (Completion.Scope.empty()) {
         if ((C.SemaResult->Kind == CodeCompletionResult::RK_Declaration) ||
@@ -463,6 +468,8 @@ struct CodeCompletionBuilder {
                    C.SemaResult->CursorKind,
                    /*IncludeFunctionArguments=*/C.SemaResult->FunctionCanBeCall,
                    /*RequiredQualifiers=*/&Completion.RequiredQualifier);
+      if (C.SemaResult->Name) // Description is self-contained.
+        S.Signature.clear();
       S.ReturnType = getReturnType(*SemaCCS);
       if (C.SemaResult->Kind == CodeCompletionResult::RK_Declaration)
         if (const auto *D = C.SemaResult->getDeclaration())
@@ -787,8 +794,8 @@ SpecifiedScope getQueryScopes(CodeCompletionContext &CCContext,
   llvm::StringRef SpelledSpecifier = Lexer::getSourceText(
       CharSourceRange::getCharRange(SemaSpecifier->getRange()),
       CCSema.SourceMgr, clang::LangOptions());
-  if (SpelledSpecifier.consume_front("::")) 
-      Scopes.QueryScopes = {""};
+  if (SpelledSpecifier.consume_front("::"))
+    Scopes.QueryScopes = {""};
   Scopes.UnresolvedQualifier = std::string(SpelledSpecifier);
   // Sema excludes the trailing "::".
   if (!Scopes.UnresolvedQualifier->empty())
@@ -960,6 +967,8 @@ struct CompletionRecorder : public CodeCompleteConsumer {
   // Returns the filtering/sorting name for Result, which must be from Results.
   // Returned string is owned by this recorder (or the AST).
   llvm::StringRef getName(const CodeCompletionResult &Result) {
+    if (Result.Name)
+      return Result.Name;
     switch (Result.Kind) {
     case CodeCompletionResult::RK_Declaration:
       if (auto *ID = Result.Declaration->getIdentifier())
@@ -1581,7 +1590,7 @@ class CodeCompleteFlow {
   CompletionPrefix HeuristicPrefix;
   std::optional<FuzzyMatcher> Filter; // Initialized once Sema runs.
   Range ReplacedRange;
-  std::vector<std::string> QueryScopes; // Initialized once Sema runs.
+  std::vector<std::string> QueryScopes;      // Initialized once Sema runs.
   std::vector<std::string> AccessibleScopes; // Initialized once Sema runs.
   // Initialized once QueryScopes is initialized, if there are scopes.
   std::optional<ScopeDistance> ScopeProximity;
@@ -2310,9 +2319,16 @@ CompletionItem CodeCompletion::render(const CodeCompleteOptions &Opts) const {
   // In VSCode there are rendering issues that prevent these being aligned.
   LSP.label = ((InsertInclude && InsertInclude->Insertion)
                    ? Opts.IncludeIndicator.Insert
-                   : Opts.IncludeIndicator.NoInsert) +
-              (Opts.ShowOrigins ? "[" + llvm::to_string(Origin) + "]" : "") +
-              RequiredQualifier + Name;
+               : AbstractName ? Opts.IncludeIndicator.Rewrite
+                              : Opts.IncludeIndicator.NoInsert);
+  if (Opts.ShowOrigins)
+    LSP.label += "[" + llvm::to_string(Origin) + "]";
+  if (AbstractName) {
+    LSP.label += Name;
+  } else {
+    LSP.label += RequiredQualifier;
+    LSP.label += Name;
+  }
   LSP.labelDetails.emplace();
   LSP.labelDetails->detail = Signature;
 
@@ -2333,7 +2349,9 @@ CompletionItem CodeCompletion::render(const CodeCompleteOptions &Opts) const {
   }
   LSP.sortText = sortText(Score.Total, FilterText);
   LSP.filterText = FilterText;
-  LSP.textEdit = {CompletionTokenRange, RequiredQualifier + Name, ""};
+  LSP.textEdit = {CompletionTokenRange,
+                  AbstractName ? RequiredQualifier : RequiredQualifier + Name,
+                  ""};
   // Merge continuous additionalTextEdits into main edit. The main motivation
   // behind this is to help LSP clients, it seems most of them are confused when
   // they are provided with additionalTextEdits that are consecutive to main
@@ -2342,7 +2360,7 @@ CompletionItem CodeCompletion::render(const CodeCompleteOptions &Opts) const {
   // is mainly to help LSP clients again, so that changes do not effect each
   // other.
   for (const auto &FixIt : FixIts) {
-    if (FixIt.range.end == LSP.textEdit->range.start) {
+    if (0 && FixIt.range.end == LSP.textEdit->range.start) {
       LSP.textEdit->newText = FixIt.newText + LSP.textEdit->newText;
       LSP.textEdit->range.start = FixIt.range.start;
     } else {
diff --git a/clang-tools-extra/clangd/CodeComplete.h b/clang-tools-extra/clangd/CodeComplete.h
index a7c1ae95dcbf..dc946db5c04b 100644
--- a/clang-tools-extra/clangd/CodeComplete.h
+++ b/clang-tools-extra/clangd/CodeComplete.h
@@ -79,6 +79,7 @@ struct CodeCompleteOptions {
   struct IncludeInsertionIndicator {
     std::string Insert = "•";
     std::string NoInsert = " ";
+    std::string Rewrite = "⮞";
   } IncludeIndicator;
 
   /// Expose origins of completion items in the label (for debugging).
@@ -205,6 +206,9 @@ struct CodeCompletion {
   // thse includes may not be accurate for all of them.
   llvm::SmallVector<IncludeCandidate, 1> Includes;
 
+  /// True if the name is a description, rather than text to be inserted.
+  bool AbstractName = false;
+
   /// Holds information about small corrections that needs to be done. Like
   /// converting '->' to '.' on member access.
   std::vector<TextEdit> FixIts;
diff --git a/clang/include/clang/Sema/CodeCompleteConsumer.h b/clang/include/clang/Sema/CodeCompleteConsumer.h
index a2028e40f83d..d8a25811600a 100644
--- a/clang/include/clang/Sema/CodeCompleteConsumer.h
+++ b/clang/include/clang/Sema/CodeCompleteConsumer.h
@@ -791,6 +791,13 @@ public:
     const IdentifierInfo *Macro;
   };
 
+  /// When Kind == RK_Pattern, an optional short name for the pattern.
+  /// Often he pattern combines with a fixit to rewrite surrounding code.
+  ///
+  /// For, example after "foo.", a completion that rewrites to "std::move(foo)"
+  /// could have Name = "move".
+  const char *Name = nullptr;
+
   /// The priority of this particular code-completion result.
   unsigned Priority;
 
diff --git a/clang/lib/Sema/SemaCodeComplete.cpp b/clang/lib/Sema/SemaCodeComplete.cpp
index 83ebcaf9e765..306891b130e2 100644
--- a/clang/lib/Sema/SemaCodeComplete.cpp
+++ b/clang/lib/Sema/SemaCodeComplete.cpp
@@ -184,7 +184,7 @@ private:
 
   /// Overloaded C++ member functions found by SemaLookup.
   /// Used to determine when one overload is dominated by another.
-  llvm::DenseMap<std::pair<DeclContext *, /*Name*/uintptr_t>, ShadowMapEntry>
+  llvm::DenseMap<std::pair<DeclContext *, /*Name*/ uintptr_t>, ShadowMapEntry>
       OverloadMap;
 
   /// If we're potentially referring to a C++ member function, the set
@@ -1430,16 +1430,16 @@ void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
         }
         // Detect cases where a ref-qualified method cannot be invoked.
         switch (Method->getRefQualifier()) {
-          case RQ_LValue:
-            if (ObjectKind != VK_LValue && !MethodQuals.hasConst())
-              return;
-            break;
-          case RQ_RValue:
-            if (ObjectKind == VK_LValue)
-              return;
-            break;
-          case RQ_None:
-            break;
+        case RQ_LValue:
+          if (ObjectKind != VK_LValue && !MethodQuals.hasConst())
+            return;
+          break;
+        case RQ_RValue:
+          if (ObjectKind == VK_LValue)
+            return;
+          break;
+        case RQ_None:
+          break;
         }
 
         /// Check whether this dominates another overloaded method, which should
@@ -1487,9 +1487,7 @@ void ResultBuilder::AddResult(Result R) {
 void ResultBuilder::EnterNewScope() { ShadowMaps.emplace_back(); }
 
 /// Exit from the current scope.
-void ResultBuilder::ExitScope() {
-  ShadowMaps.pop_back();
-}
+void ResultBuilder::ExitScope() { ShadowMaps.pop_back(); }
 
 /// Determines whether this given declaration will be found by
 /// ordinary name lookup.
@@ -2472,7 +2470,8 @@ static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, Scope *S,
       ReturnType = Method->getReturnType();
     else if (SemaRef.getCurBlock() &&
              !SemaRef.getCurBlock()->ReturnType.isNull())
-      ReturnType = SemaRef.getCurBlock()->ReturnType;;
+      ReturnType = SemaRef.getCurBlock()->ReturnType;
+    ;
     if (ReturnType.isNull() || ReturnType->isVoidType()) {
       Builder.AddTypedTextChunk("return");
       Builder.AddChunk(CodeCompletionString::CK_SemiColon);
@@ -2564,15 +2563,19 @@ static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, Scope *S,
       // 'this', if we're in a non-static member function.
       addThisCompletion(SemaRef, Results);
 
-      // true
-      Builder.AddResultTypeChunk("bool");
-      Builder.AddTypedTextChunk("true");
-      Results.AddResult(Result(Builder.TakeString()));
+      if (Results.getCompletionContext().getPreferredType().isNull() ||
+          Results.getCompletionContext()
+                  .getPreferredType()
+                  .getCanonicalType() == SemaRef.getASTContext().BoolTy) {
+        Builder.AddResultTypeChunk("bool");
+        Builder.AddTypedTextChunk("true");
+        Results.AddResult(Result(Builder.TakeString()));
 
-      // false
-      Builder.AddResultTypeChunk("bool");
-      Builder.AddTypedTextChunk("false");
-      Results.AddResult(Result(Builder.TakeString()));
+        // false
+        Builder.AddResultTypeChunk("bool");
+        Builder.AddTypedTextChunk("false");
+        Results.AddResult(Result(Builder.TakeString()));
+      }
 
       if (SemaRef.getLangOpts().RTTI) {
         // dynamic_cast < type-id > ( expression )
@@ -4753,7 +4756,8 @@ static void AddEnumerators(ResultBuilder &Results, ASTContext &Context,
                            EnumDecl *Enum, DeclContext *CurContext,
                            const CoveredEnumerators &Enumerators) {
   NestedNameSpecifier *Qualifier = Enumerators.SuggestedQualifier;
-  if (Context.getLangOpts().CPlusPlus && !Qualifier && Enumerators.Seen.empty()) {
+  if (Context.getLangOpts().CPlusPlus && !Qualifier &&
+      Enumerators.Seen.empty()) {
     // If there are no prior enumerators in C++, check whether we have to
     // qualify the names of the enumerators that we suggest, because they
     // may not be visible in this scope.
@@ -5156,8 +5160,7 @@ AddObjCProperties(const CodeCompletionContext &CCContext,
                         AllowNullaryMethods, CurContext, AddedProperties,
                         Results, IsBaseExprStatement, IsClassProperty,
                         /*InOriginalClass*/ false);
-  } else if (const auto *Category =
-                 dyn_cast<ObjCCategoryDecl>(Container)) {
+  } else if (const auto *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
     // Look through protocols.
     for (auto *P : Category->protocols())
       AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
@@ -5699,6 +5702,557 @@ Expr *unwrapParenList(Expr *Base) {
   return Base;
 }
 
+bool isMovable(Expr *E) {
+  if (E->getValueKind() != VK_LValue)
+    return false;
+  return E->getType().getNonReferenceType()->isStructureOrClassType();
+}
+
+QualType pointeeType(QualType T, Sema &S) {
+  T = T.getCanonicalType();
+  if (const auto *PT = dyn_cast<PointerType>(T))
+    return PT->getPointeeType();
+  if (const auto *RT = dyn_cast<RecordType>(T)) {
+    // If RD is complete, look at its operator*.
+    // Unfortunately with templates it's often incomplete, and instantiating is
+    // messy. See fallback cases below.
+    if (auto *RD = RT->getDecl()->getDefinition()) {
+      if (auto *Star =
+              RD->lookup(S.getASTContext().DeclarationNames.getCXXOperatorName(
+                             clang::OO_Star))
+                  .find_first<FunctionDecl>())
+        return Star->getReturnType().getNonReferenceType();
+    } else if (const auto *CTSD =
+                   dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl())) {
+      // Heuristic: pointee of Iterator<T> is T.
+      // XXX this isn't a good heuristic: in libstdc++ vector<T>::iterator
+      // is __normal_iterator<T*, vector<T>>!
+      const auto &Args = CTSD->getTemplateArgs();
+      if (Args.size() > 0)
+        return Args.get(0).getAsType();
+    } else if (RT->getDecl()->getDeclContext()->getDeclKind() ==
+               Decl::ClassTemplateSpecialization) {
+      // Heuristic: pointee of Container<T>::Iterator is T.
+      const auto &Args = static_cast<ClassTemplateSpecializationDecl *>(
+                             RT->getDecl()->getDeclContext())
+                             ->getTemplateArgs();
+      if (Args.size() > 0)
+        return Args.get(0).getAsType();
+    }
+  }
+  // Not much point probing into dependent TemplateSpecializationType,
+  // it's very to yield a dependent type we can't analyze.
+  return QualType();
+}
+
+bool isByValue(QualType T, ASTContext &Ctx) {
+  T = T.getCanonicalType().getNonReferenceType();
+  if (T->isLiteralType(Ctx)) {
+    if (auto Size = Ctx.getTypeSizeInCharsIfKnown(T))
+      // Arbitrary threshold. Allows string_view by value.
+      return Size->getQuantity() < 16;
+  }
+  return false;
+}
+
+QualType iteratorType(const RecordDecl *RD, const ASTContext &Ctx) {
+  if (RD && (RD = RD->getDefinition())) {
+    auto Begin = RD->lookup(&Ctx.Idents.get("begin"));
+    if (!Begin.empty() && !RD->lookup(&Ctx.Idents.get("end")).empty()) {
+      if (const auto *FD = Begin.front()->getAsFunction()) {
+        if (FD->getMinRequiredArguments() == 0)
+          return FD->getReturnType();
+      }
+    }
+  }
+  return QualType();
+}
+
+// If T is a valid container for a C++ foreach loop, return its iterator type.
+// If it isn't or we can't tell, return null.
+// If there's ambiguity (e.g. overloaded begin()) return one arbitrarily.
+QualType iteratorType(QualType T, ASTContext &Ctx) {
+  T = T.getCanonicalType().getNonReferenceType();
+  if (const auto *ET = T->getArrayElementTypeNoTypeQual())
+    return Ctx.getPointerType(QualType(ET, 0));
+  if (const auto *RT = T->getAs<RecordType>())
+    return iteratorType(RT->getDecl(), Ctx);
+  if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
+    if (auto *CTD = dyn_cast_or_null<ClassTemplateDecl>(
+            TST->getTemplateName().getAsTemplateDecl()))
+      return iteratorType(CTD->getTemplatedDecl(), Ctx);
+  }
+  return QualType();
+}
+
+const char *iterationVariableType(QualType IteratorType, Sema &S) {
+  if (IteratorType.isNull())
+    return nullptr;
+  QualType Element = pointeeType(IteratorType, S);
+  llvm::errs() << "element type is " << Element.getAsString() << "\n";
+  if (!Element.isNull()) {
+    if (Element->isPointerType()) {
+      if (const auto *PT = dyn_cast<PointerType>(Element)) {
+        Element = PT->getPointeeType();
+        if (Element->isPointerType())
+          return "const auto*";
+      }
+    }
+    if (isByValue(Element, S.getASTContext()))
+      return "auto";
+  }
+  return "const auto&";
+}
+
+// Whether E is a simple reference that we shouldn't extract a variable for.
+bool isSyntacticallySimple(const Expr *E) {
+  if (const auto *DRE = llvm::dyn_cast<DeclRefExpr>(E)) {
+    if (!DRE->getQualifier())
+      return true;
+  } else if (const auto *ME = llvm::dyn_cast<MemberExpr>(E)) {
+    if (ME->getBase()->isImplicitCXXThis())
+      return true;
+  }
+  return false;
+}
+
+bool isConvertibleTo(const RecordDecl *RD, CanQualType To) {
+  const auto &Ctx = RD->getParentASTContext();
+  return !RD->lookup(Ctx.DeclarationNames.getCXXConversionFunctionName(To))
+              .empty();
+}
+
+struct Cast {
+  using Set = unsigned;
+  enum : unsigned {
+    Static = 1 << 0,
+    StaticAddRef = 1 << 1,
+    Dynamic = 1 << 2,
+    Reinterpret = 1 << 3,
+    Bit = 1 << 4,
+    Const = 1 << 5,
+    C = 1 << 6,
+  };
+};
+Cast::Set getDowncasts(QualType From, QualType To, ASTContext &Ctx) {
+  assert(From.isCanonical() && To.isCanonical() &&
+         From.getQualifiers() == To.getQualifiers());
+  if (!Ctx.getLangOpts().CPlusPlus)
+    return 0;
+  Cast::Set Result = 0;
+  if (auto *FromRT = dyn_cast<RecordType>(From))
+    if (auto *ToRT = dyn_cast<RecordType>(To)) {
+      if (ToRT->getAsCXXRecordDecl() && FromRT->getAsCXXRecordDecl()) {
+        auto *ToCxx = ToRT->getAsCXXRecordDecl();
+        auto *FromCxx = FromRT->getAsCXXRecordDecl();
+        if ( ToCxx->isCompleteDefinition() && FromCxx->isCompleteDefinition() && ToCxx->isDerivedFrom(FromCxx)) {
+          Result |= Cast::Static;
+          if (FromCxx->isPolymorphic() && Ctx.getLangOpts().RTTI)
+            Result |= Cast::Dynamic;
+        }
+      }
+    }
+  return Result;
+}
+
+Cast::Set recommendCasts(Expr *FromExpr, QualType To, ASTContext &Ctx) {
+  QualType FromNoRef = FromExpr->getType()
+                           .getCanonicalType()
+                           .getNonReferenceType()
+                           .getUnqualifiedType();
+  QualType ToNoRef =
+      To.getCanonicalType().getNonReferenceType().getUnqualifiedType();
+
+  bool IsToAuto = ToNoRef->isPointerType()
+                      ? dyn_cast<AutoType>(ToNoRef->getPointeeType())
+                      : dyn_cast<AutoType>(ToNoRef);
+  if (IsToAuto)
+    return Cast::Static | Cast::Dynamic | Cast::Reinterpret;
+
+  // Producing a non-const reference has only a few possibilities...
+  if (To->isLValueReferenceType() && !To->getPointeeType().isConstQualified()) {
+    // it must always come from an lvalue
+    if (FromExpr->isLValue()) {
+      // if it's from a const lvalue, const_cast is possible
+      if (FromExpr->getType().isConstQualified())
+        return FromNoRef == ToNoRef ? Cast::Const : 0;
+      // otherwise cast between non-const refs can only be inheritance
+      return getDowncasts(FromNoRef, ToNoRef, Ctx);
+    }
+    return 0;
+  }
+  // From here, we assume we're producing values and mostly ignore refs.
+
+  // void* to T*
+  if (FromNoRef->isVoidPointerType() && ToNoRef->isPointerType() &&
+      !ToNoRef->isVoidPointerType())
+    return Cast::Static;
+
+  // Integral casts. Only emit those that can never be implicit.
+  if ((FromNoRef->isScopedEnumeralType() && ToNoRef->isIntegerType()) ||
+      (FromNoRef->isIntegerType() && ToNoRef->isEnumeralType()))
+    return Cast::Static;
+  if (((FromNoRef->isIntegerType() || FromNoRef->isFloatingType()) &&
+       (ToNoRef->isIntegerType() || ToNoRef->isFloatingType())) &&
+      FromNoRef != ToNoRef)
+    return Cast::Static;
+  auto IsIntPointer = [&](QualType T) {
+    return Ctx.getIntPtrType() == T || Ctx.getUIntPtrType() == T;
+  };
+  if ((FromNoRef->isPointerType() && IsIntPointer(ToNoRef)) ||
+      (ToNoRef->isPointerType() && IsIntPointer(FromNoRef)))
+    return Cast::Reinterpret;
+
+  // Downcasts of refs/pointers/values of related class types.
+  if (auto Downcasts = getDowncasts(FromNoRef, ToNoRef, Ctx))
+    return Downcasts;
+  if (FromNoRef->isPointerType() && ToNoRef->isPointerType()) {
+    QualType FromPointee = FromNoRef->getPointeeType();
+    QualType ToPointee = ToNoRef->getPointeeType();
+    if (FromPointee.getQualifiers() == ToPointee.getQualifiers())
+      if (auto Downcasts = getDowncasts(FromPointee, ToPointee, Ctx))
+        return Downcasts;
+  }
+
+  if (FromNoRef->isPointerType() && (ToNoRef->isPointerType() || IsToAuto)) {
+    auto SizeFrom = Ctx.getTypeSizeInCharsIfKnown(FromNoRef->getPointeeType());
+    auto SizeTo = Ctx.getTypeSizeInCharsIfKnown(ToNoRef->getPointeeType());
+    if (SizeFrom && SizeTo && SizeFrom->getQuantity() == SizeTo->getQuantity())
+      return Cast::Reinterpret;
+  }
+  return 0;
+}
+
+bool isConvertibleTo(QualType T, ASTContext &Ctx, CanQualType To) {
+  T = T.getCanonicalType();
+  if (const auto *RT = dyn_cast<RecordType>(T)) {
+    if (const auto *RD = RT->getDecl()->getDefinition())
+      return isConvertibleTo(RD, To);
+    else if (const auto *CTSD =
+                 llvm::dyn_cast<ClassTemplateSpecializationDecl>(RD))
+      return isConvertibleTo(CTSD->getTemplateInstantiationPattern(), To);
+  }
+  if (const auto *TST = dyn_cast<TemplateSpecializationType>(T)) {
+    if (const auto *TD = dyn_cast_or_null<ClassTemplateDecl>(
+            TST->getTemplateName().getAsTemplateDecl()))
+      return isConvertibleTo(TD->getTemplatedDecl(), To);
+  }
+  return false;
+}
+
+bool isConvertibleToBool(QualType T, ASTContext &Ctx) {
+  if (T.getCanonicalType()->isIntegralOrUnscopedEnumerationType())
+    return true;
+  if (T.getCanonicalType()->isAnyPointerType())
+    return true;
+  return isConvertibleTo(T, Ctx, Ctx.BoolTy);
+}
+
+// The type of the condition variable that can be extracted from an expression.
+// e.g. "auto" or "const auto&". For a simple if (expr), returns nullptr
+// If not convertible to boolean, returns nullptr.
+const char *conditionVariableType(Expr *E, ASTContext &Ctx) {
+  if (!Ctx.getLangOpts().CPlusPlus11)
+    return nullptr;
+  QualType T = E->getType().getCanonicalType().getUnqualifiedType();
+  // No variable extracted if there's nothing extra in it.
+  // Don't extract a variable if we can just use the original as easily.
+  if (T->isBooleanType() || isSyntacticallySimple(E))
+    return nullptr;
+
+  if (T->isPointerType())
+    return "const auto*";
+  if (E->isLValue() && !isByValue(T, Ctx))
+    return "const auto&";
+  return "auto";
+}
+
+void addPseudoMemberCompletions(Expr *Base, SourceRange Replace,
+                                ResultBuilder &Results,
+                                bool BaseIsStmt /*false - pass arg*/,
+                                QualType PreferredType) {
+  ASTContext &Ctx = Results.getSema().getASTContext();
+  PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
+  bool Invalid = false;
+  llvm::StringRef ExprRef = Lexer::getSourceText(
+      CharSourceRange::getTokenRange(Base->getSourceRange()),
+      Ctx.getSourceManager(), Ctx.getLangOpts(), &Invalid);
+  if (Invalid)
+    return;
+  const char *ExprCode = Results.getAllocator().CopyString(ExprRef);
+  bool InParens =
+      !ExprRef.empty() && ExprRef.front() == '(' && ExprRef.back() == ')';
+
+  auto TypeString = [&](QualType T) {
+    return Results.getAllocator().CopyString(T.getAsString(Policy));
+  };
+  auto AddResult = [&](const char *Name, QualType Type, auto BuildReplacement) {
+    CodeCompletionBuilder Replacement(Results.getAllocator(),
+                                      Results.getCodeCompletionTUInfo());
+    BuildReplacement(Replacement);
+    if (!Type.isNull())
+      Replacement.AddResultTypeChunk(TypeString(Type));
+    CodeCompletionResult Result(Replacement.TakeString());
+    Result.FixIts = {FixItHint::CreateRemoval(Replace)};
+    Result.Name = Name;
+    Results.AddResult(std::move(Result));
+  };
+  if (Ctx.getLangOpts().CPlusPlus11 && !BaseIsStmt && isMovable(Base)) {
+    AddResult("move",
+              Ctx.getRValueReferenceType(Base->getType().getNonReferenceType()),
+              [&](CodeCompletionBuilder &B) {
+                B.AddTextChunk("std::move");
+                if (!InParens)
+                  B.AddChunk(CodeCompletionString::CK_LeftParen);
+                B.AddTextChunk(ExprCode);
+                if (!InParens)
+                  B.AddChunk(CodeCompletionString::CK_RightParen);
+              });
+    const char *TypeStr = TypeString(Base->getType().getNonReferenceType());
+    AddResult("forward",
+              Ctx.getRValueReferenceType(Base->getType().getNonReferenceType()),
+              [&](CodeCompletionBuilder &B) {
+                B.AddTextChunk("std::forward");
+                B.AddChunk(CodeCompletionString::CK_LeftAngle);
+                B.AddTextChunk(TypeStr);
+                B.AddChunk(CodeCompletionString::CK_RightAngle);
+                if (!InParens)
+                  B.AddChunk(CodeCompletionString::CK_LeftParen);
+                B.AddTextChunk(ExprCode);
+                if (!InParens)
+                  B.AddChunk(CodeCompletionString::CK_RightParen);
+              });
+  } else if (Ctx.getLangOpts().CPlusPlus11 && !BaseIsStmt) {
+    const char *TypeStr = TypeString(Base->getType().getNonReferenceType());
+    AddResult("forward",
+              Ctx.getRValueReferenceType(Base->getType().getNonReferenceType()),
+              [&](CodeCompletionBuilder &B) {
+                B.AddTextChunk("std::forward");
+                B.AddChunk(CodeCompletionString::CK_LeftAngle);
+                B.AddTextChunk(TypeStr);
+                B.AddChunk(CodeCompletionString::CK_RightAngle);
+                if (!InParens)
+                  B.AddChunk(CodeCompletionString::CK_LeftParen);
+                B.AddTextChunk(ExprCode);
+                if (!InParens)
+                  B.AddChunk(CodeCompletionString::CK_RightParen);
+              });
+  }
+  if (Ctx.getLangOpts().CPlusPlus11 && BaseIsStmt) {
+    QualType Iterator = iteratorType(Base->getType(), Ctx);
+    if (const char *ElementType =
+            iterationVariableType(Iterator, Results.getSema())) {
+      const auto *ParentLessExprCode = ExprCode;
+      if (InParens) {
+        auto ParentLessExprRef = ExprRef.substr(1, ExprRef.size() - 2);
+        const auto *FirtChar =
+            std::find_if(ParentLessExprRef.begin(), ParentLessExprRef.end(),
+                         [](char ch) { return !std::isspace(ch); });
+        if (FirtChar != ParentLessExprRef.end() && *FirtChar == '*')
+          ParentLessExprCode =
+              Results.getAllocator().CopyString(ParentLessExprRef);
+      }
+      AddResult("foreach", QualType(), [&](CodeCompletionBuilder &B) {
+        B.AddTextChunk("for");
+        B.AddChunk(CodeCompletionString::CK_HorizontalSpace);
+        B.AddChunk(CodeCompletionString::CK_LeftParen);
+        B.AddTextChunk(ElementType);
+        B.AddChunk(CodeCompletionString::CK_HorizontalSpace);
+        B.AddPlaceholderChunk("element");
+        B.AddChunk(CodeCompletionString::CK_HorizontalSpace);
+        B.AddChunk(CodeCompletionString::CK_Colon);
+        B.AddChunk(CodeCompletionString::CK_HorizontalSpace);
+        B.AddTextChunk(ParentLessExprCode);
+        B.AddChunk(CodeCompletionString::CK_RightParen);
+        B.AddChunk(CodeCompletionString::CK_HorizontalSpace);
+        B.AddChunk(CodeCompletionString::CK_LeftBrace);
+        B.AddChunk(CodeCompletionString::CK_VerticalSpace);
+        B.AddChunk(CodeCompletionString::CK_Placeholder);
+        B.AddChunk(CodeCompletionString::CK_VerticalSpace);
+        B.AddChunk(CodeCompletionString::CK_RightBrace);
+      });
+    }
+  }
+
+  if (!PreferredType.isNull()) {
+    QualType PreferNoRef = PreferredType.getCanonicalType()
+                               .getNonReferenceType()
+                               .getUnqualifiedType();
+    bool IsToAuto = PreferNoRef->isPointerType()
+                        ? dyn_cast<AutoType>(PreferNoRef->getPointeeType())
+                        : dyn_cast<AutoType>(PreferNoRef);
+    if (auto Casts = recommendCasts(Base, PreferredType, Ctx) || IsToAuto) {
+      const char *PreferredTypeStr = TypeString(PreferredType);
+      auto AddCxxCast = [&](const char *Name, const char *Type = nullptr) {
+        AddResult(Name, PreferredType, [&](CodeCompletionBuilder &B) {
+          B.AddTextChunk(Name);
+          B.AddChunk(CodeCompletionString::CK_LeftAngle);
+          if (Type)
+            B.AddTextChunk(Type);
+          else {
+            B.AddPlaceholderChunk("type");
+            if (PreferredType->isPointerType())
+              B.AddTextChunk("*");
+          }
+          B.AddChunk(CodeCompletionString::CK_RightAngle);
+          if (!InParens)
+            B.AddChunk(CodeCompletionString::CK_LeftParen);
+          B.AddTextChunk(ExprCode);
+          if (!InParens)
+            B.AddChunk(CodeCompletionString::CK_RightParen);
+          if (!Type)
+            B.AddChunk(CodeCompletionString::CK_Placeholder);
+        });
+      };
+      auto AddCCast = [&]() {
+        AddResult("cast", PreferredType, [&](CodeCompletionBuilder &B) {
+          B.AddChunk(CodeCompletionString::CK_LeftParen);
+          B.AddTextChunk(PreferredTypeStr);
+          B.AddChunk(CodeCompletionString::CK_RightParen);
+          B.AddTextChunk(ExprCode);
+        });
+      };
+      if (Ctx.getLangOpts().CPlusPlus) {
+        bool IsFromRecord = dyn_cast<RecordType>(Base->getType()
+                                                     .getCanonicalType()
+                                                     .getNonReferenceType()
+                                                     .getUnqualifiedType());
+        if (Casts & Cast::Static)
+          AddCxxCast("static_cast", IsToAuto ? nullptr : PreferredTypeStr);
+        if (Casts & Cast::Dynamic && IsFromRecord)
+          AddCxxCast("dynamic_cast", IsToAuto ? nullptr : PreferredTypeStr);
+        if (Casts & Cast::Reinterpret)
+          AddCxxCast("reinterpret_cast", PreferredTypeStr);
+        else
+          AddCxxCast("reinterpret_cast");
+        if (Casts & Cast::Bit)
+          AddCxxCast("bit_cast", PreferredTypeStr);
+        if (Casts & Cast::Const)
+          AddCxxCast("const_cast", PreferredTypeStr);
+        if (Casts & Cast::C)
+          AddCCast();
+      } else {
+        if (Casts & (Cast::Static | Cast::Reinterpret | Cast::C))
+          AddCCast();
+      }
+    }
+  }
+
+  if (Base->getType()->isEnumeralType() && BaseIsStmt) {
+    EnumDecl *ED =
+        Base->getType()->getAs<EnumType>()->getDecl()->getDefinition();
+    const char *Qualifier = nullptr;
+    DeclContext *QualifierDC = ED->isScoped() ? ED : ED->getDeclContext();
+    auto short_names =
+        ED && ED->isScopedUsingClassTag() && Ctx.getLangOpts().CPlusPlus20;
+    if (const auto *NNS = getRequiredQualification(
+            Ctx, Results.getSema().CurContext, QualifierDC)) {
+      std::string Str;
+      llvm::raw_string_ostream OS(Str);
+      NNS->print(OS, Policy);
+      while (Ctx.getLangOpts().CPlusPlus20 && !Str.empty() && Str.back() == ':')
+        Str.pop_back();
+      Qualifier = Results.getAllocator().CopyString(Str);
+    }
+    if (ED && !ED->enumerators().empty()) {
+      AddResult("switch", QualType(), [&](CodeCompletionBuilder &B) {
+        B.AddTextChunk("switch");
+        B.AddChunk(CodeCompletionString::CK_HorizontalSpace);
+        if (!InParens)
+          B.AddChunk(CodeCompletionString::CK_LeftParen);
+        B.AddTextChunk(ExprCode);
+        if (!InParens)
+          B.AddChunk(CodeCompletionString::CK_RightParen);
+        B.AddChunk(CodeCompletionString::CK_HorizontalSpace);
+        B.AddChunk(CodeCompletionString::CK_LeftBrace);
+        B.AddChunk(CodeCompletionString::CK_VerticalSpace);
+        if (short_names && Qualifier) {
+          B.AddTextChunk("using");
+          B.AddChunk(CodeCompletionString::CK_HorizontalSpace);
+          B.AddTextChunk("enum");
+          B.AddChunk(CodeCompletionString::CK_HorizontalSpace);
+          B.AddTextChunk(Qualifier);
+          B.AddChunk(CodeCompletionString::CK_SemiColon);
+          B.AddChunk(CodeCompletionString::CK_VerticalSpace);
+        }
+        for (const auto *ECD : ED->enumerators()) {
+          B.AddChunk(CodeCompletionString::CK_HorizontalSpace);
+          B.AddTextChunk("case");
+          B.AddChunk(CodeCompletionString::CK_HorizontalSpace);
+          if (!short_names && Qualifier)
+            B.AddTextChunk(Qualifier);
+          B.AddTextChunk(ECD->getIdentifier()->getNameStart());
+          B.AddChunk(CodeCompletionString::CK_Colon);
+          B.AddChunk(CodeCompletionString::CK_HorizontalSpace);
+          B.AddTextChunk("break");
+          B.AddChunk(CodeCompletionString::CK_SemiColon);
+          B.AddChunk(CodeCompletionString::CK_VerticalSpace);
+        }
+        B.AddChunk(CodeCompletionString::CK_RightBrace);
+      });
+    }
+  }
+  if (const auto *Array = dyn_cast<ArrayType>(Base->getType())) {
+    if (Array->getSizeModifier() != ArraySizeModifier::Star) {
+      auto AddBlock = [&](const char *Name) {
+        AddResult(Name, Base->getType()->getPointeeType(),
+                  [&](CodeCompletionBuilder &B) {
+                    B.AddTextChunk("std::");
+                    B.AddTextChunk(Name);
+                    if (!InParens)
+                      B.AddChunk(CodeCompletionString::CK_LeftParen);
+                    B.AddTextChunk(ExprCode);
+                    if (!InParens)
+                      B.AddChunk(CodeCompletionString::CK_RightParen);
+                  });
+      };
+      AddBlock("begin");
+      AddBlock("end");
+    }
+  }
+  if (BaseIsStmt && isConvertibleToBool(Base->getType(), Ctx)) {
+    const char *VarType = conditionVariableType(Base, Ctx);
+    auto AddBlock = [&](const char *Name) {
+      AddResult(Name, QualType(), [&](CodeCompletionBuilder &B) {
+        B.AddTextChunk(Name);
+        B.AddChunk(CodeCompletionString::CK_HorizontalSpace);
+        if (!InParens)
+          B.AddChunk(CodeCompletionString::CK_LeftParen);
+        if (VarType) {
+          B.AddTextChunk(VarType);
+          B.AddChunk(CodeCompletionString::CK_HorizontalSpace);
+          B.AddPlaceholderChunk("value");
+          B.AddChunk(CodeCompletionString::CK_Equal);
+        }
+        B.AddTextChunk(ExprCode);
+        auto BaseType = Base->getType();
+        if (!VarType && !BaseType->isBooleanType() &&
+            (BaseType->isPointerType() || BaseType->isFloatingType() ||
+             BaseType->isScalarType())) {
+          B.AddChunk(CodeCompletionString::CK_HorizontalSpace);
+          B.AddTextChunk("!=");
+          B.AddChunk(CodeCompletionString::CK_HorizontalSpace);
+          if (BaseType->isPointerType())
+            B.AddTextChunk("nullptr");
+          else if (BaseType->isFloatingType())
+            B.AddTextChunk("0.0");
+          else
+            B.AddTextChunk("0");
+        }
+        if (!InParens)
+          B.AddChunk(CodeCompletionString::CK_RightParen);
+        B.AddChunk(CodeCompletionString::CK_HorizontalSpace);
+        B.AddChunk(CodeCompletionString::CK_LeftBrace);
+        B.AddChunk(CodeCompletionString::CK_VerticalSpace);
+        B.AddChunk(CodeCompletionString::CK_RightBrace);
+      });
+    };
+    AddBlock("if");
+    AddBlock("while");
+  }
+  // const cast
+}
+
 } // namespace
 
 void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
@@ -5706,10 +6260,11 @@ void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
                                            SourceLocation OpLoc, bool IsArrow,
                                            bool IsBaseExprStatement,
                                            QualType PreferredType) {
-  Base = unwrapParenList(Base);
-  OtherOpBase = unwrapParenList(OtherOpBase);
   if (!Base || !CodeCompleter)
     return;
+  SourceLocation BeginLoc = Base->getBeginLoc();
+  Base = unwrapParenList(Base);
+  OtherOpBase = unwrapParenList(OtherOpBase);
 
   ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
   if (ConvertedBase.isInvalid())
@@ -5740,6 +6295,10 @@ void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
                         CodeCompleter->getCodeCompletionTUInfo(), CCContext,
                         &ResultBuilder::IsMember);
 
+  if (CodeCompleter->includeFixIts() && CodeCompleter->includeCodePatterns())
+    addPseudoMemberCompletions(Base, SourceRange(BeginLoc, OpLoc), Results,
+                               IsBaseExprStatement, PreferredType);
+
   auto DoCompletion = [&](Expr *Base, bool IsArrow,
                           std::optional<FixItHint> AccessOpFixIt) -> bool {
     if (!Base)
@@ -6019,8 +6578,7 @@ void Sema::CodeCompleteCase(Scope *S) {
 
     Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
     if (auto *DRE = dyn_cast<DeclRefExpr>(CaseVal))
-      if (auto *Enumerator =
-              dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
+      if (auto *Enumerator = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
         // We look into the AST of the case statement to determine which
         // enumerator was named. Alternatively, we could compute the value of
         // the integral constant expression, then compare it against the
@@ -8253,11 +8811,10 @@ void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
       return;
     RecExpr = Conv.get();
   }
-  QualType ReceiverType = RecExpr
-                              ? RecExpr->getType()
-                              : Super ? Context.getObjCObjectPointerType(
-                                            Context.getObjCInterfaceType(Super))
-                                      : Context.getObjCIdType();
+  QualType ReceiverType = RecExpr ? RecExpr->getType()
+                          : Super ? Context.getObjCObjectPointerType(
+                                        Context.getObjCInterfaceType(Super))
+                                  : Context.getObjCIdType();
 
   // If we're messaging an expression with type "id" or "Class", check
   // whether we know something special about the receiver that allows
@@ -10106,8 +10663,7 @@ void Sema::CodeCompleteIncludedFile(llvm::StringRef Dir, bool Angled) {
   };
 
   // Helper: scans IncludeDir for nice files, and adds results for each.
-  auto AddFilesFromIncludeDir = [&](StringRef IncludeDir,
-                                    bool IsSystem,
+  auto AddFilesFromIncludeDir = [&](StringRef IncludeDir, bool IsSystem,
                                     DirectoryLookup::LookupType_t LookupType) {
     llvm::SmallString<128> Dir = IncludeDir;
     if (!NativeRelDir.empty()) {