ide-clang-translation-unit.c 36.9 KB
Newer Older
1 2
/* ide-clang-translation-unit.c
 *
3
 * Copyright © 2015 Christian Hergert <christian@hergert.me>
4
 *
5 6 7 8
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
9
 *
10 11 12 13
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
14 15 16 17 18
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

Christian Hergert's avatar
Christian Hergert committed
19
#define G_LOG_DOMAIN "clang-translation-unit"
20

21
#include <clang-c/Index.h>
22
#include <dazzle.h>
23
#include <glib/gi18n.h>
Christian Hergert's avatar
Christian Hergert committed
24
#include <ide.h>
25

26
#include "ide-clang-completion-item.h"
27
#include "ide-clang-completion-item-private.h"
28
#include "ide-clang-private.h"
29
#include "ide-clang-symbol-tree.h"
30 31
#include "ide-clang-translation-unit.h"

32
struct _IdeClangTranslationUnit
33
{
34 35
  IdeObject          parent_instance;

36
  IdeRefPtr         *native;
37
  gint64             serial;
38
  GFile             *file;
39
  IdeHighlightIndex *index;
40
  GHashTable        *diagnostics;
41
};
42

43 44 45 46 47 48 49 50
typedef struct
{
  GPtrArray *unsaved_files;
  gchar     *path;
  guint      line;
  guint      line_offset;
} CodeCompleteState;

51 52 53 54 55 56 57
typedef struct
{
  GPtrArray *ar;
  IdeFile   *file;
  gchar     *path;
} GetSymbolsState;

58
G_DEFINE_TYPE (IdeClangTranslationUnit, ide_clang_translation_unit, IDE_TYPE_OBJECT)
59
DZL_DEFINE_COUNTER (instances, "Clang", "Translation Units", "Number of clang translation units")
60 61 62

enum {
  PROP_0,
63
  PROP_FILE,
64
  PROP_INDEX,
65 66
  PROP_NATIVE,
  PROP_SERIAL,
67 68 69
  LAST_PROP
};

70
static GParamSpec *properties [LAST_PROP];
71

72 73 74 75 76 77 78 79 80 81 82 83 84
static void
code_complete_state_free (gpointer data)
{
  CodeCompleteState *state = data;

  if (state)
    {
      g_clear_pointer (&state->unsaved_files, g_ptr_array_unref);
      g_free (state->path);
      g_free (state);
    }
}

85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
static CXFile
get_file_for_location (IdeClangTranslationUnit *self,
                       IdeSourceLocation       *location)
{
  g_autofree gchar *filename = NULL;
  IdeFile *file;
  GFile *gfile;

  g_assert (IDE_IS_CLANG_TRANSLATION_UNIT (self));
  g_assert (location != NULL);

  if (!(file = ide_source_location_get_file (location)) ||
      !(gfile = ide_file_get_file (file)) ||
      !(filename = g_file_get_path (gfile)))
    return NULL;

  return clang_getFile (ide_ref_ptr_get (self->native), filename);
}

104 105
/**
 * ide_clang_translation_unit_get_index:
106
 * @self: an #IdeClangTranslationUnit.
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
 *
 * Gets the highlight index for the translation unit.
 *
 * Returns: (transfer none) (nullable): An #IdeHighlightIndex or %NULL.
 */
IdeHighlightIndex *
ide_clang_translation_unit_get_index (IdeClangTranslationUnit *self)
{
  g_return_val_if_fail (IDE_IS_CLANG_TRANSLATION_UNIT (self), NULL);

  return self->index;
}

static void
ide_clang_translation_unit_set_index (IdeClangTranslationUnit *self,
                                      IdeHighlightIndex       *index)
{
  g_assert (IDE_IS_CLANG_TRANSLATION_UNIT (self));

  if (index != NULL)
    self->index = ide_highlight_index_ref (index);
}

130 131 132 133 134
GFile *
ide_clang_translation_unit_get_file (IdeClangTranslationUnit *self)
{
  g_return_val_if_fail (IDE_IS_CLANG_TRANSLATION_UNIT (self), NULL);

135
  return self->file;
136 137 138 139 140 141 142 143 144
}

static void
ide_clang_translation_unit_set_file (IdeClangTranslationUnit *self,
                                     GFile                   *file)
{
  g_return_if_fail (IDE_IS_CLANG_TRANSLATION_UNIT (self));
  g_return_if_fail (G_IS_FILE (file));

145
  if (g_set_object (&self->file, file))
146
    g_object_notify_by_pspec (G_OBJECT (self), properties [PROP_FILE]);
147 148
}

