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
use crate::dom::utils::extract_text;
use crate::*;
#[derive(Debug, Deserialize)]
#[serde(tag = "type")]
pub enum CompoundCondition {
TextContent {
pattern: String,
},
AttributeValue {
attribute: String,
pattern: String,
#[serde(default = "default_check_mode")]
check_mode: String,
#[serde(default)]
selector: String,
},
AttributeReference {
attribute: String,
reference_must_exist: bool,
},
ElementPresence {
selector: String,
},
Compound {
selector: String,
conditions: Vec<CompoundCondition>,
#[serde(default = "default_check_mode")]
check_mode: String,
},
}
fn default_check_mode() -> String {
"ensure_existence".to_string()
}
impl HtmlLinter {
pub(crate) fn check_custom(
&self,
rule: &Rule,
validator: &str,
index: &DOMIndex,
) -> Result<Vec<LintResult>, LinterError> {
let mut results = Vec::new();
let matches = index.query(&rule.selector);
for node_idx in matches {
if let Some(node) = index.get_node(node_idx) {
let (should_report, detailed_message) = match validator {
"no-empty-links" => {
let is_link =
index.resolve_symbol(node.tag_name).unwrap_or_default() == "a";
let is_empty = node.children.is_empty();
(
is_link && is_empty,
"Link element has no content. Links should contain text or other content to describe their purpose".to_string(),
)
}
"no-empty-headings" => {
let tag_name = index.resolve_symbol(node.tag_name).unwrap_or_default();
let is_heading = tag_name.starts_with('h');
let is_empty = node.children.is_empty();
(
is_heading && is_empty,
format!("Heading element <{}> has no content. Headings should contain text to maintain document structure", tag_name),
)
}
_ => (false, String::new()),
};
if should_report {
results.push(LintResult {
rule: rule.name.clone(),
severity: rule.severity.clone(),
message: format!("{} - {}", rule.message, detailed_message),
location: Location {
line: node.source_info.line,
column: node.source_info.column,
element: index
.resolve_symbol(node.tag_name)
.unwrap_or_default()
.to_string(),
},
source: node.source_info.source.clone(),
});
}
}
}
Ok(results)
}
pub(crate) fn check_compound(
&self,
rule: &Rule,
index: &DOMIndex,
) -> Result<Vec<LintResult>, LinterError> {
let mut results = Vec::new();
let matches = index.query(&rule.selector);
let conditions: Vec<CompoundCondition> = rule
.options
.get("conditions")
.ok_or_else(|| {
LinterError::RuleError("Missing conditions for compound rule".to_string())
})
.and_then(|conditions_str| {
serde_json::from_str(conditions_str)
.map_err(|e| LinterError::RuleError(format!("Invalid conditions JSON: {}", e)))
})?;
let check_mode = rule
.options
.get("check_mode")
.map(String::as_str)
.unwrap_or("all");
for node_idx in matches {
if let Some(node) = index.get_node(node_idx) {
let matching_conditions: Vec<bool> = conditions
.iter()
.map(|condition| self.check_single_condition(condition, node_idx, index))
.collect();
let should_report = match check_mode {
"any" => !matching_conditions.iter().any(|&x| x),
"all" => !matching_conditions.iter().all(|&x| x),
"none" => matching_conditions.iter().any(|&x| x),
"exactly_one" => matching_conditions.iter().filter(|&&x| x).count() != 1,
"at_least_one" => !matching_conditions.iter().any(|&x| x),
"majority" => {
let count = matching_conditions.iter().filter(|&&x| x).count();
count <= conditions.len() / 2
}
"weighted" => {
let weights = rule
.options
.get("weights")
.and_then(|w| serde_json::from_str::<Vec<f64>>(w).ok())
.unwrap_or_else(|| vec![1.0; conditions.len()]);
let threshold = rule
.options
.get("threshold")
.and_then(|t| t.parse::<f64>().ok())
.unwrap_or(1.0);
let total_weight = matching_conditions
.iter()
.zip(weights.iter())
.filter_map(
|(&matched, &weight)| if matched { Some(weight) } else { None },
)
.sum::<f64>();
total_weight < threshold
}
"dependency_chain" => {
let first_false = matching_conditions.iter().position(|&x| !x);
let any_true_after = first_false
.map(|pos| matching_conditions[pos..].iter().any(|&x| x))
.unwrap_or(false);
any_true_after
}
"alternating" => matching_conditions.windows(2).any(|w| w[0] == w[1]),
"subset_match" => {
if let Some(valid_sets_str) = rule.options.get("valid_sets") {
if let Ok(valid_sets) =
serde_json::from_str::<Vec<Vec<usize>>>(valid_sets_str)
{
let current_set: Vec<usize> = matching_conditions
.iter()
.enumerate()
.filter(|(_, &matched)| matched)
.map(|(i, _)| i)
.collect();
!valid_sets.iter().any(|set| {
set.iter().all(|&idx| current_set.contains(&idx))
&& current_set.iter().all(|&idx| set.contains(&idx))
})
} else {
false
}
} else {
false
}
}
_ => false,
};
if should_report {
let matching_count = matching_conditions.iter().filter(|&&x| x).count();
let total_conditions = conditions.len();
let detailed_message = match check_mode {
"any" => format!(
"None of the {} conditions were met. At least one condition must be satisfied",
total_conditions
),
"all" => format!(
"Only {}/{} conditions were satisfied. All conditions must be met",
matching_count,
total_conditions
),
"none" => format!(
"Found {} matching conditions where none should match. All conditions must fail",
matching_count
),
"exactly_one" => format!(
"Found {} matching conditions where exactly 1 was expected",
matching_count
),
"at_least_one" => format!(
"Found no matching conditions. At least 1 of {} conditions must match",
total_conditions
),
"majority" => format!(
"Only {}/{} conditions matched. More than half ({}) must match",
matching_count,
total_conditions,
(total_conditions / 2) + 1
),
"weighted" => {
let weights = rule
.options
.get("weights")
.and_then(|w| serde_json::from_str::<Vec<f64>>(w).ok())
.unwrap_or_else(|| vec![1.0; total_conditions]);
let threshold = rule
.options
.get("threshold")
.and_then(|t| t.parse::<f64>().ok())
.unwrap_or(1.0);
let total_weight: f64 = matching_conditions
.iter()
.zip(weights.iter())
.filter_map(|(&matched, &weight)| if matched { Some(weight) } else { None })
.sum();
format!(
"Total weight of matching conditions ({:.2}) is below required threshold ({:.2})",
total_weight,
threshold
)
},
"dependency_chain" => {
let chain_length = matching_conditions.iter().take_while(|&&x| x).count();
format!(
"Chain broken after {} conditions. Expected unbroken chain of {} matching conditions",
chain_length,
matching_count
)
},
"alternating" => {
let violation_index = matching_conditions
.windows(2)
.position(|w| w[0] == w[1])
.map(|i| i + 1)
.unwrap_or(0);
format!(
"Found consecutive {} conditions at position {}. Pattern must alternate between match/no-match",
if matching_conditions[violation_index] { "matching" } else { "non-matching" },
violation_index + 1
)
},
"subset_match" => {
if let Some(valid_sets_str) = rule.options.get("valid_sets") {
if let Ok(valid_sets) = serde_json::from_str::<Vec<Vec<usize>>>(valid_sets_str) {
let current_set: Vec<usize> = matching_conditions
.iter()
.enumerate()
.filter(|(_, &matched)| matched)
.map(|(i, _)| i)
.collect();
format!(
"Current matching set {:?} doesn't match any valid combination. Valid sets: {:?}",
current_set,
valid_sets
)
} else {
"Invalid valid_sets configuration".to_string()
}
} else {
"Missing valid_sets configuration".to_string()
}
},
_ => "Compound condition check failed".to_string(),
};
let condition_details: Vec<String> = conditions
.iter()
.zip(matching_conditions.iter())
.map(|(condition, &matched)| {
let status = if matched { "✓" } else { "✗" };
match condition {
CompoundCondition::TextContent { pattern } => {
format!("{} Text content pattern '{}' match", status, pattern)
}
CompoundCondition::AttributeValue {
attribute,
pattern,
check_mode,
selector,
} => {
format!(
"{} Attribute '{}' matching pattern '{}' with selector '{}' and check mode '{}'",
status, attribute, pattern, selector, check_mode
)
}
CompoundCondition::AttributeReference {
attribute,
reference_must_exist,
} => format!(
"{} Attribute '{}' reference {}",
status,
attribute,
if *reference_must_exist {
"exists"
} else {
"does not exist"
}
),
CompoundCondition::ElementPresence { selector } => {
format!(
"{} Element presence with selector '{}' {}",
status,
selector,
if matched { "exists" } else { "does not exist" }
)
}
CompoundCondition::Compound {
selector,
conditions,
check_mode,
} => {
format!(
"{} Compound condition with selector '{}' and check mode '{}' and {} conditions",
status,
selector,
check_mode,
conditions.len()
)
}
}
})
.collect();
results.push(LintResult {
rule: rule.name.clone(),
severity: rule.severity.clone(),
message: format!(
"{} - {} \nCondition details:\n{}",
rule.message,
detailed_message,
condition_details.join("\n")
),
location: Location {
line: node.source_info.line,
column: node.source_info.column,
element: index
.resolve_symbol(node.tag_name)
.unwrap_or_default()
.to_string(),
},
source: node.source_info.source.clone(),
});
}
}
}
Ok(results)
}
fn check_single_condition(
&self,
condition: &CompoundCondition,
node_idx: usize,
index: &DOMIndex,
) -> bool {
match condition {
CompoundCondition::Compound {
selector,
conditions,
check_mode,
} => {
let nested_selector = if selector.is_empty() {
format!("#{}", node_idx)
} else {
let current_node = index.get_node(node_idx).unwrap();
format!("{} {}", current_node.get_selector(index), selector)
};
let nested_matches = index.query(&nested_selector);
let mut results = Vec::new();
for nested_node_idx in nested_matches {
let nested_results: Vec<bool> = conditions
.iter()
.map(|cond| self.check_single_condition(cond, nested_node_idx, index))
.collect();
let matches = match check_mode.as_str() {
"all" => nested_results.iter().all(|&x| x),
"any" => nested_results.iter().any(|&x| x),
"none" => !nested_results.iter().any(|&x| x),
"exactly_one" => nested_results.iter().filter(|&&x| x).count() == 1,
_ => nested_results.iter().all(|&x| x),
};
results.push(matches);
}
if results.is_empty() {
return false;
}
results.iter().any(|&x| x)
}
CompoundCondition::TextContent { pattern } => {
let node = index.get_node(node_idx).unwrap();
let mut content = String::new();
if let Some(handle) = &node.handle {
extract_text(handle, &mut content);
if content.trim().is_empty() {
return false;
}
Regex::new(pattern)
.map(|regex| regex.is_match(content.trim()))
.unwrap_or(false)
} else {
false
}
}
CompoundCondition::AttributeValue {
attribute,
pattern,
check_mode,
selector,
} => {
let target_nodes = if selector.is_empty() {
vec![node_idx]
} else {
let current_node = index.get_node(node_idx).unwrap();
let scoped_selector =
format!("{} {}", current_node.get_selector(index), selector);
index.query(&scoped_selector)
};
for target_idx in target_nodes {
if let Some(node) = index.get_node(target_idx) {
if let Ok(regex) = Regex::new(pattern) {
let matches = node.attributes.iter().any(|attr| {
let name = index.resolve_symbol(attr.name).unwrap_or_default();
let value = index.resolve_symbol(attr.value).unwrap_or_default();
name == *attribute
&& !value.trim().is_empty()
&& regex.is_match(value.trim())
});
match check_mode.as_str() {
"ensure_existence" => {
if matches {
return true;
}
}
"ensure_nonexistence" => {
if !matches {
return true;
}
}
_ => {
if matches {
return true;
}
}
}
}
}
}
false
}
CompoundCondition::AttributeReference {
attribute,
reference_must_exist,
} => {
if let Some(node) = index.get_node(node_idx) {
if let Some(attr) = node.attributes.iter().find(|attr| {
index.resolve_symbol(attr.name).unwrap_or_default() == *attribute
}) {
let value = index.resolve_symbol(attr.value).unwrap_or_default();
if !value.trim().is_empty() {
let referenced_selector = format!("[id=\"{}\"]", value.trim());
let exists = !index.query(&referenced_selector).is_empty();
return exists == *reference_must_exist;
}
}
}
false
}
CompoundCondition::ElementPresence { selector } => {
if let Some(node) = index.get_node(node_idx) {
let current_selector = format!("{} {}", node.get_selector(index), selector);
let matches = index.query(¤t_selector);
!matches.is_empty()
} else {
false
}
}
}
}
}