Implementation:Onnx Onnx OnnxParser Class
| Knowledge Sources | |
|---|---|
| Domains | Parsing, Text Format, Type System |
| Last Updated | 2026-02-10 00:00 GMT |
Overview
parser.h declares the interface for the ONNX text format parser, defining the ParserBase and OnnxParser classes along with supporting type maps and keyword definitions that enable parsing of human-readable ONNX syntax into protobuf structures.
Description
This header defines the complete API for ONNX text format parsing through several layered components:
Type aliases at the top define protobuf repeated field types used throughout the parser: IdList (list of strings), NodeList, AttrList, ValueInfoList, TensorList, OpsetIdList, and StringStringList. These provide clean type names for the protobuf container types.
StringIntMap<Map> is a CRTP template class providing bidirectional string-to-integer mapping functionality with static Lookup, ToString, and Instance methods. It serves as the base for:
- PrimitiveTypeNameMap -- Maps ONNX primitive type names (float, int8, uint16, double, bfloat16, float8e4m3fn, uint4, int2, etc.) to their TensorProto_DataType enum values. Covers 25 data types including all standard and low-precision formats. Provides IsTypeName() for type checking.
- AttributeTypeNameMap -- Maps attribute type names (float, int, string, tensor, graph, sparse_tensor, type_proto, and their plural forms) to AttributeProto_AttributeType enum values.
KeyWordMap defines ONNX text format reserved keywords as an enum class: IR_VERSION, OPSET_IMPORT, PRODUCER_NAME, PRODUCER_VERSION, DOMAIN_KW, MODEL_VERSION, DOC_STRING, METADATA_PROPS, SEQ_TYPE, MAP_TYPE, OPTIONAL_TYPE, SPARSE_TENSOR_TYPE, and OVERLOAD_KW. Provides Lookup and ToString for keyword resolution.
ParserBase is the foundational parser class providing core parsing primitives:
- Position management: SavePos(), RestorePos(), GetCurrentPos(), GetErrorContext()
- Character scanning: NextChar(), Matches(), Match(), EndOfInput(), SkipWhiteSpace() (including '#' comment skipping)
- Literal parsing: Parse(Literal&) for strings, integers, and floats
- Type parsing: Parse(int64_t&), Parse(uint64_t&), Parse(float&), Parse(double&), Parse(std::string&)
- Identifier parsing: ParseOptionalIdentifier(), ParseIdentifier(), ParseQuotableIdentifier(), PeekIdentifier()
- A Literal struct with LiteralType enum (UNDEFINED, INT_LITERAL, FLOAT_LITERAL, STRING_LITERAL)
OnnxParser extends ParserBase with ONNX-specific parsing methods for all major protobuf types (TensorShapeProto, TypeProto, TensorProto, AttributeProto, NodeProto, GraphProto, FunctionProto, ModelProto, etc.). It also provides a static convenience template Parse<T>(data, input) for one-shot parsing.
Usage
This header is included wherever ONNX text format parsing is needed. The primary use cases are: constructing operator function bodies from text in schema definitions, building test cases with readable syntax, and providing text-based model construction APIs. The note in the file header indicates the syntax is experimental and may change.
Code Reference
Source Location
- Repository: Onnx_Onnx
- File: onnx/defs/parser.h
- Lines: 1-484
Signature
// Core type aliases
using IdList = google::protobuf::RepeatedPtrField<std::string>;
using NodeList = google::protobuf::RepeatedPtrField<NodeProto>;
using AttrList = google::protobuf::RepeatedPtrField<AttributeProto>;
using ValueInfoList = google::protobuf::RepeatedPtrField<ValueInfoProto>;
using TensorList = google::protobuf::RepeatedPtrField<TensorProto>;
using OpsetIdList = google::protobuf::RepeatedPtrField<OperatorSetIdProto>;
// ParserBase class
class ParserBase {
public:
explicit ParserBase(const std::string& str);
explicit ParserBase(const char* cstr);
Common::Status Parse(Literal& result);
Common::Status Parse(int64_t& val);
Common::Status Parse(std::string& val);
std::string ParseOptionalIdentifier();
Common::Status ParseIdentifier(std::string& id);
// ...
};
// OnnxParser class
class OnnxParser : public ParserBase {
public:
explicit OnnxParser(const char* cstr);
Common::Status Parse(ModelProto& model);
Common::Status Parse(GraphProto& graph);
Common::Status Parse(FunctionProto& fn);
Common::Status Parse(NodeProto& node);
Common::Status Parse(TypeProto& typeProto);
// Static convenience method
template <typename T>
static Common::Status Parse(T& parsedData, const char* input);
};
Import
#include "onnx/defs/parser.h"
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| str / cstr | const std::string& or const char* | Yes | The ONNX text format string to initialize the parser with |
| parsedData | T& (template) | Yes | Reference to the protobuf object to populate when using the static Parse method |
| input | const char* | Yes | The text input when using the static Parse convenience method |
Outputs
| Name | Type | Description |
|---|---|---|
| return | Common::Status | OK on successful parse, FAIL with detailed error message (including line:column position and error context) on failure |
| parsedData | T& (modified) | The populated protobuf structure |
Usage Examples
#include "onnx/defs/parser.h"
using namespace ONNX_NAMESPACE;
// Use the static convenience method for one-shot parsing
ModelProto model;
auto status = OnnxParser::Parse(model, "<ir_version: 8, opset_import: [\"\" : 13]> main (float[N] X) => (float[N] Y) { Y = Relu(X) }");
// Use PrimitiveTypeNameMap for type lookups
int dtype = PrimitiveTypeNameMap::Lookup("float16"); // Returns TensorProto_DataType_FLOAT16
bool is_type = PrimitiveTypeNameMap::IsTypeName("bfloat16"); // Returns true
const std::string& name = PrimitiveTypeNameMap::ToString(TensorProto_DataType_FLOAT); // Returns "float"
// Use KeyWordMap for keyword lookups
auto kw = KeyWordMap::Lookup("opset_import"); // Returns KeyWord::OPSET_IMPORT
// Use the parser instance directly for step-by-step parsing
OnnxParser parser("float[3,4,5]");
TypeProto type;
auto result = parser.Parse(type);
if (result.IsOK() && parser.EndOfInput()) {
// Successfully parsed the type
}