mib-rs 0.10.0

SNMP MIB parser and resolver
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
//! Loaded MIB module data and per-module symbol indices.
//!
//! [`ModuleData`] stores module-level metadata (organization, description,
//! revisions, imports) along with per-entity name indices for fast lookup
//! within a single module.
//!
//! For handle-oriented access, see [`Module`](super::handle::Module).

use std::collections::{HashMap, HashSet};

use crate::mib::Oid;
use crate::source::{SourceId, SourceRange};
use crate::types::{Language, Status};

use super::navigation::SemanticSpanIndex;
use super::symbol::Symbol;
use super::types::*;

/// The declared kind of a module-scoped OID identity.
///
/// Unlike the global OID tree's winning [`Kind`](crate::Kind), this value is
/// retained independently for every declaration, including aliases and OID
/// collisions.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ModuleIdentityKind {
    /// A `MODULE-IDENTITY` declaration.
    ModuleIdentity,
    /// An `OBJECT-IDENTITY` declaration.
    ObjectIdentity,
    /// A plain `OBJECT IDENTIFIER` value assignment.
    ObjectIdentifier,
}

/// Exact module-scoped data for one resolved OID identity declaration.
///
/// Multiple records may have the same numeric OID. This preserves aliases and
/// declarations that lost global OID-tree ownership to another module or to
/// an object, group, notification, or conformance definition.
#[derive(Debug, Clone)]
pub struct ModuleIdentityData {
    pub(crate) name: String,
    pub(crate) kind: ModuleIdentityKind,
    pub(crate) oid: Oid,
    pub(crate) status: Option<Status>,
    pub(crate) description: String,
    pub(crate) reference: String,
    pub(crate) last_updated: String,
    pub(crate) organization: String,
    pub(crate) contact_info: String,
    pub(crate) revisions: Vec<Revision>,
    pub(crate) oid_refs: Vec<OidRef>,
    pub(crate) range: SourceRange,
}

impl ModuleIdentityData {
    /// Return the name exactly as declared in this module.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Return the declaration kind independently of global OID ownership.
    pub fn kind(&self) -> ModuleIdentityKind {
        self.kind
    }

    /// Return the resolved numeric OID.
    pub fn oid(&self) -> &Oid {
        &self.oid
    }

    /// Return the declared status for an `OBJECT-IDENTITY`.
    pub fn status(&self) -> Option<Status> {
        self.status
    }

    /// Return the declared description text.
    pub fn description(&self) -> &str {
        &self.description
    }

    /// Return the declared reference text.
    pub fn reference(&self) -> &str {
        &self.reference
    }

    /// Return the `LAST-UPDATED` value for a `MODULE-IDENTITY`.
    pub fn last_updated(&self) -> &str {
        &self.last_updated
    }

    /// Return the `ORGANIZATION` text for a `MODULE-IDENTITY`.
    pub fn organization(&self) -> &str {
        &self.organization
    }

    /// Return the `CONTACT-INFO` text for a `MODULE-IDENTITY`.
    pub fn contact_info(&self) -> &str {
        &self.contact_info
    }

    /// Return the revisions for a `MODULE-IDENTITY` in declaration order.
    pub fn revisions(&self) -> &[Revision] {
        &self.revisions
    }

    /// Return symbolic references with exact resolved module/version provenance.
    pub fn oid_refs(&self) -> &[OidRef] {
        &self.oid_refs
    }

    /// Return the exact symbolic parent reference used by this declaration.
    pub fn declared_oid_parent(&self) -> Option<&OidRef> {
        let parent = self.oid.parent()?;
        self.oid_refs
            .iter()
            .rev()
            .find(|reference| reference.oid() == Some(&parent))
    }

    /// Return the exact symbolic parent name, or an empty string when the
    /// assignment used no exact symbolic parent.
    pub fn declared_oid_parent_name(&self) -> &str {
        self.declared_oid_parent()
            .map_or("", |reference| reference.name.as_str())
    }

    /// Return the complete source range of the declaration.
    pub fn range(&self) -> SourceRange {
        self.range
    }
}

/// A loaded and resolved MIB module.
///
/// Contains module-level metadata (organization, description, revisions),
/// import declarations, and per-entity name indices. Access through the
/// public accessor methods or the [`Module`](super::handle::Module) handle.
pub struct ModuleData {
    pub(crate) name: String,
    pub(crate) language: Language,
    pub(crate) source_id: Option<SourceId>,
    pub(crate) is_base: bool,
    pub(crate) oid: Option<Oid>,
    pub(crate) organization: String,
    pub(crate) contact_info: String,
    pub(crate) description: String,
    pub(crate) last_updated: String,
    pub(crate) revisions: Vec<Revision>,
    pub(crate) imports: Vec<Import>,
    pub(crate) identities: Vec<ModuleIdentityData>,

