ferri-pdf 0.1.4

HTML and CSS to PDF renderer for print, in pure Rust
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
use crate::style::{
    StyleError,
    registration::{Registration, Registrations},
    wide_keywords::WideKeyword,
};
use cssparser::{ParseError, ParseErrorKind, Parser, ParserInput, Token, TokenSerializationType};
use std::{
    cell::{Cell, RefCell},
    collections::{HashMap, HashSet},
    ops::Range,
    rc::Rc,
    sync::Arc,
};

const MAX_VALUE_BYTES: usize = 1024 * 1024;
const CSS_STRING_DELIMITER_BYTES: usize = "\"\"".len();
const MAX_ENVIRONMENT_ENTRIES: usize = 16384;
const MAX_ENVIRONMENT_BYTES: usize = 16 * MAX_VALUE_BYTES;
const MAX_DEPENDENCY_DEPTH: usize = 256;
pub(super) const MAX_VALUE_DEPTH: usize = 128;

#[derive(Clone, Debug, PartialEq)]
enum Origin {
    Values(Range<usize>),
    Empty {
        position: usize,
        function: Option<usize>,
    },
}
#[derive(Clone, Debug, PartialEq)]
pub(super) struct Expanded {
    source: Arc<str>,
    taint: Option<Arc<[Origin]>>,
}
impl Expanded {
    pub(super) fn as_str(&self) -> &str {
        &self.source
    }
    pub(super) fn literal(source: String) -> Result<Self, StyleError> {
        if source.len() > MAX_VALUE_BYTES {
            return Err(StyleError::VariableLimit {
                resource: "specified value bytes",
                limit: MAX_VALUE_BYTES,
            });
        }
        Ok(Self {
            source: source.into(),
            taint: None,
        })
    }
    pub(super) fn len(&self) -> usize {
        self.source.len()
    }
    fn storage_len(&self) -> usize {
        self.len() + self.taint.as_deref().map_or(0, size_of_val)
    }
    pub(super) fn has_taint(&self) -> bool {
        self.taint.is_some()
    }
    pub(super) fn taints(&self, range: Range<usize>) -> bool {
        self.taint.as_ref().is_some_and(|taint| {
            taint.iter().any(|origin| match origin {
                Origin::Values(origin) => origin.start < range.end && range.start < origin.end,
                Origin::Empty {
                    position,
                    function: Some(function),
                } => range.start <= *function && *position <= range.end,
                Origin::Empty { function: None, .. } => false,
            })
        })
    }

    pub(super) fn attribute_string(source: &str) -> Result<Self, StyleError> {
        if source.len() > MAX_VALUE_BYTES - CSS_STRING_DELIMITER_BYTES {
            return Err(Output::byte_limit(std::fmt::Error));
        }
        let mut output = Output::default();
        cssparser::serialize_string(source, &mut output).map_err(Output::byte_limit)?;
        Ok(Self {
            source: output.value.into(),
            taint: None,
        }
        .attribute_tainted())
    }
    pub(super) fn attribute_tainted(mut self) -> Self {
        self.taint = Some(Arc::from([if self.source.is_empty() {
            Origin::Empty {
                position: 0,
                function: None,
            }
        } else {
            Origin::Values(0..self.source.len())
        }]));
        self
    }
}

