// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Tokens out of a MIB module. //! //! SMI is ASN.1's syntax with a set of macros bolted on, so this lexes ASN.1 //! -- and ASN.1's lexical rules contain two traps that between them account //! for most of the disagreement between MIB parsers in the wild. //! //! ## Comments end at `--` *or* at the end of the line //! //! X.208 says a comment begins with `--` and ends either at the next `--` or //! at the end of the line, whichever comes first. So this: //! //! ``` //! SYNTAX INTEGER -- a comment -- (0..255) //! ``` //! //! has a constraint after it, and a parser that treated `--` as "rest of //! line" would silently drop it. But a great many real MIBs contain lines //! like //! //! ``` //! -- ------------------------------------------------------ //! ``` //! //! where the inner `--` pairs close the comment and reopen it an even or odd //! number of times, and the author plainly meant the whole line. net-snmp //! ships `-Pc` to switch the rule off for exactly this reason, and the //! default it chose is that `--` *does* terminate. This lexer follows X.208 by //! default and can be told otherwise, because both readings are wrong for //! some real file. //! //! ## Hyphens are part of identifiers //! //! `mib-2` and `IF-MIB` are single identifiers, so `a-b` does not lex as a //! subtraction and a hyphen is only the start of a comment when doubled. A //! trailing hyphen is not allowed and a double hyphen inside a name would be //! a comment, which is why `snmpTrapOID` is spelled the way it is. //! //! ## Case carries meaning //! //! ASN.1 distinguishes a `typereference` (initial upper case) from a //! `valuereference` (initial lower case), and SMI leans on it: `IfEntry` is a //! type and `ifEntry` is the object of that type. The lexer records which, //! because the parser needs it to tell an assignment from a macro invocation //! without looking ahead. const std = @import("std"); const assert = std.debug.assert; const testing = std.testing; const Lexer = @This(); source: []const u8, index: usize, options: Options, pub const Options = struct { /// Whether `--` closes a comment, as X.208 §8.6 says it does. /// /// Turning it off makes every comment run to the end of its line, which /// is net-snmp's `-Pc`. Neither reading parses every real MIB: the /// standard one mis-reads a banner of dashes, and the lenient one drops a /// constraint written after an inline comment. double_hyphen_ends_comment: bool = true, /// Whether an underscore may appear in an identifier. /// /// ASN.1 says no, and net-snmp agrees by default -- it offers `-Pu` to /// allow them. Cisco writes them anyway: `CISCO-LWAPP-TC-MIB` has /// `dot11_6ghz(6)` and `CISCO-SWITCH-QOS-MIB` has /// `inputStats_ingressStraight(1)`, and net-snmp rejects both with /// `Expected "(" (_)` until `-Pu` is passed. /// /// **The default here is the opposite of net-snmp's**, deliberately. The /// job of this library is to read the MIBs that exist rather than the /// ones that should, and two files out of 1,652 in Cisco's own corpus /// need it. Anything comparing this against net-snmp has to pass `-Pu` /// on that side, which is one flag in a test rather than a flag every /// caller has to remember. allow_underscores: bool = true, }; pub fn init(source: []const u8, options: Options) Lexer { return .{ .source = source, .index = 0, .options = options }; } pub const Token = struct { tag: Tag, /// Byte offsets into the source, so a diagnostic can quote the line and /// nothing needs to be copied. start: usize, end: usize, pub fn text(t: Token, source: []const u8) []const u8 { return source[t.start..t.end]; } pub const Tag = enum { end_of_file, /// An identifier beginning with a lower-case letter: an object, a /// value, a field name. value_reference, /// An identifier beginning with an upper-case letter: a type, a /// module name, a macro name. Keywords are recognised separately. type_reference, /// A reserved word, or one of SMI's macro keywords. keyword, number, /// `"..."`, which may span lines. string, /// `'0A1B'H` hex_string, /// `'1010'B` binary_string, /// `::=` assign, /// `..` range, /// `...` ellipsis, left_brace, right_brace, left_paren, right_paren, left_bracket, right_bracket, comma, semicolon, bar, /// Anything the lexer cannot make sense of. Carried as a token rather /// than returned as an error so that a parser can report where, and /// so that a fuzzer driving the lexer alone always terminates. invalid, }; }; /// The reserved words of ASN.1 that SMI uses, plus SMI's own macro keywords. /// /// SMI's macros are not reserved in ASN.1 -- `OBJECT-TYPE` is an ordinary /// macro reference -- but treating them as keywords here saves the parser a /// string comparison per assignment and makes a misspelling a lexical /// complaint rather than a mysterious parse failure. pub const keywords = std.StaticStringMap(void).initComptime(.{ // ASN.1 structure. .{"DEFINITIONS"}, .{"BEGIN"}, .{"END"}, .{"IMPORTS"}, .{"EXPORTS"}, .{"FROM"}, .{"MACRO"}, .{"NOTATION"}, .{"TYPE"}, .{"VALUE"}, // Types SMI permits. .{"INTEGER"}, .{"OCTET"}, .{"STRING"}, .{"OBJECT"}, .{"IDENTIFIER"}, .{"NULL"}, .{"SEQUENCE"}, .{"OF"}, .{"CHOICE"}, .{"BITS"}, .{"IMPLICIT"}, .{"EXPLICIT"}, .{"APPLICATION"}, .{"UNIVERSAL"}, .{"PRIVATE"}, .{"SIZE"}, .{"WITH"}, .{"SYNTAX"}, .{"COMPONENTS"}, .{"OPTIONAL"}, .{"DEFAULT"}, .{"TRUE"}, .{"FALSE"}, .{"ANY"}, .{"DEFINED"}, .{"BY"}, .{"ABSENT"}, .{"PRESENT"}, .{"MIN"}, .{"MAX"}, .{"PLUS-INFINITY"}, .{"MINUS-INFINITY"}, .{"REAL"}, .{"BOOLEAN"}, .{"ENUMERATED"}, .{"EXTERNAL"}, .{"TAGS"}, .{"AUTOMATIC"}, // SMIv2 macros, RFC 2578 and 2579 and 2580. .{"MODULE-IDENTITY"}, .{"OBJECT-IDENTITY"}, .{"OBJECT-TYPE"}, .{"NOTIFICATION-TYPE"}, .{"TEXTUAL-CONVENTION"}, .{"OBJECT-GROUP"}, .{"NOTIFICATION-GROUP"}, .{"MODULE-COMPLIANCE"}, .{"AGENT-CAPABILITIES"}, // SMIv1, RFC 1155 and 1212 and 1215. TRAP-TYPE is the one that only // exists here, and is why a v1 module cannot be read by a v2-only // parser. .{"TRAP-TYPE"}, // The clauses those macros are built from. .{"LAST-UPDATED"}, .{"ORGANIZATION"}, .{"CONTACT-INFO"}, .{"DESCRIPTION"}, .{"REVISION"}, .{"STATUS"}, .{"REFERENCE"}, .{"MAX-ACCESS"}, .{"ACCESS"}, .{"UNITS"}, .{"INDEX"}, .{"AUGMENTS"}, .{"IMPLIED"}, .{"DEFVAL"}, .{"OBJECTS"}, .{"NOTIFICATIONS"}, .{"DISPLAY-HINT"}, .{"MODULE"}, .{"MANDATORY-GROUPS"}, .{"GROUP"}, .{"WRITE-SYNTAX"}, .{"MIN-ACCESS"}, .{"PRODUCT-RELEASE"}, .{"SUPPORTS"}, .{"INCLUDES"}, .{"VARIABLES"}, .{"ENTERPRISE"}, .{"CREATION-REQUIRES"}, }); pub fn next(l: *Lexer) Token { l.skipTrivia(); const start = l.index; if (l.index >= l.source.len) return .{ .tag = .end_of_file, .start = start, .end = start }; const c = l.source[l.index]; switch (c) { '{' => return l.punctuation(.left_brace, 1), '}' => return l.punctuation(.right_brace, 1), '(' => return l.punctuation(.left_paren, 1), ')' => return l.punctuation(.right_paren, 1), '[' => return l.punctuation(.left_bracket, 1), ']' => return l.punctuation(.right_bracket, 1), ',' => return l.punctuation(.comma, 1), ';' => return l.punctuation(.semicolon, 1), '|' => return l.punctuation(.bar, 1), ':' => { if (std.mem.startsWith(u8, l.source[l.index..], "::=")) { return l.punctuation(.assign, 3); } return l.punctuation(.invalid, 1); }, '.' => { if (std.mem.startsWith(u8, l.source[l.index..], "...")) { return l.punctuation(.ellipsis, 3); } if (std.mem.startsWith(u8, l.source[l.index..], "..")) { return l.punctuation(.range, 2); } return l.punctuation(.invalid, 1); }, '"' => return l.string(start), '\'' => return l.quotedBits(start), '-' => { // A lone hyphen is a negative number's sign; a doubled one would // have been eaten as a comment by `skipTrivia`. if (l.index + 1 < l.source.len and isDigit(l.source[l.index + 1])) { l.index += 1; return l.number(start); } return l.punctuation(.invalid, 1); }, '0'...'9' => return l.number(start), else => { if (isLetter(c)) return l.identifier(start); return l.punctuation(.invalid, 1); }, } } fn punctuation(l: *Lexer, tag: Token.Tag, len: usize) Token { const start = l.index; l.index += len; return .{ .tag = tag, .start = start, .end = l.index }; } /// Whitespace and comments. fn skipTrivia(l: *Lexer) void { while (l.index < l.source.len) { const c = l.source[l.index]; if (c == ' ' or c == '\t' or c == '\r' or c == '\n') { l.index += 1; continue; } if (c == '-' and l.index + 1 < l.source.len and l.source[l.index + 1] == '-') { l.skipComment(); continue; } return; } } fn skipComment(l: *Lexer) void { assert(l.source[l.index] == '-' and l.source[l.index + 1] == '-'); l.index += 2; while (l.index < l.source.len) { const c = l.source[l.index]; // A newline always ends a comment, under either reading. if (c == '\n') { l.index += 1; return; } if (l.options.double_hyphen_ends_comment and c == '-' and l.index + 1 < l.source.len and l.source[l.index + 1] == '-') { l.index += 2; return; } l.index += 1; } } /// `"..."`, which may contain newlines and in which `""` is an escaped quote. /// /// Every DESCRIPTION in every MIB is one of these, and they are long: the /// token carries offsets rather than a copy for that reason. fn string(l: *Lexer, start: usize) Token { l.index += 1; // the opening quote while (l.index < l.source.len) { if (l.source[l.index] == '"') { // A doubled quote is one literal quote, not the end. if (l.index + 1 < l.source.len and l.source[l.index + 1] == '"') { l.index += 2; continue; } l.index += 1; return .{ .tag = .string, .start = start, .end = l.index }; } l.index += 1; } // Ran off the end with the string still open. return .{ .tag = .invalid, .start = start, .end = l.index }; } /// `'0A1B'H` or `'1010'B`. fn quotedBits(l: *Lexer, start: usize) Token { l.index += 1; // the opening quote while (l.index < l.source.len and l.source[l.index] != '\'') l.index += 1; if (l.index >= l.source.len) return .{ .tag = .invalid, .start = start, .end = l.index }; l.index += 1; // the closing quote if (l.index < l.source.len) { switch (l.source[l.index]) { 'H', 'h' => { l.index += 1; return .{ .tag = .hex_string, .start = start, .end = l.index }; }, 'B', 'b' => { l.index += 1; return .{ .tag = .binary_string, .start = start, .end = l.index }; }, else => {}, } } // A quoted run with no radix letter is not an ASN.1 construct. return .{ .tag = .invalid, .start = start, .end = l.index }; } fn number(l: *Lexer, start: usize) Token { while (l.index < l.source.len and isDigit(l.source[l.index])) l.index += 1; return .{ .tag = .number, .start = start, .end = l.index }; } /// An identifier: letters, digits and hyphens, not ending in a hyphen and /// not containing a doubled one -- which would be a comment. fn identifier(l: *Lexer, start: usize) Token { const first = l.source[l.index]; while (l.index < l.source.len) { const c = l.source[l.index]; if (isLetter(c) or isDigit(c)) { l.index += 1; continue; } if (c == '_' and l.options.allow_underscores) { l.index += 1; continue; } if (c == '-') { // A doubled hyphen starts a comment, so the identifier stops // before it; a trailing hyphen is not part of the name either. if (l.index + 1 >= l.source.len) break; const after = l.source[l.index + 1]; if (after == '-') break; if (!isLetter(after) and !isDigit(after)) break; l.index += 1; continue; } break; } const text = l.source[start..l.index]; if (keywords.has(text)) { return .{ .tag = .keyword, .start = start, .end = l.index }; } return .{ .tag = if (std.ascii.isUpper(first)) .type_reference else .value_reference, .start = start, .end = l.index, }; } fn isLetter(c: u8) bool { return std.ascii.isAlphabetic(c); } /// Whether `source` has run out of module: `END` at the top level. /// /// Real MIBs have things after it. `CISCO-OSPF-CAPABILITY.my` ends with /// ``, having evidently been saved from a browser, and /// net-snmp reads it without complaint because it stops at `END` and never /// looks. Anything walking a whole file rather than parsing one should do the /// same, or it reports trailing prose as a lexical failure. pub fn isModuleEnd(t: Token, source: []const u8) bool { return t.tag == .keyword and std.mem.eql(u8, t.text(source), "END"); } fn isDigit(c: u8) bool { return c >= '0' and c <= '9'; } // -- tests ------------------------------------------------------------------ fn expectTags(source: []const u8, expected: []const Token.Tag) !void { var l: Lexer = .init(source, .{}); for (expected) |want| { const token = l.next(); try testing.expectEqual(want, token.tag); } try testing.expectEqual(Token.Tag.end_of_file, l.next().tag); } test "the shape of a module header" { try expectTags( \\IF-MIB DEFINITIONS ::= BEGIN \\IMPORTS ifIndex FROM RFC1213-MIB; \\END , &.{ .type_reference, .keyword, .assign, .keyword, .keyword, .value_reference, .keyword, .type_reference, .semicolon, .keyword, }); } test "case is what tells a type from a value" { // ASN.1 leans on it and SMI leans harder: `IfEntry` is the type and // `ifEntry` the object of that type, and a parser needs to know which // without looking ahead. var l: Lexer = .init("IfEntry ifEntry", .{}); try testing.expectEqual(Token.Tag.type_reference, l.next().tag); try testing.expectEqual(Token.Tag.value_reference, l.next().tag); } test "a hyphen is part of a name, not an operator" { var l: Lexer = .init("mib-2 IF-MIB snmpTrapOID", .{}); const source = "mib-2 IF-MIB snmpTrapOID"; const a = l.next(); try testing.expectEqualStrings("mib-2", a.text(source)); try testing.expectEqual(Token.Tag.value_reference, a.tag); const b = l.next(); try testing.expectEqualStrings("IF-MIB", b.text(source)); try testing.expectEqual(Token.Tag.type_reference, b.tag); try testing.expectEqualStrings("snmpTrapOID", l.next().text(source)); } test "a trailing hyphen is not part of the name" { const source = "abc- def"; var l: Lexer = .init(source, .{}); const a = l.next(); try testing.expectEqualStrings("abc", a.text(source)); // The hyphen is then not anything, which is a lexical complaint rather // than a silent join. try testing.expectEqual(Token.Tag.invalid, l.next().tag); } test "X.208 says -- ends a comment, and that matters" { // The constraint after the inline comment is real, and a parser that // treated `--` as "rest of line" would drop it silently -- which is a // wrong SYNTAX rather than a parse error, so nothing would notice. const source = "SYNTAX INTEGER -- a comment -- (0..255)"; try expectTags(source, &.{ .keyword, .keyword, .left_paren, .number, .range, .number, .right_paren, }); // And with the rule switched off, as net-snmp's -Pc does, the constraint // vanishes. Both readings are wrong for some real file, which is why // this is an option rather than a decision. var lenient: Lexer = .init(source, .{ .double_hyphen_ends_comment = false }); try testing.expectEqual(Token.Tag.keyword, lenient.next().tag); try testing.expectEqual(Token.Tag.keyword, lenient.next().tag); try testing.expectEqual(Token.Tag.end_of_file, lenient.next().tag); } test "a banner of dashes, which is why the lenient reading exists" { // Real MIBs are full of these. Under X.208 the pairs close and reopen the // comment, so what follows an odd number of them is *code* -- and here // that leaves `END` visible either way, but a banner with an odd count // would expose whatever came after it on the line. const source = \\-- ------------------------------------------------- \\END ; try expectTags(source, &.{.keyword}); } test "a comment always ends at a newline" { try expectTags( \\-- an unterminated comment \\END , &.{.keyword}); } test "strings run across lines and double a quote to escape it" { const source = \\DESCRIPTION "one \\two ""quoted"" three" ; var l: Lexer = .init(source, .{}); try testing.expectEqual(Token.Tag.keyword, l.next().tag); const s = l.next(); try testing.expectEqual(Token.Tag.string, s.tag); // The whole thing, quotes included, including the newline. try testing.expect(std.mem.indexOfScalar(u8, s.text(source), '\n') != null); try testing.expect(std.mem.endsWith(u8, s.text(source), "three\"")); try testing.expectEqual(Token.Tag.end_of_file, l.next().tag); } test "an unterminated string is invalid rather than eternal" { var l: Lexer = .init("\"never closed", .{}); try testing.expectEqual(Token.Tag.invalid, l.next().tag); try testing.expectEqual(Token.Tag.end_of_file, l.next().tag); } test "hex and binary strings, and a quoted run with no radix" { var l: Lexer = .init("'0A1B'H '1010'B 'xyz'", .{}); try testing.expectEqual(Token.Tag.hex_string, l.next().tag); try testing.expectEqual(Token.Tag.binary_string, l.next().tag); try testing.expectEqual(Token.Tag.invalid, l.next().tag); } test "numbers, including a negative one" { const source = "0 255 2147483647 -1"; var l: Lexer = .init(source, .{}); try testing.expectEqualStrings("0", l.next().text(source)); try testing.expectEqualStrings("255", l.next().text(source)); try testing.expectEqualStrings("2147483647", l.next().text(source)); const negative = l.next(); try testing.expectEqual(Token.Tag.number, negative.tag); try testing.expectEqualStrings("-1", negative.text(source)); } test "an OID assignment, which is the commonest line in any MIB" { try expectTags("mib-2 OBJECT IDENTIFIER ::= { mgmt 1 }", &.{ .value_reference, .keyword, .keyword, .assign, .left_brace, .value_reference, .number, .right_brace, }); } test "the macros are keywords, so a misspelling is a lexical complaint" { var l: Lexer = .init("OBJECT-TYPE TRAP-TYPE TEXTUAL-CONVENTION", .{}); try testing.expectEqual(Token.Tag.keyword, l.next().tag); try testing.expectEqual(Token.Tag.keyword, l.next().tag); try testing.expectEqual(Token.Tag.keyword, l.next().tag); // A near miss is an ordinary identifier, which the parser will reject // where it expected a macro. var typo: Lexer = .init("OBJECT-TYP", .{}); try testing.expectEqual(Token.Tag.type_reference, typo.next().tag); } test "the lexer terminates on anything" { // Every byte value, in a few arrangements. A lexer that can loop is a // parser that hangs on a malformed file, and MIBs arrive from vendors. var all: [256]u8 = undefined; for (&all, 0..) |*byte, i| byte.* = @intCast(i); for ([_][]const u8{ &all, "", "-", "--", "'", "\"", ":", ".", "..", "::" }) |source| { var l: Lexer = .init(source, .{}); var count: usize = 0; while (l.next().tag != .end_of_file) { count += 1; if (count > source.len + 16) return error.LexerDidNotTerminate; } } } test "underscores, which Cisco writes and ASN.1 does not allow" { // `dot11_6ghz(6)` out of CISCO-LWAPP-TC-MIB. net-snmp rejects this with // `Expected "(" (_)` until `-Pu` is passed; the default here is the other // way round, because the corpus this is meant to read contains them. const source = "dot11_6ghz(6)"; var l: Lexer = .init(source, .{}); const name = l.next(); try testing.expectEqual(Token.Tag.value_reference, name.tag); try testing.expectEqualStrings("dot11_6ghz", name.text(source)); // And with the ASN.1 rule, the name stops at the underscore and the // underscore itself is nothing -- which is exactly the shape of // net-snmp's complaint. var strict: Lexer = .init(source, .{ .allow_underscores = false }); try testing.expectEqualStrings("dot11", strict.next().text(source)); try testing.expectEqual(Token.Tag.invalid, strict.next().tag); // An underscore cannot begin an identifier under either rule: a leading // one is not a letter, so there is no name to continue. var leading: Lexer = .init("_name", .{}); try testing.expectEqual(Token.Tag.invalid, leading.next().tag); } test "END is where a module stops, whatever follows it" { // CISCO-OSPF-CAPABILITY.my has `` after END, saved // from a browser by somebody. net-snmp reads the file without complaint // because it never looks past END, and anything scanning a whole file // has to do the same or report the prose as a failure. const source = \\END \\ ; var l: Lexer = .init(source, .{}); const end = l.next(); try testing.expect(Lexer.isModuleEnd(end, source)); // What follows is not lexable, which is fine because nothing should be // looking. try testing.expect(l.next().tag == .invalid); // And `END` inside a name is not the end of anything. const other = "ENDPOINT"; var o: Lexer = .init(other, .{}); try testing.expect(!Lexer.isModuleEnd(o.next(), other)); } test "the three malformed files in Cisco's corpus, reduced" { // Of 2,852 published MIBs -- 65 from net-snmp, 1,648 Cisco SMIv2 and // 1,139 Cisco SMIv1 -- exactly three do not lex, and net-snmp rejects all // three as well. Both shapes are here because both are what a real broken // MIB looks like, and because a lexer that silently accepted them would // be agreeing with nobody. // CISCO-LWAPP-RF-MIB line 199: a stray full stop after a closing quote. // net-snmp says `Expected "::=" (.)` at the same line. { const source = \\ DESCRIPTION "something". \\ REVISION "202009020000Z" ; var l: Lexer = .init(source, .{}); try testing.expectEqual(Token.Tag.keyword, l.next().tag); // DESCRIPTION try testing.expectEqual(Token.Tag.string, l.next().tag); // The full stop belongs to nothing. try testing.expectEqual(Token.Tag.invalid, l.next().tag); try testing.expectEqual(Token.Tag.keyword, l.next().tag); // REVISION } // CISCO-ST-TC and CISCO-RTTMON-TC-MIB: a DESCRIPTION whose quote was // closed early, leaving prose outside the string. The prose then lexes as // whatever it happens to look like, and the punctuation in it does not // lex at all. net-snmp reaches the same verdict a few dozen tokens later, // at the first character it calls reserved. { const source = \\DESCRIPTION "a maximum of 32Gbit." \\ fiftyG (14) - 50GBit. ; var l: Lexer = .init(source, .{}); try testing.expectEqual(Token.Tag.keyword, l.next().tag); try testing.expectEqual(Token.Tag.string, l.next().tag); // What follows is prose, and it contains things that are not tokens. var sawInvalid = false; while (true) { const t = l.next(); if (t.tag == .end_of_file) break; if (t.tag == .invalid) sawInvalid = true; } try testing.expect(sawInvalid); } }