// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! A MIB module, parsed. //! //! ``` //! IF-MIB DEFINITIONS ::= BEGIN //! IMPORTS ifIndex FROM RFC1213-MIB; //! ifTable OBJECT-TYPE ... ::= { interfaces 2 } //! END //! ``` //! //! ## Why the macro bodies are captured rather than parsed here //! //! SMI's macros -- `OBJECT-TYPE`, `TEXTUAL-CONVENTION` and the rest -- are //! ASN.1 macro *invocations*, and ASN.1's macro facility is general enough //! that parsing one properly means implementing the `MACRO` definition //! language. Nobody does that. net-snmp does not: it recognises each macro by //! name and reads its clauses with hand-written code. //! //! This parser takes the same view but splits it in two. The structure every //! macro shares -- a name, a macro keyword, a body, and `::= { parent n }` -- //! is parsed here, and the body is kept as a span of source for the clause //! parser to read. That split is worth having rather than merely convenient: //! it means the **OID tree** can be built from a module whose macro clauses //! have not been understood, so a file using a macro this does not know still //! contributes its names, and a bug in one clause cannot lose a whole module. //! //! It also makes the first thing that can be checked against net-snmp a //! complete one. `snmptranslate -Tz` prints every name and its OID, and //! nothing in that output depends on a single clause. //! //! ## What a MIB does *not* do //! //! There is no ordering. An assignment may name a parent defined later in the //! file or in a module not yet read, so resolution is a separate pass over a //! whole set of modules and cannot happen during parsing. const std = @import("std"); const Allocator = std.mem.Allocator; const assert = std.debug.assert; const testing = std.testing; const Lexer = @import("Lexer.zig"); const Token = Lexer.Token; const Parser = @This(); source: []const u8, lexer: Lexer, /// One token of lookahead, which is all the grammar needs. current: Token, gpa: Allocator, diagnostic: ?Diagnostic = null, pub const Diagnostic = struct { message: []const u8, /// Where, as a byte offset, so a caller can quote the line. offset: usize, /// The 1-based line the offset falls on. Computed rather than tracked, /// because it is wanted once per failure and never otherwise. pub fn line(d: Diagnostic, source: []const u8) usize { var n: usize = 1; for (source[0..@min(d.offset, source.len)]) |c| { if (c == '\n') n += 1; } return n; } }; pub const Error = error{ ParseFailed, /// The file contains no module: it is empty, or all comment. /// /// Distinct from `ParseFailed` because it is not a fault. Cisco's corpus /// ships `test-mib.my`, nine lines of comment saying "please ignore this /// mib", and net-snmp reads it without complaint because there is nothing /// to complain about. Anything walking a directory wants to count that /// separately from a file it could not understand. NoModule, } || Allocator.Error; /// What a module imports, and from where. pub const Import = struct { symbols: []const []const u8, from: []const u8, }; /// One sub-identifier of an OID value. /// /// `{ iso org(3) dod(6) 1 }` has all three forms in one line: a bare name, a /// name with its number in parentheses, and a bare number. The named forms /// matter because the name may be the only thing that resolves -- `{ mgmt 1 }` /// says nothing about where `mgmt` is. pub const SubIdentifier = union(enum) { /// `mgmt` name: []const u8, /// `org(3)` named_number: struct { name: []const u8, number: u32 }, /// `1` number: u32, }; /// `::= { parent 1 }` pub const OidValue = []const SubIdentifier; /// Which macro an assignment invoked, or that it was a plain ASN.1 one. pub const Kind = enum { /// `name OBJECT IDENTIFIER ::= { ... }` object_identifier, module_identity, object_identity, object_type, notification_type, object_group, notification_group, module_compliance, agent_capabilities, /// SMIv1's `TRAP-TYPE`, whose value is a bare number rather than an OID. trap_type, /// `Name ::= TEXTUAL-CONVENTION ...` textual_convention, /// `Name ::= `, an ordinary ASN.1 type assignment: `IfEntry ::= /// SEQUENCE { ... }` and `Counter ::= [APPLICATION 1] IMPLICIT INTEGER`. type_assignment, /// Whether this kind of assignment places a name in the OID tree. /// /// A type assignment and a textual convention do not: they name a *type*, /// which has no position. A TRAP-TYPE does not either -- its value is a /// trap number under an enterprise, not an OID -- which is why SMIv2 /// replaced it. pub fn hasOid(k: Kind) bool { return switch (k) { .textual_convention, .type_assignment, .trap_type => false, else => true, }; } }; pub const Assignment = struct { /// The name being defined. Lower case for an object, upper case for a /// type -- ASN.1 requires the distinction and SMI leans on it. name: []const u8, kind: Kind, /// Where it sits, for the kinds that sit anywhere. oid: ?OidValue, /// The macro's clauses, as a span of the source, for the clause parser. /// Empty for a plain OBJECT IDENTIFIER assignment, which has none. body: []const u8, /// Byte offset of the name, for diagnostics. offset: usize, }; pub const Module = struct { name: []const u8, imports: []const Import, assignments: []const Assignment, /// The assignment of that name, or null. Linear because a module has /// hundreds of assignments rather than thousands, and because building an /// index here would duplicate the one the resolver builds across modules. pub fn find(m: Module, name: []const u8) ?Assignment { for (m.assignments) |a| { if (std.mem.eql(u8, a.name, name)) return a; } return null; } }; /// Parses one module. Everything in the result is allocated from `gpa` or /// points into `source`, so an arena is the natural thing to pass. pub fn parse(gpa: Allocator, source: []const u8, options: Lexer.Options) Error!Module { var p: Parser = .{ .source = source, .lexer = .init(source, options), .current = undefined, .gpa = gpa, }; p.current = p.lexer.next(); return p.module(); } /// Parses one module, reporting where it failed. pub fn parseWithDiagnostic( gpa: Allocator, source: []const u8, options: Lexer.Options, diagnostic: *?Diagnostic, ) Error!Module { var p: Parser = .{ .source = source, .lexer = .init(source, options), .current = undefined, .gpa = gpa, }; p.current = p.lexer.next(); const result = p.module(); diagnostic.* = p.diagnostic; return result; } fn advance(p: *Parser) Token { const t = p.current; p.current = p.lexer.next(); return t; } fn text(p: *const Parser, t: Token) []const u8 { return t.text(p.source); } fn at(p: *const Parser, tag: Token.Tag) bool { return p.current.tag == tag; } fn atKeyword(p: *const Parser, word: []const u8) bool { return p.current.tag == .keyword and std.mem.eql(u8, p.text(p.current), word); } fn eatKeyword(p: *Parser, word: []const u8) bool { if (!p.atKeyword(word)) return false; _ = p.advance(); return true; } fn fail(p: *Parser, message: []const u8) error{ParseFailed} { // The first failure is the one worth reporting; anything after it is a // consequence of being lost. if (p.diagnostic == null) { p.diagnostic = .{ .message = message, .offset = p.current.start }; } return error.ParseFailed; } fn expect(p: *Parser, tag: Token.Tag, message: []const u8) Error!Token { if (p.current.tag != tag) return p.fail(message); return p.advance(); } fn expectKeyword(p: *Parser, word: []const u8, message: []const u8) Error!void { if (!p.eatKeyword(word)) return p.fail(message); } fn module(p: *Parser) Error!Module { // Nothing at all is not a failure; see `Error.NoModule`. if (p.at(.end_of_file)) return error.NoModule; // ` DEFINITIONS ::= BEGIN`. The name is a type reference because // module names are capitalised, and hyphenated: `IF-MIB`, `SNMPv2-SMI`. const name_token = switch (p.current.tag) { .type_reference, .value_reference => p.advance(), else => return p.fail("expected a module name"), }; try p.expectKeyword("DEFINITIONS", "expected DEFINITIONS after the module name"); // A module may declare its tagging environment before `::=`. SMI never // does, but the grammar allows it and a file that used it would otherwise // fail here rather than somewhere informative. while (p.at(.keyword) and !p.atKeyword("BEGIN")) { if (p.atKeyword("EXPLICIT") or p.atKeyword("IMPLICIT") or p.atKeyword("AUTOMATIC")) { _ = p.advance(); _ = p.eatKeyword("TAGS"); continue; } break; } _ = try p.expect(.assign, "expected ::= after DEFINITIONS"); try p.expectKeyword("BEGIN", "expected BEGIN"); var imports: std.ArrayList(Import) = .empty; var assignments: std.ArrayList(Assignment) = .empty; while (true) { if (p.at(.end_of_file)) return p.fail("the module ended without END"); if (p.eatKeyword("END")) break; if (p.atKeyword("IMPORTS")) { _ = p.advance(); try p.importList(&imports); continue; } if (p.atKeyword("EXPORTS")) { // Rare, and carries no information this needs: a module's exports // are what it defines. Skipped to the semicolon. _ = p.advance(); while (!p.at(.semicolon) and !p.at(.end_of_file)) _ = p.advance(); _ = p.eatKeyword(";"); if (p.at(.semicolon)) _ = p.advance(); continue; } if (try p.skipMacroDefinition()) continue; try assignments.append(p.gpa, try p.assignment()); } return .{ .name = p.text(name_token), .imports = try imports.toOwnedSlice(p.gpa), .assignments = try assignments.toOwnedSlice(p.gpa), }; } /// `IMPORTS a, b FROM MOD-1 c FROM MOD-2;` /// /// Note there are no separators between the groups: the end of one is the /// module name after `FROM`, and the start of the next is the symbol after /// that. The list ends at a semicolon. fn importList(p: *Parser, imports: *std.ArrayList(Import)) Error!void { // `IMPORTS ;` is legal and means nothing is imported. while (!p.at(.semicolon)) { if (p.at(.end_of_file)) return p.fail("the IMPORTS list ended without a semicolon"); var symbols: std.ArrayList([]const u8) = .empty; while (true) { const t = switch (p.current.tag) { .value_reference, .type_reference => p.advance(), // A few MIBs import a keyword-looking symbol -- `BITS` is the // usual one, since SMIv2 defines it and ASN.1 reserves it. .keyword => p.advance(), else => return p.fail("expected a symbol to import"), }; try symbols.append(p.gpa, p.text(t)); if (p.at(.comma)) { _ = p.advance(); continue; } break; } try p.expectKeyword("FROM", "expected FROM after the imported symbols"); const from = switch (p.current.tag) { .type_reference, .value_reference => p.advance(), else => return p.fail("expected a module name after FROM"), }; try imports.append(p.gpa, .{ .symbols = try symbols.toOwnedSlice(p.gpa), .from = p.text(from), }); } _ = p.advance(); // the semicolon } /// ` MACRO ::= BEGIN ... END`, skipped. /// /// This is ASN.1's macro *definition* language, and the four modules that /// carry it are the ones that define SMI itself: SNMPv2-TC defines /// TEXTUAL-CONVENTION, SNMPv2-CONF defines OBJECT-GROUP and friends, /// RFC1155-SMI defines OBJECT-TYPE and RFC-1215 defines TRAP-TYPE. Nobody /// implements it -- net-snmp does not -- because a reader that already knows /// those macros learns nothing from their definitions, and implementing it /// would mean a second parser for a language used by four files. /// /// So they are recognised and stepped over. Failing on them instead would /// lose the *other* assignments in those modules, and RFC1155-SMI is where /// `internet`, `mgmt` and `enterprises` are defined -- which is to say the /// top of the tree. /// /// Note the name may be a keyword: `OBJECT-TYPE MACRO ::=` opens with one. fn skipMacroDefinition(p: *Parser) Error!bool { if (p.current.tag != .keyword and p.current.tag != .type_reference and p.current.tag != .value_reference) return false; const saved_lexer = p.lexer; const saved_current = p.current; _ = p.advance(); if (!p.atKeyword("MACRO")) { p.lexer = saved_lexer; p.current = saved_current; return false; } // Past `MACRO ::= BEGIN`, then to the matching END. Macro bodies do not // nest, so the first END at any depth is the right one -- and the body // contains `TYPE NOTATION ::=` and the like, which is why this cannot go // through the ordinary assignment path. _ = p.advance(); _ = try p.expect(.assign, "expected ::= after MACRO"); try p.expectKeyword("BEGIN", "expected BEGIN after MACRO ::="); while (true) { if (p.at(.end_of_file)) return p.fail("a MACRO definition ended without END"); if (p.eatKeyword("END")) return true; _ = p.advance(); } } /// One assignment, in any of its forms. fn assignment(p: *Parser) Error!Assignment { const name_token = switch (p.current.tag) { .value_reference, .type_reference => p.advance(), else => return p.fail("expected a name at the start of an assignment"), }; const name = p.text(name_token); const offset = name_token.start; // `Name ::= ...` is a type assignment or a textual convention; anything // else is a macro invocation, whose keyword comes first. if (p.at(.assign)) { _ = p.advance(); if (p.atKeyword("TEXTUAL-CONVENTION")) { _ = p.advance(); const body = try p.macroBodyToEnd(); return .{ .name = name, .kind = .textual_convention, .oid = null, .body = body, .offset = offset, }; } const body = try p.typeBody(); return .{ .name = name, .kind = .type_assignment, .oid = null, .body = body, .offset = offset, }; } // `name OBJECT IDENTIFIER ::= { ... }`, which is the commonest line in // any MIB and is not a macro at all. if (p.atKeyword("OBJECT")) { _ = p.advance(); if (p.atKeyword("IDENTIFIER")) { _ = p.advance(); _ = try p.expect(.assign, "expected ::= after OBJECT IDENTIFIER"); const oid = try p.oidValue(); return .{ .name = name, .kind = .object_identifier, .oid = oid, .body = "", .offset = offset, }; } return p.fail("expected IDENTIFIER after OBJECT"); } const kind = p.macroKind() orelse return p.fail("expected a macro name or ::="); _ = p.advance(); const body = try p.macroBodyToAssign(); // TRAP-TYPE's value is the trap number, not an OID -- `::= 5`. SMIv2 // replaced it for exactly that reason: a trap had no place in the tree. if (kind == .trap_type) { const number = try p.expect(.number, "expected a trap number after ::="); _ = number; return .{ .name = name, .kind = kind, .oid = null, .body = body, .offset = offset }; } const oid = try p.oidValue(); return .{ .name = name, .kind = kind, .oid = oid, .body = body, .offset = offset }; } /// The macro keywords, and which kind each denotes. const macros = std.StaticStringMap(Kind).initComptime(.{ .{ "MODULE-IDENTITY", .module_identity }, .{ "OBJECT-IDENTITY", .object_identity }, .{ "OBJECT-TYPE", .object_type }, .{ "NOTIFICATION-TYPE", .notification_type }, .{ "OBJECT-GROUP", .object_group }, .{ "NOTIFICATION-GROUP", .notification_group }, .{ "MODULE-COMPLIANCE", .module_compliance }, .{ "AGENT-CAPABILITIES", .agent_capabilities }, .{ "TRAP-TYPE", .trap_type }, }); fn macroKind(p: *const Parser) ?Kind { if (p.current.tag != .keyword) return null; return macros.get(p.text(p.current)); } /// Whether this keyword, following a name, begins a new assignment. /// /// This is the lookahead that ends a type: ASN.1 has no statement /// terminator, so the only thing marking the end of `IfEntry ::= SEQUENCE /// { ... }` is that what follows looks like the start of something else. /// `OBJECT` is in the list for `name OBJECT IDENTIFIER ::=`, which is not a /// macro but begins an assignment all the same. fn startsAssignment(word: []const u8) bool { return macros.has(word) or std.mem.eql(u8, word, "OBJECT") or // ` MACRO ::= BEGIN` -- a macro definition whose name is not // itself an SMI keyword. std.mem.eql(u8, word, "MACRO"); } /// The clauses of a macro invocation, up to its `::=`. /// /// Kept as a span rather than parsed, so that an unfamiliar clause cannot /// lose the assignment's place in the tree. The only thing that has to be got /// right here is where the body *ends*, and that is the `::=` at brace depth /// zero -- a `DEFVAL { 1 }` contains braces and a `SYNTAX SEQUENCE { ... }` /// contains rather more. fn macroBodyToAssign(p: *Parser) Error![]const u8 { const start = p.current.start; var depth: usize = 0; while (true) { switch (p.current.tag) { .end_of_file => return p.fail("the macro body ended without ::="), .left_brace, .left_paren => depth += 1, .right_brace, .right_paren => { if (depth == 0) return p.fail("unbalanced brackets in a macro body"); depth -= 1; }, .assign => if (depth == 0) { const end = p.current.start; _ = p.advance(); return p.source[start..end]; }, .keyword => { // `END` at depth zero means the module ended mid-assignment, // which is a truncated file rather than a body to keep // scanning. Reporting it here names the assignment rather // than the end of the file. if (std.mem.eql(u8, p.text(p.current), "END") and depth == 0) { return p.fail("the module ended in the middle of an assignment"); } }, else => {}, } _ = p.advance(); } } /// A `TEXTUAL-CONVENTION` body, which has no `::=` of its own: it ends where /// the next assignment begins. /// /// That is the one place SMI's grammar is genuinely ambiguous without /// knowing the macro, and it is why this is a separate function. The body /// ends at `SYNTAX `, and what follows the type is the next /// definition. fn macroBodyToEnd(p: *Parser) Error![]const u8 { const start = p.current.start; var depth: usize = 0; var end = p.current.start; while (true) { switch (p.current.tag) { .end_of_file => return p.fail("a TEXTUAL-CONVENTION ended without SYNTAX"), .left_brace, .left_paren => depth += 1, .right_brace, .right_paren => { if (depth > 0) depth -= 1; }, .keyword => { if (depth == 0 and std.mem.eql(u8, p.text(p.current), "SYNTAX")) { _ = p.advance(); const body_end = try p.typeBodyEnd(); return p.source[start..body_end]; } if (depth == 0 and std.mem.eql(u8, p.text(p.current), "END")) { return p.fail("a TEXTUAL-CONVENTION ended without SYNTAX"); } }, else => {}, } end = p.current.end; _ = p.advance(); } } /// A type, as it appears after `::=` in a type assignment. fn typeBody(p: *Parser) Error![]const u8 { const start = p.current.start; const end = try p.typeBodyEnd(); return p.source[start..end]; } /// Scans one type and returns where it ended. /// /// A type runs until the next assignment starts, and what marks that is a /// name followed by `::=` or by a macro keyword -- at brace depth zero. That /// is one token more lookahead than the rest of the grammar needs, and it is /// the price of ASN.1 having no statement terminator. fn typeBodyEnd(p: *Parser) Error!usize { var depth: usize = 0; var end = p.current.start; while (true) { switch (p.current.tag) { .end_of_file => return p.fail("a type ran to the end of the file"), .left_brace, .left_paren, .left_bracket => depth += 1, .right_brace, .right_paren, .right_bracket => { if (depth == 0) return p.fail("unbalanced brackets in a type"); depth -= 1; end = p.current.end; _ = p.advance(); continue; }, .keyword => if (depth == 0) { if (std.mem.eql(u8, p.text(p.current), "END")) return end; // A macro definition names itself with a keyword -- // `OBJECT-TYPE MACRO ::=` -- so the boundary that ends this // type is a keyword followed by `MACRO`, which the name case // below would never see. Without this, the type assignment // just above a macro definition swallows the macro's header, // `skipMacroDefinition` never gets a turn, and the whole // macro body is parsed as ordinary assignments until its // `END` closes the module early. That is how SNMPv2-SMI lost // everything after line 55, `zeroDotZero` included. const saved_lexer = p.lexer; const name = p.current; const after = p.lexer.next(); if (after.tag == .keyword and std.mem.eql(u8, after.text(p.source), "MACRO")) { p.lexer = saved_lexer; p.current = name; return end; } p.lexer = saved_lexer; }, .value_reference, .type_reference => if (depth == 0) { // Look one further: a name followed by `::=` or a macro // keyword begins the next assignment, so this type ended // before it. const saved_lexer = p.lexer; const name = p.current; const after = p.lexer.next(); const starts_next = after.tag == .assign or (after.tag == .keyword and startsAssignment(after.text(p.source))); if (starts_next) { p.lexer = saved_lexer; p.current = name; return end; } p.lexer = saved_lexer; }, else => {}, } end = p.current.end; _ = p.advance(); } } /// `{ iso org(3) dod(6) 1 }` fn oidValue(p: *Parser) Error!OidValue { _ = try p.expect(.left_brace, "expected { at the start of an OID value"); var parts: std.ArrayList(SubIdentifier) = .empty; while (!p.at(.right_brace)) { if (p.at(.end_of_file)) return p.fail("an OID value ended without }"); switch (p.current.tag) { .number => { const t = p.advance(); const n = std.fmt.parseInt(u32, p.text(t), 10) catch return p.fail("a sub-identifier will not fit in 32 bits"); try parts.append(p.gpa, .{ .number = n }); }, .value_reference, .type_reference, .keyword => { const t = p.advance(); const name = p.text(t); if (p.at(.left_paren)) { _ = p.advance(); const number = try p.expect(.number, "expected a number in parentheses"); const n = std.fmt.parseInt(u32, p.text(number), 10) catch return p.fail("a sub-identifier will not fit in 32 bits"); _ = try p.expect(.right_paren, "expected ) after the number"); try parts.append(p.gpa, .{ .named_number = .{ .name = name, .number = n } }); } else { try parts.append(p.gpa, .{ .name = name }); } }, else => return p.fail("expected a name or a number in an OID value"), } } _ = p.advance(); // the closing brace if (parts.items.len == 0) return p.fail("an OID value was empty"); return parts.toOwnedSlice(p.gpa); } // -- tests ------------------------------------------------------------------ fn parseTest(source: []const u8) !struct { std.heap.ArenaAllocator, Module } { var arena: std.heap.ArenaAllocator = .init(testing.allocator); errdefer arena.deinit(); var diagnostic: ?Diagnostic = null; const m = parseWithDiagnostic(arena.allocator(), source, .{}, &diagnostic) catch |err| { if (diagnostic) |d| { std.debug.print("\nparse failed at line {d}: {s}\n", .{ d.line(source), d.message }); } return err; }; return .{ arena, m }; } test "the smallest module there is" { var result = try parseTest("EMPTY-MIB DEFINITIONS ::= BEGIN END"); defer result[0].deinit(); try testing.expectEqualStrings("EMPTY-MIB", result[1].name); try testing.expectEqual(@as(usize, 0), result[1].imports.len); try testing.expectEqual(@as(usize, 0), result[1].assignments.len); } test "IMPORTS, which has no separator between its groups" { var result = try parseTest( \\IF-MIB DEFINITIONS ::= BEGIN \\IMPORTS \\ MODULE-IDENTITY, OBJECT-TYPE, Counter32 \\ FROM SNMPv2-SMI \\ DisplayString, TEXTUAL-CONVENTION \\ FROM SNMPv2-TC; \\END ); defer result[0].deinit(); const m = result[1]; try testing.expectEqual(@as(usize, 2), m.imports.len); try testing.expectEqual(@as(usize, 3), m.imports[0].symbols.len); try testing.expectEqualStrings("SNMPv2-SMI", m.imports[0].from); try testing.expectEqualStrings("Counter32", m.imports[0].symbols[2]); try testing.expectEqualStrings("SNMPv2-TC", m.imports[1].from); // `TEXTUAL-CONVENTION` and `MODULE-IDENTITY` are macro keywords *and* // imported symbols, which is why the symbol list accepts keywords. try testing.expectEqualStrings("TEXTUAL-CONVENTION", m.imports[1].symbols[1]); } test "an empty IMPORTS list, which is legal" { var result = try parseTest("M DEFINITIONS ::= BEGIN IMPORTS ; END"); defer result[0].deinit(); try testing.expectEqual(@as(usize, 0), result[1].imports.len); } test "OBJECT IDENTIFIER assignments, in all three sub-identifier forms" { var result = try parseTest( \\SNMPv2-SMI DEFINITIONS ::= BEGIN \\org OBJECT IDENTIFIER ::= { iso 3 } \\internet OBJECT IDENTIFIER ::= { iso org(3) dod(6) 1 } \\numeric OBJECT IDENTIFIER ::= { 1 3 6 1 4 } \\END ); defer result[0].deinit(); const m = result[1]; try testing.expectEqual(@as(usize, 3), m.assignments.len); const org = m.find("org").?; try testing.expectEqual(Kind.object_identifier, org.kind); try testing.expectEqualStrings("iso", org.oid.?[0].name); try testing.expectEqual(@as(u32, 3), org.oid.?[1].number); // `org(3)` carries both, and the name is what resolves when the number // is absent elsewhere. const internet = m.find("internet").?; try testing.expectEqual(@as(usize, 4), internet.oid.?.len); try testing.expectEqualStrings("org", internet.oid.?[1].named_number.name); try testing.expectEqual(@as(u32, 3), internet.oid.?[1].named_number.number); const numeric = m.find("numeric").?; try testing.expectEqual(@as(u32, 1), numeric.oid.?[0].number); try testing.expectEqual(@as(u32, 4), numeric.oid.?[4].number); } test "an OBJECT-TYPE, whose body is kept and whose place is parsed" { var result = try parseTest( \\IF-MIB DEFINITIONS ::= BEGIN \\ifEntry OBJECT-TYPE \\ SYNTAX IfEntry \\ MAX-ACCESS not-accessible \\ STATUS current \\ DESCRIPTION "An entry." \\ INDEX { ifIndex } \\ ::= { ifTable 1 } \\END ); defer result[0].deinit(); const a = result[1].find("ifEntry").?; try testing.expectEqual(Kind.object_type, a.kind); try testing.expectEqualStrings("ifTable", a.oid.?[0].name); try testing.expectEqual(@as(u32, 1), a.oid.?[1].number); // The body is the clauses, kept for the clause parser. The braces in // INDEX are inside it, which is the whole reason the scan tracks depth: // a `::=` inside a DEFVAL would otherwise end the body early. try testing.expect(std.mem.indexOf(u8, a.body, "MAX-ACCESS") != null); try testing.expect(std.mem.indexOf(u8, a.body, "INDEX") != null); try testing.expect(std.mem.indexOf(u8, a.body, "::=") == null); } test "a DEFVAL containing braces does not end the body early" { var result = try parseTest( \\M DEFINITIONS ::= BEGIN \\o OBJECT-TYPE \\ SYNTAX INTEGER \\ DEFVAL { 1 } \\ ::= { parent 3 } \\END ); defer result[0].deinit(); const a = result[1].find("o").?; try testing.expectEqual(@as(u32, 3), a.oid.?[1].number); try testing.expect(std.mem.indexOf(u8, a.body, "DEFVAL") != null); } test "a TEXTUAL-CONVENTION, which has no ::= of its own" { var result = try parseTest( \\SNMPv2-TC DEFINITIONS ::= BEGIN \\DisplayString ::= TEXTUAL-CONVENTION \\ DISPLAY-HINT "255a" \\ STATUS current \\ DESCRIPTION "Textual information." \\ SYNTAX OCTET STRING (SIZE (0..255)) \\ifIndex OBJECT-TYPE \\ SYNTAX Integer32 \\ ::= { ifEntry 1 } \\END ); defer result[0].deinit(); const m = result[1]; // The convention ends at its SYNTAX, and the next assignment is found -- // which is the thing that goes wrong if the body scan overruns. try testing.expectEqual(@as(usize, 2), m.assignments.len); const tc = m.find("DisplayString").?; try testing.expectEqual(Kind.textual_convention, tc.kind); try testing.expectEqual(@as(?OidValue, null), tc.oid); try testing.expect(std.mem.indexOf(u8, tc.body, "DISPLAY-HINT") != null); try testing.expect(std.mem.indexOf(u8, tc.body, "SIZE") != null); const o = m.find("ifIndex").?; try testing.expectEqual(Kind.object_type, o.kind); try testing.expectEqual(@as(u32, 1), o.oid.?[1].number); } test "type assignments, including the ones with brackets in them" { var result = try parseTest( \\M DEFINITIONS ::= BEGIN \\Counter ::= [APPLICATION 1] IMPLICIT INTEGER (0..4294967295) \\IfEntry ::= SEQUENCE { \\ ifIndex InterfaceIndex, \\ ifDescr DisplayString \\} \\ifTable OBJECT-TYPE \\ SYNTAX SEQUENCE OF IfEntry \\ ::= { interfaces 2 } \\END ); defer result[0].deinit(); const m = result[1]; try testing.expectEqual(@as(usize, 3), m.assignments.len); try testing.expectEqual(Kind.type_assignment, m.find("Counter").?.kind); try testing.expectEqual(Kind.type_assignment, m.find("IfEntry").?.kind); try testing.expectEqual(@as(u32, 2), m.find("ifTable").?.oid.?[1].number); } test "TRAP-TYPE, which is SMIv1 and has no place in the tree" { var result = try parseTest( \\RFC1215-MIB DEFINITIONS ::= BEGIN \\linkDown TRAP-TYPE \\ ENTERPRISE snmp \\ VARIABLES { ifIndex } \\ DESCRIPTION "A linkDown trap." \\ ::= 2 \\END ); defer result[0].deinit(); const a = result[1].find("linkDown").?; try testing.expectEqual(Kind.trap_type, a.kind); // Its value is a trap number under an enterprise, not an OID -- which is // precisely why SMIv2 replaced it with NOTIFICATION-TYPE. try testing.expectEqual(@as(?OidValue, null), a.oid); try testing.expect(!Kind.trap_type.hasOid()); } test "which kinds put a name in the tree" { try testing.expect(Kind.object_identifier.hasOid()); try testing.expect(Kind.object_type.hasOid()); try testing.expect(Kind.module_identity.hasOid()); try testing.expect(Kind.notification_type.hasOid()); // A type has no position, and neither has a trap number. try testing.expect(!Kind.type_assignment.hasOid()); try testing.expect(!Kind.textual_convention.hasOid()); try testing.expect(!Kind.trap_type.hasOid()); } test "a failure says where" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var diagnostic: ?Diagnostic = null; const source = \\M DEFINITIONS ::= BEGIN \\o OBJECT-TYPE \\ SYNTAX INTEGER \\ ::= { parent } \\ ; try testing.expectError( error.ParseFailed, parseWithDiagnostic(arena.allocator(), source, .{}, &diagnostic), ); // The module never ended, which is what the file actually does wrong. try testing.expect(diagnostic != null); try testing.expect(diagnostic.?.line(source) >= 4); } test "a module that ends mid-assignment names the assignment" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var diagnostic: ?Diagnostic = null; // This is what a truncated MIB looks like, and reporting it at the END // rather than at the end of the file is what makes it findable. try testing.expectError(error.ParseFailed, parseWithDiagnostic(arena.allocator(), \\M DEFINITIONS ::= BEGIN \\o OBJECT-TYPE \\ SYNTAX INTEGER \\END , .{}, &diagnostic)); try testing.expect(std.mem.indexOf(u8, diagnostic.?.message, "middle of an assignment") != null); } test "a MACRO definition is stepped over, not parsed" { // RFC1155-SMI defines OBJECT-TYPE *and* the top of the OID tree, so a // parser that failed on the macro definition would lose `internet`, // `mgmt` and `enterprises` -- which is to say everything. var result = try parseTest( \\RFC1155-SMI DEFINITIONS ::= BEGIN \\internet OBJECT IDENTIFIER ::= { iso org(3) dod(6) 1 } \\OBJECT-TYPE MACRO ::= \\BEGIN \\ TYPE NOTATION ::= "SYNTAX" type (TYPE ObjectSyntax) \\ "ACCESS" Access \\ VALUE NOTATION ::= value (VALUE ObjectName) \\END \\mgmt OBJECT IDENTIFIER ::= { internet 2 } \\END ); defer result[0].deinit(); const m = result[1]; // Both assignments survive, and the macro definition contributes none. try testing.expectEqual(@as(usize, 2), m.assignments.len); try testing.expect(m.find("internet") != null); try testing.expectEqual(@as(u32, 2), m.find("mgmt").?.oid.?[1].number); try testing.expect(m.find("OBJECT-TYPE") == null); } test "a macro whose name is a keyword, which is how SNMPv2-TC opens" { var result = try parseTest( \\SNMPv2-TC DEFINITIONS ::= BEGIN \\TEXTUAL-CONVENTION MACRO ::= \\BEGIN \\ TYPE NOTATION ::= DisplayPart \\END \\DisplayString ::= TEXTUAL-CONVENTION \\ STATUS current \\ DESCRIPTION "text" \\ SYNTAX OCTET STRING \\END ); defer result[0].deinit(); // The macro definition goes, and the convention that uses it stays. try testing.expectEqual(@as(usize, 1), result[1].assignments.len); try testing.expectEqual(Kind.textual_convention, result[1].find("DisplayString").?.kind); } test "a name followed by MACRO is not mistaken for an assignment" { // The lookahead has to put the token back when it guesses wrong, or an // ordinary assignment beginning with the same shape would be eaten. var result = try parseTest( \\M DEFINITIONS ::= BEGIN \\macroish OBJECT IDENTIFIER ::= { parent 1 } \\END ); defer result[0].deinit(); try testing.expectEqual(@as(usize, 1), result[1].assignments.len); } test "a file with no module in it is empty, not broken" { // Cisco's corpus ships `test-mib.my`: nine lines of comment, the fourth // of which reads "please ignore this mib". net-snmp reads it without // complaint, and a directory walker wants to count it apart from a file // it genuinely could not parse. var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); for ([_][]const u8{ "", " \n\t\n", "-- please ignore this mib\n-- really\n" }) |source| { try testing.expectError(error.NoModule, parse(arena.allocator(), source, .{})); } // Something that starts a module and then stops is a different answer. try testing.expectError( error.ParseFailed, parse(arena.allocator(), "M DEFINITIONS ::= BEGIN", .{}), ); } test "a type assignment does not swallow the macro definition below it" { // This is SNMPv2-SMI's opening, and it cost most of an afternoon. A type // assignment runs until the next assignment begins, and the lookahead // that finds that boundary knew two shapes -- a name followed by `::=`, // and a name followed by a macro keyword. It knew neither // `MODULE-IDENTITY MACRO`, whose name is a keyword, nor `Foo MACRO`. // // So `ExtUTCTime`'s body ran on through the macro header, past `BEGIN`, // and stopped at the first thing inside the macro body that did look // like an assignment -- `Revision ::=`. `skipMacroDefinition` was never // reached, the macro's internals were parsed as ordinary type // assignments, and the macro's own `END` closed the module. Everything // below line 55 of SNMPv2-SMI was silently lost, `zeroDotZero` included, // and the file still reported a successful parse. var result = try parseTest( \\SNMPv2-SMI DEFINITIONS ::= BEGIN \\ExtUTCTime ::= OCTET STRING(SIZE(11 | 13)) \\MODULE-IDENTITY MACRO ::= \\BEGIN \\ TYPE NOTATION ::= "LAST-UPDATED" value(Update ExtUTCTime) \\ Revision ::= "REVISION" value(Update ExtUTCTime) \\ Text ::= value(IA5String) \\END \\zeroDotZero OBJECT-IDENTITY \\ STATUS current \\ DESCRIPTION "A value used for null identifiers." \\ ::= { 0 0 } \\END ); defer result[0].deinit(); const m = result[1]; try testing.expectEqual(@as(usize, 2), m.assignments.len); try testing.expectEqual(Kind.type_assignment, m.find("ExtUTCTime").?.kind); try testing.expectEqual(Kind.object_identity, m.find("zeroDotZero").?.kind); // The macro's internals contribute nothing. try testing.expect(m.find("Revision") == null); try testing.expect(m.find("Text") == null); } test "a type assignment stops at a macro whose name is not a keyword" { var result = try parseTest( \\M DEFINITIONS ::= BEGIN \\Thing ::= INTEGER \\Whatever MACRO ::= \\BEGIN \\ TYPE NOTATION ::= "X" Text \\END \\after OBJECT IDENTIFIER ::= { iso 1 } \\END ); defer result[0].deinit(); const m = result[1]; try testing.expectEqual(@as(usize, 2), m.assignments.len); try testing.expect(m.find("Thing") != null); try testing.expect(m.find("after") != null); }