149 150 151
IdeClangTranslationUnit *
_ide_clang_translation_unit_new (IdeContext        *context,
                                 CXTranslationUnit  tu,
152
                                 GFile             *file,
153
                                 IdeHighlightIndex *index,
154
                                 gint64             serial)
155 156 157 158 159
{
  IdeClangTranslationUnit *ret;

  g_return_val_if_fail (IDE_IS_CONTEXT (context), NULL);
  g_return_val_if_fail (tu, NULL);
160
  g_return_val_if_fail (!file || G_IS_FILE (file), NULL);
161 162 163

  ret = g_object_new (IDE_TYPE_CLANG_TRANSLATION_UNIT,
                      "context", context,
164 165
                      "file", file,
                      "index", index,
166 167
                      "native", tu,
                      "serial", serial,
168 169 170 171 172
                      NULL);

  return ret;
}

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
static IdeDiagnosticSeverity
translate_severity (enum CXDiagnosticSeverity severity)
{
  switch (severity)
    {
    case CXDiagnostic_Ignored:
      return IDE_DIAGNOSTIC_IGNORED;

    case CXDiagnostic_Note:
      return IDE_DIAGNOSTIC_NOTE;

    case CXDiagnostic_Warning:
      return IDE_DIAGNOSTIC_WARNING;

    case CXDiagnostic_Error:
      return IDE_DIAGNOSTIC_ERROR;

    case CXDiagnostic_Fatal:
      return IDE_DIAGNOSTIC_FATAL;

    default:
      return 0;
    }
}

198 199 200 201
static gchar *
get_path (const gchar *workpath,
          const gchar *path)
{
202 203
  if (path == NULL)
    return g_strdup (workpath);
204
  else if (g_path_is_absolute (path) || g_str_has_prefix (path, workpath))
205 206 207
    return g_strdup (path);
  else
    return g_build_filename (workpath, path, NULL);
208 209
}

210 211
static IdeSourceLocation *
create_location (IdeClangTranslationUnit *self,
212
                 const gchar             *workpath,
213
                 CXSourceLocation         cxloc,
214
                 IdeSourceLocation       *alternate)
215
{
216
  g_autofree gchar *path = NULL;
217 218 219 220 221
  g_autoptr(IdeFile) file = NULL;
  g_autoptr(GFile) gfile = NULL;
  g_auto(CXString) str = {0};
  IdeContext *context;
  CXFile cxfile = NULL;
222 223 224 225
  unsigned line;
  unsigned column;
  unsigned offset;

226
  g_assert (IDE_IS_CLANG_TRANSLATION_UNIT (self));
227
  g_assert (workpath != NULL);
228 229 230

  clang_getFileLocation (cxloc, &cxfile, &line, &column, &offset);

231
  str = clang_getFileName (cxfile);
232

233 234
  if (line == 0 || clang_getCString (str) == NULL)
    return alternate ? ide_source_location_ref (alternate) : NULL;
235

236 237
  if (line > 0)
    line--;
238

239 240 241 242 243 244 245
  if (column > 0)
    column--;

  path = get_path (workpath, clang_getCString (str));
  context = ide_object_get_context (IDE_OBJECT (self));
  gfile = g_file_new_for_path (path);
  file = ide_file_new (context, gfile);
246

247
  return ide_source_location_new (file, line, column, offset);
248 249 250 251
}

static IdeSourceRange *
create_range (IdeClangTranslationUnit *self,
252
              const gchar             *workpath,
253 254
              CXSourceRange            cxrange)
{
255
  IdeSourceRange *range = NULL;
256 257 258 259 260 261 262 263 264 265
  CXSourceLocation cxbegin;
  CXSourceLocation cxend;
  g_autoptr(IdeSourceLocation) begin = NULL;
  g_autoptr(IdeSourceLocation) end = NULL;

  g_return_val_if_fail (IDE_IS_CLANG_TRANSLATION_UNIT (self), NULL);

  cxbegin = clang_getRangeStart (cxrange);
  cxend = clang_getRangeEnd (cxrange);

266 267 268 269
  /* Sometimes the end location does not have a file associated with it,
   * so we force it to have the IdeFile of the first location.
   */
  begin = create_location (self, workpath, cxbegin, NULL);
270
  end = create_location (self, workpath, cxend, begin);
271

272
  if ((begin != NULL) && (end != NULL))
273
    range = ide_source_range_new (begin, end);
274 275 276 277

  return range;
}