pub(super) type Environment = Arc<Variables>;
#[derive(Default, Debug, PartialEq)]
pub(super) struct Variables {
    parent: Option<Environment>,
    values: HashMap<String, Option<Expanded>>,
    bytes: usize,
    entries: usize,
    registrations: Arc<Registrations>,
}
impl Variables {
    /// The computed value of `name`; a registered property no ancestor sets has its initial
    /// value (CSS Properties and Values API 1 §2.1).
    pub(super) fn get(&self, name: &str) -> Option<&Option<Expanded>> {
        let mut current = self;
        loop {
            if let Some(value) = current.values.get(name) {
                return Some(value);
            }
            match current.parent.as_deref() {
                Some(parent) => current = parent,
                None => {
                    return self
                        .registrations
                        .get(name)
                        .map(|registration| &registration.initial);
                }
            }
        }
    }
    pub(super) fn registrations(&self) -> &Registrations {
        &self.registrations
    }
    /// `parent`, carrying the document's `registrations` when it does not yet.
    pub(super) fn registered(
        parent: &Environment,
        registrations: &Arc<Registrations>,
    ) -> Environment {
        if Arc::ptr_eq(&parent.registrations, registrations)
            || (parent.registrations.is_empty() && registrations.is_empty())
        {
            return parent.clone();
        }
        Arc::new(Self {
            parent: Some(parent.clone()),
            values: HashMap::new(),
            bytes: parent.bytes,
            entries: parent.entries,
            registrations: registrations.clone(),
        })
    }
    /// The local value `name` takes for a CSS-wide `keyword` (CSS Cascade 4 §7.3), with the
    /// inheritance its registration gives; `None` leaves it to inheritance.
    #[expect(
        clippy::option_option,
        reason = "outer is whether the name has a local value, inner is its value or guaranteed-invalid"
    )]
    fn defaulted(&self, name: &str, keyword: WideKeyword) -> Option<Option<Expanded>> {
        let inherited = || {
            self.parent
                .as_deref()
                .and_then(|parent| parent.get(name).cloned().flatten())
        };
        match (self.registrations.get(name), keyword) {
            (None, WideKeyword::Initial) => Some(None),
            (None, _) => None,
            (Some(registration), WideKeyword::Initial) => Some(registration.initial.clone()),
            (Some(Registration { inherits: true, .. }), _) => None,
            (Some(_), WideKeyword::Inherit) => Some(inherited()),
            (Some(registration), _) => Some(registration.initial.clone()),
        }
    }
    /// The value of `name` when invalid at computed-value time: guaranteed-invalid, or for a
    /// registered property the value `unset` gives (CSS Properties and Values API 1 §2.4).
    fn invalid(&self, name: &str) -> Option<Expanded> {
        self.registrations.get(name)?;
        self.defaulted(name, WideKeyword::Unset).unwrap_or_else(|| {
            self.parent
                .as_deref()
                .and_then(|parent| parent.get(name).cloned().flatten())
        })
    }
    /// Gives `name` the local `value`.
    fn set(&mut self, name: &str, value: Option<Expanded>) -> Result<(), StyleError> {
        if let Some(value) = &value {
            self.charge_bytes(value.storage_len())?;
        }
        if let Some(Some(previous)) = self.values.insert(name.to_owned(), value) {
            self.bytes -= previous.storage_len();
        }
        Ok(())
    }
    fn add_entry(&mut self, name: &str) -> Result<(), StyleError> {
        self.entries += 1;
        if self.entries > MAX_ENVIRONMENT_ENTRIES {
            return Err(StyleError::VariableLimit {
                resource: "environment entries",
                limit: MAX_ENVIRONMENT_ENTRIES,
            });
        }
        self.charge_bytes(name.len())
    }
    fn charge_bytes(&mut self, bytes: usize) -> Result<(), StyleError> {
        self.bytes = self
            .bytes
            .checked_add(bytes)
            .filter(|total| *total <= MAX_ENVIRONMENT_BYTES)
            .ok_or(StyleError::VariableLimit {
                resource: "environment bytes",
                limit: MAX_ENVIRONMENT_BYTES,
            })?;
        Ok(())
    }
}
#[derive(Clone, Debug)]
pub(super) struct Value(Vec<Part>);
#[derive(Clone, Debug)]
enum Part {
    Text(String, TokenSerializationType),
    Opaque(String, TokenSerializationType),
    Block(String, TokenSerializationType, Value, &'static str),
    Reference(Reference, String, Option<Value>),
    Conditional(Box<crate::style::conditional::Expression>),
    Attribute(Box<crate::style::attribute::Attribute>),
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum Reference {
    Local,
    Inherited,
}
const REFERENCE_FUNCTIONS: &[(&str, Reference)] =
    &[("var", Reference::Local), ("inherit", Reference::Inherited)];
impl Reference {
    fn from_name(name: &str) -> Option<Self> {
        REFERENCE_FUNCTIONS
            .iter()
            .find_map(|(function, reference)| {
                name.eq_ignore_ascii_case(function).then_some(*reference)
            })
    }
}
pub(super) fn substitution_function(name: &str) -> bool {
    Reference::from_name(name).is_some()
        || name.eq_ignore_ascii_case(crate::style::conditional::FUNCTION)
        || name.eq_ignore_ascii_case(crate::style::attribute::FUNCTION)
}

#[derive(Debug)]
enum ValueError {
    Syntax,
    Depth,
    Style(StyleError),
}
impl From<StyleError> for ValueError {
    fn from(error: StyleError) -> Self {
        Self::Style(error)
    }
}
impl Value {
    pub(super) fn with_substitutions(source: &str) -> Result<Option<Self>, StyleError> {
        Self::substitutions(source, false)
    }
    pub(super) fn with_property_substitutions(source: &str) -> Result<Option<Self>, StyleError> {
        Self::substitutions(source, true)
    }
    fn substitutions(source: &str, property_syntax: bool) -> Result<Option<Self>, StyleError> {
        if !source.contains('\\')
            && !REFERENCE_FUNCTIONS
                .iter()
                .map(|(name, _)| *name)
                .chain([
                    crate::style::conditional::FUNCTION,
                    crate::style::attribute::FUNCTION,
                ])
                .any(|name| {
                    source.as_bytes().windows(name.len() + 1).any(|part| {
                        part[name.len()] == b'('
                            && part[..name.len()].eq_ignore_ascii_case(name.as_bytes())
                    })
                })
        {
            return Ok(None);
        }
        let value = Self::parse_context(source, 0, property_syntax)?
            .ok_or_else(|| StyleError::Invalid("invalid value substitution syntax".into()))?;
        Ok(value.has_substitutions().then_some(value))
    }
    pub(super) fn parse(source: &str) -> Result<Option<Self>, StyleError> {
        Self::parse_at_depth(source, 0)
    }
    pub(super) fn parse_at_depth(source: &str, depth: usize) -> Result<Option<Self>, StyleError> {
        Self::parse_context(source, depth, false)
    }
    pub(super) fn parse_context(
        source: &str,
        depth: usize,
        property_syntax: bool,
    ) -> Result<Option<Self>, StyleError> {
        if source.len() > MAX_VALUE_BYTES {
            return Err(StyleError::VariableLimit {
                resource: "specified value bytes",
                limit: MAX_VALUE_BYTES,
            });
        }

        let mut input = ParserInput::new(crate::style::parser::trim_value(source));
        match Self::tokens(&mut Parser::new(&mut input), depth, false, property_syntax) {
            Ok(value) => Ok(Some(value)),
            Err(error) => match error.kind {
                ParseErrorKind::Custom(ValueError::Depth) => Err(StyleError::VariableLimit {
                    resource: "value nesting",
                    limit: MAX_VALUE_DEPTH,
                }),
                ParseErrorKind::Custom(ValueError::Style(error)) => Err(error),
                _ => Ok(None),
            },
        }
    }
    fn tokens<'i>(
        input: &mut Parser<'i, '_>,
        depth: usize,
        in_block: bool,
        property_syntax: bool,
    ) -> Result<Self, ParseError<'i, ValueError>> {
        if depth > MAX_VALUE_DEPTH {
            return Err(input.new_custom_error(ValueError::Depth));
        }
        let mut parts = Vec::new();
        loop {
            let start = input.position();
            let token = match input.next_including_whitespace_and_comments().cloned() {
                Ok(token) => token,
                Err(error) if matches!(error.kind, cssparser::BasicParseErrorKind::EndOfInput) => {
                    break;
                }
                Err(error) => return Err(error.into()),
            };
            let kind = if matches!(token, Token::Comment(_)) {
                TokenSerializationType::WhiteSpace
            } else {
                token.serialization_type()
            };
            let part = match token {
                Token::Function(name)
                    if name.eq_ignore_ascii_case(crate::style::attribute::FUNCTION) =>
                {
                    Self::attribute_part(input, depth, property_syntax)
                }
                Token::Function(name)
                    if name.eq_ignore_ascii_case(crate::style::conditional::FUNCTION) =>
                {
                    Self::conditional_part(input, depth, property_syntax)
                }
                Token::Function(name) if Reference::from_name(&name).is_some() => {
                    let reference = Reference::from_name(&name).unwrap();
                    Self::reference_part(input, reference, depth, property_syntax)
                }
                Token::Function(_)
                | Token::ParenthesisBlock
                | Token::SquareBracketBlock
                | Token::CurlyBracketBlock => {
                    Self::block_part(input, &token, start, kind, depth, property_syntax)
                }
                Token::BadString(_)
                | Token::BadUrl(_)
                | Token::CloseParenthesis
                | Token::CloseSquareBracket
                | Token::CloseCurlyBracket => Err(input.new_custom_error(ValueError::Syntax)),
                Token::Semicolon | Token::Delim('!') if !in_block => {
                    Err(input.new_custom_error(ValueError::Syntax))
                }
                _ => Ok(Part::Text(input.slice_from(start).to_owned(), kind)),
            };
            parts.push(part?);
        }
        Ok(Self(parts))
    }
    // Nested values recurse through each part parser below; separate frames keep the
    // other arms' locals off every nesting level of `tokens`.
    fn attribute_part<'i>(
        input: &mut Parser<'i, '_>,
        depth: usize,
        property_syntax: bool,
    ) -> Result<Part, ParseError<'i, ValueError>> {
        let value = input.parse_nested_block(|nested| {
            crate::style::attribute::Attribute::parse(nested, depth + 1, property_syntax)
                .map_err(|error| nested.new_custom_error(ValueError::Style(error)))?
                .ok_or_else(|| nested.new_custom_error(ValueError::Syntax))
        })?;
        Ok(Part::Attribute(Box::new(value)))
    }
    fn conditional_part<'i>(
        input: &mut Parser<'i, '_>,
        depth: usize,
        property_syntax: bool,
    ) -> Result<Part, ParseError<'i, ValueError>> {
        input.parse_nested_block(|nested| {
            match crate::style::conditional::Expression::parse(nested, depth + 1, property_syntax) {
                Ok(Some(expression)) => Ok(Part::Conditional(Box::new(expression))),
                Ok(None) => Err(nested.new_custom_error(ValueError::Syntax)),
                Err(error) => Err(nested.new_custom_error(ValueError::Style(error))),
            }
        })
    }
    fn reference_part<'i>(
        input: &mut Parser<'i, '_>,
        reference: Reference,
        depth: usize,
        property_syntax: bool,
    ) -> Result<Part, ParseError<'i, ValueError>> {
        let (name, fallback) = input.parse_nested_block(|p| {
            let name = p.expect_ident()?.to_string();
            if !name.starts_with("--") || name.len() == 2 {
                return Err(p.new_custom_error(ValueError::Syntax));
            }
            let fallback = if p.try_parse(Parser::expect_comma).is_ok() {
                let source =
                    crate::style::parser::substitution_argument(p, reference == Reference::Local)
                        .map_err(ParseError::into)?;
                let mut fallback = ParserInput::new(source);
                Some(Self::tokens(
                    &mut Parser::new(&mut fallback),
                    depth + 1,
                    false,
                    property_syntax,
                )?)
            } else {
                None
            };
            p.expect_exhausted()?;
            Ok((name, fallback))
        })?;
        Ok(Part::Reference(reference, name, fallback))
    }
    fn block_part<'i>(
        input: &mut Parser<'i, '_>,
        token: &Token<'i>,
        start: cssparser::SourcePosition,
        kind: TokenSerializationType,
        depth: usize,
        property_syntax: bool,
    ) -> Result<Part, ParseError<'i, ValueError>> {
        let close = match token {
            Token::SquareBracketBlock => "]",
            Token::CurlyBracketBlock => "}",
            _ => ")",
        };
        let open = input.slice_from(start).to_owned();
        let guarded = property_syntax
            && matches!(token, Token::Function(name) if name.eq_ignore_ascii_case(crate::style::declaration::TOGGLE));
        let value = input.parse_nested_block(|nested| {
            if guarded {
                let state = nested.state();
                let valid = crate::style::declaration::toggle_argument(nested, depth)
                    .map_err(|error| nested.new_custom_error(ValueError::Style(error)))?;
                nested.reset(&state);
                if !valid {
                    crate::style::conditions::block_source(nested);
                    return Ok(None);
                }
            }
            Self::tokens(nested, depth + 1, true, property_syntax).map(Some)
        })?;
        Ok(match value {
            Some(value) => Part::Block(open, kind, value, close),
            None => Part::Opaque(input.slice_from(start).to_owned(), kind),
        })
    }
    pub(super) fn has_substitutions(&self) -> bool {
        self.0.iter().any(|part| match part {
            Part::Reference(..) | Part::Conditional(_) | Part::Attribute(_) => true,
            Part::Block(_, _, value, _) => value.has_substitutions(),
            _ => false,
        })
    }
    pub(super) fn requires_context(&self) -> bool {
        self.0.iter().any(|part| match part {
            Part::Conditional(_) | Part::Attribute(_) => true,
            Part::Block(_, _, value, _) => value.requires_context(),
            Part::Reference(_, _, fallback) => {
                fallback.as_ref().is_some_and(Self::requires_context)
            }
            _ => false,
        })
    }
    pub(super) fn dependencies(&self, output: &mut HashSet<String>) {
        for part in &self.0 {
            match part {
                Part::Reference(reference, name, fallback) => {
                    if *reference == Reference::Local {
                        output.insert(name.clone());
                    }
                    if let Some(value) = fallback {
                        value.dependencies(output);
                    }
                }
                Part::Block(_, _, value, _) => value.dependencies(output),
                Part::Conditional(expression) => expression.dependencies(output),
                Part::Attribute(attribute) => attribute.dependencies(output),
                _ => {}
            }
        }
    }
    pub(super) fn substitute(
        &self,
        environment: &Variables,
        inherited: &Variables,
    ) -> Result<Option<Expanded>, StyleError> {
        self.substitute_with(&environment.registrations, &mut |reference, name| {
            let source = if reference == Reference::Inherited {
                inherited
            } else {
                environment
            };
            Ok(source.get(name).and_then(Clone::clone))
        })
    }
    pub(super) fn substitute_with(
        &self,
        registrations: &Registrations,
        lookup: &mut impl FnMut(Reference, &str) -> Result<Option<Expanded>, StyleError>,
    ) -> Result<Option<Expanded>, StyleError> {
        self.substitute_context(
            registrations,
            lookup,
            &mut |_| {
                Err(StyleError::Invalid(
                    "conditional substitution requires a computed property context".into(),
                ))
            },
            &mut |_| {
                Err(StyleError::Invalid(
                    "attribute substitution requires an element context".into(),
                ))
            },
        )
    }
    pub(super) fn substitute_context(
        &self,
        registrations: &Registrations,
        lookup: &mut impl FnMut(Reference, &str) -> Result<Option<Expanded>, StyleError>,
        test: &mut impl FnMut(
            &crate::style::conditional::Test,
        ) -> Result<crate::style::conditions::Truth, StyleError>,
        attribute: &mut impl FnMut(
            &crate::style::attribute::Attribute,
        ) -> Result<Option<Expanded>, StyleError>,
    ) -> Result<Option<Expanded>, StyleError> {
        let mut output = Output::default();
        if self.append(registrations, lookup, test, attribute, &mut output)? {
            Ok(Some(Expanded {
                source: output.value.into(),
                taint: if output.taint.is_empty() {
                    None
                } else {
                    Some(output.taint.into())
                },
            }))
        } else {
            Ok(None)
        }
    }
    fn append(
        &self,
        registrations: &Registrations,
        lookup: &mut impl FnMut(Reference, &str) -> Result<Option<Expanded>, StyleError>,
        test: &mut impl FnMut(
            &crate::style::conditional::Test,
        ) -> Result<crate::style::conditions::Truth, StyleError>,
        attribute: &mut impl FnMut(
            &crate::style::attribute::Attribute,
        ) -> Result<Option<Expanded>, StyleError>,
        output: &mut Output,
    ) -> Result<bool, StyleError> {
        for part in &self.0 {
            match part {
                Part::Text(text, kind) => output.token(text, *kind)?,
                Part::Opaque(text, kind) => {
                    output.token(text, *kind)?;
                    output.last = TokenSerializationType::Other;
                }

                Part::Attribute(value) => {
                    let Some(value) = attribute(value)? else {
                        return Ok(false);
                    };
                    output.source(&value)?;
                }

                Part::Block(open, kind, value, close) => {
                    output.token(open, *kind)?;
                    let function = *kind == TokenSerializationType::Function;
                    if function {
                        output.functions.push(output.value.len() - open.len());
                    }
                    let valid = value.append(registrations, lookup, test, attribute, output)?;
                    if function {
                        output.functions.pop();
                    }
                    if !valid {
                        return Ok(false);
                    }
                    output.token(close, TokenSerializationType::Other)?;
                }
                Part::Conditional(expression) => {
                    if let Some(value) = expression.select(test)?
                        && !value.append(registrations, lookup, test, attribute, output)?
                    {
                        return Ok(false);
                    }
                }
                Part::Reference(reference, name, fallback) => {
                    let checked = match (fallback, registrations.typed(name)) {
                        // CSS Properties and Values API 1 §2.7.1: a fallback for a registered
                        // property must match its syntax, whether or not it is used.
                        (Some(fallback), Some(registration)) => {
                            let Some(fallback) = fallback.substitute_context(
                                registrations,
                                lookup,
                                test,
                                attribute,
                            )?
                            else {
                                return Ok(false);
                            };
                            if !crate::style::matcher::match_syntax(
                                &registration.syntax,
                                fallback.as_str(),
                                &mut 0,
                                crate::style::matcher::ValueContext::Element,
                            )? {
                                return Ok(false);
                            }
                            Some(fallback)
                        }
                        _ => None,
                    };
                    let value = if let Some(value) = lookup(*reference, name)? {
                        Some(value)
                    } else if checked.is_some() {
                        checked
                    } else if let Some(fallback) = fallback {
                        fallback.substitute_context(registrations, lookup, test, attribute)?
                    } else {
                        None
                    };
                    let Some(value) = value else {
                        return Ok(false);
                    };
                    let value = if value.has_taint() {
                        value.attribute_tainted()
                    } else {
                        value
                    };
                    output.source(&value)?;
                }
            }
        }
        Ok(true)
    }
}
#[derive(Default)]
struct Output {
    value: String,
    taint: Vec<Origin>,
    functions: Vec<usize>,
    last: TokenSerializationType,
}
impl Output {
    fn token(&mut self, source: &str, kind: TokenSerializationType) -> Result<(), StyleError> {
        if self.last.needs_separator_when_before(kind) {
            self.append("/**/")?;
        }
        self.append(source)?;
        self.last = kind;
        Ok(())
    }
    fn source(&mut self, value: &Expanded) -> Result<(), StyleError> {
        let source = value.as_str();
        let mut raw = ParserInput::new(source);
        let input = &mut Parser::new(&mut raw);
        let mut first = TokenSerializationType::Nothing;
        let mut last = TokenSerializationType::Nothing;
        while let Ok(token) = input.next_including_whitespace_and_comments().cloned() {
            let kind = if matches!(token, Token::Comment(_)) {
                TokenSerializationType::WhiteSpace
            } else {
                token.serialization_type()
            };
            first.set_if_nothing(kind);
            last = kind;
            if matches!(
                token,
                Token::Function(_)
                    | Token::ParenthesisBlock
                    | Token::SquareBracketBlock
                    | Token::CurlyBracketBlock
            ) {
                input
                    .parse_nested_block(crate::style::parser::consume)
                    .map_err(crate::style::parser::failure)?;
                last = TokenSerializationType::Other;
            }
        }
        if first == TokenSerializationType::Nothing {
            if value.has_taint() {
                self.origin(Origin::Empty {
                    position: self.value.len(),
                    function: self.functions.last().copied(),
                });
            }
            return Ok(());
        }
        if self.last.needs_separator_when_before(first) {
            self.append("/**/")?;
        }
        let offset = self.value.len();
        self.append(source)?;
        if let Some(taint) = &value.taint {
            for origin in taint.iter() {
                self.origin(match origin {
                    Origin::Values(range) => {
                        Origin::Values(offset + range.start..offset + range.end)
                    }
                    Origin::Empty { position, function } => Origin::Empty {
                        position: offset + position,
                        function: function.map(|start| offset + start),
                    },
                });
            }
        }
        self.last = last;
        Ok(())
    }
    fn origin(&mut self, origin: Origin) {
        if let Some(last) = self.taint.last_mut() {
            if *last == origin {
                return;
            }
            if let (Origin::Values(previous), Origin::Values(next)) = (&mut *last, &origin)
                && previous.end >= next.start
            {
                previous.end = previous.end.max(next.end);
                return;
            }
        }
        self.taint.push(origin);
    }
    fn append(&mut self, source: &str) -> Result<(), StyleError> {
        std::fmt::Write::write_str(self, source).map_err(Self::byte_limit)
    }
    fn byte_limit(_: std::fmt::Error) -> StyleError {
        StyleError::VariableLimit {
            resource: "expanded value bytes",
            limit: MAX_VALUE_BYTES,
        }
    }
}
impl std::fmt::Write for Output {
    fn write_str(&mut self, source: &str) -> std::fmt::Result {
        if self
            .value
            .len()
            .checked_add(source.len())
            .is_none_or(|len| len > MAX_VALUE_BYTES)
        {
            return Err(std::fmt::Error);
        }
        self.value.push_str(source);
        Ok(())
    }
}

