stylo 0.17.0

The Stylo CSS engine
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
/* 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 https://mozilla.org/MPL/2.0/. */

//! Specified types for text properties.

use crate::derives::*;
use crate::parser::{Parse, ParserContext};
use crate::properties::longhands::writing_mode::computed_value::T as SpecifiedWritingMode;
use crate::values::computed;
use crate::values::computed::text::TextEmphasisStyle as ComputedTextEmphasisStyle;
use crate::values::computed::{Context, ToComputedValue};
use crate::values::generics::text::{
    GenericHyphenateLimitChars, GenericInitialLetter, GenericTextDecorationInset,
    GenericTextDecorationLength, GenericTextIndent,
};
use crate::values::generics::NumberOrAuto;
use crate::values::specified::length::{Length, LengthPercentage};
use crate::values::specified::{AllowQuirks, Integer, Number};
use crate::Zero;
use cssparser::Parser;
use icu_segmenter::GraphemeClusterSegmenter;
use std::fmt::{self, Write};
use style_traits::values::SequenceWriter;
use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
use style_traits::{KeywordsCollectFn, SpecifiedValueInfo};

/// A specified type for the `initial-letter` property.
pub type InitialLetter = GenericInitialLetter<Number, Integer>;

/// A spacing value used by either the `letter-spacing` or `word-spacing` properties.
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss, ToShmem, ToTyped)]
pub enum Spacing {
    /// `normal`
    Normal,
    /// `<value>`
    Value(LengthPercentage),
}

impl Parse for Spacing {
    fn parse<'i, 't>(
        context: &ParserContext,
        input: &mut Parser<'i, 't>,
    ) -> Result<Self, ParseError<'i>> {
        if input
            .try_parse(|i| i.expect_ident_matching("normal"))
            .is_ok()
        {
            return Ok(Spacing::Normal);
        }
        LengthPercentage::parse_quirky(context, input, AllowQuirks::Yes).map(Spacing::Value)
    }
}

/// A specified value for the `letter-spacing` property.
#[derive(
    Clone, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss, ToShmem, ToTyped,
)]
pub struct LetterSpacing(pub Spacing);

impl ToComputedValue for LetterSpacing {
    type ComputedValue = computed::LetterSpacing;

    fn to_computed_value(&self, context: &Context) -> Self::ComputedValue {
        use computed::text::GenericLetterSpacing;
        match self.0 {
            Spacing::Normal => GenericLetterSpacing(computed::LengthPercentage::zero()),
            Spacing::Value(ref v) => GenericLetterSpacing(v.to_computed_value(context)),
        }
    }

    fn from_computed_value(computed: &Self::ComputedValue) -> Self {
        if computed.0.is_zero() {
            return LetterSpacing(Spacing::Normal);
        }
        LetterSpacing(Spacing::Value(ToComputedValue::from_computed_value(
            &computed.0,
        )))
    }
}

/// A specified value for the `word-spacing` property.
#[derive(
    Clone, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss, ToShmem, ToTyped,
)]
pub struct WordSpacing(pub Spacing);

impl ToComputedValue for WordSpacing {
    type ComputedValue = computed::WordSpacing;

    fn to_computed_value(&self, context: &Context) -> Self::ComputedValue {
        match self.0 {
            Spacing::Normal => computed::LengthPercentage::zero(),
            Spacing::Value(ref v) => v.to_computed_value(context),
        }
    }

    fn from_computed_value(computed: &Self::ComputedValue) -> Self {
        WordSpacing(Spacing::Value(ToComputedValue::from_computed_value(
            computed,
        )))
    }
}

/// A value for the `hyphenate-character` property.
#[derive(
    Clone,
    Debug,
    MallocSizeOf,
    Parse,
    PartialEq,
    SpecifiedValueInfo,
    ToComputedValue,
    ToCss,
    ToResolvedValue,
    ToShmem,
    ToTyped,
)]
#[repr(C, u8)]
#[typed(todo_derive_fields)]
pub enum HyphenateCharacter {
    /// `auto`
    Auto,
    /// `<string>`
    String(crate::OwnedStr),
}

/// A value for the `hyphenate-limit-chars` property.
pub type HyphenateLimitChars = GenericHyphenateLimitChars<Integer>;

impl Parse for HyphenateLimitChars {
    fn parse<'i, 't>(
        context: &ParserContext,
        input: &mut Parser<'i, 't>,
    ) -> Result<Self, ParseError<'i>> {
        type IntegerOrAuto = NumberOrAuto<Integer>;

        let total_word_length = IntegerOrAuto::parse(context, input)?;
        let pre_hyphen_length = input
            .try_parse(|i| IntegerOrAuto::parse(context, i))
            .unwrap_or(IntegerOrAuto::Auto);
        let post_hyphen_length = input
            .try_parse(|i| IntegerOrAuto::parse(context, i))
            .unwrap_or(pre_hyphen_length);
        Ok(Self {
            total_word_length,
            pre_hyphen_length,
            post_hyphen_length,
        })
    }
}

impl Parse for InitialLetter {
    fn parse<'i, 't>(
        context: &ParserContext,
        input: &mut Parser<'i, 't>,
    ) -> Result<Self, ParseError<'i>> {
        if input
            .try_parse(|i| i.expect_ident_matching("normal"))
            .is_ok()
        {
            return Ok(Self::normal());
        }
        let size = Number::parse_at_least_one(context, input)?;
        let sink = input
            .try_parse(|i| Integer::parse_positive(context, i))
            .unwrap_or_else(|_| crate::Zero::zero());
        Ok(Self { size, sink })
    }
}