278 279 280 281
static gboolean
cxfile_equal (CXFile  cxfile,
              GFile  *file)
{
282 283 284
  g_auto(CXString) cxstr = {0};
  g_autofree gchar *path = NULL;
  const gchar *cstr;
285 286

  cxstr = clang_getFileName (cxfile);
287
  cstr = clang_getCString (cxstr);
288 289
  path = g_file_get_path (file);

290
  return dzl_str_equal0 (cstr, path);
291 292
}

293 294
static IdeDiagnostic *
create_diagnostic (IdeClangTranslationUnit *self,
295
                   const gchar             *workpath,
296
                   GFile                   *target,
297 298
                   CXDiagnostic            *cxdiag)
{
299
  g_autoptr(IdeSourceLocation) loc = NULL;
300 301
  enum CXDiagnosticSeverity cxseverity;
  IdeDiagnosticSeverity severity;
302
  IdeDiagnostic *diag;
303 304
  const gchar *spelling;
  g_auto(CXString) cxstr = {0};
305
  CXSourceLocation cxloc;
306
  CXFile cxfile = NULL;
307 308
  guint num_ranges;
  guint i;
309 310 311 312

  g_return_val_if_fail (IDE_IS_CLANG_TRANSLATION_UNIT (self), NULL);
  g_return_val_if_fail (cxdiag, NULL);

313 314 315
  cxloc = clang_getDiagnosticLocation (cxdiag);
  clang_getExpansionLocation (cxloc, &cxfile, NULL, NULL, NULL);

316
  if (cxfile && !cxfile_equal (cxfile, target))
317 318
    return NULL;

319 320 321
  cxseverity = clang_getDiagnosticSeverity (cxdiag);
  severity = translate_severity (cxseverity);

322
  cxstr = clang_getDiagnosticSpelling (cxdiag);
323
  spelling = clang_getCString (cxstr);
324

325 326 327 328 329 330 331 332 333 334 335 336
  /*
   * I thought we could use an approach like the following to get deprecation
   * status. However, it has so far proven ineffective.
   *
   *   cursor = clang_getCursor (self->tu, cxloc);
   *   avail = clang_getCursorAvailability (cursor);
   */
  if ((severity == IDE_DIAGNOSTIC_WARNING) &&
      (spelling != NULL) &&
      (strstr (spelling, "deprecated") != NULL))
    severity = IDE_DIAGNOSTIC_DEPRECATED;

337
  loc = create_location (self, workpath, cxloc, NULL);
338

339
  diag = ide_diagnostic_new (severity, spelling, loc);
340

341 342
  num_ranges = clang_getDiagnosticNumRanges (cxdiag);

343 344 345 346 347 348
  for (i = 0; i < num_ranges; i++)
    {
      CXSourceRange cxrange;
      IdeSourceRange *range;

      cxrange = clang_getDiagnosticRange (cxdiag, i);
349
      range = create_range (self, workpath, cxrange);
350
      if (range != NULL)
351
        ide_diagnostic_take_range (diag, range);
352 353 354
    }

  return diag;
355 356
}

357
/**
358
 * ide_clang_translation_unit_get_diagnostics_for_file:
359
 *
360
 * Retrieves the diagnostics for the translation unit for a specific file.
361 362 363 364
 *
 * Returns: (transfer none) (nullable): An #IdeDiagnostics or %NULL.
 */
IdeDiagnostics *
365 366
ide_clang_translation_unit_get_diagnostics_for_file (IdeClangTranslationUnit *self,
                                                     GFile                   *file)
