4#include "private/qtparsetemporal_p.h"
6#include "private/qcalendarmath_p.h"
7#include "private/qlocale_p.h"
8#include "private/qstringiterator_p.h"
9#include "private/qttemporalpattern_p.h"
12#include <QtCore/qxpfunctional.h>
20using namespace QtParseTemporal;
21using namespace QtTemporalPattern;
45 Q_DECLARE_FLAGS(Flaws,
Flaw)
49 PartialParse(qsizetype from) { results.startIndex = results.endIndex = from; }
54 Q_ASSERT(results.endIndex == more.startIndex);
55 results.endIndex = more.endIndex;
60 results.zone = more.zone;
61 results.timeType = more.timeType;
70 const auto order = [better = alt.wanton & ~wanton,
71 worse = wanton & ~alt.wanton](
Flaw test) {
72 Q_ASSERT(!(worse & better));
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;
95 if (
auto res = Qt::compareThreeWay(alt.results.size(), results.size()); res != 0)
106 return Qt::weak_ordering::equivalent;
111QLocaleData::DigitSequence
112parseDigitSequence(QStringView text, qsizetype from,
const QLocale &locale,
bool allowSign,
115 const auto *
const data = QLocalePrivate::get(locale)->m_data;
116 using DS = QLocaleData::DigitSequence;
119 flags.setFlag(DS::Option::AllowSign,
true);
120 return data->digitSequence(text, flags, from, maxDigits);
127 Q_ASSERT(!matched.empty());
133 const qsizetype position = matched.size() - 1;
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);
145 TemporalFieldFlags flags)
147 using F = TemporalFieldFlag;
148 const bool allowLeadingSpace = flags.testFlag(F::SpacePad);
149 Q_ASSERT(sought.size() > 0);
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) {
161 const auto matchFront = [cs](QStringView view, QStringView target) -> qsizetype {
162 if (target.isEmpty())
164 if (view.startsWith(target, cs)) {
165 qsizetype length = target.size();
169 while (view.first(length - 1).startsWith(target, cs))
173 while (!view.first(length).startsWith(target, cs))
175 Q_ASSERT(length > 0);
180 const auto spacingForward = [](QStringIterator &iter) {
185 }
while (iter.hasNext() && QChar::isSpace(iter.next()));
188 const auto matchingSpace = [](
char32_t need,
char32_t have) {
189 constexpr char32_t ASCIImax = 0x7f;
191 if (need == U' ' || need > ASCIImax)
192 return have == U' ' || have > ASCIImax;
197 constexpr qsizetype failed = 0;
198 qsizetype matched = 0;
199 if (flex || !strict) {
200 QStringIterator iter(target);
203 while (iter.hasNext()) {
204 qsizetype head = iter.index();
205 if (
const char32_t tgt = iter.next(); QChar::isSpace(tgt)) {
207 qsizetype same = head ? matchFront(view, target.first(head)) : 0;
210 QStringIterator viter(view, same);
212 if (!viter.hasNext())
214 if (
const char32_t got = viter.next(); !QChar::isSpace(got))
217 same = spacingForward(viter);
218 else if (!matchingSpace(tgt, got))
221 same = viter.index();
223 view = view.sliced(same);
224 target = target.sliced(flex ? spacingForward(iter) : iter.index());
225 iter = QStringIterator(target);
227 Q_ASSERT(!flex || !iter.hasNext() || !QChar::isSpace(iter.peekNext()));
233 const qsizetype tail = matchFront(view, target);
236 return matched + tail;
240 qsizetype offset = 0;
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)) {
249 if (flags.testFlag(F::LowerCase)) {
250 if (qsizetype match = beginLength(view, sought.toLower()))
251 return {from, from + offset + match};
253 if (flags.testFlag(F::UpperCase)) {
254 if (qsizetype match = beginLength(view, sought.toUpper()))
255 return {from, from + offset + match};
258 }
else if (qsizetype match = beginLength(view, sought)) {
259 return {from, from + offset + match};
263 if (!allowLeadingSpace) {
269 QStringIterator iter(text.sliced(from), offset);
270 if (!iter.hasNext() || !QChar::isSpace(iter.next()))
273 Q_ASSERT(iter.index() > offset);
274 offset = iter.index();
275 }
while (text.size() >= offset + sought.size() / 2);
284 return left.results.endIndex > right.results.endIndex;
288 qxp::function_ref<
void(QLocale::FormatType)
const> action)
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);
302 const QLocale locale;
303 const QCalendar calendar;
304 const std::optional<
int> baseYear;
311 bool alreadySet =
false;
314 bool allowZero =
false;
317 qsizetype maxDigits = 0;
319 qsizetype roundAfter = -1;
322 bool allowSign =
false;
323 bool allowNegative =
false;
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; }
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; }
341 if (!grow.results.year)
342 grow.results.year = 0;
343 return *grow.results.year;
347 std::vector<PartialParse>
348 numericExtend(
const PartialParse &base, QStringView text,
349 TemporalFieldFlags flags, FieldConfig &&config)
const;
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;
364 const TemporalField &field)
const;
370 TemporalFieldCategory category)
const
375 using Cat = TemporalFieldCategory;
376 if (category == Cat::Literal)
379 const bool newYear = category == Cat::Year || category == Cat::YearWithinCentury;
385 const bool newDate = (newYear || category == Cat::Month || category == Cat::DayOfMonth
386 || category == Cat::DayOfWeek);
387 if (newDate && parse.results.month && parse.results.dayOfMonth) {
389 if (parse.results.year) {
390 if (!calendar.isDateValid(*parse.results.year, parse.results.month,
391 parse.results.dayOfMonth)) {
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)
400 }
else if (calendar.daysInMonth(parse.results.month) < parse.results.dayOfMonth) {
405 if ((category == Cat::PeriodInDay && parse.results.hour >= 0)
406 || (category == Cat::Hour && parse.periodInDay >= 0)) {
408 if (parse
.periodInDay ? parse.results.hour < 12 : parse.results.hour >= 12)
412 if ((category == Cat::Hour && parse.hourMod12 > 0)
413 || (category == Cat::HourMod12 && parse.results.hour >= 0)) {
414 if ((parse.results.hour - parse
.hourMod12) % 12)
427 if (parse.results.year) {
430 }
else if (baseYear) {
431 const auto baseSplit =QRoundingDown::qDivMod<100>(*baseYear);
436 if (parse.results.month) {
439 const auto enough = [dom = parse.results.dayOfMonth](
int dim) {
440 return dim > 0 && (!dom || dom <= dim);
442 if (!enough(calendar.daysInMonth(parse.results.month, year))) {
445 for (
int off = 1; off < 10; ++off) {
446 int offset = off * 100;
447 if (enough(calendar.daysInMonth(parse.results.month, year + offset))) {
452 if (enough(calendar.daysInMonth(parse.results.month, year - offset))) {
463 if (parse.results.dayOfMonth) {
464 if (parse.results.dayOfWeek) {
465 QCalendar::YearMonthDay ymd
466 = { year, parse.results.month, parse.results.dayOfMonth };
468 = calendar.matchCenturyToWeekday(ymd, parse.results.dayOfWeek);
469 if (!resolved.isValid())
471 year = resolved.year(calendar);
473 const QDate resolved(year, parse.results.month, parse.results.dayOfMonth);
474 if (!resolved.isValid())
480 parse.results.year = year;
484 if (parse.results.hour < 0 && parse
.hourMod12 > 0) {
488 parse.results.hour += 12;
491 if (parse.results.year && parse.results.month && parse.results.dayOfMonth
492 && parse.results.zone.isValid() && parse.results.hour >= 0) {
494 const QDate date(*parse.results.year, parse.results.month, parse.results.dayOfMonth,
496 Q_ASSERT(date.isValid());
497 const QTime time = parse.results.time(QTime());
498 Q_ASSERT(time.isValid());
501 if (!Q_LIKELY(QDateTime(date, time, parse.results.zone,
502 QDateTime::TransitionResolution::Reject).isValid())) {
505 QDateTime dt(date, time, parse.results.zone, parse.results.resolveType());
508 dt = QDateTime(date, time, parse.results.zone);
512 if (dt.date() != date || dt.time() != time
513 || dt.timeRepresentation() != parse.results.zone) {
527 if (parse.results.hour < 0) {
537std::vector<PartialParse>
539 TemporalFieldFlags flags, FieldConfig &&config)
const
541 std::vector<PartialParse> matches;
543 using Flag = TemporalFieldFlag;
544 qsizetype leadingSpace = 0;
545 const bool spacePad = flags.testFlag(Flag::SpacePad);
547 QStringIterator iter(text, base.results.endIndex);
548 while (iter.hasNext() && QChar::isSpace(iter.next()))
556 constexpr qsizetype IntMaxDigits = std::numeric_limits<
int>::digits10 + 1;
560 const auto parsed = parseDigitSequence(text, base.results.endIndex + leadingSpace,
561 locale, config.allowSign, IntMaxDigits);
562 if (parsed.sign ==
'-' && !config.allowNegative)
564 const bool zeroPad = flags.testFlag(Flag::ZeroPad);
566 const int width = zeroPad || spacePad ? qMax(1, config.width - leadingSpace) : 1;
569 QByteArrayView digits{parsed.digits};
571 if (config.maxDigits > 0) {
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) {
578 const int maxWidth = qMax(-config.maxDigits, config.width > 0 ? config.width : 1);
579 if (digits.size() > maxWidth)
580 digits = digits.first(maxWidth);
584 const qsizetype appendThreshold = config.maxDigits <= 0
585 ? qMax(-config.maxDigits, qMax(config.width, config.roundAfter)) - 1
588 for (; digits.size() >= width; digits.chop(1)) {
590 unsigned whole = digits.toUInt(&ok);
593 if (config.maxValue > 0 && config.roundAfter < 0 && whole >
unsigned(config.maxValue))
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))
603 return negate ? -
int(whole) :
int(whole);
607 int value = *optvalue;
609 if (config.roundAfter >= 0) {
611 if (digits.size() < config.roundAfter) {
613 for (
int i =
int(digits.size()); i < config.roundAfter; ++i)
615 }
else if (digits.size() > config.roundAfter) {
617 for (
int i =
int(digits.size()); i > config.roundAfter; --i)
623 value = v > config.maxValue ? config.maxValue : qRound(v);
632 int &target = config.target(grow);
633 if (!config.alreadySet)
635 else if (target != value)
637 grow.results.endIndex = parsed.digitBounds[digits.size()];
639 if (!zeroPad && digits.size() > qMax(1, config.width)
640 && (config.roundAfter < 0 ? digits.startsWith(
'0') : digits.endsWith(
'0'))) {
643 if (digits.size() + leadingSpace < config.width)
649 if (digits.size() > appendThreshold)
650 matches.insert(matches.begin(),
std::move(grow));
652 matches.push_back(
std::move(grow));
658
659
660
661
662
663
664
665
666
667
668
669
670std::vector<PartialParse>
672 TemporalFieldFlags flags)
const
674 std::vector<PartialParse> matches;
675 using Flag = TemporalFieldFlag;
677 const auto addIfMatch = [&matches, &base, text, flags](
int month,
const QString &name) {
679 Q_ASSERT(!base.results.month || base.results.month == month);
683 auto match = matchedAt(text, base.results.endIndex, name, flags);
685 matches.emplace_back(base, match).results.month = month;
686 if (flags.testFlag(Flag::SpacePad))
687 matches = spacePadExtend(std::move(matches), text);
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;
705 const auto tryEachNameType = [&](QLocale::FormatType form,
int month) {
707 addIfMatch(month, calendar.standaloneMonthName(locale, month, year, form));
709 addIfMatch(month, calendar.monthName(locale, month, year, form));
718 const auto tryEachMonth = [month = base.results.month,
719 bound = calendar.maximumMonthsInYear(),
720 &tryEachNameType](QLocale::FormatType form) {
722 tryEachNameType(form, month);
724 for (
int i = bound; i > 0; --i)
725 tryEachNameType(form, i);
728 forEachLocaleFormat(flags, tryEachMonth);
733std::vector<PartialParse>
735 TemporalFieldFlags flags)
const
737 std::vector<PartialParse> matches;
738 using Flag = TemporalFieldFlag;
740 const auto addIfMatch = [&matches, &base, text, flags](
int dow,
const QString &name) {
742 Q_ASSERT(!base.results.dayOfWeek || base.results.dayOfWeek == dow);
746 auto match = matchedAt(text, base.results.endIndex, name, flags);
748 matches.emplace_back(base, match).results.dayOfWeek = dow;
749 if (flags.testFlag(Flag::SpacePad))
750 matches = spacePadExtend(std::move(matches), text);
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) {
759 addIfMatch(dow, calendar.standaloneWeekDayName(locale, dow, form));
761 addIfMatch(dow, calendar.weekDayName(locale, dow, form));
767 const auto tryEachDayOfWeek = [dow = base.results.dayOfWeek,
768 &tryEachNameType](QLocale::FormatType form) {
770 tryEachNameType(form, dow);
775 for (
int i = 1; i <= 7; ++i)
776 tryEachNameType(form, i);
779 forEachLocaleFormat(flags, tryEachDayOfWeek);
785std::pair<qsizetype,
int>
787 TemporalFieldFlags flags)
const
789 std::pair<qsizetype,
int> result = {0, -1};
790 for (
int i = 0; i < 2; ++i) {
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 };
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
841 const TemporalField &field)
const
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:
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);
857 case Cat::TimeZone: {
858 std::optional<qint64> atEpochMillis =
std::nullopt;
859 QDate date = base.results.date(calendar);
861 if (date.isValid()) {
862 QDateTime when(date, base.results.time(QTime(12, 0)), QTimeZone::UTC);
864 atEpochMillis = when.toMSecsSinceEpoch();
867 if (
const auto zones = QtParseTimeZone::prefix(text, locale, textPos, field.options,
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);
880 case Cat::SecondFraction:
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});
888 matches = numericExtend(base, text, field.options,
889 {secondTarget, base.results.second >= 0, 59,
true, field.width, 2});
893 matches = numericExtend(base, text, field.options,
894 {minuteTarget, base.results.minute >= 0, 59,
true, field.width, 2});
898 matches = numericExtend(base, text, field.options,
899 {hourMod12Target, base.hourMod12 > 0, 12,
false, field.width, 2});
902 matches = numericExtend(base, text, field.options,
903 {hourTarget, base.results.hour >= 0, 23,
true, field.width, 2});
905 case Cat::PeriodInDay:
906 if (
const auto match = dayPeriodPrefix(base, text, field.options); match.second >= 0) {
910 grow.results.endIndex = match.first;
912 if (field.options.testFlag(Flag::SpacePad))
913 matches = spacePadExtend(std::move(matches), text);
918 matches = dayNameExtend(base, text, field.options);
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});
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});
939 matches =
std::move(extend);
941 matches.insert(matches.end(), extend.begin(), extend.end());
946 case Cat::YearWithinCentury:
947 matches = numericExtend(base, text, field.options,
948 {yearWithinCenturyTarget, base.yearWithinCentury >= 0,
949 99,
true, field.width, 2});
952 matches = numericExtend(base, text, field.options,
953 {yearTarget,
bool(base.results.year), 0, calendar.hasYearZero(),
954 field.width, -4, -1,
true, calendar.isProleptic()});
1106 const QLocale &locale, QCalendar cal,
1107 std::optional<
int> baseYear, qsizetype from)
1109 if (from < 0 || from >= text.size())
1114 std::vector<PartialParse> maybe;
1115 maybe.emplace_back(from);
1117 qsizetype toCome = fields.size();
1118 for (
const QtTemporalPattern::TemporalField &field : fields) {
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) {
1126 if ((field.category == TemporalFieldCategory::Literal
1127 || matcher.isSelfConsistent(candidate, field.category))) {
1129 candidate.results.bounds.push_back(candidate.results.endIndex);
1130 else if (!matcher.resolve(candidate))
1132 maybe.push_back(std::move(candidate));
1149 for (
const PartialParse &match : QSpan{maybe}.sliced(1)) {
1150 if (match.compare(best) < 0)
1153 return best.results;
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)
static constexpr int UnknownAmHour
Qt::weak_ordering compare(const PartialParse &alt) const noexcept
PartialParse(qsizetype from)
static constexpr int UnknownPmHour
PartialParse(const PartialParse &base, const QtParseCommon::ParsedText &more)