pub(super) fn dependencies_in(
    source: &str,
    depth: usize,
    output: &mut HashSet<String>,
) -> Result<(), StyleError> {
    fn scan(
        input: &mut Parser<'_, '_>,
        depth: usize,
        output: &mut HashSet<String>,
    ) -> Result<(), StyleError> {
        if depth > MAX_VALUE_DEPTH {
            return Err(StyleError::VariableLimit {
                resource: "value nesting",
                limit: MAX_VALUE_DEPTH,
            });
        }
        while let Ok(token) = input.next().cloned() {
            if let token @ (Token::Function(_)
            | Token::ParenthesisBlock
            | Token::SquareBracketBlock
            | Token::CurlyBracketBlock) = token
            {
                let local = matches!(&token, Token::Function(name) if Reference::from_name(name) == Some(Reference::Local));
                input
                    .parse_nested_block(|nested| {
                        let state = nested.state();
                        if local
                            && let Ok(name) = nested.expect_ident_cloned()
                            && name.starts_with("--")
                            && name.len() > 2
                        {
                            output.insert(name.to_string());
                        }
                        nested.reset(&state);
                        scan(nested, depth + 1, output)
                            .map_err(|error| nested.new_custom_error(error))
                    })
                    .map_err(crate::style::parser::failure)?;
            }
        }
        Ok(())
    }
    let mut input = ParserInput::new(source);
    scan(&mut Parser::new(&mut input), depth, output)
}

