File: IndexStore.cpp

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (858 lines) | stat: -rw-r--r-- 30,766 bytes parent folder | download
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
//===- IndexStore.cpp - Index store API -----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements the API for the index store.
//
//===----------------------------------------------------------------------===//

#include "indexstore/indexstore.h"
#include "clang/Basic/PathRemapper.h"
#include "clang/Index/IndexDataStore.h"
#include "clang/Index/IndexDataStoreSymbolUtils.h"
#include "clang/Index/IndexRecordReader.h"
#include "clang/Index/IndexUnitReader.h"
#include "clang/Index/IndexUnitWriter.h"
#include "clang/DirectoryWatcher/DirectoryWatcher.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/Chrono.h"
#include "llvm/Support/ManagedStatic.h"

#if INDEXSTORE_HAS_BLOCKS
#include <Block.h>
#endif

using namespace clang;
using namespace clang::index;
using namespace llvm;

static indexstore_string_ref_t toIndexStoreString(StringRef str) {
  return indexstore_string_ref_t{ str.data(), str.size() };
}

static timespec toTimeSpec(sys::TimePoint<> tp) {
  std::chrono::seconds sec = std::chrono::time_point_cast<std::chrono::seconds>(
                 tp).time_since_epoch();
  std::chrono::nanoseconds nsec =
    std::chrono::time_point_cast<std::chrono::nanoseconds>(tp - sec)
      .time_since_epoch();
  timespec ts;
  ts.tv_sec = sec.count();
  ts.tv_nsec = nsec.count();
  return ts;
}

//===----------------------------------------------------------------------===//
// Fatal error handling
//===----------------------------------------------------------------------===//

static void fatal_error_handler(void *user_data, const char *reason,
                                bool gen_crash_diag) {
  // Write the result out to stderr avoiding errs() because raw_ostreams can
  // call report_fatal_error.
  fprintf(stderr, "INDEXSTORE FATAL ERROR: %s\n", reason);
  ::abort();
}

namespace {
struct RegisterFatalErrorHandler {
  RegisterFatalErrorHandler() {
    llvm::install_fatal_error_handler(fatal_error_handler, nullptr);
  }
};
}

static llvm::ManagedStatic<RegisterFatalErrorHandler> RegisterFatalErrorHandlerOnce;

//===----------------------------------------------------------------------===//
// C API
//===----------------------------------------------------------------------===//

namespace {

struct IndexStoreError {
  std::string Error;
};

struct IndexStoreCreationOptions {
  PathRemapper Remapper;
};

} // anonymous namespace

const char *
indexstore_error_get_description(indexstore_error_t err) {
  return static_cast<IndexStoreError*>(err)->Error.c_str();
}

void
indexstore_error_dispose(indexstore_error_t err) {
  delete static_cast<IndexStoreError*>(err);
}

unsigned
indexstore_format_version(void) {
  return IndexDataStore::getFormatVersion();
}

unsigned indexstore_version(void) {
  return INDEXSTORE_VERSION;
}

indexstore_creation_options_t
indexstore_creation_options_create(void) {
  return new IndexStoreCreationOptions();
}

void
indexstore_creation_options_dispose(indexstore_creation_options_t options) {
  delete static_cast<IndexStoreCreationOptions*>(options);
}

void indexstore_creation_options_add_prefix_mapping(
    indexstore_creation_options_t c_options, const char *path_prefix, const char *remapped_path_prefix) {
  IndexStoreCreationOptions *options = static_cast<IndexStoreCreationOptions*>(c_options);
  options->Remapper.addMapping(path_prefix, remapped_path_prefix);
}

indexstore_t
indexstore_store_create(const char *store_path, indexstore_error_t *c_error) {
  return indexstore_store_create_with_options(store_path, nullptr, c_error);
}

indexstore_t
indexstore_store_create_with_options(const char *store_path, indexstore_creation_options_t c_options,
                                     indexstore_error_t *c_error) {
  // Look through the managed static to trigger construction of the managed
  // static which registers our fatal error handler. This ensures it is only
  // registered once.
  (void)*RegisterFatalErrorHandlerOnce;

  std::unique_ptr<IndexDataStore> store;
  std::string error;
  PathRemapper Remapper;
  if (c_options != nullptr) {
    IndexStoreCreationOptions *options = static_cast<IndexStoreCreationOptions*>(c_options);
    Remapper = options->Remapper;
  }
  store = IndexDataStore::create(store_path, Remapper, error);
  if (!store) {
    if (c_error)
      *c_error = new IndexStoreError{ error };
    return nullptr;
  }
  return store.release();
}

