Skip to main content

nom_kconfig/attribute/expression/
atom.rs

1use crate::attribute::expression::parse_compare;
2use crate::attribute::r#macro::{parse_macro, Macro};
3use crate::attribute::{parse_expression, CompareExpression, Expression};
4use crate::symbol::parse_symbol;
5use crate::util::wsi;
6use crate::{KconfigInput, Symbol};
7use nom::{
8    branch::alt, bytes::complete::tag, combinator::map, sequence::delimited, IResult, Parser,
9};
10#[cfg(feature = "deserialize")]
11use serde::Deserialize;
12#[cfg(feature = "serialize")]
13use serde::Serialize;
14#[cfg(feature = "display")]
15use std::fmt::Display;
16
17#[derive(Debug, PartialEq, Clone)]
18#[cfg_attr(feature = "hash", derive(Hash))]
19#[cfg_attr(feature = "serialize", derive(Serialize))]
20#[cfg_attr(feature = "deserialize", derive(Deserialize))]
21pub enum Atom {
22    Symbol(Symbol),
23    Compare(CompareExpression),
24    Macro(Macro),
25    Parenthesis(Box<Expression>),
26}
27
28#[cfg(feature = "display")]
29impl Display for Atom {
30    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
31        match self {
32            Atom::Symbol(s) => write!(f, "{}", s),
33            Atom::Compare(c) => write!(f, "{}", c),
34            Atom::Macro(m) => write!(f, "{}", m),
35            Atom::Parenthesis(d) => write!(f, "({})", d),
36        }
37    }
38}
39
40pub fn parse_atom(input: KconfigInput) -> IResult<KconfigInput, Atom> {
41    alt((
42        wsi(parse_compare),
43        map(parse_macro, Atom::Macro),
44        map(
45            delimited(wsi(tag("(")), parse_expression, wsi(tag(")"))),
46            |expr: Expression| Atom::Parenthesis(Box::new(expr)),
47        ),
48        map(parse_symbol, Atom::Symbol), // needed to parse negative numbers, see test_parse_expression_number() in expression_test.rs
49    ))
50    .parse(input)
51}