├── .github
├── FUNDING.yml
├── pull_request_template.md
└── workflows
│ ├── go-ci.yml
│ └── golangci-lint.yml
├── LICENSE
├── LICENSE-APACHE
├── LICENSE-MIT
├── README.md
├── cycle_detector.go
├── format_composite_literals.go
├── go.mod
├── go.sum
├── internal
├── bypass
│ ├── doc.go
│ ├── main.go
│ └── main_js.go
├── customtype
│ └── customtype.go
└── test
│ ├── complex_recursive.go
│ └── test.go
├── profiler.go
├── ptr.go
├── stdtypes.go
├── testdata
├── TestEdgeCases__nil_interface_pointer.golden
├── TestEdgeCases__ptr2_to_nil_interface.golden
├── TestEdgeCases__ptr3_to_nil_interface.golden
├── TestEdgeCases__ptr_to_interface.golden
├── TestEdgeCases__ptr_to_nil_interface.golden
├── TestEdgeCases__ptr_to_ptr_to_interface.golden
├── TestExportedOnly_input__array.golden
├── TestExportedOnly_input__bool.golden
├── TestExportedOnly_input__complex128.golden
├── TestExportedOnly_input__complex64.golden
├── TestExportedOnly_input__float32.golden
├── TestExportedOnly_input__float64.golden
├── TestExportedOnly_input__int.golden
├── TestExportedOnly_input__int16.golden
├── TestExportedOnly_input__int32.golden
├── TestExportedOnly_input__int64.golden
├── TestExportedOnly_input__int8.golden
├── TestExportedOnly_input__interface.golden
├── TestExportedOnly_input__map.golden
├── TestExportedOnly_input__map_unexported_key_omitted.golden
├── TestExportedOnly_input__map_unexported_key_type.golden
├── TestExportedOnly_input__map_unexported_value_omitted.golden
├── TestExportedOnly_input__map_unexported_value_type.golden
├── TestExportedOnly_input__pointer.golden
├── TestExportedOnly_input__slice.golden
├── TestExportedOnly_input__string.golden
├── TestExportedOnly_input__struct.golden
├── TestExportedOnly_input__struct_same_package.golden
├── TestExportedOnly_input__uint.golden
├── TestExportedOnly_input__uint16.golden
├── TestExportedOnly_input__uint32.golden
├── TestExportedOnly_input__uint64.golden
├── TestExportedOnly_input__uint8.golden
├── TestExportedOnly_input__uintptr.golden
├── TestExportedOnly_input__unsafe_pointer.golden
├── TestExportedOnly_nested__external_struct_unexported_field_omitted.golden
├── TestExportedOnly_nested__interface.golden
├── TestExportedOnly_nested__struct_same_package_unexported_field_omitted.golden
├── TestIssue15_addr_values_must_be_qualified.golden
├── TestPointers__array.golden
├── TestPointers__array2.golden
├── TestPointers__bool.golden
├── TestPointers__bool2.golden
├── TestPointers__complex128.golden
├── TestPointers__complex64.golden
├── TestPointers__float32.golden
├── TestPointers__float64.golden
├── TestPointers__int.golden
├── TestPointers__int16.golden
├── TestPointers__int2.golden
├── TestPointers__int3.golden
├── TestPointers__int32.golden
├── TestPointers__int64.golden
├── TestPointers__int8.golden
├── TestPointers__interface.golden
├── TestPointers__interface2.golden
├── TestPointers__map.golden
├── TestPointers__map2.golden
├── TestPointers__pointer.golden
├── TestPointers__pointer2.golden
├── TestPointers__slice.golden
├── TestPointers__slice2.golden
├── TestPointers__string.golden
├── TestPointers__struct.golden
├── TestPointers__struct2.golden
├── TestPointers__time_local.golden
├── TestPointers__time_utc.golden
├── TestPointers__uint.golden
├── TestPointers__uint16.golden
├── TestPointers__uint32.golden
├── TestPointers__uint64.golden
├── TestPointers__uint8.golden
├── TestPointers__uintptr.golden
├── TestPointers__unsafe_pointer.golden
├── TestPointers__unsafe_pointer2.golden
├── TestRecursion__basic.golden
├── TestRecursion__struct_cyclic.golden
├── TestStringFormatting__long_multi_line_180.golden
├── TestStringFormatting__long_multi_line_with_backticks.golden
├── TestStringFormatting__long_multi_line_with_quotes.golden
├── TestStringFormatting__long_single_line_180.golden
├── TestStringFormatting__short_multi_line.golden
├── TestStringFormatting__short_quotes.golden
├── TestStringFormatting__short_single_line.golden
├── TestString__array.golden
├── TestString__bool.golden
├── TestString__bool_unqualify.golden
├── TestString__complex64.golden
├── TestString__complex64_unqualify.golden
├── TestString__float64.golden
├── TestString__float64_unqualify.golden
├── TestString__int32.golden
├── TestString__int32_unqualify.golden
├── TestString__interface.golden
├── TestString__interface_anonymous.golden
├── TestString__interface_anonymous_nil.golden
├── TestString__interface_builtin.golden
├── TestString__map.golden
├── TestString__nil.golden
├── TestString__slice.golden
├── TestString__string.golden
├── TestString__string_unqualify.golden
├── TestString__struct_anonymous.golden
├── TestString__struct_external_package.golden
├── TestString__struct_same_package.golden
├── TestString__time_local.golden
├── TestString__time_utc.golden
├── TestString__uintptr.golden
├── TestString__uintptr_unqualify.golden
├── TestString__unsafe_pointer.golden
├── TestUnexportedInputs__array.golden
├── TestUnexportedInputs__bool.golden
├── TestUnexportedInputs__complex128.golden
├── TestUnexportedInputs__complex64.golden
├── TestUnexportedInputs__float32.golden
├── TestUnexportedInputs__float64.golden
├── TestUnexportedInputs__int.golden
├── TestUnexportedInputs__int16.golden
├── TestUnexportedInputs__int32.golden
├── TestUnexportedInputs__int64.golden
├── TestUnexportedInputs__int8.golden
├── TestUnexportedInputs__interface.golden
├── TestUnexportedInputs__map.golden
├── TestUnexportedInputs__pointer.golden
├── TestUnexportedInputs__slice.golden
├── TestUnexportedInputs__string.golden
├── TestUnexportedInputs__struct.golden
├── TestUnexportedInputs__uint.golden
├── TestUnexportedInputs__uint16.golden
├── TestUnexportedInputs__uint32.golden
├── TestUnexportedInputs__uint64.golden
├── TestUnexportedInputs__uint8.golden
├── TestUnexportedInputs__uintptr.golden
└── TestUnexportedInputs__unsafe_pointer.golden
├── types.go
├── util.go
├── valast.go
└── valast_test.go
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | github: slimsag
2 |
--------------------------------------------------------------------------------
/.github/pull_request_template.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | - [ ] By selecting this checkbox, I agree to license my contributions to this project under the license(s) described in the LICENSE file, and I have the right to do so or have received permission to do so by an employer or client I am producing work for whom has this right.
--------------------------------------------------------------------------------
/.github/workflows/go-ci.yml:
--------------------------------------------------------------------------------
1 | name: Go CI
2 | on:
3 | - push
4 | - pull_request
5 | jobs:
6 | test:
7 | runs-on: ubuntu-latest
8 | steps:
9 | - name: Checkout
10 | uses: actions/checkout@v3
11 | - name: Setup Go
12 | uses: actions/setup-go@v3
13 | with:
14 | go-version: ^1
15 | - run: go test ./...
16 | - run: go test -race -coverprofile=coverage.txt -covermode=atomic ./...
17 | - name: Upload code coverage
18 | uses: codecov/codecov-action@v1
19 | with:
20 | file: ./coverage.txt
21 |
--------------------------------------------------------------------------------
/.github/workflows/golangci-lint.yml:
--------------------------------------------------------------------------------
1 | name: golangci-lint
2 | on:
3 | - push
4 | - pull_request
5 | jobs:
6 | lint:
7 | runs-on: ubuntu-latest
8 | steps:
9 | - name: Checkout
10 | uses: actions/checkout@v3
11 | - name: Setup Go
12 | uses: actions/setup-go@v3
13 | with:
14 | go-version: ^1
15 | - name: golangci-lint
16 | uses: golangci/golangci-lint-action@v3
17 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright 2020, The Valast Project Developers (given via the Git commit history).
2 |
3 | Licensed under the Apache License, Version 2.0 (see LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
4 | or the MIT license (see LICENSE-MIT or http://opensource.org/licenses/MIT), at
5 | your option. All files in the project without exclusions may not be copied,
6 | modified, or distributed except according to those terms.
7 |
--------------------------------------------------------------------------------
/LICENSE-APACHE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/LICENSE-MIT:
--------------------------------------------------------------------------------
1 | Copyright (c) 2020 The Valast Project Developers (given via the Git commit history).
2 |
3 | Permission is hereby granted, free of charge, to any
4 | person obtaining a copy of this software and associated
5 | documentation files (the "Software"), to deal in the
6 | Software without restriction, including without
7 | limitation the rights to use, copy, modify, merge,
8 | publish, distribute, sublicense, and/or sell copies of
9 | the Software, and to permit persons to whom the Software
10 | is furnished to do so, subject to the following
11 | conditions:
12 |
13 | The above copyright notice and this permission notice
14 | shall be included in all copies or substantial portions
15 | of the Software.
16 |
17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25 | DEALINGS IN THE SOFTWARE.
26 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # valast - convert Go values to their AST
2 |
3 |
4 |
5 | [](https://github.com/hexops/valast/actions) [](https://codecov.io/gh/hexops/valast) [](https://goreportcard.com/report/github.com/hexops/valast)
6 |
7 | Valast converts Go values at runtime into their `go/ast` equivalent, e.g.:
8 |
9 | ```Go
10 | x := &foo.Bar{
11 | a: "hello world!",
12 | B: 1.234,
13 | }
14 | fmt.Println(valast.String(x))
15 | ```
16 |
17 | Prints string:
18 |
19 | ```Go
20 | &foo.Bar{a: "hello world!", B: 1.234}
21 | ```
22 |
23 | ## What is this useful for?
24 |
25 | This can be useful for debugging and testing, you may think of it as a more comprehensive and configurable version of the `fmt` package's `%+v` and `%#v` formatting directives. It is similar to e.g. `repr` in Python.
26 |
27 | ## Features
28 |
29 | - Produces Go code via a `go/ast`, defers formatting to the best-in-class Go formatter [gofumpt](https://github.com/mvdan/gofumpt).
30 | - Fully handles unexported fields, types, and values (optional.)
31 | - Strong emphasis on being used for producing valid Go code that can be copy & pasted directly into e.g. tests.
32 | - [Extensively tested](https://github.com/hexops/valast/tree/main/testdata), over 88 tests and handling numerous edge cases (such as pointers to unaddressable literal values like `&"foo"` properly, and even [finding bugs in alternative packages'](https://github.com/shurcooL/go-goon/issues/15)).
33 | - Provide custom AST representations for your types with `valast.RegisterType(...)`.
34 |
35 | ## Alternatives comparison
36 |
37 | The following are alternatives to Valast, making note of the differences we found that let us to create Valast:
38 |
39 | - [github.com/davecgh/go-spew](https://github.com/davecgh/go-spew)
40 | - [may be inactive](https://github.com/davecgh/go-spew/issues/128)
41 | - Produces Go-like output, but not Go syntax.
42 | - [github.com/shurcooL/go-goon](https://github.com/shurcooL/go-goon) (based on go-spew)
43 | - Produces valid Go syntax, but not via a `go/ast`.
44 | - [Produces less idiomatic/terse results](https://github.com/shurcooL/go-goon/issues/11))
45 | - Was deprecated in favor of valast.
46 | - [github.com/alecthomas/repr](https://github.com/alecthomas/repr)
47 | - Produces Go syntax, but not always valid code (e.g. can emit illegal `&23`, whereas Valast will emit a valid expression `valast.Addr(23).(int)`), not via a `go/ast`.
48 | - [Does not handle unexported fields/types/values.](https://github.com/alecthomas/repr/pull/13)
49 |
50 | You may also wish to look at [autogold](https://github.com/hexops/autogold) and [go-cmp](https://github.com/google/go-cmp), which aim to solve the "compare Go values in a test" problem.
51 |
--------------------------------------------------------------------------------
/cycle_detector.go:
--------------------------------------------------------------------------------
1 | package valast
2 |
3 | type cycleDetector struct {
4 | seen map[interface{}]int
5 | }
6 |
7 | func (c *cycleDetector) push(ptr interface{}) bool {
8 | if c.seen == nil {
9 | c.seen = map[interface{}]int{}
10 | }
11 | cycles, seen := c.seen[ptr]
12 | if seen && cycles > 1 {
13 | return true
14 | }
15 | c.seen[ptr] = cycles + 1
16 | return false
17 | }
18 |
19 | func (c *cycleDetector) pop(ptr interface{}) {
20 | cycles := c.seen[ptr]
21 | cycles--
22 | if cycles < 0 {
23 | cycles = 0
24 | }
25 | c.seen[ptr] = cycles
26 | }
27 |
--------------------------------------------------------------------------------
/format_composite_literals.go:
--------------------------------------------------------------------------------
1 | package valast
2 |
3 | func formatCompositeLiterals(input []rune) []rune {
4 | var (
5 | inStringLiteral, inRawStringLiteral bool
6 | depth int
7 | breakFields bool
8 | lineWidth int
9 | result []rune
10 | )
11 | for i, r := range input {
12 | switch {
13 | case inStringLiteral || inRawStringLiteral:
14 | // Reading a string literal.
15 | switch {
16 | case inStringLiteral:
17 | if r == '"' && (i == 0 || input[i-1] != '\\') {
18 | inStringLiteral = false
19 | }
20 | case inRawStringLiteral:
21 | if r == '`' {
22 | inRawStringLiteral = false
23 | }
24 | }
25 | if r == '\n' {
26 | depth = 0
27 | lineWidth = 0
28 | } else {
29 | lineWidth++
30 | }
31 | result = append(result, r)
32 | default:
33 | if r == '"' {
34 | inStringLiteral = true
35 | result = append(result, r)
36 | break
37 | }
38 | if r == '`' {
39 | inRawStringLiteral = true
40 | result = append(result, r)
41 | break
42 | }
43 | if r == '\n' {
44 | depth = 0
45 | lineWidth = 0
46 | } else {
47 | lineWidth++
48 | }
49 | if lineWidth >= 50 {
50 | breakFields = true
51 | }
52 | if r == ',' && breakFields {
53 | result = append(result, r)
54 | result = append(result, '\n')
55 | break
56 | }
57 | if r == '{' {
58 | depth++
59 | if depth >= 2 {
60 | depth = 0
61 | breakFields = true
62 | result = append(result, r)
63 | result = append(result, '\n')
64 | break
65 | }
66 | }
67 | if r == '}' {
68 | depth--
69 | if depth >= 2 {
70 | depth = 0
71 | breakFields = false
72 | result = append(result, r)
73 | result = append(result, ',')
74 | result = append(result, '\n')
75 | break
76 | }
77 | }
78 | result = append(result, r)
79 | }
80 | }
81 | return result
82 | }
83 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/hexops/valast
2 |
3 | go 1.20
4 |
5 | require (
6 | github.com/hexops/autogold v0.8.1
7 | golang.org/x/tools v0.4.0
8 | mvdan.cc/gofumpt v0.4.0
9 | )
10 |
11 | require (
12 | github.com/google/go-cmp v0.5.9 // indirect
13 | github.com/hexops/gotextdiff v1.0.3 // indirect
14 | golang.org/x/mod v0.7.0 // indirect
15 | golang.org/x/sys v0.3.0 // indirect
16 | )
17 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/frankban/quicktest v1.14.3 h1:FJKSZTDHjyhriyC81FLQ0LY93eSai0ZyR/ZIkd3ZUKE=
2 | github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
3 | github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
4 | github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
5 | github.com/hexops/autogold v0.8.1 h1:wvyd/bAJ+Dy+DcE09BoLk6r4Fa5R5W+O+GUzmR985WM=
6 | github.com/hexops/autogold v0.8.1/go.mod h1:97HLDXyG23akzAoRYJh/2OBs3kd80eHyKPvZw0S5ZBY=
7 | github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM=
8 | github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg=
9 | github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
10 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
11 | github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
12 | golang.org/x/mod v0.7.0 h1:LapD9S96VoQRhi/GrNTqeBJFrUjs5UHCAtTlgwA5oZA=
13 | golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
14 | golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
15 | golang.org/x/sys v0.3.0 h1:w8ZOecv6NaNa/zC8944JTU3vz4u6Lagfk4RPQxv92NQ=
16 | golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
17 | golang.org/x/tools v0.4.0 h1:7mTAgkunk3fr4GAloyyCasadO6h9zSsQZbwvcaIciV4=
18 | golang.org/x/tools v0.4.0/go.mod h1:UE5sM2OK9E/d67R0ANs2xJizIymRP5gJU295PvKXxjQ=
19 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
20 | mvdan.cc/gofumpt v0.4.0 h1:JVf4NN1mIpHogBj7ABpgOyZc65/UUOkKQFkoURsz4MM=
21 | mvdan.cc/gofumpt v0.4.0/go.mod h1:PljLOHDeZqgS8opHRKLzp2It2VBuSdteAgqUfzMTxlQ=
22 |
--------------------------------------------------------------------------------
/internal/bypass/doc.go:
--------------------------------------------------------------------------------
1 | // Package bypass allows bypassing reflect restrictions on accessing unexported struct fields.
2 | package bypass
3 |
--------------------------------------------------------------------------------
/internal/bypass/main.go:
--------------------------------------------------------------------------------
1 | //go:build !js
2 | // +build !js
3 |
4 | package bypass
5 |
6 | import (
7 | "reflect"
8 | "unsafe"
9 | )
10 |
11 | // This code used to match unexported code in https://github.com/davecgh/go-spew/blob/master/spew/common.go
12 | // in 2014 or so.
13 |
14 | const (
15 | // ptrSize is the size of a pointer on the current arch.
16 | ptrSize = unsafe.Sizeof((*byte)(nil))
17 | )
18 |
19 | var (
20 | // offsetPtr, offsetScalar, and offsetFlag are the offsets for the
21 | // internal reflect.Value fields. These values are valid before golang
22 | // commit ecccf07e7f9d which changed the format. The are also valid
23 | // after commit 82f48826c6c7 which changed the format again to mirror
24 | // the original format. Code in the init function updates these offsets
25 | // as necessary.
26 | offsetPtr = ptrSize
27 | offsetScalar = uintptr(0)
28 | offsetFlag = ptrSize * 2
29 |
30 | // flagKindWidth and flagKindShift indicate various bits that the
31 | // reflect package uses internally to track kind information.
32 | //
33 | // flagIndir indicates whether the value field of a reflect.Value is
34 | // the actual data or a pointer to the data.
35 | //
36 | // These values are valid before golang commit 90a7c3c86944 which
37 | // changed their positions. Code in the init function updates these
38 | // flags as necessary.
39 | flagKindWidth = uintptr(5)
40 | flagKindShift = flagKindWidth - 1
41 | flagIndir = uintptr(1 << 1)
42 | )
43 |
44 | func init() {
45 | // Older versions of reflect.Value stored small integers directly in the
46 | // ptr field (which is named val in the older versions). Versions
47 | // between commits ecccf07e7f9d and 82f48826c6c7 added a new field named
48 | // scalar for this purpose which unfortunately came before the flag
49 | // field, so the offset of the flag field is different for those
50 | // versions.
51 | //
52 | // This code constructs a new reflect.Value from a known small integer
53 | // and checks if the size of the reflect.Value struct indicates it has
54 | // the scalar field. When it does, the offsets are updated accordingly.
55 | vv := reflect.ValueOf(0xf00)
56 | if unsafe.Sizeof(vv) == (ptrSize * 4) {
57 | offsetScalar = ptrSize * 2
58 | offsetFlag = ptrSize * 3
59 | }
60 |
61 | // Commit 90a7c3c86944 changed the flag positions such that the low
62 | // order bits are the kind. This code extracts the kind from the flags
63 | // field and ensures it's the correct type. When it's not, the flag
64 | // order has been changed to the newer format, so the flags are updated
65 | // accordingly.
66 | upf := unsafe.Pointer(uintptr(unsafe.Pointer(&vv)) + offsetFlag)
67 | upfv := *(*uintptr)(upf)
68 | flagKindMask := uintptr((1<>flagKindShift != uintptr(reflect.Int) {
70 | flagKindShift = 0
71 | flagIndir = 1 << 6
72 |
73 | // Commit adf9b30e5594 modified the flags to separate the
74 | // flagRO flag into two bits which specifies whether or not the
75 | // field is embedded. This causes flagIndir to move over a bit
76 | // and means that flagRO is the combination of either of the
77 | // original flagRO bit and the new bit.
78 | //
79 | // This code detects the change by extracting what used to be
80 | // the indirect bit to ensure it's set. When it's not, the flag
81 | // order has been changed to the newer format, so the flags are
82 | // updated accordingly.
83 | if upfv&flagIndir == 0 {
84 | flagIndir = 1 << 7
85 | }
86 | }
87 | }
88 |
89 | // UnsafeReflectValue converts the passed reflect.Value into a one that bypasses
90 | // the typical safety restrictions preventing access to unaddressable and
91 | // unexported data. It works by digging the raw pointer to the underlying
92 | // value out of the protected value and generating a new unprotected (unsafe)
93 | // reflect.Value to it.
94 | //
95 | // This allows us to check for implementations of the Stringer and error
96 | // interfaces to be used for pretty printing ordinarily unaddressable and
97 | // inaccessible values such as unexported struct fields.
98 | func UnsafeReflectValue(v reflect.Value) (rv reflect.Value) {
99 | indirects := 1
100 | vt := v.Type()
101 | upv := unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetPtr)
102 | rvf := *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetFlag))
103 | if rvf&flagIndir != 0 {
104 | vt = reflect.PtrTo(v.Type())
105 | indirects++
106 | } else if offsetScalar != 0 {
107 | // The value is in the scalar field when it's not one of the
108 | // reference types.
109 | switch vt.Kind() {
110 | case reflect.Uintptr:
111 | case reflect.Chan:
112 | case reflect.Func:
113 | case reflect.Map:
114 | case reflect.Ptr:
115 | case reflect.UnsafePointer:
116 | default:
117 | upv = unsafe.Pointer(uintptr(unsafe.Pointer(&v)) +
118 | offsetScalar)
119 | }
120 | }
121 |
122 | pv := reflect.NewAt(vt, upv)
123 | rv = pv
124 | for i := 0; i < indirects; i++ {
125 | rv = rv.Elem()
126 | }
127 | return rv
128 | }
129 |
--------------------------------------------------------------------------------
/internal/bypass/main_js.go:
--------------------------------------------------------------------------------
1 | //go:build js
2 | // +build js
3 |
4 | package bypass
5 |
6 | import "reflect"
7 |
8 | func UnsafeReflectValue(v reflect.Value) reflect.Value {
9 | // This is just a stub. Do more when a testable need arises.
10 | return v
11 | }
12 |
--------------------------------------------------------------------------------
/internal/customtype/customtype.go:
--------------------------------------------------------------------------------
1 | package customtype
2 |
3 | import (
4 | "fmt"
5 | "go/ast"
6 | "reflect"
7 | "sync"
8 | )
9 |
10 | var (
11 | customTypesMux sync.Mutex
12 | customTypes = make(map[reflect.Type]func(any) ast.Expr)
13 | )
14 |
15 | // See the top-level valast.RegisterType docstring for details.
16 | func Register[T any](render func(value T) ast.Expr) {
17 | customTypesMux.Lock()
18 | var zero T
19 | t := reflect.TypeOf(zero)
20 | if _, exists := customTypes[t]; exists {
21 | panic(fmt.Sprintf("%T already registered", zero))
22 | }
23 | customTypes[t] = func(value any) ast.Expr { return render(value.(T)) }
24 | customTypesMux.Unlock()
25 | }
26 |
27 | // Is indicates if the given reflect.Type has a custom AST representation
28 | // generator registered.
29 | func Is(rt reflect.Type) (func(any) ast.Expr, bool) {
30 | customTypesMux.Lock()
31 | defer customTypesMux.Unlock()
32 |
33 | t, ok := customTypes[rt]
34 | return t, ok
35 | }
36 |
--------------------------------------------------------------------------------
/internal/test/complex_recursive.go:
--------------------------------------------------------------------------------
1 | package test
2 |
3 | type ComplexNode struct {
4 | Left, Right *ComplexNode
5 | Child *ComplexNodeChild
6 | }
7 |
8 | type ComplexNodeChild struct {
9 | Parent *ComplexNode
10 | Child *ComplexNodeChild
11 | Siblings []*ComplexNode
12 | }
13 |
--------------------------------------------------------------------------------
/internal/test/test.go:
--------------------------------------------------------------------------------
1 | package test
2 |
3 | type foo struct {
4 | bar string
5 | }
6 |
7 | func (f *foo) String() string {
8 | return "foo.String says hi"
9 | }
10 |
11 | func NewFoo() *foo {
12 | return &foo{
13 | bar: "hello2",
14 | }
15 | }
16 |
17 | type Bazer interface {
18 | Baz() (err error)
19 | }
20 |
21 | type Baz struct {
22 | Bam complex64
23 | zeta *foo
24 | Beta interface{}
25 | }
26 |
27 | func (b *Baz) String() string {
28 | return "Baz.String says hi"
29 | }
30 |
31 | func (b *Baz) Baz() (err error) {
32 | return nil
33 | }
34 |
35 | func NewBaz() *Baz {
36 | return &Baz{
37 | Bam: 1.34,
38 | zeta: &foo{
39 | bar: "hello",
40 | },
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/profiler.go:
--------------------------------------------------------------------------------
1 | package valast
2 |
3 | import (
4 | "fmt"
5 | "reflect"
6 | "strings"
7 | "time"
8 | )
9 |
10 | type profiler struct {
11 | stack []reflect.Value
12 | invertedStackMessages []string
13 | }
14 |
15 | func (p *profiler) push(v reflect.Value) {
16 | if p == nil {
17 | return
18 | }
19 | p.stack = append(p.stack, v)
20 | }
21 |
22 | func (p *profiler) pop(startTime time.Time) {
23 | if p == nil {
24 | return
25 | }
26 | d := time.Since(startTime)
27 | v := p.stack[len(p.stack)-1].Interface()
28 | p.stack = p.stack[:len(p.stack)-1]
29 | stackSize := len(p.stack)
30 | msg := fmt.Sprintf("%s%vns: %T\n", strings.Repeat(" ", stackSize), d.Nanoseconds(), v)
31 | p.invertedStackMessages = append(p.invertedStackMessages, msg)
32 | }
33 |
34 | func (p *profiler) dump() {
35 | if p == nil {
36 | return
37 | }
38 | fmt.Println("valast: profile")
39 | for i := len(p.invertedStackMessages) - 1; i > 0; i-- {
40 | fmt.Print(p.invertedStackMessages[i])
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/ptr.go:
--------------------------------------------------------------------------------
1 | package valast
2 |
3 | // Ptr returns a pointer to the given value.
4 | func Ptr[V any](v V) *V {
5 | return &v
6 | }
7 |
--------------------------------------------------------------------------------
/stdtypes.go:
--------------------------------------------------------------------------------
1 | package valast
2 |
3 | import (
4 | "fmt"
5 | "go/ast"
6 | "go/token"
7 | "time"
8 | )
9 |
10 | // Register custom reprsentations of common structs from stdlib that only
11 | // contain unexported fields.
12 | func init() {
13 | // For time.Time, returns the AST expression equivalent of:
14 | //
15 | // time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
16 | RegisterType(func(t time.Time) ast.Expr {
17 | return &ast.CallExpr{
18 | Fun: &ast.SelectorExpr{
19 | X: &ast.Ident{Name: "time"},
20 | Sel: &ast.Ident{Name: "Date"},
21 | },
22 | Args: []ast.Expr{
23 | &ast.BasicLit{Kind: token.INT, Value: fmt.Sprintf("%d", t.Year())},
24 | &ast.BasicLit{Kind: token.INT, Value: fmt.Sprintf("%d", t.Month())},
25 | &ast.BasicLit{Kind: token.INT, Value: fmt.Sprintf("%d", t.Day())},
26 | &ast.BasicLit{Kind: token.INT, Value: fmt.Sprintf("%d", t.Hour())},
27 | &ast.BasicLit{Kind: token.INT, Value: fmt.Sprintf("%d", t.Minute())},
28 | &ast.BasicLit{Kind: token.INT, Value: fmt.Sprintf("%d", t.Second())},
29 | &ast.BasicLit{Kind: token.INT, Value: fmt.Sprintf("%d", t.Nanosecond())},
30 | &ast.SelectorExpr{
31 | X: &ast.Ident{Name: "time"},
32 | Sel: &ast.Ident{Name: t.Location().String()},
33 | },
34 | },
35 | }
36 | })
37 | }
38 |
--------------------------------------------------------------------------------
/testdata/TestEdgeCases__nil_interface_pointer.golden:
--------------------------------------------------------------------------------
1 | &struct {
2 | v *test.Bazer
3 | }{}
--------------------------------------------------------------------------------
/testdata/TestEdgeCases__ptr2_to_nil_interface.golden:
--------------------------------------------------------------------------------
1 | &struct {
2 | v **test.Bazer
3 | }{v: valast.Ptr(valast.AddrInterface(nil, (*test.Bazer)(nil)).(*test.Bazer))}
--------------------------------------------------------------------------------
/testdata/TestEdgeCases__ptr3_to_nil_interface.golden:
--------------------------------------------------------------------------------
1 | &struct {
2 | v ***test.Bazer
3 | }{v: valast.Ptr(valast.Ptr(valast.AddrInterface(nil,
4 | (*test.Bazer)(nil)).(*test.Bazer)))}
--------------------------------------------------------------------------------
/testdata/TestEdgeCases__ptr_to_interface.golden:
--------------------------------------------------------------------------------
1 | &struct {
2 | v *test.Bazer
3 | }{v: valast.AddrInterface(&test.Baz{
4 | Bam: (1.34 + 0i),
5 | zeta: &test.foo{
6 | bar: "hello",
7 | },
8 | },
9 | (*test.Bazer)(nil)).(*test.Bazer)}
--------------------------------------------------------------------------------
/testdata/TestEdgeCases__ptr_to_nil_interface.golden:
--------------------------------------------------------------------------------
1 | &struct {
2 | v *test.Bazer
3 | }{v: valast.AddrInterface(nil, (*test.Bazer)(nil)).(*test.Bazer)}
--------------------------------------------------------------------------------
/testdata/TestEdgeCases__ptr_to_ptr_to_interface.golden:
--------------------------------------------------------------------------------
1 | &struct {
2 | v **test.Bazer
3 | }{v: valast.Ptr(valast.AddrInterface(&test.Baz{
4 | Bam: (1.34 + 0i),
5 | zeta: &test.foo{
6 | bar: "hello",
7 | },
8 | },
9 | (*test.Bazer)(nil)).(*test.Bazer))}
--------------------------------------------------------------------------------
/testdata/TestExportedOnly_input__array.golden:
--------------------------------------------------------------------------------
1 | valast: cannot convert unexported value valast.unexportedArray
--------------------------------------------------------------------------------
/testdata/TestExportedOnly_input__bool.golden:
--------------------------------------------------------------------------------
1 | valast: cannot convert unexported value valast.unexportedBool
--------------------------------------------------------------------------------
/testdata/TestExportedOnly_input__complex128.golden:
--------------------------------------------------------------------------------
1 | valast: cannot convert unexported value valast.unexportedComplex128
--------------------------------------------------------------------------------
/testdata/TestExportedOnly_input__complex64.golden:
--------------------------------------------------------------------------------
1 | valast: cannot convert unexported value valast.unexportedComplex64
--------------------------------------------------------------------------------
/testdata/TestExportedOnly_input__float32.golden:
--------------------------------------------------------------------------------
1 | valast: cannot convert unexported value valast.unexportedFloat32
--------------------------------------------------------------------------------
/testdata/TestExportedOnly_input__float64.golden:
--------------------------------------------------------------------------------
1 | valast: cannot convert unexported value valast.unexportedFloat64
--------------------------------------------------------------------------------
/testdata/TestExportedOnly_input__int.golden:
--------------------------------------------------------------------------------
1 | valast: cannot convert unexported value valast.unexportedInt
--------------------------------------------------------------------------------
/testdata/TestExportedOnly_input__int16.golden:
--------------------------------------------------------------------------------
1 | valast: cannot convert unexported value valast.unexportedInt16
--------------------------------------------------------------------------------
/testdata/TestExportedOnly_input__int32.golden:
--------------------------------------------------------------------------------
1 | valast: cannot convert unexported value valast.unexportedInt32
--------------------------------------------------------------------------------
/testdata/TestExportedOnly_input__int64.golden:
--------------------------------------------------------------------------------
1 | valast: cannot convert unexported value valast.unexportedInt64
--------------------------------------------------------------------------------
/testdata/TestExportedOnly_input__int8.golden:
--------------------------------------------------------------------------------
1 | valast: cannot convert unexported value valast.unexportedInt8
--------------------------------------------------------------------------------
/testdata/TestExportedOnly_input__interface.golden:
--------------------------------------------------------------------------------
1 | valast: cannot convert unexported value struct { V valast.unexportedInterface }
--------------------------------------------------------------------------------
/testdata/TestExportedOnly_input__map.golden:
--------------------------------------------------------------------------------
1 | valast: cannot convert unexported value valast.unexportedMap
--------------------------------------------------------------------------------
/testdata/TestExportedOnly_input__map_unexported_key_omitted.golden:
--------------------------------------------------------------------------------
1 | map[string]interface{}{}
--------------------------------------------------------------------------------
/testdata/TestExportedOnly_input__map_unexported_key_type.golden:
--------------------------------------------------------------------------------
1 | valast: cannot convert unexported value map[valast.unexportedInt]string
--------------------------------------------------------------------------------
/testdata/TestExportedOnly_input__map_unexported_value_omitted.golden:
--------------------------------------------------------------------------------
1 | map[interface{}]string{}
--------------------------------------------------------------------------------
/testdata/TestExportedOnly_input__map_unexported_value_type.golden:
--------------------------------------------------------------------------------
1 | valast: cannot convert unexported value map[string]valast.unexportedInt
--------------------------------------------------------------------------------
/testdata/TestExportedOnly_input__pointer.golden:
--------------------------------------------------------------------------------
1 | valast: cannot convert unexported value valast.unexportedPointer
--------------------------------------------------------------------------------
/testdata/TestExportedOnly_input__slice.golden:
--------------------------------------------------------------------------------
1 | valast: cannot convert unexported value valast.unexportedSlice
--------------------------------------------------------------------------------
/testdata/TestExportedOnly_input__string.golden:
--------------------------------------------------------------------------------
1 | valast: cannot convert unexported value valast.unexportedString
--------------------------------------------------------------------------------
/testdata/TestExportedOnly_input__struct.golden:
--------------------------------------------------------------------------------
1 | valast: cannot convert unexported value valast.unexportedStruct
--------------------------------------------------------------------------------
/testdata/TestExportedOnly_input__struct_same_package.golden:
--------------------------------------------------------------------------------
1 | baz{Bam: (1.34 + 0i), zeta: foo{
2 | bar: "hello",
3 | }}
--------------------------------------------------------------------------------
/testdata/TestExportedOnly_input__uint.golden:
--------------------------------------------------------------------------------
1 | valast: cannot convert unexported value valast.unexportedUint
--------------------------------------------------------------------------------
/testdata/TestExportedOnly_input__uint16.golden:
--------------------------------------------------------------------------------
1 | valast: cannot convert unexported value valast.unexportedUint16
--------------------------------------------------------------------------------
/testdata/TestExportedOnly_input__uint32.golden:
--------------------------------------------------------------------------------
1 | valast: cannot convert unexported value valast.unexportedUint32
--------------------------------------------------------------------------------
/testdata/TestExportedOnly_input__uint64.golden:
--------------------------------------------------------------------------------
1 | valast: cannot convert unexported value valast.unexportedUint64
--------------------------------------------------------------------------------
/testdata/TestExportedOnly_input__uint8.golden:
--------------------------------------------------------------------------------
1 | valast: cannot convert unexported value valast.unexportedUint8
--------------------------------------------------------------------------------
/testdata/TestExportedOnly_input__uintptr.golden:
--------------------------------------------------------------------------------
1 | valast: cannot convert unexported value valast.unexportedUintptr
--------------------------------------------------------------------------------
/testdata/TestExportedOnly_input__unsafe_pointer.golden:
--------------------------------------------------------------------------------
1 | valast: cannot convert unexported value valast.unexportedUnsafePointer
--------------------------------------------------------------------------------
/testdata/TestExportedOnly_nested__external_struct_unexported_field_omitted.golden:
--------------------------------------------------------------------------------
1 | &test.Baz{Bam: (1.34 + 0i)}
--------------------------------------------------------------------------------
/testdata/TestExportedOnly_nested__interface.golden:
--------------------------------------------------------------------------------
1 | valast: cannot convert unexported value struct { zeta valast.foo }
--------------------------------------------------------------------------------
/testdata/TestExportedOnly_nested__struct_same_package_unexported_field_omitted.golden:
--------------------------------------------------------------------------------
1 | valast.ExportedBaz{Bam: (1.34 + 0i)}
--------------------------------------------------------------------------------
/testdata/TestIssue15_addr_values_must_be_qualified.golden:
--------------------------------------------------------------------------------
1 | struct {
2 | a *float32
3 | b *int32
4 | c *int64
5 | d *uint32
6 | e *uint64
7 | f *int
8 | g *uint
9 | h *string
10 | i *float64
11 | }{
12 | a: valast.Ptr(float32(3607)), b: valast.Ptr(int32(3607)),
13 | c: valast.Ptr(int64(3607)),
14 | d: valast.Ptr(uint32(3607)),
15 | e: valast.Ptr(uint64(3607)),
16 | f: valast.Ptr(3607),
17 | g: valast.Ptr(uint(3607)),
18 | h: valast.Ptr("foobar"),
19 | i: valast.Ptr(3.14),
20 | }
--------------------------------------------------------------------------------
/testdata/TestPointers__array.golden:
--------------------------------------------------------------------------------
1 | &[1]float32{1}
--------------------------------------------------------------------------------
/testdata/TestPointers__array2.golden:
--------------------------------------------------------------------------------
1 | valast.Ptr(&[1]float32{1})
--------------------------------------------------------------------------------
/testdata/TestPointers__bool.golden:
--------------------------------------------------------------------------------
1 | valast.Ptr(true)
--------------------------------------------------------------------------------
/testdata/TestPointers__bool2.golden:
--------------------------------------------------------------------------------
1 | valast.Ptr(valast.Ptr(true))
--------------------------------------------------------------------------------
/testdata/TestPointers__complex128.golden:
--------------------------------------------------------------------------------
1 | valast.Ptr(complex128((1 + 0i)))
--------------------------------------------------------------------------------
/testdata/TestPointers__complex64.golden:
--------------------------------------------------------------------------------
1 | valast.Ptr(complex64((1 + 0i)))
--------------------------------------------------------------------------------
/testdata/TestPointers__float32.golden:
--------------------------------------------------------------------------------
1 | valast.Ptr(float32(1))
--------------------------------------------------------------------------------
/testdata/TestPointers__float64.golden:
--------------------------------------------------------------------------------
1 | valast.Ptr(float64(1))
--------------------------------------------------------------------------------
/testdata/TestPointers__int.golden:
--------------------------------------------------------------------------------
1 | valast.Ptr(int(1))
--------------------------------------------------------------------------------
/testdata/TestPointers__int16.golden:
--------------------------------------------------------------------------------
1 | valast.Ptr(int16(1))
--------------------------------------------------------------------------------
/testdata/TestPointers__int2.golden:
--------------------------------------------------------------------------------
1 | valast.Ptr(valast.Ptr(int(1)))
--------------------------------------------------------------------------------
/testdata/TestPointers__int3.golden:
--------------------------------------------------------------------------------
1 | valast.Ptr(valast.Ptr(valast.Ptr(int(1))))
--------------------------------------------------------------------------------
/testdata/TestPointers__int32.golden:
--------------------------------------------------------------------------------
1 | valast.Ptr(int32(1))
--------------------------------------------------------------------------------
/testdata/TestPointers__int64.golden:
--------------------------------------------------------------------------------
1 | valast.Ptr(int64(1))
--------------------------------------------------------------------------------
/testdata/TestPointers__int8.golden:
--------------------------------------------------------------------------------
1 | valast.Ptr(int8(1))
--------------------------------------------------------------------------------
/testdata/TestPointers__interface.golden:
--------------------------------------------------------------------------------
1 | valast.AddrInterface(test.Bazer{&test.Baz{
2 | Bam: (1.34 + 0i),
3 | zeta: &test.foo{bar: "hello"},
4 | }},
5 | (*test.Bazer)(nil)).(*test.Bazer)
--------------------------------------------------------------------------------
/testdata/TestPointers__interface2.golden:
--------------------------------------------------------------------------------
1 | valast.Ptr(valast.AddrInterface(test.Bazer{&test.Baz{
2 | Bam: (1.34 + 0i),
3 | zeta: &test.foo{bar: "hello"},
4 | }},
5 | (*test.Bazer)(nil)).(*test.Bazer))
--------------------------------------------------------------------------------
/testdata/TestPointers__map.golden:
--------------------------------------------------------------------------------
1 | &map[string]string{"hello": "world"}
--------------------------------------------------------------------------------
/testdata/TestPointers__map2.golden:
--------------------------------------------------------------------------------
1 | valast.Ptr(&map[string]string{"hello": "world"})
--------------------------------------------------------------------------------
/testdata/TestPointers__pointer.golden:
--------------------------------------------------------------------------------
1 | valast.Ptr(valast.Ptr(uint(1)))
--------------------------------------------------------------------------------
/testdata/TestPointers__pointer2.golden:
--------------------------------------------------------------------------------
1 | valast.Ptr(valast.Ptr(valast.Ptr(uint(1))))
--------------------------------------------------------------------------------
/testdata/TestPointers__slice.golden:
--------------------------------------------------------------------------------
1 | &[]int{1, 2, 3}
--------------------------------------------------------------------------------
/testdata/TestPointers__slice2.golden:
--------------------------------------------------------------------------------
1 | valast.Ptr(&[]int{1, 2, 3})
--------------------------------------------------------------------------------
/testdata/TestPointers__string.golden:
--------------------------------------------------------------------------------
1 | valast.Ptr("hello world")
--------------------------------------------------------------------------------
/testdata/TestPointers__struct.golden:
--------------------------------------------------------------------------------
1 | &struct {
2 | A string
3 | }{A: "hello world"}
--------------------------------------------------------------------------------
/testdata/TestPointers__struct2.golden:
--------------------------------------------------------------------------------
1 | valast.Ptr(&struct {
2 | A string
3 | }{A: "hello world"})
--------------------------------------------------------------------------------
/testdata/TestPointers__time_local.golden:
--------------------------------------------------------------------------------
1 | valast.Ptr(time.Date(2016, 1, 2, 15, 4, 5, 0, time.Local))
--------------------------------------------------------------------------------
/testdata/TestPointers__time_utc.golden:
--------------------------------------------------------------------------------
1 | valast.Ptr(time.Date(2016, 1, 2, 15, 4, 5, 0, time.UTC))
--------------------------------------------------------------------------------
/testdata/TestPointers__uint.golden:
--------------------------------------------------------------------------------
1 | valast.Ptr(uint(1))
--------------------------------------------------------------------------------
/testdata/TestPointers__uint16.golden:
--------------------------------------------------------------------------------
1 | valast.Ptr(uint16(1))
--------------------------------------------------------------------------------
/testdata/TestPointers__uint32.golden:
--------------------------------------------------------------------------------
1 | valast.Ptr(uint32(1))
--------------------------------------------------------------------------------
/testdata/TestPointers__uint64.golden:
--------------------------------------------------------------------------------
1 | valast.Ptr(uint64(1))
--------------------------------------------------------------------------------
/testdata/TestPointers__uint8.golden:
--------------------------------------------------------------------------------
1 | valast.Ptr(uint8(1))
--------------------------------------------------------------------------------
/testdata/TestPointers__uintptr.golden:
--------------------------------------------------------------------------------
1 | valast.Ptr(uintptr(1))
--------------------------------------------------------------------------------
/testdata/TestPointers__unsafe_pointer.golden:
--------------------------------------------------------------------------------
1 | valast.Ptr(unsafe.Pointer(uintptr(0xdeadbeef)))
--------------------------------------------------------------------------------
/testdata/TestPointers__unsafe_pointer2.golden:
--------------------------------------------------------------------------------
1 | valast.Ptr(valast.Ptr(unsafe.Pointer(uintptr(0xdeadbeef))))
--------------------------------------------------------------------------------
/testdata/TestRecursion__basic.golden:
--------------------------------------------------------------------------------
1 | &valast.foo{name: "one", bar: &valast.foo{
2 | name: "two",
3 | bar: &valast.foo{
4 | name: "three",
5 | bar: &valast.foo{
6 | name: "four",
7 | bar: &valast.foo{name: "five"},
8 | },
9 | },
10 | }}
--------------------------------------------------------------------------------
/testdata/TestRecursion__struct_cyclic.golden:
--------------------------------------------------------------------------------
1 | &valast.foo{name: "one", bar: &valast.foo{
2 | name: "one",
3 | bar: nil,
4 | }}
--------------------------------------------------------------------------------
/testdata/TestStringFormatting__long_multi_line_180.golden:
--------------------------------------------------------------------------------
1 | `hello world hello world hello world hello world hello world hello world hello world hello world
2 | hello world hello world hello world hello world hello world hello world hello world`
--------------------------------------------------------------------------------
/testdata/TestStringFormatting__long_multi_line_with_backticks.golden:
--------------------------------------------------------------------------------
1 | "hello world hello world hello world hello world hello world hello world hello world hello world\n`hello world hello world hello world hello world hello world hello world hello world"
--------------------------------------------------------------------------------
/testdata/TestStringFormatting__long_multi_line_with_quotes.golden:
--------------------------------------------------------------------------------
1 | `"hello world"! "hello world" hello world hello world hello world hello world hello world hello world
2 | hello world hello world hello world hello world "hello" world hello world hello world`
--------------------------------------------------------------------------------
/testdata/TestStringFormatting__long_single_line_180.golden:
--------------------------------------------------------------------------------
1 | "hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world "
--------------------------------------------------------------------------------
/testdata/TestStringFormatting__short_multi_line.golden:
--------------------------------------------------------------------------------
1 | "hello\nworld"
--------------------------------------------------------------------------------
/testdata/TestStringFormatting__short_quotes.golden:
--------------------------------------------------------------------------------
1 | `"hello" "world"`
--------------------------------------------------------------------------------
/testdata/TestStringFormatting__short_single_line.golden:
--------------------------------------------------------------------------------
1 | "hello world"
--------------------------------------------------------------------------------
/testdata/TestString__array.golden:
--------------------------------------------------------------------------------
1 | [2]*baz{
2 | {
3 | Beta: "foo",
4 | },
5 | {Beta: 123},
6 | }
--------------------------------------------------------------------------------
/testdata/TestString__bool.golden:
--------------------------------------------------------------------------------
1 | true
--------------------------------------------------------------------------------
/testdata/TestString__bool_unqualify.golden:
--------------------------------------------------------------------------------
1 | false
--------------------------------------------------------------------------------
/testdata/TestString__complex64.golden:
--------------------------------------------------------------------------------
1 | complex64((1.234 + 0i))
--------------------------------------------------------------------------------
/testdata/TestString__complex64_unqualify.golden:
--------------------------------------------------------------------------------
1 | (1.234 + 0i)
--------------------------------------------------------------------------------
/testdata/TestString__float64.golden:
--------------------------------------------------------------------------------
1 | float64(1.234)
--------------------------------------------------------------------------------
/testdata/TestString__float64_unqualify.golden:
--------------------------------------------------------------------------------
1 | 1.234
--------------------------------------------------------------------------------
/testdata/TestString__int32.golden:
--------------------------------------------------------------------------------
1 | int32(1234)
--------------------------------------------------------------------------------
/testdata/TestString__int32_unqualify.golden:
--------------------------------------------------------------------------------
1 | 1234
--------------------------------------------------------------------------------
/testdata/TestString__interface.golden:
--------------------------------------------------------------------------------
1 | &struct {
2 | v test.Bazer
3 | }{v: &test.Baz{Bam: (1.34 + 0i), zeta: &test.foo{
4 | bar: "hello",
5 | }}}
--------------------------------------------------------------------------------
/testdata/TestString__interface_anonymous.golden:
--------------------------------------------------------------------------------
1 | &struct {
2 | v interface {
3 | Baz() error
4 | String() string
5 | }
6 | }{v: &test.Baz{Bam: (1.34 + 0i), zeta: &test.foo{
7 | bar: "hello",
8 | }}}
--------------------------------------------------------------------------------
/testdata/TestString__interface_anonymous_nil.golden:
--------------------------------------------------------------------------------
1 | nil
--------------------------------------------------------------------------------
/testdata/TestString__interface_builtin.golden:
--------------------------------------------------------------------------------
1 | &struct {
2 | v error
3 | }{}
--------------------------------------------------------------------------------
/testdata/TestString__map.golden:
--------------------------------------------------------------------------------
1 | map[string]int32{"bar": 64, "foo": 32}
--------------------------------------------------------------------------------
/testdata/TestString__nil.golden:
--------------------------------------------------------------------------------
1 | nil
--------------------------------------------------------------------------------
/testdata/TestString__slice.golden:
--------------------------------------------------------------------------------
1 | []*baz{
2 | {
3 | Beta: "foo",
4 | },
5 | {Beta: 123},
6 | {Beta: 3},
7 | }
--------------------------------------------------------------------------------
/testdata/TestString__string.golden:
--------------------------------------------------------------------------------
1 | "hello \t world"
--------------------------------------------------------------------------------
/testdata/TestString__string_unqualify.golden:
--------------------------------------------------------------------------------
1 | "one\ntwo\nthree"
--------------------------------------------------------------------------------
/testdata/TestString__struct_anonymous.golden:
--------------------------------------------------------------------------------
1 | struct {
2 | a int
3 | b int
4 | V string
5 | }{a: 1, b: 2, V: "efg"}
--------------------------------------------------------------------------------
/testdata/TestString__struct_external_package.golden:
--------------------------------------------------------------------------------
1 | &test.Baz{Bam: (1.34 + 0i), zeta: &test.foo{
2 | bar: "hello",
3 | }}
--------------------------------------------------------------------------------
/testdata/TestString__struct_same_package.golden:
--------------------------------------------------------------------------------
1 | baz{Bam: (1.34 + 0i), zeta: foo{
2 | bar: "hello",
3 | }}
--------------------------------------------------------------------------------
/testdata/TestString__time_local.golden:
--------------------------------------------------------------------------------
1 | time.Date(2016, 1, 2, 15, 4, 5, 0, time.Local)
--------------------------------------------------------------------------------
/testdata/TestString__time_utc.golden:
--------------------------------------------------------------------------------
1 | time.Date(2016, 1, 2, 15, 4, 5, 0, time.UTC)
--------------------------------------------------------------------------------
/testdata/TestString__uintptr.golden:
--------------------------------------------------------------------------------
1 | uintptr(1234)
--------------------------------------------------------------------------------
/testdata/TestString__uintptr_unqualify.golden:
--------------------------------------------------------------------------------
1 | 1234
--------------------------------------------------------------------------------
/testdata/TestString__unsafe_pointer.golden:
--------------------------------------------------------------------------------
1 | unsafe.Pointer(uintptr(0xdeadbeef))
--------------------------------------------------------------------------------
/testdata/TestUnexportedInputs__array.golden:
--------------------------------------------------------------------------------
1 | unexportedArray{1}
--------------------------------------------------------------------------------
/testdata/TestUnexportedInputs__bool.golden:
--------------------------------------------------------------------------------
1 | unexportedBool(true)
--------------------------------------------------------------------------------
/testdata/TestUnexportedInputs__complex128.golden:
--------------------------------------------------------------------------------
1 | unexportedComplex128((1 + 0i))
--------------------------------------------------------------------------------
/testdata/TestUnexportedInputs__complex64.golden:
--------------------------------------------------------------------------------
1 | unexportedComplex64((1 + 0i))
--------------------------------------------------------------------------------
/testdata/TestUnexportedInputs__float32.golden:
--------------------------------------------------------------------------------
1 | unexportedFloat32(1)
--------------------------------------------------------------------------------
/testdata/TestUnexportedInputs__float64.golden:
--------------------------------------------------------------------------------
1 | unexportedFloat64(1)
--------------------------------------------------------------------------------
/testdata/TestUnexportedInputs__int.golden:
--------------------------------------------------------------------------------
1 | unexportedInt(1)
--------------------------------------------------------------------------------
/testdata/TestUnexportedInputs__int16.golden:
--------------------------------------------------------------------------------
1 | unexportedInt16(1)
--------------------------------------------------------------------------------
/testdata/TestUnexportedInputs__int32.golden:
--------------------------------------------------------------------------------
1 | unexportedInt32(1)
--------------------------------------------------------------------------------
/testdata/TestUnexportedInputs__int64.golden:
--------------------------------------------------------------------------------
1 | unexportedInt64(1)
--------------------------------------------------------------------------------
/testdata/TestUnexportedInputs__int8.golden:
--------------------------------------------------------------------------------
1 | unexportedInt8(1)
--------------------------------------------------------------------------------
/testdata/TestUnexportedInputs__interface.golden:
--------------------------------------------------------------------------------
1 | struct {
2 | V unexportedInterface
3 | }{}
--------------------------------------------------------------------------------
/testdata/TestUnexportedInputs__map.golden:
--------------------------------------------------------------------------------
1 | unexportedMap{"a": "b"}
--------------------------------------------------------------------------------
/testdata/TestUnexportedInputs__pointer.golden:
--------------------------------------------------------------------------------
1 | (unexportedPointer)(nil)
--------------------------------------------------------------------------------
/testdata/TestUnexportedInputs__slice.golden:
--------------------------------------------------------------------------------
1 | unexportedSlice{1, 2, 3}
--------------------------------------------------------------------------------
/testdata/TestUnexportedInputs__string.golden:
--------------------------------------------------------------------------------
1 | unexportedString("hello")
--------------------------------------------------------------------------------
/testdata/TestUnexportedInputs__struct.golden:
--------------------------------------------------------------------------------
1 | unexportedStruct{A: "b"}
--------------------------------------------------------------------------------
/testdata/TestUnexportedInputs__uint.golden:
--------------------------------------------------------------------------------
1 | unexportedUint(1)
--------------------------------------------------------------------------------
/testdata/TestUnexportedInputs__uint16.golden:
--------------------------------------------------------------------------------
1 | unexportedUint16(1)
--------------------------------------------------------------------------------
/testdata/TestUnexportedInputs__uint32.golden:
--------------------------------------------------------------------------------
1 | unexportedUint32(1)
--------------------------------------------------------------------------------
/testdata/TestUnexportedInputs__uint64.golden:
--------------------------------------------------------------------------------
1 | unexportedUint64(1)
--------------------------------------------------------------------------------
/testdata/TestUnexportedInputs__uint8.golden:
--------------------------------------------------------------------------------
1 | unexportedUint8(1)
--------------------------------------------------------------------------------
/testdata/TestUnexportedInputs__uintptr.golden:
--------------------------------------------------------------------------------
1 | unexportedUintptr(1)
--------------------------------------------------------------------------------
/testdata/TestUnexportedInputs__unsafe_pointer.golden:
--------------------------------------------------------------------------------
1 | unexportedUnsafePointer(uintptr(0xdeadbeef))
--------------------------------------------------------------------------------
/types.go:
--------------------------------------------------------------------------------
1 | package valast
2 |
3 | import (
4 | "fmt"
5 | "go/ast"
6 | "go/token"
7 | "reflect"
8 |
9 | "github.com/hexops/valast/internal/customtype"
10 | )
11 |
12 | // RegisterType registers a type that for representation in a custom manner with
13 | // valast. If valast encounters a value or pointer to a value of this type, it
14 | // will use the given render func to generate the appropriate AST representation.
15 | //
16 | // This is useful if a type's fields are private, and can only be represented
17 | // through a constructor - see stdtypes.go for examples.
18 | //
19 | // This mechanism currently only works with struct types.
20 | func RegisterType[T any](render func(value T) ast.Expr) {
21 | customtype.Register(render)
22 | }
23 |
24 | type cacheKeyOptions struct {
25 | Unqualify bool
26 | PackagePath string
27 | PackageName string
28 | ExportedOnly bool
29 | }
30 |
31 | type cacheKey struct {
32 | v reflect.Type
33 | opt cacheKeyOptions
34 | }
35 |
36 | func newCacheKey(v reflect.Type, opt *Options) cacheKey {
37 | return cacheKey{v: v, opt: cacheKeyOptions{
38 | Unqualify: opt.Unqualify,
39 | PackagePath: opt.PackagePath,
40 | PackageName: opt.PackageName,
41 | ExportedOnly: opt.ExportedOnly,
42 | }}
43 | }
44 |
45 | type typeExprCache map[cacheKey]Result
46 |
47 | // typeExpr returns an AST type expression for the value v.
48 | //
49 | // It is cached to avoid building type expressions again for types we've already seen, which can
50 | // get quite complex (see BenchmarkComplexType.)
51 | func typeExpr(v reflect.Type, opt *Options, cache typeExprCache) (Result, error) {
52 | key := newCacheKey(v, opt)
53 | if cached, ok := cache[key]; ok {
54 | return cached, nil
55 | }
56 |
57 | result, err := uncachedTypeExpr(v, opt, cache)
58 | if err != nil {
59 | return Result{}, err
60 | }
61 | cache[key] = result
62 | return result, nil
63 | }
64 |
65 | func uncachedTypeExpr(v reflect.Type, opt *Options, cache typeExprCache) (Result, error) {
66 | if v.Kind() != reflect.UnsafePointer && v.Name() != "" {
67 | pkgPath := v.PkgPath()
68 | if pkgPath != "" && pkgPath != opt.PackagePath {
69 | pkgName, err := opt.packagePathToName(v.PkgPath())
70 | if err != nil {
71 | return Result{}, err
72 | }
73 | if pkgName != opt.PackageName {
74 | return Result{
75 | AST: &ast.SelectorExpr{X: ast.NewIdent(pkgName), Sel: ast.NewIdent(v.Name())},
76 | RequiresUnexported: !ast.IsExported(v.Name()),
77 | }, nil
78 | }
79 | }
80 | return Result{
81 | AST: ast.NewIdent(v.Name()),
82 | RequiresUnexported: false,
83 | }, nil
84 | }
85 | switch v.Kind() {
86 | case reflect.Array:
87 | elemType, err := typeExpr(v.Elem(), opt, cache)
88 | if err != nil {
89 | return Result{}, err
90 | }
91 | return Result{
92 | AST: &ast.ArrayType{
93 | Len: &ast.BasicLit{Kind: token.INT, Value: fmt.Sprint(v.Len())},
94 | Elt: elemType.AST,
95 | },
96 | RequiresUnexported: elemType.RequiresUnexported,
97 | }, nil
98 | case reflect.Interface:
99 | var methods []*ast.Field
100 | var requiresUnexported bool
101 | for i := 0; i < v.NumMethod(); i++ {
102 | method := v.Method(i)
103 | methodType, err := typeExpr(method.Type, opt, cache)
104 | if err != nil {
105 | return Result{}, err
106 | }
107 | if methodType.RequiresUnexported {
108 | requiresUnexported = true
109 | }
110 | methods = append(methods, &ast.Field{
111 | Names: []*ast.Ident{ast.NewIdent(method.Name)},
112 | Type: methodType.AST,
113 | })
114 | }
115 | return Result{
116 | AST: &ast.InterfaceType{Methods: &ast.FieldList{List: methods}},
117 | RequiresUnexported: requiresUnexported,
118 | }, nil
119 | case reflect.Func:
120 | // Note: reflect cannot determine parameter/result names. See https://groups.google.com/g/golang-nuts/c/nM_ZhL7fuGc
121 | var (
122 | requiresUnexported bool
123 | params []*ast.Field
124 | )
125 | for i := 0; i < v.NumIn(); i++ {
126 | param := v.In(i)
127 | paramType, err := typeExpr(param, opt, cache)
128 | if err != nil {
129 | return Result{}, err
130 | }
131 | if paramType.RequiresUnexported {
132 | requiresUnexported = true
133 | }
134 | params = append(params, &ast.Field{
135 | Type: paramType.AST,
136 | })
137 | }
138 | var results []*ast.Field
139 | for i := 0; i < v.NumOut(); i++ {
140 | result := v.Out(i)
141 | resultType, err := typeExpr(result, opt, cache)
142 | if err != nil {
143 | return Result{}, err
144 | }
145 | if resultType.RequiresUnexported {
146 | requiresUnexported = true
147 | }
148 | results = append(results, &ast.Field{
149 | Type: resultType.AST,
150 | })
151 | }
152 | return Result{
153 | AST: &ast.FuncType{
154 | Params: &ast.FieldList{List: params},
155 | Results: &ast.FieldList{List: results},
156 | },
157 | RequiresUnexported: requiresUnexported,
158 | }, nil
159 | case reflect.Map:
160 | keyType, err := typeExpr(v.Key(), opt, cache)
161 | if err != nil {
162 | return Result{}, err
163 | }
164 | valueType, err := typeExpr(v.Elem(), opt, cache)
165 | if err != nil {
166 | return Result{}, err
167 | }
168 | return Result{
169 | AST: &ast.MapType{
170 | Key: keyType.AST,
171 | Value: valueType.AST,
172 | },
173 | RequiresUnexported: keyType.RequiresUnexported || valueType.RequiresUnexported,
174 | }, nil
175 | case reflect.Ptr:
176 | ptrType, err := typeExpr(v.Elem(), opt, cache)
177 | if err != nil {
178 | return Result{}, err
179 | }
180 | return Result{
181 | AST: &ast.StarExpr{X: ptrType.AST},
182 | RequiresUnexported: ptrType.RequiresUnexported,
183 | }, nil
184 | case reflect.Slice:
185 | elemType, err := typeExpr(v.Elem(), opt, cache)
186 | if err != nil {
187 | return Result{}, err
188 | }
189 | return Result{
190 | AST: &ast.ArrayType{Elt: elemType.AST},
191 | RequiresUnexported: elemType.RequiresUnexported,
192 | }, nil
193 | case reflect.Struct:
194 | var (
195 | fields []*ast.Field
196 | requiresUnexported, omittedUnexported bool
197 | )
198 | for i := 0; i < v.NumField(); i++ {
199 | field := v.Field(i)
200 | fieldType, err := typeExpr(field.Type, opt, cache)
201 | if err != nil {
202 | return Result{}, err
203 | }
204 | if fieldType.RequiresUnexported {
205 | requiresUnexported = true
206 | if opt.ExportedOnly {
207 | return Result{RequiresUnexported: true}, nil
208 | }
209 | }
210 | if fieldType.OmittedUnexported {
211 | omittedUnexported = true
212 | }
213 | fields = append(fields, &ast.Field{
214 | Names: []*ast.Ident{ast.NewIdent(field.Name)},
215 | Type: fieldType.AST,
216 | })
217 | }
218 | return Result{
219 | AST: &ast.StructType{
220 | Fields: &ast.FieldList{List: fields},
221 | },
222 | RequiresUnexported: requiresUnexported,
223 | OmittedUnexported: omittedUnexported,
224 | }, nil
225 | case reflect.UnsafePointer:
226 | // Note: For a plain unsafe.Pointer type, v.PkgPath() does not report "unsafe" but rather
227 | // an empty string "".
228 | isPlainUnsafePointer := v.String() == "unsafe.Pointer"
229 | if !isPlainUnsafePointer && v.Name() != "" {
230 | pkgPath := v.PkgPath()
231 | if pkgPath != "" && pkgPath != opt.PackagePath {
232 | pkgName, err := opt.packagePathToName(v.PkgPath())
233 | if err != nil {
234 | return Result{}, err
235 | }
236 | if pkgName != opt.PackageName {
237 | return Result{
238 | AST: &ast.SelectorExpr{X: ast.NewIdent(pkgName), Sel: ast.NewIdent(v.Name())},
239 | RequiresUnexported: !ast.IsExported(v.Name()),
240 | }, nil
241 | }
242 | }
243 | return Result{
244 | AST: ast.NewIdent(v.Name()),
245 | RequiresUnexported: false,
246 | }, nil
247 | }
248 | return Result{AST: &ast.SelectorExpr{X: ast.NewIdent("unsafe"), Sel: ast.NewIdent("Pointer")}}, nil
249 | default:
250 | return Result{AST: ast.NewIdent(v.Name())}, nil
251 | }
252 | }
253 |
--------------------------------------------------------------------------------
/util.go:
--------------------------------------------------------------------------------
1 | package valast
2 |
3 | import "reflect"
4 |
5 | // isAddressableKind reports if v would be encoded as a Go literal which is addressable or not.
6 | // For example, &struct{}{}, &map[string]string{}, &[]string{} are all addressable - but &"string",
7 | // &5, &1.345, &myBool(true) are not.
8 | func isAddressableKind(v reflect.Kind) bool {
9 | return v != reflect.Bool &&
10 | v != reflect.Int &&
11 | v != reflect.Int8 &&
12 | v != reflect.Int16 &&
13 | v != reflect.Int32 &&
14 | v != reflect.Int64 &&
15 | v != reflect.Uint &&
16 | v != reflect.Uint8 &&
17 | v != reflect.Uint16 &&
18 | v != reflect.Uint32 &&
19 | v != reflect.Uint64 &&
20 | v != reflect.Uintptr &&
21 | v != reflect.Float32 &&
22 | v != reflect.Float64 &&
23 | v != reflect.Complex64 &&
24 | v != reflect.Complex128 &&
25 | v != reflect.Ptr &&
26 | v != reflect.String &&
27 | v != reflect.UnsafePointer
28 | }
29 |
30 | // valueLess tells if i is less than j, according to normal Go less-than < operator rules. Values
31 | // that are unsortable according to Go rules will always yield true.
32 | //
33 | // The two values must be of the same kind or a panic will occur.
34 | func valueLess(i, j reflect.Value) bool {
35 | ii := unexported(i)
36 | switch ii.Kind() {
37 | case reflect.Bool:
38 | x := 0
39 | if ii.Bool() {
40 | x = 1
41 | }
42 | y := 0
43 | if unexported(j).Bool() {
44 | y = 1
45 | }
46 | return x < y
47 | case reflect.Int:
48 | return ii.Int() < unexported(j).Int()
49 | case reflect.Int8:
50 | return ii.Int() < unexported(j).Int()
51 | case reflect.Int16:
52 | return ii.Int() < unexported(j).Int()
53 | case reflect.Int32:
54 | return ii.Int() < unexported(j).Int()
55 | case reflect.Int64:
56 | return ii.Int() < unexported(j).Int()
57 | case reflect.Uint:
58 | return ii.Uint() < unexported(j).Uint()
59 | case reflect.Uint8:
60 | return ii.Uint() < unexported(j).Uint()
61 | case reflect.Uint16:
62 | return ii.Uint() < unexported(j).Uint()
63 | case reflect.Uint32:
64 | return ii.Uint() < unexported(j).Uint()
65 | case reflect.Uint64:
66 | return ii.Uint() < unexported(j).Uint()
67 | case reflect.Uintptr:
68 | return ii.Uint() < unexported(j).Uint()
69 | case reflect.Float32:
70 | return ii.Float() < unexported(j).Float()
71 | case reflect.Float64:
72 | return ii.Float() < unexported(j).Float()
73 | case reflect.Ptr:
74 | return ii.Pointer() < unexported(j).Pointer()
75 | case reflect.String:
76 | return ii.String() < unexported(j).String()
77 | case reflect.UnsafePointer:
78 | return ii.Pointer() < unexported(j).Pointer()
79 | case reflect.Complex64:
80 | return true
81 | case reflect.Complex128:
82 | return true
83 | case reflect.Array:
84 | return true
85 | case reflect.Map:
86 | return true
87 | case reflect.Interface:
88 | return true
89 | case reflect.Slice:
90 | return true
91 | case reflect.Struct:
92 | return true
93 | default:
94 | // never here
95 | return true
96 | }
97 | }
98 |
--------------------------------------------------------------------------------
/valast.go:
--------------------------------------------------------------------------------
1 | package valast
2 |
3 | import (
4 | "bytes"
5 | "fmt"
6 | "go/ast"
7 | "go/format"
8 | "go/token"
9 | "io"
10 | "math"
11 | "os"
12 | "reflect"
13 | "sort"
14 | "strconv"
15 | "strings"
16 | "time"
17 |
18 | "github.com/hexops/valast/internal/bypass"
19 | "github.com/hexops/valast/internal/customtype"
20 | "golang.org/x/tools/go/packages"
21 | gofumpt "mvdan.cc/gofumpt/format"
22 | )
23 |
24 | // Options describes options for the conversion process.
25 | type Options struct {
26 | // Unqualify, if true, indicates that types should be unqualified. e.g.:
27 | //
28 | // int(8) -> 8
29 | // Bar{} -> Bar{}
30 | // string("foobar") -> "foobar"
31 | //
32 | // This is set to true automatically when operating within a context where type qualification
33 | // is definitively not needed, e.g. when producing values for a struct or map.
34 | Unqualify bool
35 |
36 | // PackagePath, if non-zero, describes that the literal is being produced within the described
37 | // package path, and thus type selectors `pkg.Foo` should just be written `Foo` if the package
38 | // path and name match.
39 | PackagePath string
40 |
41 | // PackageName, if non-zero, describes that the literal is being produced within the described
42 | // package name, and thus type selectors `pkg.Foo` should just be written `Foo` if the package
43 | // path and name match.
44 | PackageName string
45 |
46 | // ExportedOnly indicates if only exported fields and values should be included.
47 | ExportedOnly bool
48 |
49 | // PackagePathToName, if non-nil, is called to convert a Go package path to the package name
50 | // written in its source. The default is DefaultPackagePathToName
51 | PackagePathToName func(path string) (string, error)
52 | }
53 |
54 | func (o *Options) withUnqualify() *Options {
55 | tmp := *o
56 | tmp.Unqualify = true
57 | return &tmp
58 | }
59 |
60 | func (o *Options) packagePathToName(path string) (string, error) {
61 | if o.PackagePathToName != nil {
62 | return o.PackagePathToName(path)
63 | }
64 | return DefaultPackagePathToName(path)
65 | }
66 |
67 | // DefaultPackagePathToName loads the specified package from disk to determine the package name.
68 | func DefaultPackagePathToName(path string) (string, error) {
69 | pkgs, err := packages.Load(&packages.Config{Mode: packages.NeedName}, path)
70 | if err != nil {
71 | return "", err
72 | }
73 | return pkgs[0].Name, nil
74 | }
75 |
76 | // String converts the value v into the equivalent Go literal syntax.
77 | //
78 | // It is an opinionated helper for the more extensive AST function.
79 | //
80 | // If any error occurs, it will be returned as the string value. If handling errors is desired then
81 | // consider using the AST function directly.
82 | func String(v interface{}) string {
83 | return StringWithOptions(v, nil)
84 | }
85 |
86 | // StringWithOptions converts the value v into the equivalent Go literal syntax, with the specified
87 | // options.
88 | //
89 | // It is an opinionated helper for the more extensive AST function.
90 | //
91 | // If any error occurs, it will be returned as the string value. If handling errors is desired then
92 | // consider using the AST function directly.
93 | func StringWithOptions(v interface{}, opt *Options) string {
94 | if opt == nil {
95 | opt = &Options{}
96 | }
97 | var buf bytes.Buffer
98 | result, err := AST(reflect.ValueOf(v), opt)
99 | if err != nil {
100 | return err.Error()
101 | }
102 | if opt.ExportedOnly && result.RequiresUnexported {
103 | return fmt.Sprintf("valast: cannot convert unexported value %T", v)
104 | }
105 | if err := gofumptFormatExpr(&buf, token.NewFileSet(), result.AST, gofumpt.Options{
106 | ExtraRules: true,
107 | }); err != nil {
108 | return fmt.Sprintf("valast: format: %v", err)
109 | }
110 | return buf.String()
111 | }
112 |
113 | // gofumptFormatExpr is a slight hack to get gofumpt to format an ast.Expr node, because the
114 | // gofumpt/format package does not expose node-level formatting currently.
115 | func gofumptFormatExpr(w io.Writer, fset *token.FileSet, expr ast.Expr, opt gofumpt.Options) error {
116 | // First use go/format to convert the expression to Go syntax.
117 | var tmp bytes.Buffer
118 | if err := format.Node(&tmp, fset, expr); err != nil {
119 | return err
120 | }
121 |
122 | // HACK: Split composite literals onto multiple lines to avoid extra long struct values. We
123 | // will defer this to gofumpt once it can perform this: https://github.com/mvdan/gofumpt/pull/70
124 | tmpString := string(formatCompositeLiterals([]rune(tmp.String())))
125 |
126 | // Create a temporary file with our expression, run gofumpt on it, and extract the result.
127 | fileStart := `package main
128 |
129 | func main() {
130 | v := `
131 | fileEnd := `
132 | }
133 | `
134 | tmpFile := []byte(fileStart + tmpString + fileEnd)
135 | formattedFile, err := gofumpt.Source(tmpFile, opt)
136 | if err != nil {
137 | return err
138 | }
139 | formattedFile = bytes.TrimPrefix(formattedFile, []byte(fileStart))
140 | formattedFile = bytes.TrimSuffix(formattedFile, []byte(fileEnd))
141 |
142 | // Remove leading indention.
143 | lines := bytes.Split(formattedFile, []byte{'\n'})
144 | for i, line := range lines {
145 | lines[i] = bytes.TrimPrefix(line, []byte{'\t'})
146 | }
147 | formattedExpr := bytes.Join(lines, []byte{'\n'})
148 | _, err = w.Write(formattedExpr)
149 | return err
150 | }
151 |
152 | // DEPRECATED: use valast.Ptr instead.
153 | //
154 | // Addr returns a pointer to the given value.
155 | //
156 | // It is the only way to create a reference to certain values within a Go expression,
157 | // for example since &"hello" is illegal, it can instead be written in a single expression as:
158 | //
159 | // valast.Addr("hello").(*string)
160 | func Addr(v interface{}) interface{} {
161 | vv := reflect.ValueOf(v)
162 |
163 | // Create a slice with v in it so that we have an addressable value.
164 | sliceType := reflect.SliceOf(vv.Type())
165 | slice := reflect.MakeSlice(sliceType, 1, 1)
166 | if v != nil {
167 | slice.Index(0).Set(vv)
168 | }
169 | return slice.Index(0).Addr().Interface()
170 | }
171 |
172 | // AddrInterface returns a pointer to the given interface value, which is determined to be of type
173 | // T. For example, since &MyInterface(MyValue{}) is illegal, it can instead be written in a single
174 | // expression as:
175 | //
176 | // valast.AddrInterface(&MyValue{}, (*MyInterface)(nil))
177 | //
178 | // The second parameter should be a pointer to the interface type. This is needed because
179 | // reflect.ValueOf(&v).Type() returns *MyValue not MyInterface, due to reflect.ValueOf taking an
180 | // interface{} parameter and losing that type information.
181 | func AddrInterface(v, pointerToType interface{}) interface{} {
182 | // Create a slice with v in it so that we have an addressable value.
183 | sliceType := reflect.SliceOf(reflect.TypeOf(pointerToType).Elem())
184 | slice := reflect.MakeSlice(sliceType, 1, 1)
185 | if v != nil {
186 | slice.Index(0).Set(reflect.ValueOf(v))
187 | }
188 | return slice.Index(0).Addr().Interface()
189 | }
190 |
191 | func basicLit(vv reflect.Value, kind token.Token, builtinType string, v interface{}, opt *Options, typeExprCache typeExprCache) (Result, error) {
192 | typeExpr, err := typeExpr(vv.Type(), opt, typeExprCache)
193 | if err != nil {
194 | return Result{}, err
195 | }
196 | if opt.Unqualify && vv.Type().Name() == builtinType && vv.Type().PkgPath() == "" {
197 | return Result{AST: ast.NewIdent(fmt.Sprint(v))}, nil
198 | }
199 | if opt.ExportedOnly && typeExpr.RequiresUnexported {
200 | return Result{RequiresUnexported: true}, nil
201 | }
202 | return Result{
203 | AST: &ast.CallExpr{
204 | Fun: typeExpr.AST,
205 | Args: []ast.Expr{ast.NewIdent(fmt.Sprint(v))},
206 | },
207 | RequiresUnexported: typeExpr.RequiresUnexported,
208 | }, nil
209 | }
210 |
211 | // ErrInvalidType describes that the value is of a type that cannot be converted to an AST.
212 | type ErrInvalidType struct {
213 | // Value is the actual value that was being converted.
214 | Value interface{}
215 | }
216 |
217 | // Error implements the error interface.
218 | func (e *ErrInvalidType) Error() string {
219 | return fmt.Sprintf("valast: cannot convert value of type %T", e.Value)
220 | }
221 |
222 | // Result is a result from converting a Go value into its AST.
223 | type Result struct {
224 | // AST is the actual Go AST expression for the value.
225 | //
226 | // If Options.ExportedOnly == true, and the input value was unexported this field will be nil.
227 | AST ast.Expr
228 |
229 | // OmittedUnexported indicates if unexported fields were omitted or not. Only indicative if
230 | // Options.ExportedOnly == true.
231 | OmittedUnexported bool
232 |
233 | // RequiresUnexported indicates if the AST requires access to unexported types/values outside
234 | // of the package specified in the Options, and is thus invalid code.
235 | RequiresUnexported bool
236 |
237 | // Packages is the list of packages that are used in the AST.
238 | Packages []string
239 | }
240 |
241 | // AST converts the given value into its equivalent Go AST expression.
242 | //
243 | // The input must be one of these kinds:
244 | //
245 | // bool
246 | // int, int8, int16, int32, int64
247 | // uint, uint8, uint16, uint32, uint64
248 | // uintptr
249 | // float32, float64
250 | // complex64, complex128
251 | // array
252 | // interface
253 | // map
254 | // ptr
255 | // slice
256 | // string
257 | // struct
258 | // unsafe pointer
259 | //
260 | // The input type is reflect.Value instead of interface{}, specifically to allow converting
261 | // interfaces derived from struct fields or other reflection which would otherwise be lost if the
262 | // input type is interface{}.
263 | //
264 | // Cyclic data structures will have their cyclic pointer values emitted twice, followed by a nil
265 | // value. e.g. for a structure `foo` with field `bar` which points to the original `foo`:
266 | //
267 | // &foo{id: 123, bar: &foo{id: 123, bar: nil}}
268 | func AST(v reflect.Value, opt *Options) (Result, error) {
269 | var prof *profiler
270 | wantProfile, _ := strconv.ParseBool(os.Getenv("VALAST_PROFILE"))
271 | if wantProfile {
272 | prof = &profiler{}
273 | }
274 | packagesFound := make(map[string]bool)
275 | r, err := computeASTProfiled(v, opt, &cycleDetector{}, prof, typeExprCache{}, packagesFound)
276 | prof.dump()
277 |
278 | for k := range packagesFound {
279 | if k != "" {
280 | r.Packages = append(r.Packages, k)
281 | }
282 | }
283 | sort.Strings(r.Packages)
284 |
285 | return r, err
286 | }
287 |
288 | func computeASTProfiled(v reflect.Value, opt *Options, cycleDetector *cycleDetector, profiler *profiler, typeExprCache typeExprCache, packagesFound map[string]bool) (Result, error) {
289 | profiler.push(v)
290 | start := time.Now()
291 | r, err := computeAST(v, opt, cycleDetector, profiler, typeExprCache, packagesFound)
292 | profiler.pop(start)
293 | return r, err
294 | }
295 |
296 | func computeAST(v reflect.Value, opt *Options, cycleDetector *cycleDetector, profiler *profiler, typeExprCache typeExprCache, packagesFound map[string]bool) (Result, error) {
297 | if opt == nil {
298 | opt = &Options{}
299 | }
300 | if v == (reflect.Value{}) {
301 | // Technically this is an invalid reflect.Value, but we handle it to be gracious in the
302 | // case of:
303 | //
304 | // var x interface{}
305 | // valast.AST(reflect.ValueOf(x))
306 | //
307 | return Result{
308 | AST: ast.NewIdent("nil"),
309 | }, nil
310 | }
311 |
312 | vv := unexported(v)
313 | packagesFound[vv.Type().PkgPath()] = true
314 | switch vv.Kind() {
315 | case reflect.Bool:
316 | boolType, err := typeExpr(vv.Type(), opt, typeExprCache)
317 | if err != nil {
318 | return Result{}, err
319 | }
320 | if vv.Type().Name() == "bool" && vv.Type().PkgPath() == "" {
321 | return Result{AST: ast.NewIdent(fmt.Sprint(v))}, nil
322 | }
323 | if opt.ExportedOnly && boolType.RequiresUnexported {
324 | return Result{RequiresUnexported: true}, nil
325 | }
326 | return Result{
327 | AST: &ast.CallExpr{
328 | Fun: boolType.AST,
329 | Args: []ast.Expr{ast.NewIdent(fmt.Sprint(v))},
330 | },
331 | RequiresUnexported: boolType.RequiresUnexported,
332 | }, nil
333 | case reflect.Int:
334 | return basicLit(vv, token.INT, "int", v, opt, typeExprCache)
335 | case reflect.Int8:
336 | return basicLit(vv, token.INT, "int8", v, opt, typeExprCache)
337 | case reflect.Int16:
338 | return basicLit(vv, token.INT, "int16", v, opt, typeExprCache)
339 | case reflect.Int32:
340 | return basicLit(vv, token.INT, "int32", v, opt, typeExprCache)
341 | case reflect.Int64:
342 | return basicLit(vv, token.INT, "int64", v, opt, typeExprCache)
343 | case reflect.Uint:
344 | return basicLit(vv, token.INT, "uint", v, opt, typeExprCache)
345 | case reflect.Uint8:
346 | return basicLit(vv, token.INT, "uint8", v, opt, typeExprCache)
347 | case reflect.Uint16:
348 | return basicLit(vv, token.INT, "uint16", v, opt, typeExprCache)
349 | case reflect.Uint32:
350 | return basicLit(vv, token.INT, "uint32", v, opt, typeExprCache)
351 | case reflect.Uint64:
352 | return basicLit(vv, token.INT, "uint64", v, opt, typeExprCache)
353 | case reflect.Uintptr:
354 | return basicLit(vv, token.INT, "uintptr", v, opt, typeExprCache)
355 | case reflect.Float32:
356 | return basicLit(vv, token.FLOAT, "float32", v, opt, typeExprCache)
357 | case reflect.Float64:
358 | return basicLit(vv, token.FLOAT, "float64", v, opt, typeExprCache)
359 | case reflect.Complex64:
360 | return basicLit(vv, token.FLOAT, "complex64", v, opt, typeExprCache)
361 | case reflect.Complex128:
362 | return basicLit(vv, token.FLOAT, "complex128", v, opt, typeExprCache)
363 | case reflect.Array:
364 | if render, ok := customtype.Is(v.Type()); ok {
365 | return Result{
366 | AST: render(v.Interface()),
367 | }, nil
368 | }
369 |
370 | var (
371 | elts []ast.Expr
372 | requiresUnexported bool
373 | )
374 | for i := 0; i < vv.Len(); i++ {
375 | elem, err := computeASTProfiled(vv.Index(i), opt.withUnqualify(), cycleDetector, profiler, typeExprCache, packagesFound)
376 | if err != nil {
377 | return Result{}, err
378 | }
379 | if elem.RequiresUnexported {
380 | requiresUnexported = true
381 | }
382 | elts = append(elts, elem.AST)
383 | }
384 | arrayType, err := typeExpr(vv.Type(), opt, typeExprCache)
385 | if err != nil {
386 | return Result{}, err
387 | }
388 | return Result{
389 | AST: &ast.CompositeLit{
390 | Type: arrayType.AST,
391 | Elts: elts,
392 | },
393 | RequiresUnexported: arrayType.RequiresUnexported || requiresUnexported,
394 | }, nil
395 | case reflect.Interface:
396 | if opt.ExportedOnly && !ast.IsExported(vv.Type().Name()) {
397 | return Result{
398 | AST: nil,
399 | RequiresUnexported: true,
400 | }, nil
401 | }
402 | if opt.Unqualify {
403 | return computeASTProfiled(unexported(vv.Elem()), opt.withUnqualify(), cycleDetector, profiler, typeExprCache, packagesFound)
404 | }
405 | v, err := computeASTProfiled(unexported(vv.Elem()), opt, cycleDetector, profiler, typeExprCache, packagesFound)
406 | if err != nil {
407 | return Result{}, err
408 | }
409 | interfaceType, err := typeExpr(vv.Type(), opt, typeExprCache)
410 | if err != nil {
411 | return Result{}, err
412 | }
413 | return Result{
414 | AST: &ast.CompositeLit{
415 | Type: interfaceType.AST,
416 | Elts: []ast.Expr{v.AST},
417 | },
418 | RequiresUnexported: interfaceType.RequiresUnexported || v.RequiresUnexported,
419 | }, nil
420 | case reflect.Map:
421 | var (
422 | keyValueExprs []ast.Expr
423 | requiresUnexported, omittedUnexported bool
424 | keys = vv.MapKeys()
425 | )
426 | sort.Slice(keys, func(i, j int) bool {
427 | return valueLess(keys[i], keys[j])
428 | })
429 | for _, key := range keys {
430 | value := vv.MapIndex(key)
431 | k, err := computeASTProfiled(key, opt.withUnqualify(), cycleDetector, profiler, typeExprCache, packagesFound)
432 | if err != nil {
433 | return Result{}, err
434 | }
435 | if k.RequiresUnexported {
436 | if opt.ExportedOnly {
437 | omittedUnexported = true
438 | continue
439 | }
440 | requiresUnexported = true
441 | }
442 | if k.OmittedUnexported {
443 | omittedUnexported = true
444 | }
445 | v, err := computeASTProfiled(value, opt.withUnqualify(), cycleDetector, profiler, typeExprCache, packagesFound)
446 | if err != nil {
447 | return Result{}, err
448 | }
449 | if v.RequiresUnexported {
450 | if opt.ExportedOnly {
451 | omittedUnexported = true
452 | continue
453 | }
454 | requiresUnexported = true
455 | }
456 | if v.OmittedUnexported {
457 | omittedUnexported = true
458 | }
459 | keyValueExprs = append(keyValueExprs, &ast.KeyValueExpr{
460 | Key: k.AST,
461 | Value: v.AST,
462 | })
463 | }
464 | mapType, err := typeExpr(vv.Type(), opt, typeExprCache)
465 | if err != nil {
466 | return Result{}, err
467 | }
468 | return Result{
469 | AST: &ast.CompositeLit{
470 | Type: mapType.AST,
471 | Elts: keyValueExprs,
472 | },
473 | RequiresUnexported: requiresUnexported || mapType.RequiresUnexported,
474 | OmittedUnexported: omittedUnexported,
475 | }, nil
476 | case reflect.Ptr:
477 | ptrType, err := typeExpr(vv.Type(), opt, typeExprCache)
478 | if err != nil {
479 | return Result{}, err
480 | }
481 | isPtrToInterface := vv.Elem().Kind() == reflect.Interface
482 | if !isPtrToInterface && vv.IsNil() {
483 | if opt.Unqualify {
484 | return Result{AST: ast.NewIdent("nil")}, nil
485 | }
486 | return Result{
487 | AST: &ast.CallExpr{
488 | Fun: &ast.ParenExpr{X: ptrType.AST},
489 | Args: []ast.Expr{ast.NewIdent("nil")},
490 | },
491 | RequiresUnexported: ptrType.RequiresUnexported,
492 | }, nil
493 | }
494 | if opt.ExportedOnly && ptrType.RequiresUnexported {
495 | return Result{RequiresUnexported: true}, nil
496 | }
497 | if cycleDetector.push(vv.Interface()) {
498 | // cyclic data structure detected
499 | return Result{AST: ast.NewIdent("nil")}, nil
500 | }
501 |
502 | if !isPtrToInterface && !isAddressableKind(vv.Elem().Kind()) {
503 | if opt.Unqualify && literalNeedsQualification(vv.Elem()) {
504 | opt.Unqualify = false // the value must have qualification
505 | }
506 | elem, err := computeASTProfiled(vv.Elem(), opt, cycleDetector, profiler, typeExprCache, packagesFound)
507 | if err != nil {
508 | return Result{}, err
509 | }
510 | cycleDetector.pop(vv.Interface())
511 |
512 | // Pointers to unaddressable values can be created with help from valast.Addr.
513 | packagesFound["github.com/hexops/valast"] = true
514 | return Result{
515 | AST: &ast.CallExpr{
516 | Fun: &ast.SelectorExpr{
517 | X: ast.NewIdent("valast"),
518 | Sel: ast.NewIdent("Ptr"),
519 | },
520 | Args: []ast.Expr{elem.AST},
521 | },
522 | RequiresUnexported: ptrType.RequiresUnexported || elem.RequiresUnexported,
523 | OmittedUnexported: elem.OmittedUnexported,
524 | }, nil
525 | }
526 |
527 | elem, err := computeASTProfiled(vv.Elem(), opt, cycleDetector, profiler, typeExprCache, packagesFound)
528 | if err != nil {
529 | return Result{}, err
530 | }
531 | cycleDetector.pop(vv.Interface())
532 | if isPtrToInterface {
533 | // Pointers to interfaces can be created with help from valast.AddrInterface.
534 | return Result{
535 | AST: &ast.TypeAssertExpr{
536 | X: &ast.CallExpr{
537 | Fun: &ast.SelectorExpr{
538 | X: ast.NewIdent("valast"),
539 | Sel: ast.NewIdent("AddrInterface"),
540 | },
541 | Args: []ast.Expr{
542 | elem.AST,
543 | &ast.CallExpr{
544 | Fun: &ast.ParenExpr{X: ptrType.AST},
545 | Args: []ast.Expr{ast.NewIdent("nil")},
546 | },
547 | },
548 | },
549 | Type: ptrType.AST,
550 | },
551 | RequiresUnexported: ptrType.RequiresUnexported || elem.RequiresUnexported,
552 | OmittedUnexported: elem.OmittedUnexported,
553 | }, nil
554 | }
555 | if vv.Elem().Kind() == reflect.Ptr {
556 | // Pointers to pointers can be created with help from valast.Addr.
557 | return Result{
558 | AST: &ast.CallExpr{
559 | Fun: &ast.SelectorExpr{
560 | X: ast.NewIdent("valast"),
561 | Sel: ast.NewIdent("Ptr"),
562 | },
563 | Args: []ast.Expr{elem.AST},
564 | },
565 | RequiresUnexported: ptrType.RequiresUnexported || elem.RequiresUnexported,
566 | OmittedUnexported: elem.OmittedUnexported,
567 | }, nil
568 | }
569 | // Wrap custom type representations in generic pointer.
570 | if _, ok := customtype.Is(vv.Elem().Type()); ok {
571 | return Result{
572 | AST: pointifyASTExpr(elem.AST),
573 | }, nil
574 | }
575 | return Result{
576 | AST: &ast.UnaryExpr{
577 | Op: token.AND,
578 | X: elem.AST,
579 | },
580 | RequiresUnexported: ptrType.RequiresUnexported || elem.RequiresUnexported,
581 | OmittedUnexported: elem.OmittedUnexported,
582 | }, nil
583 | case reflect.Slice:
584 | var (
585 | elts []ast.Expr
586 | requiresUnexported bool
587 | )
588 | for i := 0; i < vv.Len(); i++ {
589 | elem, err := computeASTProfiled(vv.Index(i), opt.withUnqualify(), cycleDetector, profiler, typeExprCache, packagesFound)
590 | if err != nil {
591 | return Result{}, err
592 | }
593 | if elem.RequiresUnexported {
594 | requiresUnexported = true
595 | }
596 | elts = append(elts, elem.AST)
597 | }
598 | sliceType, err := typeExpr(vv.Type(), opt, typeExprCache)
599 | if err != nil {
600 | return Result{}, err
601 | }
602 | return Result{
603 | AST: &ast.CompositeLit{
604 | Type: sliceType.AST,
605 | Elts: elts,
606 | },
607 | RequiresUnexported: requiresUnexported || sliceType.RequiresUnexported,
608 | }, nil
609 | case reflect.String:
610 | s := v.String()
611 | wantRawStringLiteral := len(s) > 40 && strings.Contains(s, "\n")
612 | wantRawStringLiteral = wantRawStringLiteral || strings.Contains(s, `"`)
613 | if wantRawStringLiteral && !strings.Contains(s, "`") {
614 | return basicLit(vv, token.STRING, "string", "`"+s+"`", opt.withUnqualify(), typeExprCache)
615 | }
616 | return basicLit(vv, token.STRING, "string", strconv.Quote(v.String()), opt.withUnqualify(), typeExprCache)
617 | case reflect.Struct:
618 | if render, ok := customtype.Is(v.Type()); ok {
619 | return Result{
620 | AST: render(v.Interface()),
621 | }, nil
622 | }
623 |
624 | var (
625 | structValue []ast.Expr
626 | requiresUnexported, omittedUnexported bool
627 | )
628 | for i := 0; i < v.NumField(); i++ {
629 | if unexported(v.Field(i)).IsZero() {
630 | continue
631 | }
632 | value, err := computeASTProfiled(unexported(v.Field(i)), opt.withUnqualify(), cycleDetector, profiler, typeExprCache, packagesFound)
633 | if err != nil {
634 | return Result{}, err
635 | }
636 | if value.RequiresUnexported {
637 | if opt.ExportedOnly {
638 | omittedUnexported = true
639 | continue
640 | }
641 | requiresUnexported = true
642 | }
643 | if value.OmittedUnexported {
644 | omittedUnexported = true
645 | }
646 | structValue = append(structValue, &ast.KeyValueExpr{
647 | Key: ast.NewIdent(v.Type().Field(i).Name),
648 | Value: value.AST,
649 | })
650 | }
651 | structType, err := typeExpr(vv.Type(), opt, typeExprCache)
652 | if err != nil {
653 | return Result{}, err
654 | }
655 | if opt.ExportedOnly && structType.RequiresUnexported {
656 | return Result{RequiresUnexported: true}, nil
657 | }
658 | return Result{
659 | AST: &ast.CompositeLit{
660 | Type: structType.AST,
661 | Elts: structValue,
662 | },
663 | RequiresUnexported: structType.RequiresUnexported || requiresUnexported,
664 | OmittedUnexported: omittedUnexported,
665 | }, nil
666 | case reflect.UnsafePointer:
667 | unsafePointerType, err := typeExpr(vv.Type(), opt, typeExprCache)
668 | if err != nil {
669 | return Result{}, err
670 | }
671 | return Result{
672 | AST: &ast.CallExpr{
673 | Fun: unsafePointerType.AST,
674 | Args: []ast.Expr{
675 | &ast.CallExpr{
676 | Fun: ast.NewIdent("uintptr"),
677 | Args: []ast.Expr{&ast.BasicLit{Kind: token.INT, Value: fmt.Sprintf("0x%x", v.Pointer())}},
678 | },
679 | },
680 | },
681 | RequiresUnexported: unsafePointerType.RequiresUnexported,
682 | OmittedUnexported: unsafePointerType.OmittedUnexported,
683 | }, nil
684 | default:
685 | return Result{AST: nil}, &ErrInvalidType{Value: v.Interface()}
686 | }
687 | }
688 |
689 | // literalNeedsQualification tells if a literal value needs qualification or not when initializing
690 | // a value of type `interface{}`, e.g. being passed into the valast.Addr() helper function.
691 | func literalNeedsQualification(v reflect.Value) bool {
692 | k := v.Kind()
693 |
694 | // Simple cases: Types whose literal values are always implicitly qualified
695 | if k == reflect.Bool ||
696 | k == reflect.String ||
697 | k == reflect.Int ||
698 | k == reflect.Array ||
699 | k == reflect.Chan ||
700 | k == reflect.Func ||
701 | k == reflect.Interface ||
702 | k == reflect.Map ||
703 | k == reflect.Ptr ||
704 | k == reflect.Slice ||
705 | k == reflect.Struct ||
706 | k == reflect.UnsafePointer {
707 | return false
708 | }
709 |
710 | // Floats. If passed to a function accepting an `interface{}` value:
711 | //
712 | // * A whole number `1234` would be considered an integer.
713 | // * A non-whole number `3.14` would be considered `float64`
714 | //
715 | if k == reflect.Float64 && v.Float() != math.Trunc(v.Float()) {
716 | return false // A float64 and not a whole number, so no qualification needed.
717 | }
718 | return true // needs qualification
719 | }
720 |
721 | func unexported(v reflect.Value) reflect.Value {
722 | if v == (reflect.Value{}) {
723 | return v
724 | }
725 | return bypass.UnsafeReflectValue(v)
726 | }
727 |
728 | // pointifyASTExpr wraps an expression in a call to the `Ptr` helper function.
729 | //
730 | // valast.Ptr(//...)
731 | func pointifyASTExpr(e ast.Expr) ast.Expr {
732 | return &ast.CallExpr{
733 | Fun: &ast.SelectorExpr{
734 | X: ast.NewIdent("valast"),
735 | Sel: ast.NewIdent("Ptr"),
736 | },
737 | Args: []ast.Expr{e},
738 | }
739 | }
740 |
--------------------------------------------------------------------------------
/valast_test.go:
--------------------------------------------------------------------------------
1 | package valast
2 |
3 | import (
4 | "reflect"
5 | "testing"
6 | "time"
7 | "unsafe"
8 |
9 | "github.com/hexops/autogold"
10 | "github.com/hexops/valast/internal/test"
11 | )
12 |
13 | type foo struct {
14 | bar string
15 | }
16 |
17 | type baz struct {
18 | Bam complex64
19 | zeta foo
20 | Beta interface{}
21 | }
22 |
23 | type ExportedBaz struct {
24 | Bam complex64
25 | zeta foo
26 | Beta interface{}
27 | }
28 |
29 | func TestString(t *testing.T) {
30 | tests := []struct {
31 | name string
32 | input interface{}
33 | opt *Options
34 | }{
35 | {
36 | name: "bool",
37 | input: true,
38 | },
39 | {
40 | name: "bool_unqualify",
41 | input: false,
42 | opt: &Options{Unqualify: true},
43 | },
44 | {
45 | name: "int32",
46 | input: int32(1234),
47 | },
48 | {
49 | name: "int32_unqualify",
50 | input: int32(1234),
51 | opt: &Options{Unqualify: true},
52 | },
53 | {
54 | name: "uintptr",
55 | input: uintptr(1234),
56 | },
57 | {
58 | name: "uintptr_unqualify",
59 | input: uintptr(1234),
60 | opt: &Options{Unqualify: true},
61 | },
62 | {
63 | name: "float64",
64 | input: float64(1.234),
65 | },
66 | {
67 | name: "float64_unqualify",
68 | input: float64(1.234),
69 | opt: &Options{Unqualify: true},
70 | },
71 | {
72 | name: "complex64",
73 | input: complex64(1.234),
74 | },
75 | {
76 | name: "complex64_unqualify",
77 | input: complex64(1.234),
78 | opt: &Options{Unqualify: true},
79 | },
80 | {
81 | name: "string",
82 | input: string("hello \t world"),
83 | },
84 | {
85 | name: "string_unqualify",
86 | input: string(`one
87 | two
88 | three`),
89 | opt: &Options{Unqualify: true},
90 | },
91 | {
92 | name: "struct_anonymous",
93 | input: struct {
94 | a, b int
95 | V string
96 | }{a: 1, b: 2, V: "efg"},
97 | },
98 | {
99 | name: "struct_same_package",
100 | input: baz{
101 | Bam: 1.34,
102 | zeta: foo{
103 | bar: "hello",
104 | },
105 | },
106 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
107 | },
108 | {
109 | name: "struct_external_package",
110 | input: test.NewBaz(),
111 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
112 | },
113 | {
114 | name: "array",
115 | input: [2]*baz{
116 | {Beta: "foo"},
117 | {Beta: 123},
118 | },
119 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
120 | },
121 | {
122 | name: "slice",
123 | input: []*baz{
124 | {Beta: "foo"},
125 | {Beta: 123},
126 | {Beta: 3},
127 | },
128 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
129 | },
130 | {
131 | name: "nil",
132 | input: nil,
133 | },
134 | {
135 | name: "interface_anonymous_nil",
136 | input: interface {
137 | a() string
138 | }(nil),
139 | },
140 | {
141 | name: "interface_anonymous",
142 | input: &struct {
143 | v interface {
144 | String() string
145 | Baz() (err error)
146 | }
147 | }{v: test.NewBaz()},
148 | },
149 | {
150 | name: "interface_builtin",
151 | input: &struct {
152 | v error
153 | }{v: nil},
154 | },
155 | {
156 | name: "interface",
157 | input: &struct {
158 | v test.Bazer
159 | }{v: test.NewBaz()},
160 | },
161 | {
162 | name: "unsafe_pointer",
163 | input: unsafe.Pointer(uintptr(0xdeadbeef)),
164 | },
165 | {
166 | name: "map",
167 | input: map[string]int32{
168 | "foo": 32,
169 | "bar": 64,
170 | },
171 | },
172 | {
173 | name: "time_utc",
174 | input: time.Date(2016, 1, 2, 15, 4, 5, 0, time.UTC),
175 | },
176 | {
177 | name: "time_local",
178 | input: time.Date(2016, 1, 2, 15, 4, 5, 0, time.Local),
179 | },
180 | }
181 | for _, tst := range tests {
182 | tst := tst
183 | t.Run(tst.name, func(t *testing.T) {
184 | got := StringWithOptions(tst.input, tst.opt)
185 | autogold.Equal(t, got)
186 | })
187 | }
188 | }
189 |
190 | // TestRecursion tests how recursive and cyclic data types/values are handled.
191 | func TestRecursion(t *testing.T) {
192 | type foo struct {
193 | name string
194 | bar *foo
195 | }
196 | cyclic := &foo{name: "one"}
197 | cyclic.bar = cyclic
198 | tests := []struct {
199 | name string
200 | input interface{}
201 | opt *Options
202 | }{
203 | {
204 | name: "basic",
205 | input: &foo{
206 | name: "one",
207 | bar: &foo{
208 | name: "two",
209 | bar: &foo{
210 | name: "three",
211 | bar: &foo{
212 | name: "four",
213 | bar: &foo{
214 | name: "five",
215 | },
216 | },
217 | },
218 | },
219 | },
220 | },
221 | {
222 | name: "struct_cyclic",
223 | input: cyclic,
224 | },
225 | }
226 | for _, tst := range tests {
227 | tst := tst
228 | t.Run(tst.name, func(t *testing.T) {
229 | got := StringWithOptions(tst.input, tst.opt)
230 | autogold.Equal(t, got)
231 | })
232 | }
233 | }
234 |
235 | // TestEdgeCases tests known edge-cases and past bugs that do not fit any of the broader test
236 | // categories.
237 | func TestEdgeCases(t *testing.T) {
238 | var (
239 | nilInterface test.Bazer
240 | nilInterfacePointer = &nilInterface
241 | nilInterfacePointerPointer = &nilInterfacePointer
242 | bazer test.Bazer = test.NewBaz()
243 | bazerPointer = &bazer
244 | )
245 | tests := []struct {
246 | name string
247 | input interface{}
248 | opt *Options
249 | }{
250 | {
251 | name: "ptr_to_interface",
252 | input: &struct {
253 | v *test.Bazer
254 | }{v: &bazer},
255 | },
256 | {
257 | name: "ptr_to_ptr_to_interface",
258 | input: &struct {
259 | v **test.Bazer
260 | }{v: &bazerPointer},
261 | },
262 | {
263 | name: "ptr_to_nil_interface",
264 | input: &struct {
265 | v *test.Bazer
266 | }{v: &nilInterface},
267 | },
268 | {
269 | name: "ptr2_to_nil_interface",
270 | input: &struct {
271 | v **test.Bazer
272 | }{v: &nilInterfacePointer},
273 | },
274 | {
275 | name: "ptr3_to_nil_interface",
276 | input: &struct {
277 | v ***test.Bazer
278 | }{v: &nilInterfacePointerPointer},
279 | },
280 | {
281 | name: "nil_interface_pointer",
282 | input: &struct {
283 | v *test.Bazer
284 | }{v: nil},
285 | },
286 | }
287 | for _, tst := range tests {
288 | tst := tst
289 | t.Run(tst.name, func(t *testing.T) {
290 | got := StringWithOptions(tst.input, tst.opt)
291 | autogold.Equal(t, got)
292 | })
293 | }
294 | }
295 |
296 | // TestExportedOnly_input tests the behavior of Options.ExportedOnly when enabled with a direct unexported input.
297 | func TestExportedOnly_input(t *testing.T) {
298 | type (
299 | unexportedBool bool
300 | unexportedInt int
301 | unexportedInt8 int8
302 | unexportedInt16 int16
303 | unexportedInt32 int32
304 | unexportedInt64 int64
305 | unexportedUint uint
306 | unexportedUint8 uint8
307 | unexportedUint16 uint16
308 | unexportedUint32 uint32
309 | unexportedUint64 uint64
310 | unexportedUintptr uintptr
311 | unexportedFloat32 float32
312 | unexportedFloat64 float64
313 | unexportedComplex64 complex64
314 | unexportedComplex128 complex128
315 | unexportedArray [1]float32
316 | unexportedInterface error
317 | unexportedMap map[string]string
318 | unexportedPointer *int
319 | unexportedSlice []int
320 | unexportedString string
321 | unexportedStruct struct{ A string }
322 | unexportedUnsafePointer unsafe.Pointer
323 | )
324 | tests := []struct {
325 | name string
326 | input interface{}
327 | opt *Options
328 | }{
329 | {
330 | name: "struct_same_package",
331 | input: baz{
332 | Bam: 1.34,
333 | zeta: foo{
334 | bar: "hello",
335 | },
336 | },
337 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast", ExportedOnly: true},
338 | },
339 | {
340 | name: "bool",
341 | input: unexportedBool(true),
342 | opt: &Options{PackageName: "other", PackagePath: "github.com/other/other", ExportedOnly: true},
343 | },
344 | {
345 | name: "int",
346 | input: unexportedInt(1),
347 | opt: &Options{PackageName: "other", PackagePath: "github.com/other/other", ExportedOnly: true},
348 | },
349 | {
350 | name: "int8",
351 | input: unexportedInt8(1),
352 | opt: &Options{PackageName: "other", PackagePath: "github.com/other/other", ExportedOnly: true},
353 | },
354 | {
355 | name: "int16",
356 | input: unexportedInt16(1),
357 | opt: &Options{PackageName: "other", PackagePath: "github.com/other/other", ExportedOnly: true},
358 | },
359 | {
360 | name: "int32",
361 | input: unexportedInt32(1),
362 | opt: &Options{PackageName: "other", PackagePath: "github.com/other/other", ExportedOnly: true},
363 | },
364 | {
365 | name: "int64",
366 | input: unexportedInt64(1),
367 | opt: &Options{PackageName: "other", PackagePath: "github.com/other/other", ExportedOnly: true},
368 | },
369 | {
370 | name: "uint",
371 | input: unexportedUint(1),
372 | opt: &Options{PackageName: "other", PackagePath: "github.com/other/other", ExportedOnly: true},
373 | },
374 | {
375 | name: "uint8",
376 | input: unexportedUint8(1),
377 | opt: &Options{PackageName: "other", PackagePath: "github.com/other/other", ExportedOnly: true},
378 | },
379 | {
380 | name: "uint16",
381 | input: unexportedUint16(1),
382 | opt: &Options{PackageName: "other", PackagePath: "github.com/other/other", ExportedOnly: true},
383 | },
384 | {
385 | name: "uint32",
386 | input: unexportedUint32(1),
387 | opt: &Options{PackageName: "other", PackagePath: "github.com/other/other", ExportedOnly: true},
388 | },
389 | {
390 | name: "uint64",
391 | input: unexportedUint64(1),
392 | opt: &Options{PackageName: "other", PackagePath: "github.com/other/other", ExportedOnly: true},
393 | },
394 | {
395 | name: "uintptr",
396 | input: unexportedUintptr(1),
397 | opt: &Options{PackageName: "other", PackagePath: "github.com/other/other", ExportedOnly: true},
398 | },
399 | {
400 | name: "float32",
401 | input: unexportedFloat32(1),
402 | opt: &Options{PackageName: "other", PackagePath: "github.com/other/other", ExportedOnly: true},
403 | },
404 | {
405 | name: "float64",
406 | input: unexportedFloat64(1),
407 | opt: &Options{PackageName: "other", PackagePath: "github.com/other/other", ExportedOnly: true},
408 | },
409 | {
410 | name: "complex64",
411 | input: unexportedComplex64(1),
412 | opt: &Options{PackageName: "other", PackagePath: "github.com/other/other", ExportedOnly: true},
413 | },
414 | {
415 | name: "complex128",
416 | input: unexportedComplex128(1),
417 | opt: &Options{PackageName: "other", PackagePath: "github.com/other/other", ExportedOnly: true},
418 | },
419 | {
420 | name: "array",
421 | input: unexportedArray{1.0},
422 | opt: &Options{PackageName: "other", PackagePath: "github.com/other/other", ExportedOnly: true},
423 | },
424 | {
425 | name: "interface",
426 | input: struct {
427 | V unexportedInterface
428 | }{V: nil},
429 | opt: &Options{PackageName: "other", PackagePath: "github.com/other/other", ExportedOnly: true},
430 | },
431 | {
432 | name: "map",
433 | input: unexportedMap{
434 | "a": "b",
435 | },
436 | opt: &Options{PackageName: "other", PackagePath: "github.com/other/other", ExportedOnly: true},
437 | },
438 | {
439 | name: "map_unexported_key_type",
440 | input: map[unexportedInt]string{},
441 | opt: &Options{PackageName: "other", PackagePath: "github.com/other/other", ExportedOnly: true},
442 | },
443 | {
444 | name: "map_unexported_value_type",
445 | input: map[string]unexportedInt{},
446 | opt: &Options{PackageName: "other", PackagePath: "github.com/other/other", ExportedOnly: true},
447 | },
448 | {
449 | name: "map_unexported_key_omitted",
450 | input: map[string]interface{}{
451 | "a": unexportedInt(1),
452 | },
453 | opt: &Options{PackageName: "other", PackagePath: "github.com/other/other", ExportedOnly: true},
454 | },
455 | {
456 | name: "map_unexported_value_omitted",
457 | input: map[interface{}]string{
458 | unexportedInt(1): "a",
459 | },
460 | opt: &Options{PackageName: "other", PackagePath: "github.com/other/other", ExportedOnly: true},
461 | },
462 | {
463 | name: "pointer",
464 | input: unexportedPointer(nil),
465 | opt: &Options{PackageName: "other", PackagePath: "github.com/other/other", ExportedOnly: true},
466 | },
467 | {
468 | name: "slice",
469 | input: unexportedSlice{1, 2, 3},
470 | opt: &Options{PackageName: "other", PackagePath: "github.com/other/other", ExportedOnly: true},
471 | },
472 | {
473 | name: "string",
474 | input: unexportedString("hello"),
475 | opt: &Options{PackageName: "other", PackagePath: "github.com/other/other", ExportedOnly: true},
476 | },
477 | {
478 | name: "struct",
479 | input: unexportedStruct{A: "b"},
480 | opt: &Options{PackageName: "other", PackagePath: "github.com/other/other", ExportedOnly: true},
481 | },
482 | {
483 | name: "unsafe_pointer",
484 | input: unexportedUnsafePointer(uintptr(0xdeadbeef)),
485 | opt: &Options{PackageName: "other", PackagePath: "github.com/other/other", ExportedOnly: true},
486 | },
487 | }
488 | for _, tst := range tests {
489 | tst := tst
490 | t.Run(tst.name, func(t *testing.T) {
491 | got := StringWithOptions(tst.input, tst.opt)
492 | autogold.Equal(t, got)
493 | })
494 | }
495 | }
496 |
497 | // TestExportedOnly_nested tests the behavior of Options.ExportedOnly when enabled with an unexported
498 | // value/type nested below an exported one.
499 | func TestExportedOnly_nested(t *testing.T) {
500 | tests := []struct {
501 | name string
502 | input interface{}
503 | opt *Options
504 | }{
505 | {
506 | name: "external_struct_unexported_field_omitted",
507 | input: test.NewBaz(),
508 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast", ExportedOnly: true},
509 | },
510 | {
511 | name: "struct_same_package_unexported_field_omitted",
512 | input: ExportedBaz{
513 | Bam: 1.34,
514 | zeta: foo{
515 | bar: "hello",
516 | },
517 | },
518 | opt: &Options{PackageName: "other", PackagePath: "github.com/other/other", ExportedOnly: true},
519 | },
520 | {
521 | name: "interface",
522 | input: struct {
523 | zeta foo
524 | }{zeta: foo{bar: "baz"}},
525 | opt: &Options{PackageName: "other", PackagePath: "github.com/other/other", ExportedOnly: true},
526 | },
527 | }
528 | for _, tst := range tests {
529 | tst := tst
530 | t.Run(tst.name, func(t *testing.T) {
531 | got := StringWithOptions(tst.input, tst.opt)
532 | autogold.Equal(t, got)
533 | })
534 | }
535 | }
536 |
537 | // TestUnexportedInputs tests the behavior of Options.ExportedOnly when disabled.
538 | func TestUnexportedInputs(t *testing.T) {
539 | type (
540 | unexportedBool bool
541 | unexportedInt int
542 | unexportedInt8 int8
543 | unexportedInt16 int16
544 | unexportedInt32 int32
545 | unexportedInt64 int64
546 | unexportedUint uint
547 | unexportedUint8 uint8
548 | unexportedUint16 uint16
549 | unexportedUint32 uint32
550 | unexportedUint64 uint64
551 | unexportedUintptr uintptr
552 | unexportedFloat32 float32
553 | unexportedFloat64 float64
554 | unexportedComplex64 complex64
555 | unexportedComplex128 complex128
556 | unexportedArray [1]float32
557 | unexportedInterface error
558 | unexportedMap map[string]string
559 | unexportedPointer *int
560 | unexportedSlice []int
561 | unexportedString string
562 | unexportedStruct struct{ A string }
563 | unexportedUnsafePointer unsafe.Pointer
564 | )
565 | tests := []struct {
566 | name string
567 | input interface{}
568 | opt *Options
569 | }{
570 | {
571 | name: "bool",
572 | input: unexportedBool(true),
573 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
574 | },
575 | {
576 | name: "int",
577 | input: unexportedInt(1),
578 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
579 | },
580 | {
581 | name: "int8",
582 | input: unexportedInt8(1),
583 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
584 | },
585 | {
586 | name: "int16",
587 | input: unexportedInt16(1),
588 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
589 | },
590 | {
591 | name: "int32",
592 | input: unexportedInt32(1),
593 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
594 | },
595 | {
596 | name: "int64",
597 | input: unexportedInt64(1),
598 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
599 | },
600 | {
601 | name: "uint",
602 | input: unexportedUint(1),
603 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
604 | },
605 | {
606 | name: "uint8",
607 | input: unexportedUint8(1),
608 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
609 | },
610 | {
611 | name: "uint16",
612 | input: unexportedUint16(1),
613 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
614 | },
615 | {
616 | name: "uint32",
617 | input: unexportedUint32(1),
618 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
619 | },
620 | {
621 | name: "uint64",
622 | input: unexportedUint64(1),
623 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
624 | },
625 | {
626 | name: "uintptr",
627 | input: unexportedUintptr(1),
628 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
629 | },
630 | {
631 | name: "float32",
632 | input: unexportedFloat32(1),
633 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
634 | },
635 | {
636 | name: "float64",
637 | input: unexportedFloat64(1),
638 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
639 | },
640 | {
641 | name: "complex64",
642 | input: unexportedComplex64(1),
643 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
644 | },
645 | {
646 | name: "complex128",
647 | input: unexportedComplex128(1),
648 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
649 | },
650 | {
651 | name: "array",
652 | input: unexportedArray{1.0},
653 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
654 | },
655 | {
656 | name: "interface",
657 | input: struct {
658 | V unexportedInterface
659 | }{V: nil},
660 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
661 | },
662 | {
663 | name: "map",
664 | input: unexportedMap{
665 | "a": "b",
666 | },
667 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
668 | },
669 | {
670 | name: "pointer",
671 | input: unexportedPointer(nil),
672 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
673 | },
674 | {
675 | name: "slice",
676 | input: unexportedSlice{1, 2, 3},
677 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
678 | },
679 | {
680 | name: "string",
681 | input: unexportedString("hello"),
682 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
683 | },
684 | {
685 | name: "struct",
686 | input: unexportedStruct{A: "b"},
687 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
688 | },
689 | {
690 | name: "unsafe_pointer",
691 | input: unexportedUnsafePointer(uintptr(0xdeadbeef)),
692 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
693 | },
694 | }
695 | for _, tst := range tests {
696 | tst := tst
697 | t.Run(tst.name, func(t *testing.T) {
698 | got := StringWithOptions(tst.input, tst.opt)
699 | autogold.Equal(t, got)
700 | })
701 | }
702 | }
703 |
704 | // TestPointers tests to ensure valast.Addr and & are used when appropriate.
705 | func TestPointers(t *testing.T) {
706 | var (
707 | boolValue = true
708 | boolValuePointer = &boolValue
709 | intValue int = 1
710 | intValuePointer = &intValue
711 | intValuePointerPointer = &intValuePointer
712 | int8Value int8 = 1
713 | int16Value int16 = 1
714 | int32Value int32 = 1
715 | int64Value int64 = 1
716 | uintValue uint = 1
717 | uint8Value uint8 = 1
718 | uint16Value uint16 = 1
719 | uint32Value uint32 = 1
720 | uint64Value uint64 = 1
721 | uintptrValue uintptr = 1
722 | float32Value float32 = 1
723 | float64Value float64 = 1
724 | complex64Value complex64 = 1
725 | complex128Value complex128 = 1
726 | arrayValue = [1]float32{1}
727 | arrayValuePointer = &arrayValue
728 | interfaceValue = test.Bazer(test.NewBaz())
729 | interfaceValuePointer = &interfaceValue
730 | mapValue = map[string]string{"hello": "world"}
731 | mapValuePointer = &mapValue
732 | pointerValue = &uintValue
733 | pointerValuePointer = &pointerValue
734 | sliceValue = []int{1, 2, 3}
735 | sliceValuePointer = &sliceValue
736 | stringValue = "hello world"
737 | structValue = struct{ A string }{A: "hello world"}
738 | structValuePointer = &structValue
739 | unsafePointerValue = unsafe.Pointer(uintptr(0xdeadbeef))
740 | unsafePointerValuePointer = &unsafePointerValue
741 | timeUtcValue = time.Date(2016, 1, 2, 15, 4, 5, 0, time.UTC)
742 | timeLocalValue = time.Date(2016, 1, 2, 15, 4, 5, 0, time.Local)
743 | )
744 | tests := []struct {
745 | name string
746 | input interface{}
747 | opt *Options
748 | }{
749 | {
750 | name: "bool",
751 | input: &boolValue,
752 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
753 | },
754 | {
755 | name: "bool2",
756 | input: &boolValuePointer,
757 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
758 | },
759 |
760 | {
761 | name: "int",
762 | input: &intValue,
763 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
764 | },
765 | {
766 | name: "int2",
767 | input: &intValuePointer,
768 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
769 | },
770 | {
771 | name: "int3",
772 | input: &intValuePointerPointer,
773 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
774 | },
775 | {
776 | name: "int8",
777 | input: &int8Value,
778 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
779 | },
780 | {
781 | name: "int16",
782 | input: &int16Value,
783 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
784 | },
785 | {
786 | name: "int32",
787 | input: &int32Value,
788 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
789 | },
790 | {
791 | name: "int64",
792 | input: &int64Value,
793 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
794 | },
795 | {
796 | name: "uint",
797 | input: &uintValue,
798 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
799 | },
800 | {
801 | name: "uint8",
802 | input: &uint8Value,
803 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
804 | },
805 | {
806 | name: "uint16",
807 | input: &uint16Value,
808 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
809 | },
810 | {
811 | name: "uint32",
812 | input: &uint32Value,
813 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
814 | },
815 | {
816 | name: "uint64",
817 | input: &uint64Value,
818 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
819 | },
820 | {
821 | name: "uintptr",
822 | input: &uintptrValue,
823 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
824 | },
825 | {
826 | name: "float32",
827 | input: &float32Value,
828 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
829 | },
830 | {
831 | name: "float64",
832 | input: &float64Value,
833 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
834 | },
835 | {
836 | name: "complex64",
837 | input: &complex64Value,
838 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
839 | },
840 | {
841 | name: "complex128",
842 | input: &complex128Value,
843 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
844 | },
845 | {
846 | name: "array",
847 | input: &arrayValue,
848 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
849 | },
850 | {
851 | name: "array2",
852 | input: &arrayValuePointer,
853 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
854 | },
855 | {
856 | name: "interface",
857 | input: &interfaceValue,
858 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
859 | },
860 | {
861 | name: "interface2",
862 | input: &interfaceValuePointer,
863 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
864 | },
865 | {
866 | name: "map",
867 | input: &mapValue,
868 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
869 | },
870 | {
871 | name: "map2",
872 | input: &mapValuePointer,
873 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
874 | },
875 | {
876 | name: "pointer",
877 | input: &pointerValue,
878 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
879 | },
880 | {
881 | name: "pointer2", // ***uint
882 | input: &pointerValuePointer,
883 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
884 | },
885 | {
886 | name: "slice",
887 | input: &sliceValue,
888 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
889 | },
890 | {
891 | name: "slice2",
892 | input: &sliceValuePointer,
893 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
894 | },
895 | {
896 | name: "string",
897 | input: &stringValue,
898 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
899 | },
900 | {
901 | name: "struct",
902 | input: &structValue,
903 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
904 | },
905 | {
906 | name: "struct2",
907 | input: &structValuePointer,
908 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
909 | },
910 | {
911 | name: "unsafe_pointer",
912 | input: &unsafePointerValue,
913 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
914 | },
915 | {
916 | name: "unsafe_pointer2",
917 | input: &unsafePointerValuePointer,
918 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
919 | },
920 | {
921 | name: "time_utc",
922 | input: &timeUtcValue,
923 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
924 | },
925 | {
926 | name: "time_local",
927 | input: &timeLocalValue,
928 | opt: &Options{PackageName: "valast", PackagePath: "github.com/hexops/valast"},
929 | },
930 | }
931 | for _, tst := range tests {
932 | tst := tst
933 | t.Run(tst.name, func(t *testing.T) {
934 | got := StringWithOptions(tst.input, tst.opt)
935 | autogold.Equal(t, got)
936 | })
937 | }
938 | }
939 |
940 | func TestStringFormatting(t *testing.T) {
941 | tests := []struct {
942 | name string
943 | input interface{}
944 | }{
945 | {
946 | name: "short_single_line",
947 | input: "hello world",
948 | },
949 | {
950 | name: "long_single_line_180",
951 | input: "hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world ",
952 | },
953 | {
954 | name: "short_multi_line",
955 | input: "hello\nworld",
956 | },
957 | {
958 | name: "long_multi_line_180",
959 | input: `hello world hello world hello world hello world hello world hello world hello world hello world
960 | hello world hello world hello world hello world hello world hello world hello world`,
961 | },
962 | {
963 | name: "long_multi_line_with_backticks",
964 | input: "hello world hello world hello world hello world hello world hello world hello world hello world\n`hello world hello world hello world hello world hello world hello world hello world",
965 | },
966 | {
967 | name: "short_quotes",
968 | input: `"hello" "world"`,
969 | },
970 | {
971 | name: "long_multi_line_with_quotes",
972 | input: `"hello world"! "hello world" hello world hello world hello world hello world hello world hello world
973 | hello world hello world hello world hello world "hello" world hello world hello world`,
974 | },
975 | }
976 | for _, tst := range tests {
977 | tst := tst
978 | t.Run(tst.name, func(t *testing.T) {
979 | got := String(tst.input)
980 | autogold.Equal(t, got)
981 | })
982 | }
983 | }
984 |
985 | func TestAddrInterface(t *testing.T) {
986 | var bazer test.Bazer = test.NewBaz()
987 | got := AddrInterface(bazer, (*test.Bazer)(nil)).(*test.Bazer)
988 | if *got != bazer {
989 | t.Fatal("*got != v")
990 | }
991 | }
992 |
993 | func TestAddrInterface_golden(t *testing.T) {
994 | // Confirms the AddrInterface calls in testdata/TestEdgeCases/ptr_to_* are valid.
995 | _ = AddrInterface(&test.Baz{
996 | Bam: (1.34 + 0i),
997 | }, (*test.Bazer)(nil)).(*test.Bazer)
998 |
999 | _ = AddrInterface(nil, (*test.Bazer)(nil)).(*test.Bazer)
1000 |
1001 | _ = Addr(AddrInterface(&test.Baz{
1002 | Bam: (1.34 + 0i),
1003 | }, (*test.Bazer)(nil)).(*test.Bazer)).(**test.Bazer)
1004 |
1005 | _ = Addr(AddrInterface(nil, (*test.Bazer)(nil)).(*test.Bazer)).(**test.Bazer)
1006 |
1007 | _ = Addr(Addr(AddrInterface(nil,
1008 | (*test.Bazer)(nil)).(*test.Bazer)).(**test.Bazer)).(***test.Bazer)
1009 | }
1010 |
1011 | func TestAddr_AddrInterface(t *testing.T) {
1012 | var bazer test.Bazer = test.NewBaz()
1013 | got := Addr(AddrInterface(bazer, (*test.Bazer)(nil)).(*test.Bazer)).(**test.Bazer)
1014 | if **got != bazer {
1015 | t.Fatal("*got != v")
1016 | }
1017 | }
1018 |
1019 | func TestAddr_string(t *testing.T) {
1020 | got := Addr("hello").(*string)
1021 | if *got != "hello" {
1022 | t.Fatal("*got != v")
1023 | }
1024 | }
1025 |
1026 | func TestAddr_int(t *testing.T) {
1027 | got := Addr(5).(*int)
1028 | if *got != 5 {
1029 | t.Fatal("*got != v")
1030 | }
1031 | }
1032 |
1033 | func TestAddr_pointer(t *testing.T) {
1034 | x := 5
1035 | got := Addr(&x).(**int)
1036 | if **got != 5 {
1037 | t.Fatal("*got != v")
1038 | }
1039 | }
1040 |
1041 | func TestPackages(t *testing.T) {
1042 | foo := test.NewFoo()
1043 | res, err := AST(reflect.ValueOf(foo), nil)
1044 | if err != nil {
1045 | t.Fatal("error parsing foo for packages", err)
1046 | }
1047 | if len(res.Packages) != 1 {
1048 | t.Fatal("number of expected packages is 1")
1049 | }
1050 | if res.Packages[0] != "github.com/hexops/valast/internal/test" {
1051 | t.Fatal("unexpected package name detected")
1052 | }
1053 | }
1054 |
1055 | func TestIssue15_addr_values_must_be_qualified(t *testing.T) {
1056 | f32 := float32(3607)
1057 | i32 := int32(3607)
1058 | i64 := int64(3607)
1059 | u32 := uint32(3607)
1060 | u64 := uint64(3607)
1061 | i := int(3607)
1062 | u := uint(3607)
1063 | str := "foobar"
1064 | f64NonInteger := 3.14
1065 | input := struct {
1066 | a *float32
1067 | b *int32
1068 | c *int64
1069 | d *uint32
1070 | e *uint64
1071 | f *int
1072 | g *uint
1073 | h *string
1074 | i *float64
1075 | }{&f32, &i32, &i64, &u32, &u64, &i, &u, &str, &f64NonInteger}
1076 |
1077 | got := String(input)
1078 | autogold.Equal(t, got)
1079 | }
1080 |
1081 | func BenchmarkComplexType(b *testing.B) {
1082 | v := test.ComplexNode{
1083 | Left: &test.ComplexNode{
1084 | Child: &test.ComplexNodeChild{
1085 | Siblings: []*test.ComplexNode{nil, nil, nil},
1086 | },
1087 | },
1088 | }
1089 | for n := 0; n < b.N; n++ {
1090 | _ = String(v)
1091 | }
1092 | }
1093 |
--------------------------------------------------------------------------------