void
indexstore_store_dispose(indexstore_t store) {
  delete static_cast<IndexDataStore*>(store);
}

#if INDEXSTORE_HAS_BLOCKS
bool
indexstore_store_units_apply(indexstore_t c_store, unsigned sorted,
                            INDEXSTORE_NOESCAPE bool(^applier)(indexstore_string_ref_t unit_name)) {
  IndexDataStore *store = static_cast<IndexDataStore*>(c_store);
  return store->foreachUnitName(sorted, [&](StringRef unitName) -> bool {
    return applier(toIndexStoreString(unitName));
  });
}
#endif

bool
indexstore_store_units_apply_f(indexstore_t c_store, unsigned sorted,
                               void *context,
             INDEXSTORE_NOESCAPE bool(*applier)(void *context, indexstore_string_ref_t unit_name)) {
  IndexDataStore *store = static_cast<IndexDataStore*>(c_store);
  return store->foreachUnitName(sorted, [&](StringRef unitName) -> bool {
    return applier(context, toIndexStoreString(unitName));
  });
}

size_t
indexstore_unit_event_notification_get_events_count(indexstore_unit_event_notification_t c_evtnote) {
  auto *evtnote = static_cast<IndexDataStore::UnitEventNotification*>(c_evtnote);
  return evtnote->Events.size();
}

indexstore_unit_event_t
indexstore_unit_event_notification_get_event(indexstore_unit_event_notification_t c_evtnote, size_t index) {
  auto *evtnote = static_cast<IndexDataStore::UnitEventNotification*>(c_evtnote);
  return (indexstore_unit_event_t)&evtnote->Events[index];
}

bool
indexstore_unit_event_notification_is_initial(indexstore_unit_event_notification_t c_evtnote) {
  auto *evtnote = static_cast<IndexDataStore::UnitEventNotification*>(c_evtnote);
  return evtnote->IsInitial;
}

indexstore_unit_event_kind_t
indexstore_unit_event_get_kind(indexstore_unit_event_t c_evt) {
  auto *evt = static_cast<IndexDataStore::UnitEvent*>(c_evt);
  indexstore_unit_event_kind_t k;
  switch (evt->Kind) {
    case IndexDataStore::UnitEventKind::Removed:
      k = INDEXSTORE_UNIT_EVENT_REMOVED; break;
    case IndexDataStore::UnitEventKind::Modified:
      k = INDEXSTORE_UNIT_EVENT_MODIFIED; break;
    case IndexDataStore::UnitEventKind::DirectoryDeleted:
      k = INDEXSTORE_UNIT_EVENT_DIRECTORY_DELETED; break;
    case IndexDataStore::UnitEventKind::Failure:
      k = INDEXSTORE_UNIT_EVENT_FAILURE; break;
  }
  return k;
}

indexstore_string_ref_t
indexstore_unit_event_get_unit_name(indexstore_unit_event_t c_evt) {
  auto *evt = static_cast<IndexDataStore::UnitEvent*>(c_evt);
  return toIndexStoreString(evt->UnitName);
}

#if INDEXSTORE_HAS_BLOCKS
void
indexstore_store_set_unit_event_handler(indexstore_t c_store,
                                    indexstore_unit_event_handler_t blk_handler) {
  IndexDataStore *store = static_cast<IndexDataStore*>(c_store);
  if (!blk_handler) {
    store->setUnitEventHandler(nullptr);
    return;
  }

  class BlockWrapper {
    indexstore_unit_event_handler_t blk_handler;
  public:
    BlockWrapper(indexstore_unit_event_handler_t handler) {
      blk_handler = Block_copy(handler);
    }
    BlockWrapper(const BlockWrapper &other) {
      blk_handler = Block_copy(other.blk_handler);
    }
    ~BlockWrapper() {
      Block_release(blk_handler);
    }

    void operator()(indexstore_unit_event_notification_t evt_note) const {
      blk_handler(evt_note);
    }
  };

  BlockWrapper handler(blk_handler);

  store->setUnitEventHandler([handler](IndexDataStore::UnitEventNotification evtNote) {
    handler(&evtNote);
  });
}
#endif

