this repo has no description
at master 89 lines 2.7 kB view raw
1// Copyright 2024 CUE Authors 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14 15package astinternal_test 16 17import ( 18 "path" 19 "reflect" 20 "regexp" 21 "strings" 22 "testing" 23 24 "cuelang.org/go/cue/ast" 25 "cuelang.org/go/cue/parser" 26 "cuelang.org/go/internal/astinternal" 27 "cuelang.org/go/internal/cuetxtar" 28 29 "github.com/go-quicktest/qt" 30) 31 32var ptrPat = regexp.MustCompile(`0x[0-9a-z]+`) 33 34func TestDebugPrint(t *testing.T) { 35 test := cuetxtar.TxTarTest{ 36 Root: "testdata", 37 Name: "debugprint", 38 } 39 40 test.Run(t, func(t *cuetxtar.Test) { 41 includePointers := t.HasTag("includePointers") 42 allPositions := t.HasTag("allPositions") 43 for _, file := range t.Archive.Files { 44 if strings.HasPrefix(file.Name, "out/") { 45 continue 46 } 47 48 f, err := parser.ParseFile(file.Name, file.Data, parser.ParseComments, parser.Version("v0.13.0")) 49 qt.Assert(t, qt.IsNil(err)) 50 51 // The full syntax tree, as printed by default. 52 // We enable IncludeNodeRefs because it only adds information 53 // that would not otherwise be present. 54 // The syntax tree does not contain any maps, so 55 // the generated reference names should be deterministic. 56 full := astinternal.AppendDebug(nil, f, astinternal.DebugConfig{ 57 IncludeNodeRefs: true, 58 IncludePointers: includePointers, 59 AllPositions: allPositions, 60 }) 61 if includePointers { 62 // Pointer values change between runs. Replace with a constant 63 // string so that we can test stable output. 64 full = ptrPat.ReplaceAll(full, []byte("XXXX")) 65 } 66 t.Writer(file.Name).Write(full) 67 68 // A syntax tree which omits any empty values, 69 // and is only interested in showing string fields. 70 // We allow ast.Nodes and slices to not stop too early. 71 typNode := reflect.TypeFor[ast.Node]() 72 strings := astinternal.AppendDebug(nil, f, astinternal.DebugConfig{ 73 OmitEmpty: true, 74 Filter: func(v reflect.Value) bool { 75 if v.Type().Implements(typNode) { 76 return true 77 } 78 switch v.Kind() { 79 case reflect.Slice, reflect.String: 80 return true 81 default: 82 return false 83 } 84 }, 85 }) 86 t.Writer(path.Join(file.Name, "omitempty-strings")).Write(strings) 87 } 88 }) 89}