/
properties.mako.rs
3145 lines (2866 loc) · 123 KB
/
properties.mako.rs
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// This file is a Mako template: http://www.makotemplates.org/
// Please note that valid Rust syntax may be mangled by the Mako parser.
// For example, Vec<&Foo> will be mangled as Vec&Foo>. To work around these issues, the code
// can be escaped. In the above example, Vec<<&Foo> or Vec< &Foo> achieves the desired result of Vec<&Foo>.
<%namespace name="helpers" file="/helpers.mako.rs" />
use std::borrow::Cow;
use std::collections::HashSet;
use std::fmt;
use std::mem;
use std::ops::Deref;
use stylearc::{Arc, UniqueArc};
use app_units::Au;
#[cfg(feature = "servo")] use cssparser::RGBA;
use cssparser::{Parser, TokenSerializationType, serialize_identifier};
use cssparser::{ParserInput, CompactCowStr};
#[cfg(feature = "servo")] use euclid::SideOffsets2D;
use computed_values;
use context::QuirksMode;
use error_reporting::NullReporter;
use font_metrics::FontMetricsProvider;
#[cfg(feature = "gecko")] use gecko_bindings::bindings;
#[cfg(feature = "gecko")] use gecko_bindings::structs::{self, nsCSSPropertyID};
#[cfg(feature = "servo")] use logical_geometry::{LogicalMargin, PhysicalSide};
use logical_geometry::WritingMode;
use media_queries::Device;
use parser::{Parse, ParserContext};
use properties::animated_properties::AnimatableLonghand;
#[cfg(feature = "gecko")] use properties::longhands::system_font::SystemFont;
use selectors::parser::SelectorParseError;
#[cfg(feature = "servo")] use servo_config::prefs::PREFS;
use shared_lock::StylesheetGuards;
use style_traits::{PARSING_MODE_DEFAULT, HasViewportPercentage, ToCss, ParseError};
use style_traits::{PropertyDeclarationParseError, StyleParseError};
use stylesheets::{CssRuleType, MallocSizeOf, MallocSizeOfFn, Origin, UrlExtraData};
#[cfg(feature = "servo")] use values::Either;
use values::generics::text::LineHeight;
use values::computed;
use cascade_info::CascadeInfo;
use rule_tree::{CascadeLevel, StrongRuleNode};
use self::computed_value_flags::ComputedValueFlags;
use style_adjuster::StyleAdjuster;
#[cfg(feature = "servo")] use values::specified::BorderStyle;
pub use self::declaration_block::*;
#[cfg(feature = "gecko")]
#[macro_export]
macro_rules! property_name {
($s: tt) => { atom!($s) }
}
#[cfg(feature = "gecko")]
macro_rules! impl_bitflags_conversions {
($name: ident) => {
impl From<u8> for $name {
fn from(bits: u8) -> $name {
$name::from_bits(bits).expect("bits contain valid flag")
}
}
impl From<$name> for u8 {
fn from(v: $name) -> u8 {
v.bits()
}
}
};
}
<%!
from data import Method, Keyword, to_rust_ident, to_camel_case, SYSTEM_FONT_LONGHANDS
import os.path
%>
#[path="${repr(os.path.join(os.path.dirname(__file__), 'computed_value_flags.rs'))[1:-1]}"]
pub mod computed_value_flags;
#[path="${repr(os.path.join(os.path.dirname(__file__), 'declaration_block.rs'))[1:-1]}"]
pub mod declaration_block;
/// Conversion with fewer impls than From/Into
pub trait MaybeBoxed<Out> {
/// Convert
fn maybe_boxed(self) -> Out;
}
/// This is where we store extra font data while
/// while computing font sizes.
#[derive(Clone, Debug)]
pub struct FontComputationData {
/// font-size keyword values (and font-size-relative values applied
/// to keyword values) need to preserve their identity as originating
/// from keywords and relative font sizes. We store this information
/// out of band in the ComputedValues. When None, the font size on the
/// current struct was computed from a value that was not a keyword
/// or a chain of font-size-relative values applying to successive parents
/// terminated by a keyword. When Some, this means the font-size was derived
/// from a keyword value or a keyword value on some ancestor with only
/// font-size-relative keywords and regular inheritance in between. The
/// integer stores the final ratio of the chain of font size relative values.
/// and is 1 when there was just a keyword and no relative values.
///
/// When this is Some, we compute font sizes by computing the keyword against
/// the generic font, and then multiplying it by the ratio.
pub font_size_keyword: Option<(longhands::font_size::KeywordSize, f32)>
}
impl FontComputationData{
/// Assigns values for variables in struct FontComputationData
pub fn new(font_size_keyword: Option<(longhands::font_size::KeywordSize, f32)>) -> Self {
FontComputationData {
font_size_keyword: font_size_keyword
}
}
/// Assigns default values for variables in struct FontComputationData
pub fn default_values() -> Self {
FontComputationData{
font_size_keyword: Some((Default::default(), 1.))
}
}
}
impl<T> MaybeBoxed<T> for T {
#[inline]
fn maybe_boxed(self) -> T { self }
}
impl<T> MaybeBoxed<Box<T>> for T {
#[inline]
fn maybe_boxed(self) -> Box<T> { Box::new(self) }
}
macro_rules! expanded {
( $( $name: ident: $value: expr ),+ ) => {
expanded!( $( $name: $value, )+ )
};
( $( $name: ident: $value: expr, )+ ) => {
Longhands {
$(
$name: MaybeBoxed::maybe_boxed($value),
)+
}
}
}
/// A module with all the code for longhand properties.
#[allow(missing_docs)]
pub mod longhands {
<%include file="/longhand/background.mako.rs" />
<%include file="/longhand/border.mako.rs" />
<%include file="/longhand/box.mako.rs" />
<%include file="/longhand/color.mako.rs" />
<%include file="/longhand/column.mako.rs" />
<%include file="/longhand/counters.mako.rs" />
<%include file="/longhand/effects.mako.rs" />
<%include file="/longhand/font.mako.rs" />
<%include file="/longhand/inherited_box.mako.rs" />
<%include file="/longhand/inherited_table.mako.rs" />
<%include file="/longhand/inherited_text.mako.rs" />
<%include file="/longhand/list.mako.rs" />
<%include file="/longhand/margin.mako.rs" />
<%include file="/longhand/outline.mako.rs" />
<%include file="/longhand/padding.mako.rs" />
<%include file="/longhand/pointing.mako.rs" />
<%include file="/longhand/position.mako.rs" />
<%include file="/longhand/table.mako.rs" />
<%include file="/longhand/text.mako.rs" />
<%include file="/longhand/ui.mako.rs" />
<%include file="/longhand/inherited_svg.mako.rs" />
<%include file="/longhand/svg.mako.rs" />
<%include file="/longhand/xul.mako.rs" />
}
macro_rules! unwrap_or_initial {
($prop: ident) => (unwrap_or_initial!($prop, $prop));
($prop: ident, $expr: expr) =>
($expr.unwrap_or_else(|| $prop::get_initial_specified_value()));
}
/// A module with code for all the shorthand css properties, and a few
/// serialization helpers.
#[allow(missing_docs)]
pub mod shorthands {
use cssparser::Parser;
use parser::{Parse, ParserContext};
use style_traits::{ParseError, StyleParseError};
use values::specified;
<%include file="/shorthand/serialize.mako.rs" />
<%include file="/shorthand/background.mako.rs" />
<%include file="/shorthand/border.mako.rs" />
<%include file="/shorthand/box.mako.rs" />
<%include file="/shorthand/column.mako.rs" />
<%include file="/shorthand/font.mako.rs" />
<%include file="/shorthand/inherited_text.mako.rs" />
<%include file="/shorthand/list.mako.rs" />
<%include file="/shorthand/margin.mako.rs" />
<%include file="/shorthand/mask.mako.rs" />
<%include file="/shorthand/outline.mako.rs" />
<%include file="/shorthand/padding.mako.rs" />
<%include file="/shorthand/position.mako.rs" />
<%include file="/shorthand/inherited_svg.mako.rs" />
<%include file="/shorthand/text.mako.rs" />
// We don't defined the 'all' shorthand using the regular helpers:shorthand
// mechanism, since it causes some very large types to be generated.
<% data.declare_shorthand("all",
[p.name for p in data.longhands if p.name not in ['direction', 'unicode-bidi']],
spec="https://drafts.csswg.org/css-cascade-3/#all-shorthand") %>
}
/// A module with all the code related to animated properties.
///
/// This needs to be "included" by mako at least after all longhand modules,
/// given they populate the global data.
pub mod animated_properties {
<%include file="/helpers/animated_properties.mako.rs" />
}
/// A longhand or shorthand porperty
#[derive(Copy, Clone, Debug)]
pub struct NonCustomPropertyId(usize);
impl From<LonghandId> for NonCustomPropertyId {
fn from(id: LonghandId) -> Self {
NonCustomPropertyId(id as usize)
}
}
impl From<ShorthandId> for NonCustomPropertyId {
fn from(id: ShorthandId) -> Self {
NonCustomPropertyId((id as usize) + ${len(data.longhands)})
}
}
/// A set of longhand properties
#[derive(Clone, PartialEq)]
pub struct NonCustomPropertyIdSet {
storage: [u32; (${len(data.longhands) + len(data.shorthands)} - 1 + 32) / 32]
}
impl NonCustomPropertyIdSet {
/// Return whether the given property is in the set
#[inline]
pub fn contains(&self, id: NonCustomPropertyId) -> bool {
let bit = id.0;
(self.storage[bit / 32] & (1 << (bit % 32))) != 0
}
}
<%def name="static_non_custom_property_id_set(name, is_member)">
static ${name}: NonCustomPropertyIdSet = NonCustomPropertyIdSet {
<%
storage = [0] * ((len(data.longhands) + len(data.shorthands) - 1 + 32) / 32)
for i, property in enumerate(data.longhands + data.shorthands):
if is_member(property):
storage[i / 32] |= 1 << (i % 32)
%>
storage: [${", ".join("0x%x" % word for word in storage)}]
};
</%def>
<%def name="static_longhand_id_set(name, is_member)">
static ${name}: LonghandIdSet = LonghandIdSet {
<%
storage = [0] * ((len(data.longhands) - 1 + 32) / 32)
for i, property in enumerate(data.longhands):
if is_member(property):
storage[i / 32] |= 1 << (i % 32)
%>
storage: [${", ".join("0x%x" % word for word in storage)}]
};
</%def>
/// A set of longhand properties
#[derive(Clone, PartialEq)]
pub struct LonghandIdSet {
storage: [u32; (${len(data.longhands)} - 1 + 32) / 32]
}
impl LonghandIdSet {
/// Create an empty set
#[inline]
pub fn new() -> LonghandIdSet {
LonghandIdSet { storage: [0; (${len(data.longhands)} - 1 + 32) / 32] }
}
/// Return whether the given property is in the set
#[inline]
pub fn contains(&self, id: LonghandId) -> bool {
let bit = id as usize;
(self.storage[bit / 32] & (1 << (bit % 32))) != 0
}
/// Add the given property to the set
#[inline]
pub fn insert(&mut self, id: LonghandId) {
let bit = id as usize;
self.storage[bit / 32] |= 1 << (bit % 32);
}
/// Remove the given property from the set
#[inline]
pub fn remove(&mut self, id: LonghandId) {
let bit = id as usize;
self.storage[bit / 32] &= !(1 << (bit % 32));
}
/// Clear all bits
#[inline]
pub fn clear(&mut self) {
for cell in &mut self.storage {
*cell = 0
}
}
/// Set the corresponding bit of AnimatableLonghand.
pub fn set_animatable_longhand_bit(&mut self, property: &AnimatableLonghand) {
match *property {
% for prop in data.longhands:
% if prop.animatable:
AnimatableLonghand::${prop.camel_case} => self.insert(LonghandId::${prop.camel_case}),
% endif
% endfor
}
}
/// Return true if the corresponding bit of AnimatableLonghand is set.
pub fn has_animatable_longhand_bit(&self, property: &AnimatableLonghand) -> bool {
match *property {
% for prop in data.longhands:
% if prop.animatable:
AnimatableLonghand::${prop.camel_case} => self.contains(LonghandId::${prop.camel_case}),
% endif
% endfor
}
}
}
/// A specialized set of PropertyDeclarationId
pub struct PropertyDeclarationIdSet {
longhands: LonghandIdSet,
// FIXME: Use a HashSet instead? This Vec is usually small, so linear scan might be ok.
custom: Vec<::custom_properties::Name>,
}
impl PropertyDeclarationIdSet {
/// Empty set
pub fn new() -> Self {
PropertyDeclarationIdSet {
longhands: LonghandIdSet::new(),
custom: Vec::new(),
}
}
/// Returns whether the given ID is in the set
pub fn contains(&mut self, id: PropertyDeclarationId) -> bool {
match id {
PropertyDeclarationId::Longhand(id) => self.longhands.contains(id),
PropertyDeclarationId::Custom(name) => self.custom.contains(name),
}
}
/// Insert the given ID in the set
pub fn insert(&mut self, id: PropertyDeclarationId) {
match id {
PropertyDeclarationId::Longhand(id) => self.longhands.insert(id),
PropertyDeclarationId::Custom(name) => {
if !self.custom.contains(name) {
self.custom.push(name.clone())
}
}
}
}
}
/// An enum to represent a CSS Wide keyword.
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
#[derive(Copy, Clone, Debug, Eq, PartialEq, ToCss)]
pub enum CSSWideKeyword {
/// The `initial` keyword.
Initial,
/// The `inherit` keyword.
Inherit,
/// The `unset` keyword.
Unset,
}
impl CSSWideKeyword {
fn to_str(&self) -> &'static str {
match *self {
CSSWideKeyword::Initial => "initial",
CSSWideKeyword::Inherit => "inherit",
CSSWideKeyword::Unset => "unset",
}
}
/// Takes the result of cssparser::Parser::expect_ident() and converts it
/// to a CSSWideKeyword.
pub fn from_ident<'i>(ident: &str) -> Option<Self> {
match_ignore_ascii_case! { ident,
// If modifying this set of keyword, also update values::CustomIdent::from_ident
"initial" => Some(CSSWideKeyword::Initial),
"inherit" => Some(CSSWideKeyword::Inherit),
"unset" => Some(CSSWideKeyword::Unset),
_ => None
}
}
}
impl Parse for CSSWideKeyword {
fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
let ident = input.expect_ident()?;
input.expect_exhausted()?;
CSSWideKeyword::from_ident(&ident)
.ok_or(SelectorParseError::UnexpectedIdent(ident).into())
}
}
bitflags! {
/// A set of flags for properties.
pub flags PropertyFlags: u8 {
/// This property requires a stacking context.
const CREATES_STACKING_CONTEXT = 1 << 0,
/// This property has values that can establish a containing block for
/// fixed positioned and absolutely positioned elements.
const FIXPOS_CB = 1 << 1,
/// This property has values that can establish a containing block for
/// absolutely positioned elements.
const ABSPOS_CB = 1 << 2,
/// This shorthand property is an alias of another property.
const SHORTHAND_ALIAS_PROPERTY = 1 << 3,
}
}
/// An identifier for a given longhand property.
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub enum LonghandId {
% for i, property in enumerate(data.longhands):
/// ${property.name}
${property.camel_case} = ${i},
% endfor
}
impl LonghandId {
/// Get the name of this longhand property.
pub fn name(&self) -> &'static str {
match *self {
% for property in data.longhands:
LonghandId::${property.camel_case} => "${property.name}",
% endfor
}
}
fn inherited(&self) -> bool {
${static_longhand_id_set("INHERITED", lambda p: p.style_struct.inherited)}
INHERITED.contains(*self)
}
fn shorthands(&self) -> &'static [ShorthandId] {
// first generate longhand to shorthands lookup map
//
// NOTE(emilio): This currently doesn't exclude the "all" shorthand. It
// could potentially do so, which would speed up serialization
// algorithms and what not, I guess.
<%
longhand_to_shorthand_map = {}
for shorthand in data.shorthands:
for sub_property in shorthand.sub_properties:
if sub_property.ident not in longhand_to_shorthand_map:
longhand_to_shorthand_map[sub_property.ident] = []
longhand_to_shorthand_map[sub_property.ident].append(shorthand.camel_case)
for shorthand_list in longhand_to_shorthand_map.itervalues():
shorthand_list.sort()
%>
// based on lookup results for each longhand, create result arrays
% for property in data.longhands:
static ${property.ident.upper()}: &'static [ShorthandId] = &[
% for shorthand in longhand_to_shorthand_map.get(property.ident, []):
ShorthandId::${shorthand},
% endfor
];
% endfor
match *self {
% for property in data.longhands:
LonghandId::${property.camel_case} => ${property.ident.upper()},
% endfor
}
}
fn parse_value<'i, 't>(&self, context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<PropertyDeclaration, ParseError<'i>> {
match *self {
% for property in data.longhands:
LonghandId::${property.camel_case} => {
% if not property.derived_from:
longhands::${property.ident}::parse_declared(context, input)
% else:
Err(PropertyDeclarationParseError::UnknownProperty.into())
% endif
}
% endfor
}
}
/// If this is a logical property, return the corresponding physical one in the given writing mode.
/// Otherwise, return unchanged.
pub fn to_physical(&self, wm: WritingMode) -> Self {
match *self {
% for property in data.longhands:
% if property.logical:
LonghandId::${property.camel_case} => {
<%helpers:logical_setter_helper name="${property.name}">
<%def name="inner(physical_ident)">
LonghandId::${to_camel_case(physical_ident)}
</%def>
</%helpers:logical_setter_helper>
}
% endif
% endfor
_ => *self
}
}
/// Returns PropertyFlags for given longhand property.
pub fn flags(&self) -> PropertyFlags {
match *self {
% for property in data.longhands:
LonghandId::${property.camel_case} =>
% for flag in property.flags:
${flag} |
% endfor
PropertyFlags::empty(),
% endfor
}
}
/// Only a few properties are allowed to depend on the visited state of
/// links. When cascading visited styles, we can save time by only
/// processing these properties.
fn is_visited_dependent(&self) -> bool {
matches!(*self,
% if product == "gecko":
LonghandId::ColumnRuleColor |
LonghandId::TextEmphasisColor |
LonghandId::WebkitTextFillColor |
LonghandId::WebkitTextStrokeColor |
LonghandId::TextDecorationColor |
LonghandId::Fill |
LonghandId::Stroke |
LonghandId::CaretColor |
% endif
LonghandId::Color |
LonghandId::BackgroundColor |
LonghandId::BorderTopColor |
LonghandId::BorderRightColor |
LonghandId::BorderBottomColor |
LonghandId::BorderLeftColor |
LonghandId::OutlineColor
)
}
/// Returns true if the property is one that is ignored when document
/// colors are disabled.
fn is_ignored_when_document_colors_disabled(&self) -> bool {
matches!(*self,
${" | ".join([("LonghandId::" + p.camel_case)
for p in data.longhands if p.ignored_when_colors_disabled])}
)
}
/// The computed value of some properties depends on the (sometimes
/// computed) value of *other* properties.
///
/// So we classify properties into "early" and "other", such that the only
/// dependencies can be from "other" to "early".
///
/// Unfortunately, it’s not easy to check that this classification is
/// correct.
fn is_early_property(&self) -> bool {
matches!(*self,
% if product == 'gecko':
LonghandId::TextOrientation |
LonghandId::AnimationName |
LonghandId::TransitionProperty |
LonghandId::XLang |
LonghandId::MozScriptLevel |
LonghandId::MozMinFontSizeRatio |
% endif
LonghandId::FontSize |
LonghandId::FontFamily |
LonghandId::Color |
LonghandId::TextDecorationLine |
LonghandId::WritingMode |
LonghandId::Direction
)
}
}
/// An identifier for a given shorthand property.
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
#[derive(Clone, Copy, Debug, Eq, PartialEq, ToCss)]
pub enum ShorthandId {
% for property in data.shorthands:
/// ${property.name}
${property.camel_case},
% endfor
}
impl ShorthandId {
/// Get the name for this shorthand property.
pub fn name(&self) -> &'static str {
match *self {
% for property in data.shorthands:
ShorthandId::${property.camel_case} => "${property.name}",
% endfor
}
}
/// Get the longhand ids that form this shorthand.
pub fn longhands(&self) -> &'static [LonghandId] {
% for property in data.shorthands:
static ${property.ident.upper()}: &'static [LonghandId] = &[
% for sub in property.sub_properties:
LonghandId::${sub.camel_case},
% endfor
];
% endfor
match *self {
% for property in data.shorthands:
ShorthandId::${property.camel_case} => ${property.ident.upper()},
% endfor
}
}
/// Try to serialize the given declarations as this shorthand.
///
/// Returns an error if writing to the stream fails, or if the declarations
/// do not map to a shorthand.
pub fn longhands_to_css<'a, W, I>(&self, declarations: I, dest: &mut W) -> fmt::Result
where W: fmt::Write,
I: Iterator<Item=&'a PropertyDeclaration>,
{
match *self {
ShorthandId::All => {
// No need to try to serialize the declarations as the 'all'
// shorthand, since it only accepts CSS-wide keywords (and
// variable references), which will be handled in
// get_shorthand_appendable_value.
Err(fmt::Error)
}
% for property in data.shorthands_except_all():
ShorthandId::${property.camel_case} => {
match shorthands::${property.ident}::LonghandsToSerialize::from_iter(declarations) {
Ok(longhands) => longhands.to_css(dest),
Err(_) => Err(fmt::Error)
}
},
% endfor
}
}
/// Finds and returns an appendable value for the given declarations.
///
/// Returns the optional appendable value.
pub fn get_shorthand_appendable_value<'a, I>(self,
declarations: I)
-> Option<AppendableValue<'a, I::IntoIter>>
where I: IntoIterator<Item=&'a PropertyDeclaration>,
I::IntoIter: Clone,
{
let declarations = declarations.into_iter();
// Only cloning iterators (a few pointers each) not declarations.
let mut declarations2 = declarations.clone();
let mut declarations3 = declarations.clone();
let first_declaration = match declarations2.next() {
Some(declaration) => declaration,
None => return None
};
// https://drafts.csswg.org/css-variables/#variables-in-shorthands
if let Some(css) = first_declaration.with_variables_from_shorthand(self) {
if declarations2.all(|d| d.with_variables_from_shorthand(self) == Some(css)) {
return Some(AppendableValue::Css {
css: css,
with_variables: true,
});
}
return None;
}
// Check whether they are all the same CSS-wide keyword.
if let Some(keyword) = first_declaration.get_css_wide_keyword() {
if declarations2.all(|d| d.get_css_wide_keyword() == Some(keyword)) {
return Some(AppendableValue::Css {
css: keyword.to_str(),
with_variables: false,
});
}
return None;
}
// Check whether all declarations can be serialized as part of shorthand.
if declarations3.all(|d| d.may_serialize_as_part_of_shorthand()) {
return Some(AppendableValue::DeclarationsForShorthand(self, declarations));
}
None
}
/// Returns PropertyFlags for given shorthand property.
pub fn flags(&self) -> PropertyFlags {
match *self {
% for property in data.shorthands:
ShorthandId::${property.camel_case} =>
% for flag in property.flags:
${flag} |
% endfor
PropertyFlags::empty(),
% endfor
}
}
fn parse_into<'i, 't>(&self, declarations: &mut SourcePropertyDeclaration,
context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<(), ParseError<'i>> {
match *self {
% for shorthand in data.shorthands_except_all():
ShorthandId::${shorthand.camel_case} => {
shorthands::${shorthand.ident}::parse_into(declarations, context, input)
}
% endfor
// 'all' accepts no value other than CSS-wide keywords
ShorthandId::All => Err(StyleParseError::UnspecifiedError.into())
}
}
}
/// Servo's representation of a declared value for a given `T`, which is the
/// declared value for that property.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum DeclaredValue<'a, T: 'a> {
/// A known specified value from the stylesheet.
Value(&'a T),
/// An unparsed value that contains `var()` functions.
WithVariables(&'a Arc<UnparsedValue>),
/// An CSS-wide keyword.
CSSWideKeyword(CSSWideKeyword),
}
/// A variant of DeclaredValue that owns its data. This separation exists so
/// that PropertyDeclaration can avoid embedding a DeclaredValue (and its
/// extra discriminant word) and synthesize dependent DeclaredValues for
/// PropertyDeclaration instances as needed.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum DeclaredValueOwned<T> {
/// A known specified value from the stylesheet.
Value(T),
/// An unparsed value that contains `var()` functions.
WithVariables(Arc<UnparsedValue>),
/// An CSS-wide keyword.
CSSWideKeyword(CSSWideKeyword),
}
impl<T> DeclaredValueOwned<T> {
/// Creates a dependent DeclaredValue from this DeclaredValueOwned.
fn borrow(&self) -> DeclaredValue<T> {
match *self {
DeclaredValueOwned::Value(ref v) => DeclaredValue::Value(v),
DeclaredValueOwned::WithVariables(ref v) => DeclaredValue::WithVariables(v),
DeclaredValueOwned::CSSWideKeyword(v) => DeclaredValue::CSSWideKeyword(v),
}
}
}
/// An unparsed property value that contains `var()` functions.
#[derive(PartialEq, Eq, Debug)]
pub struct UnparsedValue {
/// The css serialization for this value.
css: String,
/// The first token type for this serialization.
first_token_type: TokenSerializationType,
/// The url data for resolving url values.
url_data: UrlExtraData,
/// The shorthand this came from.
from_shorthand: Option<ShorthandId>,
}
impl UnparsedValue {
fn substitute_variables(&self, longhand_id: LonghandId,
custom_properties: &Option<Arc<::custom_properties::CustomPropertiesMap>>,
quirks_mode: QuirksMode)
-> PropertyDeclaration {
::custom_properties::substitute(&self.css, self.first_token_type, custom_properties)
.ok()
.and_then(|css| {
// As of this writing, only the base URL is used for property values:
let reporter = NullReporter;
let context = ParserContext::new(Origin::Author,
&self.url_data,
&reporter,
None,
PARSING_MODE_DEFAULT,
quirks_mode);
let mut input = ParserInput::new(&css);
Parser::new(&mut input).parse_entirely(|input| {
match self.from_shorthand {
None => longhand_id.parse_value(&context, input),
Some(ShorthandId::All) => {
// No need to parse the 'all' shorthand as anything other than a CSS-wide
// keyword, after variable substitution.
Err(SelectorParseError::UnexpectedIdent("all".into()).into())
}
% for shorthand in data.shorthands_except_all():
Some(ShorthandId::${shorthand.camel_case}) => {
shorthands::${shorthand.ident}::parse_value(&context, input)
.map(|longhands| {
match longhand_id {
% for property in shorthand.sub_properties:
LonghandId::${property.camel_case} => {
PropertyDeclaration::${property.camel_case}(
longhands.${property.ident}
)
}
% endfor
_ => unreachable!()
}
})
}
% endfor
}
})
.ok()
})
.unwrap_or_else(|| {
// Invalid at computed-value time.
let keyword = if longhand_id.inherited() {
CSSWideKeyword::Inherit
} else {
CSSWideKeyword::Initial
};
PropertyDeclaration::CSSWideKeyword(longhand_id, keyword)
})
}
}
impl<'a, T: HasViewportPercentage> HasViewportPercentage for DeclaredValue<'a, T> {
fn has_viewport_percentage(&self) -> bool {
match *self {
DeclaredValue::Value(ref v) => v.has_viewport_percentage(),
DeclaredValue::WithVariables(_) => {
panic!("DeclaredValue::has_viewport_percentage without \
resolving variables!")
},
DeclaredValue::CSSWideKeyword(_) => false,
}
}
}
impl<'a, T: ToCss> ToCss for DeclaredValue<'a, T> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where W: fmt::Write,
{
match *self {
DeclaredValue::Value(ref inner) => inner.to_css(dest),
DeclaredValue::WithVariables(ref with_variables) => {
// https://drafts.csswg.org/css-variables/#variables-in-shorthands
if with_variables.from_shorthand.is_none() {
dest.write_str(&*with_variables.css)?
}
Ok(())
},
DeclaredValue::CSSWideKeyword(ref keyword) => keyword.to_css(dest),
}
}
}
/// An identifier for a given property declaration, which can be either a
/// longhand or a custom property.
#[derive(PartialEq, Clone, Copy)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub enum PropertyDeclarationId<'a> {
/// A longhand.
Longhand(LonghandId),
/// A custom property declaration.
Custom(&'a ::custom_properties::Name),
}
impl<'a> ToCss for PropertyDeclarationId<'a> {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where W: fmt::Write,
{
match *self {
PropertyDeclarationId::Longhand(id) => dest.write_str(id.name()),
PropertyDeclarationId::Custom(_) => {
serialize_identifier(&self.name(), dest)
}
}
}
}
impl<'a> PropertyDeclarationId<'a> {
/// Whether a given declaration id is either the same as `other`, or a
/// longhand of it.
pub fn is_or_is_longhand_of(&self, other: &PropertyId) -> bool {
match *self {
PropertyDeclarationId::Longhand(id) => {
match *other {
PropertyId::Longhand(other_id) => id == other_id,
PropertyId::Shorthand(shorthand) => self.is_longhand_of(shorthand),
PropertyId::Custom(_) => false,
}
}
PropertyDeclarationId::Custom(name) => {
matches!(*other, PropertyId::Custom(ref other_name) if name == other_name)
}
}
}
/// Whether a given declaration id is a longhand belonging to this
/// shorthand.
pub fn is_longhand_of(&self, shorthand: ShorthandId) -> bool {
match *self {
PropertyDeclarationId::Longhand(ref id) => id.shorthands().contains(&shorthand),
_ => false,
}
}
/// Returns the name of the property without CSS escaping.
pub fn name(&self) -> Cow<'static, str> {
match *self {
PropertyDeclarationId::Longhand(id) => id.name().into(),
PropertyDeclarationId::Custom(name) => {
use std::fmt::Write;
let mut s = String::new();
write!(&mut s, "--{}", name).unwrap();
s.into()
}
}
}
}
/// Servo's representation of a CSS property, that is, either a longhand, a
/// shorthand, or a custom property.
#[derive(Eq, PartialEq, Clone)]
pub enum PropertyId {
/// A longhand property.
Longhand(LonghandId),
/// A shorthand property.
Shorthand(ShorthandId),
/// A custom property.
Custom(::custom_properties::Name),
}
impl fmt::Debug for PropertyId {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
self.to_css(formatter)
}
}
impl ToCss for PropertyId {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where W: fmt::Write,
{
match *self {
PropertyId::Longhand(id) => dest.write_str(id.name()),
PropertyId::Shorthand(id) => dest.write_str(id.name()),
PropertyId::Custom(_) => {
serialize_identifier(&self.name(), dest)
}
}
}
}
impl PropertyId {
/// Returns a given property from the string `s`.
///
/// Returns Err(()) for unknown non-custom properties
pub fn parse<'i>(property_name: CompactCowStr<'i>) -> Result<Self, ParseError<'i>> {
if let Ok(name) = ::custom_properties::parse_name(&property_name) {
return Ok(PropertyId::Custom(::custom_properties::Name::from(name)))
}
// FIXME(https://github.com/rust-lang/rust/issues/33156): remove this enum and use PropertyId