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