v8
V8 is Google’s open source high-performance JavaScript and WebAssembly engine, written in C++.
Loading...
Searching...
No Matches
dateparser-inl.h
Go to the documentation of this file.
1// Copyright 2011 the V8 project authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef V8_DATE_DATEPARSER_INL_H_
6#define V8_DATE_DATEPARSER_INL_H_
7
9// Include the non-inl header before the rest of the headers.
10
13
14namespace v8 {
15namespace internal {
16
17template <typename Char>
18bool DateParser::Parse(Isolate* isolate, base::Vector<Char> str, double* out) {
19 InputReader<Char> in(str);
20 DateStringTokenizer<Char> scanner(&in);
23 DayComposer day;
24
25 // Specification:
26 // Accept ES5 ISO 8601 date-time-strings or legacy dates compatible
27 // with Safari.
28 // ES5 ISO 8601 dates:
29 // [('-'|'+')yy]yyyy[-MM[-DD]][THH:mm[:ss[.sss]][Z|(+|-)hh:mm]]
30 // where yyyy is in the range 0000..9999 and
31 // +/-yyyyyy is in the range -999999..+999999 -
32 // but -000000 is invalid (year zero must be positive),
33 // MM is in the range 01..12,
34 // DD is in the range 01..31,
35 // MM and DD defaults to 01 if missing,,
36 // HH is generally in the range 00..23, but can be 24 if mm, ss
37 // and sss are zero (or missing), representing midnight at the
38 // end of a day,
39 // mm and ss are in the range 00..59,
40 // sss is in the range 000..999,
41 // hh is in the range 00..23,
42 // mm, ss, and sss default to 00 if missing, and
43 // timezone defaults to Z if missing
44 // (following Safari, ISO actually demands local time).
45 // Extensions:
46 // We also allow sss to have more or less than three digits (but at
47 // least one).
48 // We allow hh:mm to be specified as hhmm.
49 // Legacy dates:
50 // Any unrecognized word before the first number is ignored.
51 // Parenthesized text is ignored.
52 // An unsigned number followed by ':' is a time value, and is
53 // added to the TimeComposer. A number followed by '::' adds a second
54 // zero as well. A number followed by '.' is also a time and must be
55 // followed by milliseconds.
56 // Any other number is a date component and is added to DayComposer.
57 // A month name (or really: any word having the same first three letters
58 // as a month name) is recorded as a named month in the Day composer.
59 // A word recognizable as a time-zone is recorded as such, as is
60 // '(+|-)(hhmm|hh:)'.
61 // Legacy dates don't allow extra signs ('+' or '-') or umatched ')'
62 // after a number has been read (before the first number, any garbage
63 // is allowed).
64 // Intersection of the two:
65 // A string that matches both formats (e.g. 1970-01-01) will be
66 // parsed as an ES5 date-time string - which means it will default
67 // to UTC time-zone. That's unavoidable if following the ES5
68 // specification.
69 // After a valid "T" has been read while scanning an ES5 datetime string,
70 // the input can no longer be a valid legacy date, since the "T" is a
71 // garbage string after a number has been read.
72
73 // First try getting as far as possible with as ES5 Date Time String.
74 DateToken next_unhandled_token = ParseES5DateTime(&scanner, &day, &time, &tz);
75 if (next_unhandled_token.IsInvalid()) return false;
76 bool has_read_number = !day.IsEmpty();
77 // If there's anything left, continue with the legacy parser.
78 bool legacy_parser = false;
79 for (DateToken token = next_unhandled_token; !token.IsEndOfInput();
80 token = scanner.Next()) {
81 if (token.IsNumber()) {
82 legacy_parser = true;
83 has_read_number = true;
84 int n = token.number();
85 if (scanner.SkipSymbol(':')) {
86 if (scanner.SkipSymbol(':')) {
87 // n + "::"
88 if (!time.IsEmpty()) return false;
89 time.Add(n);
90 time.Add(0);
91 } else {
92 // n + ":"
93 if (!time.Add(n)) return false;
94 if (scanner.Peek().IsSymbol('.')) scanner.Next();
95 }
96 } else if (scanner.SkipSymbol('.') && time.IsExpecting(n)) {
97 time.Add(n);
98 if (!scanner.Peek().IsNumber()) return false;
99 int ms = ReadMilliseconds(scanner.Next());
100 if (ms < 0) return false;
101 time.AddFinal(ms);
102 } else if (tz.IsExpecting(n)) {
103 tz.SetAbsoluteMinute(n);
104 } else if (time.IsExpecting(n)) {
105 time.AddFinal(n);
106 // Require end, white space, "Z", "+" or "-" immediately after
107 // finalizing time.
108 DateToken peek = scanner.Peek();
109 if (!peek.IsEndOfInput() && !peek.IsWhiteSpace() &&
110 !peek.IsKeywordZ() && !peek.IsAsciiSign())
111 return false;
112 } else {
113 if (!day.Add(n)) return false;
114 scanner.SkipSymbol('-');
115 }
116 } else if (token.IsKeyword()) {
117 legacy_parser = true;
118 // Parse a "word" (sequence of chars. >= 'A').
119 KeywordType type = token.keyword_type();
120 int value = token.keyword_value();
121 if (type == AM_PM && !time.IsEmpty()) {
122 time.SetHourOffset(value);
123 } else if (type == MONTH_NAME) {
124 day.SetNamedMonth(value);
125 scanner.SkipSymbol('-');
126 } else if (type == TIME_ZONE_NAME && has_read_number) {
127 tz.Set(value);
128 } else {
129 // Garbage words are illegal if a number has been read.
130 if (has_read_number) return false;
131 // The first number has to be separated from garbage words by
132 // whitespace or other separators.
133 if (scanner.Peek().IsNumber()) return false;
134 }
135 } else if (token.IsAsciiSign() && (tz.IsUTC() || !time.IsEmpty())) {
136 legacy_parser = true;
137 // Parse UTC offset (only after UTC or time).
138 tz.SetSign(token.ascii_sign());
139 // The following number may be empty.
140 int n = 0;
141 int length = 0;
142 if (scanner.Peek().IsNumber()) {
143 DateToken next_token = scanner.Next();
144 length = next_token.length();
145 n = next_token.number();
146 }
147 has_read_number = true;
148
149 if (scanner.Peek().IsSymbol(':')) {
150 tz.SetAbsoluteHour(n);
151 // TODO(littledan): Use minutes as part of timezone?
153 } else if (length == 2 || length == 1) {
154 // Handle time zones like GMT-8
155 tz.SetAbsoluteHour(n);
156 tz.SetAbsoluteMinute(0);
157 } else if (length == 4 || length == 3) {
158 // Looks like the hhmm format
159 tz.SetAbsoluteHour(n / 100);
160 tz.SetAbsoluteMinute(n % 100);
161 } else {
162 // No need to accept time zones like GMT-12345
163 return false;
164 }
165 } else if ((token.IsAsciiSign() || token.IsSymbol(')')) &&
166 has_read_number) {
167 // Extra sign or ')' is illegal if a number has been read.
168 return false;
169 } else {
170 // Ignore other characters and whitespace.
171 }
172 }
173
174 bool success = day.Write(out) && time.Write(out) && tz.Write(out);
175
176 if (legacy_parser && success) {
177 isolate->CountUsage(v8::Isolate::kLegacyDateParser);
178 }
179
180 return success;
181}
182
183template <typename CharType>
185 int pre_pos = in_->position();
186 if (in_->IsEnd()) return DateToken::EndOfInput();
187 if (in_->IsAsciiDigit()) {
188 int n = in_->ReadUnsignedNumeral();
189 int length = in_->position() - pre_pos;
190 return DateToken::Number(n, length);
191 }
192 if (in_->Skip(':')) return DateToken::Symbol(':');
193 if (in_->Skip('-')) return DateToken::Symbol('-');
194 if (in_->Skip('+')) return DateToken::Symbol('+');
195 if (in_->Skip('.')) return DateToken::Symbol('.');
196 if (in_->Skip(')')) return DateToken::Symbol(')');
197 if (in_->IsAsciiAlphaOrAbove() && !in_->IsWhiteSpaceChar()) {
198 DCHECK_EQ(KeywordTable::kPrefixLength, 3);
199 uint32_t buffer[3] = {0, 0, 0};
200 int length = in_->ReadWord(buffer, 3);
201 int index = KeywordTable::Lookup(buffer, length);
202 return DateToken::Keyword(KeywordTable::GetType(index),
203 KeywordTable::GetValue(index), length);
204 }
205 if (in_->SkipWhiteSpace()) {
206 return DateToken::WhiteSpace(in_->position() - pre_pos);
207 }
208 if (in_->SkipParentheses()) {
209 return DateToken::Unknown();
210 }
211 in_->Next();
212 return DateToken::Unknown();
213}
214
215template <typename Char>
218 Next();
219 return true;
220 }
221 return false;
222}
223
224template <typename Char>
226 if (ch_ != '(') return false;
227 int balance = 0;
228 do {
229 if (ch_ == ')')
230 --balance;
231 else if (ch_ == '(')
232 ++balance;
233 Next();
234 } while (balance > 0 && ch_);
235 return true;
236}
237
238template <typename Char>
241 TimeZoneComposer* tz) {
242 DCHECK(day->IsEmpty());
243 DCHECK(time->IsEmpty());
244 DCHECK(tz->IsEmpty());
245
246 // Parse mandatory date string: [('-'|'+')yy]yyyy[':'MM[':'DD]]
247 if (scanner->Peek().IsAsciiSign()) {
248 // Keep the sign token, so we can pass it back to the legacy
249 // parser if we don't use it.
250 DateToken sign_token = scanner->Next();
251 if (!scanner->Peek().IsFixedLengthNumber(6)) return sign_token;
252 int sign = sign_token.ascii_sign();
253 int year = scanner->Next().number();
254 if (sign < 0 && year == 0) return sign_token;
255 day->Add(sign * year);
256 } else if (scanner->Peek().IsFixedLengthNumber(4)) {
257 day->Add(scanner->Next().number());
258 } else {
259 return scanner->Next();
260 }
261 if (scanner->SkipSymbol('-')) {
262 if (!scanner->Peek().IsFixedLengthNumber(2) ||
263 !DayComposer::IsMonth(scanner->Peek().number()))
264 return scanner->Next();
265 day->Add(scanner->Next().number());
266 if (scanner->SkipSymbol('-')) {
267 if (!scanner->Peek().IsFixedLengthNumber(2) ||
268 !DayComposer::IsDay(scanner->Peek().number()))
269 return scanner->Next();
270 day->Add(scanner->Next().number());
271 }
272 }
273 // Check for optional time string: 'T'HH':'mm[':'ss['.'sss]]Z
274 if (!scanner->Peek().IsKeywordType(TIME_SEPARATOR)) {
275 if (!scanner->Peek().IsEndOfInput()) return scanner->Next();
276 } else {
277 // ES5 Date Time String time part is present.
278 scanner->Next();
279 if (!scanner->Peek().IsFixedLengthNumber(2) ||
280 !Between(scanner->Peek().number(), 0, 24)) {
281 return DateToken::Invalid();
282 }
283 // Allow 24:00[:00[.000]], but no other time starting with 24.
284 bool hour_is_24 = (scanner->Peek().number() == 24);
285 time->Add(scanner->Next().number());
286 if (!scanner->SkipSymbol(':')) return DateToken::Invalid();
287 if (!scanner->Peek().IsFixedLengthNumber(2) ||
288 !TimeComposer::IsMinute(scanner->Peek().number()) ||
289 (hour_is_24 && scanner->Peek().number() > 0)) {
290 return DateToken::Invalid();
291 }
292 time->Add(scanner->Next().number());
293 if (scanner->SkipSymbol(':')) {
294 if (!scanner->Peek().IsFixedLengthNumber(2) ||
295 !TimeComposer::IsSecond(scanner->Peek().number()) ||
296 (hour_is_24 && scanner->Peek().number() > 0)) {
297 return DateToken::Invalid();
298 }
299 time->Add(scanner->Next().number());
300 if (scanner->SkipSymbol('.')) {
301 if (!scanner->Peek().IsNumber() ||
302 (hour_is_24 && scanner->Peek().number() > 0)) {
303 return DateToken::Invalid();
304 }
305 // Allow more or less than the mandated three digits.
306 time->Add(ReadMilliseconds(scanner->Next()));
307 }
308 }
309 // Check for optional timezone designation: 'Z' | ('+'|'-')hh':'mm
310 if (scanner->Peek().IsKeywordZ()) {
311 scanner->Next();
312 tz->Set(0);
313 } else if (scanner->Peek().IsSymbol('+') || scanner->Peek().IsSymbol('-')) {
314 tz->SetSign(scanner->Next().symbol() == '+' ? 1 : -1);
315 if (scanner->Peek().IsFixedLengthNumber(4)) {
316 // hhmm extension syntax.
317 int hourmin = scanner->Next().number();
318 int hour = hourmin / 100;
319 int min = hourmin % 100;
321 return DateToken::Invalid();
322 }
324 tz->SetAbsoluteMinute(min);
325 } else {
326 // hh:mm standard syntax.
327 if (!scanner->Peek().IsFixedLengthNumber(2) ||
328 !TimeComposer::IsHour(scanner->Peek().number())) {
329 return DateToken::Invalid();
330 }
331 tz->SetAbsoluteHour(scanner->Next().number());
332 if (!scanner->SkipSymbol(':')) return DateToken::Invalid();
333 if (!scanner->Peek().IsFixedLengthNumber(2) ||
334 !TimeComposer::IsMinute(scanner->Peek().number())) {
335 return DateToken::Invalid();
336 }
337 tz->SetAbsoluteMinute(scanner->Next().number());
338 }
339 }
340 if (!scanner->Peek().IsEndOfInput()) return DateToken::Invalid();
341 }
342 // Successfully parsed ES5 Date Time String.
343 // ES#sec-date-time-string-format Date Time String Format
344 // "When the time zone offset is absent, date-only forms are interpreted
345 // as a UTC time and date-time forms are interpreted as a local time."
346 if (tz->IsEmpty() && time->IsEmpty()) {
347 tz->Set(0);
348 }
349 day->set_iso_date();
350 return DateToken::EndOfInput();
351}
352
353} // namespace internal
354} // namespace v8
355
356#endif // V8_DATE_DATEPARSER_INL_H_
static bool Parse(Isolate *isolate, base::Vector< Char > str, double *output)
static DateParser::DateToken ParseES5DateTime(DateStringTokenizer< Char > *scanner, DayComposer *day, TimeComposer *time, TimeZoneComposer *tz)
static const int kNone
Definition dateparser.h:50
static bool Between(int x, int lo, int hi)
Definition dateparser.h:45
static int ReadMilliseconds(DateToken number)
double hour
TimeRecord time
bool IsWhiteSpaceOrLineTerminator(base::uc32 c)
#define DCHECK(condition)
Definition logging.h:482
#define DCHECK_EQ(v1, v2)
Definition logging.h:485
bool IsKeywordType(KeywordType tag)
Definition dateparser.h:170