void
indexstore_store_set_unit_event_handler_f(indexstore_t c_store, void *context,
         void(*fn_handler)(void *context, indexstore_unit_event_notification_t),
                                          void(*finalizer)(void *context)) {
  IndexDataStore *store = static_cast<IndexDataStore*>(c_store);
  if (!fn_handler) {
    store->setUnitEventHandler(nullptr);
    return;
  }

  class BlockWrapper {
    void *context;
    void(*fn_handler)(void *context, indexstore_unit_event_notification_t);
    void(*finalizer)(void *context);

  public:
    BlockWrapper(void *_context,
                 void(*_fn_handler)(void *context, indexstore_unit_event_notification_t),
                 void(*_finalizer)(void *context))
    : context(_context), fn_handler(_fn_handler), finalizer(_finalizer) {}

    ~BlockWrapper() {
      if (finalizer) {
        finalizer(context);
      }
    }

    void operator()(indexstore_unit_event_notification_t evt_note) const {
      fn_handler(context, evt_note);
    }
  };

  auto handler = std::make_shared<BlockWrapper>(context, fn_handler, finalizer);

  store->setUnitEventHandler([handler](IndexDataStore::UnitEventNotification evtNote) {
    (*handler)(&evtNote);
  });
}

bool
indexstore_store_start_unit_event_listening(indexstore_t c_store,
                                            indexstore_unit_event_listen_options_t *client_opts,
                                            size_t listen_options_struct_size,
                                            indexstore_error_t *c_error) {
  IndexDataStore *store = static_cast<IndexDataStore*>(c_store);
  indexstore_unit_event_listen_options_t listen_opts;
  memset(&listen_opts, 0, sizeof(listen_opts));
  unsigned clientOptSize = listen_options_struct_size < sizeof(listen_opts)
                             ? listen_options_struct_size : sizeof(listen_opts);
  memcpy(&listen_opts, client_opts, clientOptSize);

  std::string error;
  bool err = store->startEventListening(listen_opts.wait_initial_sync, error);
  if (err && c_error)
    *c_error = new IndexStoreError{ error };
  return err;
}

void
indexstore_store_stop_unit_event_listening(indexstore_t c_store) {
  IndexDataStore *store = static_cast<IndexDataStore*>(c_store);
  store->stopEventListening();
}

void
indexstore_store_discard_unit(indexstore_t c_store, const char *unit_name) {
  IndexDataStore *store = static_cast<IndexDataStore*>(c_store);
  store->discardUnit(unit_name);
}

void
indexstore_store_discard_record(indexstore_t c_store, const char *record_name) {
  IndexDataStore *store = static_cast<IndexDataStore*>(c_store);
  store->discardRecord(record_name);
}

void
indexstore_store_purge_stale_data(indexstore_t c_store) {
  IndexDataStore *store = static_cast<IndexDataStore*>(c_store);
  store->purgeStaleData();
}

indexstore_symbol_kind_t
indexstore_symbol_get_kind(indexstore_symbol_t sym) {
  return getIndexStoreKind(static_cast<IndexRecordDecl *>(sym)->SymInfo.Kind);
}

indexstore_symbol_subkind_t
indexstore_symbol_get_subkind(indexstore_symbol_t sym) {
  return getIndexStoreSubKind(static_cast<IndexRecordDecl *>(sym)->SymInfo.SubKind);
}

indexstore_symbol_language_t
indexstore_symbol_get_language(indexstore_symbol_t sym) {
  return getIndexStoreLang(static_cast<IndexRecordDecl *>(sym)->SymInfo.Lang);
}

indexstore_symbol_property_t
indexstore_symbol_get_properties(indexstore_symbol_t sym) {
  return getIndexStoreProperties(static_cast<IndexRecordDecl *>(sym)->SymInfo.Properties);
}

indexstore_symbol_role_t
indexstore_symbol_get_roles(indexstore_symbol_t sym) {
  return getIndexStoreRoles(static_cast<IndexRecordDecl *>(sym)->Roles);
}