/// A generic value for the `text-overflow` property.
#[derive(
    Clone,
    Debug,
    Eq,
    MallocSizeOf,
    PartialEq,
    Parse,
    SpecifiedValueInfo,
    ToComputedValue,
    ToCss,
    ToResolvedValue,
    ToShmem,
)]
#[repr(C, u8)]
pub enum TextOverflowSide {
    /// Clip inline content.
    Clip,
    /// Render ellipsis to represent clipped inline content.
    Ellipsis,
    /// Render a given string to represent clipped inline content.
    String(crate::values::AtomString),
}

#[derive(
    Clone,
    Debug,
    Eq,
    MallocSizeOf,
    PartialEq,
    SpecifiedValueInfo,
    ToComputedValue,
    ToResolvedValue,
    ToShmem,
    ToTyped,
)]
#[repr(C)]
#[typed(todo_derive_fields)]
/// text-overflow.
/// When the specified value only has one side, that's the "second"
/// side, and the sides are logical, so "second" means "end".  The
/// start side is Clip in that case.
///
/// When the specified value has two sides, those are our "first"
/// and "second" sides, and they are physical sides ("left" and
/// "right").
pub struct TextOverflow {
    /// First side
    pub first: TextOverflowSide,
    /// Second side
    pub second: TextOverflowSide,
    /// True if the specified value only has one side.
    pub sides_are_logical: bool,
}

impl Parse for TextOverflow {
    fn parse<'i, 't>(
        context: &ParserContext,
        input: &mut Parser<'i, 't>,
    ) -> Result<TextOverflow, ParseError<'i>> {
        let first = TextOverflowSide::parse(context, input)?;
        Ok(
            if let Ok(second) = input.try_parse(|input| TextOverflowSide::parse(context, input)) {
                Self {
                    first,
                    second,
                    sides_are_logical: false,
                }
            } else {
                Self {
                    first: TextOverflowSide::Clip,
                    second: first,
                    sides_are_logical: true,
                }
            },
        )
    }
}

impl TextOverflow {
    /// Returns the initial `text-overflow` value
    pub fn get_initial_value() -> TextOverflow {
        TextOverflow {
            first: TextOverflowSide::Clip,
            second: TextOverflowSide::Clip,
            sides_are_logical: true,
        }
    }
}

impl ToCss for TextOverflow {
    fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
    where
        W: Write,
    {
        if self.sides_are_logical {
            debug_assert_eq!(self.first, TextOverflowSide::Clip);
            self.second.to_css(dest)?;
        } else {
            self.first.to_css(dest)?;
            dest.write_char(' ')?;
            self.second.to_css(dest)?;
        }
        Ok(())
    }
}

#[derive(
    Clone,
    Copy,
    Debug,
    Eq,
    MallocSizeOf,
    PartialEq,
    Parse,
    Serialize,
    SpecifiedValueInfo,
    ToCss,
    ToComputedValue,
    ToResolvedValue,
    ToShmem,
    ToTyped,
)]
#[cfg_attr(
    feature = "gecko",
    css(bitflags(
        single = "none,spelling-error,grammar-error",
        mixed = "underline,overline,line-through,blink",
    ))
)]
#[cfg_attr(
    not(feature = "gecko"),
    css(bitflags(single = "none", mixed = "underline,overline,line-through,blink",))
)]
#[repr(C)]
/// Specified keyword values for the text-decoration-line property.
pub struct TextDecorationLine(u8);
bitflags! {
    impl TextDecorationLine: u8 {
        /// No text decoration line is specified.
        const NONE = 0;
        /// underline
        const UNDERLINE = 1 << 0;
        /// overline
        const OVERLINE = 1 << 1;
        /// line-through
        const LINE_THROUGH = 1 << 2;
        /// blink
        const BLINK = 1 << 3;
        /// spelling-error
        const SPELLING_ERROR = 1 << 4;
        /// grammar-error
        const GRAMMAR_ERROR = 1 << 5;
        /// Only set by presentation attributes
        ///
        /// Setting this will mean that text-decorations use the color
        /// specified by `color` in quirks mode.
        ///
        /// For example, this gives <a href=foo><font color="red">text</font></a>
        /// a red text decoration
        #[cfg(feature = "gecko")]
        const COLOR_OVERRIDE = 1 << 7;
    }
}

impl Default for TextDecorationLine {
    fn default() -> Self {
        TextDecorationLine::NONE
    }
}

impl TextDecorationLine {
    #[inline]
    /// Returns the initial value of text-decoration-line
    pub fn none() -> Self {
        TextDecorationLine::NONE
    }
}

#[derive(
    Clone,
    Copy,
    Debug,
    Eq,
    MallocSizeOf,
    PartialEq,
    SpecifiedValueInfo,
    ToComputedValue,
    ToCss,
    ToResolvedValue,
    ToShmem,
)]
#[repr(C)]
/// Specified keyword values for case transforms in the text-transform property. (These are exclusive.)
pub enum TextTransformCase {
    /// No case transform.
    None,
    /// All uppercase.
    Uppercase,
    /// All lowercase.
    Lowercase,
    /// Capitalize each word.
    Capitalize,
    /// Automatic italicization of math variables.
    #[cfg(feature = "gecko")]
    MathAuto,
}