367 368 369
{
  g_return_val_if_fail (IDE_IS_CLANG_TRANSLATION_UNIT (self), NULL);

370
  if (!g_hash_table_contains (self->diagnostics, file))
371
    {
372
      CXTranslationUnit tu = ide_ref_ptr_get (self->native);
373 374
      g_autofree gchar *workpath = NULL;
      g_autoptr(GPtrArray) diags = NULL;
375
      IdeContext *context;
376
      GFile *workdir;
377
      IdeVcs *vcs;
378 379
      guint count;

380
      diags = g_ptr_array_new_with_free_func ((GDestroyNotify)ide_diagnostic_unref);
381

382
      context = ide_object_get_context (IDE_OBJECT (self));
383 384 385
      vcs = ide_context_get_vcs (context);
      workdir = ide_vcs_get_working_directory (vcs);
      workpath = g_file_get_path (workdir);
386

387
      count = clang_getNumDiagnostics (tu);
388
      for (guint i = 0; i < count; i++)
389
        {
390 391
          g_autoptr(CXDiagnostic) cxdiag = NULL;
          g_autoptr(IdeDiagnostic) diag = NULL;
392

393
          cxdiag = clang_getDiagnostic (tu, i);
394
          diag = create_diagnostic (self, workpath, file, cxdiag);
395 396 397

          if (diag != NULL)
            {
398
              guint num_fixits = clang_getDiagnosticNumFixIts (cxdiag);
399

400
              for (guint j = 0; j < num_fixits; j++)
401
                {
402
                  g_autoptr(IdeSourceRange) range = NULL;
403
                  g_autoptr(IdeFixit) fixit = NULL;
404
                  g_auto(CXString) cxstr = {0};
405 406 407
                  CXSourceRange cxrange;

                  cxstr = clang_getDiagnosticFixIt (cxdiag, j, &cxrange);
408
                  range = create_range (self, workpath, cxrange);
409
                  fixit = ide_fixit_new (range, clang_getCString (cxstr));
410 411

                  if (fixit != NULL)
412
                    ide_diagnostic_take_fixit (diag, g_steal_pointer (&fixit));
413 414
                }

415
              g_ptr_array_add (diags, g_steal_pointer (&diag));
416
            }
417 418
        }

419 420 421
      g_hash_table_insert (self->diagnostics,
                           g_object_ref (file),
                           ide_diagnostics_new (g_steal_pointer (&diags)));
422 423
    }

424 425 426 427 428 429 430 431 432 433 434 435 436 437
  return g_hash_table_lookup (self->diagnostics, file);
}

/**
 * ide_clang_translation_unit_get_diagnostics:
 *
 * Retrieves the diagnostics for the translation unit.
 *
 * Returns: (transfer none) (nullable): An #IdeDiagnostics or %NULL.
 */
IdeDiagnostics *
ide_clang_translation_unit_get_diagnostics (IdeClangTranslationUnit *self)
{
  return ide_clang_translation_unit_get_diagnostics_for_file (self, self->file);
438 439
}

440
gint64
441
ide_clang_translation_unit_get_serial (IdeClangTranslationUnit *self)
442 443 444
{
  g_return_val_if_fail (IDE_IS_CLANG_TRANSLATION_UNIT (self), -1);

445
  return self->serial;
446 447
}

448 449 450 451 452 453 454 455 456 457
static void
ide_clang_translation_unit_set_native (IdeClangTranslationUnit *self,
                                       CXTranslationUnit        native)
{
  g_assert (IDE_IS_CLANG_TRANSLATION_UNIT (self));

  if (native != NULL)
    self->native = ide_ref_ptr_new (native, (GDestroyNotify)clang_disposeTranslationUnit);
}

458 459 460 461 462
static void
ide_clang_translation_unit_finalize (GObject *object)
{
  IdeClangTranslationUnit *self = (IdeClangTranslationUnit *)object;

463 464
  IDE_ENTRY;

465
  g_clear_pointer (&self->native, ide_ref_ptr_unref);
466
  g_clear_object (&self->file);
467
  g_clear_pointer (&self->index, ide_highlight_index_unref);
468
  g_clear_pointer (&self->diagnostics, g_hash_table_unref);
469 470

  G_OBJECT_CLASS (ide_clang_translation_unit_parent_class)->finalize (object);
471

472
  DZL_COUNTER_DEC (instances);
473

474
  IDE_EXIT;
475 476 477 478 479 480 481 482 483 484 485 486
}

static void
ide_clang_translation_unit_get_property (GObject    *object,
                                         guint       prop_id,
                                         GValue     *value,
                                         GParamSpec *pspec)
{
  IdeClangTranslationUnit *self = IDE_CLANG_TRANSLATION_UNIT (object);

  switch (prop_id)
    {
487 488 489 490
    case PROP_FILE:
      g_value_set_object (value, ide_clang_translation_unit_get_file (self));
      break;

491 492 493 494
    case PROP_INDEX:
      g_value_set_boxed (value, ide_clang_translation_unit_get_index (self));
      break;

495 496
    case PROP_SERIAL:
      g_value_set_int64 (value, ide_clang_translation_unit_get_serial (self));
497 498 499 500 501 502 503
      break;

    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
    }
}

504 505 506 507 508 509 510 511 512 513 514 515 516 517
static void
ide_clang_translation_unit_set_property (GObject      *object,
                                         guint         prop_id,
                                         const GValue *value,
                                         GParamSpec   *pspec)
{
  IdeClangTranslationUnit *self = IDE_CLANG_TRANSLATION_UNIT (object);

  switch (prop_id)
    {
    case PROP_FILE:
      ide_clang_translation_unit_set_file (self, g_value_get_object (value));
      break;

518 519 520 521
    case PROP_INDEX:
      ide_clang_translation_unit_set_index (self, g_value_get_boxed (value));
      break;

522 523 524 525 526
    case PROP_SERIAL:
      self->serial = g_value_get_int64 (value);
      break;

    case PROP_NATIVE:
527
      ide_clang_translation_unit_set_native (self, g_value_get_pointer (value));
528 529
      break;

530 531 532 533 534
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
    }
}