indexstore_symbol_role_t
indexstore_symbol_get_related_roles(indexstore_symbol_t sym) {
  return getIndexStoreRoles(static_cast<IndexRecordDecl *>(sym)->RelatedRoles);
}

indexstore_string_ref_t
indexstore_symbol_get_name(indexstore_symbol_t sym) {
  auto *D = static_cast<IndexRecordDecl*>(sym);
  return toIndexStoreString(D->Name);
}

indexstore_string_ref_t
indexstore_symbol_get_usr(indexstore_symbol_t sym) {
  auto *D = static_cast<IndexRecordDecl*>(sym);
  return toIndexStoreString(D->USR);
}

indexstore_string_ref_t
indexstore_symbol_get_codegen_name(indexstore_symbol_t sym) {
  auto *D = static_cast<IndexRecordDecl*>(sym);
  return toIndexStoreString(D->CodeGenName);
}

indexstore_symbol_role_t
indexstore_symbol_relation_get_roles(indexstore_symbol_relation_t sym_rel) {
  return getIndexStoreRoles(static_cast<IndexRecordRelation *>(sym_rel)->Roles);
}

indexstore_symbol_t
indexstore_symbol_relation_get_symbol(indexstore_symbol_relation_t sym_rel) {
  return (indexstore_symbol_t)static_cast<IndexRecordRelation*>(sym_rel)->Dcl;
}

indexstore_symbol_t
indexstore_occurrence_get_symbol(indexstore_occurrence_t occur) {
  return (indexstore_symbol_t)static_cast<IndexRecordOccurrence*>(occur)->Dcl;
}

#if INDEXSTORE_HAS_BLOCKS
bool
indexstore_occurrence_relations_apply(indexstore_occurrence_t occur,
                      INDEXSTORE_NOESCAPE bool(^applier)(indexstore_symbol_relation_t symbol_rel)) {
  auto *recOccur = static_cast<IndexRecordOccurrence*>(occur);
  for (auto &rel : recOccur->Relations) {
    if (!applier(&rel))
      return false;
  }
  return true;
}
#endif

bool
indexstore_occurrence_relations_apply_f(indexstore_occurrence_t occur,
                                        void *context,
       INDEXSTORE_NOESCAPE bool(*applier)(void *context, indexstore_symbol_relation_t symbol_rel)) {
  auto *recOccur = static_cast<IndexRecordOccurrence*>(occur);
  for (auto &rel : recOccur->Relations) {
    if (!applier(context, &rel))
      return false;
  }
  return true;
}

indexstore_symbol_role_t
indexstore_occurrence_get_roles(indexstore_occurrence_t occur) {
  return getIndexStoreRoles(static_cast<IndexRecordOccurrence*>(occur)->Roles);
}

void
indexstore_occurrence_get_line_col(indexstore_occurrence_t occur,
                              unsigned *line, unsigned *column) {
  auto *recOccur = static_cast<IndexRecordOccurrence*>(occur);
  if (line)
    *line = recOccur->Line;
  if (column)
    *column = recOccur->Column;
}

typedef void *indexstore_record_reader_t;

indexstore_record_reader_t
indexstore_record_reader_create(indexstore_t c_store, const char *record_name,
                                indexstore_error_t *c_error) {
  IndexDataStore *store = static_cast<IndexDataStore*>(c_store);
  std::unique_ptr<IndexRecordReader> reader;
  std::string error;
  reader = IndexRecordReader::createWithRecordFilename(record_name,
                                                       store->getFilePath(),
                                                       error);
  if (!reader) {
    if (c_error)
      *c_error = new IndexStoreError{ error };
    return nullptr;
  }
  return reader.release();
}

void
indexstore_record_reader_dispose(indexstore_record_reader_t rdr) {
  auto *reader = static_cast<IndexRecordReader *>(rdr);
  delete reader;
}

