]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/theme.rs
Auto merge of #93530 - anonion0:pthread_sigmask_fix, r=JohnTitor
[rust.git] / src / librustdoc / theme.rs
1 use rustc_data_structures::fx::FxHashSet;
2 use std::fs;
3 use std::hash::{Hash, Hasher};
4 use std::path::Path;
5
6 use rustc_errors::Handler;
7
8 #[cfg(test)]
9 mod tests;
10
11 #[derive(Debug, Clone, Eq)]
12 crate struct CssPath {
13     crate name: String,
14     crate children: FxHashSet<CssPath>,
15 }
16
17 // This PartialEq implementation IS NOT COMMUTATIVE!!!
18 //
19 // The order is very important: the second object must have all first's rules.
20 // However, the first is not required to have all of the second's rules.
21 impl PartialEq for CssPath {
22     fn eq(&self, other: &CssPath) -> bool {
23         if self.name != other.name {
24             false
25         } else {
26             for child in &self.children {
27                 if !other.children.iter().any(|c| child == c) {
28                     return false;
29                 }
30             }
31             true
32         }
33     }
34 }
35
36 impl Hash for CssPath {
37     fn hash<H: Hasher>(&self, state: &mut H) {
38         self.name.hash(state);
39         for x in &self.children {
40             x.hash(state);
41         }
42     }
43 }
44
45 impl CssPath {
46     fn new(name: String) -> CssPath {
47         CssPath { name, children: FxHashSet::default() }
48     }
49 }
50
51 /// All variants contain the position they occur.
52 #[derive(Debug, Clone, Copy)]
53 enum Events {
54     StartLineComment(usize),
55     StartComment(usize),
56     EndComment(usize),
57     InBlock(usize),
58     OutBlock(usize),
59 }
60
61 impl Events {
62     fn get_pos(&self) -> usize {
63         match *self {
64             Events::StartLineComment(p)
65             | Events::StartComment(p)
66             | Events::EndComment(p)
67             | Events::InBlock(p)
68             | Events::OutBlock(p) => p,
69         }
70     }
71
72     fn is_comment(&self) -> bool {
73         matches!(
74             self,
75             Events::StartLineComment(_) | Events::StartComment(_) | Events::EndComment(_)
76         )
77     }
78 }
79
80 fn previous_is_line_comment(events: &[Events]) -> bool {
81     matches!(events.last(), Some(&Events::StartLineComment(_)))
82 }
83
84 fn is_line_comment(pos: usize, v: &[u8], events: &[Events]) -> bool {
85     if let Some(&Events::StartComment(_)) = events.last() {
86         return false;
87     }
88     v[pos + 1] == b'/'
89 }
90
91 fn load_css_events(v: &[u8]) -> Vec<Events> {
92     let mut pos = 0;
93     let mut events = Vec::with_capacity(100);
94
95     while pos + 1 < v.len() {
96         match v[pos] {
97             b'/' if v[pos + 1] == b'*' => {
98                 events.push(Events::StartComment(pos));
99                 pos += 1;
100             }
101             b'/' if is_line_comment(pos, v, &events) => {
102                 events.push(Events::StartLineComment(pos));
103                 pos += 1;
104             }
105             b'\n' if previous_is_line_comment(&events) => {
106                 events.push(Events::EndComment(pos));
107             }
108             b'*' if v[pos + 1] == b'/' => {
109                 events.push(Events::EndComment(pos + 2));
110                 pos += 1;
111             }
112             b'{' if !previous_is_line_comment(&events) => {
113                 if let Some(&Events::StartComment(_)) = events.last() {
114                     pos += 1;
115                     continue;
116                 }
117                 events.push(Events::InBlock(pos + 1));
118             }
119             b'}' if !previous_is_line_comment(&events) => {
120                 if let Some(&Events::StartComment(_)) = events.last() {
121                     pos += 1;
122                     continue;
123                 }
124                 events.push(Events::OutBlock(pos + 1));
125             }
126             _ => {}
127         }
128         pos += 1;
129     }
130     events
131 }
132
133 fn get_useful_next(events: &[Events], pos: &mut usize) -> Option<Events> {
134     while *pos < events.len() {
135         if !events[*pos].is_comment() {
136             return Some(events[*pos]);
137         }
138         *pos += 1;
139     }
140     None
141 }
142
143 fn get_previous_positions(events: &[Events], mut pos: usize) -> Vec<usize> {
144     let mut ret = Vec::with_capacity(3);
145
146     ret.push(events[pos].get_pos());
147     if pos > 0 {
148         pos -= 1;
149     }
150     loop {
151         if pos < 1 || !events[pos].is_comment() {
152             let x = events[pos].get_pos();
153             if *ret.last().unwrap() != x {
154                 ret.push(x);
155             } else {
156                 ret.push(0);
157             }
158             break;
159         }
160         ret.push(events[pos].get_pos());
161         pos -= 1;
162     }
163     if ret.len() & 1 != 0 && events[pos].is_comment() {
164         ret.push(0);
165     }
166     ret.iter().rev().cloned().collect()
167 }
168
169 fn build_rule(v: &[u8], positions: &[usize]) -> String {
170     minifier::css::minify(
171         &positions
172             .chunks(2)
173             .map(|x| ::std::str::from_utf8(&v[x[0]..x[1]]).unwrap_or(""))
174             .collect::<String>()
175             .trim()
176             .chars()
177             .filter_map(|c| match c {
178                 '\n' | '\t' => Some(' '),
179                 '/' | '{' | '}' => None,
180                 c => Some(c),
181             })
182             .collect::<String>()
183             .split(' ')
184             .filter(|s| !s.is_empty())
185             .intersperse(" ")
186             .collect::<String>(),
187     )
188     .unwrap_or_else(|_| String::new())
189 }
190
191 fn inner(v: &[u8], events: &[Events], pos: &mut usize) -> FxHashSet<CssPath> {
192     let mut paths = Vec::with_capacity(50);
193
194     while *pos < events.len() {
195         if let Some(Events::OutBlock(_)) = get_useful_next(events, pos) {
196             *pos += 1;
197             break;
198         }
199         if let Some(Events::InBlock(_)) = get_useful_next(events, pos) {
200             paths.push(CssPath::new(build_rule(v, &get_previous_positions(events, *pos))));
201             *pos += 1;
202         }
203         while let Some(Events::InBlock(_)) = get_useful_next(events, pos) {
204             if let Some(ref mut path) = paths.last_mut() {
205                 for entry in inner(v, events, pos).iter() {
206                     path.children.insert(entry.clone());
207                 }
208             }
209         }
210         if let Some(Events::OutBlock(_)) = get_useful_next(events, pos) {
211             *pos += 1;
212         }
213     }
214     paths.iter().cloned().collect()
215 }
216
217 crate fn load_css_paths(v: &[u8]) -> CssPath {
218     let events = load_css_events(v);
219     let mut pos = 0;
220
221     let mut parent = CssPath::new("parent".to_owned());
222     parent.children = inner(v, &events, &mut pos);
223     parent
224 }
225
226 crate fn get_differences(against: &CssPath, other: &CssPath, v: &mut Vec<String>) {
227     if against.name == other.name {
228         for child in &against.children {
229             let mut found = false;
230             let mut found_working = false;
231             let mut tmp = Vec::new();
232
233             for other_child in &other.children {
234                 if child.name == other_child.name {
235                     if child != other_child {
236                         get_differences(child, other_child, &mut tmp);
237                     } else {
238                         found_working = true;
239                     }
240                     found = true;
241                     break;
242                 }
243             }
244             if !found {
245                 v.push(format!("  Missing \"{}\" rule", child.name));
246             } else if !found_working {
247                 v.extend(tmp.iter().cloned());
248             }
249         }
250     }
251 }
252
253 crate fn test_theme_against<P: AsRef<Path>>(
254     f: &P,
255     against: &CssPath,
256     diag: &Handler,
257 ) -> (bool, Vec<String>) {
258     let data = match fs::read(f) {
259         Ok(c) => c,
260         Err(e) => {
261             diag.struct_err(&e.to_string()).emit();
262             return (false, vec![]);
263         }
264     };
265
266     let paths = load_css_paths(&data);
267     let mut ret = vec![];
268     get_differences(against, &paths, &mut ret);
269     (true, ret)
270 }