You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Protobuf的source_code_info().location_size()返回值为0?

Protobuf source_code_info.location_size() 返回0但ShortDebugString显示有内容的问题

问题描述

我编写了一个解析.proto文件的工具,调用file_proto.source_code_info().location_size()获取条目数量时始终得到0值,但打印file_proto.ShortDebugString()结果显示其中实际包含内容。相关代码如下:

bool PbConst::CheckFileAndGetDeclarationCode(const pb::FileDescriptor *file_desc, std::string &code_block) const {
    int ret = ErrorCode::PROCESS_SUCCESS;
    pb::FileDescriptorProto file_proto;
    file_desc->CopySourceCodeInfoTo(&file_proto);
    const pb::SourceCodeInfo *src_info = &file_proto.source_code_info();

    std::cout << file_proto.ShortDebugString() << std::endl;
    std::cout << "location_size: " << file_proto.source_code_info().location_size() << std::endl;

    for (int i = 0; i < src_info->location_size(); ++i) {
        const auto *loc = &src_info->location(i);
        if ((loc->path_size() == 1 && loc->path(0) == 2) ||  // import
            (loc->path_size() == 2 && loc->path(0) == 3)) {  // package
            if (!loc->leading_comments().empty()) {
                std::string src = loc->leading_comments();
                std::string attachment;
                ret = handle_common_cmd("@pbc_declare", src, attachment);
                COND_EXP(ret == ErrorCode::PROCESS_SUCCESS, std::swap(code_block, src); return true);
            }
        }
    }
    return false;
}

使用的Protobuf版本为3.7.0,项目代码路径为ModTools/blob/master/pbc/src/pb_const.cc。请问是location_size()存在问题,还是我有理解误区?

原因分析与解决方法

  1. 核心问题:原始FileDescriptor未包含源码信息
    CopySourceCodeInfoTo仅负责复制已有源码信息,如果传入的file_desc本身没有加载源码注释、位置等信息,复制后的FileDescriptorProto的source_code_info字段自然是空的,调用location_size()返回0是正常结果。

  2. 确保FileDescriptor包含源码信息的方式

  • 若通过protoc编译生成FileDescriptorSet后加载,需在编译时添加--include_source_info参数,生成的FileDescriptorSet才会包含源码相关数据。
  • 若动态加载.proto文件,需在构建解析器时开启对应选项(比如给google::protobuf::compiler::Parser调用set_keep_source_info(true)),让解析器保留源码信息。
  1. ShortDebugString()的误导点
    你看到ShortDebugString()有内容,大概率是FileDescriptorProto的其他字段(如package、import列表)有值,而非source_code_info字段。可以直接打印src_info->DebugString()验证,若输出为空,说明确实没有源码信息被复制过来。

内容的提问来源于stack exchange,提问作者Modnar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 09:24:17