535 536 537 538 539 540 541
static void
ide_clang_translation_unit_class_init (IdeClangTranslationUnitClass *klass)
{
  GObjectClass *object_class = G_OBJECT_CLASS (klass);

  object_class->finalize = ide_clang_translation_unit_finalize;
  object_class->get_property = ide_clang_translation_unit_get_property;
542 543
  object_class->set_property = ide_clang_translation_unit_set_property;

544
  properties [PROP_FILE] =
545
    g_param_spec_object ("file",
Piotr Drąg's avatar
Piotr Drąg committed
546 547
                         "File",
                         "The file used to build the translation unit.",
548 549
                         G_TYPE_FILE,
                         (G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
550

551
  properties [PROP_INDEX] =
552
    g_param_spec_boxed ("index",
Piotr Drąg's avatar
Piotr Drąg committed
553 554
                         "Index",
                         "The highlight index for the translation unit.",
555
                         IDE_TYPE_HIGHLIGHT_INDEX,
556
                         (G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
557

558
  properties [PROP_NATIVE] =
559
    g_param_spec_pointer ("native",
Piotr Drąg's avatar
Piotr Drąg committed
560 561
                          "Native",
                          "The native translation unit pointer.",
562 563
                          (G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));

564
  properties [PROP_SERIAL] =
565
    g_param_spec_int64 ("serial",
Piotr Drąg's avatar
Piotr Drąg committed
566 567
                        "Serial",
                        "A sequence number for the translation unit.",
568
                        0,
569 570
                        G_MAXINT64,
                        0,
571
                        (G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
572

573
  g_object_class_install_properties (object_class, LAST_PROP, properties);
574 575 576 577 578
}

static void
ide_clang_translation_unit_init (IdeClangTranslationUnit *self)
{
579
  DZL_COUNTER_INC (instances);
580

581 582 583 584
  self->diagnostics = g_hash_table_new_full ((GHashFunc)g_file_hash,
                                             (GEqualFunc)g_file_equal,
                                             g_object_unref,
                                             (GDestroyNotify)ide_diagnostics_unref);
585
}
586 587

static void
588
ide_clang_translation_unit_code_complete_worker (IdeTask      *task,
589 590 591 592 593 594 595
                                                 gpointer      source_object,
                                                 gpointer      task_data,
                                                 GCancellable *cancellable)
{
  IdeClangTranslationUnit *self = source_object;
  CodeCompleteState *state = task_data;
  CXCodeCompleteResults *results;
596
  CXTranslationUnit tu;
597 598
  g_autoptr(IdeRefPtr) refptr = NULL;
  struct CXUnsavedFile *ufs;
599
  GPtrArray *ar;
600 601 602 603 604 605 606
  gsize i;
  gsize j = 0;

  g_assert (IDE_IS_CLANG_TRANSLATION_UNIT (self));
  g_assert (state);
  g_assert (state->unsaved_files);

607 608
  tu = ide_ref_ptr_get (self->native);

609 610 611 612 613 614 615 616
  /*
   * FIXME: Not thread safe! We should probably add a "Pending" flag or something that is
   *        similar to g_input_stream_set_pending().
   */

  if (!state->path)
    {
      /* implausable to reach here, anyway */
617 618 619 620
      ide_task_return_new_error (task,
                                 G_IO_ERROR,
                                 G_IO_ERROR_INVALID_FILENAME,
                                 _("clang_codeCompleteAt() only works on local files"));
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
      return;
    }

  ufs = g_new0 (struct CXUnsavedFile, state->unsaved_files->len);

  for (i = 0; i < state->unsaved_files->len; i++)
    {
      IdeUnsavedFile *uf;
      gchar *path;
      GFile *file;

      uf = g_ptr_array_index (state->unsaved_files, i);
      file = ide_unsaved_file_get_file (uf);
      path = g_file_get_path (file);

      /*
       * NOTE: Some files might not be local, and therefore return a NULL path.
       *       Also, we will free the path from the (const char *) pointer after
       *       executing the work.
       */
      if (path != NULL)
        {
          GBytes *content = ide_unsaved_file_get_content (uf);

          ufs [j].Filename = path;
          ufs [j].Contents = g_bytes_get_data (content, NULL);
          ufs [j].Length = g_bytes_get_size (content);

          j++;
        }
    }

653
  results = clang_codeCompleteAt (tu,
654 655 656 657 658 659 660 661 662 663 664
                                  state->path,
                                  state->line + 1,
                                  state->line_offset + 1,
                                  ufs, j,
                                  clang_defaultCodeCompleteOptions ());

  /*
   * encapsulate in refptr so we don't need to malloc lots of little strings.
   * we will inflate result strings as necessary.
   */
  refptr = ide_ref_ptr_new (results, (GDestroyNotify)clang_disposeCodeCompleteResults);
665
  ar = g_ptr_array_new_with_free_func (g_object_unref);
666 667

  for (i = 0; i < results->NumResults; i++)
668
    g_ptr_array_add (ar, ide_clang_completion_item_new (refptr, i));
669

670
  ide_task_return_pointer (task, ar, (GDestroyNotify)g_ptr_array_unref);
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686

  /* cleanup malloc'd state */
  for (i = 0; i < j; i++)
    g_free ((gchar *)ufs [i].Filename);
  g_free (ufs);
}


void
ide_clang_translation_unit_code_complete_async (IdeClangTranslationUnit *self,
                                                GFile                   *file,
                                                const GtkTextIter       *location,
                                                GCancellable            *cancellable,
                                                GAsyncReadyCallback      callback,
                                                gpointer                 user_data)
{
687
  g_autoptr(IdeTask) task = NULL;
688 689 690 691
  CodeCompleteState *state;
  IdeContext *context;
  IdeUnsavedFiles *unsaved_files;

692 693
  IDE_ENTRY;

694 695 696 697 698 699 700 701
  g_return_if_fail (IDE_IS_CLANG_TRANSLATION_UNIT (self));
  g_return_if_fail (G_IS_FILE (file));
  g_return_if_fail (location);
  g_return_if_fail (!cancellable || G_IS_CANCELLABLE (cancellable));

  context = ide_object_get_context (IDE_OBJECT (self));
  unsaved_files = ide_context_get_unsaved_files (context);

702
  task = ide_task_new (self, cancellable, callback, user_data);
703 704 705 706 707

  state = g_new0 (CodeCompleteState, 1);
  state->path = g_file_get_path (file);
  state->line = gtk_text_iter_get_line (location);
  state->line_offset = gtk_text_iter_get_line_offset (location);
708
  state->unsaved_files = ide_unsaved_files_to_array (unsaved_files);
709 710 711 712 713 714

  /*
   * TODO: Technically it is not safe for us to go run this in a thread. We need to ensure
   *       that only one thread is dealing with this at a time.
   */

715 716 717
  ide_task_set_task_data (task, state, code_complete_state_free);
  ide_task_set_kind (task, IDE_TASK_KIND_COMPILER);
  ide_task_run_in_thread (task, ide_clang_translation_unit_code_complete_worker);
718 719

  IDE_EXIT;
720 721 722 723
}

/**
 * ide_clang_translation_unit_code_complete_finish:
724
 * @self: an #IdeClangTranslationUnit.
725
 * @result: a #GAsyncResult
726 727 728 729
 * @error: (out) (nullable): A location for a #GError, or %NULL.
 *
 * Completes a call to ide_clang_translation_unit_code_complete_async().
 *
730 731
 * Returns: (transfer container) (element-type GtkSourceCompletionProposal*): An array of
 *   #GtkSourceCompletionProposal. Upon failure, %NULL is returned.
732
 */
733
GPtrArray *
734 735 736 737
ide_clang_translation_unit_code_complete_finish (IdeClangTranslationUnit  *self,
                                                 GAsyncResult             *result,
                                                 GError                  **error)
{
738
  IdeTask *task = (IdeTask *)result;
739 740 741
  GPtrArray *ret;

  IDE_ENTRY;
742 743

  g_return_val_if_fail (IDE_IS_CLANG_TRANSLATION_UNIT (self), NULL);
744
  g_return_val_if_fail (IDE_IS_TASK (task), NULL);
745

746
  ret = ide_task_propagate_pointer (task, error);
747 748

  IDE_RETURN (ret);
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
static enum CXChildVisitResult
find_child_type (CXCursor     cursor,
                 CXCursor     parent,
                 CXClientData user_data)
{
  enum CXCursorKind *child_kind = user_data;
  enum CXCursorKind kind = clang_getCursorKind (cursor);

  switch ((int)kind)
    {
    case CXCursor_StructDecl:
    case CXCursor_UnionDecl:
    case CXCursor_EnumDecl:
      *child_kind = kind;
      return CXChildVisit_Break;

    case CXCursor_TypeRef:
      cursor = clang_getCursorReferenced (cursor);
      *child_kind = clang_getCursorKind (cursor);
      return CXChildVisit_Break;

    default:
      break;
    }

  return CXChildVisit_Continue;
}

779 780 781 782 783
static IdeSymbolKind
get_symbol_kind (CXCursor        cursor,
                 IdeSymbolFlags *flags)
{
  enum CXAvailabilityKind availability;
784
  enum CXCursorKind cxkind;
785 786 787 788 789 790 791
  IdeSymbolFlags local_flags = 0;
  IdeSymbolKind kind = 0;

  availability = clang_getCursorAvailability (cursor);
  if (availability == CXAvailability_Deprecated)
    local_flags |= IDE_SYMBOL_FLAGS_IS_DEPRECATED;

792 793 794 795 796 797 798 799 800 801 802
  cxkind = clang_getCursorKind (cursor);

  if (cxkind == CXCursor_TypedefDecl)
    {
      enum CXCursorKind child_kind = 0;

      clang_visitChildren (cursor, find_child_type, &child_kind);
      cxkind = child_kind;
    }

  switch ((int)cxkind)
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
    {
    case CXCursor_StructDecl:
      kind = IDE_SYMBOL_STRUCT;
      break;

    case CXCursor_UnionDecl:
      kind = IDE_SYMBOL_UNION;
      break;

    case CXCursor_ClassDecl:
      kind = IDE_SYMBOL_CLASS;
      break;

    case CXCursor_FunctionDecl:
      kind = IDE_SYMBOL_FUNCTION;
      break;

    case CXCursor_EnumDecl:
      kind = IDE_SYMBOL_ENUM;
      break;

    case CXCursor_EnumConstantDecl:
      kind = IDE_SYMBOL_ENUM_VALUE;
      break;

    case CXCursor_FieldDecl:
      kind = IDE_SYMBOL_FIELD;
      break;

Debarshi's avatar
Debarshi committed
832 833 834 835
    case CXCursor_InclusionDirective:
      kind = IDE_SYMBOL_HEADER;
      break;

836 837 838 839 840 841 842 843 844
    default:
      break;
    }

  *flags = local_flags;

  return kind;
}

845 846 847 848 849
IdeSymbol *
ide_clang_translation_unit_lookup_symbol (IdeClangTranslationUnit  *self,
                                          IdeSourceLocation        *location,
                                          GError                  **error)
{
850
  g_autofree gchar *workpath = NULL;
851
  g_auto(CXString) cxstr = { 0 };
852 853 854
  g_autoptr(IdeSourceLocation) declaration = NULL;
  g_autoptr(IdeSourceLocation) definition = NULL;
  g_autoptr(IdeSourceLocation) canonical = NULL;
855
  CXTranslationUnit tu;
856 857
  IdeSymbolKind symkind = 0;
  IdeSymbolFlags symflags = 0;
858 859 860
  IdeContext *context;
  IdeVcs *vcs;
  GFile *workdir;
861
  CXSourceLocation cxlocation;
862
  CXCursor tmpcursor;
863 864 865 866 867 868 869 870 871 872 873
  CXCursor cursor;
  CXFile cxfile;
  IdeSymbol *ret = NULL;
  guint line;
  guint line_offset;

  IDE_ENTRY;

  g_return_val_if_fail (IDE_IS_CLANG_TRANSLATION_UNIT (self), NULL);
  g_return_val_if_fail (location != NULL, NULL);

874 875
  tu = ide_ref_ptr_get (self->native);

876 877 878 879 880
  context = ide_object_get_context (IDE_OBJECT (self));
  vcs = ide_context_get_vcs (context);
  workdir = ide_vcs_get_working_directory (vcs);
  workpath = g_file_get_path (workdir);

881 882 883
  line = ide_source_location_get_line (location);
  line_offset = ide_source_location_get_line_offset (location);

884
  if (NULL == (cxfile = get_file_for_location (self, location)))
885 886
    IDE_RETURN (NULL);

887 888
  cxlocation = clang_getLocation (tu, cxfile, line + 1, line_offset + 1);
  cursor = clang_getCursor (tu, cxlocation);
889 890 891
  if (clang_Cursor_isNull (cursor))
    IDE_RETURN (NULL);

Anoop Chandu's avatar
Anoop Chandu committed
892 893 894 895 896
  tmpcursor = clang_getCursorDefinition (cursor);

  if (clang_Cursor_isNull (tmpcursor))
    tmpcursor = clang_getCursorReferenced (cursor);

897 898 899 900 901 902 903
  if (!clang_Cursor_isNull (tmpcursor))
    {
      CXSourceLocation tmploc;
      CXSourceRange cxrange;

      cxrange = clang_getCursorExtent (tmpcursor);
      tmploc = clang_getRangeStart (cxrange);
Anoop Chandu's avatar
Anoop Chandu committed
904 905

      if (clang_isCursorDefinition (tmpcursor))
906
        definition = create_location (self, workpath, tmploc, NULL);
Anoop Chandu's avatar
Anoop Chandu committed
907
      else
908
        declaration = create_location (self, workpath, tmploc, NULL);
909 910
    }

911 912
  symkind = get_symbol_kind (cursor, &symflags);

Debarshi's avatar
Debarshi committed
913 914
  if (symkind == IDE_SYMBOL_HEADER)
    {
Christian Hergert's avatar
Christian Hergert committed
915
      g_auto(CXString) included_file_name = {0};
Debarshi's avatar
Debarshi committed
916
      CXFile included_file;
917
      const gchar *path;
Debarshi's avatar
Debarshi committed
918 919 920

      included_file = clang_getIncludedFile (cursor);
      included_file_name = clang_getFileName (included_file);
921
      path = clang_getCString (included_file_name);
Debarshi's avatar
Debarshi committed
922

923 924
      if (path != NULL)
        {
Christian Hergert's avatar
Christian Hergert committed
925 926 927
          g_autoptr(IdeFile) file = NULL;
          g_autoptr(GFile) gfile = NULL;

928
          gfile = g_file_new_for_path (path);
Christian Hergert's avatar
Christian Hergert committed
929
          file = ide_file_new (context, gfile);
930 931

          g_clear_pointer (&definition, ide_symbol_unref);
Anoop Chandu's avatar
Anoop Chandu committed
932
          declaration = ide_source_location_new (file, 0, 0, 0);
933
        }
Debarshi's avatar
Debarshi committed
934 935
    }

936
  cxstr = clang_getCursorDisplayName (cursor);
937 938
  ret = ide_symbol_new (clang_getCString (cxstr), symkind, symflags,
                        declaration, definition, canonical);
939 940 941 942 943 944 945 946

  /*
   * TODO: We should also get information about the defintion of the symbol.
   *       Possibly more.
   */

  IDE_RETURN (ret);
}
947 948 949 950 951

static IdeSymbol *
create_symbol (CXCursor         cursor,
               GetSymbolsState *state)
{
952
  g_auto(CXString) cxname = {0};
953 954
  g_autoptr(IdeSourceLocation) srcloc = NULL;
  CXSourceLocation cxloc;
955 956
  IdeSymbolKind symkind;
  IdeSymbolFlags symflags;
957 958 959 960 961 962 963 964 965
  const gchar *name;
  guint line;
  guint line_offset;

  cxname = clang_getCursorSpelling (cursor);
  name = clang_getCString (cxname);
  cxloc = clang_getCursorLocation (cursor);
  clang_getFileLocation (cxloc, NULL, &line, &line_offset, NULL);
  srcloc = ide_source_location_new (state->file, line-1, line_offset-1, 0);
966 967
  symkind = get_symbol_kind (cursor, &symflags);

968
  return ide_symbol_new (name, symkind, symflags, NULL, NULL, srcloc);
969 970 971 972 973 974 975 976 977
}

static enum CXChildVisitResult
ide_clang_translation_unit_get_symbols__visitor_cb (CXCursor     cursor,
                                                    CXCursor     parent,
                                                    CXClientData user_data)
{
  GetSymbolsState *state = user_data;
  g_autoptr(IdeSymbol) symbol = NULL;
978
  g_auto(CXString) filename = {0};
979 980 981 982 983 984 985 986 987 988 989 990 991 992 993
  CXSourceLocation cxloc;
  CXFile file;
  enum CXCursorKind kind;

  g_assert (state);

  cxloc = clang_getCursorLocation (cursor);
  clang_getFileLocation (cxloc, &file, NULL, NULL, NULL);
  filename = clang_getFileName (file);

  if (0 != g_strcmp0 (clang_getCString (filename), state->path))
    return CXChildVisit_Continue;

  kind = clang_getCursorKind (cursor);

994
  switch ((int)kind)
995 996
    {
    case CXCursor_FunctionDecl:
997
    case CXCursor_TypedefDecl:
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022