pub(super) enum Source {
    Css(String),
    /// A substitution-free token stream already validated by its source parser.
    Literal(String),
}
impl From<String> for Source {
    fn from(value: String) -> Self {
        Self::Css(value)
    }
}
pub(super) enum Resolution {
    Complete(Environment),
    Wide { name: String, keyword: WideKeyword },
}

#[derive(Clone, Copy)]
pub(super) enum WideHandling<'a> {
    Recascade,
    Fallback(&'a RefCell<HashMap<String, Source>>),
}
pub(super) fn resolve(
    parent: &Environment,
    declarations: HashMap<String, impl Into<Source>>,
    wide: WideHandling<'_>,
) -> Result<Resolution, StyleError> {
    if declarations.is_empty() && parent.registrations.non_inherited().next().is_none() {
        return Ok(Resolution::Complete(parent.clone()));
    }
    let resolver = Resolver::new(parent, declarations)?;
    let evaluation = ReferencesOnly(&resolver, wide);
    for name in resolver.names() {
        if let Some((name, keyword)) = resolver.compute(&name, &evaluation)? {
            return Ok(Resolution::Wide { name, keyword });
        }
    }
    Ok(Resolution::Complete(resolver.environment(parent)?))
}

mod cycles;
pub(super) type Values = HashMap<String, Option<Rc<Value>>>;
pub(super) enum Recascade {
    Restart,
    Source(Option<Source>),
}
pub(super) trait Evaluation {
    fn enter(&self, name: &str) -> Result<(), StyleError>;
    fn leave(&self, name: &str);
    fn prepare_references(
        &self,
        value: &Value,
    ) -> Result<Option<(String, WideKeyword)>, StyleError>;
    fn substitute(&self, name: &str, value: &Value) -> Result<Option<Expanded>, StyleError>;
    fn recascade(&self, name: &str, keyword: WideKeyword) -> Result<Recascade, StyleError>;
}

