diff --git a/toolchain/lex/BUILD b/toolchain/lex/BUILD index 82285590964c..ce1b8244c8ab 100644 --- a/toolchain/lex/BUILD +++ b/toolchain/lex/BUILD @@ -77,6 +77,8 @@ cc_library( ":source_loc", "//common:check", "//toolchain/base:int", + "//toolchain/base:shared_value_stores", + "//toolchain/base:value_ids", "//toolchain/diagnostics:emitter", "//toolchain/diagnostics:format_providers", "@llvm-project//llvm:Support", @@ -89,8 +91,8 @@ cc_binary( srcs = ["numeric_literal_benchmark.cpp"], deps = [ ":numeric_literal", - "//common:check", "//testing/base:benchmark_main", + "//toolchain/base:shared_value_stores", "//toolchain/diagnostics:null_diagnostics", "@google_benchmark//:benchmark", ], @@ -103,9 +105,11 @@ cc_test( deps = [ ":numeric_literal", ":test_helpers", - "//common:check", "//common:ostream", "//testing/base:gtest_main", + "//toolchain/base:int", + "//toolchain/base:shared_value_stores", + "//toolchain/base:value_ids", "//toolchain/diagnostics:emitter", "//toolchain/diagnostics:renderer", "@googletest//:gtest", @@ -119,8 +123,10 @@ cc_fuzz_test( srcs = ["numeric_literal_fuzzer.cpp"], corpus = glob(["fuzzer_corpus/numeric_literal/*"]), deps = [ + ":character_set", ":numeric_literal", "//testing/fuzzing:libfuzzer_header", + "//toolchain/base:shared_value_stores", "//toolchain/diagnostics:emitter", "//toolchain/diagnostics:null_diagnostics", "@llvm-project//llvm:Support", diff --git a/toolchain/lex/lex.cpp b/toolchain/lex/lex.cpp index 418dc4041b65..eec701756ca7 100644 --- a/toolchain/lex/lex.cpp +++ b/toolchain/lex/lex.cpp @@ -199,7 +199,10 @@ class [[clang::internal_linkage]] Lexer { // intervening whitespace. auto CanFormRealLiteral() -> bool; - auto LexNumericLiteral(llvm::StringRef source_text, ssize_t& position) + // Always inlined into its dispatch function, so that the inline fast paths in + // `NumericLiteral` for single digits don't pay for a call. + [[clang::always_inline]] auto LexNumericLiteral(llvm::StringRef source_text, + ssize_t& position) -> LexResult; auto LexStringLiteral(llvm::StringRef source_text, ssize_t& position) @@ -1660,32 +1663,23 @@ auto Lexer::CanFormRealLiteral() -> bool { auto Lexer::LexNumericLiteral(llvm::StringRef source_text, ssize_t& position) -> LexResult { - std::optional literal = - NumericLiteral::Lex(source_text.substr(position), CanFormRealLiteral()); - if (!literal) { - return LexResult::NoMatch(); - } + // This is only dispatched at a decimal digit, as `NumericLiteral::Lex` + // requires. + NumericLiteral literal = NumericLiteral::Lex( + source_text.substr(position), [this] { return CanFormRealLiteral(); }); // Capture the position before we step past the token. int32_t byte_offset = position; - int token_size = literal->text().size(); + int token_size = literal.text().size(); position += token_size; - CARBON_KIND_SWITCH(literal->ComputeValue(emitter_)) { - case CARBON_KIND(NumericLiteral::IntValue&& value): { - return LexTokenWithPayload(TokenKind::IntLiteral, - buffer_.value_stores_->ints() - .AddUnsigned(std::move(value.value)) - .AsTokenPayload(), + CARBON_KIND_SWITCH(literal.AddValue(*buffer_.value_stores_, emitter_)) { + case CARBON_KIND(IntId id): { + return LexTokenWithPayload(TokenKind::IntLiteral, id.AsTokenPayload(), byte_offset); } - case CARBON_KIND(NumericLiteral::RealValue&& value): { - auto real_id = buffer_.value_stores_->reals().Add( - Real{.mantissa = value.mantissa, - .exponent = value.exponent, - .is_decimal = (value.radix == NumericLiteral::Radix::Decimal)}); - return LexTokenWithPayload(TokenKind::RealLiteral, real_id.index, - byte_offset); + case CARBON_KIND(RealId id): { + return LexTokenWithPayload(TokenKind::RealLiteral, id.index, byte_offset); } case CARBON_KIND(NumericLiteral::UnrecoverableError _): { return LexTokenWithPayload(TokenKind::Error, token_size, byte_offset); diff --git a/toolchain/lex/numeric_literal.cpp b/toolchain/lex/numeric_literal.cpp index 2ea9468fbb98..e8293c60001f 100644 --- a/toolchain/lex/numeric_literal.cpp +++ b/toolchain/lex/numeric_literal.cpp @@ -11,24 +11,52 @@ #include #include "common/check.h" +#include "llvm/ADT/APInt.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/FormatVariadicDetails.h" #include "toolchain/base/int.h" +#include "toolchain/base/shared_value_stores.h" +#include "toolchain/base/value_ids.h" #include "toolchain/diagnostics/format_providers.h" #include "toolchain/lex/character_set.h" #include "toolchain/lex/helpers.h" namespace Carbon::Lex { -auto NumericLiteral::Lex(llvm::StringRef source_text, - bool can_form_real_literal) - -> std::optional { - NumericLiteral result; +namespace { - if (source_text.empty() || !IsDecimalDigit(source_text.front())) { - return std::nullopt; - } +// The radix of a numeric literal. +enum class Radix : int8_t { + Binary = 2, + Octal = 8, + Decimal = 10, + Hexadecimal = 16 +}; +// The structure of a numeric literal, as found by `ScanNumericLiteral`. +struct NumericLiteralScan { + // The number of bytes in the literal. + int size; + + // The offset of the '.' character. Set to `size` if none is present. + int radix_point; + + // The offset of the alphabetical character introducing the exponent. In a + // valid literal, this will be an 'e' or a 'p', and may be followed by a '+' + // or a '-', but for error recovery, this may simply be the last lowercase + // letter in the invalid token. Always greater than or equal to radix_point. + // Set to `size` if none is present. + int exponent; +}; + +} // namespace + +// Scans a numeric literal from the start of `source_text`, which must start +// with a decimal digit. +static auto ScanNumericLiteral(llvm::StringRef source_text, + bool can_form_real_literal) + -> NumericLiteralScan { + NumericLiteralScan result = {}; bool seen_plus_minus = false; bool seen_radix_point = false; bool seen_potential_exponent = false; @@ -44,7 +72,7 @@ auto NumericLiteral::Lex(llvm::StringRef source_text, char c = source_text[i]; if (IsAlnum(c) || c == '_' || c == '$') { if (IsLower(c) && seen_radix_point && !seen_plus_minus) { - result.exponent_ = i; + result.exponent = i; seen_potential_exponent = true; } continue; @@ -54,7 +82,7 @@ auto NumericLiteral::Lex(llvm::StringRef source_text, // an alphanumeric character. if (c == '.' && can_form_real_literal && i + 1 != n && IsAlnum(source_text[i + 1]) && !seen_radix_point) { - result.radix_point_ = i; + result.radix_point = i; seen_radix_point = true; continue; } @@ -64,8 +92,7 @@ auto NumericLiteral::Lex(llvm::StringRef source_text, // followed by an alphanumeric character. This '+' or '-' cannot be an // operator because a literal cannot end in a lowercase letter. if ((c == '+' || c == '-') && seen_potential_exponent && - result.exponent_ == i - 1 && i + 1 != n && - IsAlnum(source_text[i + 1])) { + result.exponent == i - 1 && i + 1 != n && IsAlnum(source_text[i + 1])) { // This is not possible because we don't update result.exponent after we // see a '+' or '-'. CARBON_CHECK(!seen_plus_minus, "should only consume one + or -"); @@ -76,15 +103,34 @@ auto NumericLiteral::Lex(llvm::StringRef source_text, break; } - result.text_ = source_text.substr(0, i); + result.size = i; if (!seen_radix_point) { - result.radix_point_ = i; + result.radix_point = i; } if (!seen_potential_exponent) { - result.exponent_ = i; + result.exponent = i; + } + return result; +} + +auto NumericLiteral::LexOutOfLine(llvm::StringRef source_text, + bool can_form_real_literal) + -> NumericLiteral { + // Fast path for a run of decimal digits followed by the end of the text or + // by a byte that can't continue a numeric literal: those digits are the + // whole literal, without needing the general scan. + int size = source_text.size(); + int num_digits = 1; + while (num_digits < size && IsDecimalDigit(source_text[num_digits])) { + ++num_digits; + } + if (num_digits == size || !IsContinuationByte(source_text[num_digits])) + [[likely]] { + return NumericLiteral(source_text.take_front(num_digits)); } - return result; + return NumericLiteral(source_text.take_front( + ScanNumericLiteral(source_text, can_form_real_literal).size)); } // Parser for numeric literal tokens. @@ -96,7 +142,7 @@ class NumericLiteral::Parser { Parser(Diagnostics::Emitter& emitter, NumericLiteral literal); auto IsInt() -> bool { - return literal_.radix_point_ == static_cast(literal_.text_.size()); + return radix_point_ == static_cast(literal_.text_.size()); } // Check that the numeric literal token is syntactically valid and @@ -132,6 +178,11 @@ class NumericLiteral::Parser { Diagnostics::Emitter& emitter_; NumericLiteral literal_; + // The offsets of the radix point and exponent in the literal's text. See + // `NumericLiteralScan`. + int radix_point_; + int exponent_; + // The radix of the literal: 2, 10, or 16, for a prefix of '0b', no prefix, // or '0x', respectively. Radix radix_ = Radix::Decimal; @@ -155,7 +206,15 @@ class NumericLiteral::Parser { NumericLiteral::Parser::Parser(Diagnostics::Emitter& emitter, NumericLiteral literal) : emitter_(emitter), literal_(literal) { - int_part_ = literal.text_.substr(0, literal.radix_point_); + // Rescan the literal's text to find its structure. A `.` is only in the text + // when it can form a real literal, so allowing that finds the same structure. + NumericLiteralScan scan = + ScanNumericLiteral(literal.text_, /*can_form_real_literal=*/true); + CARBON_DCHECK(scan.size == static_cast(literal.text_.size())); + radix_point_ = scan.radix_point; + exponent_ = scan.exponent; + + int_part_ = literal.text_.substr(0, radix_point_); if (int_part_.consume_front("0x")) { radix_ = Radix::Hexadecimal; } else if (int_part_.consume_front("0b")) { @@ -164,10 +223,10 @@ NumericLiteral::Parser::Parser(Diagnostics::Emitter& emitter, radix_ = Radix::Octal; } - fract_part_ = literal.text_.substr( - literal.radix_point_ + 1, literal.exponent_ - literal.radix_point_ - 1); + fract_part_ = + literal.text_.substr(radix_point_ + 1, exponent_ - radix_point_ - 1); - exponent_part_ = literal.text_.substr(literal.exponent_ + 1); + exponent_part_ = literal.text_.substr(exponent_ + 1); if (!exponent_part_.consume_front("+")) { exponent_is_negative_ = exponent_part_.consume_front("-"); } @@ -195,20 +254,18 @@ static auto ParseBinary(llvm::StringRef digits, bool is_signed) -> llvm::APInt { } // Parses an octal or hexadecimal integer literal. -template - requires(Radix == NumericLiteral::Radix::Hexadecimal || - Radix == NumericLiteral::Radix::Octal) +template + requires(DigitRadix == Radix::Hexadecimal || DigitRadix == Radix::Octal) static auto ParseOctalOrHexadecimal(llvm::StringRef digits, bool is_signed) -> llvm::APInt { - constexpr int BitsPerDigit = - Radix == NumericLiteral::Radix::Hexadecimal ? 4 : 3; + constexpr int BitsPerDigit = DigitRadix == Radix::Hexadecimal ? 4 : 3; llvm::APInt value(std::max(IntStore::MinAPWidth, digits.size() * BitsPerDigit + is_signed), 0); int cursor = digits.size() * BitsPerDigit - 1; for (char c : digits) { uint8_t digit; - if constexpr (Radix == NumericLiteral::Radix::Octal) { + if constexpr (DigitRadix == Radix::Octal) { digit = c - '0'; } else { digit = c <= '9' ? (c - '0') : (c - 'A' + 10); @@ -236,6 +293,7 @@ static auto ParseOctalOrHexadecimal(llvm::StringRef digits, bool is_signed) // Parses a single chunk of up to 19 decimal digits. static auto ParseDecimalChunk(llvm::StringRef digits) -> uint64_t { + CARBON_DCHECK(digits.size() <= 19); uint64_t chunk_val = 0; for (char c : digits) { chunk_val = chunk_val * 10 + (c - '0'); @@ -293,8 +351,8 @@ static auto ParseDecimal(llvm::StringRef digits, bool is_signed) // parsing 123.456e7, we want to decompose it into an integer mantissa // (123456) and an exponent (7 - 3 = 4), and this routine is given the // "123.456" to parse as the mantissa. -static auto ParseInt(llvm::StringRef digits, NumericLiteral::Radix radix, - bool needs_cleaning, bool is_signed) -> llvm::APInt { +static auto ParseInt(llvm::StringRef digits, Radix radix, bool needs_cleaning, + bool is_signed) -> llvm::APInt { llvm::SmallString<32> cleaned; if (needs_cleaning) { cleaned.reserve(digits.size()); @@ -308,16 +366,14 @@ static auto ParseInt(llvm::StringRef digits, NumericLiteral::Radix radix, // We don't use LLVM's `getAsInteger` because it has poor performance. // Instead, we implement our own. switch (radix) { - case NumericLiteral::Radix::Binary: + case Radix::Binary: return ParseBinary(digits, is_signed); - case NumericLiteral::Radix::Octal: - return ParseOctalOrHexadecimal(digits, - is_signed); - case NumericLiteral::Radix::Decimal: + case Radix::Octal: + return ParseOctalOrHexadecimal(digits, is_signed); + case Radix::Decimal: return ParseDecimal(digits, is_signed); - case NumericLiteral::Radix::Hexadecimal: - return ParseOctalOrHexadecimal( - digits, is_signed); + case Radix::Hexadecimal: + return ParseOctalOrHexadecimal(digits, is_signed); } } @@ -453,8 +509,8 @@ auto NumericLiteral::Parser::CheckFractionalPart() -> bool { "{0:=2:binary|=8:octal} real number literals are not supported", Diagnostics::IntAsSelect); emitter_ - .Build(literal_.text_.begin() + literal_.radix_point_, - InvalidRealLiteralRadix, static_cast(radix_)) + .Build(literal_.text_.begin() + radix_point_, InvalidRealLiteralRadix, + static_cast(radix_)) .Attach(SourceLoc::Range(literal_.text_)) .Emit(); // Carry on and parse the real literal anyway. @@ -470,16 +526,16 @@ auto NumericLiteral::Parser::CheckFractionalPart() -> bool { // Check the exponent part (if any) is valid. auto NumericLiteral::Parser::CheckExponentPart() -> bool { - if (literal_.exponent_ == static_cast(literal_.text_.size())) { + if (exponent_ == static_cast(literal_.text_.size())) { return true; } char expected_exponent_kind = (radix_ == Radix::Decimal ? 'e' : 'p'); - if (literal_.text_[literal_.exponent_] != expected_exponent_kind) { + if (literal_.text_[exponent_] != expected_exponent_kind) { CARBON_DIAGNOSTIC(WrongRealLiteralExponent, Error, "expected '{0}' to introduce exponent", char); - emitter_.Emit(literal_.text_.begin() + literal_.exponent_, - WrongRealLiteralExponent, expected_exponent_kind); + emitter_.Emit(literal_.text_.begin() + exponent_, WrongRealLiteralExponent, + expected_exponent_kind); return false; } @@ -488,24 +544,53 @@ auto NumericLiteral::Parser::CheckExponentPart() -> bool { return exponent_result.ok; } -// Parse the token and compute its value. -auto NumericLiteral::ComputeValue( - Diagnostics::Emitter& emitter) const -> Value { - Parser parser(emitter, *this); +// Parses `text`, the text of a multi-character numeric literal, if it is a +// simple decimal integer literal: at most 18 decimal digits without a leading +// zero. Its value then always fits in an `int64_t`, as 10^18 - 1 < 2^63 - 1. +static auto TryParseSimpleDecimalInt(llvm::StringRef text) + -> std::optional { + CARBON_DCHECK(text.size() > 1); + constexpr size_t MaxSimpleDigits = 18; + if (text.size() > MaxSimpleDigits || text.front() == '0') [[unlikely]] { + return std::nullopt; + } + int64_t value = 0; + for (char c : text) { + if (!IsDecimalDigit(c)) [[unlikely]] { + return std::nullopt; + } + value = value * 10 + (c - '0'); + } + return value; +} + +// Parse the token, compute its value, and add it to the value stores. +auto NumericLiteral::AddValueOutOfLine(llvm::StringRef text, + SharedValueStores& value_stores, + Diagnostics::Emitter& emitter) + -> ValueId { + // Other decimal integers of up to 18 digits without a leading zero, which + // always fit in an `int64_t`, bypass the parser, and only build an `APInt` + // if they're too large to embed in their ID. + if (std::optional value = TryParseSimpleDecimalInt(text)) + [[likely]] { + return value_stores.ints().Add(*value); + } + + Parser parser(emitter, NumericLiteral(text)); if (!parser.Check()) { return UnrecoverableError(); } if (parser.IsInt()) { - return IntValue{.value = parser.GetMantissa()}; + return value_stores.ints().AddUnsigned(parser.GetMantissa()); } - return RealValue{ - .radix = (parser.GetRadix() == Radix::Decimal ? Radix::Decimal - : Radix::Binary), - .mantissa = parser.GetMantissa(), - .exponent = parser.GetExponent()}; + return value_stores.reals().Add( + Real{.mantissa = parser.GetMantissa(), + .exponent = parser.GetExponent(), + .is_decimal = (parser.GetRadix() == Radix::Decimal)}); } } // namespace Carbon::Lex diff --git a/toolchain/lex/numeric_literal.h b/toolchain/lex/numeric_literal.h index 19faf46a98d4..f6d8d9da7294 100644 --- a/toolchain/lex/numeric_literal.h +++ b/toolchain/lex/numeric_literal.h @@ -5,12 +5,18 @@ #ifndef CARBON_TOOLCHAIN_LEX_NUMERIC_LITERAL_H_ #define CARBON_TOOLCHAIN_LEX_NUMERIC_LITERAL_H_ -#include +#include +#include +#include #include -#include "llvm/ADT/APInt.h" +#include "common/check.h" #include "llvm/ADT/StringRef.h" +#include "toolchain/base/int.h" +#include "toolchain/base/shared_value_stores.h" +#include "toolchain/base/value_ids.h" #include "toolchain/diagnostics/emitter.h" +#include "toolchain/lex/character_set.h" #include "toolchain/lex/source_loc.h" namespace Carbon::Lex { @@ -18,42 +24,52 @@ namespace Carbon::Lex { // A numeric literal token that has been extracted from a source buffer. class NumericLiteral { public: - enum class Radix : int8_t { - Binary = 2, - Octal = 8, - Decimal = 10, - Hexadecimal = 16 - }; - - // Value of an integer literal. - struct IntValue { - // An unsigned literal value. - llvm::APInt value; - }; - - // Value of a real literal. - struct RealValue { - // The radix of the exponent, either Binary or Decimal. - Radix radix; - // The mantissa, represented as a variable-width unsigned integer. - llvm::APInt mantissa; - // The exponent, represented as a variable-width signed integer. - llvm::APInt exponent; - }; - struct UnrecoverableError {}; - using Value = std::variant; + // The ID of a numeric literal's value in the shared value stores. + using ValueId = std::variant; - // Extract a numeric literal from the given text, if it has a suitable form. + // Lexes the numeric literal at the start of `source_text`, which must start + // with a decimal digit. // // The supplied `source_text` must outlive the return value. - static auto Lex(llvm::StringRef source_text, bool can_form_real_literal) - -> std::optional; + // + // `can_form_real_literal` returns whether the literal can be a real literal, + // and is only called when that matters, so that callers don't pay to compute + // it in the common case. + // + // The most common numeric literal, a single digit, is lexed inline so that it + // doesn't pay for a call, and everything else out of line. + template + requires std::is_invocable_r_v + static auto Lex(llvm::StringRef source_text, + CanFormRealLiteralFn can_form_real_literal) + -> NumericLiteral { + CARBON_DCHECK(!source_text.empty() && IsDecimalDigit(source_text[0]), + "Numeric literal must start with a decimal digit"); + // A digit followed by the end of the text or by a byte that can't continue + // a numeric literal is a complete one, such as the `1` in `x + 1`. + if (source_text.size() == 1 || !IsContinuationByte(source_text[1])) + [[likely]] { + // Unlike `take_front(1)`, this doesn't clamp the size, so the compiler + // can see that it's exactly one. + return NumericLiteral(llvm::StringRef(source_text.begin(), 1)); + } + return LexOutOfLine(source_text, can_form_real_literal()); + } - // Compute the value of the token, if possible. Emit diagnostics to the given - // emitter if the token is not valid. - auto ComputeValue(Diagnostics::Emitter& emitter) const -> Value; + // Computes the value of the token, adds it to `value_stores`, and returns its + // ID. Emits diagnostics to the given emitter if the token is not valid. + // + // The most common numeric literal, a single digit, is handled inline so that + // it doesn't pay for a call, and everything else out of line. + auto AddValue(SharedValueStores& value_stores, + Diagnostics::Emitter& emitter) const -> ValueId { + if (text_.size() == 1) [[likely]] { + return value_stores.ints().Add(text_[0] - '0'); + } + return AddValueOutOfLine(text_, value_stores, emitter); + } // Get the text corresponding to this literal. auto text() const -> llvm::StringRef { return text_; } @@ -61,22 +77,54 @@ class NumericLiteral { private: class Parser; - NumericLiteral() = default; + // Constructs a literal with the given text, which must be non-empty. + explicit NumericLiteral(llvm::StringRef text) : text_(text) {} + + // The out-of-line parts of `Lex` and `AddValue`, which handle everything + // other than a single digit. These are static, with text passed by value, + // so that the inline paths' literals never need an address. + static auto LexOutOfLine(llvm::StringRef source_text, + bool can_form_real_literal) -> NumericLiteral; + static auto AddValueOutOfLine(llvm::StringRef text, + SharedValueStores& value_stores, + Diagnostics::Emitter& emitter) + -> ValueId; + + // Returns whether `c` can continue a numeric literal that starts with a + // sequence of decimal digits. If the byte after those digits can't, the + // digits are a complete decimal integer literal. + static auto IsContinuationByte(char c) -> bool { + return ContinuationByteTable[static_cast(c)]; + } + + // A table of the bytes that can continue a numeric literal after a sequence + // of decimal digits: those that `Lex` always consumes (`[0-9A-Za-z_$]`), and + // `.`, which can start the fractional part of a real literal. + static constexpr std::array ContinuationByteTable = [] { + std::array table = {}; + for (int c = '0'; c <= '9'; ++c) { + table[c] = true; + } + for (int c = 'a'; c <= 'z'; ++c) { + table[c] = true; + } + for (int c = 'A'; c <= 'Z'; ++c) { + table[c] = true; + } + table['_'] = true; + table['$'] = true; + table['.'] = true; + return table; + }(); // The text of the token. llvm::StringRef text_; - - // The offset of the '.'. Set to text.size() if none is present. - int radix_point_; - - // The offset of the alphabetical character introducing the exponent. In a - // valid literal, this will be an 'e' or a 'p', and may be followed by a '+' - // or a '-', but for error recovery, this may simply be the last lowercase - // letter in the invalid token. Always greater than or equal to radix_point. - // Set to text.size() if none is present. - int exponent_; }; +// Keep `NumericLiteral` within 16 bytes so that it can be passed and returned +// in registers. +static_assert(sizeof(NumericLiteral) <= 16); + } // namespace Carbon::Lex #endif // CARBON_TOOLCHAIN_LEX_NUMERIC_LITERAL_H_ diff --git a/toolchain/lex/numeric_literal_benchmark.cpp b/toolchain/lex/numeric_literal_benchmark.cpp index 66216e4407a7..cc1c8ea06f08 100644 --- a/toolchain/lex/numeric_literal_benchmark.cpp +++ b/toolchain/lex/numeric_literal_benchmark.cpp @@ -6,7 +6,7 @@ #include -#include "common/check.h" +#include "toolchain/base/shared_value_stores.h" #include "toolchain/diagnostics/null_diagnostics.h" #include "toolchain/lex/numeric_literal.h" @@ -32,91 +32,98 @@ static auto MakeIntString(llvm::StringLiteral prefix, int radix, int num_digits) static void BM_Lex_Float(benchmark::State& state) { for (auto _ : state) { - CARBON_CHECK(NumericLiteral::Lex("0.000001", true)); + benchmark::DoNotOptimize( + NumericLiteral::Lex("0.000001", [] { return true; })); } } static void BM_Lex_Int(benchmark::State& state) { for (auto _ : state) { - CARBON_CHECK(NumericLiteral::Lex("1_234_567_890", true)); + benchmark::DoNotOptimize( + NumericLiteral::Lex("1_234_567_890", [] { return true; })); } } static void BM_Lex_IntDecimalN(benchmark::State& state) { std::string s = MakeIntString("", 10, state.range(0)); for (auto _ : state) { - CARBON_CHECK(NumericLiteral::Lex(s, true)); + benchmark::DoNotOptimize(NumericLiteral::Lex(s, [] { return true; })); } } -static void BM_ComputeValue_Float(benchmark::State& state) { - auto val = NumericLiteral::Lex("0.000001", true); - CARBON_CHECK(val); +static void BM_AddValue_Float(benchmark::State& state) { + auto val = NumericLiteral::Lex("0.000001", [] { return true; }); auto& emitter = Diagnostics::NullEmitter(); - for (auto _ : state) { - val->ComputeValue(emitter); + // Real values aren't canonicalized, so each one grows the value store. Use a + // fresh store for each batch of values to bound its size. + constexpr int BatchSize = 1000; + while (state.KeepRunningBatch(BatchSize)) { + SharedValueStores value_stores; + for (int i = 0; i < BatchSize; ++i) { + benchmark::DoNotOptimize(val.AddValue(value_stores, emitter)); + } } } -static void BM_ComputeValue_Int(benchmark::State& state) { - auto val = NumericLiteral::Lex("1_234_567_890", true); +static void BM_AddValue_Int(benchmark::State& state) { + auto val = NumericLiteral::Lex("1_234_567_890", [] { return true; }); auto& emitter = Diagnostics::NullEmitter(); - CARBON_CHECK(val); + SharedValueStores value_stores; for (auto _ : state) { - val->ComputeValue(emitter); + benchmark::DoNotOptimize(val.AddValue(value_stores, emitter)); } } -static void BM_ComputeValue_IntDecimalN(benchmark::State& state) { +static void BM_AddValue_IntDecimalN(benchmark::State& state) { std::string s = MakeIntString("", 10, state.range(0)); - auto val = NumericLiteral::Lex(s, true); + auto val = NumericLiteral::Lex(s, [] { return true; }); auto& emitter = Diagnostics::NullEmitter(); - CARBON_CHECK(val); + SharedValueStores value_stores; for (auto _ : state) { - val->ComputeValue(emitter); + benchmark::DoNotOptimize(val.AddValue(value_stores, emitter)); } } -static void BM_ComputeValue_IntBinaryN(benchmark::State& state) { +static void BM_AddValue_IntBinaryN(benchmark::State& state) { std::string s = MakeIntString("0b", 2, state.range(0)); - auto val = NumericLiteral::Lex(s, true); + auto val = NumericLiteral::Lex(s, [] { return true; }); auto& emitter = Diagnostics::NullEmitter(); - CARBON_CHECK(val); + SharedValueStores value_stores; for (auto _ : state) { - val->ComputeValue(emitter); + benchmark::DoNotOptimize(val.AddValue(value_stores, emitter)); } } -static void BM_ComputeValue_IntOctalN(benchmark::State& state) { +static void BM_AddValue_IntOctalN(benchmark::State& state) { std::string s = MakeIntString("0o", 8, state.range(0)); - auto val = NumericLiteral::Lex(s, true); + auto val = NumericLiteral::Lex(s, [] { return true; }); auto& emitter = Diagnostics::NullEmitter(); - CARBON_CHECK(val); + SharedValueStores value_stores; for (auto _ : state) { - val->ComputeValue(emitter); + benchmark::DoNotOptimize(val.AddValue(value_stores, emitter)); } } -static void BM_ComputeValue_IntHexN(benchmark::State& state) { +static void BM_AddValue_IntHexN(benchmark::State& state) { // 0 is in the middle so that it isn't truncated in parse. std::string s = MakeIntString("0x", 16, state.range(0)); - auto val = NumericLiteral::Lex(s, true); + auto val = NumericLiteral::Lex(s, [] { return true; }); auto& emitter = Diagnostics::NullEmitter(); - CARBON_CHECK(val); + SharedValueStores value_stores; for (auto _ : state) { - val->ComputeValue(emitter); + benchmark::DoNotOptimize(val.AddValue(value_stores, emitter)); } } BENCHMARK(BM_Lex_Float); BENCHMARK(BM_Lex_Int); BENCHMARK(BM_Lex_IntDecimalN)->RangeMultiplier(10)->Range(1, 10000); -BENCHMARK(BM_ComputeValue_Float); -BENCHMARK(BM_ComputeValue_Int); -BENCHMARK(BM_ComputeValue_IntDecimalN)->RangeMultiplier(10)->Range(1, 10000); -BENCHMARK(BM_ComputeValue_IntBinaryN)->RangeMultiplier(10)->Range(1, 10000); -BENCHMARK(BM_ComputeValue_IntOctalN)->RangeMultiplier(10)->Range(1, 10000); -BENCHMARK(BM_ComputeValue_IntHexN)->RangeMultiplier(10)->Range(1, 10000); +BENCHMARK(BM_AddValue_Float); +BENCHMARK(BM_AddValue_Int); +BENCHMARK(BM_AddValue_IntDecimalN)->RangeMultiplier(10)->Range(1, 10000); +BENCHMARK(BM_AddValue_IntBinaryN)->RangeMultiplier(10)->Range(1, 10000); +BENCHMARK(BM_AddValue_IntOctalN)->RangeMultiplier(10)->Range(1, 10000); +BENCHMARK(BM_AddValue_IntHexN)->RangeMultiplier(10)->Range(1, 10000); } // namespace } // namespace Carbon::Lex diff --git a/toolchain/lex/numeric_literal_fuzzer.cpp b/toolchain/lex/numeric_literal_fuzzer.cpp index 5b25c30adf6f..74b9e54e5f5f 100644 --- a/toolchain/lex/numeric_literal_fuzzer.cpp +++ b/toolchain/lex/numeric_literal_fuzzer.cpp @@ -6,23 +6,25 @@ #include "llvm/ADT/StringRef.h" #include "testing/fuzzing/libfuzzer.h" +#include "toolchain/base/shared_value_stores.h" #include "toolchain/diagnostics/null_diagnostics.h" +#include "toolchain/lex/character_set.h" #include "toolchain/lex/numeric_literal.h" namespace Carbon::Testing { // NOLINTNEXTLINE: Match the documented fuzzer entry point declaration style. extern "C" int LLVMFuzzerTestOneInput(const unsigned char* data, size_t size) { - auto token = Lex::NumericLiteral::Lex( - llvm::StringRef(reinterpret_cast(data), size), true); - if (!token) { + llvm::StringRef text(reinterpret_cast(data), size); + if (text.empty() || !Lex::IsDecimalDigit(text.front())) { // Lexically not a numeric literal. return 0; } - volatile auto value = - token->ComputeValue(Diagnostics::NullEmitter()); - (void)value; + SharedValueStores value_stores; + Lex::NumericLiteral::Lex(text, [] { + return true; + }).AddValue(value_stores, Diagnostics::NullEmitter()); return 0; } diff --git a/toolchain/lex/numeric_literal_test.cpp b/toolchain/lex/numeric_literal_test.cpp index 92ecc9ef5989..267e5e04eadc 100644 --- a/toolchain/lex/numeric_literal_test.cpp +++ b/toolchain/lex/numeric_literal_test.cpp @@ -7,10 +7,11 @@ #include #include -#include #include -#include "common/check.h" +#include "toolchain/base/int.h" +#include "toolchain/base/shared_value_stores.h" +#include "toolchain/base/value_ids.h" #include "toolchain/diagnostics/emitter.h" #include "toolchain/lex/test_helpers.h" @@ -21,30 +22,56 @@ using ::testing::_; using ::testing::Field; using ::testing::Matcher; using ::testing::Property; +using ::testing::ResultOf; using ::testing::Truly; using ::testing::VariantWith; +struct RealMatcher { + Matcher is_decimal = _; + Matcher mantissa = _; + Matcher exponent = _; +}; + class NumericLiteralTest : public ::testing::Test { public: NumericLiteralTest() : error_tracker(Diagnostics::ConsoleConsumer()) {} auto Lex(llvm::StringRef text, bool can_form_real_literal) -> NumericLiteral { - std::optional result = - NumericLiteral::Lex(text, can_form_real_literal); - CARBON_CHECK(result); + NumericLiteral result = + NumericLiteral::Lex(text, [=] { return can_form_real_literal; }); if (can_form_real_literal) { - EXPECT_EQ(result->text(), text); + EXPECT_EQ(result.text(), text); } - return *result; + return result; } auto Parse(llvm::StringRef text, bool can_form_real_literal = true) - -> NumericLiteral::Value { + -> NumericLiteral::ValueId { Testing::SingleTokenDiagnosticEmitter emitter(&error_tracker, text); - return Lex(text, can_form_real_literal).ComputeValue(emitter); + return Lex(text, can_form_real_literal).AddValue(value_stores, emitter); + } + + // Matcher for an integer literal value. + template + auto HasIntValue(const ValueMatcher& value_matcher) + -> Matcher { + return VariantWith( + ResultOf([this](IntId id) { return value_stores.ints().Get(id); }, + value_matcher)); + } + + // Matcher for a real literal value. + auto HasRealValue(const RealMatcher& real_matcher) + -> Matcher { + return VariantWith( + ResultOf([this](RealId id) { return value_stores.reals().Get(id); }, + AllOf(Field(&Real::is_decimal, real_matcher.is_decimal), + Field(&Real::mantissa, real_matcher.mantissa), + Field(&Real::exponent, real_matcher.exponent)))); } Diagnostics::ErrorTrackingConsumer error_tracker; + SharedValueStores value_stores; }; // Matcher for signed llvm::APInt. @@ -57,31 +84,8 @@ auto IsUnsignedInt(uint64_t value) -> Matcher { return Property(&llvm::APInt::getZExtValue, value); } -// Matcher for an integer literal value. -template -auto HasIntValue(const ValueMatcher& value_matcher) - -> Matcher { - return VariantWith( - Field(&NumericLiteral::IntValue::value, value_matcher)); -} - -struct RealMatcher { - Matcher radix = _; - Matcher mantissa = _; - Matcher exponent = _; -}; - -// Matcher for a real literal value. -auto HasRealValue(const RealMatcher& real_matcher) - -> Matcher { - return VariantWith(AllOf( - Field(&NumericLiteral::RealValue::radix, real_matcher.radix), - Field(&NumericLiteral::RealValue::mantissa, real_matcher.mantissa), - Field(&NumericLiteral::RealValue::exponent, real_matcher.exponent))); -} - // Matcher for an unrecoverable parse error. -auto HasUnrecoverableError() -> Matcher { +auto HasUnrecoverableError() -> Matcher { return VariantWith(_); } @@ -301,7 +305,7 @@ TEST_F(NumericLiteralTest, HandlesRealLiteral) { for (Testcase testcase : testcases) { error_tracker.Reset(); EXPECT_THAT(Parse(testcase.token), - HasRealValue({.radix = (testcase.radix == 10 ? 10 : 2), + HasRealValue({.is_decimal = (testcase.radix == 10), .mantissa = IsUnsignedInt(testcase.mantissa), .exponent = IsSignedInt(testcase.exponent)})) << testcase.token; @@ -325,7 +329,7 @@ TEST_F(NumericLiteralTest, HandlesRealLiteralOverflow) { error_tracker.Reset(); EXPECT_THAT( Parse(input), - HasRealValue({.radix = 2, + HasRealValue({.is_decimal = false, .mantissa = IsUnsignedInt(0x1000001), .exponent = Truly([](llvm::APInt exponent) { return (exponent + 9223372036854775800).getSExtValue() == @@ -395,5 +399,46 @@ TEST_F(NumericLiteralTest, TooManyDigits) { EXPECT_TRUE(error_tracker.seen_error()); } +TEST_F(NumericLiteralTest, LexesDecimalDigits) { + // A run of decimal digits ends before a byte that can't continue it. + for (llvm::StringRef text : {"7)", "7 ", "42;"}) { + SCOPED_TRACE(text.str()); + EXPECT_EQ( + NumericLiteral::Lex(text, /*can_form_real_literal=*/[] { return true; }) + .text(), + text.drop_back()); + } + + // Anything that could continue the literal takes the general path, which + // consumes it. + for (llvm::StringRef text : {"1a", "12a", "1_000", "12$"}) { + SCOPED_TRACE(text.str()); + EXPECT_EQ(Lex(text, /*can_form_real_literal=*/true).text(), text); + } +} + +TEST_F(NumericLiteralTest, HandlesSimpleDecimalInts) { + // A single digit is handled inline, and other decimal integers of up to 18 + // digits without a leading zero bypass the parser. Longer ones take the + // general path. + struct Testcase { + llvm::StringLiteral token; + uint64_t value; + }; + Testcase testcases[] = { + {.token = "0", .value = 0}, + {.token = "7", .value = 7}, + {.token = "42", .value = 42}, + {.token = "999999999999999999", .value = 999'999'999'999'999'999}, + {.token = "9999999999999999999", .value = 9'999'999'999'999'999'999U}, + }; + for (Testcase testcase : testcases) { + EXPECT_THAT(Parse(testcase.token), + HasIntValue(IsUnsignedInt(testcase.value))) + << testcase.token; + } + EXPECT_FALSE(error_tracker.seen_error()); +} + } // namespace } // namespace Carbon::Lex diff --git a/toolchain/lex/tokenized_buffer.cpp b/toolchain/lex/tokenized_buffer.cpp index 6d9f4ee5e806..6bbb487b8293 100644 --- a/toolchain/lex/tokenized_buffer.cpp +++ b/toolchain/lex/tokenized_buffer.cpp @@ -78,11 +78,10 @@ auto TokenizedBuffer::GetTokenText(TokenIndex token) const -> llvm::StringRef { // separators the author included. if (token_info.kind() == TokenKind::IntLiteral || token_info.kind() == TokenKind::RealLiteral) { - std::optional relexed_token = - NumericLiteral::Lex(source_->text().substr(token_info.byte_offset()), - token_info.kind() == TokenKind::RealLiteral); - CARBON_CHECK(relexed_token, "Could not reform numeric literal token."); - return relexed_token->text(); + return NumericLiteral::Lex( + source_->text().substr(token_info.byte_offset()), + [&] { return token_info.kind() == TokenKind::RealLiteral; }) + .text(); } // Refer back to the source text to find the original spelling, including