Skip to main content

nom_kconfig/attribute/expression/
atom.rs

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