liberty-db 0.5.0

`liberty` data structre
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
//!
//! `liberty` data structre ast
//!

mod fmt;
pub mod parser;
use crate::ArcStr;
use core::{
  fmt::{Debug, Display, Write},
  num::{ParseFloatError, ParseIntError},
  str::FromStr,
};
pub use fmt::{
  CodeFormatter, DefaultCodeFormatter, DefaultIndentation, Indentation,
  TestCodeFormatter, TestIndentation,
};
use itertools::Itertools;
use nom::{error::Error, IResult};
use ordered_float::ParseNotNanError;
/// Wrapper for simple attribute
pub type SimpleWrapper = ArcStr;
/// Wrapper for complex attribute
pub type ComplexWrapper = Vec<Vec<ArcStr>>;
/// Wrapper for group attribute
///
/// ``` text
/// group_name ( title ) {
///   attri_key1 xxx
///   attri_key2 xxx
/// }
/// ```
#[derive(Debug, Clone, Default)]
#[derive(serde::Serialize, serde::Deserialize)]
pub struct GroupWrapper {
  /// title
  pub title: Vec<ArcStr>,
  /// `attr_list`
  pub attr_list: AttributeList,
}
/// type for Undefined `AttributeList`
pub type AttributeList = Vec<(ArcStr, AttriValue)>;
/// `AttriValue` for `undefined_attribute/serialization`
#[derive(Debug, Clone)]
#[derive(serde::Serialize, serde::Deserialize)]
pub enum AttriValue {
  /// `Simple`
  Simple(SimpleWrapper),
  /// `Complex`
  Complex(ComplexWrapper),
  /// `Group`
  Group(GroupWrapper),
}

/// Error for `LinkedGroup`
#[derive(Debug)]
#[derive(thiserror::Error)]
pub enum LinkError {
  /// `Not Find`
  #[error("Can not find in hashset!")]
  NotFind,
  /// `BorrowError`
  #[error("{0}")]
  BorrowError(core::cell::BorrowError),
}

impl PartialEq for LinkError {
  #[allow(clippy::match_like_matches_macro)]
  #[inline]
  fn eq(&self, other: &Self) -> bool {
    match (self, other) {
      (Self::NotFind, Self::NotFind) | (Self::BorrowError(_), Self::BorrowError(_)) => {
        true
      }
      _ => false,
    }
  }
}

// /// Reference: https://rustcc.cn/article?id=ac75148b-6eb0-4249-b36d-0a14875b736e
// #[derive(Debug, Clone)]
// #[derive(serde::Serialize, serde::Deserialize)]
// pub struct LinkedGroup<LinkTo>
// where
//   LinkTo: HashedGroup + GroupAttri,
// {
//   id: Arc<<LinkTo as HashedGroup>::Id>,
//   from: Arc<RefCell<GroupMap<LinkTo>>>,
// }

// impl<LinkTo: HashedGroup + GroupAttri> LinkedGroup<LinkTo> {
//   pub fn new(
//     id: Arc<<LinkTo as HashedGroup>::Id>,
//     from: &Arc<RefCell<GroupMap<LinkTo>>>,
//   ) -> Self {
//     Self { id: id.clone(), from: from.clone() }
//   }
//   pub fn get_linked<F>(&self, f: F)
//   where
//     F: FnOnce(Result<&LinkTo, LinkError>),
//   {
//     match self.from.as_ref().try_borrow() {
//       Ok(set) => match set.get(&self.id) {
//         Some(linked) => f(Ok(linked)),
//         None => f(Err(LinkError::NotFind)),
//       },
//       Err(err) => f(Err(LinkError::BorrowError(err))),
//     }
//   }
// }

type SimpleParseErr<'a, T> =
  IResult<&'a str, Result<T, (<T as FromStr>::Err, AttriValue)>, Error<&'a str>>;

/// Simple Attribute in Liberty
pub trait SimpleAttri: Sized + Display + FromStr {
  /// basic `parser`
  #[inline]
  fn parse(s: &str) -> Result<Self, <Self as FromStr>::Err> {
    FromStr::from_str(s)
  }
  /// `nom_parse`, auto implement
  #[inline]
  fn nom_parse<'a>(i: &'a str, line_num: &mut usize) -> SimpleParseErr<'a, Self> {
    let (input, simple) = parser::simple(i, line_num)?;
    match Self::parse(simple) {
      Ok(s) => Ok((input, Ok(s))),
      Err(e) => Ok((input, Err((e, AttriValue::Simple(ArcStr::from(simple)))))),
    }
  }
  // TODO: efficent?
  /// `to_wrapper`, auto implement
  #[inline]
  fn to_wrapper(&self) -> SimpleWrapper {
    self.to_string().into()
  }
  /// `fmt_liberty`
  #[inline]
  fn fmt_liberty<T: Write, I: Indentation>(
    &self,
    key: &str,
    f: &mut CodeFormatter<'_, T, I>,
  ) -> core::fmt::Result {
    <SimpleWrapper as Format>::liberty(&self.to_wrapper(), key, f)
  }
}

