【问题标题】:Function boundary identification using libclang使用 libclang 进行函数边界识别
【发布时间】:2017-09-13 14:38:13
【问题描述】:

我正在学习使用 Python + libclang 解析 C++ 文件,这在 Eli Bendersky 提供的这个内容丰富(但有点过时)的教程的帮助下。

我的目标是解析 C++ 文件并确定这些文件中存在的函数的函数边界。我期待建立一个这种形式的python字典:

{<func_name>:(<func_start_loc>, <func_end_loc>), ...}

为此,我能够获取函数名称(使用cursor.spelling 用于CursorKind.FUNCTION_DECLCursorKind.CXX_METHOD 类型的AST 节点)和起始位置(使用cursor.location

我的问题是,我如何获得函数位置的结尾

【问题讨论】:

    标签: python clang llvm clang++ libclang


    【解决方案1】:
    #include "clang/Basic/SourceManager.h"
    
    FunctionDecl *f;
    
    SourceLocation ST = f->getSourceRange().getBegin();
    SourceLocation ED = f->getSourceRange().getEnd();
    

    https://github.com/eliben/llvm-clang-samples/blob/master/src_clang/rewritersample.cpp

    https://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html https://clang.llvm.org/doxygen/classclang_1_1SourceRange.html

    【讨论】:

      【解决方案2】:

      您正在寻找 Cursor 类的 extent 属性。例如:

      s = '''
      void f();
      void g() 
      {}
      void f() 
      {}
      '''
      
      idx = clang.cindex.Index.create()
      tu = idx.parse('tmp.cpp', unsaved_files=[('tmp.cpp', s)])
      for f in tu.cursor.walk_preorder():
          if f.kind == CursorKind.FUNCTION_DECL:
              print f.extent
      

      将返回与源范围等效的 Python:

      <SourceRange start <SourceLocation file 'tmp.cpp', line 2, column 1>, end <SourceLocation file 'tmp.cpp', line 2, column 9>>
      <SourceRange start <SourceLocation file 'tmp.cpp', line 3, column 1>, end <SourceLocation file 'tmp.cpp', line 4, column 3>>
      <SourceRange start <SourceLocation file 'tmp.cpp', line 5, column 1>, end <SourceLocation file 'tmp.cpp', line 6, column 3>>
      

      如果您想要函数体而不仅仅是它们的声明,您可能需要考虑将注意力限制在使用 Cursor.is_definition 的定义上。

      【讨论】:

      • 非常感谢。这正是我想要的。
      猜你喜欢
      • 1970-01-01
      • 2020-05-26
      • 1970-01-01
      • 1970-01-01
      • 2016-10-01
      • 2012-04-30
      • 1970-01-01
      • 2021-06-08
      • 2014-01-16
      相关资源
      最近更新 更多