pub(super) struct Resolver {
    values: RefCell<Values>,
    computed: RefCell<Variables>,
    finished: RefCell<HashSet<String>>,
    depth: Cell<usize>,
}
impl Resolver {
    pub(super) fn new(
        parent: &Environment,
        declarations: HashMap<String, impl Into<Source>>,
    ) -> Result<Self, StyleError> {
        let mut computed = Variables {
            parent: Some(parent.clone()),
            bytes: parent.bytes,
            entries: parent.entries,
            values: HashMap::new(),
            registrations: parent.registrations.clone(),
        };
        let mut values = Values::new();
        for (name, source) in declarations {
            let source = source.into();
            let (source, literal) = match source {
                Source::Css(source) => (source, false),
                Source::Literal(source) => (source, true),
            };
            let defaulted = match WideKeyword::parse(&source) {
                Some(keyword) => match computed.defaulted(&name, keyword) {
                    Some(value) => Some(value),
                    None => continue,
                },
                None => None,
            };
            computed.add_entry(&name)?;
            if let Some(value) = defaulted {
                computed.set(&name, value)?;
            } else if literal {
                computed.set(&name, Some(Expanded::literal(source)?))?;
            } else {
                computed.values.insert(name.clone(), None);
                values.insert(name, Value::parse(&source)?.map(Rc::new));
            }
        }
        let finished = cycles::members(&values);
        for name in &finished {
            let invalid = computed.invalid(name);
            computed.set(name, invalid)?;
        }
        // CSS Properties and Values API 1 §2.1: a registered property that does not inherit
        // takes its initial value wherever it is not declared.
        let resets: Vec<_> = computed
            .registrations
            .non_inherited()
            .filter(|(name, registration)| {
                !computed.values.contains_key(*name)
                    && parent.get(name) != Some(&registration.initial)
            })
            .map(|(name, registration)| (name.to_owned(), registration.initial.clone()))
            .collect();
        for (name, initial) in resets {
            computed.add_entry(&name)?;
            computed.set(&name, initial)?;
        }
        Ok(Self {
            values: RefCell::new(values),
            computed: RefCell::new(computed),
            finished: RefCell::new(finished),
            depth: Cell::new(0),
        })
    }