/// `ComplexParseError`
#[derive(thiserror::Error, Debug)]
pub enum ComplexParseError {
  /// `ParseFloatError`
  #[error("{0}")]
  Float(ParseNotNanError<ParseFloatError>),
  /// `ParseIntError`
  #[error("{0}")]
  Int(ParseIntError),
  /// title length mismatch
  #[error("title length mismatch")]
  LengthDismatch,
  /// other error
  #[error("other")]
  Other,
  /// unsurpport word
  #[error("unsurpport word")]
  UnsupportedWord,
}

/// `NameAttri`
pub trait NameAttri: Sized + Clone {
  /// basic parser
  fn parse(v: Vec<ArcStr>) -> Result<Self, IdError>;
  /// name `to_vec`
  fn to_vec(self) -> Vec<ArcStr>;
}

/// Complex Attribute in Liberty
pub trait ComplexAttri: Sized {
  /// basic `parser`
  fn parse(v: &[&str]) -> Result<Self, ComplexParseError>;
  /// `to_wrapper`
  fn to_wrapper(&self) -> ComplexWrapper;
  /// `nom_parse`, auto implement
  #[inline]
  fn nom_parse<'a>(
    i: &'a str,
    line_num: &mut usize,
  ) -> IResult<&'a str, Result<Self, (ComplexParseError, AttriValue)>, Error<&'a str>> {
    let (input, complex) = parser::complex(i, line_num)?;
    match Self::parse(&complex) {
      Ok(s) => Ok((input, Ok(s))),
      Err(e) => Ok((
        input,
        Err((
          e,
          AttriValue::Complex(vec![complex.into_iter().map(ArcStr::from).collect()]),
        )),
      )),
    }
  }
  /// `fmt_liberty`
  #[inline]
  fn fmt_liberty<T: Write, I: Indentation>(
    &self,
    key: &str,
    f: &mut CodeFormatter<'_, T, I>,
  ) -> core::fmt::Result {
    <ComplexWrapper as Format>::liberty(&self.to_wrapper(), key, f)
  }
}

/// `GroupComments`
pub type GroupComments<T> = <T as GroupAttri>::Comments;

/// `AttriComment`
pub type AttriComment = Vec<ArcStr>;
/// Group Functions
pub trait GroupFn {
  /// `post_process` call back
  #[inline]
  fn post_process(&mut self) {}
}
/// `GroupAttri`
pub trait GroupAttri: Sized {
  /// group Name
  type Name;
  /// group Comments
  type Comments;
  /// return name
  fn name(&self) -> Self::Name;
  /// get name
  fn set_name(&mut self, name: Self::Name);
  /// `nom_parse`, will be implemented by macros
  fn nom_parse<'a>(
    i: &'a str,
    line_num: &mut usize,
  ) -> IResult<&'a str, Result<Self, IdError>, Error<&'a str>>;
  /// `fmt_liberty`
  fn fmt_liberty<T: Write, I: Indentation>(
    &self,
    key: &str,
    f: &mut CodeFormatter<'_, T, I>,
  ) -> core::fmt::Result;
}

/// Error for parser Group Index
#[derive(Debug)]
#[derive(thiserror::Error)]
pub enum IdError {
  /// TitleLenMismatch(want,got,title)
  #[error("title length dismatch (want={0},got={1}), title={2:?}")]
  LengthDismatch(usize, usize, Vec<ArcStr>),
  /// replace same id
  #[error("replace same id")]
  RepeatIdx,
  /// replace same attribute
  #[error("replace same attribute")]
  RepeatAttri,
  /// Int Error
  #[error("{0}")]
  Int(ParseIntError),
  /// something else
  #[error("{0}")]
  Other(String),
}

/// If more than one `#[liberty(name)]`,
/// need to impl `NamedGroup` manually
pub trait NamedGroup: GroupAttri {
  /// parse name from Vec<ArcStr>
  fn parse(v: Vec<ArcStr>) -> Result<Self::Name, IdError>;
  /// name to Vec<ArcStr>
  fn name2vec(name: Self::Name) -> Vec<ArcStr>;
  /// `fmt_liberty`
  #[inline]
  fn fmt_liberty<T: Write, I: Indentation>(
    &self,
    f: &mut CodeFormatter<'_, T, I>,
  ) -> core::fmt::Result {
    write!(
      f,
      "{}",
      Self::name2vec(self.name())
        .into_iter()
        .map(|s| if is_word(&s) { s } else { format!("\"{s}\"").into() })
        .join(", ")
    )
  }
}

fn display_nom_error(e: &nom::Err<Error<&str>>) -> ArcStr {
  match e {
    nom::Err::Incomplete(_) => e.to_string(),
    nom::Err::Failure(_e) | nom::Err::Error(_e) => format!(
      "type[{}] at[{}]",
      _e.code.description(),
      _e.input.lines().next().unwrap_or("")
    ),
  }
  .into()
}
/// Error for parser
#[derive(Debug, thiserror::Error)]
pub enum ParserError<'a> {
  /// TitleLenMismatch(want,got,title)
  #[error("Line#{0}, {1}")]
  IdError(usize, IdError),
  /// replace same id
  #[error("Line#{0}, {}", display_nom_error(.1))]
  NomError(usize, nom::Err<Error<&'a str>>),
  /// something else
  #[error("Line#{0}, {1}")]
  Other(usize, String),
}

