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