-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathparse.jl
624 lines (536 loc) · 19.3 KB
/
parse.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
using Dates: DateFormat, DatePart, min_width, max_width, tryparsenext_base10
using TimeZones.TZData: MIN_YEAR, MAX_YEAR
function tryparsenext_fixedtz(str, i, len, min_width::Int=1, max_width::Int=0)
i == len && str[i] === 'Z' && return ("Z", i+1)
tz_start, tz_end = i, 0
min_pos = min_width <= 0 ? i : i + min_width - 1
max_pos = max_width <= 0 ? len : min(chr2ind(str, ind2chr(str,i) + max_width - 1), len)
state = 1
@inbounds while i <= max_pos
c, ii = iterate(str, i)::Tuple{Char, Int}
if state == 1 && (c === '-' || c === '+')
state = 2
tz_end = i
elseif (state == 1 || state == 2) && '0' <= c <= '9'
state = 3
tz_end = i
elseif state == 3 && c === ':'
state = 4
tz_end = i
elseif (state == 3 || state == 4) && '0' <= c <= '9'
tz_end = i
else
break
end
i = ii
end
if tz_end <= min_pos
return nothing
else
tz = SubString(str, tz_start, tz_end)
return tz, i
end
end
function tryparsenext_tz(str, i, len, min_width::Int=1, max_width::Int=0)
tz_start, tz_end = i, 0
min_pos = min_width <= 0 ? i : i + min_width - 1
max_pos = max_width <= 0 ? len : min(chr2ind(str, ind2chr(str,i) + max_width - 1), len)
@inbounds while i <= max_pos
c, ii = iterate(str, i)::Tuple{Char, Int}
if c === '/' || c === '_' || isletter(c)
tz_end = i
else
break
end
i = ii
end
if tz_end == 0
return nothing
else
name = SubString(str, tz_start, tz_end)
# If the time zone is recognized make sure that it is well-defined. For our
# purposes we'll treat all abbreviations except for UTC and GMT as ambiguous.
# e.g. "MST": "Mountain Standard Time" (UTC-7) or "Moscow Summer Time" (UTC+3:31).
if name == "UTC" || name == "GMT" || '/' in name
return name, i
else
return nothing
end
end
end
function Dates.tryparsenext(d::DatePart{'z'}, str, i, len)
tryparsenext_fixedtz(str, i, len, min_width(d), max_width(d))
end
function Dates.tryparsenext(d::DatePart{'Z'}, str, i, len)
tryparsenext_tz(str, i, len, min_width(d), max_width(d))
end
function Dates.format(io::IO, d::DatePart{'z'}, zdt, locale)
write(io, string(zdt.zone.offset))
end
function Dates.format(io::IO, d::DatePart{'Z'}, zdt, locale)
write(io, string(zdt.zone)) # In most cases will be an abbreviation.
end
# Note: ISOZonedDateTimeFormat is defined in the module __init__ which means that this
# function can not be called from within this module. TODO: Ignore linting for this line
function ZonedDateTime(str::AbstractString, df::DateFormat=ISOZonedDateTimeFormat)
try
parse(ZonedDateTime, str, df)
catch e
if e isa ArgumentError
rethrow(ArgumentError(
"Unable to parse string \"$str\" using format $df. $(e.msg)"
))
else
rethrow()
end
end
end
function ZonedDateTime(str::AbstractString, format::AbstractString; locale::AbstractString="english")
ZonedDateTime(str, DateFormat(format, locale))
end
Dates.default_format(::Type{ZonedDateTime}) = ISOZonedDateTimeFormat
"""
_parsesub_tzabbr(str, [i, len]) -> Union{Tuple{AbstractString, Integer}, Exception}
Parses a section of a string as a time zone abbreviation as defined in the tzset(3) man
page. An abbreviation must be at least three or more alphabetic characters. When enclosed by
the less-than (<) and greater-than (>) signs the character set is expanded to include the
plus (+) sign, the minus (-) sign, and digits.
# Examples
```jldoctest
julia> _parsesub_tzabbr("ABC+1")
("ABC", 4)
julia> _parsesub_tzabbr("<ABC+1>+2")
("ABC+1", 6)
```
"""
function _parsesub_tzabbr(
str::AbstractString,
i::Integer=firstindex(str),
len::Integer=lastindex(str),
)
state = :started
name_start = i
name_end = prevind(str, i)
@inbounds while i <= len
c, ii = iterate(str, i)::Tuple{Char, Int}
isascii(c) || break # Restricts abbreviation support to ASCII characters
if state == :simple && isletter(c)
name_end = i
elseif state == :expanded && (isletter(c) || isdigit(c) || c === '+' || c === '-')
name_end = i
elseif state == :started && c === '<'
name_start = ii
name_end = i
state = :expanded
elseif state == :started && isletter(c)
name_end = i
state = :simple
elseif state == :expanded && c === '>'
i = ii
state = :closed
break
else
break
end
i = ii
end
if state == :expanded
return ParseNextError("Expected expanded time zone abbreviation end with the greater-than sign (>)", str, prevind(str, name_start), i)
elseif state != :closed && name_start > name_end
return ParseNextError("Time zone abbreviation must start with a letter or the less-than (<) character", str, i)
elseif length(str, name_start, name_end) < 3
char_type = if state == :simple
"alphabetic characters"
else
"characters which are either alphanumeric, the plus sign (+), or the minus sign (-)"
end
return ParseNextError("Time zone abbreviation must be at least three $char_type", str, name_start, name_end)
else
name = SubString(str, name_start, name_end)
return name, i
end
end
"""
_parsesub_offset(str, [i, len]) -> Union{Tuple{Integer, Integer}, Exception}
Parses a section of a string as an offset of the form `[+|-]hh[:mm[:ss]]`. The hour must be
between 0 and 24, and the minutes and seconds 00 and 59. This follows specification for
offsets as defined in the tzset(3) man page.
# Example
```jldoctest
julia> _parsesub_offset("1:0:0")
(3600, 5)
julia> _parsesub_offset("-0:1:2")
(-62, 6)
```
"""
function _parsesub_offset(
str::AbstractString,
i::Integer=firstindex(str),
len::Integer=lastindex(str);
name::AbstractString="offset",
)
coefficient = 1
hour = minute = second = 0
if i > len
return ParseNextError("Expected $name and instead found end of string", str, i)
end
# Optional sign
c, ii = iterate(str, i)::Tuple{Char, Int}
if c === '+' || c === '-'
coefficient = c === '-' ? -1 : 1
if ii > len
return ParseNextError("$(uppercasefirst(name)) sign ($c) is not followed by a value", str, i)
end
i = ii
end
# Hours
val = tryparsenext_base10(str, i, len)
if val === nothing
return ParseNextError("Expected $name hour digits", str, i)
end
hour, ii = val
if hour < 0 || hour > 24
return ParseNextError("Hours outside of expected range [0, 24]", str, i, prevind(str, ii))
end
i = ii
i > len && @goto done
c, ii = iterate(str, i)::Tuple{Char, Int}
c !== ':' && @goto done
i = ii
# Minutes
val = tryparsenext_base10(str, i, len)
if val === nothing
return ParseNextError("Expected $name minute digits after colon delimiter", str, i)
end
minute, ii = val
if minute < 0 || minute > 59
return ParseNextError("Minutes outside of expected range [0, 59]", str, i, prevind(str, ii))
end
i = ii
i > len && @goto done
c, ii = iterate(str, i)::Tuple{Char, Int}
c !== ':' && @goto done
i = ii
# Seconds
val = tryparsenext_base10(str, i, len)
if val === nothing
return ParseNextError("Expected $name second digits after colon delimiter", str, i)
end
second, ii = val
if second < 0 || second > 59
return ParseNextError("Seconds outside of expected range [0, 59]", str, i, prevind(str, ii))
end
i = ii
@label done
duration = coefficient * (hour * 3600 + minute * 60 + second)
return duration, i
end
"""
_parsesub_tzdate(str, [i, len]) -> Union{Tuple{Function, Integer}, Exception}
Parses a section of a string as a day of the year as defined in tzset(3). The return value
includes an anonymous function which takes the argument `year::Integer` and returns a
`Date`. The day of year includes these three supported formats:
Jn Specifies the Julian day where `n` is between 1 and 365. Leap days are not
counted. In this format, February 29 can't be represented; February 28 is day 59,
and March 1 is always day 60.
n Specifies the zero-based Julian day with `n` between 0 and 365. February 29 is
counted in leap years. For non-leap years 365 is January 1 of the following year.
Mm.w.d Specifies day `d` (0 <= `d` <= 6) of week `w` (1 <= `w` <= 5) of month `m`
(1 <= `m` <= 12). Week 1 is the first week in which day `d` occurs and week 5 is
the last week in which day `d` occurs. Day 0 is a Sunday.
# Example
```jldoctest
julia> f, i = _parsesub_tzdate("J60");
julia> f.(2019:2020)
2-element Array{Date,1}:
2019-03-01
2020-03-01
julia> f, i = _parsesub_tzdate("60");
2-element Array{Date,1}:
2019-03-02
2020-03-01
julia> f, i = _parsesub_tzdate("M3.3.0"); # Third Sunday in March
julia> f.(2019:2020)
2-element Array{Date,1}:
2019-03-17
2020-03-15
```
"""
function _parsesub_tzdate(
str::AbstractString,
i::Integer=firstindex(str),
len::Integer=lastindex(str),
)
if i > len
return ParseNextError("Expected date and instead found end of string", str, i)
end
# Detect prefix
c, ii = iterate(str, i)::Tuple{Char, Int}
if c === 'J'
i = ii
val = tryparsenext_base10(str, i, len)
if val === nothing
return ParseNextError("Expected to find number of Julian days", str, i)
end
days, ii = val
if days < 1 || days > 365
return ParseNextError("Julian days outside of expected range [1, 365]", str, i, ii)
end
i = ii
# The `J` prefix denotes a day of year between 1 and 365. Leap days are not counted.
# In this format, February 29 can't be represented; February 28 is day 59, and
# March 1 is always day 60.
f = function (year::Integer)
d = days + (isleapyear(year) && days >= 60)
Date(year, 1) + Day(d - 1)
end
return f, i
elseif c === 'M'
i = ii
# Month
val = tryparsenext_base10(str, i, len)
if val === nothing
return ParseNextError("Expected to find month", str, i)
end
month, ii = val
if month < 1 || month > 12
return ParseNextError("Month outside of expected range [1, 12]", str, i, ii)
end
i = ii
c, ii = iterate(str, i)::Tuple{Char, Int}
(c !== '.' || ii > len) && return ParseNextError("Expected to find delimiter (.)", str, i)
i = ii
# Week of month
val = tryparsenext_base10(str, i, len)
if val === nothing
return ParseNextError("Expected to find week of month", str, i)
end
week_of_month, ii = val
if week_of_month < 1 || week_of_month > 5
return ParseNextError("Week of month outside of expected range [1, 5]", str, i, ii)
end
i = ii
c, ii = iterate(str, i)::Tuple{Char, Int}
(c !== '.' || ii > len) && return ParseNextError("Expected to find delimiter (.)", str, i)
i = ii
# Day of week
val = tryparsenext_base10(str, i, len)
if val === nothing
return ParseNextError("Expected to find day of week", str, i)
end
day_of_week, ii = val
if day_of_week < 0 || day_of_week > 6
return ParseNextError("Day of week outside of expected range [0, 6]", str, i, ii)
end
i = ii
# Convert to the Julia day-of-week used by `Dates.dayofweek`
# Equivalent to: `dow = (dow - 7) % 7 + 7`
day_of_week == 0 && (day_of_week = 7)
f = function (year::Integer)
date = Date(year, month, (week_of_month - 1) * 7 + 1)
if week_of_month < 5
step = Day(1)
else
date = lastdayofmonth(date)
step = Day(-1)
end
tonext(d -> dayofweek(d) == day_of_week, date; step=step, same=true, limit=7)
end
return f, i
else
val = tryparsenext_base10(str, i, len)
if val === nothing
return ParseNextError("Expected to find number of Julian days", str, i)
end
days, ii = val
if days < 0 || days > 365
# Note: On non-leap years day 365 will be the first day of the next year. This
# is only supported as the tzset(3) man page explicitly states that the
# zero-based Julia day is between 0 and 365.
return ParseNextError("Julian days outside of expected range [0, 365]", str, i, ii)
end
i = ii
# No prefix specifies the zero-based day of year between 0 and 365. February 29 is
# counted in leap years.
days += 1
f = (year::Integer) -> Date(year, 1) + Day(days - 1)
return f, i
end
end
"""
_parsesub_time(str, [i, len]) -> Union{Tuple{Integer, Integer}, Exception}
Parses a section of a string as a time of the form `hh[:mm[:ss]]`. Primarily this function
is used to parse daylight saving transition times as outlined in tzset(3).
"""
function _parsesub_time(
str::AbstractString,
i::Integer=firstindex(str),
len::Integer=lastindex(str);
name::AbstractString="time",
)
if i > len
return ParseNextError("Expected $name and instead found end of string", str, i)
end
# Require time does not start with a sign.
c, ii = iterate(str, i)::Tuple{Char, Int}
if c === '+' || c === '-'
return ParseNextError("$(uppercasefirst(name)) should not have a sign", str, i)
end
return _parsesub_offset(str, i, len; name=name)
end
"""
_parsesub_tz(str, [i, len]) -> Union{Tuple{TimeZone, Integer}, Exception}
Parse a direct representation of a time zone as specified by the tzset(3) man page.
# Examples
```jldoctest
julia> first(_parsesub_tz("EST+5"))
EST (UTC-5)
julia> first(_parsesub_tz("NZST-12:00:00NZDT-13:00:00,M10.1.0,M3.3.0"))
NZST/NZDT (UTC+12/UTC+13)
"""
function _parsesub_tz(
str::AbstractString,
i::Integer=firstindex(str),
len::Integer=lastindex(str),
)
# An empty or unset TZ environmental variable defaults to UTC
if len == 0
return FixedTimeZone("UTC"), i
end
x = _parsesub_tzabbr(str, i, len)
if x isa Tuple
std_name, i = x
else
return x
end
x = _parsesub_offset(str, i, len; name="standard offset")
if x isa Tuple
std_offset, i = x
else
return x
end
if i <= len
x = _parsesub_tzabbr(str, i, len)
if x isa Tuple
dst_name, i = x
else
return x
end
else
dst_name = nothing
end
dst_offset = nothing
if dst_name !== nothing
iter = iterate(str, i)
if iter !== nothing && first(iter) !== ','
x = _parsesub_offset(str, i, len; name="daylight saving offset")
if x isa Tuple
dst_offset, i = x
else
return x
end
else
dst_offset = std_offset - 3600
end
end
start_dst = first(_parsesub_tzdate("M3.2.0"))::Function # Second Sunday in March
end_dst = first(_parsesub_tzdate("M11.1.0"))::Function # First Sunday in November
start_time = end_time = Hour(2) # 02:00
if i <= len
c, ii = iterate(str, i)::Tuple{Char, Int}
if c !== ','
return ParseNextError("Expected to find delimiter (,)", str, i)
end
i = ii
# Daylight saving goes into effect
x = _parsesub_tzdate(str, i, len)
if x isa Tuple
start_dst, i = x
else
return ParseNextError(
"Unable to parse daylight saving start date. $(x.msg)",
x.str, x.s, x.e,
)
end
i > len && return ParseNextError("Expected to find daylight saving end and instead found end of string", str, i)
c, ii = iterate(str, i)::Tuple{Char, Int}
if c !== '/' && c !== ','
return ParseNextError("Expected to find delimiter (,) or (/)", str, i)
end
i = ii
if c === '/'
x = _parsesub_time(str, i, len; name="daylight saving start time")
if x isa Tuple
start_time, i = x
start_time = Second(start_time)
else
return x
end
i > len && return ParseNextError("Expected to find daylight saving end and instead found end of string", str, i)
c, ii = iterate(str, i)::Tuple{Char, Int}
if c !== ','
return ParseNextError("Expected to find delimiter (,)", str, i)
end
i = ii
end
x = _parsesub_tzdate(str, i, len)
if x isa Tuple
end_dst, i = x
else
return ParseNextError(
"Unable to parse daylight saving end date. $(x.msg)",
x.str, x.s, x.e,
)
end
if i <= len
c, ii = iterate(str, i)::Tuple{Char, Int}
if c !== '/'
return ParseNextError("Expected to find delimiter (/)", str, i)
end
i = ii
x = _parsesub_time(str, i, len; name="daylight saving end time")
if x isa Tuple
end_time, i = x
end_time = Second(end_time)
else
return x
end
end
end
# "The offset is positive if the local timezone is west of the Prime Meridian and
# negative if it is east". As this is the opposite of our internal representation we
# have to negate the values.
# e.g. "STD+1DST+2" results in a timezone with a std/dst offset of UTC-1/UTC-2
std = FixedTimeZone(std_name, -std_offset)
# Note: Most of the parsing time is spent creating the `VariableTimeZone`. The way I
# would like to address this is by introducing a new `TimeZone` subtype which
# dynamically calculates the transitions.
tz = if dst_offset !== nothing
dst = FixedTimeZone(dst_name, -std_offset, -(dst_offset - std_offset))
transitions = Transition[]
for year in 1900:MAX_YEAR
# Note: "The offset specifies the time value to be added to the local time to get
# Coordinated Universal Time (UTC)".
utc_dst = DateTime(start_dst(year)) + start_time + Second(std_offset)
utc_std = DateTime(end_dst(year)) + end_time + Second(dst_offset)
append!(
transitions,
[
Transition(utc_dst, dst),
Transition(utc_std, std),
]
)
end
sort!(transitions)
cutoff_year = MAX_YEAR + 1
utc_dst = DateTime(start_dst(cutoff_year)) + start_time + Second(std_offset)
utc_std = DateTime(end_dst(cutoff_year)) + end_time + Second(dst_offset)
cutoff = min(utc_dst, utc_std)
# TODO: Ideally we would use a new TimeZone subtype which computes transitions
# on-the-fly using the functions we provided.
VariableTimeZone("$std_name/$dst_name", transitions, cutoff)
else
std
end
return tz, i
end