1#![deny(missing_docs)]
10
11use crate::derives::*;
12use crate::parser::{Parse, ParserContext};
13use crate::typed_om::{KeywordValue, NumericType, NumericValue, ToTyped, TypedValue, UnitValue};
14use crate::values::distance::{ComputeSquaredDistance, SquaredDistance};
15use crate::values::generics::position::IsTreeScoped;
16use crate::Atom;
17pub use cssparser::{serialize_identifier, serialize_name, CowRcStr, Parser};
18pub use cssparser::{SourceLocation, Token};
19use num_traits::Zero;
20use precomputed_hash::PrecomputedHash;
21use selectors::parser::SelectorParseErrorKind;
22use std::fmt::{self, Debug, Write};
23use style_traits::{CssString, CssWriter, ParseError, StyleParseErrorKind, ToCss};
24use thin_vec::ThinVec;
25use to_shmem::impl_trivial_to_shmem;
26
27pub use crate::url::CssUrl;
28
29pub mod animated;
30pub mod computed;
31pub mod distance;
32pub mod generics;
33pub mod resolved;
34pub mod specified;
35pub mod tagged_numeric;
36
37pub type CSSFloat = f32;
39
40#[inline]
43pub fn normalize(v: CSSFloat) -> CSSFloat {
44 if v.is_nan() {
45 0.0
46 } else {
47 v
48 }
49}
50
51#[inline]
55pub fn calc_min(a: CSSFloat, b: CSSFloat) -> CSSFloat {
56 match (a.is_sign_negative(), b.is_sign_negative()) {
57 (true, false) => a,
58 (false, true) => b,
59 _ => a.min(b),
60 }
61}
62
63#[inline]
67pub fn calc_max(a: CSSFloat, b: CSSFloat) -> CSSFloat {
68 match (a.is_sign_negative(), b.is_sign_negative()) {
69 (true, false) => b,
70 (false, true) => a,
71 _ => a.max(b),
72 }
73}
74
75#[inline]
80pub fn calc_sign(value: CSSFloat) -> CSSFloat {
81 if value.is_nan() {
82 f32::NAN
83 } else if value.is_zero() {
84 value
85 } else if value.is_sign_negative() {
86 -1.0
87 } else {
88 1.0
89 }
90}
91
92pub type CSSInteger = i32;
94
95#[cfg(feature = "gecko")]
97pub fn serialize_atom_identifier<W>(ident: &Atom, dest: &mut W) -> fmt::Result
98where
99 W: Write,
100{
101 ident.with_str(|s| serialize_identifier(s, dest))
102}
103
104#[cfg(feature = "servo")]
106pub fn serialize_atom_identifier<Static, W>(
107 ident: &::string_cache::Atom<Static>,
108 dest: &mut W,
109) -> fmt::Result
110where
111 Static: string_cache::StaticAtomSet,
112 W: Write,
113{
114 serialize_identifier(&ident, dest)
115}
116
117#[cfg(feature = "gecko")]
119pub fn serialize_atom_name<W>(ident: &Atom, dest: &mut W) -> fmt::Result
120where
121 W: Write,
122{
123 ident.with_str(|s| serialize_name(s, dest))
124}
125
126#[cfg(feature = "servo")]
128pub fn serialize_atom_name<Static, W>(
129 ident: &::string_cache::Atom<Static>,
130 dest: &mut W,
131) -> fmt::Result
132where
133 Static: string_cache::StaticAtomSet,
134 W: Write,
135{
136 serialize_name(&ident, dest)
137}
138
139pub fn serialize_number<W>(v: f32, dest: &mut CssWriter<W>) -> fmt::Result
141where
142 W: Write,
143{
144 serialize_specified_dimension(v, "", false, dest)
145}
146
147pub fn serialize_specified_dimension<W>(
149 v: f32,
150 unit: &str,
151 was_calc: bool,
152 dest: &mut CssWriter<W>,
153) -> fmt::Result
154where
155 W: Write,
156{
157 if was_calc {
158 dest.write_str("calc(")?;
159 }
160
161 if !v.is_finite() {
162 if v.is_nan() {
168 dest.write_str("NaN")?;
169 } else if v == f32::INFINITY {
170 dest.write_str("infinity")?;
171 } else if v == f32::NEG_INFINITY {
172 dest.write_str("-infinity")?;
173 }
174
175 if !unit.is_empty() {
176 dest.write_str(" * 1")?;
177 }
178 } else {
179 v.to_css(dest)?;
180 }
181
182 dest.write_str(unit)?;
183
184 if was_calc {
185 dest.write_char(')')?;
186 }
187 Ok(())
188}
189
190#[repr(transparent)]
192#[derive(
193 Clone,
194 Debug,
195 Default,
196 Deref,
197 Eq,
198 Hash,
199 MallocSizeOf,
200 PartialEq,
201 SpecifiedValueInfo,
202 ToAnimatedValue,
203 ToComputedValue,
204 ToResolvedValue,
205 ToShmem,
206)]
207pub struct AtomString(pub Atom);
208
209#[cfg(feature = "servo")]
210impl AsRef<str> for AtomString {
211 fn as_ref(&self) -> &str {
212 &*self.0
213 }
214}
215
216impl Parse for AtomString {
217 fn parse(_: &ParserContext, input: &mut Parser) -> Result<Self, ParseError> {
218 Ok(Self(Atom::from(input.expect_string()?.as_ref())))
219 }
220}
221
222impl cssparser::ToCss for AtomString {
223 fn to_css<W>(&self, dest: &mut W) -> fmt::Result
224 where
225 W: Write,
226 {
227 dest.write_char('"')?;
229 #[cfg(feature = "servo")]
230 {
231 cssparser::CssStringWriter::new(dest).write_str(self.as_ref())?;
232 }
233 #[cfg(feature = "gecko")]
234 {
235 self.0
236 .with_str(|s| cssparser::CssStringWriter::new(dest).write_str(s))?;
237 }
238 dest.write_char('"')
239 }
240}
241
242impl style_traits::ToCss for AtomString {
243 fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
244 where
245 W: Write,
246 {
247 cssparser::ToCss::to_css(self, dest)
248 }
249}
250
251impl PrecomputedHash for AtomString {
252 #[inline]
253 fn precomputed_hash(&self) -> u32 {
254 self.0.precomputed_hash()
255 }
256}
257
258impl From<&str> for AtomString {
259 #[inline]
260 fn from(string: &str) -> Self {
261 Self(Atom::from(string))
262 }
263}
264
265#[cfg(feature = "servo")]
267#[repr(transparent)]
268#[derive(Deref)]
269pub struct GenericAtomIdent<Set>(pub string_cache::Atom<Set>)
270where
271 Set: string_cache::StaticAtomSet;
272
273#[cfg(feature = "servo")]
275pub type AtomIdent = GenericAtomIdent<stylo_atoms::AtomStaticSet>;
276
277#[cfg(feature = "servo")]
278impl<Set: string_cache::StaticAtomSet> style_traits::SpecifiedValueInfo for GenericAtomIdent<Set> {}
279
280#[cfg(feature = "servo")]
281impl<Set: string_cache::StaticAtomSet> Default for GenericAtomIdent<Set> {
282 fn default() -> Self {
283 Self(string_cache::Atom::default())
284 }
285}
286
287#[cfg(feature = "servo")]
288impl<Set: string_cache::StaticAtomSet> std::fmt::Debug for GenericAtomIdent<Set> {
289 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
290 self.0.fmt(f)
291 }
292}
293
294#[cfg(feature = "servo")]
295impl<Set: string_cache::StaticAtomSet> std::hash::Hash for GenericAtomIdent<Set> {
296 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
297 self.0.hash(state)
298 }
299}
300
301#[cfg(feature = "servo")]
302impl<Set: string_cache::StaticAtomSet> Eq for GenericAtomIdent<Set> {}
303
304#[cfg(feature = "servo")]
305impl<Set: string_cache::StaticAtomSet> PartialEq for GenericAtomIdent<Set> {
306 fn eq(&self, other: &Self) -> bool {
307 self.0 == other.0
308 }
309}
310
311#[cfg(feature = "servo")]
312impl<Set: string_cache::StaticAtomSet> Clone for GenericAtomIdent<Set> {
313 fn clone(&self) -> Self {
314 Self(self.0.clone())
315 }
316}
317
318#[cfg(feature = "servo")]
319impl<Set: string_cache::StaticAtomSet> to_shmem::ToShmem for GenericAtomIdent<Set> {
320 fn to_shmem(&self, builder: &mut to_shmem::SharedMemoryBuilder) -> to_shmem::Result<Self> {
321 use std::mem::ManuallyDrop;
322
323 let atom = self.0.to_shmem(builder)?;
324 Ok(ManuallyDrop::new(Self(ManuallyDrop::into_inner(atom))))
325 }
326}
327
328#[cfg(feature = "servo")]
329impl<Set: string_cache::StaticAtomSet> malloc_size_of::MallocSizeOf for GenericAtomIdent<Set> {
330 fn size_of(&self, ops: &mut malloc_size_of::MallocSizeOfOps) -> usize {
331 self.0.size_of(ops)
332 }
333}
334
335#[cfg(feature = "servo")]
336impl<Set: string_cache::StaticAtomSet> cssparser::ToCss for GenericAtomIdent<Set> {
337 fn to_css<W>(&self, dest: &mut W) -> fmt::Result
338 where
339 W: Write,
340 {
341 serialize_atom_identifier(&self.0, dest)
342 }
343}
344
345#[cfg(feature = "servo")]
346impl<Set: string_cache::StaticAtomSet> style_traits::ToCss for GenericAtomIdent<Set> {
347 fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
348 where
349 W: Write,
350 {
351 serialize_atom_identifier(&self.0, dest)
352 }
353}
354
355#[cfg(feature = "servo")]
356impl<Set: string_cache::StaticAtomSet> PrecomputedHash for GenericAtomIdent<Set> {
357 #[inline]
358 fn precomputed_hash(&self) -> u32 {
359 self.0.precomputed_hash()
360 }
361}
362
363#[cfg(feature = "servo")]
364impl<'a, Set: string_cache::StaticAtomSet> From<&'a str> for GenericAtomIdent<Set> {
365 #[inline]
366 fn from(string: &str) -> Self {
367 Self(string_cache::Atom::from(string))
368 }
369}
370
371#[cfg(feature = "servo")]
372impl<Set: string_cache::StaticAtomSet> std::borrow::Borrow<string_cache::Atom<Set>>
373 for GenericAtomIdent<Set>
374{
375 #[inline]
376 fn borrow(&self) -> &string_cache::Atom<Set> {
377 &self.0
378 }
379}
380
381#[cfg(feature = "servo")]
382impl<Set: string_cache::StaticAtomSet> GenericAtomIdent<Set> {
383 #[inline]
385 pub fn new(atom: string_cache::Atom<Set>) -> Self {
386 Self(atom)
387 }
388
389 #[inline]
391 pub fn cast<'a>(atom: &'a string_cache::Atom<Set>) -> &'a Self {
392 let ptr = atom as *const _ as *const Self;
393 unsafe { &*ptr }
395 }
396}
397
398#[cfg(feature = "gecko")]
400#[repr(transparent)]
401#[derive(
402 Clone, Debug, Default, Deref, Eq, Hash, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToShmem,
403)]
404pub struct AtomIdent(pub Atom);
405
406#[cfg(feature = "gecko")]
407impl cssparser::ToCss for AtomIdent {
408 fn to_css<W>(&self, dest: &mut W) -> fmt::Result
409 where
410 W: Write,
411 {
412 serialize_atom_identifier(&self.0, dest)
413 }
414}
415
416#[cfg(feature = "gecko")]
417impl style_traits::ToCss for AtomIdent {
418 fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
419 where
420 W: Write,
421 {
422 cssparser::ToCss::to_css(self, dest)
423 }
424}
425
426#[cfg(feature = "gecko")]
427impl PrecomputedHash for AtomIdent {
428 #[inline]
429 fn precomputed_hash(&self) -> u32 {
430 self.0.precomputed_hash()
431 }
432}
433
434#[cfg(feature = "gecko")]
435impl From<&str> for AtomIdent {
436 #[inline]
437 fn from(string: &str) -> Self {
438 Self(Atom::from(string))
439 }
440}
441
442#[cfg(feature = "gecko")]
443impl AtomIdent {
444 #[inline]
446 pub fn new(atom: Atom) -> Self {
447 Self(atom)
448 }
449
450 pub unsafe fn with<F, R>(ptr: *const crate::gecko_bindings::structs::nsAtom, callback: F) -> R
452 where
453 F: FnOnce(&Self) -> R,
454 {
455 unsafe {
456 Atom::with(ptr, |atom: &Atom| {
457 let atom = atom as *const Atom as *const AtomIdent;
459 callback(&*atom)
460 })
461 }
462 }
463
464 #[inline]
466 pub fn cast(atom: &Atom) -> &Self {
467 let ptr = atom as *const _ as *const Self;
468 unsafe { &*ptr }
470 }
471}
472
473#[cfg(feature = "gecko")]
474impl std::borrow::Borrow<crate::gecko_string_cache::WeakAtom> for AtomIdent {
475 #[inline]
476 fn borrow(&self) -> &crate::gecko_string_cache::WeakAtom {
477 self.0.borrow()
478 }
479}
480
481pub fn serialize_percentage<W>(value: CSSFloat, dest: &mut CssWriter<W>) -> fmt::Result
483where
484 W: Write,
485{
486 serialize_specified_dimension(value * 100., "%", false, dest)
487}
488
489pub fn serialize_normalized_percentage<W>(value: CSSFloat, dest: &mut CssWriter<W>) -> fmt::Result
491where
492 W: Write,
493{
494 (value * 100.).to_css(dest)?;
495 dest.write_char('%')
496}
497
498pub fn reify_percentage(value: CSSFloat, dest: &mut ThinVec<TypedValue>) -> Result<(), ()> {
500 let numeric_value = NumericValue::Unit(UnitValue {
501 numeric_type: NumericType::percent(),
502 value: value * 100.,
503 unit: CssString::from("percent"),
504 });
505
506 dest.push(TypedValue::Numeric(numeric_value));
507 Ok(())
508}
509
510#[derive(
512 Clone,
513 Copy,
514 Debug,
515 Deserialize,
516 MallocSizeOf,
517 PartialEq,
518 Serialize,
519 SpecifiedValueInfo,
520 ToAnimatedValue,
521 ToComputedValue,
522 ToCss,
523 ToResolvedValue,
524)]
525pub enum Impossible {}
526
527impl ComputeSquaredDistance for Impossible {
530 #[inline]
531 fn compute_squared_distance(&self, _other: &Self) -> Result<SquaredDistance, ()> {
532 match *self {}
533 }
534}
535
536impl_trivial_to_shmem!(Impossible);
537
538impl Parse for Impossible {
539 fn parse(_context: &ParserContext, _input: &mut Parser) -> Result<Self, ParseError> {
540 Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError))
541 }
542}
543
544#[derive(
546 Animate,
547 Clone,
548 ComputeSquaredDistance,
549 Copy,
550 MallocSizeOf,
551 PartialEq,
552 Parse,
553 SpecifiedValueInfo,
554 ToAnimatedValue,
555 ToAnimatedZero,
556 ToComputedValue,
557 ToCss,
558 ToResolvedValue,
559 ToShmem,
560)]
561pub enum Either<A, B> {
562 First(A),
564 Second(B),
566}
567
568impl<A: Debug, B: Debug> Debug for Either<A, B> {
569 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
570 match *self {
571 Either::First(ref v) => v.fmt(f),
572 Either::Second(ref v) => v.fmt(f),
573 }
574 }
575}
576
577#[derive(
579 Clone,
580 Debug,
581 Default,
582 Deserialize,
583 Eq,
584 Hash,
585 MallocSizeOf,
586 PartialEq,
587 Serialize,
588 SpecifiedValueInfo,
589 ToAnimatedValue,
590 ToComputedValue,
591 ToResolvedValue,
592 ToShmem,
593)]
594#[repr(C)]
595pub struct CustomIdent(pub Atom);
596
597impl CustomIdent {
598 pub fn parse(input: &mut Parser, invalid: &[&str]) -> Result<Self, ParseError> {
603 let ident = input.expect_ident()?;
604 CustomIdent::from_ident(ident, invalid)
605 }
606
607 pub fn from_ident<'i>(ident: &CowRcStr<'i>, excluding: &[&str]) -> Result<Self, ParseError> {
609 if !Self::is_valid(ident, excluding) {
610 return Err(ParseError::custom(SelectorParseErrorKind::UnexpectedIdent));
611 }
612 if excluding.iter().any(|s| ident.eq_ignore_ascii_case(s)) {
613 Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError))
614 } else {
615 Ok(CustomIdent(Atom::from(ident.as_ref())))
616 }
617 }
618
619 fn is_valid(ident: &str, excluding: &[&str]) -> bool {
620 use crate::properties::CSSWideKeyword;
621 if CSSWideKeyword::from_ident(ident).is_ok() || ident.eq_ignore_ascii_case("default") {
626 return false;
627 }
628
629 !excluding.iter().any(|s| ident.eq_ignore_ascii_case(s))
633 }
634}
635
636impl ToCss for CustomIdent {
637 fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
638 where
639 W: Write,
640 {
641 serialize_atom_identifier(&self.0, dest)
642 }
643}
644
645impl ToTyped for CustomIdent {
646 fn to_typed(&self, dest: &mut ThinVec<TypedValue>) -> Result<(), ()> {
647 let s = ToCss::to_css_cssstring(self);
649 dest.push(TypedValue::Keyword(KeywordValue(s)));
650 Ok(())
651 }
652}
653
654#[repr(transparent)]
657#[derive(
658 Clone,
659 Debug,
660 Eq,
661 Hash,
662 MallocSizeOf,
663 PartialEq,
664 SpecifiedValueInfo,
665 ToAnimatedValue,
666 ToComputedValue,
667 ToResolvedValue,
668 ToShmem,
669 Serialize,
670 Deserialize,
671)]
672pub struct DashedIdent(pub Atom);
673
674impl DashedIdent {
675 pub fn from_ident<'i>(ident: &CowRcStr<'i>) -> Result<Self, ParseError> {
677 if !ident.starts_with("--") {
678 return Err(ParseError::custom(SelectorParseErrorKind::UnexpectedIdent));
679 }
680 Ok(Self(Atom::from(ident.as_ref())))
681 }
682
683 pub fn empty() -> Self {
685 Self(atom!(""))
686 }
687
688 pub fn is_empty(&self) -> bool {
690 self.0 == atom!("")
691 }
692
693 pub(crate) fn undashed(&self) -> Atom {
699 assert!(!self.is_empty(), "Can't undash the empty DashedIdent");
700 #[cfg(feature = "gecko")]
701 let name = &self.0.as_slice()[2..];
702 #[cfg(feature = "servo")]
703 let name = &self.0[2..];
704 Atom::from(name)
705 }
706}
707
708impl IsTreeScoped for DashedIdent {
709 fn is_tree_scoped(&self) -> bool {
710 !self.is_empty()
711 }
712}
713
714impl Parse for DashedIdent {
715 fn parse(_: &ParserContext, input: &mut Parser) -> Result<Self, ParseError> {
716 let ident = input.expect_ident()?;
717 Self::from_ident(ident)
718 }
719}
720
721impl ToCss for DashedIdent {
722 fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
723 where
724 W: Write,
725 {
726 serialize_atom_identifier(&self.0, dest)
727 }
728}
729
730#[repr(transparent)]
736#[derive(
737 Clone,
738 Debug,
739 Eq,
740 Hash,
741 PartialEq,
742 MallocSizeOf,
743 SpecifiedValueInfo,
744 ToComputedValue,
745 ToResolvedValue,
746 ToShmem,
747)]
748pub struct KeyframesName(Atom);
749
750impl KeyframesName {
751 pub fn from_ident(value: &str) -> Self {
753 Self(Atom::from(value))
754 }
755
756 pub fn none() -> Self {
758 Self(atom!(""))
759 }
760
761 pub fn is_none(&self) -> bool {
763 self.0 == atom!("")
764 }
765
766 #[cfg(feature = "gecko")]
768 pub fn from_atom(atom: Atom) -> Self {
769 Self(atom)
770 }
771
772 pub fn as_atom(&self) -> &Atom {
774 &self.0
775 }
776}
777
778impl Parse for KeyframesName {
779 fn parse(_: &ParserContext, input: &mut Parser) -> Result<Self, ParseError> {
780 Ok(match *input.next()? {
781 Token::Ident(ref s) => Self(CustomIdent::from_ident(s, &["none"])?.0),
782 Token::QuotedString(ref s) if !s.as_ref().is_empty() => Self(Atom::from(s.as_ref())),
784 _ => return Err(ParseError::unexpected_token()),
785 })
786 }
787}
788
789impl ToCss for KeyframesName {
790 fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
791 where
792 W: Write,
793 {
794 if self.is_none() {
795 return dest.write_str("none");
796 }
797
798 fn serialize<W: Write>(string: &str, dest: &mut CssWriter<W>) -> fmt::Result {
799 if CustomIdent::is_valid(string, &["none"]) {
800 serialize_identifier(string, dest)
801 } else {
802 string.to_css(dest)
803 }
804 }
805
806 #[cfg(feature = "gecko")]
807 return self.0.with_str(|s| serialize(s, dest));
808
809 #[cfg(feature = "servo")]
810 return serialize(self.0.as_ref(), dest);
811 }
812}
813
814impl ToTyped for KeyframesName {
815 fn to_typed(&self, dest: &mut ThinVec<TypedValue>) -> Result<(), ()> {
816 let s = ToCss::to_css_cssstring(self);
817 dest.push(TypedValue::Keyword(KeywordValue(s)));
818 Ok(())
819 }
820}