    pub(super) fn names(&self) -> Vec<String> {
        self.values.borrow().keys().cloned().collect()
    }

    #[expect(
        clippy::option_option,
        reason = "outer is whether the name is declared locally, inner is its value or guaranteed-invalid"
    )]
    pub(super) fn local(&self, name: &str) -> Option<Option<Expanded>> {
        self.computed.borrow().values.get(name).cloned()
    }

    pub(super) fn environment(&self, parent: &Environment) -> Result<Environment, StyleError> {
        let values = self.computed.borrow().values.clone();
        if values.is_empty() {
            return Ok(parent.clone());
        }
        let entries = parent.entries + values.len();
        if entries > MAX_ENVIRONMENT_ENTRIES {
            return Err(StyleError::VariableLimit {
                resource: "environment entries",
                limit: MAX_ENVIRONMENT_ENTRIES,
            });
        }
        let mut computed = Variables {
            parent: Some(parent.clone()),
            values,
            entries,
            bytes: parent.bytes,
            registrations: parent.registrations.clone(),
        };
        let bytes = computed
            .values
            .iter()
            .map(|(name, value)| name.len() + value.as_ref().map_or(0, Expanded::storage_len))
            .sum();
        computed.charge_bytes(bytes)?;
        Ok(Arc::new(computed))
    }

    pub(super) fn compute(
        &self,
        name: &str,
        evaluation: &impl Evaluation,
    ) -> Result<Option<(String, WideKeyword)>, StyleError> {
        if self.finished.borrow().contains(name) || !self.values.borrow().contains_key(name) {
            return Ok(None);
        }
        let depth = self.depth.get();
        if depth >= MAX_DEPENDENCY_DEPTH {
            return Err(StyleError::VariableLimit {
                resource: "dependency depth",
                limit: MAX_DEPENDENCY_DEPTH,
            });
        }
        evaluation.enter(name)?;
        self.depth.set(depth + 1);
        let result = self.compute_value(name, evaluation);
        self.depth.set(depth);
        evaluation.leave(name);
        result
    }

    fn compute_value(
        &self,
        name: &str,
        evaluation: &impl Evaluation,
    ) -> Result<Option<(String, WideKeyword)>, StyleError> {
        loop {
            if self.finished.borrow().contains(name) {
                return Ok(None);
            }
            let value = self.values.borrow().get(name).cloned().flatten();
            if let Some(value) = &value
                && let Some(wide) = evaluation.prepare_references(value)?
            {
                return Ok(Some(wide));
            }
            if self.finished.borrow().contains(name) {
                return Ok(None);
            }
            let result = match value {
                Some(value) => evaluation.substitute(name, &value)?,
                None => None,
            };
            if let Some(value) = &result
                && let Some(keyword) = WideKeyword::parse(value.as_str())
            {
                match evaluation.recascade(name, keyword)? {
                    Recascade::Restart => return Ok(Some((name.to_owned(), keyword))),
                    Recascade::Source(source) => {
                        self.replace(name, source)?;
                        continue;
                    }
                }
            }
            if self.finished.borrow().contains(name) {
                return Ok(None);
            }
            let mut computed = self.computed.borrow_mut();
            let result = match result {
                Some(value) => Some(value),
                None => computed.invalid(name),
            };
            computed.set(name, result)?;
            self.finished.borrow_mut().insert(name.to_owned());
            return Ok(None);
        }
    }

    fn replace(&self, name: &str, source: Option<Source>) -> Result<(), StyleError> {
        let (source, literal) = match source {
            Some(Source::Literal(source)) => (Some(source), true),
            Some(Source::Css(source)) => (Some(source), false),
            None => (None, false),
        };
        let keyword = source.as_deref().and_then(WideKeyword::parse);
        if source.is_none()
            || matches!(
                keyword,
                Some(WideKeyword::Inherit | WideKeyword::Unset | WideKeyword::Initial)
            )
        {
            self.values.borrow_mut().remove(name);
            let mut computed = self.computed.borrow_mut();
            match computed.defaulted(name, keyword.unwrap_or(WideKeyword::Unset)) {
                Some(value) => computed.set(name, value)?,
                None => {
                    if let Some(value) = computed.values.remove(name) {
                        computed.entries -= 1;
                        computed.bytes -= name.len() + value.map_or(0, |value| value.storage_len());
                    }
                }
            }
            self.finished.borrow_mut().insert(name.to_owned());
            return Ok(());
        }
        if literal && keyword.is_none() {
            let value = Expanded::literal(source.expect("literal custom source exists"))?;
            self.values.borrow_mut().remove(name);
            self.computed.borrow_mut().set(name, Some(value))?;
            self.finished.borrow_mut().insert(name.to_owned());
            return Ok(());
        }
        let value =
            Value::parse(source.as_deref().expect("noninitial custom source exists"))?.map(Rc::new);
        self.values.borrow_mut().insert(name.to_owned(), value);
        let cyclic = cycles::members(&self.values.borrow());
        let mut computed = self.computed.borrow_mut();
        for name in &cyclic {
            let invalid = computed.invalid(name);
            computed.set(name, invalid)?;
        }
        self.finished.borrow_mut().extend(cyclic);
        Ok(())
    }
}

