-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTommy.cs
2165 lines (1743 loc) · 71.7 KB
/
Tommy.cs
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
#region LICENSE
/**
* MIT License
*
* Copyright (c) 2019 Denis Zhidkikh
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Tommy
{
#region TOML Nodes
public abstract class TomlNode : IEnumerable
{
public virtual bool HasValue { get; } = false;
public virtual bool IsArray { get; } = false;
public virtual bool IsTable { get; } = false;
public virtual bool IsString { get; } = false;
public virtual bool IsInteger { get; } = false;
public virtual bool IsFloat { get; } = false;
public virtual bool IsDateTime { get; } = false;
public virtual bool IsBoolean { get; } = false;
public virtual string Comment { get; set; }
public virtual int CollapseLevel { get; set; } = 0;
public virtual TomlTable AsTable => this as TomlTable;
public virtual TomlString AsString => this as TomlString;
public virtual TomlInteger AsInteger => this as TomlInteger;
public virtual TomlFloat AsFloat => this as TomlFloat;
public virtual TomlBoolean AsBoolean => this as TomlBoolean;
public virtual TomlDateTime AsDateTime => this as TomlDateTime;
public virtual TomlArray AsArray => this as TomlArray;
public virtual int ChildrenCount => 0;
public virtual TomlNode this[string key]
{
get => null;
set { }
}
public virtual TomlNode this[int index]
{
get => null;
set { }
}
public virtual IEnumerable<TomlNode> Children
{
get { yield break; }
}
public virtual IEnumerable<string> Keys
{
get { yield break; }
}
public IEnumerator GetEnumerator() => Children.GetEnumerator();
public virtual bool TryGetNode(string key, out TomlNode node)
{
node = null;
return false;
}
public virtual bool HasKey(string key) => false;
public virtual bool HasItemAt(int index) => false;
public virtual void Add(string key, TomlNode node) { }
public virtual void Add(TomlNode node) { }
public virtual void Delete(TomlNode node) { }
public virtual void Delete(string key) { }
public virtual void Delete(int index) { }
public virtual void AddRange(IEnumerable<TomlNode> nodes)
{
foreach (var tomlNode in nodes) Add(tomlNode);
}
public virtual void ToTomlString(TextWriter tw, string name = null) { }
#region Native type to TOML cast
public static implicit operator TomlNode(string value) =>
new TomlString
{
Value = value
};
public static implicit operator TomlNode(bool value) =>
new TomlBoolean
{
Value = value
};
public static implicit operator TomlNode(long value) =>
new TomlInteger
{
Value = value
};
public static implicit operator TomlNode(float value) =>
new TomlFloat
{
Value = value
};
public static implicit operator TomlNode(double value) =>
new TomlFloat
{
Value = value
};
public static implicit operator TomlNode(DateTime value) =>
new TomlDateTime
{
Value = value
};
public static implicit operator TomlNode(TomlNode[] nodes)
{
var result = new TomlArray();
result.AddRange(nodes);
return result;
}
#endregion
#region TOML to native type cast
public static implicit operator string(TomlNode value) => value.AsString.Value;
public static implicit operator int(TomlNode value) => (int)value.AsInteger.Value;
public static implicit operator long(TomlNode value) => value.AsInteger.Value;
public static implicit operator float(TomlNode value) => (float)value.AsFloat.Value;
public static implicit operator double(TomlNode value) => value.AsFloat.Value;
public static implicit operator bool(TomlNode value) => value.AsBoolean.Value;
public static implicit operator DateTime(TomlNode value) => value.AsDateTime.Value;
#endregion
}
public class TomlString : TomlNode
{
public override bool HasValue { get; } = true;
public override bool IsString { get; } = true;
public bool IsMultiline { get; set; }
public bool PreferLiteral { get; set; }
public string Value { get; set; }
public override string ToString()
{
if (Value.IndexOf(TomlSyntax.LITERAL_STRING_SYMBOL) != -1 && PreferLiteral) PreferLiteral = false;
var quotes = new string(PreferLiteral ? TomlSyntax.LITERAL_STRING_SYMBOL : TomlSyntax.BASIC_STRING_SYMBOL,
IsMultiline ? 3 : 1);
var result = PreferLiteral ? Value : Value.Escape(!IsMultiline);
return $"{quotes}{result}{quotes}";
}
public override void ToTomlString(TextWriter tw, string name = null)
{
tw.Write(ToString());
}
}
public class TomlInteger : TomlNode
{
public enum Base
{
Binary = 2,
Octal = 8,
Decimal = 10,
Hexadecimal = 16
}
public override bool IsInteger { get; } = true;
public override bool HasValue { get; } = true;
public Base IntegerBase { get; set; } = Base.Decimal;
public long Value { get; set; }
public override string ToString()
{
if (IntegerBase != Base.Decimal)
return $"0{TomlSyntax.BaseIdentifiers[(int)IntegerBase]}{Convert.ToString(Value, (int)IntegerBase)}";
return Value.ToString(CultureInfo.InvariantCulture);
}
public override void ToTomlString(TextWriter tw, string name = null) => tw.Write(ToString());
}
public class TomlFloat : TomlNode
{
public override bool IsFloat { get; } = true;
public override bool HasValue { get; } = true;
public double Value { get; set; }
public override string ToString()
{
if (double.IsNaN(Value)) return TomlSyntax.NAN_VALUE;
if (double.IsPositiveInfinity(Value)) return TomlSyntax.INF_VALUE;
if (double.IsNegativeInfinity(Value)) return TomlSyntax.NEG_INF_VALUE;
return Value.ToString("G", CultureInfo.InvariantCulture);
}
public override void ToTomlString(TextWriter tw, string name = null) => tw.Write(ToString());
}
public class TomlBoolean : TomlNode
{
public override bool IsBoolean { get; } = true;
public override bool HasValue { get; } = true;
public bool Value { get; set; }
public override string ToString() => Value ? TomlSyntax.TRUE_VALUE : TomlSyntax.FALSE_VALUE;
public override void ToTomlString(TextWriter tw, string name = null) => tw.Write(ToString());
}
public class TomlDateTime : TomlNode
{
public override bool IsDateTime { get; } = true;
public override bool HasValue { get; } = true;
public bool OnlyDate { get; set; }
public bool OnlyTime { get; set; }
public int SecondsPrecision { get; set; }
public DateTime Value { get; set; }
public override string ToString()
{
if (OnlyDate) return Value.ToString(TomlSyntax.LocalDateFormat);
if (OnlyTime) return Value.ToString(TomlSyntax.RFC3339LocalTimeFormats[SecondsPrecision]);
if (Value.Kind == DateTimeKind.Local)
return Value.ToString(TomlSyntax.RFC3339LocalDateTimeFormats[SecondsPrecision]);
return Value.ToString(TomlSyntax.RFC3339Formats[SecondsPrecision]);
}
public override void ToTomlString(TextWriter tw, string name = null) => tw.Write(ToString());
}
public class TomlArray : TomlNode
{
private List<TomlNode> values;
public override bool HasValue { get; } = true;
public override bool IsArray { get; } = true;
public bool IsTableArray { get; set; }
public List<TomlNode> RawArray => values ?? (values = new List<TomlNode>());
public override TomlNode this[int index]
{
get
{
if (index < RawArray.Count) return RawArray[index];
var lazy = new TomlLazy(this);
this[index] = lazy;
return lazy;
}
set
{
if (index == RawArray.Count)
RawArray.Add(value);
else
RawArray[index] = value;
}
}
public override int ChildrenCount => RawArray.Count;
public override IEnumerable<TomlNode> Children => RawArray.AsEnumerable();
public override void Add(TomlNode node) => RawArray.Add(node);
public override void AddRange(IEnumerable<TomlNode> nodes) => RawArray.AddRange(nodes);
public override void Delete(TomlNode node) => RawArray.Remove(node);
public override void Delete(int index) => RawArray.RemoveAt(index);
public override string ToString()
{
var sb = new StringBuilder();
sb.Append(TomlSyntax.ARRAY_START_SYMBOL);
if (ChildrenCount != 0)
sb.Append(' ')
.Append($"{TomlSyntax.ITEM_SEPARATOR} ".Join(RawArray.Select(n => n.ToString())))
.Append(' ');
sb.Append(TomlSyntax.ARRAY_END_SYMBOL);
return sb.ToString();
}
public override void ToTomlString(TextWriter tw, string name = null)
{
// If it's a normal array, write it as usual
if (!IsTableArray)
{
tw.Write(ToString());
return;
}
tw.WriteLine();
Comment?.AsComment(tw);
tw.Write(TomlSyntax.ARRAY_START_SYMBOL);
tw.Write(TomlSyntax.ARRAY_START_SYMBOL);
tw.Write(name);
tw.Write(TomlSyntax.ARRAY_END_SYMBOL);
tw.Write(TomlSyntax.ARRAY_END_SYMBOL);
tw.WriteLine();
var first = true;
foreach (var tomlNode in RawArray)
{
if (!(tomlNode is TomlTable tbl))
throw new TomlFormatException("The array is marked as array table but contains non-table nodes!");
// Ensure it's parsed as a section
tbl.IsInline = false;
if (!first)
{
tw.WriteLine();
Comment?.AsComment(tw);
tw.Write(TomlSyntax.ARRAY_START_SYMBOL);
tw.Write(TomlSyntax.ARRAY_START_SYMBOL);
tw.Write(name);
tw.Write(TomlSyntax.ARRAY_END_SYMBOL);
tw.Write(TomlSyntax.ARRAY_END_SYMBOL);
tw.WriteLine();
}
first = false;
// Don't pass section name because we already specified it
tbl.ToTomlString(tw);
tw.WriteLine();
}
}
}
public class TomlTable : TomlNode
{
private Dictionary<string, TomlNode> children;
public override bool HasValue { get; } = false;
public override bool IsTable { get; } = true;
public bool IsInline { get; set; }
public Dictionary<string, TomlNode> RawTable => children ?? (children = new Dictionary<string, TomlNode>());
public override TomlNode this[string key]
{
get
{
if (RawTable.TryGetValue(key, out var result)) return result;
var lazy = new TomlLazy(this);
RawTable[key] = lazy;
return lazy;
}
set => RawTable[key] = value;
}
public override int ChildrenCount => RawTable.Count;
public override IEnumerable<TomlNode> Children => RawTable.Select(kv => kv.Value);
public override IEnumerable<string> Keys => RawTable.Select(kv => kv.Key);
public override bool HasKey(string key) => RawTable.ContainsKey(key);
public override void Add(string key, TomlNode node) => RawTable.Add(key, node);
public override bool TryGetNode(string key, out TomlNode node) => RawTable.TryGetValue(key, out node);
public override void Delete(TomlNode node) => RawTable.Remove(RawTable.First(kv => kv.Value == node).Key);
public override void Delete(string key) => RawTable.Remove(key);
public override string ToString()
{
var sb = new StringBuilder();
sb.Append(TomlSyntax.INLINE_TABLE_START_SYMBOL);
if (ChildrenCount != 0)
{
var collapsed = CollectCollapsedItems(out var nonCollapsible);
sb.Append(' ');
sb.Append($"{TomlSyntax.ITEM_SEPARATOR} ".Join(RawTable.Where(n => nonCollapsible.Contains(n.Key))
.Select(n => $"{n.Key.AsKey()} {TomlSyntax.KEY_VALUE_SEPARATOR} {n.Value.ToString()}")));
if (collapsed.Count != 0)
sb.Append(TomlSyntax.ITEM_SEPARATOR)
.Append(' ')
.Append($"{TomlSyntax.ITEM_SEPARATOR} ".Join(collapsed.Select(n => $"{n.Key} {TomlSyntax.KEY_VALUE_SEPARATOR} {n.Value.ToString()}")));
sb.Append(' ');
}
sb.Append(TomlSyntax.INLINE_TABLE_END_SYMBOL);
return sb.ToString();
}
private Dictionary<string, TomlNode> CollectCollapsedItems(out HashSet<string> nonCollapsibleItems, string prefix = "",
Dictionary<string, TomlNode> nodes = null,
int level = 0)
{
nonCollapsibleItems = new HashSet<string>();
if (nodes == null)
{
nodes = new Dictionary<string, TomlNode>();
foreach (var keyValuePair in RawTable)
{
var node = keyValuePair.Value;
var key = keyValuePair.Key.AsKey();
if (node is TomlTable tbl)
{
tbl.CollectCollapsedItems(out var nonCollapsible, $"{prefix}{key}.", nodes, level + 1);
if (nonCollapsible.Count != 0)
nonCollapsibleItems.Add(key);
}
else
nonCollapsibleItems.Add(key);
}
return nodes;
}
foreach (var keyValuePair in RawTable)
{
var node = keyValuePair.Value;
var key = keyValuePair.Key.AsKey();
if (node.CollapseLevel == level)
nodes.Add($"{prefix}{key}", node);
else if (node is TomlTable tbl)
{
tbl.CollectCollapsedItems(out var nonCollapsible, $"{prefix}{key}.", nodes, level + 1);
if (nonCollapsible.Count != 0)
nonCollapsibleItems.Add(key);
}
else
nonCollapsibleItems.Add(key);
}
return nodes;
}
public override void ToTomlString(TextWriter tw, string name = null)
{
// The table is inline table
if (IsInline && name != null)
{
tw.Write(ToString());
return;
}
if (RawTable.All(n => n.Value.CollapseLevel != 0))
return;
var hasRealValues = !RawTable.All(n => n.Value is TomlTable tbl && !tbl.IsInline);
var collapsedItems = CollectCollapsedItems(out var _);
Comment?.AsComment(tw);
if (name != null && (hasRealValues || collapsedItems.Count > 0))
{
tw.Write(TomlSyntax.ARRAY_START_SYMBOL);
tw.Write(name);
tw.Write(TomlSyntax.ARRAY_END_SYMBOL);
tw.WriteLine();
}
else if (Comment != null) // Add some spacing between the first node and the comment
{
tw.WriteLine();
}
var namePrefix = name == null ? "" : $"{name}.";
var first = true;
var sectionableItems = new Dictionary<string, TomlNode>();
foreach (var child in RawTable)
{
// If value should be parsed as section, separate if from the bunch
if (child.Value is TomlArray arr && arr.IsTableArray || child.Value is TomlTable tbl && !tbl.IsInline)
{
sectionableItems.Add(child.Key, child.Value);
continue;
}
// If the value is collapsed, it belongs to the parent
if (child.Value.CollapseLevel != 0)
continue;
if (!first) tw.WriteLine();
first = false;
var key = child.Key.AsKey();
child.Value.Comment?.AsComment(tw);
tw.Write(key);
tw.Write(' ');
tw.Write(TomlSyntax.KEY_VALUE_SEPARATOR);
tw.Write(' ');
child.Value.ToTomlString(tw, $"{namePrefix}{key}");
}
foreach (var collapsedItem in collapsedItems)
{
if (collapsedItem.Value is TomlArray arr && arr.IsTableArray ||
collapsedItem.Value is TomlTable tbl && !tbl.IsInline)
throw new
TomlFormatException($"Value {collapsedItem.Key} cannot be defined as collapsed, because it is not an inline value!");
tw.WriteLine();
var key = collapsedItem.Key;
collapsedItem.Value.Comment?.AsComment(tw);
tw.Write(key);
tw.Write(' ');
tw.Write(TomlSyntax.KEY_VALUE_SEPARATOR);
tw.Write(' ');
collapsedItem.Value.ToTomlString(tw, $"{namePrefix}{key}");
}
if (sectionableItems.Count == 0)
return;
tw.WriteLine();
tw.WriteLine();
first = true;
foreach (var child in sectionableItems)
{
if (!first) tw.WriteLine();
first = false;
child.Value.ToTomlString(tw, $"{namePrefix}{child.Key}");
}
}
}
internal class TomlLazy : TomlNode
{
private readonly TomlNode parent;
private TomlNode replacement;
public TomlLazy(TomlNode parent) => this.parent = parent;
public override TomlNode this[int index]
{
get => Set<TomlArray>()[index];
set => Set<TomlArray>()[index] = value;
}
public override TomlNode this[string key]
{
get => Set<TomlTable>()[key];
set => Set<TomlTable>()[key] = value;
}
public override void Add(TomlNode node) => Set<TomlArray>().Add(node);
public override void Add(string key, TomlNode node) => Set<TomlTable>().Add(key, node);
public override void AddRange(IEnumerable<TomlNode> nodes) => Set<TomlArray>().AddRange(nodes);
private TomlNode Set<T>() where T : TomlNode, new()
{
if (replacement != null) return replacement;
var newNode = new T
{
Comment = Comment
};
if (parent.IsTable)
{
var key = parent.Keys.FirstOrDefault(s => parent.TryGetNode(s, out var node) && node.Equals(this));
if (key == null) return default(T);
parent[key] = newNode;
}
else if (parent.IsArray)
{
var index = 0;
foreach (var child in parent.Children)
{
if (child == this) break;
index++;
}
if (index == parent.ChildrenCount) return default(T);
parent[index] = newNode;
}
else
{
return default(T);
}
replacement = newNode;
return newNode;
}
}
#endregion
#region Parser
public class TOMLParser : IDisposable
{
public enum ParseState
{
None,
KeyValuePair,
SkipToNextLine,
Table
}
private readonly TextReader reader;
private ParseState currentState;
private int line, col;
private List<TomlSyntaxException> syntaxErrors;
public TOMLParser(TextReader reader)
{
this.reader = reader;
line = col = 0;
}
public bool ForceASCII { get; set; }
public void Dispose()
{
reader?.Dispose();
}
public TomlTable Parse()
{
syntaxErrors = new List<TomlSyntaxException>();
line = col = 0;
var rootNode = new TomlTable();
var currentNode = rootNode;
currentState = ParseState.None;
var keyParts = new List<string>();
var arrayTable = false;
var latestComment = new StringBuilder();
var firstComment = true;
int currentChar;
while ((currentChar = reader.Peek()) >= 0)
{
var c = (char)currentChar;
if (currentState == ParseState.None)
{
// Skip white space
if (TomlSyntax.IsWhiteSpace(c)) goto consume_character;
if (TomlSyntax.IsNewLine(c))
{
// Check if there are any comments and so far no items being declared
if (latestComment.Length != 0 && firstComment)
{
rootNode.Comment = latestComment.ToString().TrimEnd();
latestComment.Length = 0;
firstComment = false;
}
if (TomlSyntax.IsLineBreak(c))
AdvanceLine();
goto consume_character;
}
// Start of a comment; ignore until newline
if (c == TomlSyntax.COMMENT_SYMBOL)
{
// Consume the comment symbol and buffer the whole comment line
reader.Read();
latestComment.AppendLine(reader.ReadLine()?.Trim());
AdvanceLine(0);
continue;
}
// Encountered a non-comment value. The comment must belong to it (ignore possible newlines)!
firstComment = false;
if (c == TomlSyntax.TABLE_START_SYMBOL)
{
currentState = ParseState.Table;
goto consume_character;
}
if (TomlSyntax.IsBareKey(c) || TomlSyntax.IsQuoted(c))
{
currentState = ParseState.KeyValuePair;
}
else
{
AddError($"Unexpected character \"{c}\"");
continue;
}
}
if (currentState == ParseState.KeyValuePair)
{
var keyValuePair = ReadKeyValuePair(keyParts);
if (keyValuePair == null)
{
latestComment.Length = 0;
keyParts.Clear();
if (currentState != ParseState.None)
AddError("Failed to parse key-value pair!");
continue;
}
keyValuePair.Comment = latestComment.ToString().TrimEnd();
var inserted = InsertNode(keyValuePair, currentNode, keyParts);
latestComment.Length = 0;
keyParts.Clear();
if (inserted)
currentState = ParseState.SkipToNextLine;
continue;
}
if (currentState == ParseState.Table)
{
if (keyParts.Count == 0)
{
// We have array table
if (c == TomlSyntax.TABLE_START_SYMBOL)
{
// Consume the character
ConsumeChar();
arrayTable = true;
}
if (!ReadKeyName(ref keyParts, TomlSyntax.TABLE_END_SYMBOL, true))
{
keyParts.Clear();
continue;
}
if (keyParts.Count == 0)
{
AddError("Table name is emtpy.");
arrayTable = false;
latestComment.Length = 0;
keyParts.Clear();
}
continue;
}
if (c == TomlSyntax.TABLE_END_SYMBOL)
{
if (arrayTable)
{
// Consume the ending bracket so we can peek the next character
ConsumeChar();
var nextChar = reader.Peek();
if (nextChar < 0 || (char)nextChar != TomlSyntax.TABLE_END_SYMBOL)
{
AddError($"Array table {".".Join(keyParts)} has only one closing bracket.");
keyParts.Clear();
arrayTable = false;
latestComment.Length = 0;
continue;
}
}
currentNode = CreateTable(rootNode, keyParts, arrayTable);
if (currentNode != null)
{
currentNode.IsInline = false;
currentNode.Comment = latestComment.ToString().TrimEnd();
}
keyParts.Clear();
arrayTable = false;
latestComment.Length = 0;
if (currentNode == null)
{
if (currentState != ParseState.None)
AddError("Error creating table array!");
continue;
}
currentState = ParseState.SkipToNextLine;
goto consume_character;
}
if (keyParts.Count != 0)
{
AddError($"Unexpected character \"{c}\"");
keyParts.Clear();
arrayTable = false;
latestComment.Length = 0;
}
}
if (currentState == ParseState.SkipToNextLine)
{
if (TomlSyntax.IsWhiteSpace(c) || c == TomlSyntax.NEWLINE_CARRIAGE_RETURN_CHARACTER)
goto consume_character;
if (c == TomlSyntax.COMMENT_SYMBOL || c == TomlSyntax.NEWLINE_CHARACTER)
{
currentState = ParseState.None;
AdvanceLine();
if (c == TomlSyntax.COMMENT_SYMBOL)
{
col++;
reader.ReadLine();
continue;
}
goto consume_character;
}
AddError($"Unexpected character \"{c}\" at the end of the line.");
}
consume_character:
reader.Read();
col++;
}
if (currentState != ParseState.None && currentState != ParseState.SkipToNextLine)
AddError("Unexpected end of file!");
if (syntaxErrors.Count > 0)
throw new TomlParseException(rootNode, syntaxErrors);
return rootNode;
}
private bool AddError(string message)
{
syntaxErrors.Add(new TomlSyntaxException(message, currentState, line, col));
// Skip the whole line in hope that it was only a single faulty value (and non-multiline one at that)
reader.ReadLine();
AdvanceLine(0);
currentState = ParseState.None;
return false;
}
private void AdvanceLine(int startCol = -1)
{
line++;
col = startCol;
}
private int ConsumeChar()
{
col++;
return reader.Read();
}
#region Key-Value pair parsing
/**
* Reads a single key-value pair.
* Assumes the cursor is at the first character that belong to the pair (including possible whitespace).
* Consumes all characters that belong to the key and the value (ignoring possible trailing whitespace at the end).
*
* Example:
* foo = "bar" ==> foo = "bar"
* ^ ^
*/
private TomlNode ReadKeyValuePair(List<string> keyParts)
{
int cur;
while ((cur = reader.Peek()) >= 0)
{
var c = (char)cur;
if (TomlSyntax.IsQuoted(c) || TomlSyntax.IsBareKey(c))
{
if (keyParts.Count != 0)
{
AddError("Encountered extra characters in key definition!");
return null;
}
if (!ReadKeyName(ref keyParts, TomlSyntax.KEY_VALUE_SEPARATOR))
return null;
continue;
}
if (TomlSyntax.IsWhiteSpace(c))
{
ConsumeChar();
continue;
}
if (c == TomlSyntax.KEY_VALUE_SEPARATOR)
{
ConsumeChar();
return ReadValue();
}
AddError($"Unexpected character \"{c}\" in key name.");
return null;
}
return null;
}
/**
* Reads a single value.
* Assumes the cursor is at the first character that belongs to the value (including possible starting whitespace).
* Consumes all characters belonging to the value (ignoring possible trailing whitespace at the end).
*
* Example:
* "test" ==> "test"
* ^ ^
*/
private TomlNode ReadValue(bool skipNewlines = false)
{
int cur;
while ((cur = reader.Peek()) >= 0)
{
var c = (char)cur;
if (TomlSyntax.IsWhiteSpace(c))
{
ConsumeChar();
continue;
}
if (c == TomlSyntax.COMMENT_SYMBOL)
{
AddError("No value found!");
return null;