// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! What a macro invocation said, read out of the span the parser kept. //! //! `Parser` deliberately stops at the shape every SMI macro shares -- a name, //! a macro keyword, a body, and `::= { parent n }` -- and keeps the body as a //! span of source. This is the second pass over that span, and it is separate //! for a reason worth stating: the OID tree does not depend on it. A module //! whose clauses this cannot read still contributes its names, and a bug here //! cannot lose a module the way a bug in `Parser` can. //! //! What it reads is what `snmptranslate -Td` prints, which is the oracle: //! //! ```console //! $ snmptranslate -Td IF-MIB::ifAdminStatus //! ifAdminStatus OBJECT-TYPE //! -- FROM IF-MIB, RFC1213-MIB //! SYNTAX INTEGER {up(1), down(2), testing(3)} //! MAX-ACCESS read-write //! STATUS current //! DESCRIPTION "The desired state of the interface. ..." //! ::= { ... ifEntry(1) 7 } //! ``` //! //! ## Both SMIs, in one reader //! //! SMIv1 and SMIv2 spell several of these differently, and a corpus contains //! both -- RFC1213-MIB is v1 and IF-MIB is v2, and the two define the same //! objects. So `ACCESS` and `MAX-ACCESS` land in the same field, `Status` //! admits v1's `mandatory` and `optional` alongside v2's three, and `Base` //! knows v1's `Counter`, `Gauge` and `NetworkAddress` as well as the v2 //! spellings. Nothing here needs to be told which SMI it is reading, which //! matters because plenty of real modules are a mixture. //! //! ## Unknown clauses are skipped, not failed on //! //! A clause keyword this does not know is stepped over along with its value, //! and an unrecognised body yields a `Clauses` with everything null rather //! than an error. AGENT-CAPABILITIES and MODULE-COMPLIANCE bodies are //! structured lists this makes no attempt at, and a vendor macro may contain //! anything at all; neither should stop the clauses that *are* understood //! from being read. const std = @import("std"); const Allocator = std.mem.Allocator; const testing = std.testing; const Lexer = @import("Lexer.zig"); const Token = Lexer.Token; pub const Error = Allocator.Error; /// How an object may be reached. `ACCESS` in SMIv1, `MAX-ACCESS` in SMIv2. /// /// The order is the ordering RFC 2578 §7.3 gives them, least to most, so /// `@backingInt` compares: a MODULE-COMPLIANCE `MIN-ACCESS` is satisfied by /// anything at or above it. pub const Access = enum { not_accessible, accessible_for_notify, read_only, read_write, read_create, /// SMIv1 only, and deprecated even there. RFC 2578 dropped it because an /// object that cannot be read cannot be verified. write_only, pub fn parse(word: []const u8) ?Access { return map.get(word); } const map = std.StaticStringMap(Access).initComptime(.{ .{ "not-accessible", .not_accessible }, .{ "accessible-for-notify", .accessible_for_notify }, .{ "read-only", .read_only }, .{ "read-write", .read_write }, .{ "read-create", .read_create }, .{ "write-only", .write_only }, }); /// The spelling net-snmp prints, which is the spelling in the source. pub fn text(a: Access) []const u8 { return switch (a) { .not_accessible => "not-accessible", .accessible_for_notify => "accessible-for-notify", .read_only => "read-only", .read_write => "read-write", .read_create => "read-create", .write_only => "write-only", }; } }; /// Whether a definition is still in force. pub const Status = enum { current, deprecated, obsolete, /// SMIv1's word for what SMIv2 calls `current`. mandatory, /// SMIv1 only. optional, pub fn parse(word: []const u8) ?Status { return map.get(word); } const map = std.StaticStringMap(Status).initComptime(.{ .{ "current", .current }, .{ "deprecated", .deprecated }, .{ "obsolete", .obsolete }, .{ "mandatory", .mandatory }, .{ "optional", .optional }, }); pub fn text(s: Status) []const u8 { return @tagName(s); } }; /// The types SMI allows an object to have, in both SMIs' spellings. /// /// This is closed on purpose: RFC 2578 §7.1 says these and no others, and a /// SYNTAX naming anything else is naming a textual convention or another type /// assignment, which only a `Registry` holding the defining module can /// resolve. So `Syntax.base` is null in that case rather than guessed at. pub const Base = enum { integer, integer32, octet_string, object_identifier, null_type, /// SMIv2 only. A named bit list, encoded as an OCTET STRING. bits, ip_address, counter32, gauge32, unsigned32, timeticks, opaque_type, /// SMIv2 only; a v1 agent cannot return one, which is observable. counter64, /// SMIv1's `Counter`, which became `Counter32`. counter, /// SMIv1's `Gauge`, which became `Gauge32`. gauge, /// SMIv1's `NetworkAddress`, a CHOICE with one arm. RFC 2578 dropped it. network_address, /// `SEQUENCE { ... }` -- a table's row type. sequence, /// `SEQUENCE OF ` -- a table. sequence_of, pub fn parse(word: []const u8) ?Base { return map.get(word); } /// The SMIv2 name for the same type. /// /// RFC 2578 §2 renamed three of SMIv1's types without changing them: /// `Counter` became `Counter32` and `Gauge` became `Gauge32`, both with /// the same tag and the same meaning. A module written in 1991 and one /// written in 1999 therefore describe the same object in different words, /// and anything comparing the two -- or deciding how to decode a value -- /// wants the words reconciled. net-snmp prints the SMIv2 spelling for /// both. /// /// `NetworkAddress` is deliberately not folded into `IpAddress`. It is a /// CHOICE that happens to have one arm today, which is not the same claim /// as being that arm, and RFC 2578 removed it rather than renaming it. pub fn canonical(base: Base) Base { return switch (base) { .counter => .counter32, .gauge => .gauge32, else => base, }; } const map = std.StaticStringMap(Base).initComptime(.{ .{ "INTEGER", .integer }, .{ "Integer32", .integer32 }, .{ "OCTET STRING", .octet_string }, .{ "OBJECT IDENTIFIER", .object_identifier }, .{ "NULL", .null_type }, .{ "BITS", .bits }, .{ "IpAddress", .ip_address }, .{ "Counter32", .counter32 }, .{ "Gauge32", .gauge32 }, .{ "Unsigned32", .unsigned32 }, .{ "TimeTicks", .timeticks }, .{ "Opaque", .opaque_type }, .{ "Counter64", .counter64 }, .{ "Counter", .counter }, .{ "Gauge", .gauge }, .{ "NetworkAddress", .network_address }, }); }; /// `up(1)` in an enumeration, or `ifIndex(1)` in a BITS list. pub const NamedNumber = struct { name: []const u8, value: i64, }; /// One end of a range. `MIN` and `MAX` are ASN.1's words for the type's own /// limits, which are not known until the base type is. pub const Bound = union(enum) { number: i64, min, max, }; pub const Range = struct { low: Bound, high: Bound, }; /// `(SIZE (0..255))` or `(1..65535 | 100000)`. pub const Constraint = struct { /// Whether the numbers bound the value or its length. kind: enum { value, size }, /// Alternatives, in source order. `(1..10 | 20)` is two. ranges: []const Range, }; /// A field of a `SEQUENCE`, which is to say a column of a table's row. pub const Field = struct { name: []const u8, /// The type as written; not resolved, for the same reason `Syntax.base` /// is not. type_name: []const u8, }; /// A `SYNTAX` clause, or the right-hand side of a type assignment. pub const Syntax = struct { /// The type as written: `INTEGER`, `OCTET STRING`, `Counter32`, /// `PhysAddress`. Points into the source except for the two-word base /// types, whose spelling is normalised to a single space. name: []const u8, /// Which base type `name` is, or null when it names a textual convention /// or another type assignment. base: ?Base = null, /// `INTEGER { up(1), down(2) }`, or the bit list of a `BITS`. named_numbers: []const NamedNumber = &.{}, constraint: ?Constraint = null, /// `SEQUENCE OF IfEntry` -- the element type. element: ?[]const u8 = null, /// `SEQUENCE { ifIndex InterfaceIndex, ... }` -- the columns. fields: []const Field = &.{}, /// `[APPLICATION 1] IMPLICIT INTEGER` -- SMIv1 defines its application /// types this way, and the tag is what makes `Counter` a `Counter`. tag: ?Tag = null, pub const Tag = struct { class: enum { universal, application, context, private }, number: u32, implicit: bool, }; }; /// One column named by an `INDEX` clause. pub const IndexColumn = struct { name: []const u8, /// `INDEX { ifName, IMPLIED ifAlias }` -- the last column of an index may /// be variable length without a length prefix, which is legal only for /// the last and only for one. implied: bool = false, }; /// `REVISION "..." DESCRIPTION "..."`, of which a MODULE-IDENTITY has any /// number. pub const Revision = struct { /// The `ExtUTCTime` as written, without its quotes: `"200006140000Z"`. date: []const u8, description: []const u8, }; /// Every clause this knows, with null for the ones the body did not have. /// /// A single flat struct rather than a union over the macro kinds, because the /// clauses overlap heavily -- `STATUS` and `DESCRIPTION` are in all of them -- /// and because a caller already knows the kind from the `Assignment`. Which /// clauses are *required* for a kind is RFC 2578's business and not enforced /// here: a real corpus violates those rules, and net-snmp reads the file /// anyway. /// /// Every string points into the body that was parsed, so the source must /// outlive this. Strings taken from a quoted string are the content between /// the quotes; a doubled `""` inside one is ASN.1's escape for a single /// quote, and collapsing it is a renderer's job. pub const Clauses = struct { syntax: ?Syntax = null, /// MODULE-COMPLIANCE's `WRITE-SYNTAX`, which narrows what may be written. write_syntax: ?Syntax = null, /// `DISPLAY-HINT "1x:"` -- how to render the value. On a /// TEXTUAL-CONVENTION only; an object inherits its type's. display_hint: ?[]const u8 = null, units: ?[]const u8 = null, /// `MAX-ACCESS` in SMIv2, `ACCESS` in SMIv1. access: ?Access = null, min_access: ?Access = null, status: ?Status = null, description: ?[]const u8 = null, reference: ?[]const u8 = null, /// Null when there was no INDEX clause; an empty slice cannot happen, /// since `INDEX { }` is not legal. index: ?[]const IndexColumn = null, /// `AUGMENTS { ifEntry }` -- this row extends that one and shares its /// index. Mutually exclusive with `index`, and RFC 2578 says so. augments: ?[]const u8 = null, /// `DEFVAL { 1 }` -- kept as the span between the braces, because what is /// legal there depends on the syntax: a number, a name from an /// enumeration, a quoted string, an OID, or `{ }` for an empty BITS. defval: ?[]const u8 = null, last_updated: ?[]const u8 = null, organization: ?[]const u8 = null, contact_info: ?[]const u8 = null, revisions: []const Revision = &.{}, /// `OBJECTS` of an OBJECT-GROUP or NOTIFICATION-TYPE, `NOTIFICATIONS` of /// a NOTIFICATION-GROUP, `VARIABLES` of an SMIv1 TRAP-TYPE. One field, /// because they are one idea under three names. objects: []const []const u8 = &.{}, /// SMIv1 TRAP-TYPE's `ENTERPRISE`, which is where the trap hangs. enterprise: ?[]const u8 = null, }; /// Reads the clauses out of a macro body. /// /// `body` is `Assignment.body` -- everything between the macro keyword and /// the `::=`, or for a TEXTUAL-CONVENTION everything up to and including its /// `SYNTAX`. Never fails on content: anything unreadable is skipped. pub fn parse(gpa: Allocator, body: []const u8, options: Lexer.Options) Error!Clauses { var c: Cursor = .init(gpa, body, options); var result: Clauses = .{}; var revisions: std.ArrayList(Revision) = .empty; defer revisions.deinit(gpa); while (c.token.tag != .end_of_file) { if (c.token.tag != .keyword) { c.advance(); continue; } const word = c.text(c.token); if (std.mem.eql(u8, word, "SYNTAX")) { c.advance(); result.syntax = try c.syntax(); } else if (std.mem.eql(u8, word, "WRITE-SYNTAX")) { c.advance(); result.write_syntax = try c.syntax(); } else if (std.mem.eql(u8, word, "DISPLAY-HINT")) { c.advance(); result.display_hint = c.string(); } else if (std.mem.eql(u8, word, "UNITS")) { c.advance(); result.units = c.string(); } else if (std.mem.eql(u8, word, "MAX-ACCESS") or std.mem.eql(u8, word, "ACCESS")) { c.advance(); result.access = c.access(); } else if (std.mem.eql(u8, word, "MIN-ACCESS")) { c.advance(); result.min_access = c.access(); } else if (std.mem.eql(u8, word, "STATUS")) { c.advance(); result.status = c.status(); } else if (std.mem.eql(u8, word, "DESCRIPTION")) { c.advance(); const text = c.string(); // A MODULE-IDENTITY's revisions each carry a DESCRIPTION, and the // module's own is the one before the first REVISION. Keeping the // first is what makes `-Td` agree. if (revisions.items.len == 0) { if (result.description == null) result.description = text; } else if (text) |t| { revisions.items[revisions.items.len - 1].description = t; } } else if (std.mem.eql(u8, word, "REFERENCE")) { c.advance(); if (result.reference == null) result.reference = c.string(); } else if (std.mem.eql(u8, word, "INDEX")) { c.advance(); result.index = try c.indexList(); } else if (std.mem.eql(u8, word, "AUGMENTS")) { c.advance(); const names = try c.nameList(); defer gpa.free(names); result.augments = if (names.len > 0) names[0] else null; } else if (std.mem.eql(u8, word, "DEFVAL")) { c.advance(); result.defval = c.bracedSpan(); } else if (std.mem.eql(u8, word, "LAST-UPDATED")) { c.advance(); result.last_updated = c.string(); } else if (std.mem.eql(u8, word, "ORGANIZATION")) { c.advance(); result.organization = c.string(); } else if (std.mem.eql(u8, word, "CONTACT-INFO")) { c.advance(); result.contact_info = c.string(); } else if (std.mem.eql(u8, word, "REVISION")) { c.advance(); const date = c.string() orelse ""; try revisions.append(gpa, .{ .date = date, .description = "" }); } else if (std.mem.eql(u8, word, "OBJECTS") or std.mem.eql(u8, word, "NOTIFICATIONS") or std.mem.eql(u8, word, "VARIABLES")) { c.advance(); if (result.objects.len == 0) result.objects = try c.nameList(); } else if (std.mem.eql(u8, word, "ENTERPRISE")) { c.advance(); const names = try c.nameList(); defer gpa.free(names); result.enterprise = if (names.len > 0) names[0] else null; } else { c.advance(); } } result.revisions = try revisions.toOwnedSlice(gpa); return result; } /// Reads a bare type -- the right-hand side of `Name ::= `, which has /// no clause keywords around it. pub fn parseSyntax(gpa: Allocator, body: []const u8, options: Lexer.Options) Error!Syntax { var c: Cursor = .init(gpa, body, options); return c.syntax(); } // -- the cursor ------------------------------------------------------------- /// One token of lookahead over a body, with every reader written so that /// running off the end is an empty answer rather than a fault. const Cursor = struct { gpa: Allocator, source: []const u8, lexer: Lexer, token: Token, fn init(gpa: Allocator, source: []const u8, options: Lexer.Options) Cursor { var c: Cursor = .{ .gpa = gpa, .source = source, .lexer = .init(source, options), .token = undefined, }; c.token = c.lexer.next(); return c; } fn advance(c: *Cursor) void { c.token = c.lexer.next(); } fn text(c: *const Cursor, t: Token) []const u8 { return t.text(c.source); } fn at(c: *const Cursor, tag: Token.Tag) bool { return c.token.tag == tag; } fn atKeyword(c: *const Cursor, word: []const u8) bool { return c.token.tag == .keyword and std.mem.eql(u8, c.text(c.token), word); } fn eatKeyword(c: *Cursor, word: []const u8) bool { if (!c.atKeyword(word)) return false; c.advance(); return true; } /// The content of a quoted string, without its quotes. fn string(c: *Cursor) ?[]const u8 { if (!c.at(.string)) return null; const t = c.text(c.token); c.advance(); return t[1 .. t.len - 1]; } fn access(c: *Cursor) ?Access { if (c.token.tag != .value_reference and c.token.tag != .keyword) return null; const a = Access.parse(c.text(c.token)); if (a != null) c.advance(); return a; } fn status(c: *Cursor) ?Status { // `OPTIONAL` is an ASN.1 keyword as well as an SMIv1 status, so it // arrives as a keyword rather than a value reference. if (c.token.tag != .value_reference and c.token.tag != .keyword) return null; const s = Status.parse(c.text(c.token)); if (s != null) c.advance(); return s; } /// `{ a, IMPLIED b }`. Returns null if what follows is not a brace, so a /// malformed clause yields no index rather than a wrong one. fn indexList(c: *Cursor) Error!?[]const IndexColumn { if (!c.at(.left_brace)) return null; c.advance(); var list: std.ArrayList(IndexColumn) = .empty; errdefer list.deinit(c.gpa); while (!c.at(.right_brace) and !c.at(.end_of_file)) { const implied = c.eatKeyword("IMPLIED"); switch (c.token.tag) { .value_reference, .type_reference => { try list.append(c.gpa, .{ .name = c.text(c.token), .implied = implied }); c.advance(); }, else => c.advance(), } if (c.at(.comma)) c.advance(); } if (c.at(.right_brace)) c.advance(); if (list.items.len == 0) { list.deinit(c.gpa); return null; } return try list.toOwnedSlice(c.gpa); } /// `{ a, b, c }`, used by OBJECTS, NOTIFICATIONS, VARIABLES, AUGMENTS and /// ENTERPRISE. An unbraced single name is accepted because SMIv1's /// `ENTERPRISE cisco` is written that way. fn nameList(c: *Cursor) Error![]const []const u8 { var list: std.ArrayList([]const u8) = .empty; errdefer list.deinit(c.gpa); if (!c.at(.left_brace)) { switch (c.token.tag) { .value_reference, .type_reference => { try list.append(c.gpa, c.text(c.token)); c.advance(); }, else => {}, } return try list.toOwnedSlice(c.gpa); } c.advance(); while (!c.at(.right_brace) and !c.at(.end_of_file)) { switch (c.token.tag) { .value_reference, .type_reference => { try list.append(c.gpa, c.text(c.token)); c.advance(); }, else => c.advance(), } if (c.at(.comma)) c.advance(); } if (c.at(.right_brace)) c.advance(); return try list.toOwnedSlice(c.gpa); } /// The span between a matched pair of braces, exclusive, which is what /// `DEFVAL` is kept as. fn bracedSpan(c: *Cursor) ?[]const u8 { if (!c.at(.left_brace)) return null; c.advance(); const start = c.token.start; var end = start; var depth: usize = 0; while (!c.at(.end_of_file)) { if (c.at(.left_brace)) depth += 1; if (c.at(.right_brace)) { if (depth == 0) break; depth -= 1; } end = c.token.end; c.advance(); } if (c.at(.right_brace)) c.advance(); return std.mem.trim(u8, c.source[start..end], " \t\r\n"); } /// A type: a name, possibly tagged, possibly with an enumeration or a /// constraint after it. fn syntax(c: *Cursor) Error!Syntax { var result: Syntax = .{ .name = "" }; // `[APPLICATION 1] IMPLICIT INTEGER`, which is how SMIv1's RFC1155 // defines Counter, Gauge, TimeTicks, IpAddress and Opaque. if (c.at(.left_bracket)) { c.advance(); var tag: Syntax.Tag = .{ .class = .context, .number = 0, .implicit = true }; if (c.atKeyword("APPLICATION")) { tag.class = .application; c.advance(); } else if (c.atKeyword("UNIVERSAL")) { tag.class = .universal; c.advance(); } else if (c.atKeyword("PRIVATE")) { tag.class = .private; c.advance(); } if (c.at(.number)) { tag.number = std.fmt.parseInt(u32, c.text(c.token), 10) catch 0; c.advance(); } if (c.at(.right_bracket)) c.advance(); if (c.eatKeyword("EXPLICIT")) tag.implicit = false else _ = c.eatKeyword("IMPLICIT"); result.tag = tag; } switch (c.token.tag) { .keyword => { const word = c.text(c.token); if (std.mem.eql(u8, word, "OCTET")) { c.advance(); _ = c.eatKeyword("STRING"); result.name = "OCTET STRING"; result.base = .octet_string; } else if (std.mem.eql(u8, word, "OBJECT")) { c.advance(); _ = c.eatKeyword("IDENTIFIER"); result.name = "OBJECT IDENTIFIER"; result.base = .object_identifier; } else if (std.mem.eql(u8, word, "SEQUENCE")) { c.advance(); if (c.eatKeyword("OF")) { result.name = "SEQUENCE OF"; result.base = .sequence_of; if (c.at(.type_reference) or c.at(.value_reference)) { result.element = c.text(c.token); c.advance(); } return result; } result.name = "SEQUENCE"; result.base = .sequence; result.fields = try c.fieldList(); return result; } else { result.name = word; result.base = Base.parse(word); c.advance(); } }, .type_reference, .value_reference => { result.name = c.text(c.token); result.base = Base.parse(result.name); c.advance(); }, else => return result, } // `INTEGER { up(1), down(2) }` or `BITS { a(0), b(1) }`. if (c.at(.left_brace)) { result.named_numbers = try c.namedNumbers(); return result; } // `(SIZE (0..255))`, `(1..65535)`, `(SIZE(0..32))`. if (c.at(.left_paren)) result.constraint = try c.constraint(); return result; } /// `{ ifIndex InterfaceIndex, ifDescr DisplayString }`. fn fieldList(c: *Cursor) Error![]const Field { if (!c.at(.left_brace)) return &.{}; c.advance(); var list: std.ArrayList(Field) = .empty; errdefer list.deinit(c.gpa); var depth: usize = 0; while (!c.at(.end_of_file)) { if (c.at(.right_brace) and depth == 0) break; if (c.at(.left_brace) or c.at(.left_paren)) depth += 1; if (c.at(.right_brace) or c.at(.right_paren)) depth -= 1; if (depth == 0 and c.at(.value_reference)) { const name = c.text(c.token); c.advance(); // The field's type runs to the comma or the closing brace, // and may itself be two words or carry a constraint. Only its // head is kept: a row's columns are named by other objects, // and it is the *name* that has to match. var type_name: []const u8 = ""; if (!c.at(.comma) and !c.at(.right_brace) and !c.at(.end_of_file)) { const s = try c.syntax(); type_name = s.name; } try list.append(c.gpa, .{ .name = name, .type_name = type_name }); if (c.at(.comma)) c.advance(); continue; } c.advance(); } if (c.at(.right_brace)) c.advance(); return try list.toOwnedSlice(c.gpa); } /// `{ up(1), down(2), testing(3) }`. fn namedNumbers(c: *Cursor) Error![]const NamedNumber { if (!c.at(.left_brace)) return &.{}; c.advance(); var list: std.ArrayList(NamedNumber) = .empty; errdefer list.deinit(c.gpa); while (!c.at(.right_brace) and !c.at(.end_of_file)) { if (c.token.tag != .value_reference and c.token.tag != .type_reference) { c.advance(); continue; } const name = c.text(c.token); c.advance(); var value: i64 = 0; if (c.at(.left_paren)) { c.advance(); if (c.at(.number)) { value = std.fmt.parseInt(i64, c.text(c.token), 10) catch 0; c.advance(); } if (c.at(.right_paren)) c.advance(); } try list.append(c.gpa, .{ .name = name, .value = value }); if (c.at(.comma)) c.advance(); } if (c.at(.right_brace)) c.advance(); return try list.toOwnedSlice(c.gpa); } /// `(SIZE (0..255 | 300))` or `(0..2147483647)`. fn constraint(c: *Cursor) Error!?Constraint { if (!c.at(.left_paren)) return null; c.advance(); var kind: @FieldType(Constraint, "kind") = .value; if (c.atKeyword("SIZE")) { kind = .size; c.advance(); if (!c.at(.left_paren)) { // `(SIZE)` with nothing after it: skip to the close and give // up rather than read the enclosing parenthesis as a range. while (!c.at(.right_paren) and !c.at(.end_of_file)) c.advance(); if (c.at(.right_paren)) c.advance(); return null; } c.advance(); } var list: std.ArrayList(Range) = .empty; errdefer list.deinit(c.gpa); while (!c.at(.right_paren) and !c.at(.end_of_file)) { const low = c.bound() orelse { c.advance(); continue; }; var high = low; if (c.at(.range)) { c.advance(); high = c.bound() orelse low; } try list.append(c.gpa, .{ .low = low, .high = high }); if (c.at(.bar)) c.advance(); } if (c.at(.right_paren)) c.advance(); // The outer parenthesis of `(SIZE (...))`. if (kind == .size and c.at(.right_paren)) c.advance(); if (list.items.len == 0) { list.deinit(c.gpa); return null; } return .{ .kind = kind, .ranges = try list.toOwnedSlice(c.gpa) }; } fn bound(c: *Cursor) ?Bound { switch (c.token.tag) { .number => { const n = std.fmt.parseInt(i64, c.text(c.token), 10) catch { c.advance(); return null; }; c.advance(); return .{ .number = n }; }, .keyword => { const word = c.text(c.token); if (std.mem.eql(u8, word, "MIN")) { c.advance(); return .min; } if (std.mem.eql(u8, word, "MAX")) { c.advance(); return .max; } return null; }, // `'ffffffff'H` turns up as a bound in a few vendor MIBs. .hex_string, .binary_string => { const t = c.text(c.token); const digits = t[1 .. std.mem.lastIndexOfScalar(u8, t, '\'') orelse t.len - 1]; const base: u8 = if (t[t.len - 1] == 'B') 2 else 16; const n = std.fmt.parseInt(i64, digits, base) catch { c.advance(); return null; }; c.advance(); return .{ .number = n }; }, else => return null, } } }; // -- tests ------------------------------------------------------------------ fn parseTest(body: []const u8) !Clauses { return parse(testing.allocator, body, .{}); } fn free(c: Clauses) void { const gpa = testing.allocator; if (c.syntax) |s| { gpa.free(s.named_numbers); gpa.free(s.fields); if (s.constraint) |k| gpa.free(k.ranges); } if (c.write_syntax) |s| { gpa.free(s.named_numbers); gpa.free(s.fields); if (s.constraint) |k| gpa.free(k.ranges); } if (c.index) |i| gpa.free(i); gpa.free(c.objects); gpa.free(c.revisions); } test "an SMIv2 OBJECT-TYPE, which is the commonest thing in any MIB" { const c = try parseTest( \\SYNTAX INTEGER { up(1), down(2), testing(3) } \\MAX-ACCESS read-write \\STATUS current \\DESCRIPTION "The desired state of the interface." \\REFERENCE "RFC 2863" ); defer free(c); try testing.expectEqualStrings("INTEGER", c.syntax.?.name); try testing.expectEqual(Base.integer, c.syntax.?.base.?); try testing.expectEqual(@as(usize, 3), c.syntax.?.named_numbers.len); try testing.expectEqualStrings("up", c.syntax.?.named_numbers[0].name); try testing.expectEqual(@as(i64, 3), c.syntax.?.named_numbers[2].value); try testing.expectEqual(Access.read_write, c.access.?); try testing.expectEqual(Status.current, c.status.?); try testing.expectEqualStrings("The desired state of the interface.", c.description.?); try testing.expectEqualStrings("RFC 2863", c.reference.?); } test "an SMIv1 OBJECT-TYPE, whose clauses are spelled differently" { // `ACCESS` rather than `MAX-ACCESS`, and `mandatory` rather than // `current`. RFC1213-MIB is written this way and defines many of the same // objects IF-MIB does, so both spellings have to land in the same fields // or the two cannot be compared. const c = try parseTest( \\SYNTAX Counter \\ACCESS read-only \\STATUS mandatory ); defer free(c); try testing.expectEqual(Base.counter, c.syntax.?.base.?); // The same type SMIv2 calls Counter32, and `canonical` says so. try testing.expectEqual(Base.counter32, c.syntax.?.base.?.canonical()); try testing.expectEqual(Access.read_only, c.access.?); try testing.expectEqual(Status.mandatory, c.status.?); } test "a table's row: INDEX, and the SEQUENCE that gives its columns" { const c = try parseTest( \\SYNTAX IfEntry \\MAX-ACCESS not-accessible \\STATUS current \\INDEX { ifIndex } ); defer free(c); try testing.expectEqualStrings("IfEntry", c.syntax.?.name); // Not a base type: only a Registry holding IF-MIB can say what IfEntry is. try testing.expectEqual(@as(?Base, null), c.syntax.?.base); try testing.expectEqual(@as(usize, 1), c.index.?.len); try testing.expectEqualStrings("ifIndex", c.index.?[0].name); try testing.expect(!c.index.?[0].implied); } test "IMPLIED, which is legal only on the last index column" { const c = try parseTest("INDEX { mteOwner, IMPLIED mteTriggerName }"); defer free(c); try testing.expectEqual(@as(usize, 2), c.index.?.len); try testing.expect(!c.index.?[0].implied); try testing.expect(c.index.?[1].implied); try testing.expectEqualStrings("mteTriggerName", c.index.?[1].name); } test "AUGMENTS, which is an INDEX by reference" { const c = try parseTest( \\SYNTAX IfXEntry \\MAX-ACCESS not-accessible \\STATUS current \\AUGMENTS { ifEntry } ); defer free(c); try testing.expectEqualStrings("ifEntry", c.augments.?); // RFC 2578 forbids having both, and a module that did would be reporting // two different indexes for one row. try testing.expectEqual(@as(?[]const IndexColumn, null), c.index); } test "a TEXTUAL-CONVENTION, whose body ends at its own SYNTAX" { const c = try parseTest( \\DISPLAY-HINT "1x:" \\STATUS current \\DESCRIPTION "Media- or physical-level address." \\SYNTAX OCTET STRING ); defer free(c); try testing.expectEqualStrings("1x:", c.display_hint.?); try testing.expectEqual(Base.octet_string, c.syntax.?.base.?); } test "a SIZE constraint, and a value range, which print the same" { { const c = try parseTest("SYNTAX OCTET STRING (SIZE (0..255))"); defer free(c); const k = c.syntax.?.constraint.?; try testing.expectEqual(@as(@TypeOf(k.kind), .size), k.kind); try testing.expectEqual(@as(usize, 1), k.ranges.len); try testing.expectEqual(@as(i64, 0), k.ranges[0].low.number); try testing.expectEqual(@as(i64, 255), k.ranges[0].high.number); } { const c = try parseTest("SYNTAX Integer32 (1..2147483647)"); defer free(c); const k = c.syntax.?.constraint.?; try testing.expectEqual(@as(@TypeOf(k.kind), .value), k.kind); try testing.expectEqual(@as(i64, 1), k.ranges[0].low.number); try testing.expectEqual(@as(i64, 2147483647), k.ranges[0].high.number); } } test "alternatives in a constraint, and a single permitted value" { // `(SIZE (8 | 11))` is two alternatives, each of which is one number // rather than a range -- which is how a fixed-width field is written. const c = try parseTest("SYNTAX OCTET STRING (SIZE (8 | 11))"); defer free(c); const k = c.syntax.?.constraint.?; try testing.expectEqual(@as(usize, 2), k.ranges.len); try testing.expectEqual(@as(i64, 8), k.ranges[0].low.number); try testing.expectEqual(@as(i64, 8), k.ranges[0].high.number); try testing.expectEqual(@as(i64, 11), k.ranges[1].low.number); } test "MIN and MAX, which name the type's own limits" { const c = try parseTest("SYNTAX Integer32 (MIN..MAX)"); defer free(c); const k = c.syntax.?.constraint.?; try testing.expectEqual(Bound.min, k.ranges[0].low); try testing.expectEqual(Bound.max, k.ranges[0].high); } test "SEQUENCE OF and SEQUENCE, which are a table and its row" { { const s = try parseSyntax(testing.allocator, "SEQUENCE OF IfEntry", .{}); defer testing.allocator.free(s.fields); try testing.expectEqual(Base.sequence_of, s.base.?); try testing.expectEqualStrings("IfEntry", s.element.?); } { const s = try parseSyntax(testing.allocator, \\SEQUENCE { \\ ifIndex InterfaceIndex, \\ ifDescr DisplayString, \\ ifSpeed Gauge32 \\} , .{}); defer testing.allocator.free(s.fields); try testing.expectEqual(Base.sequence, s.base.?); try testing.expectEqual(@as(usize, 3), s.fields.len); try testing.expectEqualStrings("ifIndex", s.fields[0].name); try testing.expectEqualStrings("InterfaceIndex", s.fields[0].type_name); try testing.expectEqualStrings("Gauge32", s.fields[2].type_name); } } test "a two-word field type does not eat the next column" { // `OCTET STRING` and `OBJECT IDENTIFIER` are each two tokens, and a // reader that took one would leave the second looking like a column name. const s = try parseSyntax(testing.allocator, \\SEQUENCE { a OCTET STRING, b OBJECT IDENTIFIER, c Counter32 } , .{}); defer testing.allocator.free(s.fields); try testing.expectEqual(@as(usize, 3), s.fields.len); try testing.expectEqualStrings("OCTET STRING", s.fields[0].type_name); try testing.expectEqualStrings("OBJECT IDENTIFIER", s.fields[1].type_name); try testing.expectEqualStrings("c", s.fields[2].name); } test "an application-tagged type, which is how SMIv1 defines its own" { // RFC1155-SMI has no SMIv2 base types to name, so it builds them: // `Counter ::= [APPLICATION 1] IMPLICIT INTEGER (0..4294967295)`. const s = try parseSyntax( testing.allocator, "[APPLICATION 1] IMPLICIT INTEGER (0..4294967295)", .{}, ); defer testing.allocator.free(s.named_numbers); defer if (s.constraint) |k| testing.allocator.free(k.ranges); try testing.expectEqual(@as(u32, 1), s.tag.?.number); try testing.expectEqual(@as(@TypeOf(s.tag.?.class), .application), s.tag.?.class); try testing.expect(s.tag.?.implicit); try testing.expectEqual(Base.integer, s.base.?); try testing.expectEqual(@as(i64, 4294967295), s.constraint.?.ranges[0].high.number); } test "DEFVAL is kept as written, because what is legal there depends on the type" { for ([_]struct { []const u8, []const u8 }{ .{ "DEFVAL { 1 }", "1" }, .{ "DEFVAL { up }", "up" }, .{ "DEFVAL { '00000000'H }", "'00000000'H" }, .{ "DEFVAL { \"a string\" }", "\"a string\"" }, .{ "DEFVAL { { present, absent } }", "{ present, absent }" }, // An empty BITS, which is a value and not an absence. .{ "DEFVAL { { } }", "{ }" }, }) |case| { const c = try parseTest(case[0]); defer free(c); try testing.expectEqualStrings(case[1], c.defval.?); } } test "a MODULE-IDENTITY, whose DESCRIPTIONs are its own and its revisions'" { const c = try parseTest( \\LAST-UPDATED "200006140000Z" \\ORGANIZATION "IETF Interfaces MIB Working Group" \\CONTACT-INFO "Keith McCloghrie" \\DESCRIPTION "The MIB module to describe generic objects." \\REVISION "200006140000Z" \\DESCRIPTION "Clarifications, published as RFC 2863." \\REVISION "199602282155Z" \\DESCRIPTION "Revisions made by the Interfaces MIB WG." ); defer free(c); try testing.expectEqualStrings("200006140000Z", c.last_updated.?); try testing.expectEqualStrings("IETF Interfaces MIB Working Group", c.organization.?); try testing.expectEqualStrings("Keith McCloghrie", c.contact_info.?); // The module's own description is the one before the first REVISION. try testing.expectEqualStrings("The MIB module to describe generic objects.", c.description.?); try testing.expectEqual(@as(usize, 2), c.revisions.len); try testing.expectEqualStrings("199602282155Z", c.revisions[1].date); try testing.expectEqualStrings("Revisions made by the Interfaces MIB WG.", c.revisions[1].description); } test "OBJECTS, NOTIFICATIONS and VARIABLES, which are one idea under three names" { for ([_][]const u8{ "OBJECTS { ifIndex, ifAdminStatus, ifOperStatus }", "NOTIFICATIONS { ifIndex, ifAdminStatus, ifOperStatus }", "VARIABLES { ifIndex, ifAdminStatus, ifOperStatus }", }) |body| { const c = try parseTest(body); defer free(c); try testing.expectEqual(@as(usize, 3), c.objects.len); try testing.expectEqualStrings("ifOperStatus", c.objects[2]); } } test "an SMIv1 TRAP-TYPE" { const c = try parseTest( \\ENTERPRISE cisco \\VARIABLES { ifIndex } \\DESCRIPTION "A linkDown trap." ); defer free(c); try testing.expectEqualStrings("cisco", c.enterprise.?); try testing.expectEqual(@as(usize, 1), c.objects.len); } test "a clause this does not know loses nothing else" { // AGENT-CAPABILITIES and MODULE-COMPLIANCE bodies are full of these, and // a vendor macro may contain anything. Skipping the unknown and reading // the rest is the whole reason this pass is separate from the parser. const c = try parseTest( \\PRODUCT-RELEASE "IOS 15.2" \\STATUS current \\SUPPORTS IF-MIB \\ INCLUDES { ifGeneralGroup } \\DESCRIPTION "What this agent implements." ); defer free(c); try testing.expectEqual(Status.current, c.status.?); try testing.expectEqualStrings("What this agent implements.", c.description.?); } test "an empty body, and one that is only noise" { for ([_][]const u8{ "", " \n\t", "?? ::= ..." }) |body| { const c = try parseTest(body); defer free(c); try testing.expectEqual(@as(?Syntax, null), c.syntax); try testing.expectEqual(@as(?Status, null), c.status); } } test "the access ordering, which MIN-ACCESS compares against" { // RFC 2578 §7.3 orders these, and a MODULE-COMPLIANCE's MIN-ACCESS is // satisfied by anything at or above it. try testing.expect(@backingInt(Access.not_accessible) < @backingInt(Access.read_only)); try testing.expect(@backingInt(Access.read_only) < @backingInt(Access.read_write)); try testing.expect(@backingInt(Access.read_write) < @backingInt(Access.read_create)); }