struct ReferencesOnly<'a>(&'a Resolver, WideHandling<'a>);
impl Evaluation for ReferencesOnly<'_> {
    fn enter(&self, _name: &str) -> Result<(), StyleError> {
        Ok(())
    }
    fn leave(&self, _name: &str) {}
    fn prepare_references(
        &self,
        value: &Value,
    ) -> Result<Option<(String, WideKeyword)>, StyleError> {
        let mut dependencies = HashSet::new();
        value.dependencies(&mut dependencies);
        for name in dependencies {
            if let Some(wide) = self.0.compute(&name, self)? {
                return Ok(Some(wide));
            }
        }
        Ok(None)
    }
    fn substitute(&self, _name: &str, value: &Value) -> Result<Option<Expanded>, StyleError> {
        let registrations = self.0.computed.borrow().registrations.clone();
        value.substitute_with(&registrations, &mut |reference, name| {
            let computed = self.0.computed.borrow();
            let source = if reference == Reference::Inherited {
                computed
                    .parent
                    .as_deref()
                    .expect("custom properties have an inherited environment")
            } else {
                &computed
            };
            Ok(source.get(name).and_then(Clone::clone))
        })
    }
    fn recascade(&self, name: &str, keyword: WideKeyword) -> Result<Recascade, StyleError> {
        Ok(match self.1 {
            WideHandling::Recascade => Recascade::Restart,
            WideHandling::Fallback(previous) => Recascade::Source(match keyword {
                WideKeyword::Initial => Some(keyword.name().to_owned().into()),
                WideKeyword::RevertLayer => previous.borrow_mut().remove(name),
                _ => None,
            }),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dom::{DocumentTree, Selector};
    use crate::style::{Style, Stylesheet, StylesheetSource};

    fn attribute_environment(source: &str) -> Environment {
        let sheet = Stylesheet::parse(&[StylesheetSource {
            text: format!("p{{--value:{source}}}"),
            base: Default::default(),
        }])
        .unwrap();
        let tree = DocumentTree::parse("<p data-empty='' data-token='t'>Attribute</p>");
        let element = tree.select(&Selector::parse("p").unwrap()).next().unwrap();
        sheet
            .computed(element, &Style::default())
            .unwrap()
            .custom_properties
    }

    #[test]
    fn repeated_empty_attributes_share_one_origin_at_the_same_position() {
        const REPETITIONS: usize = 256;
        let environment = attribute_environment(&"attr(data-empty *)".repeat(REPETITIONS));
        let value = environment.get("--value").unwrap().as_ref().unwrap();
        assert_eq!(value.as_str(), "");
        assert_eq!(
            value.taint.as_deref(),
            Some(
                [Origin::Empty {
                    position: 0,
                    function: None
                }]
                .as_slice()
            ),
            "repeated zero-byte substitutions must not grow retained provenance at one position"
        );
    }

    #[test]
    fn attribute_environment_budget_includes_retained_origins() {
        const REPETITIONS: usize = 8;
        let environment = attribute_environment(&"attr(data-token *) x ".repeat(REPETITIONS));
        let value = environment.get("--value").unwrap().as_ref().unwrap();
        let origins = value.taint.as_deref().unwrap();
        assert_eq!(
            origins.len(),
            REPETITIONS,
            "authored tokens between attributes keep their distinct provenance"
        );
        let retained = "--value".len() + value.len() + size_of_val(origins);
        assert_eq!(
            environment.bytes,
            retained,
            "the shared environment quota must include retained attribute metadata: source={} origins={}",
            value.len(),
            origins.len()
        );
    }

    #[test]
    fn inherited_attribute_metadata_reaches_the_environment_quota_before_text() {
        const ORIGINS_PER_ELEMENT: usize = 32 * 1024;
        const ELEMENTS: usize =
            MAX_ENVIRONMENT_BYTES / (ORIGINS_PER_ELEMENT * size_of::<Origin>()) + 1;
        let source = "var(--token) x ".repeat(ORIGINS_PER_ELEMENT);
        let sheet = Stylesheet::parse(&[StylesheetSource {
            text: format!("div{{--token:attr(data-token *);--value:{source}}}"),
            base: Default::default(),
        }])
        .unwrap();
        let html = "<div data-token=t>".repeat(ELEMENTS) + &"</div>".repeat(ELEMENTS);
        let tree = DocumentTree::parse(&html);
        let selector = Selector::parse("div").unwrap();
        let mut parent = Style::default();
        let mut text_bytes = 0;
        for (index, element) in tree.select(&selector).enumerate() {
            match sheet.computed(element, &parent) {
                Ok(style) => {
                    let value = style
                        .custom_properties
                        .get("--value")
                        .unwrap()
                        .as_ref()
                        .unwrap();
                    assert_eq!(value.taint.as_deref().unwrap().len(), ORIGINS_PER_ELEMENT);
                    text_bytes += value.len() + "t".len() + "--token".len() + "--value".len();
                    parent = style;
                }
                Err(StyleError::VariableLimit {
                    resource: "environment bytes",
                    limit: MAX_ENVIRONMENT_BYTES,
                }) => {
                    assert!(
                        text_bytes < MAX_ENVIRONMENT_BYTES,
                        "provenance must trigger the shared quota while text still fits: element={index}, text_bytes={text_bytes}"
                    );
                    return;
                }
                other => panic!(
                    "unexpected result before provenance quota at element {index}: {other:?}"
                ),
            }
        }
        panic!(
            "retained attribute provenance bypassed the environment quota across {ELEMENTS} inherited environments"
        );
    }

    #[test]
    fn literal_attribute_serialization_bounds_escaped_output_including_quotes() {
        let value = Expanded::attribute_string(&"x".repeat(MAX_VALUE_BYTES - 2)).unwrap();
        assert_eq!(value.len(), MAX_VALUE_BYTES);
        let error = Expanded::attribute_string(&"\\".repeat(MAX_VALUE_BYTES / 2)).unwrap_err();
        assert!(
            matches!(
                error,
                StyleError::VariableLimit {
                    resource: "expanded value bytes",
                    limit: MAX_VALUE_BYTES
                }
            ),
            "CSS escaping must use the same bounded output writer: {error:?}"
        );
    }

    #[test]
    fn attribute_url_roles_distinguish_image_sources_from_metadata_and_fallback_color() {
        use crate::style::{declaration, grammar::Property};
        for (clean, tainted) in [
            ("image-set('t' 1x)", "image-set(attr(data-token) 1x)"),
            ("image('t')", "image(attr(data-token))"),
        ] {
            for (source, valid) in [(clean, true), (tainted, false)] {
                let environment = attribute_environment(source);
                let value = environment.get("--value").unwrap().as_ref().unwrap();
                assert_eq!(
                    declaration::expand_expanded(Property::BackgroundImage, value)
                        .unwrap()
                        .is_some(),
                    valid,
                    "semantic URL-role validation must distinguish clean and tainted image sources before painting capability checks: {source}"
                );
            }
        }
        for source in [
            "image-set('safe.png' type(attr(data-token)) 1x)",
            "image('safe.png',attr(missing <color>,red))",
        ] {
            let environment = attribute_environment(source);
            let value = environment.get("--value").unwrap().as_ref().unwrap();
            assert!(value.has_taint());
            assert!(
                declaration::expand_expanded(Property::BackgroundImage, value)
                    .unwrap()
                    .is_some(),
                "tainted non-URL operands must not contaminate an independent authored URL: {source}"
            );
        }
    }
}