Skip to main content

px_wsdom_ts_parse/parser/
generic.rs

1use winnow::{
2    combinator::{delimited, opt, preceded, separated1},
3    PResult, Parser,
4};
5
6use super::{
7    ts_type::TsType,
8    util::{token, token_word, word1, Parsable},
9};
10
11#[derive(Debug, Clone, PartialEq, Eq, Default)]
12pub struct GenericsDeclaration<'a> {
13    pub args: Vec<GenericsDeclarationArg<'a>>,
14}
15
16impl<'a> Parsable<'a> for GenericsDeclaration<'a> {
17    fn parse(input: &mut &'a str) -> PResult<Self> {
18        delimited(
19            token('<'),
20            separated1(GenericsDeclarationArg::parse, token(',')),
21            token('>'),
22        )
23        .parse_next(input)
24        .map(|args| Self { args })
25    }
26}
27
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct GenericsDeclarationArg<'a> {
30    pub name: &'a str,
31    pub extends: Option<TsType<'a>>,
32    pub default: Option<TsType<'a>>,
33}
34impl<'a> Parsable<'a> for GenericsDeclarationArg<'a> {
35    fn parse(input: &mut &'a str) -> PResult<Self> {
36        (
37            word1,
38            opt(preceded(token_word("extends"), TsType::parse)),
39            opt(preceded(token('='), TsType::parse)),
40        )
41            .parse_next(input)
42            .map(|(name, extends, default)| Self {
43                name,
44                extends,
45                default,
46            })
47    }
48}
49#[derive(Debug, Clone, PartialEq, Eq, Default)]
50pub struct GenericArgs<'a> {
51    pub args: Vec<TsType<'a>>,
52}
53
54impl<'a> Parsable<'a> for GenericArgs<'a> {
55    fn parse(input: &mut &'a str) -> PResult<Self> {
56        delimited(
57            token('<'),
58            separated1(TsType::parse, token(',')),
59            token('>'),
60        )
61        .map(|args| Self { args })
62        .parse_next(input)
63    }
64}