From 51100a542ce7d0bdfb1b1971b22f2b5cf875a49d Mon Sep 17 00:00:00 2001 From: Ning Sun Date: Wed, 16 Oct 2024 16:01:56 -0700 Subject: [PATCH 1/8] feat: serialize AST to json --- Cargo.toml | 8 +++++++ src/label/matcher.rs | 19 +++++++++++++++++ src/label/mod.rs | 1 + src/parser/ast.rs | 30 +++++++++++++++++++++++++++ src/parser/function.rs | 2 ++ src/parser/token.rs | 1 + src/parser/value.rs | 1 + tests/ser.rs | 47 ++++++++++++++++++++++++++++++++++++++++++ 8 files changed, 109 insertions(+) create mode 100644 tests/ser.rs diff --git a/Cargo.toml b/Cargo.toml index 3d11101..52a23e3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,6 +31,14 @@ lazy_static = "1.4.0" lrlex = "0.13.5" lrpar = "0.13.5" regex = "1" +serde = { version = "1", optional = true } + +[features] +default = [] +ser = ["serde"] + +[dev-dependencies] +serde_json = "1" [build-dependencies] cfgrammar = "0.13.5" diff --git a/src/label/matcher.rs b/src/label/matcher.rs index 2e009f4..0f19f54 100644 --- a/src/label/matcher.rs +++ b/src/label/matcher.rs @@ -24,6 +24,7 @@ use crate::util::join_vector; pub enum MatchOp { Equal, NotEqual, + // TODO: do we need regex here? Re(Regex), NotRe(Regex), } @@ -64,9 +65,26 @@ impl Hash for MatchOp { } } +#[cfg(feature = "ser")] +impl serde::Serialize for MatchOp { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + match self { + MatchOp::Equal => serializer.serialize_str("="), + MatchOp::NotEqual => serializer.serialize_str("=~"), + MatchOp::Re(_reg) => serializer.serialize_str("=~"), + MatchOp::NotRe(_reg) => serializer.serialize_str("!~"), + } + } +} + // Matcher models the matching of a label. #[derive(Debug, Clone, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "ser", derive(serde::Serialize))] pub struct Matcher { + #[cfg_attr(feature = "ser", serde(rename = "type"))] pub op: MatchOp, pub name: String, pub value: String, @@ -183,6 +201,7 @@ fn try_escape_for_repeat_re(re: &str) -> String { } #[derive(Debug, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "ser", derive(serde::Serialize))] pub struct Matchers { pub matchers: Vec, pub or_matchers: Vec>, diff --git a/src/label/mod.rs b/src/label/mod.rs index 1bba6d2..96ea999 100644 --- a/src/label/mod.rs +++ b/src/label/mod.rs @@ -32,6 +32,7 @@ pub const INSTANCE_NAME: &str = "instance"; pub type Label = String; #[derive(Debug, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "ser", derive(serde::Serialize))] pub struct Labels { pub labels: Vec