#[derive(
    Clone,
    Copy,
    Debug,
    Eq,
    MallocSizeOf,
    PartialEq,
    Parse,
    Serialize,
    SpecifiedValueInfo,
    ToCss,
    ToComputedValue,
    ToResolvedValue,
    ToShmem,
    ToTyped,
)]
#[cfg_attr(
    feature = "gecko",
    css(bitflags(
        single = "none,math-auto",
        mixed = "uppercase,lowercase,capitalize,full-width,full-size-kana",
        validate_mixed = "Self::validate_mixed_flags",
    ))
)]
#[cfg_attr(
    not(feature = "gecko"),
    css(bitflags(
        single = "none",
        mixed = "uppercase,lowercase,capitalize,full-width,full-size-kana",
        validate_mixed = "Self::validate_mixed_flags",
    ))
)]
#[repr(C)]
/// Specified value for the text-transform property.
/// (The spec grammar gives
/// `none | math-auto | [capitalize | uppercase | lowercase] || full-width || full-size-kana`.)
/// https://drafts.csswg.org/css-text-4/#text-transform-property
pub struct TextTransform(u8);
bitflags! {
    impl TextTransform: u8 {
        /// none
        const NONE = 0;
        /// All uppercase.
        const UPPERCASE = 1 << 0;
        /// All lowercase.
        const LOWERCASE = 1 << 1;
        /// Capitalize each word.
        const CAPITALIZE = 1 << 2;
        /// Automatic italicization of math variables.
        #[cfg(feature = "gecko")]
        const MATH_AUTO = 1 << 3;

        /// All the case transforms, which are exclusive with each other.
        #[cfg(feature = "gecko")]
        const CASE_TRANSFORMS = Self::UPPERCASE.0 | Self::LOWERCASE.0 | Self::CAPITALIZE.0 | Self::MATH_AUTO.0;
        /// All the case transforms, which are exclusive with each other.
        #[cfg(feature = "servo")]
        const CASE_TRANSFORMS = Self::UPPERCASE.0 | Self::LOWERCASE.0 | Self::CAPITALIZE.0;

        /// full-width
        const FULL_WIDTH = 1 << 4;
        /// full-size-kana
        const FULL_SIZE_KANA = 1 << 5;
    }
}

impl TextTransform {
    /// Returns the initial value of text-transform
    #[inline]
    pub fn none() -> Self {
        Self::NONE
    }

    /// Returns whether the value is 'none'
    #[inline]
    pub fn is_none(self) -> bool {
        self == Self::NONE
    }

    fn validate_mixed_flags(&self) -> bool {
        let case = self.intersection(Self::CASE_TRANSFORMS);
        // Case bits are exclusive with each other.
        case.is_empty() || case.bits().is_power_of_two()
    }

    /// Returns the corresponding TextTransformCase.
    pub fn case(&self) -> TextTransformCase {
        match *self & Self::CASE_TRANSFORMS {
            Self::NONE => TextTransformCase::None,
            Self::UPPERCASE => TextTransformCase::Uppercase,
            Self::LOWERCASE => TextTransformCase::Lowercase,
            Self::CAPITALIZE => TextTransformCase::Capitalize,
            #[cfg(feature = "gecko")]
            Self::MATH_AUTO => TextTransformCase::MathAuto,
            _ => unreachable!("Case bits are exclusive with each other"),
        }
    }
}

/// Specified and computed value of text-align-last.
#[derive(
    Clone,
    Copy,
    Debug,
    Eq,
    FromPrimitive,
    Hash,
    MallocSizeOf,
    Parse,
    PartialEq,
    SpecifiedValueInfo,
    ToComputedValue,
    ToCss,
    ToResolvedValue,
    ToShmem,
    ToTyped,
)]
#[allow(missing_docs)]
#[repr(u8)]
pub enum TextAlignLast {
    Auto,
    Start,
    End,
    Left,
    Right,
    Center,
    Justify,
}

/// Specified value of text-align keyword value.
#[derive(
    Clone,
    Copy,
    Debug,
    Eq,
    FromPrimitive,
    Hash,
    MallocSizeOf,
    Parse,
    PartialEq,
    SpecifiedValueInfo,
    ToComputedValue,
    ToCss,
    ToResolvedValue,
    ToShmem,
    ToTyped,
)]
#[allow(missing_docs)]
#[repr(u8)]
pub enum TextAlignKeyword {
    Start,
    Left,
    Right,
    Center,
    Justify,
    End,
    #[parse(aliases = "-webkit-center")]
    MozCenter,
    #[parse(aliases = "-webkit-left")]
    MozLeft,
    #[parse(aliases = "-webkit-right")]
    MozRight,
}

/// Specified value of text-align property.
#[derive(
    Clone,
    Copy,
    Debug,
    Eq,
    Hash,
    MallocSizeOf,
    Parse,
    PartialEq,
    SpecifiedValueInfo,
    ToCss,
    ToShmem,
    ToTyped,
)]
#[typed(todo_derive_fields)]
pub enum TextAlign {
    /// Keyword value of text-align property.
    Keyword(TextAlignKeyword),
    /// `match-parent` value of text-align property. It has a different handling
    /// unlike other keywords.
    MatchParent,
    /// This is how we implement the following HTML behavior from
    /// https://html.spec.whatwg.org/#tables-2:
    ///
    ///     User agents are expected to have a rule in their user agent style sheet
    ///     that matches th elements that have a parent node whose computed value
    ///     for the 'text-align' property is its initial value, whose declaration
    ///     block consists of just a single declaration that sets the 'text-align'
    ///     property to the value 'center'.
    ///
    /// Since selectors can't depend on the ancestor styles, we implement it with a
    /// magic value that computes to the right thing. Since this is an
    /// implementation detail, it shouldn't be exposed to web content.
    #[parse(condition = "ParserContext::chrome_rules_enabled")]
    MozCenterOrInherit,
}

impl ToComputedValue for TextAlign {
    type ComputedValue = TextAlignKeyword;

