e0b5cf9c55a4308ea073c74791b091a6db30d3fd
[platform/upstream/v8.git] / src / dateparser-inl.h
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>
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 ES6 ISO 8601 date-time-strings or legacy dates compatible
28   // with Safari.
29   // ES6 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 local time if missing.
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 ES6 date-time string.
67   //  After a valid "T" has been read while scanning an ES6 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 ES6 Date Time String.
72   DateToken next_unhandled_token = ParseES6DateTime(&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   for (DateToken token = next_unhandled_token;
77        !token.IsEndOfInput();
78        token = scanner.Next()) {
79     if (token.IsNumber()) {
80       has_read_number = true;
81       int n = token.number();
82       if (scanner.SkipSymbol(':')) {
83         if (scanner.SkipSymbol(':')) {
84           // n + "::"
85           if (!time.IsEmpty()) return false;
86           time.Add(n);
87           time.Add(0);
88         } else {
89           // n + ":"
90           if (!time.Add(n)) return false;
91           if (scanner.Peek().IsSymbol('.')) scanner.Next();
92         }
93       } else if (scanner.SkipSymbol('.') && time.IsExpecting(n)) {
94         time.Add(n);
95         if (!scanner.Peek().IsNumber()) return false;
96         int n = ReadMilliseconds(scanner.Next());
97         if (n < 0) return false;
98         time.AddFinal(n);
99       } else if (tz.IsExpecting(n)) {
100         tz.SetAbsoluteMinute(n);
101       } else if (time.IsExpecting(n)) {
102         time.AddFinal(n);
103         // Require end, white space, "Z", "+" or "-" immediately after
104         // finalizing time.
105         DateToken peek = scanner.Peek();
106         if (!peek.IsEndOfInput() &&
107             !peek.IsWhiteSpace() &&
108             !peek.IsKeywordZ() &&
109             !peek.IsAsciiSign()) return false;
110       } else {
111         if (!day.Add(n)) return false;
112         scanner.SkipSymbol('-');
113       }
114     } else if (token.IsKeyword()) {
115       // Parse a "word" (sequence of chars. >= 'A').
116       KeywordType type = token.keyword_type();
117       int value = token.keyword_value();
118       if (type == AM_PM && !time.IsEmpty()) {
119         time.SetHourOffset(value);
120       } else if (type == MONTH_NAME) {
121         day.SetNamedMonth(value);
122         scanner.SkipSymbol('-');
123       } else if (type == TIME_ZONE_NAME && has_read_number) {
124         tz.Set(value);
125       } else {
126         // Garbage words are illegal if a number has been read.
127         if (has_read_number) return false;
128         // The first number has to be separated from garbage words by
129         // whitespace or other separators.
130         if (scanner.Peek().IsNumber()) return false;
131       }
132     } else if (token.IsAsciiSign() && (tz.IsUTC() || !time.IsEmpty())) {
133       // Parse UTC offset (only after UTC or time).
134       tz.SetSign(token.ascii_sign());
135       // The following number may be empty.
136       int n = 0;
137       if (scanner.Peek().IsNumber()) {
138         n = scanner.Next().number();
139       }
140       has_read_number = true;
141
142       if (scanner.Peek().IsSymbol(':')) {
143         tz.SetAbsoluteHour(n);
144         tz.SetAbsoluteMinute(kNone);
145       } else {
146         tz.SetAbsoluteHour(n / 100);
147         tz.SetAbsoluteMinute(n % 100);
148       }
149     } else if ((token.IsAsciiSign() || token.IsSymbol(')')) &&
150                has_read_number) {
151       // Extra sign or ')' is illegal if a number has been read.
152       return false;
153     } else {
154       // Ignore other characters and whitespace.
155     }
156   }
157
158   return day.Write(out) && time.Write(out) && tz.Write(out);
159 }
160
161
162 template<typename CharType>
163 DateParser::DateToken DateParser::DateStringTokenizer<CharType>::Scan() {
164   int pre_pos = in_->position();
165   if (in_->IsEnd()) return DateToken::EndOfInput();
166   if (in_->IsAsciiDigit()) {
167     int n = in_->ReadUnsignedNumeral();
168     int length = in_->position() - pre_pos;
169     return DateToken::Number(n, length);
170   }
171   if (in_->Skip(':')) return DateToken::Symbol(':');
172   if (in_->Skip('-')) return DateToken::Symbol('-');
173   if (in_->Skip('+')) return DateToken::Symbol('+');
174   if (in_->Skip('.')) return DateToken::Symbol('.');
175   if (in_->Skip(')')) return DateToken::Symbol(')');
176   if (in_->IsAsciiAlphaOrAbove()) {
177     DCHECK(KeywordTable::kPrefixLength == 3);
178     uint32_t buffer[3] = {0, 0, 0};
179     int length = in_->ReadWord(buffer, 3);
180     int index = KeywordTable::Lookup(buffer, length);
181     return DateToken::Keyword(KeywordTable::GetType(index),
182                               KeywordTable::GetValue(index),
183                               length);
184   }
185   if (in_->SkipWhiteSpace()) {
186     return DateToken::WhiteSpace(in_->position() - pre_pos);
187   }
188   if (in_->SkipParentheses()) {
189     return DateToken::Unknown();
190   }
191   in_->Next();
192   return DateToken::Unknown();
193 }
194
195
196 template <typename Char>
197 bool DateParser::InputReader<Char>::SkipWhiteSpace() {
198   if (unicode_cache_->IsWhiteSpaceOrLineTerminator(ch_)) {
199     Next();
200     return true;
201   }
202   return false;
203 }
204
205
206 template <typename Char>
207 bool DateParser::InputReader<Char>::SkipParentheses() {
208   if (ch_ != '(') return false;
209   int balance = 0;
210   do {
211     if (ch_ == ')') --balance;
212     else if (ch_ == '(') ++balance;
213     Next();
214   } while (balance > 0 && ch_);
215   return true;
216 }
217
218
219 template <typename Char>
220 DateParser::DateToken DateParser::ParseES6DateTime(
221     DateStringTokenizer<Char>* scanner,
222     DayComposer* day,
223     TimeComposer* time,
224     TimeZoneComposer* tz) {
225   DCHECK(day->IsEmpty());
226   DCHECK(time->IsEmpty());
227   DCHECK(tz->IsEmpty());
228
229   // Parse mandatory date string: [('-'|'+')yy]yyyy[':'MM[':'DD]]
230   if (scanner->Peek().IsAsciiSign()) {
231     // Keep the sign token, so we can pass it back to the legacy
232     // parser if we don't use it.
233     DateToken sign_token = scanner->Next();
234     if (!scanner->Peek().IsFixedLengthNumber(6)) return sign_token;
235     int sign = sign_token.ascii_sign();
236     int year = scanner->Next().number();
237     if (sign < 0 && year == 0) return sign_token;
238     day->Add(sign * year);
239   } else if (scanner->Peek().IsFixedLengthNumber(4)) {
240     day->Add(scanner->Next().number());
241   } else {
242     return scanner->Next();
243   }
244   if (scanner->SkipSymbol('-')) {
245     if (!scanner->Peek().IsFixedLengthNumber(2) ||
246         !DayComposer::IsMonth(scanner->Peek().number())) return scanner->Next();
247     day->Add(scanner->Next().number());
248     if (scanner->SkipSymbol('-')) {
249       if (!scanner->Peek().IsFixedLengthNumber(2) ||
250           !DayComposer::IsDay(scanner->Peek().number())) return scanner->Next();
251       day->Add(scanner->Next().number());
252     }
253   }
254   // Check for optional time string: 'T'HH':'mm[':'ss['.'sss]]Z
255   if (!scanner->Peek().IsKeywordType(TIME_SEPARATOR)) {
256     if (!scanner->Peek().IsEndOfInput()) return scanner->Next();
257   } else {
258     // ES6 Date Time String time part is present.
259     scanner->Next();
260     if (!scanner->Peek().IsFixedLengthNumber(2) ||
261         !Between(scanner->Peek().number(), 0, 24)) {
262       return DateToken::Invalid();
263     }
264     // Allow 24:00[:00[.000]], but no other time starting with 24.
265     bool hour_is_24 = (scanner->Peek().number() == 24);
266     time->Add(scanner->Next().number());
267     if (!scanner->SkipSymbol(':')) return DateToken::Invalid();
268     if (!scanner->Peek().IsFixedLengthNumber(2) ||
269         !TimeComposer::IsMinute(scanner->Peek().number()) ||
270         (hour_is_24 && scanner->Peek().number() > 0)) {
271       return DateToken::Invalid();
272     }
273     time->Add(scanner->Next().number());
274     if (scanner->SkipSymbol(':')) {
275       if (!scanner->Peek().IsFixedLengthNumber(2) ||
276           !TimeComposer::IsSecond(scanner->Peek().number()) ||
277           (hour_is_24 && scanner->Peek().number() > 0)) {
278         return DateToken::Invalid();
279       }
280       time->Add(scanner->Next().number());
281       if (scanner->SkipSymbol('.')) {
282         if (!scanner->Peek().IsNumber() ||
283             (hour_is_24 && scanner->Peek().number() > 0)) {
284           return DateToken::Invalid();
285         }
286         // Allow more or less than the mandated three digits.
287         time->Add(ReadMilliseconds(scanner->Next()));
288       }
289     }
290     // Check for optional timezone designation: 'Z' | ('+'|'-')hh':'mm
291     if (scanner->Peek().IsKeywordZ()) {
292       scanner->Next();
293       tz->Set(0);
294     } else if (scanner->Peek().IsSymbol('+') ||
295                scanner->Peek().IsSymbol('-')) {
296       tz->SetSign(scanner->Next().symbol() == '+' ? 1 : -1);
297       if (scanner->Peek().IsFixedLengthNumber(4)) {
298         // hhmm extension syntax.
299         int hourmin = scanner->Next().number();
300         int hour = hourmin / 100;
301         int min = hourmin % 100;
302         if (!TimeComposer::IsHour(hour) || !TimeComposer::IsMinute(min)) {
303           return DateToken::Invalid();
304         }
305         tz->SetAbsoluteHour(hour);
306         tz->SetAbsoluteMinute(min);
307       } else {
308         // hh:mm standard syntax.
309         if (!scanner->Peek().IsFixedLengthNumber(2) ||
310             !TimeComposer::IsHour(scanner->Peek().number())) {
311           return DateToken::Invalid();
312         }
313         tz->SetAbsoluteHour(scanner->Next().number());
314         if (!scanner->SkipSymbol(':')) return DateToken::Invalid();
315         if (!scanner->Peek().IsFixedLengthNumber(2) ||
316             !TimeComposer::IsMinute(scanner->Peek().number())) {
317           return DateToken::Invalid();
318         }
319         tz->SetAbsoluteMinute(scanner->Next().number());
320       }
321     }
322     if (!scanner->Peek().IsEndOfInput()) return DateToken::Invalid();
323   }
324   // Successfully parsed ES6 Date Time String.
325   day->set_iso_date();
326   return DateToken::EndOfInput();
327 }
328
329
330 } }  // namespace v8::internal
331
332 #endif  // V8_DATEPARSER_INL_H_