From 94a3489a39b268bd15e50f56ca9a87f3562fa285 Mon Sep 17 00:00:00 2001 From: peefy Date: Tue, 23 Jan 2024 20:26:50 +0800 Subject: [PATCH] feat: ignore ast id serialize when flag is false Signed-off-by: peefy --- kclvm/ast/src/ast.rs | 37 +++++++++++++++++++++++-------------- 1 file changed, 23 insertions(+), 14 deletions(-) diff --git a/kclvm/ast/src/ast.rs b/kclvm/ast/src/ast.rs index c14220979..79a6971de 100644 --- a/kclvm/ast/src/ast.rs +++ b/kclvm/ast/src/ast.rs @@ -33,7 +33,7 @@ //! in the compiler and regenerate the walker code. //! :copyright: Copyright The KCL Authors. All rights reserved. -use serde::{Deserialize, Serialize, Serializer}; +use serde::{ser::SerializeStruct, Deserialize, Serialize, Serializer}; use std::collections::HashMap; use compiler_base_span::{Loc, Span}; @@ -112,7 +112,7 @@ impl ToString for AstIndex { /// that all AST nodes need to contain. /// In fact, column and end_column are the counts of character, /// For example, `\t` is counted as 1 character, so it is recorded as 1 here, but generally col is 4. -#[derive(Serialize, Deserialize, Clone, PartialEq)] +#[derive(Deserialize, Clone, PartialEq)] pub struct Node { #[serde(serialize_with = "serialize_id", skip_deserializing, default)] pub id: AstIndex, @@ -124,24 +124,33 @@ pub struct Node { pub end_column: u64, } +impl Serialize for Node { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let should_serialize_id = SHOULD_SERIALIZE_ID.with(|f| *f.borrow()); + let mut state = + serializer.serialize_struct("Node", if should_serialize_id { 7 } else { 6 })?; + if should_serialize_id { + state.serialize_field("id", &self.id)?; + } + state.serialize_field("node", &self.node)?; + state.serialize_field("filename", &self.filename)?; + state.serialize_field("line", &self.line)?; + state.serialize_field("column", &self.column)?; + state.serialize_field("end_line", &self.end_line)?; + state.serialize_field("end_column", &self.end_column)?; + state.end() + } +} + pub fn set_should_serialize_id(value: bool) { SHOULD_SERIALIZE_ID.with(|f| { *f.borrow_mut() = value; }); } -fn serialize_id(id: &AstIndex, serializer: S) -> Result -where - S: Serializer, -{ - let should_serialize_id = SHOULD_SERIALIZE_ID.with(|f| *f.borrow()); - if should_serialize_id { - id.serialize(serializer) - } else { - serializer.serialize_none() - } -} - impl Debug for Node { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Node")