In ToString methods, maps are sorted alphabetically before output

This makes the output of ToString methods deterministic, and as such they can be
used for testing.
This commit is contained in:
Sasha Koshka 2022-08-17 13:50:33 -04:00
parent aee90757e3
commit 98fb4e9c66
1 changed files with 23 additions and 3 deletions

View File

@ -1,6 +1,7 @@
package parser package parser
import "fmt" import "fmt"
import "sort"
func doIndent (indent int, input ...string) (output string) { func doIndent (indent int, input ...string) (output string) {
for index := 0; index < indent; index ++ { for index := 0; index < indent; index ++ {
@ -12,6 +13,22 @@ func doIndent (indent int, input ...string) (output string) {
return return
} }
func sortMapKeysAlphabetically[KEY_TYPE any] (
unsortedMap map[string] KEY_TYPE,
) (
sortedKeys []string,
) {
sortedKeys = make([]string, len(unsortedMap))
index := 0
for key, _ := range unsortedMap {
sortedKeys[index] = key
index ++
}
sort.Strings(sortedKeys)
return
}
func (tree *SyntaxTree) ToString (indent int) (output string) { func (tree *SyntaxTree) ToString (indent int) (output string) {
output += doIndent(indent, ":arf\n") output += doIndent(indent, ":arf\n")
@ -29,8 +46,9 @@ func (tree *SyntaxTree) ToString (indent int) (output string) {
output += doIndent(indent, "---\n") output += doIndent(indent, "---\n")
for _, require := range tree.dataSections { dataSectionKeys := sortMapKeysAlphabetically(tree.dataSections)
output += require.ToString(indent) for _, name := range dataSectionKeys {
output += tree.dataSections[name].ToString(indent)
} }
return return
} }
@ -83,7 +101,9 @@ func (attributes *ObjectInitializationValues) ToString (
) ( ) (
output string, output string,
) { ) {
for name, value := range attributes.attributes { for _, name := range sortMapKeysAlphabetically(attributes.attributes) {
value := attributes.attributes[name]
output += doIndent(indent, ".", name, " ") output += doIndent(indent, ".", name, " ")
if value.kind == ArgumentKindObjectInitializationValues { if value.kind == ArgumentKindObjectInitializationValues {
output += "\n" output += "\n"