internal void WriteArrayPart(TomlArray array) { this.writer.Write('['); for (int i = 0; i < array.Items.Length - 1; i++) { WriteArrayElement(array.Items[i]); this.writer.Write(", "); } if (array.Items.Length > 0) { WriteArrayElement(array.Items[array.Items.Length - 1]); } this.writer.Write(']'); void WriteArrayElement(TomlValue value) { if (value is TomlArray arr) { this.WriteArrayPart(arr); } else { this.WriteValue(value); } } }
protected void WriteArray(TomlKey key, TomlArray array) { this.writer.Write(key.ToString()); this.writer.Write(" = "); this.WriteArrayPart(array); }
private TomlArray ReadArray(StringReader reader) { //Consume the opening bracket if (!reader.ExpectAndConsume('[')) { throw new ArgumentException("Internal Tomlet Bug: ReadArray called and first char is not a ["); } //Move to the first value _lineNumber += reader.SkipAnyCommentNewlineWhitespaceEtc(); var result = new TomlArray(); while (reader.TryPeek(out _)) { //Skip any empty lines _lineNumber += reader.SkipAnyCommentNewlineWhitespaceEtc(); if (!reader.TryPeek(out var nextChar)) { throw new TomlEOFException(_lineNumber); } //Check for end of array here (helps with trailing commas, which are legal) if (nextChar.IsEndOfArrayChar()) { break; } //Read a value result.ArrayValues.Add(ReadValue(reader)); //Skip any whitespace or newlines, NOT comments - that would be a syntax error _lineNumber += reader.SkipAnyNewlineOrWhitespace(); if (!reader.TryPeek(out var postValueChar)) { throw new TomlEOFException(_lineNumber); } if (postValueChar.IsEndOfArrayChar()) { break; //end of array } if (!postValueChar.IsComma()) { throw new TomlArraySyntaxException(_lineNumber, (char)postValueChar); } reader.ExpectAndConsume(','); //We've already verified we have one. } if (!reader.ExpectAndConsume(']')) { throw new UnterminatedTomlArrayException(_lineNumber); } return(result); }
public void Visit(TomlArray a) { for (int i = 0; i < a.Length; i++) { PushContext(i.ToString()); a[i].Visit(this); PopContext(); } }
internal static string WriteTomlFragment(TomlArray array) { return(WriteIntoStream(WriteArray)); void WriteArray(FormattingStreamWriter stream) { var writer = new TomlTableWriter(stream, array.Root.Settings); writer.WriteArrayPart(array); } }
void ITomlObjectVisitor.Visit(TomlArray a) { var clrArray = new object[a.Length]; var extractItem = new ExtractItemValue(); for (int i = 0; i < a.Items.Length; i++) { a[i].Visit(extractItem); clrArray[i] = extractItem.Item; } this.table[this.currentKey] = clrArray; }
private static void ProcessArray(Dictionary <string, string> dict, TomlArray array, string fullKey) { for (int i = 0; i < array.Items.Length; i++) { if (array.Items[i] is TomlArray a) { ProcessArray(dict, a, $"{fullKey}:{i}"); } else { dict[$"{fullKey}:{i}"] = array.Items[i].ToString(); } } }
private static void ProcessArray(Dictionary <string, string> dict, TomlArray array, string fullKey) { for (int i = 0; i < array.Items.Length; i++) { if (array.Items[i] is TomlArray a) { throw new InvalidOperationException( $"AspNet provider cannot handle jagged arrays, only simple arrays are supported." + $"The arrays key is '{fullKey}'."); } dict[$"{fullKey}:{i}"] = array.Items[i].ToString(); } }
void ITomlObjectVisitor.Visit(TomlArray a) { sb.Append("{").Append("\"type\":\"array\", \"value\":["); for (int i = 0; i < a.Length - 1; i++) { a[i].Visit(this); this.sb.Append(","); } if (a.Length > 0) { a[a.Length - 1].Visit(this); } this.sb.Append("]}"); }
public static TomlArray BuildCopyPathTable(List <CopyPathMap> list) { var result = new TomlArray() { IsTableArray = true }; foreach (var entry in list) { result.Add(DictToTomlTable(new() { { "source", entry.From }, { "target", entry.To } }));
protected void WriteArray(TomlKey key, TomlArray array) { this.writer.Write(key.ToString()); this.writer.Write(" = ["); for (int i = 0; i < array.Items.Length - 1; i++) { this.WriteValue(array[i]); this.writer.Write(", "); } if (array.Items.Length > 0) { this.WriteValue(array.Items[array.Items.Length - 1]); } this.writer.Write(']'); }
protected void WriteArray(string key, TomlArray array) { this.writer.Write(key); this.writer.Write(" = ["); for (int i = 0; i < array.Items.Length - 1; i++) { this.WriteValue(array[i]); this.writer.Write(", "); } if (array.Items.Length > 0) { this.WriteValue(array.Items[array.Items.Length - 1]); } this.writer.Write(']'); }
public static LocalConfig Load(string path) { LocalConfig returnval = new LocalConfig(); if (File.Exists(path)) { string filestr = File.ReadAllText(path); if (!string.IsNullOrEmpty(filestr)) { var doc = Toml.Parse(filestr); if (doc != null) { var table = doc.ToModel(); TomlTable MainTbl = (TomlTable)table["AssemblyGenerator"]; if (MainTbl != null) { returnval.UnityVersion = (string)MainTbl["UnityVersion"]; returnval.GameAssemblyHash = (string)MainTbl["GameAssemblyHash"]; returnval.DumperVersion = (string)MainTbl["DumperVersion"]; returnval.UnhollowerVersion = (string)MainTbl["UnhollowerVersion"]; TomlArray oldfilesarr = (TomlArray)MainTbl["OldFiles"]; if (oldfilesarr.Count > 0) { for (int i = 0; i < oldfilesarr.Count; i++) { string file = (string)oldfilesarr[i]; if (!string.IsNullOrEmpty(file)) { returnval.OldFiles.Add(file); } } } } } } } return(returnval); }
private void ReadTableArrayStatement(StringReader reader, TomlDocument document) { //Consume the (second) opening bracket if (!reader.ExpectAndConsume('[')) { throw new ArgumentException("Internal Tomlet Bug: ReadTableArrayStatement called and first char is not a ["); } //Array var arrayName = reader.ReadWhile(c => !c.IsEndOfArrayChar() && !c.IsNewline()); if (!reader.ExpectAndConsume(']') || !reader.ExpectAndConsume(']')) { throw new UnterminatedTomlTableArrayException(_lineNumber); } TomlTable parentTable; if (_lastTableArrayName != null && arrayName.StartsWith(_lastTableArrayName + ".")) { //nested array of tables directly relative to parent - we can cheat //Save parent table parentTable = _currentTable !; //Work out relative key var relativeKey = arrayName.Replace(_lastTableArrayName + ".", ""); //Make new array and table var newArray = new TomlArray(); _currentTable = new TomlTable(); newArray.ArrayValues.Add(_currentTable); //Insert into parent table parentTable !.ParserPutValue(relativeKey, newArray, _lineNumber); //Save variables _lastTableArrayName = arrayName; return; } if (TomlKeyUtils.IsSimpleKey(arrayName)) { //Not present - create and populate with one table. _currentTable = new TomlTable(); TomlArray tableArray; //Simple key so looking up via document.ContainsKey is fine. if (!document.ContainsKey(arrayName)) { //make a new one if it doesn't exist tableArray = new TomlArray { IsTableArray = true } } ; else if (document.Entries.TryGetValue(arrayName, out var hopefullyArray) && hopefullyArray is TomlArray arr) { //already exists, use it tableArray = arr; } else { throw new TomlTableArrayAlreadyExistsAsNonArrayException(_lineNumber, arrayName); } if (!tableArray.IsTableArray) { throw new TomlNonTableArrayUsedAsTableArrayException(_lineNumber, arrayName); } tableArray.ArrayValues.Add(_currentTable); if (!document.ContainsKey(arrayName)) { //Insert into the document document.ParserPutValue(arrayName, tableArray, _lineNumber); } //Save variables _lastTableArrayName = arrayName; return; } //Need to add to a complex-keyed table array, so may be behind one or more table arrays. parentTable = document; var components = TomlKeyUtils.GetKeyComponents(arrayName).ToList(); //Don't check last component for (var index = 0; index < components.Count - 1; index++) { var pathComponent = components[index]; if (!parentTable.ContainsKey(pathComponent)) { throw new MissingIntermediateInTomlTableArraySpecException(_lineNumber, pathComponent); } var value = parentTable.GetValue(pathComponent); if (value is TomlArray intermediateArray) { if (intermediateArray.Last() is TomlTable table) { parentTable = table; } else { throw new TomlTableArrayIntermediateNonTableException(_lineNumber, arrayName); } } else if (value is TomlTable table) { parentTable = table; } else { throw new TomlKeyRedefinitionException(_lineNumber, pathComponent); } } var lastComponent = components.Last(); if (parentTable.ContainsKey(lastComponent)) { if (!(parentTable.GetValue(lastComponent) is TomlArray array)) { throw new TomlTableArrayAlreadyExistsAsNonArrayException(_lineNumber, lastComponent); } if (!array.IsTableArray) { throw new TomlNonTableArrayUsedAsTableArrayException(_lineNumber, arrayName); } _currentTable = new TomlTable(); array.ArrayValues.Add(_currentTable); _lastTableArrayName = arrayName; } else { var array = new TomlArray { IsTableArray = true }; _currentTable = new TomlTable(); array.ArrayValues.Add(_currentTable); parentTable.PutValue(lastComponent, array); _lastTableArrayName = arrayName; } }
private void WriteTomlArrayWithComments(TomlKey key, TomlArray array) { this.WritePrependComments(array); this.WriteArray(key, array); this.WriteAppendComments(array); }
private static TomlArray ParseTomlArray(ITomlRoot root, TokenBuffer tokens) { TomlArray a; var prep = CommentProduction.TryParseComments(tokens, CommentLocation.Prepend).ToList(); tokens.ExpectAndConsume(TokenType.LBrac); using (tokens.UseIgnoreNewlinesContext()) { prep.AddRange(CommentProduction.TryParseComments(tokens, CommentLocation.Prepend)); if (tokens.TryExpect(TokenType.RBrac)) { // Empty array handled inside this if, else part can assume the array has values // Comments in an empty array are moved before the array at the moment. // There currently does not exist a comment location that will allow to write this comments correctly // => Parse the real items correctly and do not create a parse error, but the comment will get lost // on the next write. tokens.Consume(); a = new TomlArray(root); a.Comments.AddRange(prep); return(a); } else { List <TomlValue> values = new List <TomlValue>(); // Parse first !required! array value var v = ParseArrayValue(); v.Comments.AddRange(prep); values.Add(v); while (!tokens.TryExpect(TokenType.RBrac)) { if (!tokens.TryExpectAndConsume(TokenType.Comma)) { throw Parser.CreateParseError(tokens.Peek(), "Array not closed."); } // This comment is misplaced as we simply append it to the last value, but it does not belong to it // Comments processing needs some tweaking/redesign in the future. v.Comments.AddRange(CommentProduction.TryParseComments(tokens, CommentLocation.Append)); if (!tokens.TryExpect(TokenType.RBrac)) { var et = tokens.Peek(); v = ParseArrayValue(); if (v.GetType() != values[0].GetType()) { throw Parser.CreateParseError(et, $"Expected array value of type '{values[0].ReadableTypeName}' but value of type '{v.ReadableTypeName}' was found."); } values.Add(v); } } a = new TomlArray(root, values.ToArray()); } a.Last().Comments.AddRange(CommentProduction.TryParseComments(tokens, CommentLocation.Append)); tokens.ExpectAndConsume(TokenType.RBrac); a.Comments.AddRange(CommentProduction.TryParseComments(tokens, CommentLocation.Append)); TomlValue ParseArrayValue() { var prepComments = CommentProduction.TryParseComments(tokens, CommentLocation.Prepend); var valueParseErrorPos = tokens.Peek(); var value = ParseTomlValue(root, tokens); if (value == null) { throw Parser.CreateParseError(valueParseErrorPos, $"Array value is missing."); } value.Comments.AddRange(prepComments); value.Comments.AddRange(CommentProduction.TryParseComments(tokens, CommentLocation.Append)); return(value); } } return(a); }
static Config() { FilePath = Path.Combine(Core.BasePath, "Config.cfg"); if (!File.Exists(FilePath)) { Save(); return; } string filestr = File.ReadAllText(FilePath); if (string.IsNullOrEmpty(filestr)) { return; } DocumentSyntax docsyn = Toml.Parse(filestr); if (docsyn == null) { return; } TomlTable model = docsyn.ToModel(); if (model.Count <= 0) { return; } TomlTable tbl = (TomlTable)model["AssemblyGenerator"]; if (tbl == null) { return; } if (tbl.ContainsKey("UnityVersion")) { UnityVersion = (string)tbl["UnityVersion"]; } if (tbl.ContainsKey("Cpp2IL")) { Cpp2ILVersion = (string)tbl["Cpp2IL"]; } if (tbl.ContainsKey("Il2CppAssemblyUnhollower")) { Il2CppAssemblyUnhollowerVersion = (string)tbl["Il2CppAssemblyUnhollower"]; } if (tbl.ContainsKey("GameAssemblyHash")) { GameAssemblyHash = (string)tbl["GameAssemblyHash"]; } if (!tbl.ContainsKey("OldFiles")) { return; } TomlArray oldfilesarr = (TomlArray)tbl["OldFiles"]; if (oldfilesarr.Count <= 0) { return; } for (int i = 0; i < oldfilesarr.Count; i++) { string file = (string)oldfilesarr[i]; if (!string.IsNullOrEmpty(file)) { OldFiles.Add(file); } } }
public void Visit(TomlArray a) { var clrArray = new object[a.Length]; var extractItem = new ExtractItemValue(); for (int i = 0; i < a.Items.Length; i++) { a[i].Visit(extractItem); clrArray[i] = extractItem.Item; } this.Item = clrArray; }
private void WriteTomlArrayWithComments(string key, TomlArray array) { this.WritePrependComments(array); this.WriteArray(key, array); this.WriteAppendComments(array); }
private static TomlArray ParseTomlArray(ITomlRoot root, TokenBuffer tokens) { TomlArray a; tokens.ExpectAndConsume(TokenType.LBrac); tokens.ConsumeAllNewlines(); if (tokens.TryExpect(TokenType.RBrac)) { // Empty array handled inside this if, else part can assume the array has values tokens.Consume(); return new TomlArray(root); } else { List<TomlValue> values = new List<TomlValue>(); var errPos = tokens.Peek(); var v = ParseTomlValue(root, tokens); if (v == null) { throw Parser.CreateParseError(errPos, $"Array value is missing."); } values.Add(v); while (!tokens.TryExpect(TokenType.RBrac)) { if (!tokens.TryExpectAndConsume(TokenType.Comma)) { throw Parser.CreateParseError(tokens.Peek(), "Array not closed."); } tokens.ConsumeAllNewlines(); values.Last().Comments.AddRange(CommentProduction.TryParseComments(tokens, CommentLocation.Append)); if (!tokens.TryExpect(TokenType.RBrac)) { var et = tokens.Peek(); v = ParseTomlValue(root, tokens); if (v == null) { throw Parser.CreateParseError(et, $"Array value is missing."); } if (v.GetType() != values[0].GetType()) { throw Parser.CreateParseError(et, $"Expected value of type '{values[0].ReadableTypeName}' but value of type '{v.ReadableTypeName}' was found."); } values.Add(v); tokens.ConsumeAllNewlines(); } } a = new TomlArray(root, values.ToArray()); } a.Last().Comments.AddRange(CommentProduction.TryParseComments(tokens, CommentLocation.Append)); tokens.ExpectAndConsume(TokenType.RBrac); return a; }
private static TomlObject ToTomlValue(ITomlRoot root, ValueNode node) { switch (node.Value.SyntaxNode()) { case TerminalNode tn: return(CreateValueFromTerminal(tn.Terminal)); case ArrayNode an: return(CreateArrayOrTableArray(an)); case InlineTableNode it: return(CreateInlineTable(it)); default: throw new Exception($"Cannot create TomlValue from node with type '{node.GetType()}'."); } TomlValue CreateValueFromTerminal(Token terminal) { switch (terminal.Type) { case TokenType.Integer: return(new TomlInt(root, Convert.ToInt64(Cleanup(terminal.Value, 0)), TomlInt.IntTypes.Decimal)); case TokenType.HexInteger: return(new TomlInt(root, Convert.ToInt64(Cleanup(terminal.Value, 2), 16), TomlInt.IntTypes.Hex)); case TokenType.BinaryInteger: return(new TomlInt(root, Convert.ToInt64(Cleanup(terminal.Value, 2), 2), TomlInt.IntTypes.Binary)); case TokenType.OctalInteger: return(new TomlInt(root, Convert.ToInt64(Cleanup(terminal.Value, 2), 8), TomlInt.IntTypes.Octal)); case TokenType.Bool: return(new TomlBool(root, Convert.ToBoolean(terminal.Value))); case TokenType.String: return(new TomlString(root, terminal.Value.Unescape(terminal))); case TokenType.LiteralString: return(new TomlString(root, terminal.Value, TomlString.TypeOfString.Literal)); case TokenType.MultilineLiteralString: return(new TomlString(root, terminal.Value, TomlString.TypeOfString.MultilineLiteral)); case TokenType.MultilineString: return(new TomlString(root, terminal.Value, TomlString.TypeOfString.Multiline)); case TokenType.Float: return(TomlFloat.FromTerminal(root, terminal)); case TokenType.OffsetDateTime: return(TomlOffsetDateTime.Parse(root, terminal.Value)); case TokenType.LocalTime: return(TomlLocalTime.Parse(root, terminal.Value)); case TokenType.Duration: return(TomlDuration.Parse(root, terminal.Value)); case TokenType.LocalDate: return(TomlLocalDate.Parse(root, terminal.Value)); case TokenType.LocalDateTime: return(TomlLocalDateTime.Parse(root, terminal.Value)); default: throw new NotSupportedException(); } string Cleanup(string s, int sub) => s.Substring(sub).Replace("_", string.Empty); } TomlObject CreateArrayOrTableArray(ArrayNode array) { var values = CreateValues(array.GetValues()).ToList(); var tables = values.OfType <TomlTable>().ToList(); if (tables.Count > 0 && tables.Count == values.Count) { var ta = new TomlTableArray(root, tables); ta.AddComments(array); return(ta); } else if (tables.Count == 0) { var arr = new TomlArray(root, values.Cast <TomlValue>().ToArray()); arr.AddComments(array); return(arr); } else { throw new InvalidOperationException("Array is a mixture of a value array and a TOML table array."); } IEnumerable <TomlObject> CreateValues(IEnumerable <ValueNode> nodes) { var linked = nodes.Select(n => Tuple.Create(n, ToTomlValue(root, n))).ToList(); var expectedType = linked.DistinctBy(n => n.Item2.GetType()).FirstOrDefault(); var wrongType = linked.DistinctBy(n => n.Item2.GetType()).Skip(1).FirstOrDefault(); if (wrongType != null) { string msg = $"Expected array value of type '{expectedType.Item2.ReadableTypeName}' " + $"but value of type '{wrongType.Item2.ReadableTypeName}' was found.'"; throw ParseException.MessageForNode(wrongType.Item1, msg); } return(linked.Select(l => l.Item2)); } } TomlTable CreateInlineTable(InlineTableNode it) { TomlTable table = new TomlTable(root, TomlTable.TableTypes.Inline); table.AddComments(it); System.Collections.Generic.IEnumerable <KeyValueExpressionNode> expressions = it.GetExpressions(); foreach (KeyValueExpressionNode e in expressions) { table.AddRow(e.Key.SyntaxNode().ExpressionKey(), ToTomlValue(root, e.Value.SyntaxNode())); } return(table); } }