#if INDEXSTORE_HAS_BLOCKS
/// Goes through the symbol data and passes symbols to \c receiver, for the
/// symbol data that \c filter returns true on.
///
/// This allows allocating memory only for the record symbols that the caller is
/// interested in.
bool
indexstore_record_reader_search_symbols(indexstore_record_reader_t rdr,
    INDEXSTORE_NOESCAPE bool(^filter)(indexstore_symbol_t symbol, bool *stop),
    INDEXSTORE_NOESCAPE void(^receiver)(indexstore_symbol_t symbol)) {
  auto *reader = static_cast<IndexRecordReader *>(rdr);

  auto filterFn = [&](const IndexRecordDecl &D) -> IndexRecordReader::DeclSearchReturn {
    bool stop = false;
    bool accept = filter((indexstore_symbol_t)&D, &stop);
    return { accept, !stop };
  };
  auto receiverFn = [&](const IndexRecordDecl *D) {
    receiver((indexstore_symbol_t)D);
  };

  return reader->searchDecls(filterFn, receiverFn);
}

bool
indexstore_record_reader_symbols_apply(indexstore_record_reader_t rdr,
                                        bool nocache,
                                   INDEXSTORE_NOESCAPE bool(^applier)(indexstore_symbol_t symbol)) {
  auto *reader = static_cast<IndexRecordReader *>(rdr);
  auto receiverFn = [&](const IndexRecordDecl *D) -> bool {
    return applier((indexstore_symbol_t)D);
  };
  return reader->foreachDecl(nocache, receiverFn);
}

bool
indexstore_record_reader_occurrences_apply(indexstore_record_reader_t rdr,
                                INDEXSTORE_NOESCAPE bool(^applier)(indexstore_occurrence_t occur)) {
  auto *reader = static_cast<IndexRecordReader *>(rdr);
  auto receiverFn = [&](const IndexRecordOccurrence &RO) -> bool {
    return applier((indexstore_occurrence_t)&RO);
  };
  return reader->foreachOccurrence(receiverFn);
}

bool
indexstore_record_reader_occurrences_in_line_range_apply(indexstore_record_reader_t rdr,
                                                         unsigned line_start,
                                                         unsigned line_count,
                                INDEXSTORE_NOESCAPE bool(^applier)(indexstore_occurrence_t occur)) {
  auto *reader = static_cast<IndexRecordReader *>(rdr);
  auto receiverFn = [&](const IndexRecordOccurrence &RO) -> bool {
    return applier((indexstore_occurrence_t)&RO);
  };
  return reader->foreachOccurrenceInLineRange(line_start, line_count, receiverFn);
}

/// \param symbols if non-zero \c symbols_count, indicates the list of symbols
/// that we want to get occurrences for. An empty array indicates that we want
/// occurrences for all symbols.
/// \param related_symbols Same as \c symbols but for related symbols.
bool
indexstore_record_reader_occurrences_of_symbols_apply(indexstore_record_reader_t rdr,
        indexstore_symbol_t *symbols, size_t symbols_count,
        indexstore_symbol_t *related_symbols, size_t related_symbols_count,
        INDEXSTORE_NOESCAPE bool(^applier)(indexstore_occurrence_t occur)) {
  auto *reader = static_cast<IndexRecordReader *>(rdr);
  auto receiverFn = [&](const IndexRecordOccurrence &RO) -> bool {
    return applier((indexstore_occurrence_t)&RO);
  };
  return reader->foreachOccurrence({(IndexRecordDecl**)symbols, symbols_count},
                                   {(IndexRecordDecl**)related_symbols, related_symbols_count},
                                   receiverFn);
}
#endif

bool
indexstore_record_reader_search_symbols_f(indexstore_record_reader_t rdr,
                                          void *filter_ctx,
    INDEXSTORE_NOESCAPE bool(*filter)(void *filter_ctx, indexstore_symbol_t symbol, bool *stop),
                                          void *receiver_ctx,
              INDEXSTORE_NOESCAPE void(*receiver)(void *receiver_ctx, indexstore_symbol_t symbol)) {
  auto *reader = static_cast<IndexRecordReader *>(rdr);

  auto filterFn = [&](const IndexRecordDecl &D) -> IndexRecordReader::DeclSearchReturn {
    bool stop = false;
    bool accept = filter(filter_ctx, (indexstore_symbol_t)&D, &stop);
    return { accept, !stop };
  };
  auto receiverFn = [&](const IndexRecordDecl *D) {
    receiver(receiver_ctx, (indexstore_symbol_t)D);
  };

  return reader->searchDecls(filterFn, receiverFn);
}

