Datasets:
File size: 59,930 Bytes
0e239c6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 | diff --git a/.github/workflows/difftest.yml b/.github/workflows/difftest.yml
new file mode 100644
index 0000000..b6e0d6c
--- /dev/null
+++ b/.github/workflows/difftest.yml
@@ -0,0 +1,47 @@
+name: difftest
+
+# The milestone-6 cron lane: differential fuzzing of darkwing against the
+# pinned DuckDB CLI, plus a native fuzz run of the public Parse API. The
+# nightly artifact only matches the pin until upstream moves it, so the
+# lane verifies the version first and skips (green) once it drifts —
+# advancing the pin is its own workflow (cmd/regenerate), not this one.
+
+on:
+ schedule:
+ - cron: "17 5 * * *"
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+jobs:
+ difftest:
+ runs-on: ubuntu-latest
+ timeout-minutes: 60
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-go@v5
+ with:
+ go-version-file: go.mod
+ - name: Download the nightly DuckDB CLI
+ run: |
+ curl -sSL -o duckdb.zip https://artifacts.duckdb.org/latest/duckdb-binaries-linux-amd64.zip
+ unzip -o -q duckdb.zip duckdb_cli-linux-amd64.zip
+ unzip -o -q duckdb_cli-linux-amd64.zip
+ ./duckdb --version
+ - name: Check the nightly against the pin
+ id: pin
+ run: |
+ pin=$(sed -n 's/.*PinnedVersion = "\(.*\)"/\1/p' internal/duckdbsrc/duckdbsrc.go)
+ version=$(./duckdb --version)
+ if echo "$version" | grep -qF "$pin"; then
+ echo "matches=true" >> "$GITHUB_OUTPUT"
+ else
+ echo "matches=false" >> "$GITHUB_OUTPUT"
+ echo "nightly is $version, pin is $pin - skipping until the pin advances"
+ fi
+ - name: Differential fuzzing vs the pinned CLI
+ if: steps.pin.outputs.matches == 'true'
+ run: DARKWING_DUCKDB=$PWD/duckdb go run ./cmd/difftest -seed $(date +%s) -duration 20m
+ - name: Native fuzzing of Parse
+ run: go test ./parser -run '^$' -fuzz FuzzParse -fuzztime 10m
diff --git a/CLAUDE.md b/CLAUDE.md
index b35d5bd..ffb3fc9 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -77,6 +77,10 @@ Two corpus gates run under `go test ./parser`:
pinned DuckDB binary parses it. Since milestone 3 the classification
runs the full Parse pipeline, so transformer-raised Parser Errors count
alongside the matcher's syntax errors.
+- **Error fidelity** (`TestCorpusErrorMessages`, since milestone 6):
+ every rejection renders the oracle's recorded first line verbatim.
+ Positions and messages the corpus can't pin are covered by unit tests
+ in `parser/errors_test.go`.
- **Tree shape** (`TestSerializeGoldens`): `internal/serialize` output
must match vendored `json_serialize_sql` goldens for a corpus sample
(see `parser/testdata/serialize/README.md`).
diff --git a/README.md b/README.md
index 7939a27..4a28c5b 100644
--- a/README.md
+++ b/README.md
@@ -20,28 +20,34 @@ loader, and matcher (with packrat memoization) — to Go.
## Status
-Milestone 2 (corpus + accept/reject conformance) is in place: the corpus
-under `parser/testdata/` is extracted from DuckDB's own test suite and
-classified by the pinned DuckDB CLI (`cmd/regenerate`); `go test ./parser`
-enforces *darkwing accepts iff pinned DuckDB parses*, with remaining
-disagreements tracked in todo metadata (`cmd/next-test`).
-
-Milestone 1 (engine) is complete:
-
-- `token/` — token kinds and DuckDB's keyword categories
-- `lexer/` — port of the parsing tokenizer
-- `internal/grammar/` — vendored grammar (pinned upstream commit recorded in
- `internal/grammar/README.md`) and the grammar loader
-- `internal/matcher/` — matcher tree, packrat memoization, rule overrides,
- furthest-failure error reporting
-- `cmd/debug-parse` — dump tokens or the raw parse tree for SQL on the
- command line
-
-Next: the typed AST and transformer core (milestone 3).
+Milestones 1–6 are complete: the engine (tokenizer, grammar loader,
+matcher with packrat memoization), the corpus conformance gates, the full
+typed AST with a transformer for every statement, and the hardening pass.
+`go test ./parser` enforces, corpus-wide against the pinned DuckDB CLI:
+
+- **Accept/reject** — darkwing accepts a statement iff the pinned binary
+ parses it (`TestCorpus`), including transformer-raised parser errors.
+- **Error fidelity** — every rejection renders the oracle's error message
+ verbatim (`TestCorpusErrorMessages`), with positions pinned by unit
+ tests.
+- **Tree shape** — `internal/serialize` output matches vendored
+ `json_serialize_sql` goldens for the SELECT subset
+ (`TestSerializeGoldens`), with AST snapshots covering the rest.
+
+Hardening: `FuzzParse` holds the public API to its invariants on
+arbitrary input, benchmarks pin parse throughput and upstream's
+pathological-backtracking case (19 unmatched parens: milliseconds, thanks
+to packrat), and `cmd/difftest` mutates corpus seeds and diffs darkwing's
+verdicts against the pinned CLI (run nightly in CI while the nightly
+artifact matches the pin).
+
+Next: advancing the pin to the v2.0.0 tag when it lands (milestone 7),
+then sqlc integration.
```
$ go run ./cmd/debug-parse 'SELECT 1'
$ go run ./cmd/debug-parse -tokens 'SELECT * FROM t'
+$ go run ./cmd/debug-parse -ast 'FROM t SELECT x'
```
## License
diff --git a/cmd/difftest/main.go b/cmd/difftest/main.go
new file mode 100644
index 0000000..02db11c
--- /dev/null
+++ b/cmd/difftest/main.go
@@ -0,0 +1,355 @@
+// Command difftest is the milestone-6 differential fuzzer: it mutates
+// corpus seed statements at token boundaries and compares darkwing's
+// accept/reject verdict (and, for syntax errors, the message) against the
+// pinned DuckDB CLI — the strongest check on the matcher's ordered-choice
+// fidelity, cheap to run for hours in a cron lane.
+//
+// Usage:
+//
+// difftest [-n 500] [-duration 0] [-seed 1] [-jobs N] [-corpus dir]
+//
+// Deterministic for a given -seed/-corpus pair (a fixed -n; -duration
+// bounds wall clock instead). Exit status 1 when any disagreement is
+// found. The oracle binary is located via $DARKWING_DUCKDB (see
+// internal/duckdbsrc).
+//
+// Verdict policy mirrors the corpus harness: darkwing must reject iff
+// the oracle raises a Parser Error. Two known oracle imprecisions are
+// filtered rather than reported: mutants that mention the nested-SQL
+// functions (query, query_table, json_serialize_sql, ...) whose
+// bind-time inner parse also raises Parser Error, and oracle rejects
+// whose message is not a syntax error (bind-time ParserException raised
+// outside the parse pipeline — the corpus todo category). Oracle
+// timeouts and crashes leave a mutant unverified and are skipped.
+package main
+
+import (
+ "context"
+ "errors"
+ "flag"
+ "fmt"
+ "io/fs"
+ "math/rand"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "github.com/sqlc-dev/darkwing/internal/duckdbsrc"
+ "github.com/sqlc-dev/darkwing/internal/testfile"
+ "github.com/sqlc-dev/darkwing/lexer"
+ "github.com/sqlc-dev/darkwing/parser"
+ "github.com/sqlc-dev/darkwing/token"
+)
+
+func main() {
+ n := flag.Int("n", 500, "number of mutants to test (ignored with -duration)")
+ duration := flag.Duration("duration", 0, "run for this long instead of a fixed -n")
+ seed := flag.Int64("seed", 1, "mutation RNG seed")
+ jobs := flag.Int("jobs", runtime.NumCPU(), "concurrent oracle processes")
+ corpusDir := flag.String("corpus", filepath.Join("parser", "testdata", "corpus"), "corpus directory for seed statements")
+ maxPrint := flag.Int("max-print", 25, "max disagreements to print in detail")
+ verbose := flag.Bool("v", false, "print every mutant tested")
+ flag.Parse()
+
+ bin, err := duckdbsrc.Find()
+ if err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+ seeds, err := loadSeeds(*corpusDir)
+ if err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+ if len(seeds) == 0 {
+ fmt.Fprintf(os.Stderr, "no seed statements under %s (run cmd/regenerate first)\n", *corpusDir)
+ os.Exit(1)
+ }
+ fmt.Printf("difftest: %d seeds, seed=%d, jobs=%d\n", len(seeds), *seed, *jobs)
+
+ // one generator goroutine keeps mutation deterministic for a given
+ // -seed; workers race only for oracle execution
+ mutants := make(chan string, *jobs)
+ go func() {
+ defer close(mutants)
+ rng := rand.New(rand.NewSource(*seed))
+ deadline := time.Time{}
+ if *duration > 0 {
+ deadline = time.Now().Add(*duration)
+ }
+ for i := 0; *duration > 0 || i < *n; i++ {
+ if !deadline.IsZero() && time.Now().After(deadline) {
+ return
+ }
+ mutants <- mutate(rng, seeds)
+ }
+ }()
+
+ var (
+ mu sync.Mutex
+ disagreements int
+ tested atomic.Int64
+ unverified atomic.Int64
+ softSkipped atomic.Int64
+ )
+ var wg sync.WaitGroup
+ for w := 0; w < *jobs; w++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ oracle := &duckdbsrc.Oracle{Binary: bin}
+ for sql := range mutants {
+ if nestedParseSQL(sql) || shellArtifact(sql) {
+ softSkipped.Add(1)
+ continue
+ }
+ verdict, err := oracle.Run(sql)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "oracle: %v\n", err)
+ os.Exit(1)
+ }
+ if verdict.TimedOut || verdict.Crashed {
+ unverified.Add(1)
+ continue
+ }
+ got := classify(sql)
+ if !verdict.Reject && got.reject && verdict.PostParseError && multiStatement(sql) {
+ // the batch-mode CLI stops at the first failing
+ // statement: a post-parse error on an earlier
+ // statement leaves the rest unparsed, so the
+ // oracle's accept does not cover darkwing's reject
+ unverified.Add(1)
+ continue
+ }
+ tested.Add(1)
+ if *verbose {
+ fmt.Printf("mutant: %q oracle-reject=%v darkwing-reject=%v\n", sql, verdict.Reject, got.reject)
+ }
+ if diff := compare(verdict, got); diff != "" {
+ if verdict.Reject && !got.reject && !isSyntaxError(verdict.Error) {
+ // bind-time ParserException outside the parse
+ // pipeline: the corpus todo category, not a bug
+ softSkipped.Add(1)
+ continue
+ }
+ mu.Lock()
+ disagreements++
+ if disagreements <= *maxPrint {
+ fmt.Printf("DISAGREEMENT (%s)\nSQL: %s\noracle: %s\ndarkwing: %s\n\n",
+ diff, sql, describe(verdict.Reject, verdict.Error), describe(got.reject, got.detail))
+ }
+ mu.Unlock()
+ }
+ }
+ }()
+ }
+ wg.Wait()
+
+ fmt.Printf("tested %d mutants: %d disagreements (%d unverified, %d skipped as bind-time/nested-parse)\n",
+ tested.Load(), disagreements, unverified.Load(), softSkipped.Load())
+ if disagreements > 0 {
+ os.Exit(1)
+ }
+}
+
+// loadSeeds collects every corpus statement that is not skip-listed —
+// including must-rejects, whose mutants probe the error paths.
+func loadSeeds(root string) ([]string, error) {
+ var seeds []string
+ err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ if d.IsDir() || !strings.HasSuffix(path, ".test") {
+ return nil
+ }
+ file, err := testfile.Read(path)
+ if err != nil {
+ return err
+ }
+ meta, err := testfile.ReadMetadata(path)
+ if err != nil {
+ return err
+ }
+ for i := range file.Cases {
+ c := &file.Cases[i]
+ if _, skip := meta.Skip[c.Key()]; skip {
+ continue
+ }
+ if _, ok := lexer.Tokenize(c.SQL); ok == nil {
+ seeds = append(seeds, c.SQL)
+ }
+ }
+ return nil
+ })
+ return seeds, err
+}
+
+// verdict mirrors the corpus harness's classification: tokenizer,
+// matcher and transformer parse errors are rejects.
+type verdict struct {
+ reject bool
+ detail string
+}
+
+func classify(sql string) (v verdict) {
+ defer func() {
+ if r := recover(); r != nil {
+ v = verdict{reject: false, detail: fmt.Sprintf("transformer panic: %v", r)}
+ }
+ }()
+ _, err := parser.Parse(context.Background(), strings.NewReader(sql))
+ if err == nil {
+ return verdict{}
+ }
+ var pe *parser.Error
+ if errors.As(err, &pe) {
+ return verdict{reject: true, detail: pe.Error()}
+ }
+ return verdict{reject: false, detail: "internal error: " + err.Error()}
+}
+
+func isSyntaxError(msg string) bool {
+ return strings.HasPrefix(msg, "Parser Error: syntax error at or near")
+}
+
+// compare returns a non-empty disagreement kind when darkwing diverges
+// from the oracle on the mutant.
+func compare(oracle duckdbsrc.Verdict, got verdict) string {
+ if !got.reject && got.detail != "" {
+ return "internal error"
+ }
+ if oracle.Reject != got.reject {
+ if oracle.Reject {
+ return "oracle rejects, darkwing accepts"
+ }
+ return "darkwing rejects, oracle accepts"
+ }
+ // message fidelity: pinned only for syntax errors — a bind-time
+ // oracle reject can coincide with a darkwing reject for a different
+ // (legitimate) reason
+ if oracle.Reject && isSyntaxError(oracle.Error) {
+ // the oracle records the trimmed first line of a message; a token
+ // spelling with an embedded newline (unterminated dollar quote)
+ // spills across lines, so darkwing's line is trimmed to match
+ firstLine, _, _ := strings.Cut(got.detail, "\n")
+ if strings.TrimSpace(firstLine) != oracle.Error {
+ return "message mismatch"
+ }
+ }
+ return ""
+}
+
+func describe(reject bool, detail string) string {
+ if !reject {
+ if detail != "" {
+ return "accept (" + detail + ")"
+ }
+ return "accept"
+ }
+ return "reject (" + detail + ")"
+}
+
+// shellArtifact reports mutants the CLI shell intercepts before the
+// parser sees them: a line starting with '#' in column 0 is a shell
+// comment (an indented '#' reaches the parser as an operator) and a
+// line starting with '.' is a dot command.
+func shellArtifact(sql string) bool {
+ for _, line := range strings.Split(sql, "\n") {
+ if strings.HasPrefix(line, "#") || strings.HasPrefix(line, ".") {
+ return true
+ }
+ }
+ return false
+}
+
+// multiStatement reports whether sql contains a statement separator with
+// content after it (a ';' inside a string or comment also matches — the
+// check only widens the unverified skip, never a reported disagreement).
+func multiStatement(sql string) bool {
+ return strings.Contains(strings.TrimRight(sql, "; \t\r\n"), ";")
+}
+
+// nestedParseSQL reports statements that mention the functions whose
+// arguments the oracle parses as SQL at bind time — their Parser Errors
+// come from the inner parse the grammar never sees.
+func nestedParseSQL(sql string) bool {
+ l := strings.ToLower(sql)
+ for _, fn := range []string{"query", "query_table", "json_serialize_sql", "nextval", "currval"} {
+ if strings.Contains(l, fn) {
+ return true
+ }
+ }
+ return false
+}
+
+// mutate produces one mutant from the seed pool. All mutations cut and
+// splice the original source at token span boundaries, preserving the
+// seed's exact spelling (strings, comments, whitespace).
+func mutate(rng *rand.Rand, seeds []string) string {
+ src := seeds[rng.Intn(len(seeds))]
+ toks := realTokens(src)
+ if len(toks) == 0 {
+ return src
+ }
+ switch rng.Intn(6) {
+ case 0: // delete a token
+ t := toks[rng.Intn(len(toks))]
+ return src[:t.Span.Start] + src[t.Span.End:]
+ case 1: // duplicate a token
+ t := toks[rng.Intn(len(toks))]
+ return src[:t.Span.End] + " " + src[t.Span.Start:t.Span.End] + src[t.Span.End:]
+ case 2: // swap two adjacent tokens
+ if len(toks) < 2 {
+ return src
+ }
+ i := rng.Intn(len(toks) - 1)
+ a, b := toks[i], toks[i+1]
+ return src[:a.Span.Start] + src[b.Span.Start:b.Span.End] + src[a.Span.End:b.Span.Start] +
+ src[a.Span.Start:a.Span.End] + src[b.Span.End:]
+ case 3: // replace a token with one drawn from another seed
+ t := toks[rng.Intn(len(toks))]
+ other := seeds[rng.Intn(len(seeds))]
+ otherToks := realTokens(other)
+ if len(otherToks) == 0 {
+ return src
+ }
+ o := otherToks[rng.Intn(len(otherToks))]
+ return src[:t.Span.Start] + other[o.Span.Start:o.Span.End] + src[t.Span.End:]
+ case 4: // truncate at a token boundary
+ t := toks[rng.Intn(len(toks))]
+ return src[:t.Span.Start]
+ default: // splice a prefix of one seed onto a suffix of another
+ other := seeds[rng.Intn(len(seeds))]
+ otherToks := realTokens(other)
+ if len(otherToks) == 0 {
+ return src
+ }
+ t := toks[rng.Intn(len(toks))]
+ o := otherToks[rng.Intn(len(otherToks))]
+ return src[:t.Span.End] + " " + other[o.Span.Start:]
+ }
+}
+
+// realTokens tokenizes src, drops the end-of-input sentinel, and clamps
+// spans to the source (dollar-quoted string tokens record the rewritten
+// literal's length, which can overrun the source extent).
+func realTokens(src string) []token.Token {
+ toks, err := lexer.Tokenize(src)
+ if err != nil {
+ return nil
+ }
+ for len(toks) > 0 && toks[len(toks)-1].Kind == token.EndOfInput {
+ toks = toks[:len(toks)-1]
+ }
+ for i := range toks {
+ if toks[i].Span.End > len(src) {
+ toks[i].Span.End = len(src)
+ }
+ }
+ return toks
+}
diff --git a/internal/duckdbsrc/duckdbsrc.go b/internal/duckdbsrc/duckdbsrc.go
index fd7daad..634fd93 100644
--- a/internal/duckdbsrc/duckdbsrc.go
+++ b/internal/duckdbsrc/duckdbsrc.go
@@ -11,6 +11,7 @@ import (
"fmt"
"os"
"os/exec"
+ "regexp"
"strings"
"time"
)
@@ -79,6 +80,12 @@ type Verdict struct {
// Crashed records that the CLI died before printing a verdict; like
// TimedOut, the statement is unverified.
Crashed bool
+ // PostParseError records that the CLI reported a non-parser error
+ // (Binder Error, Catalog Error, ...). Still must-accept — but the
+ // batch-mode CLI stops at the first failing statement, so for
+ // multi-statement input everything after that statement went
+ // unparsed and the accept verdict does not cover it.
+ PostParseError bool
}
// Oracle runs statements through the pinned CLI against :memory:.
@@ -126,6 +133,7 @@ func (o *Oracle) Run(sql string) (Verdict, error) {
// execution ran long: parsing succeeded
return Verdict{TimedOut: true}, nil
}
+ postParse := hasPostParseError(stderr.String())
if err != nil {
var exitErr *exec.ExitError
if errors.As(err, &exitErr) {
@@ -137,11 +145,30 @@ func (o *Oracle) Run(sql string) (Verdict, error) {
}
// plain error exit with a non-parser error on stderr:
// post-parse failure, must-accept
- return Verdict{}, nil
+ return Verdict{PostParseError: postParse}, nil
}
return Verdict{}, fmt.Errorf("running oracle: %w", err)
}
- return Verdict{}, nil
+ return Verdict{PostParseError: postParse}, nil
+}
+
+// errorLine matches the CLI's non-parser error headers ("Binder Error:",
+// "Catalog Error: ", "Invalid Input Error: ", ...).
+var errorLine = regexp.MustCompile(`^[A-Za-z][A-Za-z ]*Error: `)
+
+// hasPostParseError reports whether stderr carries a non-parser error
+// line.
+func hasPostParseError(stderr string) bool {
+ for _, line := range strings.Split(stderr, "\n") {
+ line = strings.TrimSpace(line)
+ if strings.HasPrefix(line, "Parser Error") {
+ continue
+ }
+ if errorLine.MatchString(line) {
+ return true
+ }
+ }
+ return false
}
// classify scans CLI stderr for the first error line. Only "Parser Error"
diff --git a/internal/matcher/engine.go b/internal/matcher/engine.go
index 416a0ee..6ee2e86 100644
--- a/internal/matcher/engine.go
+++ b/internal/matcher/engine.go
@@ -17,7 +17,10 @@ type SyntaxError struct {
}
func (e *SyntaxError) Error() string {
- return fmt.Sprintf("syntax error at or near %q", e.Token.Text)
+ // the token's raw spelling goes between plain double quotes with no
+ // escaping, exactly as upstream renders it (embedded quotes,
+ // backslashes and newlines stay verbatim)
+ return `syntax error at or near "` + e.Token.Text + `"`
}
// MatchError is a non-positional matching error, mirroring the
diff --git a/parser/bench_test.go b/parser/bench_test.go
new file mode 100644
index 0000000..682d298
--- /dev/null
+++ b/parser/bench_test.go
@@ -0,0 +1,112 @@
+// Milestone 6 benchmarks: parse throughput on representative statements
+// and upstream's pathological-backtracking case. Upstream's motivating
+// packrat example — 19 unmatched '(' going from 10.6 s to 1 ms — is both
+// a benchmark and a regression test here.
+package parser
+
+import (
+ "context"
+ "strings"
+ "testing"
+
+ "github.com/sqlc-dev/darkwing/lexer"
+)
+
+const benchSimpleSelect = "SELECT a, b + 1 FROM t WHERE c = 'x' ORDER BY a LIMIT 10"
+
+const benchComplexSelect = `
+WITH sales AS (
+ SELECT region, product, amount, sold_at
+ FROM raw_sales
+ WHERE sold_at >= DATE '2024-01-01'
+), ranked AS (
+ SELECT region, product,
+ sum(amount) AS total,
+ rank() OVER (PARTITION BY region ORDER BY sum(amount) DESC) AS r
+ FROM sales
+ GROUP BY ALL
+)
+SELECT r.region, r.product, r.total,
+ t.name AS region_name,
+ CASE WHEN r.total > 1000 THEN 'big' ELSE 'small' END AS bucket
+FROM ranked r
+JOIN regions t ON r.region = t.id
+WHERE r.r <= 3
+QUALIFY row_number() OVER (ORDER BY r.total DESC) <= 100
+ORDER BY ALL`
+
+// benchMixed exercises the non-SELECT transformers.
+var benchMixed = []string{
+ "INSERT INTO t (a, b) VALUES (1, 'x'), (2, 'y') ON CONFLICT (a) DO UPDATE SET b = excluded.b RETURNING a",
+ "UPDATE t SET b = b + 1 FROM u WHERE t.a = u.a",
+ "DELETE FROM t USING u WHERE t.a = u.a RETURNING *",
+ "CREATE TABLE IF NOT EXISTS t (a INTEGER PRIMARY KEY, b VARCHAR DEFAULT 'x', c STRUCT(x INT, y MAP(TEXT, DOUBLE[])))",
+ "COPY t TO 'out.parquet' (FORMAT parquet, COMPRESSION zstd)",
+ "PIVOT sales ON month IN (jan, feb) USING sum(amount) GROUP BY region",
+ "SELECT * EXCLUDE (a) REPLACE (b + 1 AS b) FROM t USING SAMPLE 10%",
+ "ATTACH 'other.db' AS other (READ_ONLY)",
+ "PREPARE q AS SELECT * FROM t WHERE a = $1 AND b = $name",
+}
+
+func benchmarkParse(b *testing.B, sql string) {
+ b.Helper()
+ // prime the engine compile outside the timed loop
+ if _, err := Parse(context.Background(), strings.NewReader(sql)); err != nil {
+ b.Fatalf("Parse(%q): %v", sql, err)
+ }
+ b.SetBytes(int64(len(sql)))
+ b.ReportAllocs()
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ if _, err := parseString(context.Background(), sql); err != nil {
+ b.Fatal(err)
+ }
+ }
+}
+
+func BenchmarkParseSimpleSelect(b *testing.B) { benchmarkParse(b, benchSimpleSelect) }
+func BenchmarkParseComplexSelect(b *testing.B) { benchmarkParse(b, benchComplexSelect) }
+
+func BenchmarkParseMixed(b *testing.B) {
+ all := strings.Join(benchMixed, ";\n") + ";"
+ benchmarkParse(b, all)
+}
+
+func BenchmarkTokenize(b *testing.B) {
+ b.SetBytes(int64(len(benchComplexSelect)))
+ b.ReportAllocs()
+ for i := 0; i < b.N; i++ {
+ if _, err := lexer.Tokenize(benchComplexSelect); err != nil {
+ b.Fatal(err)
+ }
+ }
+}
+
+// unmatchedParens is upstream's pathological backtracking input: without
+// packrat memoization each unmatched '(' multiplies the work (10.6 s at
+// 19 parens in upstream's pre-memoization measurement).
+func unmatchedParens(n int) string {
+ return "SELECT " + strings.Repeat("(", n) + "1"
+}
+
+func BenchmarkUnmatchedParens19(b *testing.B) {
+ sql := unmatchedParens(19)
+ b.ReportAllocs()
+ for i := 0; i < b.N; i++ {
+ if _, err := parseString(context.Background(), sql); err == nil {
+ b.Fatal("expected a syntax error")
+ }
+ }
+}
+
+// TestPathologicalBacktracking is the packrat regression gate: well past
+// upstream's 19-paren case must still fail fast. If memoization breaks,
+// this does not finish.
+func TestPathologicalBacktracking(t *testing.T) {
+ for _, n := range []int{19, 40} {
+ pe := rejectError(t, unmatchedParens(n))
+ if !strings.Contains(pe.Msg, "syntax error") {
+ t.Errorf("unmatchedParens(%d): unexpected message %q", n, pe.Msg)
+ }
+ }
+}
diff --git a/parser/dml_test.go b/parser/dml_test.go
index 2aa6db1..81975d0 100644
--- a/parser/dml_test.go
+++ b/parser/dml_test.go
@@ -97,7 +97,7 @@ func TestInsertOnConflict(t *testing.T) {
if ins.OnConflict == nil || ins.OnConflict.Action != ast.OnConflictReplace {
t.Errorf("OR REPLACE on-conflict = %#v", ins.OnConflict)
}
- if msg := parseErr(t, "INSERT OR REPLACE INTO t VALUES (1) ON CONFLICT DO NOTHING"); !strings.Contains(msg, "not compatible") {
+ if msg := parseErr(t, "INSERT OR REPLACE INTO t VALUES (1) ON CONFLICT DO NOTHING"); !strings.Contains(msg, "can not provide both OR REPLACE|IGNORE") {
t.Errorf("shorthand+clause error = %q", msg)
}
}
diff --git a/parser/errors_test.go b/parser/errors_test.go
new file mode 100644
index 0000000..d11f9b8
--- /dev/null
+++ b/parser/errors_test.go
@@ -0,0 +1,197 @@
+// Error message and position fidelity (milestone 6): darkwing's rendered
+// parse errors must match the pinned DuckDB build's. The corpus records
+// the first line of the oracle's message for every must-reject case;
+// TestCorpusErrorMessages holds darkwing to it exactly. Positions are not
+// recorded in the corpus (the CLI renders them as a LINE/caret display
+// below the first line), so TestErrorPositions pins them with hand-written
+// cases instead.
+package parser
+
+import (
+ "context"
+ "errors"
+ "strings"
+ "testing"
+
+ "github.com/sqlc-dev/darkwing/internal/testfile"
+)
+
+// rejectError parses sql and returns the *Error it must fail with.
+func rejectError(t *testing.T, sql string) *Error {
+ t.Helper()
+ _, err := Parse(context.Background(), strings.NewReader(sql))
+ if err == nil {
+ t.Fatalf("Parse(%q): expected error", sql)
+ }
+ var pe *Error
+ if !errors.As(err, &pe) {
+ t.Fatalf("Parse(%q): got %T (%v), want *parser.Error", sql, err, err)
+ }
+ return pe
+}
+
+// TestCorpusErrorMessages is the negative-corpus message gate: for every
+// must-reject case, darkwing's error must render the oracle's recorded
+// first line verbatim.
+func TestCorpusErrorMessages(t *testing.T) {
+ for _, path := range corpusFiles(t) {
+ rel := strings.TrimPrefix(path, "testdata/")
+ t.Run(rel, func(t *testing.T) {
+ t.Parallel()
+ file, err := testfile.Read(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ meta, err := testfile.ReadMetadata(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for i := range file.Cases {
+ c := &file.Cases[i]
+ key := c.Key()
+ if !c.Reject {
+ continue
+ }
+ if _, skip := meta.Skip[key]; skip {
+ continue
+ }
+ if _, todo := meta.Todo[key]; todo {
+ continue
+ }
+ got := classify(nil, c.SQL)
+ if !got.reject {
+ // TestCorpus reports accept/reject disagreements
+ continue
+ }
+ // the oracle records only the first line; darkwing's
+ // multi-line messages (e.g. the PIVOT hints) match beyond it
+ firstLine, _, _ := strings.Cut(got.detail, "\n")
+ if firstLine != c.Error {
+ t.Errorf("case %s: error message diverges from the oracle\nSQL: %s\nwant: %s\ngot: %s",
+ key, c.SQL, c.Error, firstLine)
+ }
+ }
+ })
+ }
+}
+
+// TestErrorPositions pins Offset/Line/Column on representative failures.
+// Column counts bytes from 1, as the pinned CLI's caret display does.
+func TestErrorPositions(t *testing.T) {
+ tests := []struct {
+ sql string
+ msg string // rendered first line
+ offset int
+ line, col int
+ }{
+ {
+ // SELCT itself parses as a bare expression statement (a
+ // column reference), so the failure lands on the 1
+ sql: "SELCT 1",
+ msg: `Parser Error: syntax error at or near "1"`,
+ offset: 6, line: 1, col: 7,
+ },
+ {
+ sql: "SELECT 1 2",
+ msg: `Parser Error: syntax error at or near "2"`,
+ offset: 9, line: 1, col: 10,
+ },
+ {
+ sql: "SELECT 1;\nSELCT 2;",
+ msg: `Parser Error: syntax error at or near "2"`,
+ offset: 16, line: 2, col: 7,
+ },
+ {
+ sql: "SELECT 1\nFROM t\nWHERE (",
+ msg: `Parser Error: syntax error at or near "("`,
+ offset: 22, line: 3, col: 7,
+ },
+ {
+ // whole-query UTF-8 validation, positioned at the bad byte
+ sql: "SELECT\n 42\nFR\xffOM t;",
+ msg: "Parser Error: Invalid UTF-8 in query (byte sequence mismatch)",
+ offset: 14, line: 3, col: 3,
+ },
+ {
+ // a well-formed sequence encoding a surrogate is the other
+ // UnicodeInvalidReason
+ sql: "SELECT '\xed\xa0\x80'",
+ msg: "Parser Error: Invalid UTF-8 in query (invalid unicode)",
+ offset: 8, line: 1, col: 9,
+ },
+ }
+ for _, tt := range tests {
+ pe := rejectError(t, tt.sql)
+ firstLine, _, _ := strings.Cut(pe.Error(), "\n")
+ if firstLine != tt.msg {
+ t.Errorf("Parse(%q): message = %q, want %q", tt.sql, firstLine, tt.msg)
+ }
+ if pe.Offset != tt.offset || pe.Line != tt.line || pe.Column != tt.col {
+ t.Errorf("Parse(%q): position = offset %d line %d col %d, want offset %d line %d col %d",
+ tt.sql, pe.Offset, pe.Line, pe.Column, tt.offset, tt.line, tt.col)
+ }
+ }
+}
+
+// TestErrorMessages pins messages that only fire on inputs the corpus
+// does not cover.
+func TestErrorMessages(t *testing.T) {
+ tests := []struct{ sql, msg string }{
+ // escape-literal UTF-8 classification: raw invalid byte vs
+ // well-formed surrogate sequence
+ {`SELECT e'\xFF'`, "Parser Error: Invalid UTF-8 in escape string literal at byte offset 0: byte mismatch"},
+ {`SELECT e'a\xed\xa0\x80'`, "Parser Error: Invalid UTF-8 in escape string literal at byte offset 1: invalid unicode"},
+ // KeywordHelper::WriteOptionallyQuoted quotes keywords and
+ // non-plain identifiers, and leaves plain ones bare
+ {"CREATE TABLE t (foo)", "Parser Error: Column foo must have a type or be defined as a GENERATED column."},
+ {"CREATE TABLE t (name)", `Parser Error: Column "name" must have a type or be defined as a GENERATED column.`},
+ {`CREATE TABLE t ("A b")`, `Parser Error: Column "A b" must have a type or be defined as a GENERATED column.`},
+ // upstream names the last offending RESET option
+ {"ALTER TABLE t RESET (a='1', b='2')", `Parser Error: Reset option "b" cannot set any value. Did you mean to use SET?`},
+ {"ALTER TABLE t RESET (a='1', b)", `Parser Error: Reset option "a" cannot set any value. Did you mean to use SET?`},
+ // a deeper operand error beats the chained-comparison ban
+ {"SELECT 1 < 2 < [3][]", "Parser Error: Empty subscript '[]' is not allowed"},
+ {"SELECT 1 < 2 < 3", "Parser Error: Chained comparisons are not supported, use AND to combine comparisons"},
+ // the offending token's raw spelling goes between plain quotes
+ // with no escaping (found by cmd/difftest)
+ {`TABLE ALTER "other name" RENAME`, `Parser Error: syntax error at or near ""other name""`},
+ {`SELECT E'\\' = '\' '\';`, `Parser Error: syntax error at or near "'\'"`},
+ }
+ for _, tt := range tests {
+ pe := rejectError(t, tt.sql)
+ firstLine, _, _ := strings.Cut(pe.Error(), "\n")
+ if firstLine != tt.msg {
+ t.Errorf("Parse(%q): message = %q, want %q", tt.sql, firstLine, tt.msg)
+ }
+ }
+}
+
+// TestAnalyzeUTF8 pins the Utf8Proc::Analyze port's classification and
+// positions, including the deliberate divergence from the standard
+// library: overlong encodings pass.
+func TestAnalyzeUTF8(t *testing.T) {
+ tests := []struct {
+ in string
+ reason utf8Reason
+ pos int
+ }{
+ {"", utf8Valid, -1},
+ {"plain ascii", utf8Valid, -1},
+ {"caf\xc3\xa9", utf8Valid, -1},
+ {"\xf0\x9f\xa6\x86", utf8Valid, -1}, // U+1F986 (duck)
+ {"\xff", utf8ByteMismatch, 0},
+ {"a\x80", utf8ByteMismatch, 1}, // stray continuation byte
+ {"a\xc3", utf8ByteMismatch, 1}, // truncated 2-byte sequence
+ {"ab\xe0\xa0", utf8ByteMismatch, 2}, // truncated 3-byte sequence
+ {"\xc3(", utf8ByteMismatch, 0}, // bad continuation byte
+ {"\xed\xa0\x80", utf8InvalidUnicode, 0}, // surrogate U+D800
+ {"a\xf4\x90\x80\x80", utf8InvalidUnicode, 1}, // > U+10FFFF
+ {"\xc0\xaf", utf8Valid, -1}, // overlong '/', accepted like upstream
+ }
+ for _, tt := range tests {
+ reason, pos := analyzeUTF8(tt.in)
+ if reason != tt.reason || pos != tt.pos {
+ t.Errorf("analyzeUTF8(%q) = (%v, %d), want (%v, %d)", tt.in, reason, pos, tt.reason, tt.pos)
+ }
+ }
+}
diff --git a/parser/fuzz_test.go b/parser/fuzz_test.go
new file mode 100644
index 0000000..8dfbeb6
--- /dev/null
+++ b/parser/fuzz_test.go
@@ -0,0 +1,125 @@
+// Milestone 6 hardening: native fuzzing of the public Parse entry point
+// and a shared-engine parallel parse test (run under -race by the dev
+// loop and CI).
+package parser
+
+import (
+ "context"
+ "errors"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/sqlc-dev/darkwing/ast"
+)
+
+// checkParseInvariants parses src and enforces what Parse promises for
+// any input: no panic other than the controlled internal kinds, errors
+// are *parser.Error with sane positions, and on success the statement
+// spans tile the input.
+func checkParseInvariants(t *testing.T, src string) {
+ t.Helper()
+ stmts, err := Parse(context.Background(), strings.NewReader(src))
+ if err != nil {
+ var pe *Error
+ if !errors.As(err, &pe) {
+ t.Fatalf("Parse(%q): error is %T (%v), want *parser.Error", src, err, err)
+ }
+ if pe.Offset < -1 || pe.Offset > len(src) {
+ t.Fatalf("Parse(%q): error offset %d out of range", src, pe.Offset)
+ }
+ if pe.Line < 1 || pe.Column < 1 {
+ t.Fatalf("Parse(%q): error position line %d col %d", src, pe.Line, pe.Column)
+ }
+ return
+ }
+ // spans tile the input: the first statement starts at 0, each next
+ // one starts where the previous ended, the last ends at len(src)
+ prev := 0
+ for i, stmt := range stmts {
+ if stmt == nil {
+ t.Fatalf("Parse(%q): statement %d is nil", src, i)
+ }
+ sp := ast.Span{Start: stmt.Pos(), End: stmt.End()}
+ if sp.Start != prev {
+ t.Fatalf("Parse(%q): statement %d starts at %d, want %d", src, i, sp.Start, prev)
+ }
+ if sp.End < sp.Start || sp.End > len(src) {
+ t.Fatalf("Parse(%q): statement %d span [%d,%d) out of range", src, i, sp.Start, sp.End)
+ }
+ prev = sp.End
+ }
+ if len(stmts) > 0 && prev != len(src) {
+ t.Fatalf("Parse(%q): last statement ends at %d, want %d", src, prev, len(src))
+ }
+}
+
+var fuzzSeeds = []string{
+ "",
+ ";;",
+ "SELECT 1",
+ "SELECT * FROM t WHERE a = $1 AND b = ? AND c = $name",
+ "FROM t SELECT x: a + 1",
+ "WITH RECURSIVE c AS (SELECT 1) SELECT * FROM c UNION ALL BY NAME SELECT 2",
+ "INSERT OR REPLACE INTO t BY NAME SELECT 1 RETURNING *",
+ "CREATE TABLE t (a INT PRIMARY KEY, b STRUCT(x INT[], y MAP(TEXT, UNION(i INT, s TEXT))))",
+ "PIVOT sales ON month USING sum(amount)",
+ "SELECT [x + 1 FOR x IN [1,2,3] IF x > 1], l[1:3:2], r['k'], s.*.x",
+ "SELECT interval '2 10' years to months",
+ "SELECT e'\\x41\\n' || $tag$body$tag$ || 'lit''eral'",
+ "SELECT $$'''$$", // rewritten literal longer than its source extent
+ "SELECT a -> '$.b' ->> 'c' FROM j -- comment\n/* block /* nested */ */",
+ "ATTACH 'f.db' AS d (READ_ONLY); USE d; SET threads = 4;",
+ "SELECT (((((((1",
+ "SELCT 1 2 3 (",
+ "SELECT '\xff'",
+ "select 1 = 1 = 1",
+ "[1,2,3][];",
+}
+
+func FuzzParse(f *testing.F) {
+ for _, seed := range fuzzSeeds {
+ f.Add(seed)
+ }
+ f.Fuzz(func(t *testing.T, src string) {
+ if len(src) > 1<<14 {
+ // long adversarial inputs stress the matcher superlinearly;
+ // throughput is covered by the benchmarks
+ t.Skip()
+ }
+ checkParseInvariants(t, src)
+ })
+}
+
+// TestParseInvariantsOnSeeds keeps the fuzz seeds honest in ordinary
+// test runs (go test does not execute the fuzz engine).
+func TestParseInvariantsOnSeeds(t *testing.T) {
+ for _, seed := range fuzzSeeds {
+ checkParseInvariants(t, seed)
+ }
+}
+
+// TestParallelParse hammers the shared engine from many goroutines — the
+// race-clean gate for the immutable compiled grammar and the per-call
+// packrat state (meaningful under -race, as the dev loop and CI run it).
+func TestParallelParse(t *testing.T) {
+ inputs := append([]string(nil), fuzzSeeds...)
+ inputs = append(inputs, benchComplexSelect, unmatchedParens(19))
+ var wg sync.WaitGroup
+ for g := 0; g < 8; g++ {
+ wg.Add(1)
+ go func(g int) {
+ defer wg.Done()
+ for i := 0; i < 20; i++ {
+ src := inputs[(g+i)%len(inputs)]
+ _, err := Parse(context.Background(), strings.NewReader(src))
+ var pe *Error
+ if err != nil && !errors.As(err, &pe) {
+ t.Errorf("Parse(%q): unexpected error type %T", src, err)
+ return
+ }
+ }
+ }(g)
+ }
+ wg.Wait()
+}
diff --git a/parser/misc_test.go b/parser/misc_test.go
index 0db456b..5d4a33a 100644
--- a/parser/misc_test.go
+++ b/parser/misc_test.go
@@ -469,3 +469,42 @@ func TestSequenceOptionChecks(t *testing.T) {
}
parseOne(t, "CREATE SEQUENCE s INCREMENT 2 MINVALUE 0 MAXVALUE 100 START 4 CYCLE")
}
+
+// TestCollateNames pins the collationName port: identifier chains join
+// with '.', constants render via Value::ToString, and anything else —
+// where upstream throws NotImplementedException at bind time — still
+// parses (found by cmd/difftest).
+func TestCollateNames(t *testing.T) {
+ sel := func(sql string) *ast.CollateExpression {
+ t.Helper()
+ stmt := parseOne(t, sql).(*ast.SelectStatement)
+ node := stmt.Node.(*ast.SelectNode)
+ return node.SelectList[0].(*ast.CollateExpression)
+ }
+ for _, tt := range []struct{ sql, collation string }{
+ {"SELECT 'x' COLLATE nocase", "nocase"},
+ {"SELECT 'x' COLLATE a.b", "a.b"},
+ {"SELECT 'x' COLLATE 'lit'", "lit"},
+ {"SELECT 'x' COLLATE NULL", "NULL"},
+ {"SELECT 'x' COLLATE 3.5", "3.5"},
+ {"SELECT 'x' COLLATE true", "true"},
+ } {
+ if c := sel(tt.sql); c.Collation != tt.collation {
+ t.Errorf("%s: collation = %q, want %q", tt.sql, c.Collation, tt.collation)
+ }
+ }
+ // upstream: NotImplementedException (post-parse), so these parse
+ parseOne(t, "SELECT strpos('HELLO WORLD' COLLATE NOCASE 'o w')")
+ parseOne(t, "SELECT 'x' COLLATE $1")
+}
+
+// TestUnconvertibleNumberLiterals: a number token whose text has no
+// value ("2.03.0") still parses — upstream throws InvalidInputException
+// only while constructing the value, which is post-parse under the
+// oracle's classification (found by cmd/difftest).
+func TestUnconvertibleNumberLiterals(t *testing.T) {
+ parseOne(t, "SELECT 2.03.0")
+ parseOne(t, "SELECT list_position([1.0,2.03.0,]::varchar[], 'a')")
+ parseOne(t, "SELECT 12.5.5.5")
+ parseOne(t, "SELECT 999999999999999999999999999999999999999999.1.1")
+}
diff --git a/parser/parser.go b/parser/parser.go
index 0f15ba9..7681156 100644
--- a/parser/parser.go
+++ b/parser/parser.go
@@ -67,6 +67,9 @@ func ParseExpr(ctx context.Context, sql string) (expr ast.Expr, err error) {
if err != nil {
return nil, err
}
+ if ue := validateQueryUTF8(sql); ue != nil {
+ return nil, ue
+ }
tokens, err := lexer.Tokenize(sql)
if err != nil {
return nil, newError(sql, err)
@@ -92,6 +95,10 @@ func parseString(ctx context.Context, src string) (stmts []ast.Stmt, err error)
if err != nil {
return nil, err
}
+ // the pinned build validates the whole query's UTF-8 before parsing
+ if ue := validateQueryUTF8(src); ue != nil {
+ return nil, ue
+ }
tokens, err := lexer.Tokenize(src)
if err != nil {
return nil, newError(src, err)
@@ -148,12 +155,19 @@ func parseString(ctx context.Context, src string) (stmts []ast.Stmt, err error)
// consumedEnd returns the byte offset just past the tokens consumed by
// the match from pos to newPos (excluding the end-of-input sentinel).
+// Dollar-quoted string tokens record the rewritten literal's length
+// rather than the source extent (upstream behavior, pinned by the
+// serialize goldens' query_location_length), so the end is clamped to
+// keep statement spans inside the input they promise to tile.
func consumedEnd(tokens []token.Token, pos, newPos, srcLen int) int {
for i := newPos - 1; i >= pos; i-- {
if tokens[i].Kind == token.EndOfInput {
continue
}
- return tokens[i].Span.End
+ if end := tokens[i].Span.End; end < srcLen {
+ return end
+ }
+ return srcLen
}
return srcLen
}
@@ -204,6 +218,12 @@ func newError(src string, err error) error {
default:
msg = err.Error()
}
+ return errorAt(src, msg, offset)
+}
+
+// errorAt builds an *Error at a byte offset in src, deriving line and
+// column (offset -1 means no position).
+func errorAt(src, msg string, offset int) *Error {
pe := &Error{Msg: msg, Offset: offset, Line: 1, Column: 1}
if offset >= 0 {
line, col := 1, 1
diff --git a/parser/testdata/corpus/sql/join/nearest/nearest_errors.test.metadata.json b/parser/testdata/corpus/sql/join/nearest/nearest_errors.test.metadata.json
deleted file mode 100644
index de0d2fb..0000000
--- a/parser/testdata/corpus/sql/join/nearest/nearest_errors.test.metadata.json
+++ /dev/null
@@ -1,5 +0,0 @@
-{
- "todo": {
- "07e88975ac7f20a0": "oracle's Parser Error comes from outside the parse pipeline (bind-time setting/function/constraint validation or nested SQL parsing); darkwing accepts by design - revisit with milestone 6 error-fidelity work"
- }
-}
diff --git a/parser/transform_ddl.go b/parser/transform_ddl.go
index 8612e33..fdc3e71 100644
--- a/parser/transform_ddl.go
+++ b/parser/transform_ddl.go
@@ -68,7 +68,7 @@ func (tc *transformContext) transformCreate(n tnode) ast.Stmt {
base.Temporary = temporary
if base.OnConflict == "" || onConflict == ast.CreateReplace {
if base.OnConflict == ast.CreateIgnore && onConflict == ast.CreateReplace {
- raise("cannot combine OR REPLACE with IF NOT EXISTS")
+ raise("Cannot specify both OR REPLACE and IF NOT EXISTS within single create statement")
}
if onConflict != ast.CreateError || base.OnConflict == "" {
if base.OnConflict == "" {
@@ -114,7 +114,7 @@ func (tc *transformContext) transformCreateTable(n tnode) ast.CreateInfo {
stmt := tc.transformStatement(def.child(4))
sel, ok := stmt.(*ast.SelectStatement)
if !ok {
- raise("CREATE TABLE AS requires a SELECT statement")
+ raise("CREATE TABLE AS requires a SELECT clause")
}
info.Query = sel
case "CreateColumnList":
@@ -164,7 +164,7 @@ func (tc *transformContext) transformColumnDefinition(n tnode) ast.ColumnDef {
}
}
if col.Type == nil && col.Generated == "" {
- raise("Column %s must have a type or be defined as a GENERATED column.", strings.Join(col.Names, "."))
+ raise("Column %s must have a type or be defined as a GENERATED column.", optionallyQuoted(strings.Join(col.Names, ".")))
}
if col.Generated != "" {
name := col.Names[len(col.Names)-1]
@@ -926,17 +926,22 @@ func (tc *transformContext) transformAlterTableOption(n tnode) ast.AlterInfo {
info := &ast.GenericAlterInfo{Kind: "RESET_OPTIONS"}
info.SetSpan(alt.span())
// RESET (...) options cannot carry values (a bare NULL passes,
- // mirroring upstream's null-constant default)
+ // mirroring upstream's null-constant default); upstream checks
+ // the whole list and names the last offending option
+ offender := ""
for _, o := range alt.child(1).parens().listElems() {
// RelOption <- RelOptionName RelOptionArgumentOpt?
if arg, ok := o.child(1).opt(); ok {
// RelOptionArgumentOpt <- '=' DefArg
_, def := arg.child(1).sole().choice()
if def.name() != "DefArgNull" {
- raise("Reset option \"%s\" cannot set any value. Did you mean to use SET?", relOptionName(o.child(0)))
+ offender = relOptionName(o.child(0))
}
}
}
+ if offender != "" {
+ raise("Reset option \"%s\" cannot set any value. Did you mean to use SET?", offender)
+ }
return info
}
shapeError(alt, "unknown alter table option")
diff --git a/parser/transform_dml.go b/parser/transform_dml.go
index fcfeca2..1685578 100644
--- a/parser/transform_dml.go
+++ b/parser/transform_dml.go
@@ -83,7 +83,7 @@ func (tc *transformContext) transformInsert(n tnode) ast.Stmt {
}
if oc, ok := n.child(8).opt(); ok {
if stmt.OnConflict != nil {
- raise("OR REPLACE|IGNORE is not compatible with ON CONFLICT")
+ raise("You can not provide both OR REPLACE|IGNORE and an ON CONFLICT clause, please remove the first if you want to have more granular control")
}
stmt.OnConflict = tc.transformOnConflict(oc)
}
diff --git a/parser/transform_expr.go b/parser/transform_expr.go
index 27a2971..e99e86f 100644
--- a/parser/transform_expr.go
+++ b/parser/transform_expr.go
@@ -6,6 +6,8 @@
package parser
import (
+ "math/big"
+ "strconv"
"strings"
"github.com/sqlc-dev/darkwing/ast"
@@ -229,8 +231,13 @@ func (tc *transformContext) transformComparison(n tnode) ast.Expr {
return expr
}
if len(tails) > 1 {
- // upstream bans chained comparisons in the transformer
- raise("Chained comparisons (e.g. a < b < c) are not supported")
+ // upstream bans chained comparisons in the transformer, but only
+ // after transforming the operands - a deeper operand error (e.g.
+ // an empty subscript) takes precedence over the chain ban
+ for _, tail := range tails {
+ tc.transformBetweenInLike(tail.child(2))
+ }
+ raise("Chained comparisons are not supported, use AND to combine comparisons")
}
tail := tails[0]
_, opAlt := tail.child(0).sole().choice()
@@ -705,7 +712,7 @@ func (tc *transformContext) transformCollate(n tnode) ast.Expr {
expr := tc.transformAtTimeZone(n.child(0))
for _, tail := range n.child(1).repeat() {
rhs := tc.transformAtTimeZone(tail.child(1))
- collation := collationName(rhs)
+ collation := tc.collationName(rhs)
c := &ast.CollateExpression{Child: expr, Collation: collation}
c.SetSpan(ast.Span{Start: n.span().Start, End: tail.span().End})
expr = c
@@ -714,13 +721,78 @@ func (tc *transformContext) transformCollate(n tnode) ast.Expr {
}
// collationName extracts the collation name from the right-hand
-// expression of COLLATE (a bare identifier chain).
-func collationName(e ast.Expr) string {
- ref, ok := e.(*ast.ColumnRefExpression)
- if !ok {
- raise("COLLATE expects a collation name")
+// expression of COLLATE: an identifier chain joined with '.', or a
+// constant rendered with Value::ToString semantics ('x' COLLATE 'nocase'
+// and even COLLATE 3 parse; the name fails lookup at bind time). For any
+// other expression upstream throws NotImplementedException ("Unexpected
+// expression encountered for collate, ...") — a post-parse error under
+// the oracle's classification — so darkwing accepts and records the
+// source spelling.
+func (tc *transformContext) collationName(e ast.Expr) string {
+ switch v := e.(type) {
+ case *ast.ColumnRefExpression:
+ return strings.Join(v.ColumnNames, ".")
+ case *ast.ConstantExpression:
+ return valueString(v.Value)
+ }
+ return tc.exprSourceText(e)
+}
+
+// valueString ports Value::ToString for the constants the transformer
+// produces.
+func valueString(v ast.Value) string {
+ if v.IsNull {
+ return "NULL"
}
- return strings.Join(ref.ColumnNames, ".")
+ switch v.Kind {
+ case ast.ValueBool:
+ if v.Bool {
+ return "true"
+ }
+ return "false"
+ case ast.ValueInt64:
+ if v.Type.ID == "DECIMAL" {
+ return decimalValueString(strconv.FormatInt(v.Int64, 10), v.Type.Scale)
+ }
+ return strconv.FormatInt(v.Int64, 10)
+ case ast.ValueHugeint:
+ s := hugeintString(v.Hugeint)
+ if v.Type.ID == "DECIMAL" {
+ return decimalValueString(s, v.Type.Scale)
+ }
+ return s
+ case ast.ValueDouble:
+ return strconv.FormatFloat(v.Float64, 'g', -1, 64)
+ case ast.ValueString:
+ return v.Str
+ }
+ return ""
+}
+
+// hugeintString renders the 128-bit integer in decimal.
+func hugeintString(h ast.Hugeint) string {
+ n := new(big.Int).SetInt64(h.Upper)
+ n.Lsh(n, 64)
+ n.Add(n, new(big.Int).SetUint64(h.Lower))
+ return n.String()
+}
+
+// decimalValueString inserts the decimal point into an unscaled integer
+// rendering, Decimal::ToString-style ("35" scale 1 -> "3.5", "5" scale 2
+// -> "0.05").
+func decimalValueString(digits string, scale int) string {
+ if scale <= 0 {
+ return digits
+ }
+ sign := ""
+ if strings.HasPrefix(digits, "-") {
+ sign, digits = "-", digits[1:]
+ }
+ for len(digits) <= scale {
+ digits = "0" + digits
+ }
+ cut := len(digits) - scale
+ return sign + digits[:cut] + "." + digits[cut:]
}
// AtTimeZoneExpression <- PrefixExpression AtTimeZoneExpressionTail*
@@ -954,7 +1026,7 @@ func (tc *transformContext) transformSlice(base ast.Expr, n tnode) ast.Expr {
endBound, hasEnd := bound.child(1).opt()
if !hasEnd {
if start == nil {
- raise("empty subscript is not allowed")
+ raise("Empty subscript '[]' is not allowed")
}
return opExpr(sp, ast.ArrayExtract, base, start)
}
diff --git a/parser/transform_func.go b/parser/transform_func.go
index bf7edc8..6022845 100644
--- a/parser/transform_func.go
+++ b/parser/transform_func.go
@@ -433,17 +433,18 @@ func (tc *transformContext) transformFrameClause(w *ast.WindowExpression, n tnod
case "BetweenFrameExtent":
start, startExpr := tc.transformFrameBound(extent.child(1), kind, true)
end, endExpr := tc.transformFrameBound(extent.child(3), kind, false)
- if end == ast.WindowUnboundedPreceding {
- raise("Frame end cannot be UNBOUNDED PRECEDING")
- }
w.FrameStart, w.StartExpr = start, startExpr
w.FrameEnd, w.EndExpr = end, endExpr
default:
shapeError(extent, "unknown frame extent")
}
+ // upstream validates the start bound before the end bound
if w.FrameStart == ast.WindowUnboundedFollowing {
raise("Frame start cannot be UNBOUNDED FOLLOWING")
}
+ if w.FrameEnd == ast.WindowUnboundedPreceding {
+ raise("Frame end cannot be UNBOUNDED PRECEDING")
+ }
if excl, ok := n.child(2).opt(); ok {
_, e := excl.child(1).sole().choice()
switch e.name() {
@@ -1004,6 +1005,18 @@ var intervalFuncs = map[string]string{
"MillenniumKeyword": "to_millennia",
}
+// intervalRangeSpecifiers spells the IntervalToInterval alternatives the
+// way upstream's error message does.
+var intervalRangeSpecifiers = map[string]string{
+ "YearToMonth": "YEAR TO MONTH",
+ "DayToHour": "DAY TO HOUR",
+ "DayToMinute": "DAY TO MINUTE",
+ "DayToSecond": "DAY TO SECOND",
+ "HourToMinute": "HOUR TO MINUTE",
+ "HourToSecond": "HOUR TO SECOND",
+ "MinuteToSecond": "MINUTE TO SECOND",
+}
+
// IntervalLiteral <- 'INTERVAL' IntervalParameter Interval?
func (tc *transformContext) transformIntervalLiteral(n tnode) ast.Expr {
sp := n.span()
@@ -1031,7 +1044,12 @@ func (tc *transformContext) transformIntervalLiteral(n tnode) ast.Expr {
}
_, unit := unitNode.sole().choice()
if unit.name() == "IntervalToInterval" {
- raise("interval range specifiers (e.g. YEAR TO MONTH) are not supported in interval literals")
+ _, r := unit.sole().choice()
+ spec, ok := intervalRangeSpecifiers[r.name()]
+ if !ok {
+ shapeError(r, "unknown interval range specifier")
+ }
+ raise("%s is not supported", spec)
}
fname, ok := intervalFuncs[unit.name()]
if !ok {
diff --git a/parser/transform_misc.go b/parser/transform_misc.go
index 5eae438..a92ed6b 100644
--- a/parser/transform_misc.go
+++ b/parser/transform_misc.go
@@ -22,6 +22,7 @@ import (
"strings"
"github.com/sqlc-dev/darkwing/ast"
+ "github.com/sqlc-dev/darkwing/token"
)
func init() {
@@ -753,6 +754,28 @@ func (tc *transformContext) transformComment(n tnode) ast.Stmt {
return stmt
}
+// optionallyQuoted renders an identifier for an error message the way
+// upstream's KeywordHelper::WriteOptionallyQuoted does: wrapped in double
+// quotes (embedded quotes doubled) when it is empty, is a keyword, or is
+// not a plain lowercase identifier.
+func optionallyQuoted(s string) string {
+ needs := s == "" || token.IsKeyword(s)
+ for i := 0; i < len(s) && !needs; i++ {
+ c := s[i]
+ switch {
+ case c >= 'a' && c <= 'z' || c == '_':
+ case c >= '0' && c <= '9':
+ needs = i == 0
+ default:
+ needs = true
+ }
+ }
+ if !needs {
+ return s
+ }
+ return `"` + strings.ReplaceAll(s, `"`, `""`) + `"`
+}
+
// qualifiedNameFromParts splits a dotted path into catalog/schema/name,
// mirroring upstream's QualifiedName::StringToQualifiedName.
func qualifiedNameFromParts(parts []string) (catalog, schema, name string) {
@@ -764,7 +787,7 @@ func qualifiedNameFromParts(parts []string) (catalog, schema, name string) {
case 3:
return parts[0], parts[1], parts[2]
}
- raise("Too many qualifications for name \"%s\"", strings.Join(parts, "."))
+ raise("Too many qualifications found - expected [catalog.schema.name] or [schema.name]")
return "", "", ""
}
diff --git a/parser/transform_single.go b/parser/transform_single.go
index 95d1241..81f1875 100644
--- a/parser/transform_single.go
+++ b/parser/transform_single.go
@@ -6,10 +6,10 @@ package parser
import (
"errors"
+ "fmt"
"math"
"strconv"
"strings"
- "unicode/utf8"
"github.com/sqlc-dev/darkwing/ast"
"github.com/sqlc-dev/darkwing/internal/matcher"
@@ -191,9 +191,12 @@ func (tc *transformContext) stringConstant(sp ast.Span, s string, kind matcher.S
if strings.IndexByte(unescaped, 0) >= 0 {
raise("Null character not permitted in escape string literal")
}
- if !utf8.ValidString(unescaped) {
- raise("Invalid UTF-8 in escape string literal at byte offset %d: invalid unicode codepoint",
- invalidUTF8Offset(unescaped))
+ if reason, off := analyzeUTF8(unescaped); reason != utf8Valid {
+ kind := "byte mismatch"
+ if reason == utf8InvalidUnicode {
+ kind = "invalid unicode"
+ }
+ raise("Invalid UTF-8 in escape string literal at byte offset %d: %s", off, kind)
}
return constExpr(sp, varcharValue(unescaped))
default:
@@ -250,19 +253,6 @@ func unescapeString(s string) string {
return sb.String()
}
-// invalidUTF8Offset finds the first invalid byte offset of a non-UTF-8
-// string (for the escape-literal error message).
-func invalidUTF8Offset(s string) int {
- for i := 0; i < len(s); {
- r, size := utf8.DecodeRuneInString(s[i:])
- if r == utf8.RuneError && size == 1 {
- return i
- }
- i += size
- }
- return len(s)
-}
-
func isHexDigit(c byte) bool {
return c >= '0' && c <= '9' || c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F'
}
@@ -306,13 +296,26 @@ func integerTypeFor(v int64) string {
// INTEGER/BIGINT/HUGEINT (then DOUBLE), plain decimals become DECIMAL
// with derived width/scale (up to width 38), exponent forms become
// DOUBLE.
+// unconvertibleNumber stands in for a number literal whose text has no
+// value (e.g. "2.03.0", tokenized as a single number): upstream accepts
+// the token and throws InvalidInputException while constructing the
+// value ("Could not convert string ... to DECIMAL(5,1)") — post-parse
+// under the oracle's classification — so darkwing records the raw text
+// as a cast to the derived type and accepts (found by cmd/difftest).
+func unconvertibleNumber(sp ast.Span, text, typeID string) ast.Expr {
+ child := constExpr(invalidSpan, varcharValue(text))
+ cast := &ast.CastExpression{Child: child, ResolvedType: typeID}
+ cast.SetSpan(sp)
+ return cast
+}
+
func numberConstant(sp ast.Span, text string) ast.Expr {
clean := strings.ReplaceAll(text, "_", "")
lower := strings.ToLower(clean)
if strings.ContainsAny(lower, "e") {
f, err := parseDouble(clean)
if err != nil {
- raise("invalid number literal \"%s\"", text)
+ return unconvertibleNumber(sp, clean, "DOUBLE")
}
return constExpr(sp, ast.Value{Type: ast.LogicalType{ID: "DOUBLE"}, Kind: ast.ValueDouble, Float64: f})
}
@@ -331,7 +334,7 @@ func numberConstant(sp ast.Span, text string) ast.Expr {
}
f, err := parseDouble(clean)
if err != nil {
- raise("invalid number literal \"%s\"", text)
+ return unconvertibleNumber(sp, clean, "DOUBLE")
}
return constExpr(sp, ast.Value{Type: ast.LogicalType{ID: "DOUBLE"}, Kind: ast.ValueDouble, Float64: f})
}
@@ -362,7 +365,7 @@ func decimalConstant(sp ast.Span, clean string, dot int) ast.Expr {
if width > 38 {
f, err := parseDouble(clean)
if err != nil {
- raise("invalid number literal \"%s\"", clean)
+ return unconvertibleNumber(sp, clean, "DOUBLE")
}
return constExpr(sp, ast.Value{Type: ast.LogicalType{ID: "DOUBLE"}, Kind: ast.ValueDouble, Float64: f})
}
@@ -376,7 +379,7 @@ func decimalConstant(sp ast.Span, clean string, dot int) ast.Expr {
}
h, ok := parseHugeint(unscaled)
if !ok {
- raise("invalid number literal \"%s\"", clean)
+ return unconvertibleNumber(sp, clean, fmt.Sprintf("DECIMAL(%d,%d)", width, scale))
}
return constExpr(sp, ast.Value{Type: typ, Kind: ast.ValueHugeint, Hugeint: h})
}
diff --git a/parser/transform_tableref.go b/parser/transform_tableref.go
index d1892c1..07103fa 100644
--- a/parser/transform_tableref.go
+++ b/parser/transform_tableref.go
@@ -511,8 +511,8 @@ func (tc *transformContext) transformNearestJoin(left ast.TableRef, n tnode) ast
}
if num, ok := alt.child(5).opt(); ok {
v, err := strconv.ParseInt(num.number(), 10, 64)
- if err != nil {
- raise("invalid NEAREST count")
+ if err != nil || v <= 0 {
+ raise("NEAREST expects a positive integer literal, got \"%s\"", num.number())
}
join.NearestCount = v
}
@@ -795,7 +795,7 @@ func (tc *transformContext) transformPivotStatement(n tnode) ast.QueryNode {
raise("Cannot pivot on constant value \"%s\"", constantText(e))
}
if hasSubquery(e) {
- raise("Cannot pivot on subquery \"%s\"", constantText(e))
+ raise("Cannot pivot on subquery \"%s\"", tc.exprSourceText(e))
}
}
}
@@ -898,6 +898,18 @@ func constantText(e ast.Expr) string {
return "?"
}
+// exprSourceText renders an expression for an error message by slicing
+// the original source at its span — a best-effort stand-in for upstream's
+// ToString renderer, which darkwing does not have. Falls back to
+// constantText when the span is invalid.
+func (tc *transformContext) exprSourceText(e ast.Expr) string {
+ start, end := e.Pos(), e.End()
+ if start >= 0 && start < end && end <= len(tc.src) {
+ return tc.src[start:end]
+ }
+ return constantText(e)
+}
+
// PivotColumnEntry <- PivotColumnSubquery / PivotValueList / PivotColumnExpression
func (tc *transformContext) transformPivotColumnEntry(n tnode) ast.PivotColumn {
_, alt := n.sole().choice()
diff --git a/parser/utf8.go b/parser/utf8.go
new file mode 100644
index 0000000..1ca97f1
--- /dev/null
+++ b/parser/utf8.go
@@ -0,0 +1,69 @@
+package parser
+
+// utf8Reason classifies why a byte string is not valid UTF-8 — the port
+// of upstream's UnicodeInvalidReason.
+type utf8Reason int
+
+const (
+ utf8Valid utf8Reason = iota
+ // utf8ByteMismatch is a malformed byte sequence (bad start byte or
+ // missing/invalid continuation byte).
+ utf8ByteMismatch
+ // utf8InvalidUnicode is a well-formed sequence encoding an invalid
+ // codepoint (surrogate or beyond U+10FFFF).
+ utf8InvalidUnicode
+)
+
+// analyzeUTF8 walks s the way upstream's Utf8Proc::Analyze does and
+// returns the first invalid sequence's classification and start offset
+// (utf8Valid and -1 when the whole string is valid). Unlike the standard
+// library's utf8.ValidString it accepts overlong encodings, matching the
+// pinned build's effective behavior.
+func analyzeUTF8(s string) (utf8Reason, int) {
+ for i := 0; i < len(s); {
+ c := s[i]
+ if c&0x80 == 0 {
+ i++
+ continue
+ }
+ start := i
+ var cont int
+ var cp int32
+ switch {
+ case c&0xE0 == 0xC0:
+ cont, cp = 1, int32(c&0x1F)
+ case c&0xF0 == 0xE0:
+ cont, cp = 2, int32(c&0x0F)
+ case c&0xF8 == 0xF0:
+ cont, cp = 3, int32(c&0x07)
+ default:
+ return utf8ByteMismatch, start
+ }
+ i++
+ for j := 0; j < cont; j++ {
+ if i >= len(s) || s[i]&0xC0 != 0x80 {
+ return utf8ByteMismatch, start
+ }
+ cp = cp<<6 | int32(s[i]&0x3F)
+ i++
+ }
+ if cp > 0x10FFFF || (cp >= 0xD800 && cp <= 0xDFFF) {
+ return utf8InvalidUnicode, start
+ }
+ }
+ return utf8Valid, -1
+}
+
+// validateQueryUTF8 raises the pinned build's whole-query UTF-8 error
+// when src is not valid UTF-8, positioned at the invalid sequence.
+func validateQueryUTF8(src string) *Error {
+ reason, off := analyzeUTF8(src)
+ if reason == utf8Valid {
+ return nil
+ }
+ kind := "byte sequence mismatch"
+ if reason == utf8InvalidUnicode {
+ kind = "invalid unicode"
+ }
+ return errorAt(src, "Invalid UTF-8 in query ("+kind+")", off)
+}
|