    pub(crate) objects: Vec<ObjectId>,
    pub(crate) types: Vec<TypeId>,
    pub(crate) notifications: Vec<NotificationId>,
    pub(crate) groups: Vec<GroupId>,
    pub(crate) compliances: Vec<ComplianceId>,
    pub(crate) capabilities: Vec<CapabilityId>,
    pub(crate) nodes: Vec<NodeId>,

    pub(crate) used_import_names: HashSet<String>,
    pub(crate) resolved_imports: HashMap<String, ModuleId>,
    pub(crate) import_resolutions: HashMap<String, ImportResolution>,
    pub(crate) semantic_spans: SemanticSpanIndex,

    pub(crate) objects_by_name: HashMap<String, ObjectId>,
    pub(crate) types_by_name: HashMap<String, TypeId>,
    pub(crate) notifications_by_name: HashMap<String, NotificationId>,
    pub(crate) groups_by_name: HashMap<String, GroupId>,
    pub(crate) compliances_by_name: HashMap<String, ComplianceId>,
    pub(crate) capabilities_by_name: HashMap<String, CapabilityId>,
    pub(crate) nodes_by_name: HashMap<String, NodeId>,
}

impl ModuleData {
    pub(crate) fn new(name: String) -> Self {
        Self {
            name,
            language: Language::Unknown,
            source_id: None,
            is_base: false,
            oid: None,
            organization: String::new(),
            contact_info: String::new(),
            description: String::new(),
            last_updated: String::new(),
            revisions: Vec::new(),
            imports: Vec::new(),
            identities: Vec::new(),
            objects: Vec::new(),
            types: Vec::new(),
            notifications: Vec::new(),
            groups: Vec::new(),
            compliances: Vec::new(),
            capabilities: Vec::new(),
            nodes: Vec::new(),
            used_import_names: HashSet::new(),
            resolved_imports: HashMap::new(),
            import_resolutions: HashMap::new(),
            semantic_spans: SemanticSpanIndex::default(),
            objects_by_name: HashMap::new(),
            types_by_name: HashMap::new(),
            notifications_by_name: HashMap::new(),
            groups_by_name: HashMap::new(),
            compliances_by_name: HashMap::new(),
            capabilities_by_name: HashMap::new(),
            nodes_by_name: HashMap::new(),
        }
    }

    /// Return the module name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Return the SMI language version.
    pub fn language(&self) -> Language {
        self.language
    }

    /// Return the compilation-local source identity, if this module came from source text.
    pub fn source_id(&self) -> Option<SourceId> {
        self.source_id
    }

    /// Return `true` if this is an SMI foundation module.
    ///
    /// See [`Module::is_base`](super::Module::is_base) for details.
    pub fn is_base(&self) -> bool {
        self.is_base
    }

    /// Return the module's MODULE-IDENTITY OID, if any.
    pub fn oid(&self) -> Option<&Oid> {
        self.oid.as_ref()
    }

    /// Return the ORGANIZATION clause text.
    pub fn organization(&self) -> &str {
        &self.organization
    }

    /// Return the CONTACT-INFO clause text.
    pub fn contact_info(&self) -> &str {
        &self.contact_info
    }

    /// Return the DESCRIPTION clause text.
    pub fn description(&self) -> &str {
        &self.description
    }

    /// Return the LAST-UPDATED timestamp string.
    pub fn last_updated(&self) -> &str {
        &self.last_updated
    }

    /// Return the REVISION entries.
    pub fn revisions(&self) -> &[Revision] {
        &self.revisions
    }

    /// Return the IMPORTS declarations.
    pub fn imports(&self) -> &[Import] {
        &self.imports
    }

    /// Return exact module-scoped OID identity declarations.
    ///
    /// Records retain aliases and collisions independently of the global OID
    /// tree's selected name, kind, metadata, and owning module.
    pub fn identities(&self) -> &[ModuleIdentityData] {
        &self.identities
    }

    /// Return the object ids defined by this module.
    pub fn objects(&self) -> &[ObjectId] {
        &self.objects
    }

    /// Return the type ids defined by this module.
    pub fn types(&self) -> &[TypeId] {
        &self.types
    }

    /// Return the notification ids defined by this module.
    pub fn notifications(&self) -> &[NotificationId] {
        &self.notifications
    }

    /// Return the group ids defined by this module.
    pub fn groups(&self) -> &[GroupId] {
        &self.groups
    }