bool
indexstore_record_reader_symbols_apply_f(indexstore_record_reader_t rdr,
                                         bool nocache,
                                         void *context,
                    INDEXSTORE_NOESCAPE bool(*applier)(void *context, indexstore_symbol_t symbol)) {
  auto *reader = static_cast<IndexRecordReader *>(rdr);
  auto receiverFn = [&](const IndexRecordDecl *D) -> bool {
    return applier(context, (indexstore_symbol_t)D);
  };
  return reader->foreachDecl(nocache, receiverFn);
}

bool
indexstore_record_reader_occurrences_apply_f(indexstore_record_reader_t rdr,
                                             void *context,
                 INDEXSTORE_NOESCAPE bool(*applier)(void *context, indexstore_occurrence_t occur)) {
  auto *reader = static_cast<IndexRecordReader *>(rdr);
  auto receiverFn = [&](const IndexRecordOccurrence &RO) -> bool {
    return applier(context, (indexstore_occurrence_t)&RO);
  };
  return reader->foreachOccurrence(receiverFn);
}

bool
indexstore_record_reader_occurrences_in_line_range_apply_f(indexstore_record_reader_t rdr,
                                                           unsigned line_start,
                                                           unsigned line_count,
                                                           void *context,
                 INDEXSTORE_NOESCAPE bool(*applier)(void *context, indexstore_occurrence_t occur)) {
  auto *reader = static_cast<IndexRecordReader *>(rdr);
  auto receiverFn = [&](const IndexRecordOccurrence &RO) -> bool {
    return applier(context, (indexstore_occurrence_t)&RO);
  };
  return reader->foreachOccurrenceInLineRange(line_start, line_count, receiverFn);
}

bool
indexstore_record_reader_occurrences_of_symbols_apply_f(indexstore_record_reader_t rdr,
        indexstore_symbol_t *symbols, size_t symbols_count,
        indexstore_symbol_t *related_symbols, size_t related_symbols_count,
        void *context,
        INDEXSTORE_NOESCAPE bool(*applier)(void *context, indexstore_occurrence_t occur)) {
  auto *reader = static_cast<IndexRecordReader *>(rdr);
  auto receiverFn = [&](const IndexRecordOccurrence &RO) -> bool {
    return applier(context, (indexstore_occurrence_t)&RO);
  };
  return reader->foreachOccurrence({(IndexRecordDecl**)symbols, symbols_count},
                                   {(IndexRecordDecl**)related_symbols, related_symbols_count},
                                   receiverFn);
}

size_t
indexstore_store_get_unit_name_from_output_path(indexstore_t c_store,
                                                const char *output_path,
                                                char *name_buf,
                                                size_t buf_size) {
  SmallString<256> unitName;
  // We intentionally don't use the index store's path remapper since it
  // maps from canonical -> local instead of local -> canonical. This means that
  // callers must gives us the canonical `output_path`, not the local one.
  PathRemapper remapper;
  IndexUnitWriter::getUnitNameForAbsoluteOutputFile(output_path, unitName,
                                                    remapper);
  size_t nameLen = unitName.size();
  if (buf_size != 0) {
    strncpy(name_buf, unitName.c_str(), buf_size-1);
    name_buf[buf_size-1] = '\0';
  }
  return nameLen;
}

bool
indexstore_store_get_unit_modification_time(indexstore_t c_store,
                                            const char *unit_name,
                                            int64_t *seconds,
                                            int64_t *nanoseconds,
                                            indexstore_error_t *c_error) {
  IndexDataStore *store = static_cast<IndexDataStore*>(c_store);
  std::string error;
  // FIXME: This provides mod time with second-only accuracy.
  auto optModTime = IndexUnitReader::getModificationTimeForUnit(unit_name,
                                              store->getFilePath(), error);
  if (!optModTime) {
    if (c_error)
      *c_error = new IndexStoreError{ error };
    return true;
  }

  timespec ts = toTimeSpec(*optModTime);
  if (seconds)
    *seconds = ts.tv_sec;
  if (nanoseconds)
    *nanoseconds = ts.tv_nsec;

  return false;
}