    #[inline]
    fn to_computed_value(&self, _context: &Context) -> Self::ComputedValue {
        match *self {
            TextAlign::Keyword(key) => key,
            TextAlign::MatchParent => {
                // on the root <html> element we should still respect the dir
                // but the parent dir of that element is LTR even if it's <html dir=rtl>
                // and will only be RTL if certain prefs have been set.
                // In that case, the default behavior here will set it to left,
                // but we want to set it to right -- instead set it to the default (`start`),
                // which will do the right thing in this case (but not the general case)
                if _context.builder.is_root_element {
                    return TextAlignKeyword::Start;
                }
                let parent = _context
                    .builder
                    .get_parent_inherited_text()
                    .clone_text_align();
                let ltr = _context.builder.inherited_writing_mode().is_bidi_ltr();
                match (parent, ltr) {
                    (TextAlignKeyword::Start, true) => TextAlignKeyword::Left,
                    (TextAlignKeyword::Start, false) => TextAlignKeyword::Right,
                    (TextAlignKeyword::End, true) => TextAlignKeyword::Right,
                    (TextAlignKeyword::End, false) => TextAlignKeyword::Left,
                    _ => parent,
                }
            },
            TextAlign::MozCenterOrInherit => {
                let parent = _context
                    .builder
                    .get_parent_inherited_text()
                    .clone_text_align();
                if parent == TextAlignKeyword::Start {
                    TextAlignKeyword::Center
                } else {
                    parent
                }
            },
        }
    }

    #[inline]
    fn from_computed_value(computed: &Self::ComputedValue) -> Self {
        TextAlign::Keyword(*computed)
    }
}

fn fill_mode_is_default_and_shape_exists(
    fill: &TextEmphasisFillMode,
    shape: &Option<TextEmphasisShapeKeyword>,
) -> bool {
    shape.is_some() && fill.is_filled()
}

/// Specified value of text-emphasis-style property.
///
/// https://drafts.csswg.org/css-text-decor/#propdef-text-emphasis-style
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss, ToShmem, ToTyped)]
#[allow(missing_docs)]
#[typed(todo_derive_fields)]
pub enum TextEmphasisStyle {
    /// [ <fill> || <shape> ]
    Keyword {
        #[css(contextual_skip_if = "fill_mode_is_default_and_shape_exists")]
        fill: TextEmphasisFillMode,
        shape: Option<TextEmphasisShapeKeyword>,
    },
    /// `none`
    None,
    /// `<string>` (of which only the first grapheme cluster will be used).
    String(crate::OwnedStr),
}

/// Fill mode for the text-emphasis-style property
#[derive(
    Clone,
    Copy,
    Debug,
    MallocSizeOf,
    Parse,
    PartialEq,
    SpecifiedValueInfo,
    ToCss,
    ToComputedValue,
    ToResolvedValue,
    ToShmem,
)]
#[repr(u8)]
pub enum TextEmphasisFillMode {
    /// `filled`
    Filled,
    /// `open`
    Open,
}

impl TextEmphasisFillMode {
    /// Whether the value is `filled`.
    #[inline]
    pub fn is_filled(&self) -> bool {
        matches!(*self, TextEmphasisFillMode::Filled)
    }
}

/// Shape keyword for the text-emphasis-style property
#[derive(
    Clone,
    Copy,
    Debug,
    Eq,
    MallocSizeOf,
    Parse,
    PartialEq,
    SpecifiedValueInfo,
    ToCss,
    ToComputedValue,
    ToResolvedValue,
    ToShmem,
)]
#[repr(u8)]
pub enum TextEmphasisShapeKeyword {
    /// `dot`
    Dot,
    /// `circle`
    Circle,
    /// `double-circle`
    DoubleCircle,
    /// `triangle`
    Triangle,
    /// `sesame`
    Sesame,
}

impl ToComputedValue for TextEmphasisStyle {
    type ComputedValue = ComputedTextEmphasisStyle;

    #[inline]
    fn to_computed_value(&self, context: &Context) -> Self::ComputedValue {
        match *self {
            TextEmphasisStyle::Keyword { fill, shape } => {
                let shape = shape.unwrap_or_else(|| {
                    // FIXME(emilio, bug 1572958): This should set the
                    // rule_cache_conditions properly.
                    //
                    // Also should probably use WritingMode::is_vertical rather
                    // than the computed value of the `writing-mode` property.
                    if context.style().get_inherited_box().clone_writing_mode()
                        == SpecifiedWritingMode::HorizontalTb
                    {
                        TextEmphasisShapeKeyword::Circle
                    } else {
                        TextEmphasisShapeKeyword::Sesame
                    }
                });
                ComputedTextEmphasisStyle::Keyword { fill, shape }
            },
            TextEmphasisStyle::None => ComputedTextEmphasisStyle::None,
            TextEmphasisStyle::String(ref s) => {
                // FIXME(emilio): Doing this at computed value time seems wrong.
                // The spec doesn't say that this should be a computed-value
                // time operation. This is observable from getComputedStyle().
                //
                // Note that the first grapheme cluster boundary should always be the start of the string.
                let first_grapheme_end = GraphemeClusterSegmenter::new()
                    .segment_str(s)
                    .nth(1)
                    .unwrap_or(0);
                ComputedTextEmphasisStyle::String(s[0..first_grapheme_end].to_string().into())
            },
        }
    }

    #[inline]
    fn from_computed_value(computed: &Self::ComputedValue) -> Self {
        match *computed {
            ComputedTextEmphasisStyle::Keyword { fill, shape } => TextEmphasisStyle::Keyword {
                fill,
                shape: Some(shape),
            },
            ComputedTextEmphasisStyle::None => TextEmphasisStyle::None,
            ComputedTextEmphasisStyle::String(ref string) => {
                TextEmphasisStyle::String(string.clone())
            },
        }
    }
}

