From c6943fd66b359177c026351c08a2f87bf97f8f83 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Canna=C3=B2?= Date: Wed, 25 Nov 2026 14:22:57 +0100 Subject: [PATCH 1/2] feat(digest): report what the token-level digest replaced or dropped The token-level digest turns a statement into its normalized text and a hash in one tokenizer pass. A caller that wants to treat two statements with the same normalized text as "the same statement with different values" (to reuse an analysis it already made of the first one, or to bind the values) had to tokenize the statement a second time to find the values, and could not tell when the normalized text had lost something that matters. Digest::compute(sql, len, DigestTrace&) is the same digest, with the same normalized text and hash as compute(sql, len), and also reports: - literals: the token type and source span (quotes and prefixes included) of every literal that became '?', in source order. Up to DigestTrace::max_literals are recorded; literal_count counts them all. - consumed: the input bytes up to and including the ';' that ended the first statement, or the whole input. The digest covers one statement; this tells the caller whether anything follows it. - collapsed: an IN list or VALUES rows were collapsed, so tokens are missing from the normalized text. A single VALUES row made only of literals loses nothing: its literals are reported and the flag stays clear. Any other token in the first row (a sign, a function call, an expression) or a further row sets it. - delimited_identifier: a quoted identifier appears in the normalized text without its delimiters, so "T" and T look the same. - comments: a comment was skipped. - errors: the tokenizer returned an error token. The tokenizer gains has_comments(), sticky since reset(), set wherever a comment is recognised (line comments, block comments, MySQL optimizer hints and executable comments). compute(sql, len) is unchanged and pays nothing for the trace beyond a null check where a literal is emitted. Tests: DigestTraceTest (9 cases) covers literal spans, equality with the untraced digest, the consumed boundary, IN and VALUES collapsing, the exact single-row case, delimited identifiers in both dialects, comments, errors and the literal cap. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01HsQTtbyp4v1ARw6Ym5CcEe --- include/sql_parser/digest.h | 73 ++++++++++++++++++++- include/sql_parser/tokenizer.h | 8 +++ tests/test_digest.cpp | 116 +++++++++++++++++++++++++++++++++ 3 files changed, 195 insertions(+), 2 deletions(-) diff --git a/include/sql_parser/digest.h b/include/sql_parser/digest.h index 3508c34..40245d7 100644 --- a/include/sql_parser/digest.h +++ b/include/sql_parser/digest.h @@ -16,6 +16,29 @@ struct DigestResult { uint64_t hash; // 64-bit FNV-1a hash }; +// A literal the token-level digest replaced with '?': its token type and where +// its source spelling (quotes and prefixes included) sits in the input. +struct DigestLiteral { + TokenType type; + uint32_t offset; + uint32_t length; +}; + +// What the token-level digest replaced, dropped or could not represent. It is +// for a caller that wants to treat two statements with the same normalized +// text as the same statement with different literal values: that holds only +// when none of the flags is set and the non-value literals are compared too. +struct DigestTrace { + static constexpr uint32_t max_literals = 16; + DigestLiteral literals[max_literals]; + uint32_t literal_count = 0; // all literals seen; only the first max_literals are recorded + uint32_t consumed = 0; // input bytes up to and including the terminating ';', else all + bool collapsed = false; // an IN list or VALUES rows were collapsed (tokens dropped) + bool delimited_identifier = false; // a quoted identifier lost its delimiters in the text + bool comments = false; // a comment was skipped + bool errors = false; // the tokenizer returned an error token +}; + // FNV-1a 64-bit hash -- simple, fast, no external dependency struct FnvHash { static constexpr uint64_t FNV_OFFSET_BASIS = 14695981039346656037ULL; @@ -58,8 +81,22 @@ class Digest { return compute_token_level(sql, len); } + // The same token-level digest, also reporting in 'trace' what the + // normalized text no longer shows. One tokenizer pass either way. + DigestResult compute(const char* sql, size_t len, DigestTrace& trace) { + trace.literal_count = 0; + trace.consumed = 0; + trace.collapsed = trace.delimited_identifier = trace.comments = trace.errors = false; + trace_ = &trace; + const DigestResult result = compute_token_level(sql, len); + trace_ = nullptr; + return result; + } + private: Arena& arena_; + DigestTrace* trace_ = nullptr; + const char* input_ = nullptr; // Helper: check if a token type is a keyword (not an identifier, literal, or operator) static bool is_keyword_token(TokenType type) { @@ -104,6 +141,20 @@ class Digest { return true; } + // Report a literal that the normalized text shows as '?'. + void trace_literal(const Token& t) { + if (!trace_) return; + if (trace_->literal_count < DigestTrace::max_literals) { + trace_->literals[trace_->literal_count] = DigestLiteral{ + t.type, static_cast(t.source.ptr - input_), t.source.len}; + } + ++trace_->literal_count; + } + // Report that tokens were left out of the normalized text. + void trace_collapsed() { + if (trace_) trace_->collapsed = true; + } + // Emit a single token to the string builder, uppercasing keywords, replacing literals with ? void emit_token(StringBuilder& sb, const Token& t, TokenType prev) { bool quoted_user_after_account = t.type == TokenType::TK_USER_VARIABLE && @@ -116,9 +167,11 @@ class Digest { if (is_literal_token(t.type)) { sb.append_char('?'); + trace_literal(t); } else if (is_keyword_token(t.type)) { append_upper(sb, t.text.ptr, t.text.len); } else if (t.type == TokenType::TK_IDENTIFIER) { + if (trace_ && t.source.len != t.text.len) trace_->delimited_identifier = true; sb.append(t.text.ptr, t.text.len); } else if (t.type == TokenType::TK_QUESTION) { sb.append_char('?'); @@ -152,6 +205,7 @@ class Digest { DigestResult compute_token_level(const char* sql, size_t len) { Tokenizer tok; tok.reset(sql, len); + input_ = sql; StringBuilder sb(arena_); TokenType prev = TokenType::TK_EOF; @@ -172,6 +226,7 @@ class Digest { // Emit " (" emit_token(sb, next, prev); prev = next.type; + trace_collapsed(); // Collapse contents to single ? bool emitted_q = false; int depth = 1; @@ -214,13 +269,16 @@ class Digest { emit_token(sb, next, prev); prev = next.type; - // Emit first row contents with ? for each value slot + // Emit first row contents with ? for each value slot. A + // row of plain literals loses nothing; any other token in + // it is left out of the text and reported as collapsed. int depth = 1; while (depth > 0) { Token inner = tok.next_token(); - if (inner.type == TokenType::TK_EOF) break; + if (inner.type == TokenType::TK_EOF) { trace_collapsed(); break; } if (inner.type == TokenType::TK_LPAREN) { depth++; + trace_collapsed(); continue; } if (inner.type == TokenType::TK_RPAREN) { @@ -243,8 +301,11 @@ class Digest { if (prev == TokenType::TK_LPAREN || prev == TokenType::TK_COMMA) { sb.append_char('?'); prev = TokenType::TK_QUESTION; + if (is_literal_token(inner.type)) trace_literal(inner); + continue; } } + trace_collapsed(); } // Skip additional rows: , (...) @@ -254,6 +315,7 @@ class Digest { Token peek2 = tok.next_token(); if (peek2.type == TokenType::TK_LPAREN) { // Skip this entire row + trace_collapsed(); skip_paren_contents(tok); continue; } else { @@ -289,6 +351,13 @@ class Digest { t = tok.next_token(); } + if (trace_) { + trace_->consumed = t.type == TokenType::TK_SEMICOLON + ? static_cast(t.source.ptr + t.source.len - sql) + : static_cast(len); + trace_->comments = tok.has_comments(); + trace_->errors = tok.has_error(); + } StringRef normalized = sb.finish(); FnvHash hasher; hasher.update(normalized.ptr, normalized.len); diff --git a/include/sql_parser/tokenizer.h b/include/sql_parser/tokenizer.h index 9e2456f..a3b356f 100644 --- a/include/sql_parser/tokenizer.h +++ b/include/sql_parser/tokenizer.h @@ -18,6 +18,7 @@ class Tokenizer { has_error_ = false; has_fatal_error_ = false; has_user_variables_ = false; + has_comments_ = false; hint_allowed_ = false; after_dot_ = false; paren_depth_ = 0; @@ -32,6 +33,9 @@ class Tokenizer { bool has_error() const { return has_error_; } bool has_fatal_error() const { return has_fatal_error_; } bool has_user_variables() const { return has_user_variables_; } + // True iff a comment was skipped since the last reset(), including MySQL + // optimizer hints and executable comments. + bool has_comments() const { return has_comments_; } StringRef error_source() const { return error_source_; } // Hook for parser-level (non-tokenizer) errors -- when the parser @@ -89,6 +93,7 @@ class Tokenizer { bool has_error_ = false; bool has_fatal_error_ = false; bool has_user_variables_ = false; + bool has_comments_ = false; uint32_t paren_depth_ = 0; const char* first_open_paren_ = nullptr; StringRef error_source_; @@ -126,6 +131,7 @@ class Tokenizer { (static_cast(peek_char(2)) <= 0x20 || static_cast(peek_char(2)) == 0x7f))); if (dash_comment) { + has_comments_ = true; hint_allowed_ = false; cursor_ += 2; while (cursor_ < end_ && *cursor_ != '\n') ++cursor_; @@ -135,6 +141,7 @@ class Tokenizer { // # line comment (MySQL only) if constexpr (D == Dialect::MySQL) { if (c == '#') { + has_comments_ = true; hint_allowed_ = false; ++cursor_; while (cursor_ < end_ && *cursor_ != '\n') ++cursor_; @@ -144,6 +151,7 @@ class Tokenizer { // /* block comment */ if (c == '/' && peek_char(1) == '*') { + has_comments_ = true; if constexpr (D == Dialect::MySQL) { if (hint_allowed_ && peek_char(2) == '+') return; } diff --git a/tests/test_digest.cpp b/tests/test_digest.cpp index 412175f..a26820b 100644 --- a/tests/test_digest.cpp +++ b/tests/test_digest.cpp @@ -403,3 +403,119 @@ TEST_F(MySQLDigestTest, TokenLevelValuesMultiRowSameHash) { auto d2 = digest_token("INSERT INTO t (a) VALUES (1), (2), (3)"); EXPECT_EQ(d1.hash, d2.hash); } + +// ========== Token-level digest trace ========== + +namespace { + +struct TracedDigest { + std::string normalized; + uint64_t hash; + DigestTrace trace; +}; + +template +TracedDigest traced(const std::string& sql) { + Arena arena; + Digest digest(arena); + TracedDigest out; + const DigestResult dr = digest.compute(sql.data(), sql.size(), out.trace); + out.normalized.assign(dr.normalized.ptr, dr.normalized.len); + out.hash = dr.hash; + return out; +} + +std::string literal_source(const std::string& sql, const DigestTrace& trace, uint32_t n) { + return sql.substr(trace.literals[n].offset, trace.literals[n].length); +} + +} // namespace + +TEST(DigestTraceTest, ReportsLiteralsInSourceOrder) { + const std::string sql = "UPDATE t SET a = a - 1, b = 'x' WHERE id = 4711;"; + const auto d = traced(sql); + EXPECT_EQ(d.normalized, "UPDATE t SET a = a - ?, b = ? WHERE id = ?"); + ASSERT_EQ(d.trace.literal_count, 3u); + EXPECT_EQ(d.trace.literals[0].type, TokenType::TK_INTEGER); + EXPECT_EQ(literal_source(sql, d.trace, 0), "1"); + EXPECT_EQ(d.trace.literals[1].type, TokenType::TK_STRING); + EXPECT_EQ(literal_source(sql, d.trace, 1), "'x'"); // source spelling, quotes included + EXPECT_EQ(d.trace.literals[2].type, TokenType::TK_INTEGER); + EXPECT_EQ(literal_source(sql, d.trace, 2), "4711"); + EXPECT_FALSE(d.trace.collapsed); + EXPECT_FALSE(d.trace.delimited_identifier); + EXPECT_FALSE(d.trace.comments); + EXPECT_FALSE(d.trace.errors); +} + +TEST(DigestTraceTest, SameTextAndHashAsUntracedDigest) { + for (const std::string sql : {"SELECT a, b FROM t WHERE id = 5 AND name = 'bob'", + "INSERT INTO t (a, b) VALUES (1, 'x'), (2, 'y')", + "SELECT * FROM t WHERE id IN (1, 2, 3)", "BEGIN"}) { + Arena arena; + Digest digest(arena); + const DigestResult plain = digest.compute(sql.data(), sql.size()); + const std::string plain_text(plain.normalized.ptr, plain.normalized.len); + const auto d = traced(sql); + EXPECT_EQ(d.normalized, plain_text) << sql; + EXPECT_EQ(d.hash, plain.hash) << sql; + } +} + +TEST(DigestTraceTest, ConsumedCoversTheFirstStatementOnly) { + const std::string two = "SELECT 1; SELECT 2"; + const auto d = traced(two); + EXPECT_EQ(d.normalized, "SELECT ?"); + EXPECT_EQ(d.trace.consumed, 9u); // up to and including the ';' + EXPECT_EQ(d.trace.literal_count, 1u); + + const std::string open = "SELECT 1"; + EXPECT_EQ(traced(open).trace.consumed, open.size()); +} + +TEST(DigestTraceTest, InListIsReportedAsCollapsed) { + const auto d = traced("SELECT * FROM t WHERE id IN (1, 2, 3)"); + EXPECT_EQ(d.normalized, "SELECT * FROM t WHERE id IN (?)"); + EXPECT_TRUE(d.trace.collapsed); +} + +TEST(DigestTraceTest, SingleRowOfPlainLiteralsIsExact) { + const std::string sql = "INSERT INTO t (a, b) VALUES (5, 'x')"; + const auto d = traced(sql); + EXPECT_EQ(d.normalized, "INSERT INTO t (a, b) VALUES (?, ?)"); + EXPECT_FALSE(d.trace.collapsed); + ASSERT_EQ(d.trace.literal_count, 2u); + EXPECT_EQ(literal_source(sql, d.trace, 0), "5"); + EXPECT_EQ(literal_source(sql, d.trace, 1), "'x'"); +} + +TEST(DigestTraceTest, ValuesRowsThatLoseTokensAreCollapsed) { + EXPECT_TRUE(traced("INSERT INTO t (a) VALUES (1), (2)").trace.collapsed); + EXPECT_TRUE(traced("INSERT INTO t (a, b) VALUES (1, now())").trace.collapsed); + EXPECT_TRUE(traced("INSERT INTO t (a) VALUES (-1)").trace.collapsed); + EXPECT_TRUE(traced("INSERT INTO t (a) VALUES (1 + 2)").trace.collapsed); +} + +TEST(DigestTraceTest, DelimitedIdentifierIsReported) { + EXPECT_TRUE(traced("SELECT a FROM \"T\" WHERE id = 1").trace.delimited_identifier); + EXPECT_TRUE(traced("SELECT a FROM `T` WHERE id = 1").trace.delimited_identifier); + EXPECT_FALSE(traced("SELECT a FROM T WHERE id = 1").trace.delimited_identifier); +} + +TEST(DigestTraceTest, CommentsAndErrorsAreReported) { + EXPECT_TRUE(traced("SELECT /* c */ a FROM t").trace.comments); + EXPECT_TRUE(traced("SELECT a FROM t -- c").trace.comments); + EXPECT_TRUE(traced("SELECT a FROM t # c").trace.comments); + EXPECT_FALSE(traced("SELECT a - 1 FROM t").trace.comments); + EXPECT_TRUE(traced("SELECT 'unterminated").trace.errors); + EXPECT_FALSE(traced("SELECT 'terminated'").trace.errors); +} + +TEST(DigestTraceTest, CountsLiteralsBeyondTheRecordedOnes) { + std::string sql = "SELECT 0"; + for (int i = 1; i < 20; ++i) sql += " + " + std::to_string(i); + const auto d = traced(sql); + EXPECT_EQ(d.trace.literal_count, 20u); + EXPECT_EQ(literal_source(sql, d.trace, DigestTrace::max_literals - 1), + std::to_string(DigestTrace::max_literals - 1)); +} From c77db41d59264c0e7b13717f946eb4bd75c086c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Canna=C3=B2?= Date: Wed, 25 Nov 2026 14:26:19 +0100 Subject: [PATCH 2/2] perf(tokenizer): scan a word once and shorten the common token paths Tokenizing a short statement cost about 200 instructions per token, most of it per-token overhead rather than per-byte work. What the tokenizer and the token-level digest produce is unchanged. Tokenizer - A word (identifier or keyword) is scanned once. A 256-entry table classifies each byte and gives its lower-case fold, and the keyword hash is computed during that scan; the old code walked the word to find its end and walked it again to hash it. lookup_hashed() takes the hash; hash_keyword() and lookup() are unchanged for other callers. - A word longer than the longest keyword, or containing a '$', is not looked up: it cannot be a keyword. - A word token is built by make_word_token(), which skips the bookkeeping make_token() does for errors, parentheses, end of input and user variables (none applies to a word) and keeps the MySQL hint state. - scan_token() steps over a single space, and enters skip_whitespace_and_comments() only when the next byte can start whitespace or a comment. - '(' ')' '[' ']' ',' ';' are returned before the literal, hint and operator checks: in both dialects they start nothing longer. - A PostgreSQL operator character followed by a non-operator character is returned as a one-character operator without the run scan. Digest - A keyword is upper-cased into the output with one capacity check (StringBuilder::extend()) instead of one per character. - The per-token emit step is expanded in the main loop of the token-level digest; the IN and VALUES branches keep calling emit_token(). Instructions per statement (g++ -O2, user mode, one million iterations, PostgreSQL dialect): statement tokenize token digest UPDATE t SET balance = balance - 1 WHERE id=N 3,313 -> 2,410 5,586 -> 4,221 SELECT a, b, c FROM t WHERE id = N 3,297 -> 2,364 5,526 -> 4,125 BEGIN 473 -> 345 741 -> 560 Verification - make test: 1,799 tests pass. - Differential check: for 2,000,000 pseudo-random SQL-like inputs (words in mixed case, every operator and punctuation character, quotes, comments, hints, dollar forms, numbers, stray and high bytes), in both dialects, the tokens (type, text and source span, offset, with peeks mixed in), the tokenizer flags, and the digest text, hash and trace are identical before and after this change. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01HsQTtbyp4v1ARw6Ym5CcEe --- include/sql_parser/digest.h | 16 +++- include/sql_parser/keyword_hash.h | 34 ++++++- include/sql_parser/keywords_mysql.h | 9 ++ include/sql_parser/keywords_pgsql.h | 9 ++ include/sql_parser/string_builder.h | 11 +++ include/sql_parser/tokenizer.h | 143 +++++++++++++++++++++------- 6 files changed, 183 insertions(+), 39 deletions(-) diff --git a/include/sql_parser/digest.h b/include/sql_parser/digest.h index 40245d7..0f0d262 100644 --- a/include/sql_parser/digest.h +++ b/include/sql_parser/digest.h @@ -120,8 +120,10 @@ class Digest { // Append token text uppercased to StringBuilder static void append_upper(StringBuilder& sb, const char* ptr, uint32_t len) { + char* out = sb.extend(len); + if (!out) return; for (uint32_t i = 0; i < len; ++i) { - sb.append_char(to_upper(ptr[i])); + out[i] = to_upper(ptr[i]); } } @@ -157,6 +159,16 @@ class Digest { // Emit a single token to the string builder, uppercasing keywords, replacing literals with ? void emit_token(StringBuilder& sb, const Token& t, TokenType prev) { + emit_token_inline(sb, t, prev); + } + + // The body of emit_token(), expanded in place where the caller is the + // per-token loop of an ordinary statement: there the call and passing the + // token through memory cost more than the work itself. +#if defined(__GNUC__) || defined(__clang__) + __attribute__((always_inline)) +#endif + inline void emit_token_inline(StringBuilder& sb, const Token& t, TokenType prev) { bool quoted_user_after_account = t.type == TokenType::TK_USER_VARIABLE && t.source.len >= 2 && (t.source.ptr[1] == '\'' || t.source.ptr[1] == '"' || t.source.ptr[1] == '`') && @@ -343,7 +355,7 @@ class Digest { // Check if we've reached the end (can happen after VALUES/IN lookahead) if (t.type == TokenType::TK_EOF || t.type == TokenType::TK_SEMICOLON) break; - emit_token(sb, t, prev); + emit_token_inline(sb, t, prev); prev = t.type; // For literal tokens, record as TK_QUESTION since we emitted ? if (is_literal_token(t.type)) prev = TokenType::TK_QUESTION; diff --git a/include/sql_parser/keyword_hash.h b/include/sql_parser/keyword_hash.h index 0372ae3..7aa67b9 100644 --- a/include/sql_parser/keyword_hash.h +++ b/include/sql_parser/keyword_hash.h @@ -22,6 +22,17 @@ inline uint32_t hash_keyword(const char* text, uint32_t len) { return h; } +// hash_keyword() one byte at a time, for a scanner that already walks the +// text: hash_keyword(text, len) equals folding hash_keyword_step() over the +// bytes of text starting from HASH_SEED. +static constexpr uint32_t HASH_SEED = 0x811c9dc5u; +inline uint32_t hash_keyword_step(uint32_t h, uint8_t c) { + if (c >= 'A' && c <= 'Z') c += 32; + h ^= c; + h *= 0x01000193u; + return h; +} + // Hash table entry struct HashEntry { const char* text; // uppercase keyword text (nullptr = empty slot) @@ -67,10 +78,10 @@ inline void build_table(const KeywordEntry (&keywords)[N], HashEntry (&table)[TA } } -// Lookup a keyword in a pre-built hash table. -inline TokenType lookup_in_table(const HashEntry (&table)[TABLE_SIZE], - const char* text, uint32_t len) { - uint32_t idx = hash_keyword(text, len) & TABLE_MASK; +// Lookup a keyword in a pre-built hash table, given hash_keyword(text, len). +inline TokenType lookup_in_table_hashed(const HashEntry (&table)[TABLE_SIZE], + const char* text, uint32_t len, uint32_t hash) { + uint32_t idx = hash & TABLE_MASK; for (uint32_t probe = 0; probe <= MAX_PROBE; ++probe) { const HashEntry& e = table[idx]; if (e.text == nullptr) return TokenType::TK_IDENTIFIER; @@ -80,6 +91,21 @@ inline TokenType lookup_in_table(const HashEntry (&table)[TABLE_SIZE], return TokenType::TK_IDENTIFIER; } +// Lookup a keyword in a pre-built hash table. +inline TokenType lookup_in_table(const HashEntry (&table)[TABLE_SIZE], + const char* text, uint32_t len) { + return lookup_in_table_hashed(table, text, len, hash_keyword(text, len)); +} + +// Length of the longest keyword of an array: a longer word is not a keyword. +template +constexpr uint32_t max_keyword_length(const KeywordEntry (&keywords)[N]) { + uint32_t longest = 0; + for (size_t k = 0; k < N; ++k) + if (keywords[k].len > longest) longest = keywords[k].len; + return longest; +} + } // namespace keyword_hash } // namespace sql_parser diff --git a/include/sql_parser/keywords_mysql.h b/include/sql_parser/keywords_mysql.h index a9c700b..a785bcc 100644 --- a/include/sql_parser/keywords_mysql.h +++ b/include/sql_parser/keywords_mysql.h @@ -198,6 +198,15 @@ inline TokenType lookup(const char* text, uint32_t len) { return keyword_hash::lookup_in_table(HASH_TABLE, text, len); } +inline constexpr uint32_t MAX_KEYWORD_LENGTH = keyword_hash::max_keyword_length(KEYWORDS); + +// lookup() for a caller that computed keyword_hash::hash_keyword(text, len) +// while scanning the word. +inline TokenType lookup_hashed(const char* text, uint32_t len, uint32_t hash) { + if (len > MAX_KEYWORD_LENGTH) return TokenType::TK_IDENTIFIER; + return keyword_hash::lookup_in_table_hashed(HASH_TABLE, text, len, hash); +} + } // namespace mysql_keywords } // namespace sql_parser diff --git a/include/sql_parser/keywords_pgsql.h b/include/sql_parser/keywords_pgsql.h index 5e1bf40..40e75dd 100644 --- a/include/sql_parser/keywords_pgsql.h +++ b/include/sql_parser/keywords_pgsql.h @@ -162,6 +162,15 @@ inline TokenType lookup(const char* text, uint32_t len) { return keyword_hash::lookup_in_table(HASH_TABLE, text, len); } +inline constexpr uint32_t MAX_KEYWORD_LENGTH = keyword_hash::max_keyword_length(KEYWORDS); + +// lookup() for a caller that computed keyword_hash::hash_keyword(text, len) +// while scanning the word. +inline TokenType lookup_hashed(const char* text, uint32_t len, uint32_t hash) { + if (len > MAX_KEYWORD_LENGTH) return TokenType::TK_IDENTIFIER; + return keyword_hash::lookup_in_table_hashed(HASH_TABLE, text, len, hash); +} + } // namespace pgsql_keywords } // namespace sql_parser diff --git a/include/sql_parser/string_builder.h b/include/sql_parser/string_builder.h index be4311c..76b64dc 100644 --- a/include/sql_parser/string_builder.h +++ b/include/sql_parser/string_builder.h @@ -25,6 +25,17 @@ class StringBuilder { } } + // Room for n more bytes, already counted in the length, for a caller that + // writes them itself. Null when the arena is exhausted, as append() then + // appends nothing. + char* extend(size_t n) { + ensure_capacity(n); + if (!buf_) return nullptr; + char* at = buf_ + len_; + len_ += n; + return at; + } + void append(StringRef ref) { if (ref.ptr && ref.len > 0) { append(ref.ptr, ref.len); diff --git a/include/sql_parser/tokenizer.h b/include/sql_parser/tokenizer.h index a3b356f..180829d 100644 --- a/include/sql_parser/tokenizer.h +++ b/include/sql_parser/tokenizer.h @@ -244,36 +244,78 @@ class Tokenizer { static_cast(source_start - start_)}; } + // make_token() for an identifier or keyword: none of the bookkeeping for + // errors, parentheses, end of input or user variables applies to a word. + Token make_word_token(TokenType type, const char* start, uint32_t len) { + if constexpr (D == Dialect::MySQL) { + hint_allowed_ = !after_dot_ && (type == TokenType::TK_SELECT || type == TokenType::TK_INSERT || + type == TokenType::TK_UPDATE || type == TokenType::TK_DELETE || type == TokenType::TK_REPLACE); + after_dot_ = false; + } + return Token{type, StringRef{start, len}, StringRef{start, len}, + static_cast(start - start_)}; + } + + // word_char_fold()[c] is c folded to lower case when c is an ASCII word + // character ([A-Za-z0-9_]) and 0 otherwise. One load classifies the byte + // and gives what the keyword hash consumes for it. + static const uint8_t* word_char_fold() { + struct Table { + uint8_t fold[256]; + constexpr Table() : fold() { + for (int c = 0; c < 256; ++c) { + if (c >= 'A' && c <= 'Z') fold[c] = static_cast(c + 32); + else if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_') + fold[c] = static_cast(c); + else fold[c] = 0; + } + } + }; + static constexpr Table table{}; + return table.fold; + } + Token scan_identifier_or_keyword() { - const char* start = cursor_; - while (cursor_ < end_) { - char c = *cursor_; - bool is_cont = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || - (c >= '0' && c <= '9') || c == '_'; + const char* const start = cursor_; + const char* const end = end_; + const uint8_t* const fold = word_char_fold(); + const char* p = start; + // The keyword hash is computed while the word is scanned. A word + // with a `$` is not a keyword. + uint32_t hash = keyword_hash::HASH_SEED; + bool keyword_candidate = true; + while (p < end) { + const auto c = static_cast(*p); + if (const uint8_t folded = fold[c]) { + hash = (hash ^ folded) * 0x01000193u; + ++p; + continue; + } // PostgreSQL allows `$` as an identifier continuation char (but // not as the first char, which is enforced because $ at start // is handled by the $$ / $N branches in next_token_impl()). // e.g. `SET search_path = schema$1` — `schema$1` is a single // identifier, not `schema` followed by the placeholder `$1`. - if (!is_cont && D == Dialect::PostgreSQL && c == '$' && cursor_ > start) { - is_cont = true; - } - if (is_cont) { - ++cursor_; - } else { - break; + if (D == Dialect::PostgreSQL && c == '$' && p > start) { + ++p; + keyword_candidate = false; + continue; } + break; } - uint32_t len = static_cast(cursor_ - start); + cursor_ = p; + const uint32_t len = static_cast(p - start); // Keyword lookup - TokenType kw; - if constexpr (D == Dialect::MySQL) { - kw = mysql_keywords::lookup(start, len); - } else { - kw = pgsql_keywords::lookup(start, len); + TokenType kw = TokenType::TK_IDENTIFIER; + if (keyword_candidate) { + if constexpr (D == Dialect::MySQL) { + kw = mysql_keywords::lookup_hashed(start, len, hash); + } else { + kw = pgsql_keywords::lookup_hashed(start, len, hash); + } } - return make_token(kw, start, len); + return make_word_token(kw, start, len); } Token scan_number() { @@ -538,6 +580,22 @@ class Tokenizer { } } + // Token type of a one-character PostgreSQL operator. + static TokenType pg_single_operator(char c) { + switch (c) { + case '+': return TokenType::TK_PLUS; + case '-': return TokenType::TK_MINUS; + case '*': return TokenType::TK_ASTERISK; + case '/': return TokenType::TK_SLASH; + case '%': return TokenType::TK_PERCENT; + case '^': return TokenType::TK_CARET; + case '=': return TokenType::TK_EQUAL; + case '<': return TokenType::TK_LESS; + case '>': return TokenType::TK_GREATER; + default: return TokenType::TK_PG_OPERATOR; + } + } + Token scan_pg_operator() { const char* start = cursor_; while (cursor_ < end_ && pg_operator_char(*cursor_)) { @@ -558,18 +616,7 @@ class Tokenizer { TokenType type = TokenType::TK_PG_OPERATOR; if (len >= 64) type = TokenType::TK_ERROR; else if (len == 1) { - switch (*start) { - case '+': type = TokenType::TK_PLUS; break; - case '-': type = TokenType::TK_MINUS; break; - case '*': type = TokenType::TK_ASTERISK; break; - case '/': type = TokenType::TK_SLASH; break; - case '%': type = TokenType::TK_PERCENT; break; - case '^': type = TokenType::TK_CARET; break; - case '=': type = TokenType::TK_EQUAL; break; - case '<': type = TokenType::TK_LESS; break; - case '>': type = TokenType::TK_GREATER; break; - default: break; - } + type = pg_single_operator(*start); } else if (len == 2) { if (start[0] == '<' && start[1] == '=') type = TokenType::TK_LESS_EQUAL; else if (start[0] == '>' && start[1] == '=') type = TokenType::TK_GREATER_EQUAL; @@ -581,7 +628,15 @@ class Tokenizer { } Token scan_token() { - skip_whitespace_and_comments(); + // The usual separator is one space. Beyond it, whitespace is at most + // ' ' and a comment starts with '-', '/' or '#': any other byte + // begins a token right here. + if (cursor_ < end_ && *cursor_ == ' ') ++cursor_; + if (cursor_ < end_) { + const auto first = static_cast(*cursor_); + if (first <= ' ' || first == '-' || first == '/' || first == '#') + skip_whitespace_and_comments(); + } if (cursor_ >= end_) { return make_token(TokenType::TK_EOF, cursor_, 0); @@ -589,6 +644,18 @@ class Tokenizer { char c = *cursor_; + // Punctuation that is a token by itself in both dialects: it starts + // no literal, comment, hint or longer operator. + switch (c) { + case '(': { const char* s = cursor_++; return make_token(TokenType::TK_LPAREN, s, 1); } + case ')': { const char* s = cursor_++; return make_token(TokenType::TK_RPAREN, s, 1); } + case '[': { const char* s = cursor_++; return make_token(TokenType::TK_LBRACKET, s, 1); } + case ']': { const char* s = cursor_++; return make_token(TokenType::TK_RBRACKET, s, 1); } + case ',': { const char* s = cursor_++; return make_token(TokenType::TK_COMMA, s, 1); } + case ';': { const char* s = cursor_++; return make_token(TokenType::TK_SEMICOLON, s, 1); } + default: break; + } + if constexpr (D == Dialect::MySQL) { if (hint_allowed_ && c == '/' && peek_char(1) == '*' && peek_char(2) == '+') { const char* begin = cursor_; @@ -654,7 +721,17 @@ class Tokenizer { } if constexpr (D == Dialect::PostgreSQL) { - if (pg_operator_char(c)) return scan_pg_operator(); + if (pg_operator_char(c)) { + // An operator character followed by something else is a + // one-character operator: no run to scan, and no comment can + // start here (those were skipped above). + if (cursor_ + 1 >= end_ || !pg_operator_char(cursor_[1])) { + const char* s = cursor_; + ++cursor_; + return make_token(pg_single_operator(c), s, 1); + } + return scan_pg_operator(); + } } // @ and @@