-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathyamerl_parser.erl
4525 lines (4216 loc) · 166 KB
/
yamerl_parser.erl
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
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
%-
% Copyright (c) 2012-2014 Yakaz
% Copyright (c) 2016-2022 Jean-Sébastien Pédron <[email protected]>
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions
% are met:
% 1. Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% 2. Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in the
% documentation and/or other materials provided with the distribution.
%
% THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
% ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
% FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
% DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
% OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
% HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
% LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
% OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
% SUCH DAMAGE.
%% @author Jean-Sébastien Pédron <[email protected]>
%% @copyright
%% 2012-2014 Yakaz,
%% 2016-2022 Jean-Sébastien Pédron <[email protected]>
%%
%% @doc {@module} implements a YAML parser. It is not meant to be used
%% directly. Instead, you should use {@link yamerl_constr}.
%%
%% The `yamerl' application must be started to use the parser.
-module(yamerl_parser).
-include("yamerl_errors.hrl").
-include("yamerl_tokens.hrl").
-include("yamerl_parser.hrl").
%% Public API.
-export([
new/1,
new/2,
string/1,
string/2,
file/1,
file/2,
next_chunk/2,
next_chunk/3,
last_chunk/2,
get_token_fun/1,
set_token_fun/2,
option_names/0
]).
%% -------------------------------------------------------------------
%% Exported types.
%% -------------------------------------------------------------------
%% FIXME:
%% This type should be "-opaque". However, up-to Erlang R15B03, an issue
%% with either this code or Dialyzer prevents us from declaring it
%% properly: Dialyzer reports warning regarding the stream_state_fun()
%% type and several guard expression which will never match.
-type yamerl_parser() :: #yamerl_parser{}.
-export_type([
yamerl_parser/0,
yamerl_parser_option/0,
yamerl_parser_token_fun/0
]).
%% -------------------------------------------------------------------
%% Secondary records to store the scanner state.
%% -------------------------------------------------------------------
-record(directive_ctx, {
line = 1 :: position(),
col = 1 :: position(),
name = "" :: string()
}).
-record(yaml_directive_ctx, {
line = 1 :: position(),
col = 1 :: position(),
major :: non_neg_integer() | undefined,
minor :: non_neg_integer() | undefined
}).
-record(tag_directive_ctx, {
line = 1 :: position(),
col = 1 :: position(),
handle :: tag_handle() | [] | undefined,
prefix :: tag_prefix() | [] | undefined
}).
-record(reserved_directive_ctx, {
line = 1 :: position(),
col = 1 :: position(),
name = "" :: string(),
current :: string() | undefined,
args = [] :: [string()],
args_count = 0 :: non_neg_integer()
}).
-type whitespace() :: [9 | 10 | 32].
-record(block_scalar_hd_ctx, {
style = literal :: literal | folded,
line = 1 :: position(), %% Line where the token starts.
col = 1 :: position(), %% Column where the token starts.
chomp :: strip | keep | undefined, %% Chomping indicator.
indent :: pos_integer() %% Indentation indicator.
| {tmp, pos_integer()} | undefined,
in_comment = false :: boolean() %% Trailing comment.
}).
-record(block_scalar_ctx, {
style = literal :: literal | folded,
line = 1 :: position(), %% Line where the token starts.
col = 1 :: position(), %% Column where the token starts.
endline = 1 :: position(), %% Line where the token ends.
endcol = 1 :: position(), %% Column where the token ends.
chomp = clip :: strip | keep | clip, %% Chomping method.
indent :: pos_integer() | undefined, %% Block indent.
longest_empty = 0 :: non_neg_integer(), %% Longest leading empty line.
newline = false :: boolean(), %% Met a newline character.
spaces = "" :: whitespace(), %% Last white spaces seen.
more_indent = false :: boolean(), %% Last line is more indented.
output = "" :: string() %% Already parsed characters.
}).
-record(flow_scalar_ctx, {
style = plain :: double_quoted | single_quoted | plain,
line = 1 :: position(), %% Line where the token starts.
col = 1 :: position(), %% Column where the token starts.
endline = 1 :: position(), %% Line where the token ends.
endcol = 1 :: position(), %% Column where the token ends.
surrogate :: 16#d800..16#dbff | undefined, %% High surrogate.
newline = false :: boolean(), %% Met a newline character.
spaces = "" :: whitespace(), %% Last white spaces seen.
output = "" :: string() %% Already parsed characters.
}).
-record(anchor_ctx, {
type :: anchor | alias,
line :: position(),
col :: position(),
output = "" :: string()
}).
-record(tag_ctx, {
line :: position(),
col :: position(),
prefix :: string() | undefined,
suffix :: string() | tag_uri()
}).
-define(IO_BLOCKSIZE, 4096). %% Common filesystem blocksize.
-define(FAKE_IMPL_KEY, #impl_key{}).
-define(IN_BLOCK_CTX(P), (is_record(P#yamerl_parser.cur_coll, bcoll))).
-define(IN_FLOW_CTX(P), (is_record(P#yamerl_parser.cur_coll, fcoll))).
-define(IS_SPACE(C), (C == $\s orelse C == $\t)).
-define(IS_NEWLINE(C), (C == $\n orelse C == $\r)).
-define(IS_NEWLINE_11(C),
(C == 16#85 orelse C == 16#2028 orelse C == 16#2029)).
-define(IS_FLOW_INDICATOR(C), (
C == $[ orelse C == $] orelse
C == ${ orelse C == $} orelse
C == $,)).
-define(IS_HEXADECIMAL(C), (
(O1 >= $0 andalso O1 =< $9) orelse
(O1 >= $a andalso O1 =< $f) orelse
(O1 >= $A andalso O1 =< $F)
)).
-define(IS_URI_CHAR(C),
(
(C >= $a andalso C =< $z) orelse
(C >= $A andalso C =< $Z) orelse
(C >= $0 andalso C =< $9) orelse
C == $- orelse
C == $% orelse C == $# orelse C == $; orelse C == $/ orelse C == $? orelse
C == $: orelse C == $@ orelse C == $& orelse C == $= orelse C == $+ orelse
C == $$ orelse C == $, orelse C == $_ orelse C == $. orelse C == $! orelse
C == $~ orelse C == $* orelse C == $' orelse C == $( orelse C == $) orelse
C == $[ orelse C == $]
)).
-define(IS_BOM(C), (C == 16#feff)).
-define(IS_HIGH_SURROGATE(C), (C >= 16#d800 andalso C =< 16#dbff)).
-define(IS_LOW_SURROGATE(C), (C >= 16#dc00 andalso C =< 16#dfff)).
-define(MISSING_ENTRY(S), (
S#yamerl_parser.pending_entry andalso
S#yamerl_parser.last_tag == undefined
)).
-define(MISSING_KVPAIR(S), (
S#yamerl_parser.waiting_for_kvpair andalso
not element(#impl_key.possible, hd(S#yamerl_parser.ik_stack))
)).
-define(IS_JSON_LIKE(T), (
(is_record(T, yamerl_scalar) andalso
(T#yamerl_scalar.substyle == single_quoted orelse
T#yamerl_scalar.substyle == double_quoted)) orelse
(is_record(T, yamerl_collection_end) andalso
T#yamerl_collection_end.style == flow)
)).
-define(DEFAULT_TAG(U, L, C),
#yamerl_tag{
uri = U,
line = L,
column = C
}).
-define(NEXT_COL(Co, De, Count),
{Co + Count, De + Count}).
-define(NEXT_LINE(Ch, Li, De, P),
case Ch of
[$\r, $\n | R] -> {R, Li + 1, 1, De + 2};
[_ | R] -> {R, Li + 1, 1, De + 1}
end).
%%
%% We use macros instead of functions for a few #yamerl_parser updates
%% to take advantage of the optimization described in §3.5 in the
%% Efficiency Guide.
%%
-define(PUSH_FAKE_IMPL_KEY(P),
P#yamerl_parser{ik_stack = [?FAKE_IMPL_KEY | P#yamerl_parser.ik_stack]}).
-define(POP_IMPL_KEY(P),
P#yamerl_parser{ik_stack = tl(P#yamerl_parser.ik_stack)}).
-define(ALLOW_IMPL_KEY(P, F),
P#yamerl_parser{ik_allowed = F}).
-define(FLUSH_TO_PARSER(Ch, Li, Co, De, P),
P#yamerl_parser{
chars = Ch,
chars_len = P#yamerl_parser.chars_len - De,
chars_idx = P#yamerl_parser.chars_idx + De,
line = Li,
col = Co
}).
-define(WARN_IF_NON_ASCII_LINE_BREAK(Ch, Li, Co, P),
case Ch of
[NL | _] when ?IS_NEWLINE_11(NL) ->
%% Non-ASCII line break in a YAML 1.2 document.
Err = #yamerl_parsing_error{
type = warning,
name = non_ascii_line_break,
line = Li,
column = Co
},
add_error(P, Err,
"Use of non-ASCII line break is not supported anymore starting "
"with YAML 1.2; treated as non-break character", []);
_ ->
P
end).
-define(BLOCK_SCALAR_DEFAULT_TAG(L, C),
?DEFAULT_TAG({non_specific, "!"}, L, C)).
-define(PLAIN_SCALAR_DEFAULT_TAG(L, C),
?DEFAULT_TAG({non_specific, "?"}, L, C)).
-define(FLOW_SCALAR_DEFAULT_TAG(L, C),
?DEFAULT_TAG({non_specific, "!"}, L, C)).
-define(COLL_SCALAR_DEFAULT_TAG(L, C),
?DEFAULT_TAG({non_specific, "?"}, L, C)).
%% -------------------------------------------------------------------
%% Public API: chunked stream scanning.
%% -------------------------------------------------------------------
%% @equiv new(Source, [])
-spec new(Source) ->
Parser | no_return() when
Source :: term(),
Parser :: yamerl_parser().
new(Source) ->
new(Source, []).
%% @doc Creates and returns a new YAML parser state.
-spec new(Source, Options) ->
Parser | no_return() when
Source :: term(),
Options :: [yamerl_parser_option()],
Parser :: yamerl_parser().
new(Source, Options) ->
Options0 = proplists:unfold(Options),
check_options(Options0),
#yamerl_parser{
source = Source,
options = Options0,
stream_state = fun start_stream/5,
token_fun = proplists:get_value(token_fun, Options0, acc)
}.
%% @equiv next_chunk(Parser, Chunk, false)
-spec next_chunk(Parser, Chunk) ->
Ret | no_return() when
Parser :: yamerl_parser(),
Chunk :: unicode_binary(),
Ret :: {continue, New_Parser},
New_Parser :: yamerl_parser().
next_chunk(Parser, Chunk) ->
next_chunk(Parser, Chunk, false).
%% @doc Feeds the parser with the next chunk from the YAML stream.
-spec next_chunk(Parser, Chunk, Last_Chunk) ->
Ret | no_return() when
Parser :: yamerl_parser(),
Chunk :: unicode_binary(),
Last_Chunk :: boolean(),
Ret :: {continue, New_Parser} | New_Parser,
New_Parser :: yamerl_parser().
next_chunk(Parser, <<>>, false) ->
%% No need to proceed further without any data.
do_return(Parser);
next_chunk(#yamerl_parser{raw_data = Data} = Parser, Chunk, EOS) ->
%% Append new data to the remaining data. Those data must then be
%% decoded to Unicode characters.
New_Data = list_to_binary([Data, Chunk]),
Parser1 = Parser#yamerl_parser{
raw_data = New_Data,
raw_eos = EOS
},
decode_unicode(Parser1).
%% @equiv next_chunk(Parser, Chunk, true)
-spec last_chunk(Parser, Chunk) ->
Ret | no_return() when
Parser :: yamerl_parser(),
Chunk :: unicode_binary(),
Ret :: {continue, New_Parser} | New_Parser,
New_Parser :: yamerl_parser().
last_chunk(Parser, Chunk) ->
next_chunk(Parser, Chunk, true).
%% -------------------------------------------------------------------
%% Public API: common stream sources.
%% -------------------------------------------------------------------
%% @equiv string(String, [])
-spec string(String) ->
Parser | no_return() when
String :: unicode_data(),
Parser :: yamerl_parser().
string(String) ->
string(String, []).
%% @doc Parses a YAML document from an in-memory YAML string.
-spec string(String, Options) ->
Parser | no_return() when
String :: unicode_data(),
Options :: [yamerl_parser_option()],
Parser :: yamerl_parser().
string(String, Options) when is_binary(String) ->
Parser = new(string, Options),
next_chunk(Parser, String, true);
string(String, Options) when is_list(String) ->
string(unicode:characters_to_binary(String), Options).
%% @equiv file(Filename, [])
-spec file(Filename) ->
Parser | no_return() when
Filename :: string(),
Parser :: yamerl_parser().
file(Filename) ->
file(Filename, []).
%% @doc Parses a YAML document from a regular file.
-spec file(Filename, Options) ->
Parser | no_return() when
Filename :: string(),
Options :: [yamerl_parser_option()],
Parser :: yamerl_parser().
file(Filename, Options) ->
Parser = new({file, Filename}, Options),
Blocksize = proplists:get_value(io_blocksize, Options, ?IO_BLOCKSIZE),
case file:open(Filename, [read, binary]) of
{ok, FD} ->
%% The file is read in binary mode. The scanner is
%% responsible for determining the encoding and converting
%% the stream accordingly.
file2(Parser, FD, Blocksize);
{error, Reason} ->
Error2 = #yamerl_parsing_error{
name = file_open_failure,
extra = [{error, Reason}]
},
Parser2 = add_error(Parser, Error2,
"Failed to open file \"~s\": ~s",
[Filename, file:format_error(Reason)]),
do_return(Parser2)
end.
file2(#yamerl_parser{source = {file, Filename}} = Parser, FD, Blocksize) ->
case file:read(FD, Blocksize) of
{ok, Data} ->
%% If the chunk is smaller than the requested size, we
%% reached EOS.
EOS = byte_size(Data) < Blocksize,
if
EOS -> file:close(FD);
true -> ok
end,
try
case next_chunk(Parser, Data, EOS) of
{continue, Parser1} ->
file2(Parser1, FD, Blocksize);
Parser1 ->
Parser1
end
catch
throw:{yamerl_parser, _} = Exception ->
%% Close the file and throw the exception again.
file:close(FD),
throw(Exception)
end;
eof ->
file:close(FD),
next_chunk(Parser, <<>>, true);
{error, Reason} ->
Error = #yamerl_parsing_error{
name = file_read_failure,
extra = [{error, Reason}]
},
Parser1 = add_error(Parser, Error,
"Failed to read file \"~s\": ~s",
[Filename, file:format_error(Reason)]),
do_return(Parser1)
end.
%% -------------------------------------------------------------------
%% Public API: get/set the token function.
%% -------------------------------------------------------------------
%% @doc Returns the constructor callback function
get_token_fun(#yamerl_parser{token_fun = Fun}) ->
Fun.
%% @doc Sets the constructor callback function
set_token_fun(Parser, Fun) when is_function(Fun, 1) ->
Parser#yamerl_parser{token_fun = Fun}.
%% -------------------------------------------------------------------
%% Determine encoding and decode Unicode.
%% -------------------------------------------------------------------
decode_unicode(#yamerl_parser{stream_state = State,
encoding = Encoding, raw_data = Data, raw_idx = Raw_Index,
chars = Chars, chars_len = Chars_Count} = Parser)
when Encoding /= undefined ->
%% We have previously determined the encoding of the stream. We can
%% decode the Unicode characters from the raw data.
Ret = unicode:characters_to_list(Data, Encoding),
{Parser2, Chars2} = case Ret of
{Reason, New_Chars, Remaining_Data} ->
%% Ok, we have more characters to scan!
Raw_Index1 = Raw_Index +
(byte_size(Data) - byte_size(Remaining_Data)),
Parser1 = Parser#yamerl_parser{
raw_data = Remaining_Data,
raw_idx = Raw_Index1,
chars_len = Chars_Count + length(New_Chars)
},
Chars1 = Chars ++ New_Chars,
case Reason of
incomplete ->
{Parser1, Chars1};
error ->
Error = #yamerl_parsing_error{
name = invalid_unicode,
extra = [{byte, Raw_Index1 + 1}]
},
{
add_error(Parser1, Error,
"Invalid Unicode character at byte #~b",
[Raw_Index1 + 1]),
Chars1
}
end;
New_Chars ->
%% Ok, we have more characters to scan!
Raw_Index1 = Raw_Index + byte_size(Data),
Parser1 = Parser#yamerl_parser{
raw_data = <<>>,
raw_idx = Raw_Index1,
chars_len = Chars_Count + length(New_Chars)
},
Chars1 = Chars ++ New_Chars,
{Parser1, Chars1}
end,
State(Chars2, Parser2#yamerl_parser.line, Parser2#yamerl_parser.col, 0,
Parser2);
decode_unicode(#yamerl_parser{raw_data = Data, raw_eos = EOS} = Parser)
when ((EOS == false andalso byte_size(Data) >= 4) orelse EOS == true) ->
%% We have enough (maybe even all) data to determine the encoding.
%% Let's check if the stream starts with a BOM.
{Encoding, Length} = get_encoding(Data),
%% The stream may start with a BOM: remove it.
<<_:Length/binary, New_Data/binary>> = Data,
Parser1 = Parser#yamerl_parser{
encoding = Encoding,
raw_data = New_Data,
raw_idx = Length,
chars_idx = 1
},
decode_unicode(Parser1);
decode_unicode(Parser) ->
%% We don't have enough data to determine the encoding. We ask for
%% more data.
do_return(Parser).
get_encoding(<<16#00, 16#00, 16#fe, 16#ff, _/binary>>) -> {{utf32, big}, 4};
get_encoding(<<16#00, 16#00, 16#00, _, _/binary>>) -> {{utf32, big}, 0};
get_encoding(<<16#ff, 16#fe, 16#00, 16#00, _/binary>>) -> {{utf32, little}, 4};
get_encoding(<<_, 16#00, 16#00, 16#00, _/binary>>) -> {{utf32, little}, 0};
get_encoding(<<16#fe, 16#ff, _, _, _/binary>>) -> {{utf16, big}, 2};
get_encoding(<<16#00, _, _, _, _/binary>>) -> {{utf16, big}, 0};
get_encoding(<<16#ff, 16#fe, _, _, _/binary>>) -> {{utf16, little}, 2};
get_encoding(<<_, 16#00, _, _, _/binary>>) -> {{utf16, little}, 0};
get_encoding(<<16#ef, 16#bb, 16#bf, _, _/binary>>) -> {utf8, 3};
get_encoding(_) -> {utf8, 0}.
%% -------------------------------------------------------------------
%% Scan characters and emit tokens.
%% -------------------------------------------------------------------
%%
%% Stream start/end.
%%
start_stream(Chars, Line, Col, Delta,
#yamerl_parser{encoding = Encoding} = Parser) ->
%% The very first token to emit is the stream start. The stream
%% encoding is provided as an attribute. The encoding may appear at
%% the start of each document but can't be changed: all documents
%% must have the same encoding!
Parser1 = ?PUSH_FAKE_IMPL_KEY(Parser),
Parser2 = ?ALLOW_IMPL_KEY(Parser1, true),
Parser3 = setup_default_tags(Parser2),
Token = #yamerl_stream_start{
encoding = Encoding,
line = Line,
column = Col
},
Parser4 = queue_token(Parser3, Token),
find_next_token(Chars, Line, Col, Delta, Parser4).
end_stream(Chars, Line, Col, Delta,
#yamerl_parser{last_token_endline = Last_Line,
last_token_endcol = Last_Col} = Parser) ->
%% Reset cursor on column 0 to close all opened block collections.
Parser1 = check_for_closed_block_collections(Chars, Line, Col, Delta,
Parser, 0),
Parser2 = remove_impl_key_pos(Parser1),
Parser3 = ?ALLOW_IMPL_KEY(Parser2, false),
%% Set the line and column number to the last token endline/endcol
%% number. This is useful when parsing a file: the last line is
%% often terminated by a newline character. Thanks to this, the
%% stream_end token will be on the last token line.
Token = #yamerl_stream_end{
line = Last_Line,
column = Last_Col
},
Parser4 = queue_token(Parser3, Token),
return(Chars, Line, Col, Delta, Parser4).
%%
%% Next token.
%%
find_next_token(Chars, Line, Col, Delta,
#yamerl_parser{endpos_set_by_token = true} = Parser) ->
%% The line and column numbers where the last token ends was already
%% set during token parsing.
Parser1 = Parser#yamerl_parser{
endpos_set_by_token = false
},
do_find_next_token(Chars, Line, Col, Delta, Parser1);
find_next_token(Chars, Line, Col, Delta, Parser) ->
%% Record the line and columns numbers where the last token ends.
%% It's used to determine if an implicit key would span several
%% lines and therefore would be unacceptable.
Parser1 = Parser#yamerl_parser{
endpos_set_by_token = false,
last_token_endline = Line,
last_token_endcol = Col
},
do_find_next_token(Chars, Line, Col, Delta, Parser1).
%% Skip spaces.
do_find_next_token([$\s | Rest], Line, Col, Delta, Parser) ->
{Col1, Delta1} = ?NEXT_COL(Col, Delta, 1),
do_find_next_token(Rest, Line, Col1, Delta1, Parser);
%% Skip tabs only when they're separation spaces, not indentation.
do_find_next_token([$\t | Rest], Line, Col, Delta,
#yamerl_parser{ik_allowed = IK_Allowed} = Parser)
when ?IN_FLOW_CTX(Parser) orelse not IK_Allowed ->
{Col1, Delta1} = ?NEXT_COL(Col, Delta, 1),
do_find_next_token(Rest, Line, Col1, Delta1, Parser);
%% Skip comments.
do_find_next_token([$# | _] = Chars, Line, Col, Delta, Parser) ->
parse_comment(Chars, Line, Col, Delta, Parser);
%% Continue with next line.
do_find_next_token(Chars, Line, Col, Delta,
#yamerl_parser{missed_nl = true} = Parser) ->
Parser1 = Parser#yamerl_parser{
missed_nl = false
},
Parser2 = if
?IN_BLOCK_CTX(Parser1) -> ?ALLOW_IMPL_KEY(Parser1, true);
true -> Parser1
end,
do_find_next_token(Chars, Line, Col, Delta, Parser2);
do_find_next_token([$\r] = Chars, Line, Col, Delta,
#yamerl_parser{raw_eos = false} = Parser) ->
%% Can't be sure it's a newline. It may be followed by a LF.
suspend_parsing(Chars, Line, Col, Delta, Parser, fun do_find_next_token/5);
do_find_next_token([C | _] = Chars, Line, _, Delta,
#yamerl_parser{doc_version = Version} = Parser)
when ?IS_NEWLINE(C) orelse (Version == {1,1} andalso ?IS_NEWLINE_11(C)) ->
{Chars1, Line1, Col1, Delta1} = ?NEXT_LINE(Chars, Line, Delta, Parser),
Parser1 = if
?IN_BLOCK_CTX(Parser) -> ?ALLOW_IMPL_KEY(Parser, true);
true -> Parser
end,
do_find_next_token(Chars1, Line1, Col1, Delta1, Parser1);
%% End-of-stream reached.
do_find_next_token([] = Chars, Line, Col, Delta,
#yamerl_parser{raw_eos = true} = Parser) ->
end_stream(Chars, Line, Col, Delta, Parser);
%% Wait for more data.
do_find_next_token([] = Chars, Line, Col, Delta, Parser) ->
suspend_parsing(Chars, Line, Col, Delta, Parser, fun do_find_next_token/5);
%% Next token found!
do_find_next_token(Chars, Line, Col, Delta, Parser) ->
Parser1 = ?WARN_IF_NON_ASCII_LINE_BREAK(Chars, Line, Col, Parser),
Parser2 = check_for_closed_block_collections(Chars, Line, Col, Delta,
Parser1, Col),
determine_token_type(Chars, Line, Col, Delta, Parser2).
%%
%% Token type.
%%
%% Not enough data to determine the token type.
determine_token_type(Chars, Line, Col, Delta,
#yamerl_parser{chars_len = Len, raw_eos = false} = Parser)
when (Len - Delta) < 4 ->
suspend_parsing(Chars, Line, Col, Delta, Parser,
fun determine_token_type/5);
%% BOM, before a document only!
determine_token_type([C | Rest], Line, Col, Delta,
#yamerl_parser{doc_started = false} = Parser)
when ?IS_BOM(C) ->
{Col1, Delta1} = ?NEXT_COL(Col, Delta, 1),
find_next_token(Rest, Line, Col1, Delta1, Parser);
determine_token_type([C | Rest], Line, Col, Delta,
#yamerl_parser{doc_started = true} = Parser)
when ?IS_BOM(C) ->
%% A BOM is forbidden after the document start. Because it's not
%% fatal during parsing, we only add a warning. Note that the YAML
%% specification considers this to be an error.
Error = #yamerl_parsing_error{
type = warning,
name = bom_after_doc_start,
line = Line,
column = Col
},
Parser1 = add_error(Parser, Error,
"A BOM must not appear inside a document", []),
{Col1, Delta1} = ?NEXT_COL(Col, Delta, 1),
find_next_token(Rest, Line, Col1, Delta1, Parser1);
%% Directives end indicator.
determine_token_type([$-, $-, $-, C | _] = Chars, Line, 1 = Col, Delta,
#yamerl_parser{doc_version = Version} = Parser)
when ?IS_NEWLINE(C) orelse ?IS_SPACE(C) orelse
(Version == {1,1} andalso ?IS_NEWLINE_11(C)) ->
parse_document_sep(Chars, Line, Col, Delta, Parser, directives_end);
determine_token_type([$-, $-, $-] = Chars, Line, 1 = Col, Delta,
#yamerl_parser{raw_eos = true} = Parser) ->
parse_document_sep(Chars, Line, Col, Delta, Parser, directives_end);
%% Document end indicator.
determine_token_type([$., $., $., C | _] = Chars, Line, 1 = Col, Delta,
#yamerl_parser{doc_version = Version} = Parser)
when ?IS_NEWLINE(C) orelse ?IS_SPACE(C) orelse
(Version == {1,1} andalso ?IS_NEWLINE_11(C)) ->
parse_document_sep(Chars, Line, Col, Delta, Parser, document_end);
determine_token_type([$., $., $.] = Chars, Line, 1 = Col, Delta,
#yamerl_parser{raw_eos = true} = Parser) ->
parse_document_sep(Chars, Line, Col, Delta, Parser, document_end);
%% Directive indicator.
determine_token_type([$% | _] = Chars, Line, 1 = Col, Delta,
#yamerl_parser{doc_started = false} = Parser) ->
parse_directive(Chars, Line, Col, Delta, Parser);
%% Flow sequence indicators.
determine_token_type([$[ | _] = Chars, Line, Col, Delta, Parser) ->
parse_flow_collection_start(Chars, Line, Col, Delta, Parser, sequence);
determine_token_type([$] | _] = Chars, Line, Col, Delta, Parser) ->
parse_flow_collection_end(Chars, Line, Col, Delta, Parser, sequence);
%% Flow mapping indicators.
determine_token_type([${ | _] = Chars, Line, Col, Delta, Parser) ->
parse_flow_collection_start(Chars, Line, Col, Delta, Parser, mapping);
determine_token_type([$} | _] = Chars, Line, Col, Delta, Parser) ->
parse_flow_collection_end(Chars, Line, Col, Delta, Parser, mapping);
%% Flow collection entry indicator.
determine_token_type([$, | _] = Chars, Line, Col, Delta, Parser) ->
parse_flow_entry(Chars, Line, Col, Delta, Parser);
%% Block collection entry indicator.
determine_token_type([$-, C | _] = Chars, Line, Col, Delta,
#yamerl_parser{doc_version = Version} = Parser)
when ?IS_SPACE(C) orelse ?IS_NEWLINE(C) orelse
(Version == {1,1} andalso ?IS_NEWLINE_11(C)) ->
parse_block_entry(Chars, Line, Col, Delta, Parser);
%% Mapping key indicator.
determine_token_type([$?, C | _] = Chars, Line, Col, Delta,
#yamerl_parser{doc_version = Version} = Parser)
when ?IS_SPACE(C) orelse ?IS_NEWLINE(C) orelse
(Version == {1,1} andalso ?IS_NEWLINE_11(C)) ->
parse_mapping_key(Chars, Line, Col, Delta, Parser);
%% Mapping value indicator.
determine_token_type([$:, C | _] = Chars, Line, Col, Delta,
#yamerl_parser{doc_version = Version} = Parser)
when ?IS_SPACE(C) orelse ?IS_NEWLINE(C) orelse ?IS_FLOW_INDICATOR(C) orelse
(Version == {1,1} andalso ?IS_NEWLINE_11(C)) ->
parse_mapping_value(Chars, Line, Col, Delta, Parser);
determine_token_type([$: | _] = Chars, Line, Col, Delta,
#yamerl_parser{last_is_json_like = true} = Parser)
when ?IN_FLOW_CTX(Parser) ->
%% This is a key: value pair indicator only when the last token is
%% JSON-like and we're in flow context.
parse_mapping_value(Chars, Line, Col, Delta, Parser);
determine_token_type([$:] = Chars, Line, Col, Delta,
#yamerl_parser{raw_eos = true} = Parser)
when ?IN_BLOCK_CTX(Parser) ->
parse_mapping_value(Chars, Line, Col, Delta, Parser);
%% Anchor and alias indicator.
determine_token_type([$& | _] = Chars, Line, Col, Delta, Parser) ->
parse_anchor_or_alias(Chars, Line, Col, Delta, Parser, anchor);
determine_token_type([$* | _] = Chars, Line, Col, Delta, Parser) ->
parse_anchor_or_alias(Chars, Line, Col, Delta, Parser, alias);
%% Tag indicator.
determine_token_type([$! | _] = Chars, Line, Col, Delta, Parser) ->
parse_tag(Chars, Line, Col, Delta, Parser);
%% Block scalar.
determine_token_type([$| | _] = Chars, Line, Col, Delta, Parser) ->
parse_block_scalar(Chars, Line, Col, Delta, Parser, literal);
determine_token_type([$> | _] = Chars, Line, Col, Delta, Parser) ->
parse_block_scalar(Chars, Line, Col, Delta, Parser, folded);
%% Single-quoted flow scalar.
determine_token_type([$' | _] = Chars, Line, Col, Delta, Parser) ->
parse_flow_scalar(Chars, Line, Col, Delta, Parser, single_quoted);
%% Double-quoted flow scalar.
determine_token_type([$" | _] = Chars, Line, Col, Delta, Parser) ->
parse_flow_scalar(Chars, Line, Col, Delta, Parser, double_quoted);
%% Reserved indicators.
%% We add a warning and parse it as a plain scalar.
determine_token_type([C | _] = Chars, Line, Col, Delta, Parser)
when C == $@ orelse C == $` ->
Error = #yamerl_parsing_error{
name = reserved_indicator,
type = warning,
line = Line,
column = Col
},
Parser1 = add_error(Parser, Error,
"The reserved indicator \"~c\" is not allowed at the "
"beginning of a plain scalar", [C]),
parse_flow_scalar(Chars, Line, Col, Delta, Parser1, plain);
%% Plain flow scalar.
determine_token_type(Chars, Line, Col, Delta, Parser) ->
parse_flow_scalar(Chars, Line, Col, Delta, Parser, plain).
%% -------------------------------------------------------------------
%% Directives and document ends.
%% -------------------------------------------------------------------
parse_document_sep([_, _, _ | Rest] = Chars, Line, Col, Delta, Parser, Type) ->
%% Reset cursor on column 0 to close all opened block collections.
Parser1 = check_for_closed_block_collections(Chars, Line, Col, Delta,
Parser, 0),
Parser2 = remove_impl_key_pos(Parser1),
Parser3 = ?ALLOW_IMPL_KEY(Parser2, false),
Parser4 = case Type of
directives_end -> start_doc(Parser3, Line, Col, tail);
document_end -> end_doc(Parser3, Line, Col, tail)
end,
{Col1, Delta1} = ?NEXT_COL(Col, Delta, 3),
find_next_token(Rest, Line, Col1, Delta1, Parser4).
start_doc(#yamerl_parser{doc_started = true} = Parser,
Line, Col, Insert_At) ->
%% A document is already opened: we must close it before starting a
%% new one.
Parser1 = end_doc(Parser, Line, Col, Insert_At),
start_doc(Parser1, Line, Col, next_insert_at(Insert_At, 1));
start_doc(
#yamerl_parser{options = Options, doc_version = Version,
tags = Tags} = Parser,
Line, Col, Insert_At) ->
%% When a document starts, we set the version to
%% ?IMPLICIT_DOC_VERSION if no YAML directive were specified.
Forced = proplists:get_value(doc_version, Options),
Version1 = case Version of
_ when Forced /= undefined -> Forced;
undefined -> ?IMPLICIT_YAML_VERSION;
_ -> Version
end,
Token = #yamerl_doc_start{
version = Version1,
tags = Tags,
line = Line,
column = Col
},
Parser1 = case Version1 of
{Major, Minor} when Major < ?MIN_YAML_MAJOR_VERSION_SUPPORTED orelse
(Major == ?MIN_YAML_MAJOR_VERSION_SUPPORTED andalso
Minor < ?MIN_YAML_MINOR_VERSION_SUPPORTED) ->
%% The document's version is not supported at all (below
%% minimum supported version).
Error = #yamerl_parsing_error{
name = version_not_supported,
token = Token,
line = Line,
column = Col
},
Parser0 = add_error(Parser, Error,
"Version ~b.~b not supported (minimum version ~b.~b)",
[
Major, Minor,
?MIN_YAML_MAJOR_VERSION_SUPPORTED,
?MIN_YAML_MINOR_VERSION_SUPPORTED
]),
%% Caution: Chars/Line/Col/Delta aren't flushed to Parser.
do_return(Parser0);
{Major, Minor} when
Major < ?MAX_YAML_MAJOR_VERSION_SUPPORTED orelse
(Major == ?MAX_YAML_MAJOR_VERSION_SUPPORTED andalso
Minor =< ?MAX_YAML_MINOR_VERSION_SUPPORTED) ->
%% Version supported.
Parser;
{Major, Minor} when Major > ?MAX_YAML_MAJOR_VERSION_SUPPORTED ->
%% The document's version is not supported at all (major
%% above maximum supported major).
Error = #yamerl_parsing_error{
name = version_not_supported,
token = Token,
line = Line,
column = Col
},
Parser0 = add_error(Parser, Error,
"Version ~b.~b not supported (maximum version ~b.~b)",
[
Major, Minor,
?MAX_YAML_MAJOR_VERSION_SUPPORTED,
?MAX_YAML_MINOR_VERSION_SUPPORTED
]),
%% Caution: Chars/Line/Col/Delta aren't flushed to Parser.
do_return(Parser0);
{Major, Minor} when Minor > ?MAX_YAML_MINOR_VERSION_SUPPORTED ->
%% The document's minor version is greater than the
%% supported version. Add a warning and continue anyway.
Error = #yamerl_parsing_error{
name = version_not_supported,
type = warning,
token = Token,
line = Line,
column = Col
},
Parser0 = add_error(Parser, Error,
"Version ~b.~b not supported (maximum version ~b.~b); "
"parsing may fail",
[
Major, Minor,
?MAX_YAML_MAJOR_VERSION_SUPPORTED,
?MAX_YAML_MINOR_VERSION_SUPPORTED
]),
Parser0
end,
Parser2 = Parser1#yamerl_parser{
doc_started = true,
doc_version = Version1
},
%% Emit a token with the determined version and the tags table.
queue_token(Parser2, Token, Insert_At).
end_doc(#yamerl_parser{doc_started = false} = Parser, _, _, _) ->
%% No document to end.
Parser;
end_doc(Parser, Line, Col, Insert_At) ->
%% At the end of the document, we reset the version and the tags
%% table.
Parser1 = Parser#yamerl_parser{
doc_started = false,
doc_version = undefined
},
Parser2 = setup_default_tags(Parser1),
Token = #yamerl_doc_end{
line = Line,
column = Col
},
%% We check if there is an unfinished flow collection.
Parser3 = case ?IN_FLOW_CTX(Parser) of
false ->
Parser2;
true ->
Error = #yamerl_parsing_error{
name = unfinished_flow_collection,
token = Token,
line = Line,
column = Col
},
add_error(Parser2, Error, "Unfinished flow collection", [])
end,
queue_token(Parser3, Token, Insert_At).
%% -------------------------------------------------------------------
%% Directives.
%% -------------------------------------------------------------------
parse_directive([_ | Rest] = Chars, Line, Col, Delta, Parser) ->
Ctx = #directive_ctx{
line = Line,
col = Col
},
%% Reset cursor on column 0 to close all opened block collections.
Parser1 = check_for_closed_block_collections(Chars, Line, Col, Delta,
Parser, 0),
Parser2 = remove_impl_key_pos(Parser1),
Parser3 = ?ALLOW_IMPL_KEY(Parser2, false),
{Col1, Delta1} = ?NEXT_COL(Col, Delta, 1),
do_parse_directive(Rest, Line, Col1, Delta1, Parser3, Ctx).
do_parse_directive([C | _] = Chars, Line, Col, Delta,
#yamerl_parser{doc_version = Version} = Parser, Ctx)
when ?IS_NEWLINE(C) orelse ?IS_SPACE(C) orelse
(Version == {1,1} andalso ?IS_NEWLINE_11(C)) ->
parse_directive2(Chars, Line, Col, Delta, Parser, Ctx);