impl Parse for TextEmphasisStyle {
    fn parse<'i, 't>(
        _context: &ParserContext,
        input: &mut Parser<'i, 't>,
    ) -> Result<Self, ParseError<'i>> {
        if input
            .try_parse(|input| input.expect_ident_matching("none"))
            .is_ok()
        {
            return Ok(TextEmphasisStyle::None);
        }

        if let Ok(s) = input.try_parse(|i| i.expect_string().map(|s| s.as_ref().to_owned())) {
            // Handle <string>
            return Ok(TextEmphasisStyle::String(s.into()));
        }

        // Handle a pair of keywords
        let mut shape = input.try_parse(TextEmphasisShapeKeyword::parse).ok();
        let fill = input.try_parse(TextEmphasisFillMode::parse).ok();
        if shape.is_none() {
            shape = input.try_parse(TextEmphasisShapeKeyword::parse).ok();
        }

        if shape.is_none() && fill.is_none() {
            return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError));
        }

        // If a shape keyword is specified but neither filled nor open is
        // specified, filled is assumed.
        let fill = fill.unwrap_or(TextEmphasisFillMode::Filled);

        // We cannot do the same because the default `<shape>` depends on the
        // computed writing-mode.
        Ok(TextEmphasisStyle::Keyword { fill, shape })
    }
}

#[derive(
    Clone,
    Copy,
    Debug,
    Eq,
    MallocSizeOf,
    PartialEq,
    Parse,
    Serialize,
    SpecifiedValueInfo,
    ToCss,
    ToComputedValue,
    ToResolvedValue,
    ToShmem,
    ToTyped,
)]
#[repr(C)]
#[css(bitflags(
    single = "auto",
    mixed = "over,under,left,right",
    validate_mixed = "Self::validate_and_simplify"
))]
/// Values for text-emphasis-position:
/// <https://drafts.csswg.org/css-text-decor/#text-emphasis-position-property>
pub struct TextEmphasisPosition(u8);
bitflags! {
    impl TextEmphasisPosition: u8 {
        /// Automatically choose mark position based on language.
        const AUTO = 1 << 0;
        /// Draw marks over the text in horizontal writing mode.
        const OVER = 1 << 1;
        /// Draw marks under the text in horizontal writing mode.
        const UNDER = 1 << 2;
        /// Draw marks to the left of the text in vertical writing mode.
        const LEFT = 1 << 3;
        /// Draw marks to the right of the text in vertical writing mode.
        const RIGHT = 1 << 4;
    }
}

impl TextEmphasisPosition {
    fn validate_and_simplify(&mut self) -> bool {
        // Require one but not both of 'over' and 'under'.
        if self.intersects(Self::OVER) == self.intersects(Self::UNDER) {
            return false;
        }

        // If 'left' is present, 'right' must be absent.
        if self.intersects(Self::LEFT) {
            return !self.intersects(Self::RIGHT);
        }

        self.remove(Self::RIGHT); // Right is the default
        true
    }
}

/// Values for the `word-break` property.
#[repr(u8)]
#[derive(
    Clone,
    Copy,
    Debug,
    Eq,
    MallocSizeOf,
    Parse,
    PartialEq,
    SpecifiedValueInfo,
    ToComputedValue,
    ToCss,
    ToResolvedValue,
    ToShmem,
    ToTyped,
)]
#[allow(missing_docs)]
pub enum WordBreak {
    Normal,
    BreakAll,
    KeepAll,
    /// The break-word value, needed for compat.
    ///
    /// Specifying `word-break: break-word` makes `overflow-wrap` behave as
    /// `anywhere`, and `word-break` behave like `normal`.
    #[cfg(feature = "gecko")]
    BreakWord,
}

/// Values for the `text-justify` CSS property.
#[repr(u8)]
#[derive(
    Clone,
    Copy,
    Debug,
    Eq,
    MallocSizeOf,
    Parse,
    PartialEq,
    SpecifiedValueInfo,
    ToComputedValue,
    ToCss,
    ToResolvedValue,
    ToShmem,
    ToTyped,
)]
#[allow(missing_docs)]
pub enum TextJustify {
    Auto,
    None,
    InterWord,
    // See https://drafts.csswg.org/css-text-3/#valdef-text-justify-distribute
    // and https://github.com/w3c/csswg-drafts/issues/6156 for the alias.
    #[parse(aliases = "distribute")]
    InterCharacter,
}

/// Values for the `-moz-control-character-visibility` CSS property.
#[repr(u8)]
#[derive(
    Clone,
    Copy,
    Debug,
    Eq,
    MallocSizeOf,
    Parse,
    PartialEq,
    SpecifiedValueInfo,
    ToComputedValue,
    ToCss,
    ToResolvedValue,
    ToShmem,
    ToTyped,
)]
#[allow(missing_docs)]
pub enum MozControlCharacterVisibility {
    Hidden,
    Visible,
}

#[cfg(feature = "gecko")]
impl Default for MozControlCharacterVisibility {
    fn default() -> Self {
        if static_prefs::pref!("layout.css.control-characters.visible") {
            Self::Visible
        } else {
            Self::Hidden
        }
    }
}

/// Values for the `line-break` property.
#[repr(u8)]
#[derive(
    Clone,
    Copy,
    Debug,
    Eq,
    MallocSizeOf,
    Parse,
    PartialEq,
    SpecifiedValueInfo,
    ToComputedValue,
    ToCss,
    ToResolvedValue,
    ToShmem,
    ToTyped,
)]
#[allow(missing_docs)]
pub enum LineBreak {
    Auto,
    Loose,
    Normal,
    Strict,
    Anywhere,
}

