packages/sql-semantics-mysql/fuzz/Target/RoundTripTarget.php
1<?php
2
3declare(strict_types=1);
4
5namespace Fuzz\Target;
6
7use Error;
8use SqlSemantics\Platform\MySql\Model\Validation\Equivalence;
9use SqlSemantics\Platform\MySql\Semantics;
10use Throwable;
11
12/**
13 * Every generated statement must be analyzed into a semantic structure whose rendering analyzes into the same structure.
14 */
15final class RoundTripTarget
16{
17 public function __construct(private readonly Semantics $semantics, private readonly string $grammarVersion)
18 {
19 }
20
21 /**
22 * Records rejections, implementation gaps, invariant violations and structural differences as fuzz findings.
23 */
24 public function verify(string $sql, string $input): void
25 {
26 $context = "Grammar: {$this->grammarVersion}\nInput (hex): " . bin2hex($input) . "\nSQL: {$sql}";
27 if ($sql === '') {
28 throw new Error("Statement generation returned an empty string\n{$context}");
29 }
30 $rendered = null;
31 try {
32 $operation = $this->semantics->inspect($sql);
33 $rendered = $operation->toString();
34 $again = $this->semantics->inspect($rendered);
35 $difference = (new Equivalence())->difference($operation->statement, $again->statement);
36 if ($difference !== null) {
37 throw new Error('The structure of the rendered SQL differs from the structure of the input at ' . $difference);
38 }
39 if ($again->toString() !== $rendered) {
40 throw new Error('The rendering is not stable: ' . $again->toString());
41 }
42 } catch (Throwable $failure) {
43 throw new Error("Semantic round trip failed\n{$context}\nRendered: {$rendered}\nError: {$failure->getMessage()}", 0, $failure);
44 }
45 }
46}
47