Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qtparsetemporal.cpp
Go to the documentation of this file.
1// Copyright (C) 2026 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:critical reason:data-parser
4#include "private/qtparsetemporal_p.h"
5
6#include "private/qcalendarmath_p.h"
7#include "private/qlocale_p.h"
8#include "private/qstringiterator_p.h"
9#include "private/qttemporalpattern_p.h"
10
11#include <algorithm> // sort, stable_sort
12#include <QtCore/qxpfunctional.h>
13#include <optional>
14#include <utility> // exchange, move, pair
15#include <vector>
16
17QT_BEGIN_NAMESPACE
18
19namespace {
20using namespace QtParseTemporal;
21using namespace QtTemporalPattern;
22
24{
26 int periodInDay = -1; // 0: am, 1: pm
27 int hourMod12 = 0; // 1 through 12
28 int yearWithinCentury = -1; // 0 through 99
29 static constexpr int UnknownAmHour = -12, UnknownPmHour = 36;
30 enum Flaw : quint16 {
31 // Flaws that justify prefering a shorter parse without the flaw over
32 // longer with it, in order of decreasing severity:
33 Irreconcilable = 1, // field values cannot be reconciled
34 // Ideally continuations() would catch irreconcilable issues, but if one
35 // is expensive to spot it can be left for resolve() to flag up.
36 LegacyResolves = 2, // field values can only be resolved by ignoring timeType
37 ResolutionChanges = 4, // resolved values don't match parsed values
38 ZeroPad = 8, // used zero-padded part of text where field didn't require it
39 Narrow = 0x10, // used fewer digits from text than field width, where allowed
40
41 // Flaws not worth giving up a longer parse over, in decreasing order of
42 // strength of preference among those of equal length:
43 SelfResolved = 0x100, // ambiguous field values resolve cleanly
44 };
45 Q_DECLARE_FLAGS(Flaws, Flaw)
47
48 // Constructor for initial empty parse:
49 PartialParse(qsizetype from) { results.startIndex = results.endIndex = from; }
50 // Constructors extending a parse with something more:
51 PartialParse(const PartialParse &base, const QtParseCommon::ParsedText &more)
52 : PartialParse(base)
53 {
54 Q_ASSERT(results.endIndex == more.startIndex);
55 results.endIndex = more.endIndex;
56 }
57 PartialParse(const PartialParse &base, const QtParseTimeZone::ParsedZone &more)
59 {
60 results.zone = more.zone;
61 results.timeType = more.timeType;
62 }
63
64 Qt::weak_ordering compare(const PartialParse &alt) const noexcept
65 {
66 // Measures of how this->wanton differs from alt.wanton: it's worse if
67 // it has a flaw that alt lacks, better if the opposite. Here, "less" is
68 // used to mean "this is better than alt" as we sort better entries
69 // earlier in our lists of partial parse candidates.
70 const auto order = [better = alt.wanton & ~wanton,
71 worse = wanton & ~alt.wanton](Flaw test) {
72 Q_ASSERT(!(worse & better)); // So at most one of these testFlag()s is true:
73 if (better.testFlag(test))
74 return Qt::weak_ordering::less;
75 if (worse.testFlag(test))
76 return Qt::weak_ordering::greater;
77 return Qt::weak_ordering::equivalent;
78 };
79
80 if (auto res = order(Flaw::Irreconcilable); res != 0)
81 return res;
82
83 // In decreasing order of severity
84 if (auto res = order(Flaw::LegacyResolves); res != 0)
85 return res;
86 if (auto res = order(Flaw::ResolutionChanges); res != 0)
87 return res;
88 if (auto res = order(Flaw::Narrow); res != 0)
89 return res;
90
91 // The above take precedence over size: a shorter parse without those
92 // flaws is better than a longer one with them.
93
94 // Longer is better, to be understood as "sorts before" i.e. less than.
95 if (auto res = Qt::compareThreeWay(alt.results.size(), results.size()); res != 0)
96 return res;
97
98 // The following remains as a preference only among matches of the same
99 // length: it's nice to avoid, but a longer parse is still better.
100
101 if (auto res = order(Flaw::ZeroPad); res != 0)
102 return res;
103 if (auto res = order(Flaw::SelfResolved); res != 0)
104 return res;
105
106 return Qt::weak_ordering::equivalent;
107 }
108};
109Q_DECLARE_OPERATORS_FOR_FLAGS(PartialParse::Flaws)
110
111QLocaleData::DigitSequence
112parseDigitSequence(QStringView text, qsizetype from, const QLocale &locale, bool allowSign,
113 qsizetype maxDigits)
114{
115 const auto *const data = QLocalePrivate::get(locale)->m_data;
116 using DS = QLocaleData::DigitSequence;
117 DS::Options flags;
118 if (allowSign)
119 flags.setFlag(DS::Option::AllowSign, true);
120 return data->digitSequence(text, flags, from, maxDigits);
121}
122
123std::vector<PartialParse> spacePadExtend(std::vector<PartialParse> matched, QStringView text)
124{
125 // Pass the whole text: the results.endIndex of the last entry in matched is
126 // an index into it that we shall use to add entries that extend that entry.
127 Q_ASSERT(!matched.empty());
128 // Assumes matched.back()'s last field is allowed to end in space-padding
129 // and inserts a partial parse resulting from accepting each subsequent
130 // space as extending the match. Each longer match is inserted before all
131 // shorter matches. Only extensions of matched.back() are added, so call
132 // after adding each entry to matched, if adding several.
133 const qsizetype position = matched.size() - 1;
134 PartialParse copy = matched.back();
135 QStringIterator iter(text, copy.results.endIndex);
136 while (iter.hasNext() && QChar::isSpace(iter.next())) {
137 Q_ASSERT(iter.index() > copy.results.endIndex);
138 copy.results.endIndex = iter.index();
139 matched.insert(matched.begin() + position, copy);
140 }
141 return matched;
142}
143
144QtParseCommon::ParsedText matchedAt(QStringView text, qsizetype from, const QString &sought,
145 TemporalFieldFlags flags)
146{
147 using F = TemporalFieldFlag;
148 const bool allowLeadingSpace = flags.testFlag(F::SpacePad);
149 Q_ASSERT(sought.size() > 0);
150 // Note: returns the first match within text[from:]. If sought is all space
151 // and SpacePad is set, there may be later matches if text[from:] starts
152 // with more space than (possibly some non-matching spaces, then) that.
153 // caller is expected to follow the match implied by the return from this
154 // with more generated by spacePadExtend().
155
156 const auto beginLength = [flex = flags.testFlag(F::FlexSpace),
157 strict = flags.testFlag(F::StrictSpace)]
158 (QStringView view, QStringView target, Qt::CaseSensitivity cs = Qt::CaseSensitive) {
159 // Technical hitch: case-insensitive comparison may match a string of
160 // different length. Roll a brute-force length-determining version:
161 const auto matchFront = [cs](QStringView view, QStringView target) -> qsizetype {
162 if (target.isEmpty()) // Only empty matches empty.
163 return 0;
164 if (view.startsWith(target, cs)) {
165 qsizetype length = target.size();
166 // Non-empty target can't be matched by view.first(0) so length
167 // == 1 won't satisfy this loop condition and, as length is
168 // initially > 0, we don't need to bounds-check this:
169 while (view.first(length - 1).startsWith(target, cs))
170 --length;
171 // We know view as a whole does start with target, so this won't
172 // run past length == view.size():
173 while (!view.first(length).startsWith(target, cs))
174 ++length;
175 Q_ASSERT(length > 0);
176 return length;
177 }
178 return -1;
179 };
180 const auto spacingForward = [](QStringIterator &iter) {
181 // Steps iter past next non-space, returns index at which it appeared.
182 qsizetype used;
183 do {
184 used = iter.index();
185 } while (iter.hasNext() && QChar::isSpace(iter.next()));
186 return used;
187 };
188 const auto matchingSpace = [](char32_t need, char32_t have) {
189 constexpr char32_t ASCIImax = 0x7f;
190 // Treat SPACE and non-ASCII spaces as equivalent:
191 if (need == U' ' || need > ASCIImax)
192 return have == U' ' || have > ASCIImax;
193 // Otherwise, require exact match:
194 return need == have;
195 };
196
197 constexpr qsizetype failed = 0;
198 qsizetype matched = 0;
199 if (flex || !strict) {
200 QStringIterator iter(target);
201 // Advance through the string; on each space, check match since last
202 // space then matching of spaces; and prune view, target past match.
203 while (iter.hasNext()) {
204 qsizetype head = iter.index();
205 if (const char32_t tgt = iter.next(); QChar::isSpace(tgt)) {
206 // Match any non-space stepped over since start or last space:
207 qsizetype same = head ? matchFront(view, target.first(head)) : 0;
208 if (same < 0)
209 return failed;
210 QStringIterator viter(view, same);
211 // Require at least one spacing character in view to match target's:
212 if (!viter.hasNext())
213 return failed;
214 if (const char32_t got = viter.next(); !QChar::isSpace(got))
215 return failed;
216 else if (flex)
217 same = spacingForward(viter);
218 else if (!matchingSpace(tgt, got))
219 return failed;
220 else
221 same = viter.index();
222 matched += same;
223 view = view.sliced(same);
224 target = target.sliced(flex ? spacingForward(iter) : iter.index());
225 iter = QStringIterator(target);
226 // In the flex case, the next iteration will step over a non-space:
227 Q_ASSERT(!flex || !iter.hasNext() || !QChar::isSpace(iter.peekNext()));
228 }
229 }
230 // If target isn't empty, it's a spacing-free tail, to be checked
231 // the same way we would the whole would be in strict mode.
232 }
233 const qsizetype tail = matchFront(view, target);
234 if (tail < 0)
235 return failed;
236 return matched + tail;
237 };
238 // TODO: consider a comparison that ignores Unicode invisibles, like BiDi
239 // markers, when matching.
240 qsizetype offset = 0;
241 do {
242 QStringView view = text.sliced(from + offset);
243 if (flags.testFlag(F::IgnoreCase)) {
244 if (qsizetype match = beginLength(view, sought, Qt::CaseInsensitive))
245 return {from, from + offset + match};
246 } else if (flags.testAnyFlags(F::LowerCase | F::UpperCase)) {
247 // If either case is specified, only match specified cases.
248 // If both cases are specified, accept either (but not mixed).
249 if (flags.testFlag(F::LowerCase)) {
250 if (qsizetype match = beginLength(view, sought.toLower()))
251 return {from, from + offset + match};
252 }
253 if (flags.testFlag(F::UpperCase)) {
254 if (qsizetype match = beginLength(view, sought.toUpper()))
255 return {from, from + offset + match};
256 }
257 // Otherwise, only an exact match is accepted:
258 } else if (qsizetype match = beginLength(view, sought)) {
259 return {from, from + offset + match};
260 }
261
262 // No match at this position; maybe later if leading space is allowed:
263 if (!allowLeadingSpace) {
264 Q_ASSERT(!offset);
265 break;
266 }
267
268 // Consume one space at a time until we find a match:
269 QStringIterator iter(text.sliced(from), offset);
270 if (!iter.hasNext() || !QChar::isSpace(iter.next()))
271 break;
272
273 Q_ASSERT(iter.index() > offset);
274 offset = iter.index();
275 } while (text.size() >= offset + sought.size() / 2);
276 // Loop wants to test text.size() >= offset + sought.size(), but see beginLength().
277 return {};
278}
279
280bool longerEarlier(const PartialParse &left, const PartialParse &right)
281{
282 // True if we want left before right in our sorted lists.
283 // We want longer matches before shorter:
284 return left.results.endIndex > right.results.endIndex;
285}
286
287void forEachLocaleFormat(TemporalFieldFlags flags,
288 qxp::function_ref<void(QLocale::FormatType) const> action)
289{
290 using Flag = TemporalFieldFlag;
291 constexpr auto Widths = FieldGroup::WidthMask;
292 if (matchesFlagWithin(flags, Flag::Wide, Widths))
293 action(QLocale::LongFormat);
294 if (matchesFlagsWithin(flags, Flag::Short | Flag::Abbreviated, Widths))
295 action(QLocale::ShortFormat);
296 if (matchesFlagWithin(flags, Flag::Narrow, Widths))
297 action(QLocale::NarrowFormat);
298}
299
301{
302 const QLocale locale;
303 const QCalendar calendar;
304 const std::optional<int> baseYear;
305
306 // Numeric
307 struct FieldConfig
308 {
309 // Where to write the int, once read:
310 int &(*target)(PartialParse &);
311 bool alreadySet = false; // Did base parse already know this field ?
312 // Acceptable values:
313 int maxValue = 0; // 0 means unbounded
314 bool allowZero = false;
315 // Form of the parsed text:
316 qsizetype width; // min digits
317 qsizetype maxDigits = 0; // <= 0 means unbounded
318 // If unbounded, beyond max(width, roundAfter, -maxDigits) prefer fewer digits to more.
319 qsizetype roundAfter = -1; // >= 0: is fractional part: round to this many digits
320 // (Values with fewer than roundAfter digits will also be *=10'd up to match.)
321 // Special cases for year:
322 bool allowSign = false;
323 bool allowNegative = false;
324 };
325 // For use as FieldConfig::target:
326 static int &millisTarget(PartialParse &grow) { return grow.results.millis; }
327 static int &secondTarget(PartialParse &grow) { return grow.results.second; }
328 static int &minuteTarget(PartialParse &grow) { return grow.results.minute; }
329 static int &hourTarget(PartialParse &grow) { return grow.results.hour; }
330 static int &hourMod12Target(PartialParse &grow) { return grow.hourMod12; }
331 static int &dayOfWeekTarget(PartialParse &grow) { return grow.results.dayOfWeek; }
332 static int &dayOfMonthTarget(PartialParse &grow) { return grow.results.dayOfMonth; }
333 static int &monthTarget(PartialParse &grow) { return grow.results.month; }
334 static int &yearTarget(PartialParse &grow)
335 {
336 // Always called on a freshly-copied grow that shall be discarded unless
337 // year was previously unset or equal to the value about to be set. In
338 // the latter case we already have that value to return a reference to
339 // and in the former the caller already knows to overwrite, so setting
340 // any value will suffice to give us a reference it can overwrite:
341 if (!grow.results.year)
342 grow.results.year = 0;
343 return *grow.results.year;
344 }
345 static int &yearWithinCenturyTarget(PartialParse &grow) { return grow.yearWithinCentury; }
346
347 std::vector<PartialParse>
348 numericExtend(const PartialParse &base, QStringView text,
349 TemporalFieldFlags flags, FieldConfig &&config) const;
350
351 // Verbal, Standalone:
352 std::vector<PartialParse> monthNameExtend(const PartialParse &base, QStringView text,
353 TemporalFieldFlags flags) const;
354 std::vector<PartialParse> dayNameExtend(const PartialParse &base, QStringView text,
355 TemporalFieldFlags flags) const;
356 std::pair<qsizetype, int> dayPeriodPrefix(const PartialParse &base, QStringView text,
357 TemporalFieldFlags flags) const;
358public:
359 TemporalFieldMatcher(const QLocale &loc, QCalendar cal, std::optional<int> centuryStart)
361 {}
362
363 std::vector<PartialParse> continuations(const PartialParse &base, QStringView text,
364 const TemporalField &field) const;
365 bool isSelfConsistent(const PartialParse &parsed, TemporalFieldCategory category) const;
366 bool resolve(PartialParse &parsed) const;
367};
368
370 TemporalFieldCategory category) const
371{
372 // Take into account calendar, and potentially baseYear, but only do cheap
373 // checks. This will be run on *each* candidate parse after *each* field,
374 // need not check conditions the current field could not have affected.
375 using Cat = TemporalFieldCategory;
376 if (category == Cat::Literal) // Can't have introduced any inconsistency.
377 return true;
378
379 const bool newYear = category == Cat::Year || category == Cat::YearWithinCentury;
380 if (newYear && parse.yearWithinCentury >= 0 && parse.results.year
381 && (*parse.results.year - parse.yearWithinCentury) % 100) {
382 return false;
383 }
384
385 const bool newDate = (newYear || category == Cat::Month || category == Cat::DayOfMonth
386 || category == Cat::DayOfWeek);
387 if (newDate && parse.results.month && parse.results.dayOfMonth) {
388 // Calendrical calculations: somewhat expensive, but still arithmetic.
389 if (parse.results.year) {
390 if (!calendar.isDateValid(*parse.results.year, parse.results.month,
391 parse.results.dayOfMonth)) {
392 return false;
393 }
394 if (parse.results.dayOfWeek) {
395 QDate date = calendar.dateFromParts(*parse.results.year, parse.results.month,
396 parse.results.dayOfMonth);
397 if (calendar.dayOfWeek(date) != parse.results.dayOfWeek)
398 return false;
399 }
400 } else if (calendar.daysInMonth(parse.results.month) < parse.results.dayOfMonth) {
401 return false;
402 }
403 }
404
405 if ((category == Cat::PeriodInDay && parse.results.hour >= 0)
406 || (category == Cat::Hour && parse.periodInDay >= 0)) {
407 // 00, 01, ... 11 are 12, 1, ... 11 am; 12, 13, ... 23 are 12, 1, ..., 11 pm.
408 if (parse.periodInDay ? parse.results.hour < 12 : parse.results.hour >= 12)
409 return false;
410 }
411
412 if ((category == Cat::Hour && parse.hourMod12 > 0)
413 || (category == Cat::HourMod12 && parse.results.hour >= 0)) {
414 if ((parse.results.hour - parse.hourMod12) % 12)
415 return false;
416 }
417 return true;
418}
419
421{
422 // Final pass, modifying parsed as needed, true if parse.result has been
423 // given a value consistent with all fields of parse. Applies fully rigorous
424 // checks, given what isSelfConsistent() already checked. May record flaws
425 // in parse.wanton where relevant tests reveal them.
426 if (parse.yearWithinCentury >= 0) {
427 if (parse.results.year) {
428 // Previously checked by isSelfConsistent():
429 Q_ASSERT((*parse.results.year - parse.yearWithinCentury) % 100 == 0);
430 } else if (baseYear) {
431 const auto baseSplit =QRoundingDown::qDivMod<100>(*baseYear);
432 int year = baseSplit.quotient * 100 + parse.yearWithinCentury;
433 if (parse.yearWithinCentury < baseSplit.remainder)
434 year += 100;
435
436 if (parse.results.month) {
437 // Check the year has this month and, if given, enough days in
438 // it for dayOfMonth:
439 const auto enough = [dom = parse.results.dayOfMonth](int dim) {
440 return dim > 0 && (!dom || dom <= dim);
441 };
442 if (!enough(calendar.daysInMonth(parse.results.month, year))) {
443 // Search outwards for a better century:
444 bool fixed = false;
445 for (int off = 1; off < 10; ++off) {
446 int offset = off * 100;
447 if (enough(calendar.daysInMonth(parse.results.month, year + offset))) {
448 year += offset;
449 fixed = true;
450 break;
451 }
452 if (enough(calendar.daysInMonth(parse.results.month, year - offset))) {
453 year -= offset;
454 fixed = true;
455 break;
456 }
457 }
458 // No century within a millennium each way will do:
459 if (!fixed)
460 return false;
461 }
462
463 if (parse.results.dayOfMonth) {
464 if (parse.results.dayOfWeek) {
465 QCalendar::YearMonthDay ymd
466 = { year, parse.results.month, parse.results.dayOfMonth };
467 const QDate resolved
468 = calendar.matchCenturyToWeekday(ymd, parse.results.dayOfWeek);
469 if (!resolved.isValid())
470 return false;
471 year = resolved.year(calendar);
472 } else {
473 const QDate resolved(year, parse.results.month, parse.results.dayOfMonth);
474 if (!resolved.isValid())
475 return false;
476 }
477 }
478 }
479
480 parse.results.year = year;
481 }
482 }
483
484 if (parse.results.hour < 0 && parse.hourMod12 > 0) {
485 Q_ASSERT(parse.hourMod12 <= 12);
486 parse.results.hour = parse.hourMod12 < 12 || parse.periodInDay < 0 ? parse.hourMod12 : 0;
487 if (parse.periodInDay > 0)
488 parse.results.hour += 12;
489 }
490
491 if (parse.results.year && parse.results.month && parse.results.dayOfMonth
492 && parse.results.zone.isValid() && parse.results.hour >= 0) {
493 // Should be able to construct a datetime with this:
494 const QDate date(*parse.results.year, parse.results.month, parse.results.dayOfMonth,
495 calendar);
496 Q_ASSERT(date.isValid()); // Should be ensured by earlier checks.
497 const QTime time = parse.results.time(QTime());
498 Q_ASSERT(time.isValid()); // Should be ensured by earlier checks.
499
500 // Is the given time in a transition of the given zone, on the given date ?
501 if (!Q_LIKELY(QDateTime(date, time, parse.results.zone,
502 QDateTime::TransitionResolution::Reject).isValid())) {
503 // Ambiguity, gap or outright borkage.
504 using Flaw = PartialParse::Flaw;
505 QDateTime dt(date, time, parse.results.zone, parse.results.resolveType());
506 if (!dt.isValid()) {
507 // Fall back to default resolution (same as LegacyBehavior):
508 dt = QDateTime(date, time, parse.results.zone);
509 // If that succeeded, Abbreviated (bad); otherwise Narrow (worse).
510 parse.wanton |= dt.isValid() ? Flaw::LegacyResolves : Flaw::Irreconcilable;
511 }
512 if (dt.date() != date || dt.time() != time
513 || dt.timeRepresentation() != parse.results.zone) {
514 // OK, resolution *worked* but didn't get exactly what we asked
515 // for (presumably a spring-forward's gap):
516 parse.wanton |= Flaw::ResolutionChanges;
517 // ... but we don't change parse.results because they should
518 // reflect what parsing learned; the caller can rediscover this.
519 } else {
520 // We got what we asked for (presumably the expected branch of a
521 // fall-back):
522 parse.wanton |= Flaw::SelfResolved;
523 }
524 }
525 }
526
527 if (parse.results.hour < 0) {
528 // Leave ParsedTemporal::time() a clue to am/pm, if known:
529 if (parse.periodInDay > 0)
530 parse.results.hour = PartialParse::UnknownPmHour;
531 else if (parse.periodInDay == 0)
532 parse.results.hour = PartialParse::UnknownAmHour;
533 }
534 return true;
535}
536
537std::vector<PartialParse>
538TemporalFieldMatcher::numericExtend(const PartialParse &base, QStringView text,
539 TemporalFieldFlags flags, FieldConfig &&config) const
540{
541 std::vector<PartialParse> matches;
542
543 using Flag = TemporalFieldFlag;
544 qsizetype leadingSpace = 0;
545 const bool spacePad = flags.testFlag(Flag::SpacePad);
546 if (spacePad) {
547 QStringIterator iter(text, base.results.endIndex);
548 while (iter.hasNext() && QChar::isSpace(iter.next()))
549 ++leadingSpace;
550 // If that's used up the string, the code below shall reject the field.
551 }
552
553 // Parsed field must be representable in an int, so don't try to read more
554 // digits than an int can hold (digits10 is how many 9s in a row an int can
555 // hold; but int can hold some sequences one digit longer than that):
556 constexpr qsizetype IntMaxDigits = std::numeric_limits<int>::digits10 + 1;
557 // TODO: for SecondFraction, if width is unlimited (not yet exercised),
558 // iterate past stray dangling digits, within reason, after useful data.
559
560 const auto parsed = parseDigitSequence(text, base.results.endIndex + leadingSpace,
561 locale, config.allowSign, IntMaxDigits);
562 if (parsed.sign == '-' && !config.allowNegative)
563 return matches;
564 const bool zeroPad = flags.testFlag(Flag::ZeroPad);
565 // If !zeroPad, we allow < config.width but flag with Narrow in wanton fields.
566 const int width = zeroPad || spacePad ? qMax(1, config.width - leadingSpace) : 1;
567 // This is necessarily positive: the use of chop(1) below depends on that.
568
569 QByteArrayView digits{parsed.digits};
570 // Take config and flags into account, too:
571 if (config.maxDigits > 0) {
572 // Allow config.width to override config.maxDigits:
573 const int maxWidth = qMax(config.maxDigits, config.width);
574 if (digits.size() > maxWidth)
575 digits = digits.first(maxWidth);
576 } else if (flags.testFlag(Flag::YearSignIso8601) && !parsed.sign) {
577 // Limit width because a field longer than width would need a sign.
578 const int maxWidth = qMax(-config.maxDigits, config.width > 0 ? config.width : 1);
579 if (digits.size() > maxWidth)
580 digits = digits.first(maxWidth);
581 }
582 // For unbounded, work out in advance when to switch from prepending to
583 // appending; otherwise, set a cut-off that'll be true already.
584 const qsizetype appendThreshold = config.maxDigits <= 0
585 ? qMax(-config.maxDigits, qMax(config.width, config.roundAfter)) - 1
586 : digits.size();
587
588 for (; digits.size() >= width; digits.chop(1)) {
589 bool ok = false;
590 unsigned whole = digits.toUInt(&ok);
591 if (!ok)
592 continue;
593 if (config.maxValue > 0 && config.roundAfter < 0 && whole > unsigned(config.maxValue))
594 continue;
595
596 auto optvalue = [whole, forbidZero = !config.allowZero,
597 negate = parsed.sign == '-']() -> std::optional<int> {
598 constexpr unsigned maxInt = std::numeric_limits<int>::max();
599 if (negate && whole == 1 + maxInt)
600 return std::numeric_limits<int>::min();
601 if (whole > maxInt || (forbidZero && !whole))
602 return {};
603 return negate ? -int(whole) : int(whole);
604 }();
605 if (!optvalue) // Overflow or too low
606 continue;
607 int value = *optvalue;
608
609 if (config.roundAfter >= 0) {
610 // Fractional part
611 if (digits.size() < config.roundAfter) {
612 // Interpolate omitted zero-padding up to rounding size:
613 for (int i = int(digits.size()); i < config.roundAfter; ++i)
614 value *= 10;
615 } else if (digits.size() > config.roundAfter) {
616 double v = value;
617 for (int i = int(digits.size()); i > config.roundAfter; --i)
618 v /= 10.;
619 // A timestamp that's before the end of a specified second
620 // should be rounded to the last we can before that second,
621 // especially if it's the last second of its minute, in turn
622 // especially if that's the last second of its hour (and so on).
623 value = v > config.maxValue ? config.maxValue : qRound(v);
624 // There may of course be use-cases where rounding up to the
625 // next second is desired. If it turns out those are
626 // significant, we can perhaps add a field option for it.
627 }
628 // else: exact match to number of digits, nothing to frob.
629 }
630
631 PartialParse grow = base;
632 int &target = config.target(grow);
633 if (!config.alreadySet) // If not previously set, store:
634 target = value;
635 else if (target != value) // Conflicts with earlier field: skip this reading.
636 continue;
637 grow.results.endIndex = parsed.digitBounds[digits.size()];
638
639 if (!zeroPad && digits.size() > qMax(1, config.width)
640 && (config.roundAfter < 0 ? digits.startsWith('0') : digits.endsWith('0'))) {
641 grow.wanton |= PartialParse::Flaw::ZeroPad;
642 }
643 if (digits.size() + leadingSpace < config.width) // (can only happen if !zeroPad)
644 grow.wanton |= PartialParse::Flaw::Narrow;
645
646 // Entries in matches are all longer than this one, as we're reducing
647 // digits. Mostly we want shorter after longer, but (for example) we
648 // prefer 4-digit years over longer matches.
649 if (digits.size() > appendThreshold)
650 matches.insert(matches.begin(), std::move(grow));
651 else
652 matches.push_back(std::move(grow));
653 }
654 return matches;
655}
656
657/* Some month names may be prefixes of others.
658 For example, the English long forms of Islamic calendar month names include:
659 * RabiÊ» I, RabiÊ» II
660 * Jumada I, Jumada II
661 Their short-forms are likewise:
662 * Rab. I, Rab. II
663 * Jum. I, Jum. II
664 In each case, one month name is a prefix of the next month's name.
665
666 In any sane format, greedy parsing shall suffice but ill-considered formats
667 happen. So the initial parse recognizes every possible match and we sort out
668 any mistakes greed might make as we parse later fields.
669*/
670std::vector<PartialParse>
671TemporalFieldMatcher::monthNameExtend(const PartialParse &base, QStringView text,
672 TemporalFieldFlags flags) const
673{
674 std::vector<PartialParse> matches;
675 using Flag = TemporalFieldFlag;
676
677 const auto addIfMatch = [&matches, &base, text, flags](int month, const QString &name) {
678 // tryEachMonth() has ensured this:
679 Q_ASSERT(!base.results.month || base.results.month == month);
680 if (name.isEmpty()) // Locale doesn't know this month's name.
681 return;
682 // If matchedAt(), add to matches:
683 auto match = matchedAt(text, base.results.endIndex, name, flags);
684 if (match) {
685 matches.emplace_back(base, match).results.month = month;
686 if (flags.testFlag(Flag::SpacePad))
687 matches = spacePadExtend(std::move(matches), text);
688 }
689 };
690
691 constexpr auto Forms = FieldGroup::FormMask;
692 constexpr int noYear = QCalendar::Unspecified;
693 const bool verb = matchesFlagWithin(flags, Flag::Verbal, Forms);
694 const bool lone = matchesFlagWithin(flags, Flag::Standalone, Forms);
695 const int year = base.results.year ? *base.results.year : noYear;
696 // We could try to take account of baseYear, when yearWithinCentury is
697 // known, but that's susceptible to tweaks and perturbation from other
698 // fields, so stick with noYear and the usual naming of months if we don't
699 // know year. We can consider adding a QCalendar::parseMonthName() that can
700 // consult the internal lists of localized month names, both for efficiency
701 // and to ensure we try all names, including those that appear only in some
702 // years. If we do that, its return should package month number, whether the
703 // month appears in all years and whether it was standalone or plain, along
704 // with the start and end indices of the match within the text.
705 const auto tryEachNameType = [&](QLocale::FormatType form, int month) {
706 if (lone)
707 addIfMatch(month, calendar.standaloneMonthName(locale, month, year, form));
708 if (verb)
709 addIfMatch(month, calendar.monthName(locale, month, year, form));
710 };
711 // This could in principle, for non-system locales, be done more efficiently
712 // by walking the internal ';'-joined list of month names QCalendarBackend
713 // can give us. The entanglement between QCalendarBackend and QLocale
714 // internals is, however, already quite untidy enough, so leave that for
715 // if/when we discover it's a significant bottle-neck and/or we've unpicked
716 // the existing entanglement a bit first.
717
718 const auto tryEachMonth = [month = base.results.month,
719 bound = calendar.maximumMonthsInYear(),
720 &tryEachNameType](QLocale::FormatType form) {
721 if (month > 0) {
722 tryEachNameType(form, month);
723 } else {
724 for (int i = bound; i > 0; --i)
725 tryEachNameType(form, i);
726 }
727 };
728 forEachLocaleFormat(flags, tryEachMonth);
729
730 return matches;
731}
732
733std::vector<PartialParse>
734TemporalFieldMatcher::dayNameExtend(const PartialParse &base, QStringView text,
735 TemporalFieldFlags flags) const
736{
737 std::vector<PartialParse> matches;
738 using Flag = TemporalFieldFlag;
739
740 const auto addIfMatch = [&matches, &base, text, flags](int dow, const QString &name) {
741 // tryEachDayOfWeek() has ensured this:
742 Q_ASSERT(!base.results.dayOfWeek || base.results.dayOfWeek == dow);
743 if (name.isEmpty()) // Locale doesn't know this day of the week's name.
744 return;
745 // If matchedAt(), add to matches:
746 auto match = matchedAt(text, base.results.endIndex, name, flags);
747 if (match) {
748 matches.emplace_back(base, match).results.dayOfWeek = dow;
749 if (flags.testFlag(Flag::SpacePad))
750 matches = spacePadExtend(std::move(matches), text);
751 }
752 };
753
754 constexpr auto Forms = FieldGroup::FormMask;
755 const bool verb = matchesFlagWithin(flags, Flag::Verbal, Forms);
756 const bool lone = matchesFlagWithin(flags, Flag::Standalone, Forms);
757 const auto tryEachNameType = [&](QLocale::FormatType form, int dow) {
758 if (lone)
759 addIfMatch(dow, calendar.standaloneWeekDayName(locale, dow, form));
760 if (verb)
761 addIfMatch(dow, calendar.weekDayName(locale, dow, form));
762 };
763 // As for month names (see above), some collaboration with QCalendarBackend
764 // might make this more efficient for non-system locales, at the expense of
765 // adding to the existing tangle of complexity.
766
767 const auto tryEachDayOfWeek = [dow = base.results.dayOfWeek,
768 &tryEachNameType](QLocale::FormatType form) {
769 if (dow > 0) {
770 tryEachNameType(form, dow);
771 } else {
772 // Iterate possible day numbers. Issue: some calendars might have
773 // intercalary days with numbers > 7. When that happens, we may
774 // need to let this run past 7 until it's seen some empty answers.
775 for (int i = 1; i <= 7; ++i)
776 tryEachNameType(form, i);
777 }
778 };
779 forEachLocaleFormat(flags, tryEachDayOfWeek);
780
781 std::sort(matches.begin(), matches.end(), longerEarlier);
782 return matches;
783}
784
785std::pair<qsizetype, int>
786TemporalFieldMatcher::dayPeriodPrefix(const PartialParse &base, QStringView text,
787 TemporalFieldFlags flags) const
788{
789 std::pair<qsizetype, int> result = {0, -1};
790 for (int i = 0; i < 2; ++i) {
791 if (base.periodInDay >= 0 && base.periodInDay != i)
792 continue;
793 if (const QString token = i ? locale.pmText() : locale.amText(); !token.isEmpty()) {
794 if (auto match = matchedAt(text, base.results.endIndex, token, flags);
795 match.endIndex > result.first) {
796 result = { match.endIndex, i };
797 }
798 }
799 }
800 return result;
801}
802
803/*!
804 \internal
805 Find all matches to \a field, within \a text, that extend \a base.
806
807 Each match must begin at offset \c{base.results.endIndex} within \a text.
808 For each match, update a copy of \a base with the match's result, to include
809 in the returned list.
810
811 May use \c calendar to determine the range of values allowed for field.
812 Does not attempt to determine consistency between fields; see resolve() and
813 isSelfConsistent() for that. Updates the copy's member holding the value
814 described by \a field to reflect the match.
815
816 Ignores base.result.startIndex and base.result.bounds and updates each
817 copy's .endIndex to reflect the end of the match. (This leaves the caller to
818 decide whether to transfer that to .bounds.)
819
820 For fields that allow space padding, this consumes leading space as
821 necessary to make a match and includes a match for each end position at
822 which it could end; before any dangling space and after each space that
823 follows. Later calls to \c continuations() shall filter out any earlier
824 matches that precludes later fields matching just after its end. Successive
825 space-padded fields surrounded by large amounts of space are apt to lead to
826 many matches, as are final space-padded fields followed by large amounts of
827 space. (TODO: we can almost certainly mitigate this with a trivial
828 heuristic, once everything is working.)
829
830 For those matches with various flaws, relative to the field specification
831 (such as using zero padding when not obliged to), the copy's .wanton records
832 that flaw.
833
834 Sort order of the returned list should put entries likely to represent more
835 suitable matches (ignoring .wanton complications) earlier. For most fields,
836 that means longer matches come first. (For full year field matches with > 4
837 digits, though, that reverses.)
838*/
840TemporalFieldMatcher::continuations(const PartialParse &base, QStringView text,
841 const TemporalField &field) const
842{
843 std::vector<PartialParse> matches;
844 const qsizetype textPos = base.results.endIndex;
845 switch (field.category) {
846 using Cat = TemporalFieldCategory;
847 using Flag = TemporalFieldFlag;
848 case Cat::EndCategories:
849 Q_UNREACHABLE();
850 case Cat::Literal:
851 if (auto match = matchedAt(text, textPos, field.literal, field.options)) {
852 matches.emplace_back(base, match);
853 if (field.options.testFlag(Flag::SpacePad))
854 matches = spacePadExtend(std::move(matches), text);
855 }
856 break;
857 case Cat::TimeZone: {
858 std::optional<qint64> atEpochMillis = std::nullopt;
859 QDate date = base.results.date(calendar);
860
861 if (date.isValid()) {
862 QDateTime when(date, base.results.time(QTime(12, 0)), QTimeZone::UTC);
863 if (when.isValid())
864 atEpochMillis = when.toMSecsSinceEpoch();
865 }
866
867 if (const auto zones = QtParseTimeZone::prefix(text, locale, textPos, field.options,
868 atEpochMillis);
869 !zones.isEmpty()) {
870 for (const auto &match : zones) {
871 matches.emplace_back(base, match);
872 if (field.options.testFlag(Flag::SpacePad))
873 matches = spacePadExtend(std::move(matches), text);
874 }
875 }
876 break;
877 }
878
879 // case Cat::MillisecondInDay: break;
880 case Cat::SecondFraction:
881 // QTime, QDateTime only support millisecond precision, so use 3 as roundAfter.
882 // That's also maxDigits, unless RoundFraction => unlimited.
883 matches = numericExtend(base, text, field.options,
884 {millisTarget, base.results.millis >= 0, 999, true, field.width,
885 field.options.testFlag(Flag::RoundFraction) ? 0 : 3, 3});
886 break;
887 case Cat::Second:
888 matches = numericExtend(base, text, field.options,
889 {secondTarget, base.results.second >= 0, 59, true, field.width, 2});
890 break;
891 // case Cat::MinuteFraction: break;
892 case Cat::Minute:
893 matches = numericExtend(base, text, field.options,
894 {minuteTarget, base.results.minute >= 0, 59, true, field.width, 2});
895 break;
896 // case Cat::HourFraction: break;
897 case Cat::HourMod12:
898 matches = numericExtend(base, text, field.options,
899 {hourMod12Target, base.hourMod12 > 0, 12, false, field.width, 2});
900 break;
901 case Cat::Hour:
902 matches = numericExtend(base, text, field.options,
903 {hourTarget, base.results.hour >= 0, 23, true, field.width, 2});
904 break;
905 case Cat::PeriodInDay: // am/pm; LDML also has noon, midnight, "at night" and others.
906 if (const auto match = dayPeriodPrefix(base, text, field.options); match.second >= 0) {
907 // Ensured by dayPeriodPrefix:
908 Q_ASSERT(base.periodInDay < 0 || base.periodInDay == match.second);
909 PartialParse &grow = matches.emplace_back(base);
910 grow.results.endIndex = match.first;
911 grow.periodInDay = match.second;
912 if (field.options.testFlag(Flag::SpacePad))
913 matches = spacePadExtend(std::move(matches), text);
914 }
915 break;
916
917 case Cat::DayOfWeek:
918 matches = dayNameExtend(base, text, field.options);
919 break;
920 case Cat::DayOfMonth: {
921 const int maxDays = calendar.maximumDaysInMonth();
922 matches = numericExtend(base, text, field.options,
923 {dayOfMonthTarget, base.results.dayOfMonth > 0, maxDays, false,
924 field.width, maxDays < 10 ? 1 : maxDays < 100 ? 2 : 3});
925 }
926 break;
927 // case Cat::DayOfYear: break;
928 // case Cat::JulianDay: break;
929 // case Cat::WeekOfMonth: break;
930 // case Cat::WeekOfYear: break;
931 case Cat::Month:
932 // Verbal and Standalone, in so far as supported:
933 matches = monthNameExtend(base, text, field.options);
934 if (matchesFlagWithin(field.options, Flag::Numeric, FieldGroup::FormMask)) {
935 auto extend = numericExtend(base, text, field.options,
936 {monthTarget, base.results.month > 0,
937 calendar.maximumMonthsInYear(), false, field.width, 2});
938 if (matches.empty())
939 matches = std::move(extend);
940 else
941 matches.insert(matches.end(), extend.begin(), extend.end());
942 }
943 std::sort(matches.begin(), matches.end(), longerEarlier);
944 break;
945 // case Cat::Quarter: break;
946 case Cat::YearWithinCentury:
947 matches = numericExtend(base, text, field.options,
948 {yearWithinCenturyTarget, base.yearWithinCentury >= 0,
949 99, true, field.width, 2});
950 break;
951 case Cat::Year:
952 matches = numericExtend(base, text, field.options,
953 {yearTarget, bool(base.results.year), 0, calendar.hasYearZero(),
954 field.width, -4, -1, true, calendar.isProleptic()});
955 break;
956 // case Cat::RelatedGregorianYear: break;
957 // case Cat::Century: break;
958 // case Cat::Era: break;
959 }
960 return matches;
961}
962
963} // nameless namespace
964
967{
968 if (defaults.isValid()) {
971
973 // Defaults conflict with parsed day of the week.
974 if (!dayOfMonth) {
975 // (Assumes no intercalary days.)
976 // Number of days to the nearest with the right day of the week:
977 const int offset = (dayOfWeek + 10 - draft.dayOfWeek(cal)) % 7 - 3;
978 Q_ASSERT(offset != 0); // Otherwise, day of week matched, already.
979 Q_ASSERT(-4 < offset && offset < 4);
980 // Prefer closer unless nearby has more in common with what we asked for:
982 QDate nearby = draft.addDays(offset < 0 ? offset + 7 : offset - 7);
983 if (nearby.isValid()
984 && (!closer.isValid()
987 || (closer.month(cal) != draft.month(cal)
988 && nearby.month(cal) == draft.month(cal)))) {
989 // (We could also give year(cal) the same treatment, but
990 // different year, for dates within ten days of one another,
991 // plies different month, so check would be redundant.)
992 std::swap(nearby, draft);
993 } else if (closer.isValid() && closer.dayOfWeek(cal) == dayOfWeek) {
994 std::swap(closer, draft);
995 }
996
997 } else if (!month) {
999 auto use = [&draft, cal, dow=dayOfWeek](int yr, int mon, int day) {
1000 QDate maybe(yr, mon, day, cal);
1001 if (!maybe.isValid() || maybe.dayOfWeek(cal) != dow)
1002 return false;
1003 std::swap(maybe, draft);
1004 return true;
1005 };
1006 // Find nearest month with the right dayOfMonth and dayOfWeek.
1007 // If year was specified we're limited to it; otherwise,
1008 // draft.year() is derived from defaults so the search can
1009 // spread to nearby years.
1010 int loYear = draft.year(cal), hiYear = loYear;
1011 int loMon = draft.month(cal), hiMon = loMon;
1012 bool maybeLo = true, maybeHi = true;
1013 while (maybeLo || maybeHi) {
1014 if (maybeHi) {
1015 if (hiMon < cal.monthsInYear(hiYear)) {
1016 ++hiMon;
1017 } else if (year) {
1018 Q_ASSERT(hiYear == *year);
1019 maybeHi = false;
1020 } else if (hiYear + 1 || cal.hasYearZero()) {
1021 ++hiYear;
1022 hiMon = 1;
1023 } else if (cal.isProleptic()) {
1024 hiYear = +1;
1025 hiMon = 1;
1026 } else {
1027 maybeHi = false;
1028 }
1029 }
1030 if (maybeHi && use(hiYear, hiMon, dayOfMonth))
1031 break;
1032
1033 if (maybeLo) {
1034 if (loMon > 1) {
1035 --loMon;
1036 } else if (year) {
1037 Q_ASSERT(loYear == *year);
1038 maybeLo = false;
1039 } else if (loYear - 1 || cal.hasYearZero()) {
1040 --loYear;
1042 } else if (cal.isProleptic()) {
1043 loYear = -1;
1045 } else {
1046 maybeLo = false;
1047 }
1048 }
1049 if (maybeLo && use(loYear, loMon, dayOfMonth))
1050 break;
1051
1052 // Avoid looping for ever: if we can't find a match within a
1053 // 30 year window we probably never shall. If we haven't
1054 // found a match by then, the likelihood that the input has
1055 // a typo in it is fairly high, in any case.
1056 if (hiYear - loYear > 30)
1057 break;
1058 }
1059 } else if (!year) {
1060 // As for resolve()'s handling of two-digit centuries:
1064 std::swap(maybe, draft);
1065 }
1066 if (draft.dayOfWeek(cal) != dayOfWeek)
1067 return {};
1068 }
1069 return draft;
1070 }
1071 if (year && month && dayOfMonth)
1072 return QDate(*year, month, dayOfMonth, cal);
1073 return {};
1074}
1075
1077{
1078 if (defaults.isValid()) {
1079 int hr = defaults.hour();
1080 // hour: -1 means we have no information, less means unknown am, > 24 means unknown pm.
1081 if (hour < -1) // UnknownAmHour
1082 hr = hr % 12;
1083 else if (hour > 24) // UnknownPmHour
1084 hr = hr % 12 + 12;
1085 else if (hour >= 0)
1086 hr = hour;
1087 // (Note: hour == 24 is currently unused but may be relevant for 24:00:00 in future.)
1088 return QTime(hr,
1089 minute < 0 ? defaults.minute() : minute,
1090 second < 0 ? defaults.second() : second,
1091 millis < 0 ? defaults.msec() : millis);
1092 }
1093
1094 if (hour < 0 || hour > 24)
1095 return {};
1096 if (minute < 0)
1097 return QTime(hour, 0);
1098 if (second < 0)
1099 return QTime(hour, minute);
1100 if (millis < 0)
1101 return QTime(hour, minute, second);
1102 return QTime(hour, minute, second, millis);
1103}
1104
1105ParsedTemporal prefix(QStringView text, QSpan<const QtTemporalPattern::TemporalField> fields,
1106 const QLocale &locale, QCalendar cal,
1107 std::optional<int> baseYear, qsizetype from)
1108{
1109 if (from < 0 || from >= text.size())
1110 return {};
1111
1112 const TemporalFieldMatcher matcher(locale, cal, baseYear);
1113 // Technically this is the correct (empty) result when fields.isEmpty():
1114 std::vector<PartialParse> maybe;
1115 maybe.emplace_back(from);
1116
1117 qsizetype toCome = fields.size();
1118 for (const QtTemporalPattern::TemporalField &field : fields) {
1119 --toCome;
1120 const std::vector<PartialParse> prior = std::exchange(maybe, {});
1121 for (const PartialParse &base : prior) {
1122 std::vector<PartialParse> more
1123 = matcher.continuations(base, text, field);
1124 for (PartialParse &candidate : more) {
1125 // Consistency won't have been changed by a literal field:
1126 if ((field.category == TemporalFieldCategory::Literal
1127 || matcher.isSelfConsistent(candidate, field.category))) {
1128 if (toCome) // Earlier fields' ends go in bounds:
1129 candidate.results.bounds.push_back(candidate.results.endIndex);
1130 else if (!matcher.resolve(candidate)) // Last field: makes sense of it all.
1131 continue;
1132 maybe.push_back(std::move(candidate));
1133 }
1134 }
1135 }
1136 if (maybe.empty()) // No point continuing
1137 return {};
1138 }
1139 // Now select our most favourable entry from maybe.
1140
1141 // Although we've, thus far, prefered sensible-length matches over longer
1142 // ones in individual numeric fields, so that later numeric fields can take
1143 // up the slack and win, we still want to be greedy over-all, so prefer
1144 // overall longer matches to shorter ones. None the less, between matches of
1145 // equal length, preserve our preference, up to now, for sane lengths of
1146 // each field within that, as long as later fields are taking up the slack.
1147 // That preference can be fine-tuned via .wanton, see PartialParse::Flaw.
1148 PartialParse best = maybe.front();
1149 for (const PartialParse &match : QSpan{maybe}.sliced(1)) {
1150 if (match.compare(best) < 0)
1151 best = match;
1152 }
1153 return best.results;
1154}
1155
1156} // QtParseTemporal
1157
1158QT_END_NAMESPACE
bool isSelfConsistent(const PartialParse &parsed, TemporalFieldCategory category) const
bool resolve(PartialParse &parsed) const
std::vector< PartialParse > continuations(const PartialParse &base, QStringView text, const TemporalField &field) const
TemporalFieldMatcher(const QLocale &loc, QCalendar cal, std::optional< int > centuryStart)
bool longerEarlier(const PartialParse &left, const PartialParse &right)
std::vector< PartialParse > spacePadExtend(std::vector< PartialParse > matched, QStringView text)
QtParseCommon::ParsedText matchedAt(QStringView text, qsizetype from, const QString &sought, TemporalFieldFlags flags)
void forEachLocaleFormat(TemporalFieldFlags flags, qxp::function_ref< void(QLocale::FormatType) const > action)
ParsedTemporal prefix(QStringView text, QSpan< const QtTemporalPattern::TemporalField > fields, const QLocale &locale, QCalendar cal, std::optional< int > baseYear, qsizetype from)
Qt::weak_ordering compare(const PartialParse &alt) const noexcept
PartialParse(const PartialParse &base, const QtParseCommon::ParsedText &more)