Debian Codegraph @

deps/ada-toml/src/toml-generic_parse.adb

raw
1 with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
2
3 with Interfaces;
4
5 function TOML.Generic_Parse
6 (Stream : in out Input_Stream) return TOML.Read_Result
7 is
8
9 ----------------------------
10 -- Lexical analysis state --
11 ----------------------------
12
13 WW_Backspace : constant Wide_Wide_Character :=
14 Wide_Wide_Character'Val (Character'Pos (ASCII.BS));
15 WW_Linefeed : constant Wide_Wide_Character :=
16 Wide_Wide_Character'Val (Character'Pos (ASCII.LF));
17 WW_Form_Feed : constant Wide_Wide_Character :=
18 Wide_Wide_Character'Val (Character'Pos (ASCII.FF));
19 WW_Carriage_Return : constant Wide_Wide_Character :=
20 Wide_Wide_Character'Val (Character'Pos (ASCII.CR));
21 WW_Tab : constant Wide_Wide_Character :=
22 Wide_Wide_Character'Val (Character'Pos (ASCII.HT));
23
24 subtype WW_Control_Characters is Wide_Wide_Character
25 with Static_Predicate => WW_Control_Characters in
26 Wide_Wide_Character'Val (16#00#)
27 .. Wide_Wide_Character'Val (16#1F#)
28 | Wide_Wide_Character'Val (16#7F#);
29
30 subtype WW_Non_ASCII is Wide_Wide_Character
31 range Wide_Wide_Character'Val (16#80#) .. Wide_Wide_Character'Last;
32
33 subtype WW_Surrogates is Wide_Wide_Character
34 range Wide_Wide_Character'Val (16#D800#)
35 .. Wide_Wide_Character'Val (16#DFFF#);
36
37 type Codepoint_Buffer_Type (EOF : Boolean := False) is record
38 To_Reemit : Boolean;
39 -- If true, the next call to Read_Codepoint should do nothing, except
40 -- resetting this to component to false.
41
42 Location : Source_Location;
43
44 case EOF is
45 when True => null;
46 when False =>
47 Codepoint : Wide_Wide_Character;
48 end case;
49 end record;
50 Codepoint_Buffer : Codepoint_Buffer_Type :=
51 (EOF => False,
52 To_Reemit => False,
53 Location => No_Location,
54 Codepoint => <>);
55 -- Buffer used to temporarily store information read from Stream
56
57 type Any_String_Format is
58 (Bare_Key,
59 Basic_String,
60 Multiline_Basic_String,
61 Literal_String,
62 Multiline_Literal_String);
63 subtype Valid_Key_Format is Any_String_Format with Static_Predicate =>
64 Valid_Key_Format in Bare_Key | Basic_String | Literal_String;
65
66 type Token_Kind is
67 (Newline, Equal, Dot, Comma,
68
69 Curly_Bracket_Open, Curly_Bracket_Close,
70 Square_Bracket_Open, Square_Bracket_Close,
71 Double_Square_Bracket_Open, Double_Square_Bracket_Close,
72
73 Boolean_Literal, Integer_Literal, Float_Literal, String_Literal,
74 Offset_Datetime_Literal, Local_Datetime_Literal,
75 Local_Date_Literal, Local_Time_Literal);
76
77 subtype No_Text_Token is Token_Kind range
78 Newline .. Double_Square_Bracket_Close;
79 -- Tokens whose text does not matter: the kind itself holds enough
80 -- information to describe the token.
81
82 type Any_Token (Kind : Token_Kind := Token_Kind'First) is record
83 case Kind is
84 when No_Text_Token => null;
85 when Boolean_Literal => Boolean_Value : Boolean;
86 when Integer_Literal => Integer_Value : Any_Integer;
87 when Float_Literal => Float_Value : Any_Float;
88 when String_Literal =>
89 String_Value : Unbounded_UTF8_String;
90 String_Format : Any_String_Format;
91 when Offset_Datetime_Literal =>
92 Offset_Datetime_Value : Any_Offset_Datetime;
93 when Local_Datetime_Literal =>
94 Local_Datetime_Value : Any_Local_Datetime;
95 when Local_Date_Literal => Local_Date_Value : Any_Local_Date;
96 when Local_Time_Literal => Local_Time_Value : Any_Local_Time;
97 end case;
98 end record;
99
100 True_Keyword : constant Any_Token :=
101 (Kind => Boolean_Literal, Boolean_Value => True);
102 False_Keyword : constant Any_Token :=
103 (Kind => Boolean_Literal, Boolean_Value => False);
104
105 type Token_Buffer_Type (EOF : Boolean := False) is record
106 To_Reemit : Boolean;
107 -- If true, the next call to Read_Token should do nothing, except
108 -- resetting this to component to false.
109
110 case EOF is
111 when True => null;
112 when False =>
113 Token : Any_Token;
114 Location : Source_Location;
115 end case;
116 end record;
117 Token_Buffer : Token_Buffer_Type :=
118 (EOF => False, To_Reemit => False, Location => No_Location, Token => <>);
119
120 ------------------------------
121 -- Syntactic analysis state --
122 ------------------------------
123
124 Root_Table : constant TOML_Value := Create_Table;
125 Result : Read_Result := (Success => True, Value => Root_Table);
126
127 Current_Table : TOML_Value := Root_Table;
128 -- Table that the next key/value pair node will update
129
130 function Create_Error
131 (Message : String;
132 Location : Source_Location := No_Location) return Boolean
133 with Post => not Create_Error'Result;
134 -- Put in Result an unsuccessful Read_Result value with the provided error
135 -- information. If no source location is passed, use
136 -- Codepoint_Buffer.Location.
137 --
138 -- This is a function that always return False for convenience in parsing
139 -- helpers, which are all functions that return False on error.
140
141 function Create_Lexing_Error
142 (Message : String := "invalid token") return Boolean
143 with Post => not Create_Lexing_Error'Result;
144 -- Like Create_Error, but use Token_Buffer.Location as the source location
145 -- for the error.
146
147 function Create_Syntax_Error
148 (Message : String := "invalid syntax") return Boolean
149 with Post => not Create_Syntax_Error'Result;
150 -- Like Create_Error, but use Token_Buffer.Location as the source location
151 -- for the error.
152
153 -----------------------
154 -- Codepoint reading --
155 -----------------------
156
157 function Read_Codepoint return Boolean
158 with Pre => not Codepoint_Buffer.EOF or else Codepoint_Buffer.To_Reemit;
159 -- Read a UTF-8 codepoint from Stream. If EOF is reached or a codepoint
160 -- could be read, return True and update Codepoint_Buffer accordingly
161 -- (location included). Otherwise, return False and put an error in Result.
162 --
163 -- Note that this automatically discards carriage returns codepoints when
164 -- they are immediately followed by a linefeed. When they are not followed
165 -- by a linefeed, this creates an error.
166
167 procedure Reemit_Codepoint
168 with Pre => not Codepoint_Buffer.To_Reemit;
169 -- Re-emit the same codepoint the next time that Read_Codepoint is called
170
171 --------------------
172 -- Token decoding --
173 --------------------
174
175 function Read_Token (Key_Expected : Boolean) return Boolean
176 with Pre => not Token_Buffer.EOF or else Token_Buffer.To_Reemit;
177 -- Read a token from Stream. If EOF is reached or a token could be read,
178 -- return True and update Token_Buffer accordingly (location included).
179 -- Otherwise, return False and put an error in Result.
180 --
181 -- If Key_Expected is true:
182 --
183 -- * parse tokens that could be integer literals as string literals;
184 -- * parse "[["/"]]" as double square bracket tokens instead of two
185 -- consecutive square bracket tokens.
186
187 procedure Reemit_Token
188 with Pre => not Token_Buffer.To_Reemit;
189 -- Re-emit the same token the next time that Read_Token is called
190
191 procedure Append_As_UTF8 (Codepoint : Wide_Wide_Character)
192 with Pre => not Token_Buffer.EOF
193 and then Token_Buffer.Token.Kind = String_Literal;
194 -- Append the given codepoint to Token_Buffer.Token.String_Value (a UTF-8
195 -- encoded string).
196
197 function Digit_Value
198 (Codepoint : Wide_Wide_Character) return Interfaces.Unsigned_64
199 with Pre => Codepoint in '0' .. '9' | 'a' .. 'f' | 'A' .. 'F';
200 -- Assuming that Codepoint is a valid hexadecimal digit, return the
201 -- corresponding number value.
202
203 function Read_Unicode_Escape_Sequence
204 (Location : Source_Location) return Boolean;
205 -- Helper for Read_Quoted_String. Assuming that string parsing just read a
206 -- "\u" or "\U" prefix, parse the rest of the Unicode escape sequence and
207 -- append the denoted codepoint using Append_As_UTF8. If successful, return
208 -- True, otherwise put an error in Result and return False.
209
210 function Read_Quoted_String return Boolean;
211 -- Helper for Read_Token. Read a string literal, whose first quote is in
212 -- Codepoint_Buffer. Return whether successful, updating Token_Buffer
213 -- accordingly.
214
215 function Read_Number_Like return Boolean;
216 -- Helper for Read_Token. Read an integer literal or a local date, whose
217 -- first digit (or sign) is in Codepoint_Buffer. Return whether successful,
218 -- updating Token_Buffer accordingly.
219
220 function Read_Datetime_Field
221 (What : String;
222 Digit_Count : Positive;
223 Base_Value : Interfaces.Unsigned_64;
224 Base_Digits : Natural;
225 Value : out Interfaces.Unsigned_64) return Boolean;
226 -- Helper to read dates and times. Read a specific date/time field: What is
227 -- the name of the field to read. Considering that we already read
228 -- Base_Digits number of digits and that the decoded value so far is
229 -- Base_Value, continue consuming digits until we have a total of
230 -- Digit_Count digits. Put the decoded value in Value and return True if
231 -- successful. Create a lexing error and return False otherwise.
232
233 function Read_Date
234 (Base_Value : Interfaces.Unsigned_64; Base_Digits : Natural)
235 return Boolean;
236 -- Helper for Read_Number_Like. Read a local date, local datetime or an
237 -- offset datetime, considering that we already consumed Base_Digits
238 -- digits, whose value is Base_Value. Return whether successful, updating
239 -- Token_Buffer accordingly.
240
241 function Read_Local_Time
242 (Base_Value : Interfaces.Unsigned_64;
243 Base_Digits : Natural;
244 Read_Timezone : Boolean) return Boolean;
245 -- Helper for Read_Number_Like and Read_Date. Read a local time,
246 -- considering that we already consumed Base_Digits digits, whose value
247 -- is Base_Value. Return whether successful, updating Token_Buffer
248 -- accordingly (Local_Time_Literal).
249 --
250 -- If Read_Timezone is true, attempt to read the timezone information. In
251 -- this mode, assume that Token_Buffer already contains a date
252 -- (Local_Date_Literal) and update it to contain either an
253 -- Offset_Datetime_Literal variant (if there is a timezone) or a
254 -- Local_Datetime_Literal variant.
255
256 function Read_Float
257 (Positive : Boolean;
258 Integer_Value : Interfaces.Unsigned_64) return Boolean;
259 -- Helper for Read_Number_Like. Read a floating point number considering
260 -- that we already consumed its sign (Positive) and its integer part
261 -- (Integer_Part): the codepoint buffer must contain one of '.' | 'e' |
262 -- 'E'. Return whether successful, updating Token_Buffer accordingly.
263
264 function Read_Special_Float
265 (Name : Wide_Wide_String;
266 Kind : Special_Float_Kind;
267 Positive : Boolean) return Boolean;
268 -- Helper for Read_Number_Like. Read the name of a special floating point
269 -- number. Return whether successful, updating Token_Buffer accordingly.
270
271 function Read_Bare_Key return Boolean;
272 -- Helper for Read_Token. Read a bare key, whose first character is in
273 -- Codepoint_Buffer. Return whether successful, updating Token_Buffer
274 -- accordingly.
275
276 function Read_Keyword
277 (Text : Wide_Wide_String; Token : Any_Token) return Boolean;
278 -- Helper for Read_Token. Try to read the given Text, whose first character
279 -- is in Codepoint_Buffer. Return whether successful, updating Token_Buffer
280 -- accordingly.
281
282 --------------------
283 -- Syntax parsing --
284 --------------------
285
286 function Parse_Line return Boolean;
287 -- Read and parse the next line in Stream. Update Result accordingly.
288
289 ------------------------
290 -- Table construction --
291 ------------------------
292
293 function Get_Table
294 (Key : Unbounded_UTF8_String;
295 Table : in out TOML_Value;
296 Traverse_Arrays : Boolean := False) return Boolean;
297 -- Look for a sub-table in Table correspondig to Key. On success, store it
298 -- in Table and return True. Otherwise, return False and put an error in
299 -- Result.
300 --
301 -- If there is no Key entry in Table, create one and register it.
302 --
303 -- If this entry is an array, then assuming all the following hold:
304 --
305 -- * Traverse_Arrays is true;
306 -- * Table contains a Key entry that is an array of tables;
307 -- * this array contains at least one element.
308 --
309 -- then this gets the last table that was added to this array. Otherwise,
310 -- this fails.
311
312 function Parse_Section (Array_Of_Table : Boolean) return Boolean;
313 -- Parse the name of a section ([my.table]) and update Current_Table
314 -- accordingly. This assumes that the opening bracket is already in
315 -- Token_Buffer. When this returns, the Newline token (or EOF) is in
316 -- Token_Buffer.
317 --
318 -- If Array_Of_Table is false, expect the section name to designate a
319 -- table. Otherwise, expect it to designate an array of tables.
320 --
321 -- Return whether parsing and interpretation was successful.
322
323 function Parse_Dotted_Keys
324 (Table : in out TOML_Value;
325 Key : out Unbounded_UTF8_String;
326 Traverse_Arrays : Boolean := False) return Boolean;
327 -- Parse a sequence of dotted keys and interpret it as a reference into
328 -- Table. Put the last key in Key, and update Table to the referenced table
329 -- (i.e. the one in which Key will reference/create an entry).
330 --
331 -- This assumes that the first token that constitutes the dotted keys is in
332 -- Token_Buffer. When this returns, the token just passed the dotted keys
333 -- will be in Token_Buffer.
334 --
335 -- Return whether parsing and interpretation was successful.
336
337 function Parse_Value (Value : out TOML_Value) return Boolean;
338 -- Parse an inline value (boolean/integer literal, inline table, inline
339 -- array, ...) and put it in Value.
340 --
341 -- The first token that constitutes the value is expected to be read during
342 -- the call. When this returns, Token_Buffer contains the last token that
343 -- was used to parse the value.
344
345 function Parse_Array (Value : out TOML_Value) return Boolean;
346 -- Parse an inline array and put it in Value.
347 --
348 -- This assumes that the first token that constitutes the array (i.e. '[')
349 -- is in Token_Buffer. When this returns, Token_Buffer contains the last
350 -- token that was used to parse the value (i.e. ']').
351
352 function Parse_Table (Value : out TOML_Value) return Boolean;
353 -- Parse an inline table and put it in Value.
354 --
355 -- This assumes that the first token that constitutes the table (i.e. '{')
356 -- is in Token_Buffer. When this returns, Token_Buffer contains the last
357 -- token that was used to parse the value (i.e. '}').
358
359 ------------------
360 -- Create_Error --
361 ------------------
362
363 function Create_Error
364 (Message : String;
365 Location : Source_Location := No_Location) return Boolean is
366 begin
367 Result :=
368 (Success => False,
369 Message => To_Unbounded_String (Message),
370 Location => (if Location = No_Location
371 then Codepoint_Buffer.Location
372 else Location));
373 return False;
374 end Create_Error;
375
376 -------------------------
377 -- Create_Lexing_Error --
378 -------------------------
379
380 function Create_Lexing_Error
381 (Message : String := "invalid token") return Boolean is
382 begin
383 return Create_Error (Message, Token_Buffer.Location);
384 end Create_Lexing_Error;
385
386 -------------------------
387 -- Create_Syntax_Error --
388 -------------------------
389
390 function Create_Syntax_Error
391 (Message : String := "invalid syntax") return Boolean is
392 begin
393 return Create_Error (Message, Token_Buffer.Location);
394 end Create_Syntax_Error;
395
396 --------------------
397 -- Read_Codepoint --
398 --------------------
399
400 function Read_Codepoint return Boolean is
401 use type Interfaces.Unsigned_32;
402
403 Error_Message : constant String := "invalid UTF-8 encoding";
404
405 EOF : Boolean;
406 Char : Character;
407 -- Holders for Get OUT formals
408
409 Bytes_Count : Positive;
410 -- Number of bytes that encode the codepoint to read
411
412 Min_Codepoint : constant array (1 .. 4) of Interfaces.Unsigned_32 :=
413 (1 => 16#00#,
414 2 => 16#80#,
415 3 => 16#80_00#,
416 4 => 16#1_00_00#);
417 -- For each Bytes_Count, smallest codepoint that is allowed
418
419 Byte : Interfaces.Unsigned_32;
420 -- Numeric view for Char
421
422 Result : Interfaces.Unsigned_32 := 0;
423 -- Numeric view for the Result
424
425 begin
426 -- If we are supposed to re-emit the previously read codepoint, do
427 -- nothing more.
428
429 if Codepoint_Buffer.To_Reemit then
430 Codepoint_Buffer.To_Reemit := False;
431 return True;
432 end if;
433
434 -- Try to read the first byte
435
436 Get (Stream, EOF, Char);
437 if EOF then
438 Codepoint_Buffer :=
439 (EOF => True,
440 To_Reemit => False,
441 Location => (Codepoint_Buffer.Location.Line,
442 Codepoint_Buffer.Location.Column + 1));
443 return True;
444 else
445 Byte := Character'Pos (Char);
446 end if;
447
448 -- ASCII characters are always one byte long, so we can handle them
449 -- right now: process ASCII's control characters.
450
451 case Char is
452
453 when ASCII.NUL .. ASCII.BS
454 | ASCII.VT
455 | ASCII.FF
456 | ASCII.SO .. ASCII.US
457 | ASCII.DEL =>
458
459 return Create_Error ("invalid ASCII control character");
460
461 when ASCII.CR =>
462
463 -- If this is a carriage return, discarding after checking that it is
464 -- followed by a linefeed.
465
466 Get (Stream, EOF, Char);
467 if EOF or else Char /= ASCII.LF then
468 return Create_Error ("invalid stray carriage return");
469 end if;
470
471 Byte := Character'Pos (Char);
472
473 when others =>
474 null;
475 end case;
476
477 -- Special handling of source location update occurs only with pure
478 -- ASCII characters, so we can handle it here, too.
479
480 if Codepoint_Buffer.Location = No_Location then
481 Codepoint_Buffer.Location := (1, 1);
482 else
483 case Char is
484 when ASCII.LF =>
485 Codepoint_Buffer.Location :=
486 (Codepoint_Buffer.Location.Line + 1, 1);
487 when ASCII.HT =>
488 declare
489 Column : Natural := Codepoint_Buffer.Location.Column;
490 Column_Mod : constant Natural := Column mod Tab_Stop;
491 begin
492 if Column_Mod = 0 then
493 Column := Column + Tab_Stop;
494 else
495 Column := Column + Tab_Stop - Column_Mod;
496 end if;
497 Codepoint_Buffer.Location.Column := Column;
498 end;
499
500 when others =>
501 Codepoint_Buffer.Location.Column :=
502 Codepoint_Buffer.Location.Column + 1;
503 end case;
504 end if;
505
506 -- Its leading bits tell us how many bytes are to be expected
507
508 if (Byte and 2#1000_0000#) = 0 then
509 Bytes_Count := 1;
510 Result := Byte and 2#0111_1111#;
511
512 elsif (Byte and 2#1110_0000#) = 2#1100_0000# then
513 Bytes_Count := 2;
514 Result := Byte and 2#0001_1111#;
515
516 elsif (Byte and 2#1111_0000#) = 2#1110_0000# then
517 Bytes_Count := 3;
518 Result := Byte and 2#0000_1111#;
519
520 elsif (Byte and 2#1111_1000#) = 2#1111_0000# then
521 Bytes_Count := 4;
522 Result := Byte and 2#0000_0111#;
523
524 else
525 return Create_Error (Error_Message);
526 end if;
527
528 -- Read the remaining bytes. We know how many we must read, so if we
529 -- reach EOF in the process, we know it's an error.
530
531 for I in 2 .. Bytes_Count loop
532 Get (Stream, EOF, Char);
533 Byte := Character'Pos (Char);
534
535 if EOF or else (Byte and 2#1100_0000#) /= 2#1000_0000# then
536 return Create_Error (Error_Message);
537 end if;
538
539 Result := 64 * Result + (Byte and 2#0011_1111#);
540 end loop;
541
542 -- Check that the codepoint is as big as the number of bytes allows
543
544 if Result < Min_Codepoint (Bytes_Count) then
545 return Create_Error (Error_Message);
546 end if;
547
548 Codepoint_Buffer.Codepoint := Wide_Wide_Character'Val (Result);
549
550 -- Reject surrogate codepoints
551
552 if Codepoint_Buffer.Codepoint in WW_Surrogates then
553 return Create_Error ("surrogate codepoints are invalid");
554 end if;
555
556 return True;
557 end Read_Codepoint;
558
559 ----------------------
560 -- Reemit_Codepoint --
561 ----------------------
562
563 procedure Reemit_Codepoint is
564 begin
565 Codepoint_Buffer.To_Reemit := True;
566 end Reemit_Codepoint;
567
568 ----------------
569 -- Read_Token --
570 ----------------
571
572 function Read_Token (Key_Expected : Boolean) return Boolean is
573 begin
574 -- If we are supposed to re-emit the previously read token, do nothing
575 -- more.
576
577 if Token_Buffer.To_Reemit then
578 Token_Buffer.To_Reemit := False;
579 return True;
580 end if;
581
582 loop
583 -- The location for this token is the location of the codepoint
584 -- cursor before reading it. Special case for the first token:
585 -- codepoint location is not initialized yet, so use the actual first
586 -- location.
587
588 Token_Buffer.Location := Codepoint_Buffer.Location;
589 if Token_Buffer.Location = No_Location then
590 Token_Buffer.Location := (1, 1);
591 end if;
592
593 -- Try to read the first codepoint. If we reached the end of file,
594 -- communicate this fact to the caller and stop there.
595
596 if not Read_Codepoint then
597 return False;
598 end if;
599
600 if Codepoint_Buffer.EOF then
601 Token_Buffer := (EOF => True, To_Reemit => False);
602 return True;
603 end if;
604
605 -- Otherwise, see what we can do with this codepoint
606
607 case Codepoint_Buffer.Codepoint is
608
609 -- If this is a newline (either LF or CR-LF), return the
610 -- corresponding token.
611
612 when WW_Linefeed =>
613 Token_Buffer.Location := Codepoint_Buffer.Location;
614 Token_Buffer.Token := (Kind => Newline);
615 return True;
616
617 when WW_Carriage_Return =>
618 if not Read_Codepoint then
619 return False;
620 elsif Codepoint_Buffer.EOF then
621 return Create_Lexing_Error ("trailing CR");
622 elsif Codepoint_Buffer.Codepoint /= WW_Linefeed then
623 return Create_Lexing_Error ("stray CR");
624 end if;
625 Token_Buffer.Token := (Kind => Newline);
626 return True;
627
628 -- Skip whitespaces
629
630 when WW_Tab | ' ' =>
631 null;
632
633 -- Skip comments. Note that the end of file is allowed to occur in
634 -- a comment, i.e. without a newline at the end.
635
636 when '#' =>
637 Comment_Loop : loop
638 if not Read_Codepoint then
639 return False;
640 elsif Codepoint_Buffer.EOF then
641 Token_Buffer := (EOF => True, To_Reemit => False);
642 return True;
643 elsif Codepoint_Buffer.Codepoint = WW_Linefeed then
644 -- Don't forget to re-emit the linefeed: it is not part
645 -- of the comment itself
646
647 Reemit_Codepoint;
648 exit Comment_Loop;
649 end if;
650 end loop Comment_Loop;
651
652 -- Parse no-text tokens that cannot be keys
653
654 when '=' =>
655 Token_Buffer.Token := (Kind => Equal);
656 return True;
657
658 when '.' =>
659 Token_Buffer.Token := (Kind => Dot);
660 return True;
661
662 when ',' =>
663 Token_Buffer.Token := (Kind => Comma);
664 return True;
665
666 when '{' =>
667 Token_Buffer.Token := (Kind => Curly_Bracket_Open);
668 return True;
669
670 when '}' =>
671 Token_Buffer.Token := (Kind => Curly_Bracket_Close);
672 return True;
673
674 when '[' =>
675 if not Read_Codepoint then
676 return False;
677 elsif Key_Expected
678 and then not Codepoint_Buffer.EOF
679 and then Codepoint_Buffer.Codepoint = '['
680 then
681 Token_Buffer.Token := (Kind => Double_Square_Bracket_Open);
682 else
683 Reemit_Codepoint;
684 Token_Buffer.Token := (Kind => Square_Bracket_Open);
685 end if;
686 return True;
687
688 when ']' =>
689 if not Read_Codepoint then
690 return False;
691 elsif Key_Expected
692 and then not Codepoint_Buffer.EOF
693 and then Codepoint_Buffer.Codepoint = ']'
694 then
695 Token_Buffer.Token := (Kind => Double_Square_Bracket_Close);
696 else
697 Reemit_Codepoint;
698 Token_Buffer.Token := (Kind => Square_Bracket_Close);
699 end if;
700 return True;
701
702 -- Parse string literals
703
704 when '"' | ''' =>
705 return Read_Quoted_String;
706
707 -- The rest is potential bare keys (bare keys, integer literals,
708 -- boolean literals, ...).
709
710 when '0' .. '9' =>
711 if Key_Expected then
712 return Read_Bare_Key;
713 else
714 return Read_Number_Like;
715 end if;
716
717 when 'A' .. 'Z' | 'a' .. 'z' | '_' =>
718 if Key_Expected then
719 return Read_Bare_Key;
720 end if;
721
722 -- Detect keywords: "false" or "true". TODO: handle "inf" and
723 -- "nan".
724
725 case Codepoint_Buffer.Codepoint is
726 when 'f' =>
727 return Read_Keyword ("false", False_Keyword);
728 when 't' =>
729 return Read_Keyword ("true", True_Keyword);
730 when 'n' =>
731 return Read_Special_Float ("nan", NaN, True);
732 when 'i' =>
733 return Read_Special_Float ("inf", Infinity, True);
734 when others =>
735 return Create_Lexing_Error;
736 end case;
737
738 when '+' =>
739 return Read_Number_Like;
740
741 when '-' =>
742 if Key_Expected then
743 return Read_Bare_Key;
744 else
745 return Read_Number_Like;
746 end if;
747
748 when others =>
749 return Create_Lexing_Error;
750 end case;
751 end loop;
752 end Read_Token;
753
754 ------------------
755 -- Reemit_Token --
756 ------------------
757
758 procedure Reemit_Token is
759 begin
760 Token_Buffer.To_Reemit := True;
761 end Reemit_Token;
762
763 --------------------
764 -- Append_As_UTF8 --
765 --------------------
766
767 procedure Append_As_UTF8 (Codepoint : Wide_Wide_Character) is
768 use Interfaces;
769
770 Ordinal : constant Unsigned_32 := Wide_Wide_Character'Pos (Codepoint);
771
772 function Bit_Slice (LSB, Width : Natural) return Unsigned_8;
773 -- Return the slice of bits in Codepoint/Ordinal starting at the given
774 -- 0-based index Least Significant Bit (LSB) and that contains Width
775 -- bits.
776
777 function Bit_Slice (LSB, Width : Natural) return Unsigned_8 is
778 Shifted : constant Unsigned_32 := Shift_Right (Ordinal, LSB);
779 Mask : constant Unsigned_32 := 2 ** Width - 1;
780 begin
781 return Unsigned_8 (Shifted and Mask);
782 end Bit_Slice;
783
784 Bytes : array (1 .. 4) of Unsigned_8;
785 Last_Byte : Positive;
786 begin
787 case Ordinal is
788 when 16#0000# .. 16#007F# =>
789 Bytes (1) := Bit_Slice (0, 7);
790 Last_Byte := 1;
791 when 16#0080# .. 16#07FF# =>
792 Bytes (1) := 2#1100_0000# or Bit_Slice (6, 5);
793 Bytes (2) := 2#1000_0000# or Bit_Slice (0, 6);
794 Last_Byte := 2;
795 when 16#0800# .. 16#FFFF# =>
796 Bytes (1) := 2#1110_0000# or Bit_Slice (12, 4);
797 Bytes (2) := 2#1000_0000# or Bit_Slice (6, 6);
798 Bytes (3) := 2#1000_0000# or Bit_Slice (0, 6);
799 Last_Byte := 3;
800 when 16#1_0000# .. 16#10_FFFF# =>
801 Bytes (1) := 2#1111_0000# or Bit_Slice (18, 3);
802 Bytes (2) := 2#1000_0000# or Bit_Slice (12, 6);
803 Bytes (3) := 2#1000_0000# or Bit_Slice (6, 6);
804 Bytes (4) := 2#1000_0000# or Bit_Slice (0, 6);
805 Last_Byte := 4;
806 when 16#11_0000# .. Unsigned_32'Last =>
807 -- Given that Codepoint comes from decoded UTF-8, this alternative
808 -- should be unreachable.
809 raise Program_Error;
810 end case;
811
812 declare
813 Str : String (1 .. Last_Byte) with Import, Address => Bytes'Address;
814 begin
815 Append (Token_Buffer.Token.String_Value, Str);
816 end;
817 end Append_As_UTF8;
818
819 -----------------
820 -- Digit_Value --
821 -----------------
822
823 function Digit_Value
824 (Codepoint : Wide_Wide_Character) return Interfaces.Unsigned_64
825 is
826 use Interfaces;
827 CP : constant Unsigned_64 :=
828 Wide_Wide_Character'Pos (Codepoint_Buffer.Codepoint);
829 begin
830 case Codepoint is
831 when '0' .. '9' =>
832 return CP - Wide_Wide_Character'Pos ('0');
833 when 'a' .. 'f' =>
834 return CP - Wide_Wide_Character'Pos ('a') + 10;
835 when 'A' .. 'F' =>
836 return CP - Wide_Wide_Character'Pos ('A') + 10;
837 when others =>
838 raise Program_Error;
839 end case;
840 end Digit_Value;
841
842 ----------------------------------
843 -- Read_Unicode_Escape_Sequence --
844 ----------------------------------
845
846 function Read_Unicode_Escape_Sequence
847 (Location : Source_Location) return Boolean
848 is
849 use Interfaces;
850
851 Size : constant Positive :=
852 (if Codepoint_Buffer.Codepoint = 'u' then 4 else 8);
853 -- Number of digits to read
854
855 CP : Unsigned_32;
856 -- Temporary buffer for the codepoint we just read
857
858 Result : Unsigned_32 := 0;
859 -- Denoted Unicode codepoint
860 begin
861 for I in 1 .. Size loop
862 if not Read_Codepoint then
863 return False;
864 elsif Codepoint_Buffer.EOF then
865 return Create_Error
866 ("unterminated Unicode escape sequence", Location);
867 end if;
868
869 -- Turn the hexadecimal digit we just read into a number and add it
870 -- to Result, or raise an error if this is not a valid digit.
871
872 CP := Wide_Wide_Character'Pos (Codepoint_Buffer.Codepoint);
873 declare
874 Denoted_Digit : Unsigned_32;
875 begin
876 if Codepoint_Buffer.Codepoint in '0' .. '9' then
877 Denoted_Digit := CP - Wide_Wide_Character'Pos ('0');
878 elsif Codepoint_Buffer.Codepoint in 'a' .. 'f' then
879 Denoted_Digit := CP - Wide_Wide_Character'Pos ('a') + 10;
880 elsif Codepoint_Buffer.Codepoint in 'A' .. 'F' then
881 Denoted_Digit := CP - Wide_Wide_Character'Pos ('A') + 10;
882 else
883 return Create_Error
884 ("invalid Unicode escape sequence", Location);
885 end if;
886 Result := 16 * Result + Denoted_Digit;
887 end;
888 end loop;
889
890 declare
891 Codepoint : constant Wide_Wide_Character :=
892 Wide_Wide_Character'Val (Result);
893 begin
894 -- Reject surrogate codepoints
895
896 if Codepoint in WW_Surrogates then
897 return Create_Error ("surrogate codepoints are invalid", Location);
898 end if;
899
900 Append_As_UTF8 (Codepoint);
901 return True;
902 end;
903 end Read_Unicode_Escape_Sequence;
904
905 ------------------------
906 -- Read_Quoted_String --
907 ------------------------
908
909 function Read_Quoted_String return Boolean is
910 Delimiter : constant Wide_Wide_Character :=
911 Codepoint_Buffer.Codepoint;
912
913 Is_Literal : constant Boolean := Delimiter = ''';
914 Is_Multiline : Boolean := False;
915
916 function Unterminated_String return Boolean is
917 (Create_Error ("unterminated string"));
918
919 function Skip_Line_Ending_Backslash return Boolean;
920 -- Assuming that, in a multiline string, we just processed a backslash
921 -- followed by a whitespace or a line feed (i.e. a line ending
922 -- backslash), skip all the following whitespaces/line feeds/backslashes
923 -- that should be ignored when processing the string. Return whether
924 -- successful (i.e. if there is no syntax error).
925
926 Location : Source_Location;
927
928 --------------------------------
929 -- Skip_Line_Ending_Backslash --
930 --------------------------------
931
932 function Skip_Line_Ending_Backslash return Boolean is
933 Line_Ended : Boolean := Codepoint_Buffer.Codepoint = WW_Linefeed;
934 -- Whether we processed a line feed after the last backslash. We keep
935 -- track of this to make sure that only whitespaces can follow line
936 -- ending backslashes.
937 begin
938 loop
939 if not Read_Codepoint then
940 return False;
941 elsif Codepoint_Buffer.EOF then
942 return Unterminated_String;
943 elsif Codepoint_Buffer.Codepoint not in ' ' | WW_Tab | WW_Linefeed
944 then
945 -- We found something that must not be
946 -- discarded: re-emit it so that the next
947 -- loop iteration processes it.
948
949 Reemit_Codepoint;
950 exit;
951
952 elsif Line_Ended and then Codepoint_Buffer.Codepoint = '\' then
953
954 -- On a separate line, we found a new line ending backslash:
955 -- skip it and only expect whitespaces before the next new
956 -- line.
957
958 Line_Ended := False;
959
960 else
961 Line_Ended :=
962 Line_Ended or else Codepoint_Buffer.Codepoint in WW_Linefeed;
963 end if;
964 end loop;
965
966 -- There must be a line feed before the first non-whitespace
967 -- codepoint that follows a line ending backslash.
968
969 return (Line_Ended
970 or else Create_Error ("invalid escape sequence", Location));
971 end Skip_Line_Ending_Backslash;
972 begin
973 -- Read the potential first character of this string.
974
975 if not Read_Codepoint then
976 return False;
977 elsif Codepoint_Buffer.EOF then
978 return Create_Error ("unterminated string");
979 end if;
980
981 Token_Buffer.Token :=
982 (Kind => String_Literal,
983 String_Format =>
984 (if Is_Literal then Literal_String else Basic_String),
985 others => <>);
986
987 -- If we have a second delimiter, then check if this is a multi-line
988 -- string.
989
990 if Codepoint_Buffer.Codepoint = Delimiter then
991
992 if not Read_Codepoint then
993 return False;
994
995 elsif Codepoint_Buffer.EOF
996 or else Codepoint_Buffer.Codepoint /= Delimiter
997 then
998 -- We found two delimiters not followed by a third one: this
999 -- designates an empty string.
1000
1001 Reemit_Codepoint;
1002 return True;
1003
1004 else
1005 -- We have three consecutive delimiters: this is a multiline
1006 -- string.
1007
1008 Is_Multiline := True;
1009 Token_Buffer.Token.String_Format :=
1010 (if Is_Literal
1011 then Multiline_Literal_String
1012 else Multiline_Basic_String);
1013 end if;
1014
1015 else
1016 -- Never mind: no second delimiter, so put this codepoint back to be
1017 -- read again in the scanning loop.
1018
1019 Reemit_Codepoint;
1020 end if;
1021
1022 -- Now, go through all codepoints until we find the closing
1023 -- delimiter(s).
1024
1025 loop
1026 if not Read_Codepoint then
1027 return False;
1028 elsif Codepoint_Buffer.EOF then
1029 return Create_Error ("unterminated string");
1030 end if;
1031
1032 Location := Codepoint_Buffer.Location;
1033 case Codepoint_Buffer.Codepoint is
1034 when '"' | ''' =>
1035 if Codepoint_Buffer.Codepoint /= Delimiter then
1036 -- If this character is not the string delimiter, include it
1037 -- as-is in the denoted string.
1038
1039 Append_As_UTF8 (Codepoint_Buffer.Codepoint);
1040
1041 elsif not Is_Multiline then
1042 -- Otherwise, if the string is not multi-line, it's the end
1043 -- of our string.
1044
1045 return True;
1046
1047 -- At this point, we know this string is multiline: look for
1048 -- the two next characters: if they are all delimiters, this
1049 -- is the end of our string. Otherwise, continue reading
1050 -- them...
1051
1052 elsif not Read_Codepoint then
1053 return False;
1054
1055 elsif Codepoint_Buffer.EOF then
1056 return Unterminated_String;
1057
1058 elsif Codepoint_Buffer.Codepoint /= Delimiter then
1059 -- The second delimiter is missing: append the first one
1060 -- and schedule to re-examine the current codepoint in
1061 -- another loop iteration.
1062
1063 Append_As_UTF8 (Delimiter);
1064 Reemit_Codepoint;
1065
1066 -- Read the third character...
1067
1068 elsif not Read_Codepoint then
1069 return False;
1070
1071 elsif Codepoint_Buffer.EOF then
1072 return Unterminated_String;
1073
1074 elsif Codepoint_Buffer.Codepoint /= Delimiter then
1075 -- The third delimiter is missing: append the first two ones
1076 -- and schedule to re-examine the current codepoint in
1077 -- another loop iteration.
1078
1079 Append_As_UTF8 (Delimiter);
1080 Append_As_UTF8 (Delimiter);
1081 Reemit_Codepoint;
1082
1083 -- We just got the third delimiter, but we can still have (a)
1084 -- one or (b) two more delimiters: in that case the first (a)
1085 -- one or (b) two are part of the string, and the last three
1086 -- are closing the string. So try reading a fourth delimiter...
1087
1088 elsif not Read_Codepoint then
1089 return False;
1090
1091 elsif Codepoint_Buffer.EOF
1092 or else Codepoint_Buffer.Codepoint /= Delimiter
1093 then
1094 -- No fourth delimiter: put back the EOF/codepoint and
1095 -- return a successful multiline string parsing.
1096
1097 Reemit_Codepoint;
1098 return True;
1099
1100 else
1101 -- We got a fourth delimiter: append one to the denoted
1102 -- string and try to read the fifth one...
1103
1104 Append_As_UTF8 (Delimiter);
1105
1106 if not Read_Codepoint then
1107 return False;
1108 elsif Codepoint_Buffer.EOF
1109 or else Codepoint_Buffer.Codepoint /= Delimiter
1110 then
1111 -- Just like above, if we could not get one, just put the
1112 -- codepoint back and return success.
1113
1114 Reemit_Codepoint;
1115
1116 else
1117 -- We got a fifth delimiter: append yet another delimiter
1118 -- (the second one) to the denoted string and consider
1119 -- the read done.
1120
1121 Append_As_UTF8 (Delimiter);
1122 end if;
1123 return True;
1124 end if;
1125
1126 when '\' =>
1127 -- If this is a literal string, we have a literal backslash.
1128
1129 if Is_Literal then
1130 Append_As_UTF8 (Codepoint_Buffer.Codepoint);
1131
1132 -- This starts an escape sequence: read the next character to
1133 -- find out which.
1134
1135 elsif not Read_Codepoint then
1136 return False;
1137 elsif Codepoint_Buffer.EOF then
1138 return Unterminated_String;
1139 else
1140 case Codepoint_Buffer.Codepoint is
1141 when 'b' => Append_As_UTF8 (WW_Backspace);
1142 when 't' => Append_As_UTF8 (WW_Tab);
1143 when 'n' => Append_As_UTF8 (WW_Linefeed);
1144 when 'f' => Append_As_UTF8 (WW_Form_Feed);
1145 when 'r' => Append_As_UTF8 (WW_Carriage_Return);
1146 when '"' => Append_As_UTF8 ('"');
1147 when '\' => Append_As_UTF8 ('\');
1148
1149 when 'u' | 'U' =>
1150 if not Read_Unicode_Escape_Sequence (Location) then
1151 return False;
1152 end if;
1153
1154 when ' ' | WW_Tab | WW_Linefeed =>
1155
1156 -- This is valid only for multi-line strings. If
1157 -- literal, just append these codepoints. Otherwise we
1158 -- we just found a "line ending backslash": discard
1159 -- all the whitespace characters we find next.
1160
1161 if not Is_Multiline then
1162 return Unterminated_String;
1163 elsif Is_Literal then
1164 Append_As_UTF8 (WW_Linefeed);
1165 elsif not Skip_Line_Ending_Backslash then
1166 return False;
1167 end if;
1168
1169 when others =>
1170 return Create_Error
1171 ("invalid escape sequence", Location);
1172 end case;
1173 end if;
1174
1175 when WW_Control_Characters =>
1176 -- Linefeeds are allowed only for multi-line strings.
1177
1178 if Codepoint_Buffer.Codepoint = WW_Linefeed
1179 and then Is_Multiline
1180 then
1181 -- When they are the first codepoint after the string
1182 -- delimiter, they are discarded.
1183
1184 if Length (Token_Buffer.Token.String_Value) > 0 then
1185 Append_As_UTF8 (WW_Linefeed);
1186 end if;
1187
1188 elsif Codepoint_Buffer.Codepoint = WW_Tab then
1189
1190 -- Horizontal tabs are always allowed
1191
1192 Append_As_UTF8 (WW_Tab);
1193
1194 else
1195 return Create_Error ("invalid string", Location);
1196 end if;
1197
1198 when others =>
1199 Append_As_UTF8 (Codepoint_Buffer.Codepoint);
1200 end case;
1201 end loop;
1202 end Read_Quoted_String;
1203
1204 ----------------------
1205 -- Read_Number_Like --
1206 ----------------------
1207
1208 function Read_Number_Like return Boolean is
1209 use Interfaces;
1210
1211 type Any_Format is (Decimal, Hexadecimal, Binary, Octal);
1212 Format : Any_Format := Decimal;
1213 -- Format for the integer to parse
1214
1215 Base : constant array (Any_Format) of Unsigned_64 :=
1216 (Decimal => 10, Hexadecimal => 16, Binary => 2, Octal => 8);
1217
1218 type Any_Sign is (None, Positive, Negative);
1219 Sign : Any_Sign := None;
1220 Sign_Explicit : Boolean := False;
1221 -- Sign for the integer to parse, and whether it was explicit
1222
1223 Abs_Value : Interfaces.Unsigned_64 := 0;
1224 -- Absolute value for the integer that is parsed
1225
1226 Digit_Count : Natural := 0;
1227 -- Number of digit codepoints consumed
1228
1229 Had_Underscore : Boolean := False;
1230 -- Whether we found an underscore at all for this token
1231
1232 Leading_Zero : Boolean := False;
1233 -- Whether this number starts with a zero
1234
1235 Just_Passed_Underscore : Boolean := False;
1236 -- Whether the last codepoint processed was an underscore
1237
1238 function Reject_Leading_Zero return Boolean;
1239 -- If Leading_Zero is true, create an error and return False. Return
1240 -- true otherwise.
1241
1242 function Reject_Passed_Underscore return Boolean;
1243 -- If Just_Passed_Underscore is true, create an error and return False.
1244 -- Return true otherwise.
1245
1246 -------------------------
1247 -- Reject_Leading_Zero --
1248 -------------------------
1249
1250 function Reject_Leading_Zero return Boolean is
1251 begin
1252 if Leading_Zero then
1253 return Create_Lexing_Error
1254 ("leading zeros are not allowed in decimals");
1255 end if;
1256 return True;
1257 end Reject_Leading_Zero;
1258
1259 ------------------------------
1260 -- Reject_Passed_Underscore --
1261 ------------------------------
1262
1263 function Reject_Passed_Underscore return Boolean is
1264 begin
1265 if Just_Passed_Underscore then
1266 return Create_Lexing_Error
1267 ("underscores must be surrounded by digits");
1268 end if;
1269 return True;
1270 end Reject_Passed_Underscore;
1271
1272 function Too_Large_Error return Boolean is
1273 (Create_Error ("too large integer", Token_Buffer.Location));
1274 begin
1275 Token_Buffer.Token := (Kind => Integer_Literal, Integer_Value => 0);
1276
1277 -- Decode the sign, if any
1278
1279 if Codepoint_Buffer.Codepoint in '+' | '-' then
1280 Sign := (if Codepoint_Buffer.Codepoint = '+'
1281 then Positive
1282 else Negative);
1283 Sign_Explicit := True;
1284 if not Read_Codepoint then
1285 return False;
1286 elsif Codepoint_Buffer.EOF then
1287 return Create_Lexing_Error;
1288 end if;
1289 end if;
1290
1291 -- If this token starts with 0, we have either:
1292 --
1293 -- * just 0, i.e. the next character cannot be a digit as leading zeros
1294 -- are forbidden.
1295 --
1296 -- * 'b' (for binary literals), 'x' (for hexadecimal) or 'o' (for
1297 -- octal).
1298
1299 if Codepoint_Buffer.Codepoint = '0' then
1300 if not Read_Codepoint then
1301 return False;
1302 elsif Codepoint_Buffer.EOF then
1303 Reemit_Codepoint;
1304 return True;
1305 end if;
1306
1307 case Codepoint_Buffer.Codepoint is
1308 when '_' | '0' .. '9' =>
1309 Digit_Count := Digit_Count + 1;
1310 Leading_Zero := True;
1311
1312 when 'b' =>
1313 Format := Binary;
1314 when 'o' =>
1315 Format := Octal;
1316 when 'x' =>
1317 Format := Hexadecimal;
1318
1319 when '.' | 'e' | 'E' =>
1320 return Read_Float (Sign /= Negative, Abs_Value);
1321
1322 when others =>
1323 -- Consider all other codepoints as token separators
1324
1325 Reemit_Codepoint;
1326 return True;
1327 end case;
1328
1329 -- Explicit signs are valid only for numbers in decimal form
1330
1331 if Format /= Decimal and then Sign_Explicit then
1332 return Create_Lexing_Error
1333 ("explicit sign not allowed but for decimals");
1334 end if;
1335
1336 -- If we had a format specifier sequence, read the next codepoint,
1337 -- which will be the first digit of the number to read.
1338
1339 if Format /= Decimal then
1340 if not Read_Codepoint then
1341 return False;
1342 elsif Codepoint_Buffer.EOF then
1343 Reemit_Codepoint;
1344 return True;
1345 elsif Codepoint_Buffer.Codepoint = '_' then
1346 return Create_Lexing_Error
1347 ("underscores must be surrounded by digits");
1348 end if;
1349 end if;
1350
1351 -- Check for special float values ("nan" and "inf")
1352
1353 elsif Codepoint_Buffer.Codepoint = 'n' then
1354 return Read_Special_Float ("nan", NaN, Sign /= Negative);
1355 elsif Codepoint_Buffer.Codepoint = 'i' then
1356 return Read_Special_Float ("inf", Infinity, Sign /= Negative);
1357 end if;
1358
1359 -- Now read and decode all digits for this token
1360
1361 loop
1362 declare
1363 Is_Digit : Boolean := False;
1364 Digit : Unsigned_64;
1365 begin
1366 -- See if we have a digit
1367
1368 case Codepoint_Buffer.Codepoint is
1369 when '0' .. '9' | 'a' .. 'f' | 'A' .. 'F' =>
1370 if Format = Decimal
1371 and then Codepoint_Buffer.Codepoint in 'e' | 'E'
1372 then
1373 return Reject_Leading_Zero and then
1374 Reject_Passed_Underscore and then
1375 Read_Float (Sign /= Negative, Abs_Value);
1376 end if;
1377
1378 Is_Digit := True;
1379 Digit := Digit_Value (Codepoint_Buffer.Codepoint);
1380
1381 when '_' =>
1382 Had_Underscore := True;
1383 if Just_Passed_Underscore then
1384 return Reject_Passed_Underscore;
1385 else
1386 Just_Passed_Underscore := True;
1387 end if;
1388
1389 when 'g' .. 'z' | 'G' .. 'Z' | WW_Non_ASCII =>
1390
1391 -- These codepoints cannot start a new token and yet they
1392 -- are invalid elements for integer literals: this is an
1393 -- error.
1394
1395 return Create_Lexing_Error;
1396
1397 when '-' | ':' =>
1398
1399 -- If we had no sign, no underscore and no base specifier,
1400 -- we have a local date ('-') or local time (':').
1401
1402 if Sign /= None
1403 or else Format /= Decimal
1404 or else Had_Underscore
1405 then
1406 Reemit_Codepoint;
1407 exit;
1408 end if;
1409
1410 if Codepoint_Buffer.Codepoint = '-' then
1411 return Read_Date (Abs_Value, Digit_Count);
1412 else
1413 return Read_Local_Time (Abs_Value, Digit_Count,
1414 Read_Timezone => False);
1415 end if;
1416
1417 when '.' =>
1418
1419 -- If we had no base specifier, we have a floating point
1420 -- number.
1421 --
1422 -- Floating point numbers can only use decimal digits, and
1423 -- there must be at least one digit before the dot.
1424
1425 if Format /= Decimal or Digit_Count = 0 then
1426 return Create_Lexing_Error ("invalid float");
1427 end if;
1428 return Reject_Leading_Zero and then
1429 Reject_Passed_Underscore and then
1430 Read_Float (Sign /= Negative, Abs_Value);
1431
1432 when others =>
1433 -- If we end up here, either we found the beginning of a new
1434 -- token, or a token separator: stop reading the integer
1435 -- right here.
1436
1437 Reemit_Codepoint;
1438 exit;
1439 end case;
1440
1441 -- Decode the digit (if we found one)
1442
1443 if Is_Digit then
1444 Digit_Count := Digit_Count + 1;
1445 if Digit >= Base (Format) then
1446 return Create_Lexing_Error;
1447 end if;
1448
1449 declare
1450 Next_Value : Unsigned_64;
1451 begin
1452 begin
1453 Next_Value := Base (Format) * Abs_Value + Digit;
1454 exception
1455 when Constraint_Error =>
1456 return Too_Large_Error;
1457 end;
1458 Abs_Value := Next_Value;
1459 end;
1460 Just_Passed_Underscore := False;
1461 end if;
1462
1463 -- Read the next digit. Consider this integer token done if we
1464 -- reached the end of stream.
1465
1466 if not Read_Codepoint then
1467 return False;
1468 elsif Codepoint_Buffer.EOF then
1469 Reemit_Codepoint;
1470 exit;
1471 end if;
1472 end;
1473 end loop;
1474
1475 -- If we reach this point, we know that the token is an integer (it's
1476 -- not a date or something else).
1477
1478 if not Reject_Leading_Zero or else not Reject_Passed_Underscore then
1479 return False;
1480 end if;
1481
1482 -- Apply the sign, making sure that there is no overflow in the process
1483
1484 declare
1485 Rel_Value : Integer_64;
1486 begin
1487 if Sign = Negative then
1488 if Abs_Value <= Unsigned_64 (Integer_64'Last) then
1489 Rel_Value := -Integer_64 (Abs_Value);
1490 elsif Abs_Value = Unsigned_64 (Integer_64'Last) + 1 then
1491 Rel_Value := Integer_64'First;
1492 else
1493 return Too_Large_Error;
1494 end if;
1495
1496 else
1497 if Abs_Value <= Unsigned_64 (Integer_64'Last) then
1498 Rel_Value := Integer_64 (Abs_Value);
1499 else
1500 return Too_Large_Error;
1501 end if;
1502 end if;
1503
1504 Token_Buffer.Token.Integer_Value := Any_Integer (Rel_Value);
1505 return True;
1506 end;
1507 end Read_Number_Like;
1508
1509 -------------------------
1510 -- Read_Datetime_Field --
1511 -------------------------
1512
1513 function Read_Datetime_Field
1514 (What : String;
1515 Digit_Count : Positive;
1516 Base_Value : Interfaces.Unsigned_64;
1517 Base_Digits : Natural;
1518 Value : out Interfaces.Unsigned_64) return Boolean
1519 is
1520 use Interfaces;
1521
1522 function Create_Error return Boolean is
1523 (Create_Lexing_Error ("invalid " & What));
1524 begin
1525 if Base_Digits > Digit_Count then
1526 return Create_Error;
1527 end if;
1528
1529 Value := Base_value;
1530
1531 for DC in Base_Digits + 1 .. Digit_Count loop
1532
1533 -- Decode the current digit and add it to the decoded value
1534
1535 if Codepoint_Buffer.Codepoint not in '0' .. '9' then
1536 return Create_Error;
1537 end if;
1538
1539 Value := 10 * Value + Digit_Value (Codepoint_Buffer.Codepoint);
1540
1541 -- Read the next digit. We accept EOF only if we were able to read
1542 -- as many digits as requested.
1543
1544 if not Read_Codepoint then
1545 return False;
1546 elsif Codepoint_Buffer.EOF then
1547 exit when DC = Digit_Count;
1548 return Create_Error;
1549 end if;
1550 end loop;
1551
1552 -- This check is not necessary for correctness. It improves user
1553 -- diagnostics: if a digit follows the last expected digit, we know
1554 -- there is an error.
1555
1556 if not Codepoint_Buffer.EOF
1557 and then Codepoint_Buffer.Codepoint in '0' .. '9'
1558 then
1559 return Create_Error;
1560 end if;
1561
1562 -- If we came across a codepoint, re-emit it so that the lexing loop
1563 -- can call Read_Token once more.
1564
1565 if Codepoint_Buffer.EOF then
1566 Reemit_Codepoint;
1567 end if;
1568
1569 return True;
1570 end Read_Datetime_Field;
1571
1572 ---------------
1573 -- Read_Date --
1574 ---------------
1575
1576 function Read_Date
1577 (Base_Value : Interfaces.Unsigned_64; Base_Digits : Natural)
1578 return Boolean
1579 is
1580 use Interfaces;
1581
1582 subtype Year_Range is Unsigned_64 range
1583 Unsigned_64 (Any_Year'First) .. Unsigned_64 (Any_Year'Last);
1584 subtype Month_Range is Unsigned_64 range
1585 Unsigned_64 (Any_Month'First) .. Unsigned_64 (Any_Month'Last);
1586 subtype Day_Range is Unsigned_64 range
1587 Unsigned_64 (Any_Day'First) .. Unsigned_64 (Any_Day'Last);
1588
1589 Year, Month, Day : Unsigned_64 := Base_Value;
1590 Datetime : Any_Local_Datetime;
1591 begin
1592 -- Finish reading the year and consume the following dash
1593
1594 if not Read_Datetime_Field ("year", 4, Base_Value, Base_Digits, Year)
1595 then
1596 return False;
1597 elsif Codepoint_Buffer.EOF or else Codepoint_Buffer.Codepoint /= '-' then
1598 return Create_Lexing_Error ("invalid year");
1599 end if;
1600
1601 -- Now read the month and consume the following dash
1602
1603 if not Read_Codepoint then
1604 return False;
1605 elsif Codepoint_Buffer.EOF then
1606 return Create_Lexing_Error ("invalid month");
1607 elsif not Read_Datetime_Field ("month", 2, 0, 0, Month) then
1608 return False;
1609 elsif Codepoint_Buffer.EOF or else Codepoint_Buffer.Codepoint /= '-' then
1610 return Create_Lexing_Error ("invalid month");
1611 end if;
1612
1613 -- Now read the day
1614
1615 if not Read_Codepoint then
1616 return False;
1617 elsif Codepoint_Buffer.EOF then
1618 return Create_Lexing_Error ("invalid day");
1619 elsif not Read_Datetime_Field ("day", 2, 0, 0, Day) then
1620 return False;
1621 end if;
1622
1623 -- Check that all fields are in range.
1624 --
1625 -- TODO: check that the date they represent is valid. This is not
1626 -- trivial as TOML can handle all years between 0 and 9999 while
1627 -- Ada.Calendar supports only 1901 through 2399.
1628
1629 if Year not in Year_Range then
1630 return Create_Lexing_Error ("out of range year");
1631 elsif Month not in Month_Range then
1632 return Create_Lexing_Error ("out of range month");
1633 elsif Day not in Day_Range then
1634 return Create_Lexing_Error ("out of range day");
1635 end if;
1636
1637 Datetime.Date := (Year => Any_Year (Year),
1638 Month => Any_Month (Month),
1639 Day => Any_Day (Day));
1640 Token_Buffer.Token := (Kind => Local_Date_Literal,
1641 Local_Date_Value => Datetime.Date);
1642
1643 -- Now try to read a local time: if there is one, we can create a local
1644 -- datetime, otherwise it's just a local date.
1645
1646 if not Codepoint_Buffer.EOF
1647 and then Codepoint_Buffer.Codepoint in 'T' | 't'
1648 then
1649 -- If the first codepoint after the date is 'T', then we know we have
1650 -- a local time ahead.
1651
1652 if not Read_Codepoint then
1653 return False;
1654 elsif Codepoint_Buffer.EOF then
1655 return Create_Lexing_Error ("truncated datetime");
1656 end if;
1657
1658 elsif not Codepoint_Buffer.EOF and then Codepoint_Buffer.Codepoint = ' '
1659 then
1660 -- If the first codepoint after the date is ' ', then we know we have
1661 -- a local time ahead iff a digit follows this space. Otherwise, just
1662 -- consider it's the beginning of another token.
1663
1664 if not Read_Codepoint then
1665 return False;
1666 elsif Codepoint_Buffer.EOF
1667 or else Codepoint_Buffer.Codepoint not in '0' .. '9'
1668 then
1669 Reemit_Codepoint;
1670 return True;
1671 end if;
1672
1673 else
1674 Reemit_Codepoint;
1675 return True;
1676 end if;
1677
1678 -- At this point, we know there is a local time ahead, so try to read it
1679
1680 return Read_Local_Time (0, 0, Read_Timezone => True);
1681 end Read_Date;
1682
1683 ---------------------
1684 -- Read_Local_Time --
1685 ---------------------
1686
1687 function Read_Local_Time
1688 (Base_Value : Interfaces.Unsigned_64;
1689 Base_Digits : Natural;
1690 Read_Timezone : Boolean) return Boolean
1691 is
1692 use Interfaces;
1693
1694 subtype Hour_Range is Unsigned_64 range
1695 Unsigned_64 (Any_Hour'First) .. Unsigned_64 (Any_Hour'Last);
1696 subtype Minute_Range is Unsigned_64 range
1697 Unsigned_64 (Any_Minute'First) .. Unsigned_64 (Any_Minute'Last);
1698 subtype Second_Range is Unsigned_64 range
1699 Unsigned_64 (Any_Second'First) .. Unsigned_64 (Any_Second'Last);
1700 subtype Millisecond_Range is Unsigned_64 range
1701 Unsigned_64 (Any_Millisecond'First)
1702 .. Unsigned_64 (Any_Millisecond'Last);
1703
1704 Hour, Minute, Second, Millisecond : Unsigned_64 := Base_Value;
1705
1706 Time : Any_Local_Time;
1707 begin
1708 -- Finish reading the hour and consume the following colon
1709
1710 if not Read_Datetime_Field ("hour", 2, Base_Value, Base_Digits, Hour)
1711 then
1712 return False;
1713 elsif Codepoint_Buffer.EOF or else Codepoint_Buffer.Codepoint /= ':' then
1714 return Create_Lexing_Error ("invalid hour");
1715 end if;
1716
1717 -- Now read the minute and consume the following colon
1718
1719 if not Read_Codepoint then
1720 return False;
1721 elsif Codepoint_Buffer.EOF then
1722 return Create_Lexing_Error ("invalid minute");
1723 elsif not Read_Datetime_Field ("minute", 2, 0, 0, Minute) then
1724 return False;
1725 elsif Codepoint_Buffer.EOF or else Codepoint_Buffer.Codepoint /= ':' then
1726 return Create_Lexing_Error ("invalid minute");
1727 end if;
1728
1729 -- Now read the second
1730
1731 if not Read_Codepoint then
1732 return False;
1733 elsif Codepoint_Buffer.EOF then
1734 return Create_Lexing_Error ("invalid second");
1735 elsif not Read_Datetime_Field ("second", 2, 0, 0, Second) then
1736 return False;
1737 end if;
1738
1739 -- If present, read a dot, and then read the millisecond
1740
1741 Millisecond := 0;
1742 if Codepoint_Buffer.EOF or else Codepoint_Buffer.Codepoint /= '.' then
1743 Reemit_Codepoint;
1744 elsif not Read_Codepoint then
1745 return False;
1746 elsif Codepoint_Buffer.EOF then
1747 return Create_Lexing_Error ("truncated millisecond");
1748 else
1749 -- Read at least 1 digit and at most 3 digits, then discard other
1750 -- digits.
1751
1752 declare
1753 Digit_Count : Natural := 0;
1754 begin
1755 while not Codepoint_Buffer.EOF
1756 and then Codepoint_Buffer.Codepoint in '0' .. '9'
1757 loop
1758 if Digit_Count < 3 then
1759 Digit_Count := Digit_Count + 1;
1760 Millisecond := (10 * Millisecond
1761 + Digit_Value (Codepoint_Buffer.Codepoint));
1762 end if;
1763
1764 if not Read_Codepoint then
1765 return False;
1766 end if;
1767 end loop;
1768
1769 -- Artificially append zeros so that what we really get is the
1770 -- number of milliseconds (".1" should give 100 milliseconds, not
1771 -- just 1).
1772
1773 while Digit_Count < 3 loop
1774 Digit_Count := Digit_Count + 1;
1775 Millisecond := 10 * Millisecond;
1776 end loop;
1777
1778 Reemit_Codepoint;
1779 end;
1780 end if;
1781
1782 -- Check that all fields are in range
1783
1784 if Hour not in Hour_Range then
1785 return Create_Lexing_Error ("out of range hour");
1786 elsif Minute not in Minute_Range then
1787 return Create_Lexing_Error ("out of range minute");
1788 elsif Second not in Second_Range then
1789 return Create_Lexing_Error ("out of range second");
1790 end if;
1791
1792 -- The millisecond is read with 3 digits, and that's exactly what the
1793 -- millisecond range allows so this should be always true.
1794
1795 pragma Assert (Millisecond in Millisecond_Range);
1796
1797 Time := (Hour => Any_Hour (Hour),
1798 Minute => Any_Minute (Minute),
1799 Second => Any_Second (Second),
1800 Millisecond => Any_Millisecond (Millisecond));
1801
1802 if not Read_Timezone then
1803 Token_Buffer.Token :=
1804 (Kind => Local_Time_Literal,
1805 Local_Time_Value => Time);
1806 return True;
1807 end if;
1808
1809 -- We were asked to read the timezone information: assume the token
1810 -- buffer contains a date and complete it with the time, and the
1811 -- timezone if present.
1812
1813 declare
1814 Datetime : constant Any_Local_Datetime :=
1815 (Date => Token_Buffer.Token.Local_Date_Value,
1816 Time => Time);
1817
1818 -- Temporaries to build the local offset value that is read
1819
1820 Positive_Offset : Boolean;
1821 -- Whether the offset is positive (starts with '+' or 'Z'). Note that
1822 -- RFC 3339 states that a negative offset with zero minutes means
1823 -- "unknown local offset".
1824
1825 Hour_Offset : Unsigned_64 := 0;
1826 Minute_Offset : Unsigned_64 := 0;
1827 -- Individual temporaries for the amount of ours and of minutes for
1828 -- the local offset.
1829 begin
1830 Token_Buffer.Token :=
1831 (Kind => Local_Datetime_Literal,
1832 Local_Datetime_Value => Datetime);
1833
1834 if not Read_Codepoint then
1835 return False;
1836 elsif Codepoint_Buffer.EOF
1837 or else Codepoint_Buffer.Codepoint not in 'Z' | 'z' | '+' | '-'
1838 then
1839 Reemit_Codepoint;
1840 return True;
1841 end if;
1842
1843 if Codepoint_Buffer.Codepoint in 'Z' | 'z' then
1844 Positive_Offset := True;
1845 else
1846 Positive_Offset := Codepoint_Buffer.Codepoint = '+';
1847
1848 -- Consume the hour offset and consume the colon
1849
1850 if not Read_Codepoint then
1851 return False;
1852 elsif Codepoint_Buffer.EOF then
1853 return Create_Lexing_Error ("truncated hour offset");
1854 elsif not Read_Datetime_Field ("hour offset", 2, 0, 0, Hour_Offset)
1855 then
1856 return False;
1857 elsif Codepoint_Buffer.EOF
1858 or else Codepoint_Buffer.Codepoint /= ':'
1859 then
1860 return Create_Lexing_Error ("invalid hour offset");
1861 end if;
1862
1863 -- Now consume the minute offset
1864
1865 if not Read_Codepoint then
1866 return False;
1867 elsif Codepoint_Buffer.EOF then
1868 return Create_Lexing_Error ("truncated minute offset");
1869 elsif not Read_Datetime_Field
1870 ("minute offset", 2, 0, 0, Minute_Offset)
1871 then
1872 return False;
1873 end if;
1874
1875 -- Reemit the last codepoint as Read_Datetime_Field consumes the
1876 -- one that appears right after the last codepoint that is part of
1877 -- the datetime field.
1878
1879 Reemit_Codepoint;
1880 end if;
1881
1882 -- Check ranges for hours/minutes
1883
1884 if Hour_Offset not in Hour_Range then
1885 return Create_Lexing_Error ("out of range hour offset");
1886 elsif Minute_Offset not in Minute_Range then
1887 return Create_Lexing_Error ("out of range minute offset");
1888 end if;
1889
1890 -- Gather all decoded data to format the result
1891
1892 declare
1893 Absolute_Offset : constant Any_Local_Offset := Any_Local_Offset
1894 (60 * Hour_Offset + Minute_Offset);
1895 Offset : constant Any_Local_Offset :=
1896 (if Positive_Offset
1897 then Absolute_Offset
1898 else -Absolute_Offset);
1899 Offset_Datetime : constant Any_Offset_Datetime :=
1900 (Datetime => Datetime,
1901 Offset => Offset,
1902 Unknown_Offset => Offset = 0 and then not Positive_Offset);
1903 begin
1904 Token_Buffer.Token :=
1905 (Kind => Offset_Datetime_Literal,
1906 Offset_Datetime_Value => Offset_Datetime);
1907 return True;
1908 end;
1909 end;
1910 end Read_Local_Time;
1911
1912 ----------------
1913 -- Read_Float --
1914 ----------------
1915
1916 function Read_Float
1917 (Positive : Boolean;
1918 Integer_Value : Interfaces.Unsigned_64) return Boolean
1919 is
1920 function Invalid_Float return Boolean is
1921 (Create_Lexing_Error ("invalid float"));
1922 function Too_Large return Boolean is
1923 (Create_Lexing_Error ("too large float"));
1924
1925 function Read_Simple_Integer
1926 (Value : out Interfaces.Unsigned_64) return Boolean
1927 with Pre => not Codepoint_Buffer.EOF;
1928 -- Helper to read a simple decimal integer, including underscores
1929
1930 -------------------------
1931 -- Read_Simple_Integer --
1932 -------------------------
1933
1934 function Read_Simple_Integer
1935 (Value : out Interfaces.Unsigned_64) return Boolean
1936 is
1937 use type Interfaces.Unsigned_64;
1938
1939 Empty : Boolean := True;
1940 -- Whether we read no digit so far
1941
1942 Previous_Is_Underscore : Boolean := True;
1943 -- Given that it is forbidden to have a leading underscore, do as if
1944 -- we just had an underscore at the beginning so that we need to
1945 -- check only for consecutive underscores.
1946 begin
1947 Value := 0;
1948
1949 -- Read and decode all digits that follow in the stream
1950
1951 while not Codepoint_Buffer.EOF
1952 and then Codepoint_Buffer.Codepoint in '0' .. '9' | '_'
1953 loop
1954 -- Discard underscores, yet do not allow consecutive ones
1955
1956 if Codepoint_Buffer.Codepoint = '_' then
1957 if Previous_Is_Underscore then
1958 return Invalid_Float;
1959 else
1960 Previous_Is_Underscore := True;
1961 end if;
1962
1963 -- Decode digits to build Value as we go. Consider the number too
1964 -- large as soon as it is bigger than half the largest possible
1965 -- unsigned 64 value: bigger numbers are unlikely and this allows
1966 -- us to negate values safely later on.
1967
1968 else
1969 begin
1970 Value :=
1971 10 * Value + Digit_Value (Codepoint_Buffer.Codepoint);
1972
1973 if Value > Interfaces.Unsigned_64'Last / 2 then
1974 return Too_Large;
1975 end if;
1976
1977 exception
1978 when Constraint_Error =>
1979 return Too_Large;
1980 end;
1981 Empty := False;
1982 Previous_Is_Underscore := False;
1983 end if;
1984
1985 if not Read_Codepoint then
1986 return Invalid_Float;
1987 end if;
1988 end loop;
1989
1990 -- We expect at least one digit, and the last codepoint must not be
1991 -- an underscore.
1992
1993 if Empty or else Previous_Is_Underscore then
1994 return Invalid_Float;
1995 else
1996 return True;
1997 end if;
1998 end Read_Simple_Integer;
1999
2000 Fractional_Value : Interfaces.Unsigned_64 := 0;
2001 Exponent : Interfaces.Unsigned_64 := 0;
2002 Exponent_Positive : Boolean := True;
2003 Result : Any_Float := (Kind => Regular, Value => <>);
2004 begin
2005 -- Read the fractional part, if present
2006
2007 if Codepoint_Buffer.Codepoint = '.' then
2008 if not Read_Codepoint then
2009 return False;
2010 elsif Codepoint_Buffer.EOF then
2011 return Invalid_Float;
2012 elsif not Read_Simple_Integer (Fractional_Value) then
2013 return False;
2014 end if;
2015 end if;
2016
2017 -- Read the exponent, if present
2018
2019 if not Codepoint_Buffer.EOF
2020 and then Codepoint_Buffer.Codepoint in 'e' | 'E'
2021 then
2022 if not Read_Codepoint then
2023 return False;
2024 elsif Codepoint_Buffer.EOF then
2025 return Invalid_Float;
2026 end if;
2027
2028 -- First read the sign
2029
2030 if Codepoint_Buffer.Codepoint in '+' | '-' then
2031 Exponent_Positive := Codepoint_Buffer.Codepoint /= '-';
2032 if not Read_Codepoint then
2033 return False;
2034 elsif Codepoint_Buffer.EOF then
2035 return Invalid_Float;
2036 end if;
2037 end if;
2038
2039 -- Then the exponent absolute value
2040
2041 if not Read_Simple_Integer (Exponent) then
2042 return False;
2043 end if;
2044 end if;
2045
2046 -- Reemit the last codepoint: it is not part of the float token and the
2047 -- next token reading iteration needs to read it.
2048
2049 Reemit_Codepoint;
2050
2051 -- Use all lexed parts to create a floating point value
2052
2053 declare
2054 function Image
2055 (Positive : Boolean; Value : Interfaces.Unsigned_64) return String;
2056
2057 -----------
2058 -- Image --
2059 -----------
2060
2061 function Image
2062 (Positive : Boolean; Value : Interfaces.Unsigned_64) return String
2063 is
2064 Result : constant String := Value'Image;
2065 Stripped : String renames Result (Result'First + 1 .. Result'Last);
2066 pragma Assert (Result (Result'First) = ' ');
2067 begin
2068 return (if Positive
2069 then Stripped
2070 else "-" & Stripped);
2071 end Image;
2072
2073 Value_Image : constant String :=
2074 Image (Positive, Integer_Value)
2075 & "." & Image (True, Fractional_Value)
2076 & "e" & Image (Exponent_Positive, Exponent);
2077 begin
2078 Result.Value := Valid_Float'Value (Value_Image);
2079 exception
2080 when Constraint_Error =>
2081 return Too_Large;
2082 end;
2083 if not Result.Value'Valid then
2084 if Result.Value < Valid_Float'First then
2085 Result := (Kind => Infinity, Positive => False);
2086 elsif Result.Value > Valid_Float'Last then
2087 Result := (Kind => Infinity, Positive => True);
2088 else
2089 Result := (Kind => NaN, Positive => True);
2090 end if;
2091 end if;
2092 Token_Buffer.Token := (Kind => Float_Literal, Float_Value => Result);
2093 return True;
2094 end Read_Float;
2095
2096 ------------------------
2097 -- Read_Special_Float --
2098 ------------------------
2099
2100 function Read_Special_Float
2101 (Name : Wide_Wide_String;
2102 Kind : Special_Float_Kind;
2103 Positive : Boolean) return Boolean
2104 is
2105 function Invalid_Float return Boolean is
2106 (Create_Lexing_Error ("invalid float"));
2107 begin
2108 pragma Assert (Codepoint_Buffer.Codepoint = Name (Name'First));
2109
2110 for C of Name (Name'First + 1 .. Name'Last) loop
2111 if not Read_Codepoint then
2112 return False;
2113 elsif Codepoint_Buffer.EOF
2114 or else Codepoint_Buffer.Codepoint /= C
2115 then
2116 return Invalid_Float;
2117 end if;
2118 end loop;
2119
2120 declare
2121 Value : Any_Float (Kind);
2122 begin
2123 Value.Positive := Positive;
2124 Token_Buffer.Token := (Kind => Float_Literal, Float_Value => Value);
2125 end;
2126 return True;
2127 end Read_Special_Float;
2128
2129 -------------------
2130 -- Read_Bare_Key --
2131 -------------------
2132
2133 function Read_Bare_Key return Boolean is
2134 begin
2135 Token_Buffer.Token :=
2136 (Kind => String_Literal,
2137 String_Format => Bare_Key,
2138 others => <>);
2139
2140 loop
2141 -- Add the previously read character to the key token
2142
2143 Append_As_UTF8 (Codepoint_Buffer.Codepoint);
2144
2145 -- Then check the next character: exit the loop as soon as we either
2146 -- reach the end of stream, or we find a non-key character.
2147
2148 if not Read_Codepoint then
2149 return False;
2150 end if;
2151
2152 exit when
2153 Codepoint_Buffer.EOF
2154 or else Codepoint_Buffer.Codepoint not in
2155 '0' .. '9' | 'A' .. 'Z' | 'a' .. 'z' | '_' | '-';
2156 end loop;
2157
2158 -- Be sure to schedule the re-emission of the read event that made us
2159 -- stop reading characters so that callers can attempt to read one more
2160 -- token.
2161
2162 Reemit_Codepoint;
2163
2164 return True;
2165 end Read_Bare_Key;
2166
2167 ------------------
2168 -- Read_Keyword --
2169 ------------------
2170
2171 function Read_Keyword
2172 (Text : Wide_Wide_String; Token : Any_Token) return Boolean is
2173 begin
2174 -- Read all codepoints that constitute the token (except the first one,
2175 -- as per the Read_Keyword contract) and make sure they match the
2176 -- expected text.
2177
2178 for I in Text'First + 1 .. Text'Last loop
2179 if not Read_Codepoint then
2180 return False;
2181 elsif Codepoint_Buffer.EOF
2182 or else Codepoint_Buffer.Codepoint /= Text (I)
2183 then
2184 return Create_Lexing_Error ("invalid token");
2185 end if;
2186 end loop;
2187
2188 Token_Buffer.Token := Token;
2189 return True;
2190 end Read_Keyword;
2191
2192 ----------------
2193 -- Parse_Line --
2194 ----------------
2195
2196 function Parse_Line return Boolean is
2197 begin
2198 if not Read_Token (Key_Expected => True) then
2199 return False;
2200 elsif Token_Buffer.EOF then
2201 return True;
2202 end if;
2203
2204 case Token_Buffer.Token.Kind is
2205 when Newline =>
2206 return True;
2207
2208 when Square_Bracket_Open =>
2209 -- Parse a [section]
2210
2211 return Parse_Section (Array_Of_Table => False);
2212
2213 when Double_Square_Bracket_Open =>
2214 -- Parse a [[section]]
2215
2216 return Parse_Section (Array_Of_Table => True);
2217
2218 when String_Literal =>
2219 -- Parse a key/value pair
2220
2221 declare
2222 Table : TOML_Value := Current_Table;
2223 Key : Unbounded_UTF8_String;
2224 Value : TOML_Value;
2225 begin
2226 -- Parse the dotted key that identify the table entry to
2227 -- create. In particular, get the destination table (Table) and
2228 -- the key to insert (Key) and make sure there is no existing
2229 -- entry for Key.
2230
2231 if not Parse_Dotted_Keys (Table, Key, Traverse_Arrays => False)
2232 then
2233 return False;
2234 elsif Table.Has (Key) then
2235 return Create_Syntax_Error ("duplicate key");
2236 end if;
2237
2238 if Token_Buffer.EOF or else Token_Buffer.Token.Kind /= Equal
2239 then
2240 return Create_Syntax_Error;
2241 end if;
2242
2243 -- Now parse the value for the entry to insert. On success, do
2244 -- the insertion.
2245
2246 if Parse_Value (Value) then
2247 Table.Set (Key, Value);
2248 else
2249 return False;
2250 end if;
2251
2252 -- Expect either a new line, or the end of the file
2253
2254 if not Read_Token (Key_Expected => True) then
2255 return False;
2256 elsif Token_Buffer.EOF then
2257 return True;
2258 elsif Token_Buffer.Token.Kind /= Newline then
2259 return Create_Syntax_Error ("missing newline");
2260 end if;
2261
2262 return True;
2263 end;
2264
2265 when others =>
2266 return Create_Syntax_Error;
2267 end case;
2268 end Parse_Line;
2269
2270 ---------------
2271 -- Get_Table --
2272 ---------------
2273
2274 function Get_Table
2275 (Key : Unbounded_UTF8_String;
2276 Table : in out TOML_Value;
2277 Traverse_Arrays : Boolean := False) return Boolean
2278 is
2279 Next_Table : TOML_Value := Table.Get_Or_Null (Key);
2280 begin
2281 if Next_Table.Is_Null then
2282 Next_Table := Create_Table;
2283 Next_Table.Set_Implicitly_Created;
2284 Table.Set (Key, Next_Table);
2285 Table := Next_Table;
2286 return True;
2287
2288 elsif Next_Table.Kind = TOML_Table then
2289 Table := Next_Table;
2290 return True;
2291
2292 elsif Traverse_Arrays
2293 and then Next_Table.Kind = TOML_Array
2294 and then Next_Table.Length > 0
2295 then
2296 Table := Next_Table.Item (Next_Table.Length);
2297 return True;
2298
2299 else
2300 return Create_Syntax_Error ("invalid table key");
2301 end if;
2302 end Get_Table;
2303
2304 -------------------
2305 -- Parse_Section --
2306 -------------------
2307
2308 function Parse_Section (Array_Of_Table : Boolean) return Boolean is
2309 Opening_Bracket_Location : constant Source_Location :=
2310 Token_Buffer.Location;
2311
2312 Closing_Bracket : constant Token_Kind :=
2313 (if Array_Of_Table
2314 then Double_Square_Bracket_Close
2315 else Square_Bracket_Close);
2316
2317 Table : TOML_Value := Root_Table;
2318 Key : Unbounded_UTF8_String;
2319 begin
2320 -- Get the first token for the section name, as per Parse_Dotted_Keys's
2321 -- contract.
2322
2323 if not Read_Token (Key_Expected => True) then
2324 return False;
2325
2326 elsif Token_Buffer.EOF then
2327 return Create_Syntax_Error;
2328
2329 elsif not Parse_Dotted_Keys (Table, Key, Traverse_Arrays => True) then
2330 return False;
2331
2332 -- At this point, Parse_Dotted_Keys left the first non-key token in
2333 -- Token_Buffer: make sure we have the closing bracket.
2334
2335 elsif Token_Buffer.EOF or else Token_Buffer.Token.Kind /= Closing_Bracket
2336 then
2337 return Create_Syntax_Error;
2338
2339 -- And now, make sure that we have either EOF or a newline next
2340
2341 elsif not Read_Token (Key_Expected => False)
2342 or else (not Token_Buffer.EOF
2343 and then Token_Buffer.Token.Kind /= Newline)
2344 then
2345 return Create_Syntax_Error;
2346 end if;
2347
2348 -- Finally, create the requested table
2349
2350 if Array_Of_Table then
2351 -- Key is supposed to refer to an array of tables: if there is no
2352 -- such entry in Table, create one, otherwise make sure it has the
2353 -- expected item type.
2354
2355 declare
2356 Arr : TOML_Value := Table.Get_Or_Null (Key);
2357 begin
2358 if Arr.Is_Null then
2359 Arr := Create_Array;
2360 Arr.Set_Implicitly_Created;
2361 Table.Set (Key, Arr);
2362 elsif Arr.Kind /= TOML_Array then
2363 return Create_Error
2364 ("invalid array", Opening_Bracket_Location);
2365 elsif not Arr.Implicitly_Created then
2366 return Create_Error
2367 ("arrays of tables cannot complete inline arrays",
2368 Opening_Bracket_Location);
2369 end if;
2370
2371 -- Create a new table and append it to this array
2372
2373 Current_Table := Create_Table;
2374 Arr.Append (Current_Table);
2375 end;
2376
2377 else
2378 -- If Key is already associated to a table, return it (it's an error
2379 -- if it is not a table or if it was already created explicitly).
2380 -- Create the destination table otherwise.
2381
2382 if Table.Has (Key) then
2383 Current_Table := Table.Get (Key);
2384 if Current_Table.Kind /= TOML_Table then
2385 return Create_Error
2386 ("duplicate key", Opening_Bracket_Location);
2387 elsif Current_Table.Implicitly_Created then
2388 Current_Table.Set_Explicitly_Created;
2389 else
2390 return Create_Error
2391 ("cannot create tables twice", Opening_Bracket_Location);
2392 end if;
2393 else
2394 Current_Table := Create_Table;
2395 Table.Set (Key, Current_Table);
2396 end if;
2397 end if;
2398
2399 return True;
2400 end Parse_Section;
2401
2402 -----------------------
2403 -- Parse_Dotted_Keys --
2404 -----------------------
2405
2406 function Parse_Dotted_Keys
2407 (Table : in out TOML_Value;
2408 Key : out Unbounded_UTF8_String;
2409 Traverse_Arrays : Boolean := False) return Boolean
2410 is
2411 Has_Key : Boolean := False;
2412 -- Whether we parsed at least one key
2413 begin
2414 loop
2415 -- Process the current key, updating Table accordingly
2416
2417 if Token_Buffer.EOF
2418 or else Token_Buffer.Token.Kind /= String_Literal
2419 or else Token_Buffer.Token.String_Format not in Valid_Key_Format
2420 then
2421 return Create_Syntax_Error;
2422 end if;
2423
2424 -- We are about to parse a key. If we already parsed one, we need to
2425 -- fetch the corresponding table.
2426
2427 if Has_Key and then not Get_Table (Key, Table, Traverse_Arrays) then
2428 return False;
2429 end if;
2430 Key := Token_Buffer.Token.String_Value;
2431 Has_Key := True;
2432
2433 -- If the next token is a dot, expect another key. Otherwise, stop
2434 -- parsing keys.
2435
2436 if not Read_Token (Key_Expected => True) then
2437 return False;
2438
2439 elsif Token_Buffer.EOF or else Token_Buffer.Token.Kind /= Dot then
2440 return True;
2441
2442 elsif not Read_Token (Key_Expected => True) then
2443 return False;
2444 end if;
2445 end loop;
2446 end Parse_Dotted_Keys;
2447
2448 -----------------
2449 -- Parse_Value --
2450 -----------------
2451
2452 function Parse_Value (Value : out TOML_Value) return Boolean is
2453 begin
2454 -- Fetch the first token that encodes the value to parse...
2455
2456 if not Read_Token (Key_Expected => False) then
2457 return False;
2458
2459 elsif Token_Buffer.EOF then
2460 return Create_Syntax_Error;
2461 end if;
2462
2463 case Token_Buffer.Token.Kind is
2464 when Boolean_Literal =>
2465 Value := Create_Boolean (Token_Buffer.Token.Boolean_Value);
2466
2467 when Integer_Literal =>
2468 Value := Create_Integer (Token_Buffer.Token.Integer_Value);
2469
2470 when Float_Literal =>
2471 Value := Create_Float (Token_Buffer.Token.Float_Value);
2472
2473 when String_Literal =>
2474 Value := Create_String (Token_Buffer.Token.String_Value);
2475
2476 when Offset_Datetime_Literal =>
2477 Value := Create_Offset_Datetime
2478 (Token_Buffer.Token.Offset_Datetime_Value);
2479
2480 when Local_Datetime_Literal =>
2481 Value := Create_Local_Datetime
2482 (Token_Buffer.Token.Local_Datetime_Value);
2483
2484 when Local_Date_Literal =>
2485 Value := Create_Local_Date (Token_Buffer.Token.Local_Date_Value);
2486
2487 when Local_Time_Literal =>
2488 Value := Create_Local_Time (Token_Buffer.Token.Local_Time_Value);
2489
2490 when Square_Bracket_Open =>
2491 return Parse_Array (Value);
2492
2493 when Curly_Bracket_Open =>
2494 return Parse_Table (Value);
2495
2496 when others =>
2497 return Create_Syntax_Error
2498 ("invalid (or not supported yet) syntax");
2499 end case;
2500
2501 return True;
2502 end Parse_Value;
2503
2504 -----------------
2505 -- Parse_Array --
2506 -----------------
2507
2508 function Parse_Array (Value : out TOML_Value) return Boolean is
2509 Comma_Allowed : Boolean := False;
2510 begin
2511 Value := Create_Array;
2512
2513 loop
2514 -- Fetch the next token. We need one, so reaching end of stream is a
2515 -- parsing error.
2516
2517 if not Read_Token (Key_Expected => False) then
2518 return False;
2519
2520 elsif Token_Buffer.EOF then
2521 return Create_Syntax_Error;
2522 end if;
2523
2524 case Token_Buffer.Token.Kind is
2525 when Square_Bracket_Close =>
2526 return True;
2527
2528 when Newline =>
2529 -- Newlines are allowed anywhere between surrounding brackets,
2530 -- values and commas.
2531 null;
2532
2533 when Comma =>
2534 if Comma_Allowed then
2535 Comma_Allowed := False;
2536 else
2537 return Create_Syntax_Error;
2538 end if;
2539
2540 when others =>
2541 -- We are expecting a comma right after parsing a value, so if
2542 -- we have a potential value in this case, we know a comma is
2543 -- missing.
2544
2545 if Comma_Allowed then
2546 return Create_Syntax_Error;
2547 end if;
2548
2549 -- We already read the first token for this value, but
2550 -- Parse_Value expects it not to be read yet, so plan to
2551 -- re-emit it.
2552
2553 Reemit_Token;
2554
2555 declare
2556 Item : TOML_Value;
2557 begin
2558 -- Parse the item value and then append the item to the
2559 -- result.
2560
2561 if not Parse_Value (Item) then
2562 return False;
2563 end if;
2564
2565 Value.Append (Item);
2566 end;
2567 Comma_Allowed := True;
2568 end case;
2569 end loop;
2570 end Parse_Array;
2571
2572 -----------------
2573 -- Parse_Table --
2574 -----------------
2575
2576 function Parse_Table (Value : out TOML_Value) return Boolean is
2577 Comma_Allowed : Boolean := False;
2578 Last_Was_Comma : Boolean := False;
2579 Key : Unbounded_UTF8_String;
2580 Table : TOML_Value;
2581 begin
2582 Value := Create_Table;
2583
2584 loop
2585 -- Fetch the next token (a potential key for the next table entry, or
2586 -- a closing bracket). We need one, so reaching end of stream is a
2587 -- parsing error.
2588
2589 if not Read_Token (Key_Expected => True) then
2590 return False;
2591 elsif Token_Buffer.EOF then
2592 return Create_Syntax_Error;
2593 end if;
2594
2595 case Token_Buffer.Token.Kind is
2596 when Curly_Bracket_Close =>
2597 if Last_Was_Comma then
2598 return Create_Error ("invalid trailing comma");
2599 end if;
2600 return True;
2601
2602 when Newline =>
2603 return Create_Error ("newlines not allowed in inlined tables");
2604
2605 when Comma =>
2606 Last_Was_Comma := True;
2607 if Comma_Allowed then
2608 Comma_Allowed := False;
2609 else
2610 return Create_Syntax_Error;
2611 end if;
2612
2613 when String_Literal =>
2614
2615 -- We are expecting a comma right after parsing a value, so if
2616 -- we have a potential value in this case, we know a comma is
2617 -- missing.
2618
2619 if Comma_Allowed then
2620 return Create_Syntax_Error;
2621 end if;
2622
2623 -- Dotted keys are allowed in inline tables, so attempt to
2624 -- parse dotted keys (i.e. multiple tokens) and make sure it is
2625 -- followed by an equal token.
2626
2627 Table := Value;
2628 if not Parse_Dotted_Keys (Table, Key, Traverse_Arrays => False)
2629 then
2630 return False;
2631 elsif Token_Buffer.EOF or else Token_Buffer.Token.Kind /= Equal
2632 then
2633 return Create_Syntax_Error;
2634 end if;
2635
2636 -- Then try to create the table entry
2637
2638 if Table.Has (Key) then
2639 return Create_Syntax_Error ("duplicate key");
2640 end if;
2641
2642 -- Now read the value
2643
2644 declare
2645 Item : TOML_Value;
2646 begin
2647 -- Parse the item value, reject heterogeneous arrays, and
2648 -- then append the item to the result.
2649
2650 if not Parse_Value (Item) then
2651 return False;
2652 end if;
2653
2654 -- Finally register the table entry
2655
2656 Table.Set (Key, Item);
2657 Comma_Allowed := True;
2658 Last_Was_Comma := False;
2659 end;
2660
2661 when others =>
2662 return Create_Syntax_Error;
2663 end case;
2664 end loop;
2665 end Parse_Table;
2666
2667 begin
2668 while not Token_Buffer.EOF loop
2669 if not Parse_Line then
2670 return Result;
2671 end if;
2672 end loop;
2673
2674 return Result;
2675 end TOML.Generic_Parse;