blob: ee4319056fdad40739b4e812557eb88bfe2f2960 [file] [log] [blame]
Joe Tsai27c2a762018-08-01 16:48:18 -07001// Copyright 2018 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package text
6
7import (
8 "fmt"
9 "math"
10 "strings"
11 "testing"
12 "unicode/utf8"
13
14 "github.com/google/go-cmp/cmp"
15 "github.com/google/go-cmp/cmp/cmpopts"
Damien Neile89e6242019-05-13 23:55:40 -070016 "google.golang.org/protobuf/internal/detrand"
17 "google.golang.org/protobuf/internal/flags"
18 "google.golang.org/protobuf/reflect/protoreflect"
Joe Tsai27c2a762018-08-01 16:48:18 -070019)
20
Joe Tsai71acbc72018-11-28 19:27:29 -080021// Disable detrand to enable direct comparisons on outputs.
22func init() { detrand.Disable() }
23
Herbie Ongc3f4d482018-11-22 14:29:07 -080024var S = fmt.Sprintf
25var V = ValueOf
26var ID = func(n protoreflect.Name) Value { return V(n) }
27
28type Lst = []Value
29type Msg = [][2]Value
30
Joe Tsai27c2a762018-08-01 16:48:18 -070031func Test(t *testing.T) {
32 const space = " \n\r\t"
Joe Tsai27c2a762018-08-01 16:48:18 -070033
34 tests := []struct {
35 in string
36 wantVal Value
37 wantOut string
38 wantOutBracket string
39 wantOutASCII string
40 wantOutIndent string
41 wantErr string
42 }{{
43 in: "",
44 wantVal: V(Msg{}),
45 wantOutIndent: "\n",
46 }, {
47 in: S("%s# hello%s", space, space),
48 wantVal: V(Msg{}),
49 }, {
50 in: S("%s# hello\rfoo:bar", space),
51 wantVal: V(Msg{}),
52 }, {
53 // Comments only extend until the newline.
54 in: S("%s# hello\nfoo:bar", space),
55 wantVal: V(Msg{{ID("foo"), ID("bar")}}),
56 wantOut: "foo:bar",
57 wantOutIndent: "foo: bar\n",
58 }, {
59 // NUL is an invalid whitespace since C++ uses C-strings.
60 in: "\x00",
61 wantErr: `invalid "\x00" as identifier`,
62 }, {
63 in: "foo:0",
64 wantVal: V(Msg{{ID("foo"), V(uint32(0))}}),
65 wantOut: "foo:0",
66 }, {
67 in: S("%sfoo%s:0", space, space),
68 wantVal: V(Msg{{ID("foo"), V(uint32(0))}}),
69 }, {
70 in: "foo bar:0",
71 wantErr: `expected ':' after message key`,
72 }, {
73 in: "[foo]:0",
74 wantVal: V(Msg{{V("foo"), V(uint32(0))}}),
75 wantOut: "[foo]:0",
76 wantOutIndent: "[foo]: 0\n",
77 }, {
78 in: S("%s[%sfoo%s]%s:0", space, space, space, space),
79 wantVal: V(Msg{{V("foo"), V(uint32(0))}}),
80 }, {
81 in: "[proto.package.name]:0",
82 wantVal: V(Msg{{V("proto.package.name"), V(uint32(0))}}),
83 wantOut: "[proto.package.name]:0",
84 wantOutIndent: "[proto.package.name]: 0\n",
85 }, {
86 in: S("%s[%sproto.package.name%s]%s:0", space, space, space, space),
87 wantVal: V(Msg{{V("proto.package.name"), V(uint32(0))}}),
88 }, {
89 in: "['sub.domain.com\x2fpath\x2fto\x2fproto.package.name']:0",
90 wantVal: V(Msg{{V("sub.domain.com/path/to/proto.package.name"), V(uint32(0))}}),
91 wantOut: "[sub.domain.com/path/to/proto.package.name]:0",
92 wantOutIndent: "[sub.domain.com/path/to/proto.package.name]: 0\n",
93 }, {
94 in: "[\"sub.domain.com\x2fpath\x2fto\x2fproto.package.name\"]:0",
95 wantVal: V(Msg{{V("sub.domain.com/path/to/proto.package.name"), V(uint32(0))}}),
96 }, {
97 in: S("%s[%s'sub.domain.com\x2fpath\x2fto\x2fproto.package.name'%s]%s:0", space, space, space, space),
98 wantVal: V(Msg{{V("sub.domain.com/path/to/proto.package.name"), V(uint32(0))}}),
99 }, {
100 in: S("%s[%s\"sub.domain.com\x2fpath\x2fto\x2fproto.package.name\"%s]%s:0", space, space, space, space),
101 wantVal: V(Msg{{V("sub.domain.com/path/to/proto.package.name"), V(uint32(0))}}),
102 }, {
103 in: `['http://example.com/path/to/proto.package.name']:0`,
104 wantVal: V(Msg{{V("http://example.com/path/to/proto.package.name"), V(uint32(0))}}),
105 wantOut: `["http://example.com/path/to/proto.package.name"]:0`,
106 wantOutIndent: `["http://example.com/path/to/proto.package.name"]: 0` + "\n",
107 }, {
108 in: "[proto.package.name:0",
109 wantErr: `invalid character ':', expected ']' at end of extension name`,
110 }, {
111 in: "[proto.package name]:0",
112 wantErr: `invalid character 'n', expected ']' at end of extension name`,
113 }, {
114 in: `["proto.package" "name"]:0`,
115 wantErr: `invalid character '"', expected ']' at end of extension name`,
116 }, {
117 in: `["\z"]`,
118 wantErr: `invalid escape code "\\z" in string`,
119 }, {
120 in: "[$]",
121 wantErr: `invalid "$" as identifier`,
122 }, {
123 // This parses fine, but should result in a error later since no
124 // type name in proto will ever be just a number.
125 in: "[20]:0",
126 wantVal: V(Msg{{V("20"), V(uint32(0))}}),
127 wantOut: "[20]:0",
128 }, {
129 in: "20:0",
130 wantVal: V(Msg{{V(uint32(20)), V(uint32(0))}}),
131 wantOut: "20:0",
132 }, {
133 in: "0x20:0",
134 wantVal: V(Msg{{V(uint32(0x20)), V(uint32(0))}}),
135 wantOut: "32:0",
136 }, {
137 in: "020:0",
138 wantVal: V(Msg{{V(uint32(020)), V(uint32(0))}}),
139 wantOut: "16:0",
140 }, {
141 in: "-20:0",
142 wantErr: `invalid "-20" as identifier`,
143 }, {
144 in: `foo:true bar:"s" baz:{} qux:[] wib:id`,
145 wantVal: V(Msg{
146 {ID("foo"), V(true)},
147 {ID("bar"), V("s")},
148 {ID("baz"), V(Msg{})},
149 {ID("qux"), V(Lst{})},
150 {ID("wib"), ID("id")},
151 }),
152 wantOut: `foo:true bar:"s" baz:{} qux:[] wib:id`,
153 wantOutIndent: "foo: true\nbar: \"s\"\nbaz: {}\nqux: []\nwib: id\n",
154 }, {
155 in: S(`%sfoo%s:%strue%s %sbar%s:%s"s"%s %sbaz%s:%s<>%s %squx%s:%s[]%s %swib%s:%sid%s`,
156 space, space, space, space, space, space, space, space, space, space, space, space, space, space, space, space, space, space, space, space),
157 wantVal: V(Msg{
158 {ID("foo"), V(true)},
159 {ID("bar"), V("s")},
160 {ID("baz"), V(Msg{})},
161 {ID("qux"), V(Lst{})},
162 {ID("wib"), ID("id")},
163 }),
164 }, {
165 in: `foo:true;`,
166 wantVal: V(Msg{{ID("foo"), V(true)}}),
167 wantOut: "foo:true",
168 wantOutIndent: "foo: true\n",
169 }, {
170 in: `foo:true,`,
171 wantVal: V(Msg{{ID("foo"), V(true)}}),
172 }, {
173 in: `foo:bar;,`,
174 wantErr: `invalid "," as identifier`,
175 }, {
176 in: `foo:bar,;`,
177 wantErr: `invalid ";" as identifier`,
178 }, {
179 in: `footrue`,
180 wantErr: `unexpected EOF`,
181 }, {
182 in: `foo true`,
183 wantErr: `expected ':' after message key`,
184 }, {
185 in: `foo"s"`,
186 wantErr: `expected ':' after message key`,
187 }, {
188 in: `foo "s"`,
189 wantErr: `expected ':' after message key`,
190 }, {
191 in: `foo{}`,
192 wantVal: V(Msg{{ID("foo"), V(Msg{})}}),
193 wantOut: "foo:{}",
194 wantOutBracket: "foo:<>",
195 wantOutIndent: "foo: {}\n",
196 }, {
197 in: `foo {}`,
198 wantVal: V(Msg{{ID("foo"), V(Msg{})}}),
199 }, {
200 in: `foo<>`,
201 wantVal: V(Msg{{ID("foo"), V(Msg{})}}),
202 }, {
203 in: `foo <>`,
204 wantVal: V(Msg{{ID("foo"), V(Msg{})}}),
205 }, {
206 in: `foo[]`,
207 wantErr: `expected ':' after message key`,
208 }, {
209 in: `foo []`,
210 wantErr: `expected ':' after message key`,
211 }, {
212 in: `foo:truebar:true`,
213 wantErr: `invalid ":" as identifier`,
214 }, {
215 in: `foo:"s"bar:true`,
216 wantVal: V(Msg{{ID("foo"), V("s")}, {ID("bar"), V(true)}}),
217 wantOut: `foo:"s" bar:true`,
218 wantOutIndent: "foo: \"s\"\nbar: true\n",
219 }, {
220 in: `foo:0bar:true`,
221 wantErr: `invalid "0bar" as number or bool`,
222 }, {
223 in: `foo:{}bar:true`,
224 wantVal: V(Msg{{ID("foo"), V(Msg{})}, {ID("bar"), V(true)}}),
225 wantOut: "foo:{} bar:true",
226 wantOutBracket: "foo:<> bar:true",
227 wantOutIndent: "foo: {}\nbar: true\n",
228 }, {
229 in: `foo:[]bar:true`,
230 wantVal: V(Msg{{ID("foo"), V(Lst{})}, {ID("bar"), V(true)}}),
231 }, {
232 in: `foo{bar:true}`,
233 wantVal: V(Msg{{ID("foo"), V(Msg{{ID("bar"), V(true)}})}}),
234 wantOut: "foo:{bar:true}",
235 wantOutBracket: "foo:<bar:true>",
236 wantOutIndent: "foo: {\n\tbar: true\n}\n",
237 }, {
238 in: `foo<bar:true>`,
239 wantVal: V(Msg{{ID("foo"), V(Msg{{ID("bar"), V(true)}})}}),
240 }, {
241 in: `foo{bar:true,}`,
242 wantVal: V(Msg{{ID("foo"), V(Msg{{ID("bar"), V(true)}})}}),
243 }, {
244 in: `foo{bar:true;}`,
245 wantVal: V(Msg{{ID("foo"), V(Msg{{ID("bar"), V(true)}})}}),
246 }, {
247 in: `foo{`,
248 wantErr: `unexpected EOF`,
249 }, {
250 in: `foo{ `,
251 wantErr: `unexpected EOF`,
252 }, {
253 in: `foo{[`,
254 wantErr: `unexpected EOF`,
255 }, {
256 in: `foo{[ `,
257 wantErr: `unexpected EOF`,
258 }, {
259 in: `foo{bar:true,;}`,
260 wantErr: `invalid ";" as identifier`,
261 }, {
262 in: `foo{bar:true;,}`,
263 wantErr: `invalid "," as identifier`,
264 }, {
265 in: `foo<bar:{}>`,
266 wantVal: V(Msg{{ID("foo"), V(Msg{{ID("bar"), V(Msg{})}})}}),
267 wantOut: "foo:{bar:{}}",
268 wantOutBracket: "foo:<bar:<>>",
269 wantOutIndent: "foo: {\n\tbar: {}\n}\n",
270 }, {
271 in: `foo<bar:{>`,
272 wantErr: `invalid character '>', expected '}' at end of message`,
273 }, {
274 in: `foo<bar:{}`,
275 wantErr: `unexpected EOF`,
276 }, {
277 in: `arr:[]`,
278 wantVal: V(Msg{{ID("arr"), V(Lst{})}}),
279 wantOut: "arr:[]",
280 wantOutBracket: "arr:[]",
281 wantOutIndent: "arr: []\n",
282 }, {
283 in: `arr:[,]`,
284 wantErr: `invalid "," as number or bool`,
285 }, {
286 in: `arr:[0 0]`,
287 wantErr: `invalid character '0', expected ']' at end of list`,
288 }, {
289 in: `arr:["foo" "bar"]`,
290 wantVal: V(Msg{{ID("arr"), V(Lst{V("foobar")})}}),
291 wantOut: `arr:["foobar"]`,
292 wantOutBracket: `arr:["foobar"]`,
293 wantOutIndent: "arr: [\n\t\"foobar\"\n]\n",
294 }, {
295 in: `arr:[0,]`,
296 wantErr: `invalid "]" as number or bool`,
297 }, {
298 in: `arr:[true,0,"",id,[],{}]`,
299 wantVal: V(Msg{{ID("arr"), V(Lst{
300 V(true), V(uint32(0)), V(""), ID("id"), V(Lst{}), V(Msg{}),
301 })}}),
302 wantOut: `arr:[true,0,"",id,[],{}]`,
303 wantOutBracket: `arr:[true,0,"",id,[],<>]`,
304 wantOutIndent: "arr: [\n\ttrue,\n\t0,\n\t\"\",\n\tid,\n\t[],\n\t{}\n]\n",
305 }, {
306 in: S(`arr:[%strue%s,%s0%s,%s""%s,%sid%s,%s[]%s,%s{}%s]`,
307 space, space, space, space, space, space, space, space, space, space, space, space),
308 wantVal: V(Msg{{ID("arr"), V(Lst{
309 V(true), V(uint32(0)), V(""), ID("id"), V(Lst{}), V(Msg{}),
310 })}}),
311 }, {
312 in: `arr:[`,
313 wantErr: `unexpected EOF`,
314 }, {
315 in: `{`,
316 wantErr: `invalid "{" as identifier`,
317 }, {
318 in: `<`,
319 wantErr: `invalid "<" as identifier`,
320 }, {
321 in: `[`,
322 wantErr: "unexpected EOF",
323 }, {
324 in: `}`,
325 wantErr: "1 bytes of unconsumed input",
326 }, {
327 in: `>`,
328 wantErr: "1 bytes of unconsumed input",
329 }, {
330 in: `]`,
331 wantErr: `invalid "]" as identifier`,
332 }, {
333 in: `str: "'"`,
334 wantVal: V(Msg{{ID("str"), V(`'`)}}),
335 wantOut: `str:"'"`,
336 }, {
337 in: `str: '"'`,
338 wantVal: V(Msg{{ID("str"), V(`"`)}}),
339 wantOut: `str:"\""`,
340 }, {
341 // String that has as few escaped characters as possible.
342 in: `str: ` + func() string {
343 var b []byte
344 for i := 0; i < utf8.RuneSelf; i++ {
345 switch i {
346 case 0, '\\', '\n', '\'': // these must be escaped, so ignore them
347 default:
348 b = append(b, byte(i))
349 }
350 }
351 return "'" + string(b) + "'"
352 }(),
353 wantVal: V(Msg{{ID("str"), V("\x01\x02\x03\x04\x05\x06\a\b\t\v\f\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~\u007f")}}),
354 wantOut: `str:"\x01\x02\x03\x04\x05\x06\x07\x08\t\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_` + "`abcdefghijklmnopqrstuvwxyz{|}~\x7f\"",
355 wantOutASCII: `str:"\x01\x02\x03\x04\x05\x06\x07\x08\t\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_` + "`abcdefghijklmnopqrstuvwxyz{|}~\x7f\"",
356 }, {
Damien Neil8c86fc52019-06-19 09:28:29 -0700357 in: "str: '\xde\xad\xbe\xef'",
358 wantErr: "invalid UTF-8 detected",
Joe Tsai27c2a762018-08-01 16:48:18 -0700359 }, {
360 // Valid UTF-8 wire encoding, but sub-optimal encoding.
Damien Neil8c86fc52019-06-19 09:28:29 -0700361 in: "str: '\xc0\x80'",
362 wantErr: "invalid UTF-8 detected",
Joe Tsai27c2a762018-08-01 16:48:18 -0700363 }, {
364 // Valid UTF-8 wire encoding, but invalid rune (surrogate pair).
Damien Neil8c86fc52019-06-19 09:28:29 -0700365 in: "str: '\xed\xa0\x80'",
366 wantErr: "invalid UTF-8 detected",
Joe Tsai27c2a762018-08-01 16:48:18 -0700367 }, {
368 // Valid UTF-8 wire encoding, but invalid rune (above max rune).
Damien Neil8c86fc52019-06-19 09:28:29 -0700369 in: "str: '\xf7\xbf\xbf\xbf'",
370 wantErr: "invalid UTF-8 detected",
Joe Tsai27c2a762018-08-01 16:48:18 -0700371 }, {
372 // Valid UTF-8 wire encoding of the RuneError rune.
373 in: "str: '\xef\xbf\xbd'",
374 wantVal: V(Msg{{ID("str"), V(string(utf8.RuneError))}}),
375 wantOut: `str:"` + string(utf8.RuneError) + `"`,
376 wantOutASCII: `str:"\ufffd"`,
377 }, {
378 in: "str: 'hello\u1234world'",
379 wantVal: V(Msg{{ID("str"), V("hello\u1234world")}}),
380 wantOut: "str:\"hello\u1234world\"",
381 wantOutASCII: `str:"hello\u1234world"`,
382 }, {
383 in: `str: '\"\'\\\?\a\b\n\r\t\v\f\1\12\123\xA\xaB\x12\uAb8f\U0010FFFF'`,
384 wantVal: V(Msg{{ID("str"), V("\"'\\?\a\b\n\r\t\v\f\x01\nS\n\xab\x12\uab8f\U0010ffff")}}),
385 wantOut: `str:"\"'\\?\x07\x08\n\r\t\x0b\x0c\x01\nS\n\xab\x12` + "\uab8f\U0010ffff" + `"`,
386 wantOutASCII: `str:"\"'\\?\x07\x08\n\r\t\x0b\x0c\x01\nS\n\xab\x12\uab8f\U0010ffff"`,
387 }, {
388 in: `str: '`,
389 wantErr: `unexpected EOF`,
390 }, {
391 in: `str: '\`,
392 wantErr: `unexpected EOF`,
393 }, {
394 in: `str: '\'`,
395 wantErr: `unexpected EOF`,
396 }, {
397 in: `str: '\8'`,
398 wantErr: `invalid escape code "\\8" in string`,
399 }, {
400 in: `str: '\1x'`,
401 wantVal: V(Msg{{ID("str"), V("\001x")}}),
402 wantOut: `str:"\x01x"`,
403 wantOutASCII: `str:"\x01x"`,
404 }, {
405 in: `str: '\12x'`,
406 wantVal: V(Msg{{ID("str"), V("\012x")}}),
407 wantOut: `str:"\nx"`,
408 wantOutASCII: `str:"\nx"`,
409 }, {
410 in: `str: '\123x'`,
411 wantVal: V(Msg{{ID("str"), V("\123x")}}),
412 wantOut: `str:"Sx"`,
413 wantOutASCII: `str:"Sx"`,
414 }, {
415 in: `str: '\1234x'`,
416 wantVal: V(Msg{{ID("str"), V("\1234x")}}),
417 wantOut: `str:"S4x"`,
418 wantOutASCII: `str:"S4x"`,
419 }, {
420 in: `str: '\1'`,
421 wantVal: V(Msg{{ID("str"), V("\001")}}),
422 wantOut: `str:"\x01"`,
423 wantOutASCII: `str:"\x01"`,
424 }, {
425 in: `str: '\12'`,
426 wantVal: V(Msg{{ID("str"), V("\012")}}),
427 wantOut: `str:"\n"`,
428 wantOutASCII: `str:"\n"`,
429 }, {
430 in: `str: '\123'`,
431 wantVal: V(Msg{{ID("str"), V("\123")}}),
432 wantOut: `str:"S"`,
433 wantOutASCII: `str:"S"`,
434 }, {
435 in: `str: '\1234'`,
436 wantVal: V(Msg{{ID("str"), V("\1234")}}),
437 wantOut: `str:"S4"`,
438 wantOutASCII: `str:"S4"`,
439 }, {
440 in: `str: '\377'`,
441 wantVal: V(Msg{{ID("str"), V("\377")}}),
442 wantOut: `str:"\xff"`,
443 wantOutASCII: `str:"\xff"`,
444 }, {
445 // Overflow octal escape.
446 in: `str: '\400'`,
447 wantErr: `invalid octal escape code "\\400" in string`,
448 }, {
449 in: `str: '\xfx'`,
450 wantVal: V(Msg{{ID("str"), V("\x0fx")}}),
451 wantOut: `str:"\x0fx"`,
452 wantOutASCII: `str:"\x0fx"`,
453 }, {
454 in: `str: '\xffx'`,
455 wantVal: V(Msg{{ID("str"), V("\xffx")}}),
456 wantOut: `str:"\xffx"`,
457 wantOutASCII: `str:"\xffx"`,
458 }, {
459 in: `str: '\xfffx'`,
460 wantVal: V(Msg{{ID("str"), V("\xfffx")}}),
461 wantOut: `str:"\xfffx"`,
462 wantOutASCII: `str:"\xfffx"`,
463 }, {
464 in: `str: '\xf'`,
465 wantVal: V(Msg{{ID("str"), V("\x0f")}}),
466 wantOut: `str:"\x0f"`,
467 wantOutASCII: `str:"\x0f"`,
468 }, {
469 in: `str: '\xff'`,
470 wantVal: V(Msg{{ID("str"), V("\xff")}}),
471 wantOut: `str:"\xff"`,
472 wantOutASCII: `str:"\xff"`,
473 }, {
474 in: `str: '\xfff'`,
475 wantVal: V(Msg{{ID("str"), V("\xfff")}}),
476 wantOut: `str:"\xfff"`,
477 wantOutASCII: `str:"\xfff"`,
478 }, {
479 in: `str: '\xz'`,
480 wantErr: `invalid hex escape code "\\x" in string`,
481 }, {
482 in: `str: '\uPo'`,
483 wantErr: `unexpected EOF`,
484 }, {
485 in: `str: '\uPoo'`,
486 wantErr: `invalid Unicode escape code "\\uPoo'" in string`,
487 }, {
488 in: `str: '\uPoop'`,
489 wantErr: `invalid Unicode escape code "\\uPoop" in string`,
490 }, {
491 // Unmatched surrogate pair.
492 in: `str: '\uDEAD'`,
493 wantErr: `unexpected EOF`, // trying to reader other half
494 }, {
495 // Surrogate pair with invalid other half.
496 in: `str: '\uDEAD\u0000'`,
497 wantErr: `invalid Unicode escape code "\\u0000" in string`,
498 }, {
499 // Properly matched surrogate pair.
500 in: `str: '\uD800\uDEAD'`,
501 wantVal: V(Msg{{ID("str"), V("𐊭")}}),
502 wantOut: `str:"𐊭"`,
503 wantOutASCII: `str:"\U000102ad"`,
504 }, {
505 // Overflow on Unicode rune.
506 in: `str: '\U00110000'`,
507 wantErr: `invalid Unicode escape code "\\U00110000" in string`,
508 }, {
509 in: `str: '\z'`,
510 wantErr: `invalid escape code "\\z" in string`,
511 }, {
512 // Strings cannot have NUL literal since C-style strings forbid them.
513 in: "str: '\x00'",
514 wantErr: `invalid character '\x00' in string`,
515 }, {
516 // Strings cannot have newline literal. The C++ permits them if an
517 // option is specified to allow them. In Go, we always forbid them.
518 in: "str: '\n'",
519 wantErr: `invalid character '\n' in string`,
520 }, {
521 in: "name: \"My name is \"\n\"elsewhere\"",
522 wantVal: V(Msg{{ID("name"), V("My name is elsewhere")}}),
523 wantOut: `name:"My name is elsewhere"`,
524 wantOutASCII: `name:"My name is elsewhere"`,
525 }, {
526 in: "name: 'My name is '\n'elsewhere'",
527 wantVal: V(Msg{{ID("name"), V("My name is elsewhere")}}),
528 }, {
529 in: "name: 'My name is '\n\"elsewhere\"",
530 wantVal: V(Msg{{ID("name"), V("My name is elsewhere")}}),
531 }, {
532 in: "name: \"My name is \"\n'elsewhere'",
533 wantVal: V(Msg{{ID("name"), V("My name is elsewhere")}}),
534 }, {
535 in: "name: \"My \"'name '\"is \"\n'elsewhere'",
536 wantVal: V(Msg{{ID("name"), V("My name is elsewhere")}}),
537 }, {
538 in: `crazy:"x'"'\""\''"'z"`,
539 wantVal: V(Msg{{ID("crazy"), V(`x'""''z`)}}),
540 }, {
541 in: `nums: [t,T,true,True,TRUE,f,F,false,False,FALSE]`,
542 wantVal: V(Msg{{ID("nums"), V(Lst{
543 V(true),
544 ID("T"),
545 V(true),
546 V(true),
547 ID("TRUE"),
548 V(false),
549 ID("F"),
550 V(false),
551 V(false),
552 ID("FALSE"),
553 })}}),
554 wantOut: "nums:[true,T,true,true,TRUE,false,F,false,false,FALSE]",
555 wantOutIndent: "nums: [\n\ttrue,\n\tT,\n\ttrue,\n\ttrue,\n\tTRUE,\n\tfalse,\n\tF,\n\tfalse,\n\tfalse,\n\tFALSE\n]\n",
556 }, {
557 in: `nums: [nan,inf,-inf,NaN,NAN,Inf,INF]`,
558 wantVal: V(Msg{{ID("nums"), V(Lst{
559 V(math.NaN()),
560 V(math.Inf(+1)),
561 V(math.Inf(-1)),
562 ID("NaN"),
563 ID("NAN"),
564 ID("Inf"),
565 ID("INF"),
566 })}}),
567 wantOut: "nums:[nan,inf,-inf,NaN,NAN,Inf,INF]",
568 wantOutIndent: "nums: [\n\tnan,\n\tinf,\n\t-inf,\n\tNaN,\n\tNAN,\n\tInf,\n\tINF\n]\n",
569 }, {
570 // C++ permits this, but we currently reject this.
571 in: `num: -nan`,
572 wantErr: `invalid "-nan" as number or bool`,
573 }, {
574 in: `nums: [0,-0,-9876543210,9876543210,0x0,0x0123456789abcdef,-0x0123456789abcdef,01234567,-01234567]`,
575 wantVal: V(Msg{{ID("nums"), V(Lst{
576 V(uint32(0)),
577 V(int32(-0)),
578 V(int64(-9876543210)),
579 V(uint64(9876543210)),
580 V(uint32(0x0)),
581 V(uint64(0x0123456789abcdef)),
582 V(int64(-0x0123456789abcdef)),
583 V(uint64(01234567)),
584 V(int64(-01234567)),
585 })}}),
586 wantOut: "nums:[0,0,-9876543210,9876543210,0,81985529216486895,-81985529216486895,342391,-342391]",
587 wantOutIndent: "nums: [\n\t0,\n\t0,\n\t-9876543210,\n\t9876543210,\n\t0,\n\t81985529216486895,\n\t-81985529216486895,\n\t342391,\n\t-342391\n]\n",
588 }, {
589 in: `nums: [0.,0f,1f,10f,-0f,-1f,-10f,1.0,0.1e-3,1.5e+5,1e10,.0]`,
590 wantVal: V(Msg{{ID("nums"), V(Lst{
591 V(0.0),
592 V(0.0),
593 V(1.0),
594 V(10.0),
595 V(-0.0),
596 V(-1.0),
597 V(-10.0),
598 V(1.0),
599 V(0.1e-3),
600 V(1.5e+5),
601 V(1.0e+10),
602 V(0.0),
603 })}}),
604 wantOut: "nums:[0,0,1,10,0,-1,-10,1,0.0001,150000,1e+10,0]",
605 wantOutIndent: "nums: [\n\t0,\n\t0,\n\t1,\n\t10,\n\t0,\n\t-1,\n\t-10,\n\t1,\n\t0.0001,\n\t150000,\n\t1e+10,\n\t0\n]\n",
606 }, {
607 in: `nums: [0xbeefbeef,0xbeefbeefbeefbeef]`,
608 wantVal: V(Msg{{ID("nums"), func() Value {
609 if flags.Proto1Legacy {
610 return V(Lst{V(int32(-1091584273)), V(int64(-4688318750159552785))})
611 } else {
612 return V(Lst{V(uint32(0xbeefbeef)), V(uint64(0xbeefbeefbeefbeef))})
613 }
614 }()}}),
615 }, {
616 in: `num: +0`,
617 wantErr: `invalid "+0" as number or bool`,
618 }, {
619 in: `num: 01.1234`,
620 wantErr: `invalid "01.1234" as number or bool`,
621 }, {
622 in: `num: 0x`,
623 wantErr: `invalid "0x" as number or bool`,
624 }, {
625 in: `num: 0xX`,
626 wantErr: `invalid "0xX" as number or bool`,
627 }, {
628 in: `num: 0800`,
629 wantErr: `invalid "0800" as number or bool`,
630 }, {
631 in: `num: true.`,
632 wantErr: `invalid "true." as number or bool`,
633 }, {
634 in: `num: .`,
635 wantErr: `parsing ".": invalid syntax`,
636 }, {
637 in: `num: -.`,
638 wantErr: `parsing "-.": invalid syntax`,
639 }, {
640 in: `num: 1e10000`,
641 wantErr: `parsing "1e10000": value out of range`,
642 }, {
643 in: `num: 99999999999999999999`,
644 wantErr: `parsing "99999999999999999999": value out of range`,
645 }, {
646 in: `num: -99999999999999999999`,
647 wantErr: `parsing "-99999999999999999999": value out of range`,
648 }, {
649 in: "x: -",
650 wantErr: `syntax error (line 1:5)`,
651 }, {
652 in: "x:[\"💩\"x",
653 wantErr: `syntax error (line 1:7)`,
654 }, {
655 in: "x:\n\n[\"🔥🔥🔥\"x",
656 wantErr: `syntax error (line 3:7)`,
657 }, {
658 in: "x:[\"👍🏻👍🏿\"x",
659 wantErr: `syntax error (line 1:10)`, // multi-rune emojis; could be column:8
660 }, {
661 in: `
662 firstName : "John",
663 lastName : "Smith" ,
664 isAlive : true,
665 age : 27,
666 address { # missing colon is okay for messages
667 streetAddress : "21 2nd Street" ,
668 city : "New York" ,
669 state : "NY" ,
670 postalCode : "10021-3100" ; # trailing semicolon is okay
671 },
672 phoneNumbers : [ {
673 type : "home" ,
674 number : "212 555-1234"
675 } , {
676 type : "office" ,
677 number : "646 555-4567"
678 } , {
679 type : "mobile" ,
680 number : "123 456-7890" , # trailing comma is okay
681 } ],
682 children : [] ,
683 spouse : null`,
684 wantVal: V(Msg{
685 {ID("firstName"), V("John")},
686 {ID("lastName"), V("Smith")},
687 {ID("isAlive"), V(true)},
688 {ID("age"), V(27.0)},
689 {ID("address"), V(Msg{
690 {ID("streetAddress"), V("21 2nd Street")},
691 {ID("city"), V("New York")},
692 {ID("state"), V("NY")},
693 {ID("postalCode"), V("10021-3100")},
694 })},
695 {ID("phoneNumbers"), V([]Value{
696 V(Msg{
697 {ID("type"), V("home")},
698 {ID("number"), V("212 555-1234")},
699 }),
700 V(Msg{
701 {ID("type"), V("office")},
702 {ID("number"), V("646 555-4567")},
703 }),
704 V(Msg{
705 {ID("type"), V("mobile")},
706 {ID("number"), V("123 456-7890")},
707 }),
708 })},
709 {ID("children"), V([]Value{})},
710 {ID("spouse"), V(protoreflect.Name("null"))},
711 }),
712 wantOut: `firstName:"John" lastName:"Smith" isAlive:true age:27 address:{streetAddress:"21 2nd Street" city:"New York" state:"NY" postalCode:"10021-3100"} phoneNumbers:[{type:"home" number:"212 555-1234"},{type:"office" number:"646 555-4567"},{type:"mobile" number:"123 456-7890"}] children:[] spouse:null`,
713 wantOutBracket: `firstName:"John" lastName:"Smith" isAlive:true age:27 address:<streetAddress:"21 2nd Street" city:"New York" state:"NY" postalCode:"10021-3100"> phoneNumbers:[<type:"home" number:"212 555-1234">,<type:"office" number:"646 555-4567">,<type:"mobile" number:"123 456-7890">] children:[] spouse:null`,
714 wantOutIndent: `firstName: "John"
715lastName: "Smith"
716isAlive: true
717age: 27
718address: {
719 streetAddress: "21 2nd Street"
720 city: "New York"
721 state: "NY"
722 postalCode: "10021-3100"
723}
724phoneNumbers: [
725 {
726 type: "home"
727 number: "212 555-1234"
728 },
729 {
730 type: "office"
731 number: "646 555-4567"
732 },
733 {
734 type: "mobile"
735 number: "123 456-7890"
736 }
737]
738children: []
739spouse: null
740`,
741 }}
742
743 opts := cmp.Options{
744 cmpopts.EquateEmpty(),
745
746 // Transform composites (List and Message).
747 cmp.FilterValues(func(x, y Value) bool {
748 return (x.Type() == List && y.Type() == List) || (x.Type() == Message && y.Type() == Message)
749 }, cmp.Transformer("", func(v Value) interface{} {
750 if v.Type() == List {
751 return v.List()
752 } else {
753 return v.Message()
754 }
755 })),
756
757 // Compare scalars (Bool, Int, Uint, Float, String, Name).
758 cmp.FilterValues(func(x, y Value) bool {
759 return !(x.Type() == List && y.Type() == List) && !(x.Type() == Message && y.Type() == Message)
760 }, cmp.Comparer(func(x, y Value) bool {
761 if x.Type() == List || x.Type() == Message || y.Type() == List || y.Type() == Message {
762 return false
763 }
764 // Ensure golden value is always in x variable.
765 if len(x.raw) > 0 {
766 x, y = y, x
767 }
768 switch x.Type() {
769 case Bool:
770 want, _ := x.Bool()
771 got, ok := y.Bool()
772 return got == want && ok
773 case Int:
774 want, _ := x.Int(true)
775 got, ok := y.Int(want < math.MinInt32 || math.MaxInt32 < want)
776 return got == want && ok
777 case Uint:
778 want, _ := x.Uint(true)
779 got, ok := y.Uint(math.MaxUint32 < want)
780 return got == want && ok
Herbie Ong250c6ea2019-03-12 20:55:10 -0700781 case Float32, Float64:
782 want, _ := x.Float(true)
783 got, ok := y.Float(math.MaxFloat32 < math.Abs(want))
Joe Tsai27c2a762018-08-01 16:48:18 -0700784 if math.IsNaN(got) || math.IsNaN(want) {
785 return math.IsNaN(got) == math.IsNaN(want)
786 }
787 return got == want && ok
788 case Name:
789 want, _ := x.Name()
790 got, ok := y.Name()
791 return got == want && ok
792 default:
793 return x.String() == y.String()
794 }
795 })),
796 }
797 for _, tt := range tests {
798 t.Run("", func(t *testing.T) {
799 if tt.in != "" || tt.wantVal.Type() != 0 || tt.wantErr != "" {
800 gotVal, err := Unmarshal([]byte(tt.in))
801 if err == nil {
802 if tt.wantErr != "" {
803 t.Errorf("Unmarshal(): got nil error, want %v", tt.wantErr)
804 }
805 } else {
806 if tt.wantErr == "" {
807 t.Errorf("Unmarshal(): got %v, want nil error", err)
808 } else if !strings.Contains(err.Error(), tt.wantErr) {
809 t.Errorf("Unmarshal(): got %v, want %v", err, tt.wantErr)
810 }
811 }
812 if diff := cmp.Diff(gotVal, tt.wantVal, opts); diff != "" {
813 t.Errorf("Unmarshal(): output mismatch (-got +want):\n%s", diff)
814 }
815 }
816 if tt.wantOut != "" {
817 gotOut, err := Marshal(tt.wantVal, "", [2]byte{0, 0}, false)
818 if err != nil {
819 t.Errorf("Marshal(): got %v, want nil error", err)
820 }
Joe Tsai71acbc72018-11-28 19:27:29 -0800821 if string(gotOut) != tt.wantOut {
Joe Tsai27c2a762018-08-01 16:48:18 -0700822 t.Errorf("Marshal():\ngot: %s\nwant: %s", gotOut, tt.wantOut)
823 }
824 }
825 if tt.wantOutBracket != "" {
826 gotOut, err := Marshal(tt.wantVal, "", [2]byte{'<', '>'}, false)
827 if err != nil {
828 t.Errorf("Marshal(Bracket): got %v, want nil error", err)
829 }
Joe Tsai71acbc72018-11-28 19:27:29 -0800830 if string(gotOut) != tt.wantOutBracket {
Joe Tsai27c2a762018-08-01 16:48:18 -0700831 t.Errorf("Marshal(Bracket):\ngot: %s\nwant: %s", gotOut, tt.wantOutBracket)
832 }
833 }
834 if tt.wantOutASCII != "" {
835 gotOut, err := Marshal(tt.wantVal, "", [2]byte{0, 0}, true)
836 if err != nil {
837 t.Errorf("Marshal(ASCII): got %v, want nil error", err)
838 }
Joe Tsai71acbc72018-11-28 19:27:29 -0800839 if string(gotOut) != tt.wantOutASCII {
Joe Tsai27c2a762018-08-01 16:48:18 -0700840 t.Errorf("Marshal(ASCII):\ngot: %s\nwant: %s", gotOut, tt.wantOutASCII)
841 }
842 }
843 if tt.wantOutIndent != "" {
844 gotOut, err := Marshal(tt.wantVal, "\t", [2]byte{0, 0}, false)
845 if err != nil {
846 t.Errorf("Marshal(Indent): got %v, want nil error", err)
847 }
Joe Tsai71acbc72018-11-28 19:27:29 -0800848 if string(gotOut) != tt.wantOutIndent {
Joe Tsai27c2a762018-08-01 16:48:18 -0700849 t.Errorf("Marshal(Indent):\ngot: %s\nwant: %s", gotOut, tt.wantOutIndent)
850 }
851 }
852 })
853 }
854}