Debian Codegraph @

node/@bufbuild/protobuf/dist/commonjs/txtpb/from-text.js

raw
1 "use strict";
2 // Copyright 2021-2026 Buf Technologies, Inc.
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 Object.defineProperty(exports, "__esModule", { value: true });
16 exports.fromText = fromText;
17 exports.mergeFromText = mergeFromText;
18 const descriptors_js_1 = require("../descriptors.js");
19 const proto_int64_js_1 = require("../proto-int64.js");
20 const reflect_js_1 = require("../reflect/reflect.js");
21 const error_js_1 = require("../reflect/error.js");
22 const scalar_js_1 = require("../reflect/scalar.js");
23 const to_binary_js_1 = require("../to-binary.js");
24 const extensions_js_1 = require("../extensions.js");
25 const text_encoding_js_1 = require("../wire/text-encoding.js");
26 const reader_js_1 = require("./reader.js");
27 const is_group_like_js_1 = require("./is-group-like.js");
28 function makeReadContext(reader, options) {
29 return Object.assign(Object.assign({ recursionLimit: 100 }, options), { reader, depth: 0 });
30 }
31 /**
32 * Parse a message from the protobuf text format.
33 *
34 * Requires BigInt: throws immediately if the environment does not support it.
35 */
36 function fromText(schema, text, options) {
37 const msg = (0, reflect_js_1.reflect)(schema);
38 parseText(msg, text, options);
39 return msg.message;
40 }
41 /**
42 * Parse a message from the protobuf text format, merging into the target.
43 *
44 * Repeated fields are appended, singular fields are overwritten (last wins),
45 * message fields are merged, and map entries are added (overwriting an existing
46 * key).
47 *
48 * Requires BigInt: throws immediately if the environment does not support it.
49 */
50 function mergeFromText(schema, target, text, options) {
51 parseText((0, reflect_js_1.reflect)(schema, target), text, options);
52 return target;
53 }
54 function parseText(msg, text, options) {
55 if (!proto_int64_js_1.protoInt64.supported) {
56 throw new Error("the protobuf text format requires BigInt, which is unavailable in this environment");
57 }
58 const ctx = makeReadContext(new reader_js_1.Reader(text), options);
59 try {
60 readMessageBody(msg, ctx, "eof");
61 }
62 catch (e) {
63 if ((0, error_js_1.isFieldError)(e)) {
64 throw new Error(`cannot decode ${e.field()} from text format: ${e.message}`,
65 // @ts-expect-error we use the ES2022 error CTOR option "cause" for better stack traces
66 { cause: e });
67 }
68 throw e;
69 }
70 }
71 /**
72 * Read a message body (its fields until `close`), guarding nesting depth. The
73 * top-level message and every nested "{...}"/"<...>" block go through here, so
74 * the recursion limit counts the root too, matching fromJson and fromBinary.
75 */
76 function readMessageBody(msg, ctx, close) {
77 if (++ctx.depth > ctx.recursionLimit) {
78 throw new Error(`recursion limit of ${ctx.recursionLimit} reached decoding ${msg.desc}`);
79 }
80 readFields(msg, ctx, close);
81 ctx.depth--;
82 }
83 /**
84 * Read the fields of a message until `close` (the matching close token, or
85 * "eof" for the top-level message).
86 */
87 function readFields(msg, ctx, close) {
88 const seen = { fields: new Set(), oneofs: new Set() };
89 for (;;) {
90 const tok = ctx.reader.peek();
91 if (tok.type === "eof") {
92 if (close !== "eof") {
93 throw new Error(`unexpected end of input, expected "${close}"`);
94 }
95 return;
96 }
97 if (close !== "eof" && tok.type === close) {
98 ctx.reader.next();
99 return;
100 }
101 readField(msg, ctx, seen);
102 // A single optional "," or ";" may follow a field. Because the next
103 // iteration treats a separator as a field name and rejects it, a doubled
104 // separator is an error, while a single trailing one is allowed.
105 consumeSeparator(ctx);
106 }
107 }
108 function readField(msg, ctx, seen) {
109 var _a;
110 const nameTok = ctx.reader.next();
111 if (nameTok.type === "identifier") {
112 const field = fieldByTextName(msg.desc, nameTok.value);
113 if (field !== undefined) {
114 checkSeen(field, seen);
115 readFieldValue(msg, field, ctx);
116 return;
117 }
118 // Reserved field names are silently skipped; any other unknown name is an
119 // error. This matches protobuf-go.
120 if (msg.desc.proto.reservedName.includes(nameTok.value)) {
121 skipFieldValue(ctx);
122 return;
123 }
124 throw new Error(`unknown field "${nameTok.value}" for ${msg.desc}`);
125 }
126 if (nameTok.type === "[") {
127 const name = ctx.reader.readTypeName();
128 // Inside google.protobuf.Any, a bracketed name is always a type URL; in any
129 // other message it is an extension name.
130 if (msg.desc.typeName === "google.protobuf.Any") {
131 readExpandedAny(msg, ctx, name, seen);
132 return;
133 }
134 const ext = (_a = ctx.registry) === null || _a === void 0 ? void 0 : _a.getExtension(name);
135 if (ext !== undefined && ext.extendee.typeName === msg.desc.typeName) {
136 checkSeen(ext, seen);
137 readExtensionField(msg, ext, ctx);
138 return;
139 }
140 throw new Error(`unknown extension "[${name}]" for ${msg.desc}`);
141 }
142 if (nameTok.type === "int") {
143 // Like protobuf-go, a field cannot be addressed by number, so the numbered
144 // output of printUnknownFields cannot be read back.
145 throw new Error(`cannot specify field by number: ${nameTok.text}`);
146 }
147 throw new Error(`expected a field name, got ${describe(nameTok)}`);
148 }
149 // Rejects a repeated occurrence of a singular field, or a second member of the
150 // same oneof. Repeated and map fields may appear any number of times.
151 function checkSeen(field, seen) {
152 if (field.fieldKind === "list" || field.fieldKind === "map") {
153 return;
154 }
155 if (field.oneof !== undefined) {
156 if (seen.oneofs.has(field.oneof)) {
157 throw new Error(`oneof "${field.oneof.name}" is already set`);
158 }
159 seen.oneofs.add(field.oneof);
160 }
161 if (seen.fields.has(field.number)) {
162 const what = field.kind === "extension"
163 ? `extension "[${field.typeName}]"`
164 : `field "${field.name}"`;
165 throw new Error(`non-repeated ${what} is repeated`);
166 }
167 seen.fields.add(field.number);
168 }
169 function readFieldValue(target, field, ctx) {
170 // The ":" separator is optional before a message, group, or map value, but
171 // required for scalars, enums, and lists of them.
172 const hasColon = consumeColon(ctx);
173 if (!colonOptional(field) && !hasColon) {
174 throw new Error(`expected ":" before value of field "${field.name}"`);
175 }
176 switch (field.fieldKind) {
177 case "scalar":
178 target.set(field, readScalarValue(field, field.scalar, ctx));
179 break;
180 case "enum":
181 target.set(field, readEnumValue(field.enum, ctx));
182 break;
183 case "message": {
184 const sub = target.isSet(field)
185 ? target.get(field)
186 : (0, reflect_js_1.reflect)(field.message);
187 readMessageValue(sub, ctx);
188 target.set(field, sub);
189 break;
190 }
191 case "list":
192 readListField(field, target.get(field), ctx);
193 break;
194 case "map":
195 readMapField(field, target.get(field), ctx);
196 break;
197 }
198 }
199 function readExtensionField(msg, ext, ctx) {
200 // Extensions live in the unknown-field set. We read the new value into a
201 // container seeded with any existing value, so a repeated extension appends.
202 const existing = (0, extensions_js_1.hasExtension)(msg.message, ext)
203 ? (0, extensions_js_1.getExtension)(msg.message, ext)
204 : undefined;
205 const [container, field, get] = (0, extensions_js_1.createExtensionContainer)(ext, existing);
206 readFieldValue(container, field, ctx);
207 (0, extensions_js_1.setExtension)(msg.message, ext, get());
208 }
209 function colonOptional(field) {
210 return (field.fieldKind === "message" ||
211 field.fieldKind === "map" ||
212 (field.fieldKind === "list" && field.listKind === "message"));
213 }
214 /**
215 * Read a "{ ... }" or "< ... >" block into the given message.
216 */
217 function readMessageValue(msg, ctx) {
218 readMessageBody(msg, ctx, readMessageOpen(ctx));
219 }
220 function readMessageOpen(ctx) {
221 const open = ctx.reader.next();
222 if (open.type === "{") {
223 return "}";
224 }
225 if (open.type === "<") {
226 return ">";
227 }
228 throw new Error(`expected "{" or "<", got ${describe(open)}`);
229 }
230 /**
231 * Read a repeated value: either a single element, or a bracketed list
232 * "[ e, e, ... ]". This is the one place the list grammar lives, so list
233 * fields, map fields, and the reserved-skip path cannot drift in how they
234 * accept (and reject) separators.
235 */
236 function readBracketedList(ctx, readElement) {
237 if (ctx.reader.peek().type !== "[") {
238 readElement();
239 return;
240 }
241 ctx.reader.next(); // "["
242 if (ctx.reader.peek().type === "]") {
243 ctx.reader.next();
244 return;
245 }
246 for (;;) {
247 readElement();
248 const sep = ctx.reader.next();
249 if (sep.type === "]") {
250 return;
251 }
252 if (sep.type !== ",") {
253 throw new Error(`expected "," or "]" in list, got ${describe(sep)}`);
254 }
255 }
256 }
257 function readListField(field, list, ctx) {
258 readBracketedList(ctx, () => list.add(readListItem(field, ctx)));
259 }
260 function readListItem(field, ctx) {
261 switch (field.listKind) {
262 case "scalar":
263 return readScalarValue(field, field.scalar, ctx);
264 case "enum":
265 return readEnumValue(field.enum, ctx);
266 case "message": {
267 const sub = (0, reflect_js_1.reflect)(field.message);
268 readMessageValue(sub, ctx);
269 return sub;
270 }
271 }
272 }
273 function readMapField(field, map, ctx) {
274 readBracketedList(ctx, () => readMapEntry(field, map, ctx));
275 }
276 /**
277 * Read a map entry: a "{ key: ... value: ... }" block. A missing key or value
278 * defaults to the zero value, like protobuf-go. A duplicate "key" or "value"
279 * within one entry is an error; duplicate keys across separate entries are
280 * legal, with the last entry winning (handled by the caller's map.set).
281 */
282 function readMapEntry(field, map, ctx) {
283 if (++ctx.depth > ctx.recursionLimit) {
284 throw new Error(`recursion limit of ${ctx.recursionLimit} reached decoding a map entry`);
285 }
286 const close = readMessageOpen(ctx);
287 let key = (0, scalar_js_1.scalarZeroValue)(field.mapKey, false);
288 let value = mapValueZero(field);
289 let keySeen = false;
290 let valueSeen = false;
291 for (;;) {
292 const tok = ctx.reader.peek();
293 if (tok.type === close) {
294 ctx.reader.next();
295 break;
296 }
297 if (tok.type === "eof") {
298 throw new Error(`unexpected end of input, expected "${close}"`);
299 }
300 const nameTok = ctx.reader.next();
301 if (nameTok.type !== "identifier") {
302 throw new Error(`expected "key" or "value", got ${describe(nameTok)}`);
303 }
304 if (nameTok.value === "key") {
305 if (keySeen) {
306 throw new Error('map entry "key" is already set');
307 }
308 keySeen = true;
309 requireColon(ctx);
310 key = readScalarValue(field, field.mapKey, ctx);
311 }
312 else if (nameTok.value === "value") {
313 if (valueSeen) {
314 throw new Error('map entry "value" is already set');
315 }
316 valueSeen = true;
317 value = readMapValue(field, ctx);
318 }
319 else {
320 throw new Error(`unknown field "${nameTok.value}" in map entry`);
321 }
322 consumeSeparator(ctx);
323 }
324 ctx.depth--;
325 map.set(key, value);
326 }
327 function readMapValue(field, ctx) {
328 switch (field.mapKind) {
329 case "scalar":
330 requireColon(ctx);
331 return readScalarValue(field, field.scalar, ctx);
332 case "enum":
333 requireColon(ctx);
334 return readEnumValue(field.enum, ctx);
335 case "message": {
336 consumeColon(ctx);
337 const sub = (0, reflect_js_1.reflect)(field.message);
338 readMessageValue(sub, ctx);
339 return sub;
340 }
341 }
342 }
343 function mapValueZero(field) {
344 switch (field.mapKind) {
345 case "scalar":
346 return (0, scalar_js_1.scalarZeroValue)(field.scalar, false);
347 case "enum":
348 return field.enum.values[0].number;
349 case "message":
350 return (0, reflect_js_1.reflect)(field.message);
351 }
352 }
353 /**
354 * Read `google.protobuf.Any` in its expanded form `[type.url]: { ... }`.
355 *
356 * The expanded form is mutually exclusive with the raw `type_url` (field 1) and
357 * `value` (field 2) fields, and may appear only once. We enforce that through
358 * the same seen-set the duplicate-field check uses: the expansion is rejected
359 * if either field is already set, and it marks both as set so a following
360 * `type_url` or `value` is rejected too.
361 */
362 function readExpandedAny(msg, ctx, typeUrl, seen) {
363 var _a;
364 if (seen.fields.has(1) || seen.fields.has(2)) {
365 throw new Error("google.protobuf.Any cannot mix the expanded form with type_url/value");
366 }
367 const slash = typeUrl.lastIndexOf("/");
368 const typeName = slash >= 0 ? typeUrl.substring(slash + 1) : typeUrl;
369 const desc = (_a = ctx.registry) === null || _a === void 0 ? void 0 : _a.getMessage(typeName);
370 if (desc === undefined) {
371 throw new Error(`unable to resolve "${typeUrl}" for google.protobuf.Any`);
372 }
373 consumeColon(ctx);
374 const unpacked = (0, reflect_js_1.reflect)(desc);
375 readMessageValue(unpacked, ctx);
376 const any = msg.message;
377 // Preserve the exact type URL, including any custom domain prefix.
378 any.typeUrl = typeUrl;
379 any.value = (0, to_binary_js_1.toBinary)(desc, unpacked.message);
380 seen.fields.add(1);
381 seen.fields.add(2);
382 }
383 // Consume an optional leading "-" sign and report whether one was present.
384 // This sees a sign token only before a number (the scanner glues a sign onto an
385 // identifier as in "-inf"), and whitespace and comments between the sign and the
386 // number are insignificant, so "- 42" means -42, matching protobuf-go.
387 function consumeSign(ctx) {
388 if (ctx.reader.peek().type === "-") {
389 ctx.reader.next();
390 return true;
391 }
392 return false;
393 }
394 function readScalarValue(field, type, ctx) {
395 const negative = consumeSign(ctx);
396 const tok = ctx.reader.next();
397 switch (type) {
398 case descriptors_js_1.ScalarType.STRING:
399 case descriptors_js_1.ScalarType.BYTES: {
400 if (negative) {
401 throw new Error("a string value cannot have a sign");
402 }
403 if (tok.type !== "string") {
404 throw new Error(`expected a string, got ${describe(tok)}`);
405 }
406 const bytes = concatStrings(tok, ctx);
407 if (type === descriptors_js_1.ScalarType.BYTES) {
408 return bytes;
409 }
410 try {
411 return (0, text_encoding_js_1.getTextEncoding)().decodeUtf8(bytes, field.utf8Validation);
412 }
413 catch (_a) {
414 throw new Error("invalid UTF-8 in string");
415 }
416 }
417 case descriptors_js_1.ScalarType.BOOL:
418 return readBoolValue(tok, negative);
419 case descriptors_js_1.ScalarType.FLOAT:
420 // Round to 32-bit precision: an out-of-range value becomes ±inf, which is
421 // what the text format requires for float overflow.
422 return Math.fround(readFloatValue(tok, negative));
423 case descriptors_js_1.ScalarType.DOUBLE:
424 return readFloatValue(tok, negative);
425 case descriptors_js_1.ScalarType.UINT32:
426 case descriptors_js_1.ScalarType.FIXED32:
427 return Number(readUnsignedInt(tok, negative));
428 case descriptors_js_1.ScalarType.UINT64:
429 case descriptors_js_1.ScalarType.FIXED64:
430 return readUnsignedInt(tok, negative);
431 case descriptors_js_1.ScalarType.INT64:
432 case descriptors_js_1.ScalarType.SINT64:
433 case descriptors_js_1.ScalarType.SFIXED64:
434 return readSignedInt(tok, negative);
435 default:
436 // INT32, SINT32, SFIXED32: the reflect layer range-checks the number.
437 return Number(readSignedInt(tok, negative));
438 }
439 }
440 function readEnumValue(descEnum, ctx) {
441 const negative = consumeSign(ctx);
442 const tok = ctx.reader.next();
443 if (tok.type === "identifier") {
444 if (negative) {
445 throw new Error(`invalid enum value "-${tok.value}" for ${descEnum}`);
446 }
447 const value = descEnum.values.find((v) => v.name === tok.value);
448 if (value === undefined) {
449 throw new Error(`unknown enum value "${tok.value}" for ${descEnum}`);
450 }
451 return value.number;
452 }
453 if (tok.type === "int") {
454 // The reflect layer validates the number: any int32 for open enums, a known
455 // value for closed (proto2) enums.
456 return Number(readSignedInt(tok, negative));
457 }
458 throw new Error(`expected an enum value for ${descEnum}, got ${describe(tok)}`);
459 }
460 function readBoolValue(tok, negative) {
461 if (!negative) {
462 if (tok.type === "identifier") {
463 switch (tok.value) {
464 case "true":
465 case "True":
466 case "t":
467 return true;
468 case "false":
469 case "False":
470 case "f":
471 return false;
472 }
473 }
474 if (tok.type === "int") {
475 const value = intTokenToBigInt(tok);
476 if (value === BigInt(0)) {
477 return false;
478 }
479 if (value === BigInt(1)) {
480 return true;
481 }
482 }
483 }
484 throw new Error(`expected a bool, got ${negative ? "-" : ""}${describe(tok)}`);
485 }
486 function readFloatValue(tok, negative) {
487 if (tok.type === "identifier") {
488 // A separate "-" token (negative) before a float literal is invalid; the
489 // only signed literals are "-inf"/"-infinity", which the scanner glues into
490 // one identifier token. "-nan" is not a literal, so it falls through to the
491 // error below. This matches protobuf-go's identifier-path sign handling.
492 if (negative) {
493 throw new Error(`invalid float value "-${tok.value}"`);
494 }
495 switch (tok.value.toLowerCase()) {
496 case "inf":
497 case "infinity":
498 return Number.POSITIVE_INFINITY;
499 case "-inf":
500 case "-infinity":
501 return Number.NEGATIVE_INFINITY;
502 case "nan":
503 return Number.NaN;
504 }
505 throw new Error(`invalid float value "${tok.value}"`);
506 }
507 if (tok.type === "float") {
508 const n = Number(tok.text);
509 return negative ? -n : n;
510 }
511 if (tok.type === "int") {
512 // Octal and hexadecimal literals are not valid for float and double fields.
513 if (tok.base !== 10) {
514 throw new Error("octal and hexadecimal are not valid for a float field");
515 }
516 const n = Number(tok.text);
517 return negative ? -n : n;
518 }
519 throw new Error(`expected a float, got ${describe(tok)}`);
520 }
521 function readSignedInt(tok, negative) {
522 if (tok.type !== "int") {
523 throw new Error(`expected an integer, got ${describe(tok)}`);
524 }
525 const value = intTokenToBigInt(tok);
526 return negative ? -value : value;
527 }
528 function readUnsignedInt(tok, negative) {
529 // Reject any sign for an unsigned field, including "-0": the reflect layer
530 // would silently accept it as 0.
531 if (negative) {
532 throw new Error("an unsigned field does not accept a negative value");
533 }
534 return readSignedInt(tok, false);
535 }
536 function intTokenToBigInt(tok) {
537 // Octal text keeps its leading "0" (e.g. "0755"), which BigInt would read as
538 // decimal, so it needs the "0o" prefix. Hex ("0x...") and decimal text are
539 // accepted by BigInt as-is.
540 return tok.base === 8
541 ? BigInt("0o" + tok.text.substring(1))
542 : BigInt(tok.text);
543 }
544 // Concatenate adjacent string literals into a single byte string.
545 function concatStrings(first, ctx) {
546 if (ctx.reader.peek().type !== "string") {
547 return first.value;
548 }
549 const parts = [first.value];
550 let length = first.value.length;
551 while (ctx.reader.peek().type === "string") {
552 const tok = ctx.reader.next();
553 parts.push(tok.value);
554 length += tok.value.length;
555 }
556 const bytes = new Uint8Array(length);
557 let offset = 0;
558 for (const part of parts) {
559 bytes.set(part, offset);
560 offset += part.length;
561 }
562 return bytes;
563 }
564 /**
565 * Skip the value of a reserved field. Like every other nested read, the message
566 * case is guarded by the recursion limit.
567 */
568 function skipFieldValue(ctx) {
569 consumeColon(ctx);
570 skipValue(ctx);
571 }
572 function skipValue(ctx) {
573 readBracketedList(ctx, () => skipSingleValue(ctx));
574 }
575 function skipSingleValue(ctx) {
576 const tok = ctx.reader.peek();
577 if (tok.type === "{" || tok.type === "<") {
578 skipMessageBlock(ctx);
579 return;
580 }
581 // A leading sign is consumed leniently here: skipping a reserved value should
582 // tolerate "- 5".
583 consumeSign(ctx);
584 const value = ctx.reader.next();
585 if (value.type === "string") {
586 while (ctx.reader.peek().type === "string") {
587 ctx.reader.next();
588 }
589 return;
590 }
591 if (value.type !== "identifier" &&
592 value.type !== "int" &&
593 value.type !== "float") {
594 throw new Error(`expected a value, got ${describe(value)}`);
595 }
596 }
597 function skipMessageBlock(ctx) {
598 if (++ctx.depth > ctx.recursionLimit) {
599 throw new Error(`recursion limit of ${ctx.recursionLimit} reached skipping a reserved field`);
600 }
601 const close = readMessageOpen(ctx);
602 for (;;) {
603 const tok = ctx.reader.peek();
604 if (tok.type === close) {
605 ctx.reader.next();
606 ctx.depth--;
607 return;
608 }
609 if (tok.type === "eof") {
610 throw new Error(`unexpected end of input, expected "${close}"`);
611 }
612 const nameTok = ctx.reader.next();
613 if (nameTok.type === "[") {
614 ctx.reader.readTypeName();
615 }
616 else if (nameTok.type !== "identifier" && nameTok.type !== "int") {
617 throw new Error(`expected a field name, got ${describe(nameTok)}`);
618 }
619 skipFieldValue(ctx);
620 consumeSeparator(ctx);
621 }
622 }
623 // Consume an optional "," or ";" that separates fields or list/map elements.
624 function consumeSeparator(ctx) {
625 const sep = ctx.reader.peek();
626 if (sep.type === "," || sep.type === ";") {
627 ctx.reader.next();
628 }
629 }
630 function consumeColon(ctx) {
631 if (ctx.reader.peek().type === ":") {
632 ctx.reader.next();
633 return true;
634 }
635 return false;
636 }
637 function requireColon(ctx) {
638 if (!consumeColon(ctx)) {
639 throw new Error(`expected ":", got ${describe(ctx.reader.peek())}`);
640 }
641 }
642 const textFieldCache = new WeakMap();
643 /**
644 * Resolve a field by its text format name, mirroring protobuf-go's ByTextName:
645 * group-like fields are addressed by their message type name, with the
646 * lowercase form as an alias; JSON names are not in this table.
647 */
648 function fieldByTextName(desc, name) {
649 let byText = textFieldCache.get(desc);
650 if (byText === undefined) {
651 byText = new Map();
652 for (const field of desc.fields) {
653 if ((0, is_group_like_js_1.isGroupLike)(field)) {
654 setOnce(byText, field.message.name, field);
655 setOnce(byText, field.message.name.toLowerCase(), field);
656 }
657 else {
658 setOnce(byText, field.name, field);
659 }
660 }
661 textFieldCache.set(desc, byText);
662 }
663 return byText.get(name);
664 }
665 function setOnce(map, key, field) {
666 if (!map.has(key)) {
667 map.set(key, field);
668 }
669 }
670 function describe(tok) {
671 switch (tok.type) {
672 case "identifier":
673 return `"${tok.value}"`;
674 case "int":
675 case "float":
676 return `"${tok.text}"`;
677 case "string":
678 return "a string";
679 case "eof":
680 return "end of input";
681 default:
682 return `"${tok.type}"`;
683 }
684 }