Skip to main content

whichtime_sys/parsers/pt/
weekday.rs

1//! Portuguese weekday parser
2//!
3//! Handles Portuguese weekday expressions like:
4//! - "segunda", "na terça-feira"
5//! - "próxima sexta", "sexta passada"
6//! - "sexta que vem", "domingo anterior"
7
8use crate::components::Component;
9use crate::context::ParsingContext;
10use crate::dictionaries::RelativeModifier;
11use crate::dictionaries::pt::{get_relative_modifier, get_weekday};
12use crate::error::Result;
13use crate::parsers::Parser;
14use crate::results::ParsedResult;
15use chrono::{Datelike, Duration};
16use fancy_regex::Regex;
17use std::sync::LazyLock;
18
19static PATTERN: LazyLock<Regex> = LazyLock::new(|| {
20    Regex::new(
21        r"(?ix)
22        (?<![a-zA-Z])
23        (?:(?:em|na|no)\s+)?
24        (?:
25            (?P<prefix>esta|este|próxima|proxima|próximo|proximo|passada|passado|última|ultima|último|ultimo)
26            \s+
27        )?
28        (?P<weekday>domingo|dom\.?|segunda(?:-feira)?|seg\.?|terça(?:-feira)?|terca(?:-feira)?|ter\.?|quarta(?:-feira)?|qua\.?|quinta(?:-feira)?|qui\.?|sexta(?:-feira)?|sex\.?|sábado|sabado|sab\.?)
29        (?:
30            \s+
31            (?P<suffix_mod>passada|passado|que\s+vem|seguinte|anterior|próxima|proxima|próximo|proximo)
32        )?
33        (?=\W|$)
34        "
35    ).unwrap()
36});
37
38/// Portuguese weekday parser
39pub struct PTWeekdayParser;
40
41impl PTWeekdayParser {
42    pub fn new() -> Self {
43        Self
44    }
45}
46
47impl Default for PTWeekdayParser {
48    fn default() -> Self {
49        Self::new()
50    }
51}
52
53impl Parser for PTWeekdayParser {
54    fn name(&self) -> &'static str {
55        "PTWeekdayParser"
56    }
57
58    fn should_apply(&self, _context: &ParsingContext) -> bool {
59        true
60    }
61
62    fn parse(&self, context: &ParsingContext) -> Result<Vec<ParsedResult>> {
63        let mut results = Vec::new();
64        let ref_date = context.reference.instant;
65        let ref_weekday = ref_date.weekday().num_days_from_sunday() as i64;
66
67        let mut start = 0;
68        while start < context.text.len() {
69            let search_text = &context.text[start..];
70            let captures = match PATTERN.captures(search_text) {
71                Ok(Some(caps)) => caps,
72                Ok(None) => break,
73                Err(_) => break,
74            };
75
76            let full_match = match captures.get(0) {
77                Some(m) => m,
78                None => break,
79            };
80
81            let match_start = start + full_match.start();
82            let match_end = start + full_match.end();
83            let matched_text = full_match.as_str();
84
85            let weekday_str = captures
86                .name("weekday")
87                .map(|m| m.as_str().to_lowercase())
88                .unwrap_or_default();
89            let prefix_str = captures.name("prefix").map(|m| m.as_str().to_lowercase());
90            let suffix_mod_str = captures
91                .name("suffix_mod")
92                .map(|m| m.as_str().to_lowercase());
93
94            let Some(weekday) = get_weekday(&weekday_str) else {
95                start = match_end;
96                continue;
97            };
98
99            let target_weekday = weekday as i64;
100
101            // Determine modifier from prefix or suffix
102            let modifier = prefix_str
103                .as_ref()
104                .and_then(|s| get_relative_modifier(s))
105                .or_else(|| {
106                    suffix_mod_str.as_ref().and_then(|s| {
107                        if s.contains("que vem") || s.contains("seguinte") {
108                            Some(RelativeModifier::Next)
109                        } else {
110                            get_relative_modifier(s)
111                        }
112                    })
113                });
114
115            // Calculate days offset
116            let days_offset = match modifier {
117                Some(RelativeModifier::Next) => {
118                    let diff = target_weekday - ref_weekday;
119                    if diff <= 0 { diff + 7 } else { diff }
120                }
121                Some(RelativeModifier::Last) => {
122                    let diff = target_weekday - ref_weekday;
123                    if diff >= 0 { diff - 7 } else { diff }
124                }
125                Some(RelativeModifier::This) | None => {
126                    // Default behavior: find closest day
127                    let diff = target_weekday - ref_weekday;
128                    if diff == 0 {
129                        0
130                    } else if diff > 0 {
131                        if diff <= 3 { diff } else { diff - 7 }
132                    } else if diff >= -3 {
133                        diff
134                    } else {
135                        diff + 7
136                    }
137                }
138            };
139
140            let target_date = ref_date + Duration::days(days_offset);
141
142            let mut components = context.create_components();
143            components.assign(Component::Year, target_date.year());
144            components.assign(Component::Month, target_date.month() as i32);
145            components.assign(Component::Day, target_date.day() as i32);
146            components.assign(Component::Weekday, target_weekday as i32);
147
148            // Find actual text bounds (trim leading/trailing non-alphanumeric)
149            let actual_start = matched_text
150                .find(|c: char| c.is_alphanumeric())
151                .unwrap_or(0);
152            let actual_end = matched_text
153                .rfind(|c: char| c.is_alphanumeric())
154                .map(|i| i + matched_text[i..].chars().next().map_or(1, char::len_utf8))
155                .unwrap_or(matched_text.len());
156
157            results.push(context.create_result(
158                match_start + actual_start,
159                match_start + actual_end,
160                components,
161                None,
162            ));
163
164            start = match_end;
165        }
166
167        Ok(results)
168    }
169}