indexstore_unit_reader_t
indexstore_unit_reader_create(indexstore_t c_store, const char *unit_name,
                              indexstore_error_t *c_error) {
  IndexDataStore *store = static_cast<IndexDataStore*>(c_store);
  std::unique_ptr<IndexUnitReader> reader;
  std::string error;
  reader = IndexUnitReader::createWithUnitFilename(unit_name,
                                                   store->getFilePath(),
                                                   store->getPathRemapper(),
                                                   error);
  if (!reader) {
    if (c_error)
      *c_error = new IndexStoreError{ error };
    return nullptr;
  }
  return reader.release();
}

void
indexstore_unit_reader_dispose(indexstore_unit_reader_t rdr) {
  auto reader = static_cast<IndexUnitReader*>(rdr);
  delete reader;
}

indexstore_string_ref_t
indexstore_unit_reader_get_provider_identifier(indexstore_unit_reader_t rdr) {
  auto reader = static_cast<IndexUnitReader*>(rdr);
  return toIndexStoreString(reader->getProviderIdentifier());
}

indexstore_string_ref_t
indexstore_unit_reader_get_provider_version(indexstore_unit_reader_t rdr) {
  auto reader = static_cast<IndexUnitReader*>(rdr);
  return toIndexStoreString(reader->getProviderVersion());
}

void
indexstore_unit_reader_get_modification_time(indexstore_unit_reader_t rdr,
                                             int64_t *seconds,
                                             int64_t *nanoseconds) {
  auto reader = static_cast<IndexUnitReader*>(rdr);
  // FIXME: This provides mod time with second-only accuracy.
  sys::TimePoint<> timeVal = reader->getModificationTime();
  timespec ts = toTimeSpec(timeVal);
  if (seconds)
    *seconds = ts.tv_sec;
  if (nanoseconds)
    *nanoseconds = ts.tv_nsec;
}

bool
indexstore_unit_reader_is_system_unit(indexstore_unit_reader_t rdr) {
  auto reader = static_cast<IndexUnitReader*>(rdr);
  return reader->isSystemUnit();
}

bool
indexstore_unit_reader_is_module_unit(indexstore_unit_reader_t rdr) {
  auto reader = static_cast<IndexUnitReader*>(rdr);
  return reader->isModuleUnit();
}

bool
indexstore_unit_reader_is_debug_compilation(indexstore_unit_reader_t rdr) {
  auto reader = static_cast<IndexUnitReader*>(rdr);
  return reader->isDebugCompilation();
}

bool
indexstore_unit_reader_has_main_file(indexstore_unit_reader_t rdr) {
  auto reader = static_cast<IndexUnitReader*>(rdr);
  return reader->hasMainFile();
}

indexstore_string_ref_t
indexstore_unit_reader_get_main_file(indexstore_unit_reader_t rdr) {
  auto reader = static_cast<IndexUnitReader*>(rdr);
  return toIndexStoreString(reader->getMainFilePath());
}

indexstore_string_ref_t
indexstore_unit_reader_get_module_name(indexstore_unit_reader_t rdr) {
  auto reader = static_cast<IndexUnitReader*>(rdr);
  return toIndexStoreString(reader->getModuleName());
}

indexstore_string_ref_t
indexstore_unit_reader_get_working_dir(indexstore_unit_reader_t rdr) {
  auto reader = static_cast<IndexUnitReader*>(rdr);
  return toIndexStoreString(reader->getWorkingDirectory());
}

indexstore_string_ref_t
indexstore_unit_reader_get_output_file(indexstore_unit_reader_t rdr) {
  auto reader = static_cast<IndexUnitReader*>(rdr);
  return toIndexStoreString(reader->getOutputFile());
}

indexstore_string_ref_t
indexstore_unit_reader_get_sysroot_path(indexstore_unit_reader_t rdr) {
  auto reader = static_cast<IndexUnitReader*>(rdr);
  return toIndexStoreString(reader->getSysrootPath());
}

indexstore_string_ref_t
indexstore_unit_reader_get_target(indexstore_unit_reader_t rdr) {
  auto reader = static_cast<IndexUnitReader*>(rdr);
  return toIndexStoreString(reader->getTarget());
}

