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