summaryrefslogtreecommitdiffstats
path: root/third_party/rust/naga/src/front/glsl/preprocess.rs
blob: 6050594719d48e5b9aa28816fd76a1ad6708bb91 (plain)
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
use crate::FastHashMap;
use thiserror::Error;

#[derive(Clone, Debug, Error)]
#[cfg_attr(test, derive(PartialEq))]
pub enum Error {
    #[error("unmatched else")]
    UnmatchedElse,
    #[error("unmatched endif")]
    UnmatchedEndif,
    #[error("missing macro name")]
    MissingMacro,
}

#[derive(Clone, Debug)]
pub struct IfState {
    true_branch: bool,
    else_seen: bool,
}

#[derive(Clone, Debug)]
pub struct LinePreProcessor {
    pub defines: FastHashMap<String, String>,
    if_stack: Vec<IfState>,
    inside_comment: bool,
    in_preprocess: bool,
}

impl LinePreProcessor {
    pub fn new() -> Self {
        LinePreProcessor {
            defines: FastHashMap::default(),
            if_stack: vec![],
            inside_comment: false,
            in_preprocess: false,
        }
    }

    fn subst_defines(&self, input: &str) -> String {
        //TODO: don't subst in commments, strings literals?
        self.defines
            .iter()
            .fold(input.to_string(), |acc, (k, v)| acc.replace(k, v))
    }

    pub fn process_line(&mut self, line: &str) -> Result<Option<String>, Error> {
        let mut skip = !self.if_stack.last().map(|i| i.true_branch).unwrap_or(true);
        let mut inside_comment = self.inside_comment;
        let mut in_preprocess = inside_comment && self.in_preprocess;
        // single-line comment
        let mut processed = line;
        if let Some(pos) = line.find("//") {
            processed = line.split_at(pos).0;
        }
        // multi-line comment
        let mut processed_string: String;
        loop {
            if inside_comment {
                if let Some(pos) = processed.find("*/") {
                    processed = processed.split_at(pos + 2).1;
                    inside_comment = false;
                    self.inside_comment = false;
                    continue;
                }
            } else if let Some(pos) = processed.find("/*") {
                if let Some(end_pos) = processed[pos + 2..].find("*/") {
                    // comment ends during this line
                    processed_string = processed.to_string();
                    processed_string.replace_range(pos..pos + end_pos + 4, "");
                    processed = &processed_string;
                } else {
                    processed = processed.split_at(pos).0;
                    inside_comment = true;
                }
                continue;
            }
            break;
        }
        // strip leading whitespace
        processed = processed.trim_start();
        if processed.starts_with('#') && !self.inside_comment {
            let mut iter = processed[1..]
                .trim_start()
                .splitn(2, |c: char| c.is_whitespace());
            if let Some(directive) = iter.next() {
                skip = true;
                in_preprocess = true;
                match directive {
                    "version" => {
                        skip = false;
                    }
                    "define" => {
                        let rest = iter.next().ok_or(Error::MissingMacro)?;
                        let pos = rest
                            .find(|c: char| !c.is_ascii_alphanumeric() && c != '_' && c != '(')
                            .unwrap_or_else(|| rest.len());
                        let (key, mut value) = rest.split_at(pos);
                        value = value.trim();
                        self.defines.insert(key.into(), self.subst_defines(value));
                    }
                    "undef" => {
                        let rest = iter.next().ok_or(Error::MissingMacro)?;
                        let key = rest.trim();
                        self.defines.remove(key);
                    }
                    "ifdef" => {
                        let rest = iter.next().ok_or(Error::MissingMacro)?;
                        let key = rest.trim();
                        self.if_stack.push(IfState {
                            true_branch: self.defines.contains_key(key),
                            else_seen: false,
                        });
                    }
                    "ifndef" => {
                        let rest = iter.next().ok_or(Error::MissingMacro)?;
                        let key = rest.trim();
                        self.if_stack.push(IfState {
                            true_branch: !self.defines.contains_key(key),
                            else_seen: false,
                        });
                    }
                    "else" => {
                        let if_state = self.if_stack.last_mut().ok_or(Error::UnmatchedElse)?;
                        if !if_state.else_seen {
                            // this is first else
                            if_state.true_branch = !if_state.true_branch;
                            if_state.else_seen = true;
                        } else {
                            return Err(Error::UnmatchedElse);
                        }
                    }
                    "endif" => {
                        self.if_stack.pop().ok_or(Error::UnmatchedEndif)?;
                    }
                    _ => {}
                }
            }
        }
        let res = if !skip && !self.inside_comment {
            Ok(Some(self.subst_defines(&line)))
        } else {
            Ok(if in_preprocess && !self.in_preprocess {
                Some("".to_string())
            } else {
                None
            })
        };
        self.in_preprocess = in_preprocess || skip;
        self.inside_comment = inside_comment;
        res
    }
}