#[allow(unused)]
pub(crate) fn test_parse_group<G: GroupAttri + Debug>(s: &str) -> (G, String, usize) {
  let mut n = 1;
  match G::nom_parse(s, &mut n) {
    Ok((_, Ok(group))) => {
      println!("{group:#?}");
      println!("{n}");
      let mut output = String::new();
      let mut f = TestCodeFormatter::new(&mut output);
      if let Err(e) = GroupAttri::fmt_liberty(&group, core::any::type_name::<G>(), &mut f)
      {
        panic!("{e}");
      }
      println!("{output}");
      (group, output, n)
    }
    Ok((_, Err(e))) => panic!("{e:#?}"),
    Err(e) => panic!("{e:#?}"),
  }
}
/// For basic formatter
pub trait Format {
  /// `.lib` format
  fn liberty<T: Write, I: Indentation>(
    &self,
    key: &str,
    f: &mut CodeFormatter<'_, T, I>,
  ) -> core::fmt::Result;
  /// `.db` format
  #[inline]
  fn db<T: Write, I: Indentation>(
    &self,
    key: &str,
    f: &mut CodeFormatter<'_, T, I>,
  ) -> core::fmt::Result {
    _ = key;
    _ = f;
    todo!()
  }
  /// `.json` format
  #[inline]
  fn json<T: Write, I: Indentation>(
    &self,
    key: &str,
    f: &mut CodeFormatter<'_, T, I>,
  ) -> core::fmt::Result {
    _ = key;
    _ = f;
    todo!()
  }
}
pub(crate) fn is_word(s: &ArcStr) -> bool {
  !s.is_empty() && s.chars().all(parser::char_in_word)
}
impl Format for AttriComment {
  #[inline]
  fn liberty<T: Write, I: Indentation>(
    &self,
    _: &str,
    f: &mut CodeFormatter<'_, T, I>,
  ) -> core::fmt::Result {
    if self.is_empty() {
      Ok(())
    } else {
      // TODO: NOT use replace
      let indent = f.indentation();
      write!(
        f,
        "\n{indent}/* {} */",
        self.join("\n").replace('\n', format!("\n{indent}* ").as_str())
      )
    }
  }
}

impl Format for SimpleWrapper {
  #[inline]
  fn liberty<T: Write, I: Indentation>(
    &self,
    key: &str,
    f: &mut CodeFormatter<'_, T, I>,
  ) -> core::fmt::Result {
    if self.is_empty() {
      Ok(())
    } else if is_word(self) {
      write!(f, "\n{}{key} : {self};", f.indentation())
    } else {
      write!(f, "\n{}{key} : \"{self}\";", f.indentation())
    }
  }
}

impl Format for ComplexWrapper {
  #[allow(clippy::indexing_slicing)]
  #[inline]
  fn liberty<T: Write, I: Indentation>(
    &self,
    key: &str,
    f: &mut CodeFormatter<'_, T, I>,
  ) -> core::fmt::Result {
    if self.is_empty() || (self.len() == 1 && self[0].is_empty()) {
      return Ok(());
    };
    let indent1 = f.indentation();
    if self[0].iter().all(is_word) {
      write!(f, "\n{indent1}{key} ({}", self[0].join(", "))?;
    } else {
      write!(f, "\n{indent1}{key} (\"{}\"", self[0].join(", "))?;
    }
    f.indent(1);
    let indent2 = f.indentation();
    for v in self.iter().skip(1) {
      if v.iter().all(is_word) {
        write!(f, ", \\\n{indent2}{}", v.join(", "))?;
      } else {
        write!(f, ", \\\n{indent2}\"{}\"", v.join(", "))?;
      }
    }
    f.dedent(1);
    write!(f, ");")
  }
}

#[inline]
pub(crate) fn liberty_attr_list<T: Write, I: Indentation>(
  attr_list: &AttributeList,
  f: &mut CodeFormatter<'_, T, I>,
) -> core::fmt::Result {
  for (key, attr) in attr_list {
    match attr {
      AttriValue::Simple(a) => Format::liberty(a, key, f)?,
      AttriValue::Complex(a) => Format::liberty(a, key, f)?,
      AttriValue::Group(a) => Format::liberty(a, key, f)?,
    }
  }
  Ok(())
}

impl Format for GroupWrapper {
  #[inline]
  fn liberty<T: Write, I: Indentation>(
    &self,
    key: &str,
    f: &mut CodeFormatter<'_, T, I>,
  ) -> core::fmt::Result {
    let indent = f.indentation();
    write!(
      f,
      "\n{indent}{key} ({}) {{",
      self
        .title
        .iter()
        .map(|s| if is_word(s) { s.clone() } else { format!("\"{s}\"").into() })
        .join(",")
    )?;
    f.indent(1);
    liberty_attr_list(&self.attr_list, f)?;
    f.dedent(1);
    write!(f, "\n{indent}}}")
  }
}