/// Values for the `overflow-wrap` property.
#[repr(u8)]
#[derive(
    Clone,
    Copy,
    Debug,
    Eq,
    MallocSizeOf,
    Parse,
    PartialEq,
    SpecifiedValueInfo,
    ToComputedValue,
    ToCss,
    ToResolvedValue,
    ToShmem,
    ToTyped,
)]
#[allow(missing_docs)]
pub enum OverflowWrap {
    Normal,
    BreakWord,
    Anywhere,
}

/// A specified value for the `text-indent` property
/// which takes the grammar of [<length-percentage>] && hanging? && each-line?
///
/// https://drafts.csswg.org/css-text/#propdef-text-indent
pub type TextIndent = GenericTextIndent<LengthPercentage>;

impl Parse for TextIndent {
    fn parse<'i, 't>(
        context: &ParserContext,
        input: &mut Parser<'i, 't>,
    ) -> Result<Self, ParseError<'i>> {
        let mut length = None;
        let mut hanging = false;
        let mut each_line = false;

        // The length-percentage and the two possible keywords can occur in any order.
        while !input.is_exhausted() {
            // If we haven't seen a length yet, try to parse one.
            if length.is_none() {
                if let Ok(len) = input
                    .try_parse(|i| LengthPercentage::parse_quirky(context, i, AllowQuirks::Yes))
                {
                    length = Some(len);
                    continue;
                }
            }

            // Servo doesn't support the keywords, so just break and let the caller deal with it.
            if cfg!(feature = "servo") {
                break;
            }

            // Check for the keywords (boolean flags).
            try_match_ident_ignore_ascii_case! { input,
                "hanging" if !hanging => hanging = true,
                "each-line" if !each_line => each_line = true,
            }
        }

        // The length-percentage value is required for the declaration to be valid.
        if let Some(length) = length {
            Ok(Self {
                length,
                hanging,
                each_line,
            })
        } else {
            Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError))
        }
    }
}

/// Implements text-decoration-skip-ink which takes the keywords auto | none | all
///
/// https://drafts.csswg.org/css-text-decor-4/#text-decoration-skip-ink-property
#[repr(u8)]
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(
    Clone,
    Copy,
    Debug,
    Eq,
    MallocSizeOf,
    Parse,
    PartialEq,
    SpecifiedValueInfo,
    ToComputedValue,
    ToCss,
    ToResolvedValue,
    ToShmem,
    ToTyped,
)]
#[allow(missing_docs)]
pub enum TextDecorationSkipInk {
    Auto,
    None,
    All,
}

/// Implements type for `text-decoration-thickness` property
pub type TextDecorationLength = GenericTextDecorationLength<LengthPercentage>;

impl TextDecorationLength {
    /// `Auto` value.
    #[inline]
    pub fn auto() -> Self {
        GenericTextDecorationLength::Auto
    }

    /// Whether this is the `Auto` value.
    #[inline]
    pub fn is_auto(&self) -> bool {
        matches!(*self, GenericTextDecorationLength::Auto)
    }
}

/// Implements type for `text-decoration-inset` property
pub type TextDecorationInset = GenericTextDecorationInset<Length>;

impl TextDecorationInset {
    /// `Auto` value.
    #[inline]
    pub fn auto() -> Self {
        GenericTextDecorationInset::Auto
    }

    /// Whether this is the `Auto` value.
    #[inline]
    pub fn is_auto(&self) -> bool {
        matches!(*self, GenericTextDecorationInset::Auto)
    }
}

impl Parse for TextDecorationInset {
    fn parse<'i, 't>(
        ctx: &ParserContext,
        input: &mut Parser<'i, 't>,
    ) -> Result<Self, ParseError<'i>> {
        if let Ok(start) = input.try_parse(|i| Length::parse(ctx, i)) {
            let end = input.try_parse(|i| Length::parse(ctx, i));
            let end = end.unwrap_or_else(|_| start.clone());
            return Ok(TextDecorationInset::Length { start, end });
        }
        input.expect_ident_matching("auto")?;
        Ok(TextDecorationInset::Auto)
    }
}

#[derive(
    Clone,
    Copy,
    Debug,
    Eq,
    MallocSizeOf,
    Parse,
    PartialEq,
    SpecifiedValueInfo,
    ToComputedValue,
    ToResolvedValue,
    ToShmem,
    ToTyped,
)]
#[css(bitflags(
    single = "auto",
    mixed = "from-font,under,left,right",
    validate_mixed = "Self::validate_mixed_flags",
))]
#[repr(C)]
/// Specified keyword values for the text-underline-position property.
/// (Non-exclusive, but not all combinations are allowed: the spec grammar gives
/// `auto | [ from-font | under ] || [ left | right ]`.)
/// https://drafts.csswg.org/css-text-decor-4/#text-underline-position-property
pub struct TextUnderlinePosition(u8);
bitflags! {
    impl TextUnderlinePosition: u8 {
        /// Use automatic positioning below the alphabetic baseline.
        const AUTO = 0;
        /// Use underline position from the first available font.
        const FROM_FONT = 1 << 0;
        /// Below the glyph box.
        const UNDER = 1 << 1;
        /// In vertical mode, place to the left of the text.
        const LEFT = 1 << 2;
        /// In vertical mode, place to the right of the text.
        const RIGHT = 1 << 3;
    }
}

impl TextUnderlinePosition {
    fn validate_mixed_flags(&self) -> bool {
        if self.contains(Self::LEFT | Self::RIGHT) {
            // left and right can't be mixed together.
            return false;
        }
        if self.contains(Self::FROM_FONT | Self::UNDER) {
            // from-font and under can't be mixed together either.
            return false;
        }
        true
    }
}