    /// Return the compliance ids defined by this module.
    pub fn compliances(&self) -> &[ComplianceId] {
        &self.compliances
    }

    /// Return the capability ids defined by this module.
    pub fn capabilities(&self) -> &[CapabilityId] {
        &self.capabilities
    }

    /// Return the node ids defined by this module.
    pub fn nodes(&self) -> &[NodeId] {
        &self.nodes
    }

    /// Look up an object by name within this module.
    pub fn object_by_name(&self, name: &str) -> Option<ObjectId> {
        self.objects_by_name.get(name).copied()
    }

    /// Look up a type by name within this module.
    pub fn type_by_name(&self, name: &str) -> Option<TypeId> {
        self.types_by_name.get(name).copied()
    }

    /// Look up a notification by name within this module.
    pub fn notification_by_name(&self, name: &str) -> Option<NotificationId> {
        self.notifications_by_name.get(name).copied()
    }

    /// Look up a group by name within this module.
    pub fn group_by_name(&self, name: &str) -> Option<GroupId> {
        self.groups_by_name.get(name).copied()
    }

    /// Look up a compliance statement by name within this module.
    pub fn compliance_by_name(&self, name: &str) -> Option<ComplianceId> {
        self.compliances_by_name.get(name).copied()
    }

    /// Look up a capability statement by name within this module.
    pub fn capability_by_name(&self, name: &str) -> Option<CapabilityId> {
        self.capabilities_by_name.get(name).copied()
    }

    /// Look up a node by name within this module.
    pub fn node_by_name(&self, name: &str) -> Option<NodeId> {
        self.nodes_by_name.get(name).copied()
    }

    /// Look up a symbol by name. Priority: objects, types, notifications,
    /// groups, compliances, capabilities, then plain nodes.
    pub fn symbol(&self, name: &str) -> Option<Symbol> {
        if let Some(&id) = self.objects_by_name.get(name) {
            return Some(Symbol::Object(id));
        }
        if let Some(&id) = self.types_by_name.get(name) {
            return Some(Symbol::Type(id));
        }
        if let Some(&id) = self.notifications_by_name.get(name) {
            return Some(Symbol::Notification(id));
        }
        if let Some(&id) = self.groups_by_name.get(name) {
            return Some(Symbol::Group(id));
        }
        if let Some(&id) = self.compliances_by_name.get(name) {
            return Some(Symbol::Compliance(id));
        }
        if let Some(&id) = self.capabilities_by_name.get(name) {
            return Some(Symbol::Capability(id));
        }
        if let Some(&id) = self.nodes_by_name.get(name) {
            return Some(Symbol::Node(id));
        }
        None
    }

    /// Look up every distinct definition kind with this name in the module.
    ///
    /// An OID entity is returned instead of its attached plain node. A type
    /// and an OID entity with the same name are both retained.
    pub fn symbols(&self, name: &str) -> Vec<Symbol> {
        let mut symbols = Vec::new();
        if let Some(&id) = self.objects_by_name.get(name) {
            symbols.push(Symbol::Object(id));
        }
        if let Some(&id) = self.notifications_by_name.get(name) {
            symbols.push(Symbol::Notification(id));
        }
        if let Some(&id) = self.groups_by_name.get(name) {
            symbols.push(Symbol::Group(id));
        }
        if let Some(&id) = self.compliances_by_name.get(name) {
            symbols.push(Symbol::Compliance(id));
        }
        if let Some(&id) = self.capabilities_by_name.get(name) {
            symbols.push(Symbol::Capability(id));
        }
        if symbols.is_empty()
            && let Some(&id) = self.nodes_by_name.get(name)
        {
            symbols.push(Symbol::Node(id));
        }
        if let Some(&id) = self.types_by_name.get(name) {
            symbols.push(Symbol::Type(id));
        }
        symbols
    }

    /// Return `true` if this module defines a symbol with the given name.
    pub fn defines_symbol(&self, name: &str) -> bool {
        self.symbol(name).is_some()
    }

    /// Return `true` if this module imports a symbol with the given name.
    pub fn imports_symbol(&self, name: &str) -> bool {
        self.imports
            .iter()
            .any(|imp| imp.symbols.iter().any(|s| s.name == name))
    }

    /// Return `true` if the named import was actually used during resolution.
    pub fn is_import_used(&self, name: &str) -> bool {
        self.used_import_names.contains(name)
    }

    /// Return the resolved source module for an imported name.
    pub fn import_source(&self, name: &str) -> Option<ModuleId> {
        self.resolved_imports.get(name).copied()
    }