indexstore_unit_dependency_kind_t
indexstore_unit_dependency_get_kind(indexstore_unit_dependency_t c_dep) {
  auto dep = static_cast<const IndexUnitReader::DependencyInfo*>(c_dep);
  switch (dep->Kind) {
  case IndexUnitReader::DependencyKind::Unit: return INDEXSTORE_UNIT_DEPENDENCY_UNIT;
  case IndexUnitReader::DependencyKind::Record: return INDEXSTORE_UNIT_DEPENDENCY_RECORD;
  case IndexUnitReader::DependencyKind::File: return INDEXSTORE_UNIT_DEPENDENCY_FILE;
  }
}

bool
indexstore_unit_dependency_is_system(indexstore_unit_dependency_t c_dep) {
  auto dep = static_cast<const IndexUnitReader::DependencyInfo*>(c_dep);
  return dep->IsSystem;
}

indexstore_string_ref_t
indexstore_unit_dependency_get_filepath(indexstore_unit_dependency_t c_dep) {
  auto dep = static_cast<const IndexUnitReader::DependencyInfo*>(c_dep);
  return toIndexStoreString(dep->FilePath);
}

indexstore_string_ref_t
indexstore_unit_dependency_get_modulename(indexstore_unit_dependency_t c_dep) {
  auto dep = static_cast<const IndexUnitReader::DependencyInfo*>(c_dep);
  return toIndexStoreString(dep->ModuleName);
}

indexstore_string_ref_t
indexstore_unit_dependency_get_name(indexstore_unit_dependency_t c_dep) {
  auto dep = static_cast<const IndexUnitReader::DependencyInfo*>(c_dep);
  return toIndexStoreString(dep->UnitOrRecordName);
}

indexstore_string_ref_t
indexstore_unit_include_get_source_path(indexstore_unit_include_t c_inc) {
  auto inc = static_cast<const IndexUnitReader::IncludeInfo*>(c_inc);
  return toIndexStoreString(inc->SourcePath);
}

indexstore_string_ref_t
indexstore_unit_include_get_target_path(indexstore_unit_include_t c_inc) {
  auto inc = static_cast<const IndexUnitReader::IncludeInfo*>(c_inc);
  return toIndexStoreString(inc->TargetPath);
}

unsigned
indexstore_unit_include_get_source_line(indexstore_unit_include_t c_inc) {
  auto inc = static_cast<const IndexUnitReader::IncludeInfo*>(c_inc);
  return inc->SourceLine;
}

#if INDEXSTORE_HAS_BLOCKS
bool
indexstore_unit_reader_dependencies_apply(indexstore_unit_reader_t rdr,
                             INDEXSTORE_NOESCAPE bool(^applier)(indexstore_unit_dependency_t)) {
  auto reader = static_cast<IndexUnitReader*>(rdr);
  return reader->foreachDependency([&](const IndexUnitReader::DependencyInfo &depInfo) -> bool {
    return applier((void*)&depInfo);
  });
}

bool
indexstore_unit_reader_includes_apply(indexstore_unit_reader_t rdr,
                             INDEXSTORE_NOESCAPE bool(^applier)(indexstore_unit_include_t)) {
  auto reader = static_cast<IndexUnitReader*>(rdr);
  return reader->foreachInclude([&](const IndexUnitReader::IncludeInfo &incInfo) -> bool {
    return applier((void*)&incInfo);
  });
}
#endif

bool
indexstore_unit_reader_dependencies_apply_f(indexstore_unit_reader_t rdr,
                                            void *context,
                  INDEXSTORE_NOESCAPE bool(*applier)(void *context, indexstore_unit_dependency_t)) {
  auto reader = static_cast<IndexUnitReader*>(rdr);
  return reader->foreachDependency([&](const IndexUnitReader::DependencyInfo &depInfo) -> bool {
    return applier(context, (void*)&depInfo);
  });
}

bool
indexstore_unit_reader_includes_apply_f(indexstore_unit_reader_t rdr,
                                        void *context,
                     INDEXSTORE_NOESCAPE bool(*applier)(void *context, indexstore_unit_include_t)) {
  auto reader = static_cast<IndexUnitReader*>(rdr);
  return reader->foreachInclude([&](const IndexUnitReader::IncludeInfo &incInfo) -> bool {
    return applier(context, (void*)&incInfo);
  });
}