llvm / llvm-project

The LLVM Project is a collection of modular and reusable compiler and toolchain technologies.
http://llvm.org
Other
28.06k stars 11.59k forks source link

-ast-dump=json does not reference the correct include file #62500

Open briandw opened 1 year ago

briandw commented 1 year ago

The ast-dump command attributes the struct foo to the wrong include file when dumping to JSON.

Here's the setup:

secondary.h:

struct foo {
  int x;
};
typedef struct foo foo_t;

primary.h:

#include "secondary.h"

test.c:

#include "primary.h"

void bar(foo_t f) {}

Normal ast-dump lists secondary.h:

$ clang -I. -Xclang -ast-dump -fsyntax-only -x c test.c
RecordDecl 0x1230f2528 <./secondary.h:2:1, line:4:1> line:2:8 struct foo definition
| `-FieldDecl 0x1230f25e8 <line:3:3, col:7> col:7 x 'int'
|-TypedefDecl 0x1230f2690 <line:6:1, col:20> col:20 referenced foo_t 'struct foo':'struct foo'
| `-ElaboratedType 0x1230f2640 'struct foo' sugar
|   `-RecordType 0x1230f25b0 'struct foo'
|     `-Record 0x1230f2528 'foo'
`-FunctionDecl 0x1230f2858 <test.c:4:1, line:6:1> line:4:6 bar 'void (foo_t)'
  |-ParmVarDecl 0x1230f2760 <col:10, col:16> col:16 f 'foo_t':'struct foo'

JSON ast-dump lists primary.h:

$ clang -I. -Xclang -ast-dump=json -fsyntax-only -x c test.c    
{
      "id": "0x15a0f0690",
      "kind": "TypedefDecl",
      "loc": {
        "offset": 46,
        "line": 6,
        "col": 20,
        "tokLen": 5,
        "includedFrom": {
          "file": "./primary.h"
        }
      },
      "range": {
        "begin": {
          "offset": 27,
          "col": 1,
          "tokLen": 7,
          "includedFrom": {
            "file": "./primary.h"
          }
        },
        "end": {
          "offset": 46,
          "col": 20,
          "tokLen": 5,
          "includedFrom": {
            "file": "./primary.h"
          }
        }
      },
      "isReferenced": true,
      "name": "foo_t",
      "type": {
        "desugaredQualType": "struct foo",
        "qualType": "struct foo"
      },
llvmbot commented 1 year ago

@llvm/issue-subscribers-clang-frontend

AaronBallman commented 1 year ago

I believe the issue is around: https://github.com/llvm/llvm-project/blob/main/clang/lib/AST/JSONNodeDumper.cpp#L276; we're getting the presumed location so we properly handle GNU linemarkers and whatnot, but it seems we're getting an unexpected source location in this case.