blob: a5c7143bdd37743a0b334696ec6e83ecd181b96e [file] [log] [blame]
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001// Copyright 2011 the V8 project authors. All rights reserved.
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
ager@chromium.org5ec48922009-05-05 07:25:34 +000028#ifndef V8_DATEPARSER_INL_H_
29#define V8_DATEPARSER_INL_H_
30
christian.plesner.hansen@gmail.com9d58c2b2009-10-16 11:48:38 +000031#include "dateparser.h"
32
kasperl@chromium.org71affb52009-05-26 05:44:31 +000033namespace v8 {
34namespace internal {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000035
36template <typename Char>
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +000037bool DateParser::Parse(Vector<Char> str,
38 FixedArray* out,
39 UnicodeCache* unicode_cache) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000040 ASSERT(out->length() >= OUTPUT_SIZE);
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +000041 InputReader<Char> in(unicode_cache, str);
ricow@chromium.org4f693d62011-07-04 14:01:31 +000042 DateStringTokenizer<Char> scanner(&in);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +000043 TimeZoneComposer tz;
44 TimeComposer time;
45 DayComposer day;
46
ricow@chromium.org4f693d62011-07-04 14:01:31 +000047 // Specification:
48 // Accept ES5 ISO 8601 date-time-strings or legacy dates compatible
49 // with Safari.
50 // ES5 ISO 8601 dates:
51 // [('-'|'+')yy]yyyy[-MM[-DD]][THH:mm[:ss[.sss]][Z|(+|-)hh:mm]]
52 // where yyyy is in the range 0000..9999 and
53 // +/-yyyyyy is in the range -999999..+999999 -
54 // but -000000 is invalid (year zero must be positive),
55 // MM is in the range 01..12,
56 // DD is in the range 01..31,
57 // MM and DD defaults to 01 if missing,,
58 // HH is generally in the range 00..23, but can be 24 if mm, ss
59 // and sss are zero (or missing), representing midnight at the
60 // end of a day,
61 // mm and ss are in the range 00..59,
62 // sss is in the range 000..999,
63 // hh is in the range 00..23,
64 // mm, ss, and sss default to 00 if missing, and
65 // timezone defaults to Z if missing.
66 // Extensions:
67 // We also allow sss to have more or less than three digits (but at
68 // least one).
69 // We allow hh:mm to be specified as hhmm.
70 // Legacy dates:
71 // Any unrecognized word before the first number is ignored.
72 // Parenthesized text is ignored.
73 // An unsigned number followed by ':' is a time value, and is
74 // added to the TimeComposer. A number followed by '::' adds a second
75 // zero as well. A number followed by '.' is also a time and must be
76 // followed by milliseconds.
77 // Any other number is a date component and is added to DayComposer.
78 // A month name (or really: any word having the same first three letters
79 // as a month name) is recorded as a named month in the Day composer.
80 // A word recognizable as a time-zone is recorded as such, as is
81 // '(+|-)(hhmm|hh:)'.
82 // Legacy dates don't allow extra signs ('+' or '-') or umatched ')'
83 // after a number has been read (before the first number, any garbage
84 // is allowed).
85 // Intersection of the two:
86 // A string that matches both formats (e.g. 1970-01-01) will be
87 // parsed as an ES5 date-time string - which means it will default
88 // to UTC time-zone. That's unavoidable if following the ES5
89 // specification.
90 // After a valid "T" has been read while scanning an ES5 datetime string,
91 // the input can no longer be a valid legacy date, since the "T" is a
92 // garbage string after a number has been read.
93
94 // First try getting as far as possible with as ES5 Date Time String.
95 DateToken next_unhandled_token = ParseES5DateTime(&scanner, &day, &time, &tz);
96 if (next_unhandled_token.IsInvalid()) return false;
97 bool has_read_number = !day.IsEmpty();
98 // If there's anything left, continue with the legacy parser.
99 for (DateToken token = next_unhandled_token;
100 !token.IsEndOfInput();
101 token = scanner.Next()) {
102 if (token.IsNumber()) {
103 has_read_number = true;
104 int n = token.number();
105 if (scanner.SkipSymbol(':')) {
106 if (scanner.SkipSymbol(':')) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000107 // n + "::"
108 if (!time.IsEmpty()) return false;
109 time.Add(n);
110 time.Add(0);
111 } else {
112 // n + ":"
113 if (!time.Add(n)) return false;
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000114 if (scanner.Peek().IsSymbol('.')) scanner.Next();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000115 }
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000116 } else if (scanner.SkipSymbol('.') && time.IsExpecting(n)) {
kmillikin@chromium.org4111b802010-05-03 10:34:42 +0000117 time.Add(n);
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000118 if (!scanner.Peek().IsNumber()) return false;
119 int n = ReadMilliseconds(scanner.Next());
120 if (n < 0) return false;
kmillikin@chromium.org4111b802010-05-03 10:34:42 +0000121 time.AddFinal(n);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000122 } else if (tz.IsExpecting(n)) {
123 tz.SetAbsoluteMinute(n);
124 } else if (time.IsExpecting(n)) {
125 time.AddFinal(n);
sgjesse@chromium.org2ec107f2010-09-13 09:19:46 +0000126 // Require end, white space, "Z", "+" or "-" immediately after
127 // finalizing time.
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000128 DateToken peek = scanner.Peek();
129 if (!peek.IsEndOfInput() &&
130 !peek.IsWhiteSpace() &&
131 !peek.IsKeywordZ() &&
132 !peek.IsAsciiSign()) return false;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000133 } else {
134 if (!day.Add(n)) return false;
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000135 scanner.SkipSymbol('-');
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000136 }
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000137 } else if (token.IsKeyword()) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000138 // Parse a "word" (sequence of chars. >= 'A').
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000139 KeywordType type = token.keyword_type();
140 int value = token.keyword_value();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000141 if (type == AM_PM && !time.IsEmpty()) {
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000142 time.SetHourOffset(value);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000143 } else if (type == MONTH_NAME) {
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000144 day.SetNamedMonth(value);
145 scanner.SkipSymbol('-');
146 } else if (type == TIME_ZONE_NAME && has_read_number) {
147 tz.Set(value);
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000148 } else {
149 // Garbage words are illegal if a number has been read.
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000150 if (has_read_number) return false;
mmassi@chromium.org7028c052012-06-13 11:51:58 +0000151 // The first number has to be separated from garbage words by
152 // whitespace or other separators.
153 if (scanner.Peek().IsNumber()) return false;
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000154 }
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000155 } else if (token.IsAsciiSign() && (tz.IsUTC() || !time.IsEmpty())) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000156 // Parse UTC offset (only after UTC or time).
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000157 tz.SetSign(token.ascii_sign());
158 // The following number may be empty.
159 int n = 0;
160 if (scanner.Peek().IsNumber()) {
161 n = scanner.Next().number();
162 }
163 has_read_number = true;
164
165 if (scanner.Peek().IsSymbol(':')) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000166 tz.SetAbsoluteHour(n);
167 tz.SetAbsoluteMinute(kNone);
168 } else {
169 tz.SetAbsoluteHour(n / 100);
170 tz.SetAbsoluteMinute(n % 100);
171 }
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000172 } else if ((token.IsAsciiSign() || token.IsSymbol(')')) &&
173 has_read_number) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000174 // Extra sign or ')' is illegal if a number has been read.
175 return false;
176 } else {
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000177 // Ignore other characters and whitespace.
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000178 }
179 }
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000180
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000181 return day.Write(out) && time.Write(out) && tz.Write(out);
182}
183
ricow@chromium.org4f693d62011-07-04 14:01:31 +0000184
185template<typename CharType>
186DateParser::DateToken DateParser::DateStringTokenizer<CharType>::Scan() {
187 int pre_pos = in_->position();
188 if (in_->IsEnd()) return DateToken::EndOfInput();
189 if (in_->IsAsciiDigit()) {
190 int n = in_->ReadUnsignedNumeral();
191 int length = in_->position() - pre_pos;
192 return DateToken::Number(n, length);
193 }
194 if (in_->Skip(':')) return DateToken::Symbol(':');
195 if (in_->Skip('-')) return DateToken::Symbol('-');
196 if (in_->Skip('+')) return DateToken::Symbol('+');
197 if (in_->Skip('.')) return DateToken::Symbol('.');
198 if (in_->Skip(')')) return DateToken::Symbol(')');
199 if (in_->IsAsciiAlphaOrAbove()) {
200 ASSERT(KeywordTable::kPrefixLength == 3);
201 uint32_t buffer[3] = {0, 0, 0};
202 int length = in_->ReadWord(buffer, 3);
203 int index = KeywordTable::Lookup(buffer, length);
204 return DateToken::Keyword(KeywordTable::GetType(index),
205 KeywordTable::GetValue(index),
206 length);
207 }
208 if (in_->SkipWhiteSpace()) {
209 return DateToken::WhiteSpace(in_->position() - pre_pos);
210 }
211 if (in_->SkipParentheses()) {
212 return DateToken::Unknown();
213 }
214 in_->Next();
215 return DateToken::Unknown();
216}
217
218
219template <typename Char>
220DateParser::DateToken DateParser::ParseES5DateTime(
221 DateStringTokenizer<Char>* scanner,
222 DayComposer* day,
223 TimeComposer* time,
224 TimeZoneComposer* tz) {
225 ASSERT(day->IsEmpty());
226 ASSERT(time->IsEmpty());
227 ASSERT(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 // ES5 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 ES5 Date Time String. Default to UTC if no TZ given.
325 if (tz->IsEmpty()) tz->Set(0);
326 day->set_iso_date();
327 return DateToken::EndOfInput();
328}
329
330
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000331} } // namespace v8::internal
ager@chromium.org5ec48922009-05-05 07:25:34 +0000332
333#endif // V8_DATEPARSER_INL_H_