impl ToCss for TextUnderlinePosition {
    fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
    where
        W: Write,
    {
        if self.is_empty() {
            return dest.write_str("auto");
        }

        let mut writer = SequenceWriter::new(dest, " ");
        let mut any = false;

        macro_rules! maybe_write {
            ($ident:ident => $str:expr) => {
                if self.contains(TextUnderlinePosition::$ident) {
                    any = true;
                    writer.raw_item($str)?;
                }
            };
        }

        maybe_write!(FROM_FONT => "from-font");
        maybe_write!(UNDER => "under");
        maybe_write!(LEFT => "left");
        maybe_write!(RIGHT => "right");

        debug_assert!(any);

        Ok(())
    }
}

/// Values for `ruby-position` property
#[repr(u8)]
#[derive(
    Clone,
    Copy,
    Debug,
    Eq,
    MallocSizeOf,
    PartialEq,
    ToComputedValue,
    ToResolvedValue,
    ToShmem,
    ToTyped,
)]
#[allow(missing_docs)]
pub enum RubyPosition {
    AlternateOver,
    AlternateUnder,
    Over,
    Under,
}

impl Parse for RubyPosition {
    fn parse<'i, 't>(
        _context: &ParserContext,
        input: &mut Parser<'i, 't>,
    ) -> Result<RubyPosition, ParseError<'i>> {
        // Parse alternate before
        let alternate = input
            .try_parse(|i| i.expect_ident_matching("alternate"))
            .is_ok();
        if alternate && input.is_exhausted() {
            return Ok(RubyPosition::AlternateOver);
        }
        // Parse over / under
        let over = try_match_ident_ignore_ascii_case! { input,
            "over" => true,
            "under" => false,
        };
        // Parse alternate after
        let alternate = alternate
            || input
                .try_parse(|i| i.expect_ident_matching("alternate"))
                .is_ok();

        Ok(match (over, alternate) {
            (true, true) => RubyPosition::AlternateOver,
            (false, true) => RubyPosition::AlternateUnder,
            (true, false) => RubyPosition::Over,
            (false, false) => RubyPosition::Under,
        })
    }
}

impl ToCss for RubyPosition {
    fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
    where
        W: Write,
    {
        dest.write_str(match self {
            RubyPosition::AlternateOver => "alternate",
            RubyPosition::AlternateUnder => "alternate under",
            RubyPosition::Over => "over",
            RubyPosition::Under => "under",
        })
    }
}

impl SpecifiedValueInfo for RubyPosition {
    fn collect_completion_keywords(f: KeywordsCollectFn) {
        f(&["alternate", "over", "under"])
    }
}

/// Specified value for the text-autospace property
/// which takes the grammar:
///     normal | <autospace> | auto
/// where:
///     <autospace> = no-autospace |
///                   [ ideograph-alpha || ideograph-numeric || punctuation ]
///                   || [ insert | replace ]
///
/// https://drafts.csswg.org/css-text-4/#text-autospace-property
///
/// Bug 1980111: 'replace' value is not supported yet.
#[derive(
    Clone,
    Copy,
    Debug,
    Eq,
    MallocSizeOf,
    Parse,
    PartialEq,
    Serialize,
    SpecifiedValueInfo,
    ToCss,
    ToComputedValue,
    ToResolvedValue,
    ToShmem,
    ToTyped,
)]
#[css(bitflags(
    single = "normal,auto,no-autospace",
    // Bug 1980111: add 'replace' to 'mixed' in the future so that it parses correctly.
    // Bug 1986500: add 'punctuation' to 'mixed' in the future so that it parses correctly.
    mixed = "ideograph-alpha,ideograph-numeric,insert",
    // Bug 1980111: Uncomment 'validate_mixed' to support 'replace' value.
    // validate_mixed = "Self::validate_mixed_flags",
))]
#[repr(C)]
pub struct TextAutospace(u8);
bitflags! {
    impl TextAutospace: u8 {
        /// No automatic space is inserted.
        const NO_AUTOSPACE = 0;

        /// The user agent chooses a set of typographically high quality spacing values.
        const AUTO = 1 << 0;

        /// Same behavior as ideograph-alpha ideograph-numeric.
        const NORMAL = 1 << 1;

        /// 1/8ic space between ideographic characters and non-ideographic letters.
        const IDEOGRAPH_ALPHA = 1 << 2;

        /// 1/8ic space between ideographic characters and non-ideographic decimal numerals.
        const IDEOGRAPH_NUMERIC = 1 << 3;

        /* Bug 1986500: Uncomment the following to support the 'punctuation' value.
        /// Apply special spacing between letters and punctuation (French).
        const PUNCTUATION = 1 << 4;
        */

        /// Auto-spacing is only inserted if no space character is present in the text.
        const INSERT = 1 << 5;

        /* Bug 1980111: Uncomment the following to support 'replace' value.
        /// Auto-spacing may replace an existing U+0020 space with custom space.
        const REPLACE = 1 << 6;
        */
    }
}

/* Bug 1980111: Uncomment the following to support 'replace' value.
impl TextAutospace {
    fn validate_mixed_flags(&self) -> bool {
        // It's not valid to have both INSERT and REPLACE set.
        !self.contains(TextAutospace::INSERT | TextAutospace::REPLACE)
    }
}
*/
#[derive(
    Clone,
    Copy,
    Debug,
    Eq,
    FromPrimitive,
    Hash,
    MallocSizeOf,
    Parse,
    PartialEq,
    SpecifiedValueInfo,
    ToComputedValue,
    ToCss,
    ToResolvedValue,
    ToShmem,
    ToTyped,
)]
#[repr(u8)]
/// Identifies specific font metrics for use in the <text-edge> typedef.
///
/// https://drafts.csswg.org/css-inline-3/#typedef-text-edge
pub enum TextEdgeKeyword {
    /// Use the text-over baseline/text-under baseline as the over/under edge.
    Text,
    /// Use the ideographic-over baseline/ideographic-under baseline as the over/under edge.
    Ideographic,
    /// Use the ideographic-ink-over baseline/ideographic-ink-under baseline as the over/under edge.
    IdeographicInk,
    /// Use the cap-height baseline as the over edge.
    Cap,
    /// Use the x-height baseline as the over edge.
    Ex,
    /// Use the alphabetic baseline as the under edge.
    Alphabetic,
}

