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
use std::ops::Deref;

use nom::{error::Error, Err};
use nom_locate::LocatedSpan;

mod parser;

type Span<'a> = LocatedSpan<&'a str>;

#[derive(Debug)]
pub enum Sundry<'a> {
    Comment(Span<'a>),
    Empty(Span<'a>),
    EOF,
}

#[derive(Debug, PartialEq, Eq)]
pub enum Identifier<'a> {
    Raw(&'a str),
    Interpreted(String),
}

impl Deref for Identifier<'_> {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        match self {
            Self::Raw(s) => s,
            Self::Interpreted(s) => s.as_str(),
        }
    }
}

#[derive(Debug, PartialEq, Eq)]
pub enum RetractSpec<'a> {
    Version(Identifier<'a>),
    Range((Identifier<'a>, Identifier<'a>)),
}

#[derive(Debug, PartialEq, Eq)]
pub struct ReplaceSpec<'a> {
    pub module_path: &'a str,
    pub version: Option<Identifier<'a>>,
    pub replacement: Replacement<'a>,
}

#[derive(Debug, PartialEq, Eq)]
pub enum Replacement<'a> {
    FilePath(Identifier<'a>),
    Module((&'a str, Identifier<'a>)),
}

// comments on directive includes preceding-line comments and same-line comment
#[derive(Debug, PartialEq, Eq)]
pub enum Directive<'a> {
    Module {
        module_path: &'a str,
    },
    Go {
        version: Identifier<'a>,
    },
    Require {
        specs: Vec<Context<'a, (&'a str, Identifier<'a>)>>,
    },
    Toolchain {
        name: Identifier<'a>,
    },
    Godebug {
        specs: Vec<Context<'a, (&'a str, &'a str)>>,
    },
    Replace {
        specs: Vec<Context<'a, ReplaceSpec<'a>>>,
    },
    Exclude {
        specs: Vec<Context<'a, (&'a str, Identifier<'a>)>>,
    },
    Retract {
        specs: Vec<Context<'a, RetractSpec<'a>>>,
    },
}

#[derive(Debug, Default, PartialEq, Eq)]
pub struct Location {
    pub line: u32,
    pub offset: usize,
}

pub type Range = (Location, Location);

#[derive(Debug, PartialEq, Eq)]
pub struct Context<'a, T: 'a> {
    pub range: Range,
    pub comments: Vec<&'a str>,
    pub value: T,
}

pub type GoMod<'a> = Vec<Context<'a, Directive<'a>>>;

pub fn parse_gomod(text: &str) -> Result<GoMod, Err<Error<Span>>> {
    let (_, ret) = parser::parse_gomod(Span::new(text))?;
    Ok(ret)
}