    /// Return retained pre-collapse resolution provenance for an imported symbol.
    pub fn import_resolution(&self, name: &str) -> Option<&ImportResolution> {
        self.import_resolutions.get(name)
    }

    // Builder methods used during resolution.

    pub(crate) fn add_object(&mut self, name: impl Into<String>, id: ObjectId) {
        self.objects.push(id);
        self.objects_by_name.entry(name.into()).or_insert(id);
    }

    pub(crate) fn add_type(&mut self, name: impl Into<String>, id: TypeId) {
        self.types.push(id);
        self.types_by_name.entry(name.into()).or_insert(id);
    }

    pub(crate) fn add_notification(&mut self, name: impl Into<String>, id: NotificationId) {
        self.notifications.push(id);
        self.notifications_by_name.entry(name.into()).or_insert(id);
    }

    pub(crate) fn add_group(&mut self, name: impl Into<String>, id: GroupId) {
        self.groups.push(id);
        self.groups_by_name.entry(name.into()).or_insert(id);
    }

    pub(crate) fn add_compliance(&mut self, name: impl Into<String>, id: ComplianceId) {
        self.compliances.push(id);
        self.compliances_by_name.entry(name.into()).or_insert(id);
    }

    pub(crate) fn add_capability(&mut self, name: impl Into<String>, id: CapabilityId) {
        self.capabilities.push(id);
        self.capabilities_by_name.entry(name.into()).or_insert(id);
    }

    pub(crate) fn add_node(&mut self, name: impl Into<String>, id: NodeId) {
        self.nodes.push(id);
        self.nodes_by_name.entry(name.into()).or_insert(id);
    }

    pub(crate) fn add_identity(&mut self, identity: ModuleIdentityData) {
        self.identities.push(identity);
    }

    /// Yield all definitions in this module as [`Symbol`] values.
    ///
    /// Entity-backed definitions (objects, types, notifications, groups,
    /// compliances, capabilities) come first. Plain nodes (not attached to
    /// any entity) are yielded last.
    pub fn definitions(&self) -> impl Iterator<Item = Symbol> + '_ {
        // Covered node IDs: nodes whose names also appear in an entity map.
        let covered_node_ids: HashSet<NodeId> = self
            .nodes_by_name
            .iter()
            .filter_map(|(name, &id)| {
                (self.objects_by_name.contains_key(name)
                    || self.notifications_by_name.contains_key(name)
                    || self.groups_by_name.contains_key(name)
                    || self.compliances_by_name.contains_key(name)
                    || self.capabilities_by_name.contains_key(name))
                .then_some(id)
            })
            .collect();

        self.objects
            .iter()
            .map(|&id| Symbol::Object(id))
            .chain(self.types.iter().map(|&id| Symbol::Type(id)))
            .chain(
                self.notifications
                    .iter()
                    .map(|&id| Symbol::Notification(id)),
            )
            .chain(self.groups.iter().map(|&id| Symbol::Group(id)))
            .chain(self.compliances.iter().map(|&id| Symbol::Compliance(id)))
            .chain(self.capabilities.iter().map(|&id| Symbol::Capability(id)))
            .chain(
                self.nodes
                    .iter()
                    .filter(move |id| !covered_node_ids.contains(id))
                    .map(|&id| Symbol::Node(id)),
            )
    }
}

impl std::fmt::Debug for ModuleData {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ModuleData")
            .field("name", &self.name)
            .field("language", &self.language)
            .field("is_base", &self.is_base)
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn definitions_include_only_plain_nodes() {
        let mut module = ModuleData::new("TEST-MIB".to_string());

        let object_id = ObjectId::new(0);
        let object_node = NodeId::new(10);
        let plain_node = NodeId::new(11);

        module.add_object("ifIndex", object_id);
        module.add_node("ifIndex", object_node);
        module.add_node("internet", plain_node);

        let defs: Vec<_> = module.definitions().collect();

        assert_eq!(defs.len(), 2);
        assert_eq!(defs[0], Symbol::Object(object_id));
        assert_eq!(defs[1], Symbol::Node(plain_node));
    }

    #[test]
    fn definitions_keep_plain_nodes_on_type_name_collision() {
        let mut module = ModuleData::new("TEST-MIB".to_string());

        let type_id = TypeId::new(0);
        let plain_node = NodeId::new(11);

        module.add_type("DisplayString", type_id);
        module.add_node("DisplayString", plain_node);

        let defs: Vec<_> = module.definitions().collect();

        assert_eq!(defs.len(), 2);
        assert_eq!(defs[0], Symbol::Type(type_id));
        assert_eq!(defs[1], Symbol::Node(plain_node));
    }
}