impl TextEdgeKeyword {
    fn is_valid_for_over(&self) -> bool {
        match self {
            TextEdgeKeyword::Text
            | TextEdgeKeyword::Ideographic
            | TextEdgeKeyword::IdeographicInk
            | TextEdgeKeyword::Cap
            | TextEdgeKeyword::Ex => true,
            _ => false,
        }
    }

    fn is_valid_for_under(&self) -> bool {
        match self {
            TextEdgeKeyword::Text
            | TextEdgeKeyword::Ideographic
            | TextEdgeKeyword::IdeographicInk
            | TextEdgeKeyword::Alphabetic => true,
            _ => false,
        }
    }
}

#[derive(
    Clone,
    Copy,
    Debug,
    Eq,
    Hash,
    MallocSizeOf,
    PartialEq,
    SpecifiedValueInfo,
    ToComputedValue,
    ToResolvedValue,
    ToShmem,
    ToTyped,
)]
#[repr(C)]
/// The <text-edge> typedef, used by the `line-fit-edge` and
/// `text-box-edge` properties.
///
/// The first value specifies the text over edge; the second value
/// specifies the text under edge. If only one value is specified,
/// both edges are assigned that same keyword if possible; else
/// text is assumed as the missing value.
///
/// https://drafts.csswg.org/css-inline-3/#typedef-text-edge
pub struct TextEdge {
    /// Font metric to use for the text over edge.
    pub over: TextEdgeKeyword,
    /// Font metric to use for the text under edge.
    pub under: TextEdgeKeyword,
}

impl Parse for TextEdge {
    fn parse<'i, 't>(
        _context: &ParserContext,
        input: &mut Parser<'i, 't>,
    ) -> Result<TextEdge, ParseError<'i>> {
        let first = TextEdgeKeyword::parse(input)?;

        if let Ok(second) = input.try_parse(TextEdgeKeyword::parse) {
            if !first.is_valid_for_over() || !second.is_valid_for_under() {
                return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError));
            }

            return Ok(TextEdge {
                over: first,
                under: second,
            });
        }

        // https://drafts.csswg.org/css-inline-3/#typedef-text-edge
        // > If only one value is specified, both edges are assigned that same
        // > keyword if possible; else 'text' is assumed as the missing value.
        match (first.is_valid_for_over(), first.is_valid_for_under()) {
            (true, true) => Ok(TextEdge {
                over: first,
                under: first,
            }),
            (true, false) => Ok(TextEdge {
                over: first,
                under: TextEdgeKeyword::Text,
            }),
            (false, true) => Ok(TextEdge {
                over: TextEdgeKeyword::Text,
                under: first,
            }),
            _ => unreachable!("Parsed keyword will be valid for at least one edge"),
        }
    }
}

impl ToCss for TextEdge {
    fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
    where
        W: Write,
    {
        match (self.over, self.under) {
            (over, TextEdgeKeyword::Text) if !over.is_valid_for_under() => over.to_css(dest),
            (TextEdgeKeyword::Text, under) if !under.is_valid_for_over() => under.to_css(dest),
            (over, under) => {
                over.to_css(dest)?;

                if over != under {
                    dest.write_char(' ')?;
                    self.under.to_css(dest)?;
                }

                Ok(())
            },
        }
    }
}

#[derive(
    Clone,
    Copy,
    Debug,
    Eq,
    Hash,
    MallocSizeOf,
    Parse,
    PartialEq,
    SpecifiedValueInfo,
    ToComputedValue,
    ToCss,
    ToResolvedValue,
    ToShmem,
    ToTyped,
)]
#[repr(C, u8)]
/// Specified value for the `text-box-edge` property.
///
/// https://drafts.csswg.org/css-inline-3/#text-box-edge
pub enum TextBoxEdge {
    /// Uses the value of `line-fit-edge`, interpreting `leading` (the initial value) as `text`.
    Auto,
    /// Uses the specified font metrics.
    TextEdge(TextEdge),
}

#[derive(
    Clone,
    Copy,
    Debug,
    Eq,
    MallocSizeOf,
    PartialEq,
    Parse,
    Serialize,
    SpecifiedValueInfo,
    ToCss,
    ToComputedValue,
    ToResolvedValue,
    ToShmem,
    ToTyped,
)]
#[css(bitflags(single = "none,trim-start,trim-end,trim-both"))]
#[repr(C)]
/// Specified value for the `text-box-trim` property.
///
/// https://drafts.csswg.org/css-inline-3/#text-box-edge
pub struct TextBoxTrim(u8);
bitflags! {
    impl TextBoxTrim: u8 {
        /// NONE
        const NONE = 0;
        /// TRIM_START
        const TRIM_START = 1 << 0;
        /// TRIM_END
        const TRIM_END = 1 << 1;
        /// TRIM_BOTH
        const TRIM_BOTH = Self::TRIM_START.0 | Self::TRIM_END.0;
    }
}

impl TextBoxTrim {
    /// Returns the initial value of text-box-trim
    #[inline]
    pub fn none() -> Self {
        TextBoxTrim::NONE
    }
}