Skip to content

Commit 4d5d427

Browse files
committed
More rust docs
1 parent 5497b36 commit 4d5d427

File tree

13 files changed

+228
-25
lines changed

13 files changed

+228
-25
lines changed

node/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,7 @@ struct Drafts {
232232
fn compile<'i>(code: &'i str, config: &Config) -> Result<TransformResult, CompileError<'i>> {
233233
let drafts = config.drafts.as_ref();
234234
let mut stylesheet = StyleSheet::parse(
235-
config.filename.clone(),
235+
&config.filename,
236236
&code,
237237
ParserOptions {
238238
nesting: matches!(drafts, Some(d) if d.nesting),

scripts/build-prefixes.js

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -294,10 +294,28 @@ let prefixMapping = {
294294
let enumify = (f) => f.replace(/^@([a-z])/, (_, x) => 'At' + x.toUpperCase()).replace(/^::([a-z])/, (_, x) => 'PseudoElement' + x.toUpperCase()).replace(/^:([a-z])/, (_, x) => 'PseudoClass' + x.toUpperCase()).replace(/(^|-)([a-z])/g, (_, a, x) => x.toUpperCase())
295295

296296
let allBrowsers = Object.keys(browsers).filter(b => !(b in BROWSER_MAPPING)).sort();
297-
let targets = `// This file is autogenerated by build-prefixes.js. DO NOT EDIT!
297+
let targets = `//! Browser target options.
298+
// This file is autogenerated by build-prefixes.js. DO NOT EDIT!
298299
299300
use serde::{Deserialize, Serialize};
300301
302+
/// Browser versions to compile CSS for.
303+
///
304+
/// Versions are represented as a single 24-bit integer, with one byte
305+
/// per \`major.minor.patch\` component.
306+
///
307+
/// # Example
308+
///
309+
/// This example represents a target of Safari 13.2.0.
310+
///
311+
/// \`\`\`
312+
/// use parcel_css::targets::Browsers;
313+
///
314+
/// let targets = Browsers {
315+
/// safari: (13 << 16) | (2 << 8),
316+
/// ..Browsers::default()
317+
/// };
318+
/// \`\`\`
301319
#[derive(Serialize, Debug, Deserialize, Clone, Copy, Default)]
302320
pub struct Browsers {
303321
pub ${allBrowsers.join(': Option<u32>,\n pub ')}: Option<u32>

src/bundler.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -263,7 +263,7 @@ impl<'a, 's, P: SourceProvider> Bundler<'a, 's, P> {
263263
let _ = source_map.set_source_content(source_index as usize, code);
264264
}
265265

266-
let mut stylesheet = StyleSheet::parse(filename.into(), code, opts)?;
266+
let mut stylesheet = StyleSheet::parse(filename, code, opts)?;
267267

268268
// Collect and load dependencies for this stylesheet in parallel.
269269
let dependencies: Result<Vec<u32>, _> = stylesheet

src/lib.rs

Lines changed: 17 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -37,14 +37,14 @@ mod tests {
3737
use std::collections::HashMap;
3838

3939
fn test(source: &str, expected: &str) {
40-
let mut stylesheet = StyleSheet::parse("test.css".into(), &source, ParserOptions::default()).unwrap();
40+
let mut stylesheet = StyleSheet::parse("test.css", &source, ParserOptions::default()).unwrap();
4141
stylesheet.minify(MinifyOptions::default()).unwrap();
4242
let res = stylesheet.to_css(PrinterOptions::default()).unwrap();
4343
assert_eq!(res.code, expected);
4444
}
4545

4646
fn minify_test(source: &str, expected: &str) {
47-
let mut stylesheet = StyleSheet::parse("test.css".into(), &source, ParserOptions::default()).unwrap();
47+
let mut stylesheet = StyleSheet::parse("test.css", &source, ParserOptions::default()).unwrap();
4848
stylesheet.minify(MinifyOptions::default()).unwrap();
4949
let res = stylesheet
5050
.to_css(PrinterOptions {
@@ -56,7 +56,7 @@ mod tests {
5656
}
5757

5858
fn prefix_test(source: &str, expected: &str, targets: Browsers) {
59-
let mut stylesheet = StyleSheet::parse("test.css".into(), &source, ParserOptions::default()).unwrap();
59+
let mut stylesheet = StyleSheet::parse("test.css", &source, ParserOptions::default()).unwrap();
6060
stylesheet
6161
.minify(MinifyOptions {
6262
targets: Some(targets),
@@ -94,7 +94,7 @@ mod tests {
9494
..Browsers::default()
9595
});
9696
let mut stylesheet = StyleSheet::parse(
97-
"test.css".into(),
97+
"test.css",
9898
&source,
9999
ParserOptions {
100100
nesting: true,
@@ -119,7 +119,7 @@ mod tests {
119119

120120
fn nesting_test_no_targets(source: &str, expected: &str) {
121121
let mut stylesheet = StyleSheet::parse(
122-
"test.css".into(),
122+
"test.css",
123123
&source,
124124
ParserOptions {
125125
nesting: true,
@@ -134,7 +134,7 @@ mod tests {
134134

135135
fn css_modules_test(source: &str, expected: &str, expected_exports: CssModuleExports) {
136136
let mut stylesheet = StyleSheet::parse(
137-
"test.css".into(),
137+
"test.css",
138138
&source,
139139
ParserOptions {
140140
css_modules: true,
@@ -150,7 +150,7 @@ mod tests {
150150

151151
fn custom_media_test(source: &str, expected: &str) {
152152
let mut stylesheet = StyleSheet::parse(
153-
"test.css".into(),
153+
"test.css",
154154
&source,
155155
ParserOptions {
156156
custom_media: true,
@@ -172,7 +172,7 @@ mod tests {
172172
}
173173

174174
fn error_test(source: &str, error: ParserError) {
175-
let res = StyleSheet::parse("test.css".into(), &source, ParserOptions::default());
175+
let res = StyleSheet::parse("test.css", &source, ParserOptions::default());
176176
match res {
177177
Ok(_) => unreachable!(),
178178
Err(e) => assert_eq!(e.kind, error),
@@ -15921,7 +15921,7 @@ mod tests {
1592115921
}
1592215922
"#};
1592315923

15924-
let stylesheet = StyleSheet::parse("test.css".into(), &source, ParserOptions::default()).unwrap();
15924+
let stylesheet = StyleSheet::parse("test.css", &source, ParserOptions::default()).unwrap();
1592515925
let res = stylesheet
1592615926
.to_css(PrinterOptions {
1592715927
pseudo_classes: Some(PseudoClasses {
@@ -15948,7 +15948,7 @@ mod tests {
1594815948
"#};
1594915949

1595015950
let stylesheet = StyleSheet::parse(
15951-
"test.css".into(),
15951+
"test.css",
1595215952
&source,
1595315953
ParserOptions {
1595415954
css_modules: true,
@@ -16034,7 +16034,7 @@ mod tests {
1603416034
}
1603516035
"#};
1603616036

16037-
let mut stylesheet = StyleSheet::parse("test.css".into(), &source, ParserOptions::default()).unwrap();
16037+
let mut stylesheet = StyleSheet::parse("test.css", &source, ParserOptions::default()).unwrap();
1603816038
stylesheet
1603916039
.minify(MinifyOptions {
1604016040
unused_symbols: vec!["bar", "other_id", "fade", "circles"]
@@ -16064,7 +16064,7 @@ mod tests {
1606416064
"#};
1606516065

1606616066
let mut stylesheet = StyleSheet::parse(
16067-
"test.css".into(),
16067+
"test.css",
1606816068
&source,
1606916069
ParserOptions {
1607016070
nesting: true,
@@ -16118,7 +16118,7 @@ mod tests {
1611816118
"#};
1611916119

1612016120
let mut stylesheet = StyleSheet::parse(
16121-
"test.css".into(),
16121+
"test.css",
1612216122
&source,
1612316123
ParserOptions {
1612416124
nesting: true,
@@ -17380,7 +17380,7 @@ mod tests {
1738017380

1738117381
fn custom_media_error_test(source: &str, err: Error<MinifyErrorKind>) {
1738217382
let mut stylesheet = StyleSheet::parse(
17383-
"test.css".into(),
17383+
"test.css",
1738417384
&source,
1738517385
ParserOptions {
1738617386
custom_media: true,
@@ -17619,7 +17619,7 @@ mod tests {
1761917619
#[test]
1762017620
fn test_dependencies() {
1762117621
fn dep_test(source: &str, expected: &str, deps: Vec<(&str, &str)>) {
17622-
let mut stylesheet = StyleSheet::parse("test.css".into(), &source, ParserOptions::default()).unwrap();
17622+
let mut stylesheet = StyleSheet::parse("test.css", &source, ParserOptions::default()).unwrap();
1762317623
stylesheet.minify(MinifyOptions::default()).unwrap();
1762417624
let res = stylesheet
1762517625
.to_css(PrinterOptions {
@@ -17643,7 +17643,7 @@ mod tests {
1764317643
}
1764417644

1764517645
fn dep_error_test(source: &str, error: PrinterErrorKind) {
17646-
let stylesheet = StyleSheet::parse("test.css".into(), &source, ParserOptions::default()).unwrap();
17646+
let stylesheet = StyleSheet::parse("test.css", &source, ParserOptions::default()).unwrap();
1764717647
let res = stylesheet.to_css(PrinterOptions {
1764817648
analyze_dependencies: true,
1764917649
..PrinterOptions::default()
@@ -17722,8 +17722,7 @@ mod tests {
1772217722

1772317723
#[test]
1772417724
fn test_api() {
17725-
let stylesheet =
17726-
StyleSheet::parse("test.css".into(), ".foo:hover { color: red }", ParserOptions::default()).unwrap();
17725+
let stylesheet = StyleSheet::parse("test.css", ".foo:hover { color: red }", ParserOptions::default()).unwrap();
1772717726
match &stylesheet.rules.0[0] {
1772817727
CssRule::Style(s) => {
1772917728
assert_eq!(&s.selectors.to_string(), ".foo:hover");

src/main.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ pub fn main() -> Result<(), std::io::Error> {
7979
sm.add_source(&filename);
8080
let _ = sm.set_source_content(0, &source);
8181
}
82-
StyleSheet::parse(filename.into(), &source, options).unwrap()
82+
StyleSheet::parse(filename, &source, options).unwrap()
8383
};
8484

8585
let targets = browserslist_to_targets(cli_args.targets).unwrap();

src/printer.rs

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
//! CSS serialization and source map generation.
2+
13
use crate::css_modules::CssModule;
24
use crate::dependencies::Dependency;
35
use crate::error::{Error, ErrorLocation, PrinterError, PrinterErrorKind};
@@ -7,24 +9,54 @@ use crate::vendor_prefix::VendorPrefix;
79
use cssparser::{serialize_identifier, SourceLocation};
810
use parcel_sourcemap::{OriginalLocation, SourceMap};
911

12+
/// Options that control how CSS is serialized to a string.
1013
#[derive(Default)]
1114
pub struct PrinterOptions<'a> {
15+
/// Whether to minify the CSS, i.e. remove white space.
1216
pub minify: bool,
17+
/// An optional reference to a source map to write mappings into.
1318
pub source_map: Option<&'a mut SourceMap>,
19+
/// Browser targets to output the CSS for.
1420
pub targets: Option<Browsers>,
21+
/// Whether to analyze dependencies (i.e. `@import` and `url()`).
22+
/// If true, the dependencies are returned as part of the
23+
/// [ToCssResult](super::stylesheet::ToCssResult).
24+
///
25+
/// When enabled, `@import` rules are removed, and `url()` dependencies
26+
/// are replaced with hashed placeholders that can be replaced with the final
27+
/// urls later (after bundling).
1528
pub analyze_dependencies: bool,
29+
/// A mapping of pseudo classes to replace with class names that can be applied
30+
/// from JavaScript. Useful for polyfills, for example.
1631
pub pseudo_classes: Option<PseudoClasses<'a>>,
1732
}
1833

34+
/// A mapping of user action pseudo classes to replace with class names.
35+
///
36+
/// See [PrinterOptions](PrinterOptions).
1937
#[derive(Default, Debug)]
2038
pub struct PseudoClasses<'a> {
39+
/// The class name to replace `:hover` with.
2140
pub hover: Option<&'a str>,
41+
/// The class name to replace `:active` with.
2242
pub active: Option<&'a str>,
43+
/// The class name to replace `:focus` with.
2344
pub focus: Option<&'a str>,
45+
/// The class name to replace `:focus-visible` with.
2446
pub focus_visible: Option<&'a str>,
47+
/// The class name to replace `:focus-within` with.
2548
pub focus_within: Option<&'a str>,
2649
}
2750

51+
/// A `Printer` represents a destination to output serialized CSS, as used in
52+
/// the [ToCss](super::traits::ToCss) trait. It can wrap any destination that
53+
/// implements [std::fmt::Write](std::fmt::Write), such as a [String](String).
54+
///
55+
/// A `Printer` keeps track of the current line and column position, and uses
56+
/// this to generate a source map if provided in the options.
57+
///
58+
/// `Printer` also includes helper functions that assist with writing output
59+
/// that respects options such as `minify`, and `css_modules`.
2860
pub struct Printer<'a, W> {
2961
pub(crate) sources: Option<&'a Vec<String>>,
3062
dest: &'a mut W,
@@ -45,6 +77,7 @@ pub struct Printer<'a, W> {
4577
}
4678

4779
impl<'a, W: std::fmt::Write + Sized> Printer<'a, W> {
80+
/// Create a new Printer wrapping the given destination.
4881
pub fn new(dest: &'a mut W, options: PrinterOptions<'a>) -> Printer<'a, W> {
4982
Printer {
5083
sources: None,
@@ -68,6 +101,7 @@ impl<'a, W: std::fmt::Write + Sized> Printer<'a, W> {
68101
}
69102
}
70103

104+
/// Returns the current source filename that is being printed.
71105
pub fn filename(&self) -> &str {
72106
if let Some(sources) = self.sources {
73107
if let Some(f) = sources.get(self.source_index as usize) {
@@ -80,12 +114,17 @@ impl<'a, W: std::fmt::Write + Sized> Printer<'a, W> {
80114
}
81115
}
82116

117+
/// Writes a raw string to the underlying destination.
118+
///
119+
/// NOTE: Is is assumed that the string does not contain any newline characters.
120+
/// If such a string is written, it will break source maps.
83121
pub fn write_str(&mut self, s: &str) -> Result<(), PrinterError> {
84122
self.col += s.len() as u32;
85123
self.dest.write_str(s)?;
86124
Ok(())
87125
}
88126

127+
/// Write a single character to the underlying destination.
89128
pub fn write_char(&mut self, c: char) -> Result<(), PrinterError> {
90129
if c == '\n' {
91130
self.line += 1;
@@ -97,6 +136,10 @@ impl<'a, W: std::fmt::Write + Sized> Printer<'a, W> {
97136
Ok(())
98137
}
99138

139+
/// Writes a single whitespace character, unless the `minify` option is enabled.
140+
///
141+
/// Use `write_char` instead if you wish to force a space character to be written,
142+
/// regardless of the `minify` option.
100143
pub fn whitespace(&mut self) -> Result<(), PrinterError> {
101144
if self.minify {
102145
return Ok(());
@@ -105,6 +148,8 @@ impl<'a, W: std::fmt::Write + Sized> Printer<'a, W> {
105148
self.write_char(' ')
106149
}
107150

151+
/// Writes a delimeter character, followed by whitespace (depending on the `minify` option).
152+
/// If `ws_before` is true, then whitespace is also written before the delimeter.
108153
pub fn delim(&mut self, delim: char, ws_before: bool) -> Result<(), PrinterError> {
109154
if ws_before {
110155
self.whitespace()?;
@@ -113,6 +158,8 @@ impl<'a, W: std::fmt::Write + Sized> Printer<'a, W> {
113158
self.whitespace()
114159
}
115160

161+
/// Writes a newline character followed by indentation.
162+
/// If the `minify` option is enabled, then nothing is printed.
116163
pub fn newline(&mut self) -> Result<(), PrinterError> {
117164
if self.minify {
118165
return Ok(());
@@ -126,26 +173,32 @@ impl<'a, W: std::fmt::Write + Sized> Printer<'a, W> {
126173
Ok(())
127174
}
128175

176+
/// Increases the current indent level.
129177
pub fn indent(&mut self) {
130178
self.indent += 2;
131179
}
132180

181+
/// Decreases the current indent level.
133182
pub fn dedent(&mut self) {
134183
self.indent -= 2;
135184
}
136185

186+
/// Increases the current indent level by the given number of characters.
137187
pub fn indent_by(&mut self, amt: u8) {
138188
self.indent += amt;
139189
}
140190

191+
/// Decreases the current indent level by the given number of characters.
141192
pub fn dedent_by(&mut self, amt: u8) {
142193
self.indent -= amt;
143194
}
144195

196+
/// Returns whether the indent level is greater than one.
145197
pub fn is_nested(&self) -> bool {
146198
self.indent > 2
147199
}
148200

201+
/// Adds a mapping to the source map, if any.
149202
pub fn add_mapping(&mut self, loc: Location) {
150203
self.source_index = loc.source_index;
151204
if let Some(map) = &mut self.source_map {
@@ -162,6 +215,9 @@ impl<'a, W: std::fmt::Write + Sized> Printer<'a, W> {
162215
}
163216
}
164217

218+
/// Writes a CSS identifier to the underlying destination, escaping it
219+
/// as appropriate. If the `css_modules` option was enabled, then a hash
220+
/// is added, and the mapping is added to the CSS module.
165221
pub fn write_ident(&mut self, ident: &str) -> Result<(), PrinterError> {
166222
let hash = if let Some(css_module) = &self.css_module {
167223
Some(css_module.hash)
@@ -183,6 +239,7 @@ impl<'a, W: std::fmt::Write + Sized> Printer<'a, W> {
183239
Ok(())
184240
}
185241

242+
/// Returns an error of the given kind at the provided location in the current source file.
186243
pub fn error(&self, kind: PrinterErrorKind, loc: SourceLocation) -> Error<PrinterErrorKind> {
187244
Error {
188245
kind,

src/rules/font_palette_values.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ impl<'i> AtRuleParser<'i> for FontPaletteValuesDeclarationParser {
111111
}
112112

113113
impl<'i> FontPaletteValuesRule<'i> {
114-
pub fn parse<'t>(
114+
pub(crate) fn parse<'t>(
115115
name: DashedIdent<'i>,
116116
input: &mut Parser<'i, 't>,
117117
loc: Location,

0 commit comments

Comments
 (0)