diff --git a/lexer/numeric_literal.cpp b/lexer/numeric_literal.cpp index 242fb38d9c84..9c79e682f3b0 100644 --- a/lexer/numeric_literal.cpp +++ b/lexer/numeric_literal.cpp @@ -145,6 +145,74 @@ auto LexedNumericLiteral::Lex(llvm::StringRef source_text) return result; } +// Parser for numeric literal tokens. +// +// Responsible for checking that a numeric literal is valid and meaningful and +// either diagnosing or extracting its meaning. +class LexedNumericLiteral::Parser { + public: + Parser(DiagnosticEmitter& emitter, LexedNumericLiteral literal); + + auto IsInteger() -> bool { + return literal.radix_point == static_cast(literal.text.size()); + } + + // Check that the numeric literal token is syntactically valid and + // meaningful, and diagnose if not. Returns `true` if the token was + // sufficiently valid that we could determine its meaning. If `false` is + // returned, a diagnostic has already been issued. + auto Check() -> bool; + + // Get the radix of this token. One of 2, 10, or 16. + auto GetRadix() -> int { return radix; } + + // Get the mantissa of this token's value. + auto GetMantissa() -> llvm::APInt; + + // Get the exponent of this token's value. This is always zero for an integer + // literal. + auto GetExponent() -> llvm::APInt; + + private: + struct CheckDigitSequenceResult { + bool ok; + bool has_digit_separators = false; + }; + + auto CheckDigitSequence(llvm::StringRef text, int radix, + bool allow_digit_separators = true) + -> CheckDigitSequenceResult; + auto CheckDigitSeparatorPlacement(llvm::StringRef text, int radix, + int num_digit_separators) -> void; + auto CheckLeadingZero() -> bool; + auto CheckIntPart() -> bool; + auto CheckFractionalPart() -> bool; + auto CheckExponentPart() -> bool; + + private: + DiagnosticEmitter& emitter; + LexedNumericLiteral literal; + + // The radix of the literal: 2, 10, or 16, for a prefix of '0b', no prefix, + // or '0x', respectively. + int radix = 10; + + // The various components of a numeric literal: + // + // [radix] int_part [. fract_part [[ep] [+-] exponent_part]] + llvm::StringRef int_part; + llvm::StringRef fract_part; + llvm::StringRef exponent_part; + + // Do we need to remove any special characters (digit separator or radix + // point) before interpreting the mantissa or exponent as an integer? + bool mantissa_needs_cleaning = false; + bool exponent_needs_cleaning = false; + + // True if we found a `-` before `exponent_part`. + bool exponent_is_negative = false; +}; + LexedNumericLiteral::Parser::Parser(DiagnosticEmitter& emitter, LexedNumericLiteral literal) : emitter(emitter), literal(literal) { @@ -396,4 +464,22 @@ auto LexedNumericLiteral::Parser::CheckExponentPart() -> bool { return exponent_result.ok; } +// Parse the token and compute its value. +auto LexedNumericLiteral::ComputeValue( + DiagnosticEmitter& emitter) const -> Value { + Parser parser(emitter, *this); + + if (!parser.Check()) { + return UnrecoverableError(); + } + + if (parser.IsInteger()) { + return IntegerValue{.value = parser.GetMantissa()}; + } + + return RealValue{.radix = (parser.GetRadix() == 10 ? 10 : 2), + .mantissa = parser.GetMantissa(), + .exponent = parser.GetExponent()}; +} + } // namespace Carbon diff --git a/lexer/numeric_literal.h b/lexer/numeric_literal.h index 4da99057f849..52faea635059 100644 --- a/lexer/numeric_literal.h +++ b/lexer/numeric_literal.h @@ -6,6 +6,7 @@ #define LEXER_NUMERIC_LITERAL_H_ #include +#include #include "diagnostics/diagnostic_emitter.h" #include "llvm/ADT/APInt.h" @@ -26,11 +27,35 @@ class LexedNumericLiteral { static auto Lex(llvm::StringRef source_text) -> llvm::Optional; - class Parser; + // Value of an integer literal. + struct IntegerValue { + // An unsigned literal value. + llvm::APInt value; + }; + + // Value of a real literal. + struct RealValue { + // The radix of the exponent, either 2 or 10. + int 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; + + // Compute the value of the token, if possible. Emit diagnostics to the given + // emitter if the token is not valid. + auto ComputeValue(DiagnosticEmitter& emitter) const -> Value; private: LexedNumericLiteral() {} + class Parser; + // The text of the token. llvm::StringRef text; @@ -45,74 +70,6 @@ class LexedNumericLiteral { int exponent; }; -// Parser for numeric literal tokens. -// -// Responsible for checking that a numeric literal is valid and meaningful and -// either diagnosing or extracting its meaning. -class LexedNumericLiteral::Parser { - public: - Parser(DiagnosticEmitter& emitter, LexedNumericLiteral literal); - - auto IsInteger() -> bool { - return literal.radix_point == static_cast(literal.text.size()); - } - - // Check that the numeric literal token is syntactically valid and - // meaningful, and diagnose if not. Returns `true` if the token was - // sufficiently valid that we could determine its meaning. If `false` is - // returned, a diagnostic has already been issued. - auto Check() -> bool; - - // Get the radix of this token. One of 2, 10, or 16. - auto GetRadix() -> int { return radix; } - - // Get the mantissa of this token's value. - auto GetMantissa() -> llvm::APInt; - - // Get the exponent of this token's value. This is always zero for an integer - // literal. - auto GetExponent() -> llvm::APInt; - - private: - struct CheckDigitSequenceResult { - bool ok; - bool has_digit_separators = false; - }; - - auto CheckDigitSequence(llvm::StringRef text, int radix, - bool allow_digit_separators = true) - -> CheckDigitSequenceResult; - auto CheckDigitSeparatorPlacement(llvm::StringRef text, int radix, - int num_digit_separators) -> void; - auto CheckLeadingZero() -> bool; - auto CheckIntPart() -> bool; - auto CheckFractionalPart() -> bool; - auto CheckExponentPart() -> bool; - - private: - DiagnosticEmitter& emitter; - LexedNumericLiteral literal; - - // The radix of the literal: 2, 10, or 16, for a prefix of '0b', no prefix, - // or '0x', respectively. - int radix = 10; - - // The various components of a numeric literal: - // - // [radix] int_part [. fract_part [[ep] [+-] exponent_part]] - llvm::StringRef int_part; - llvm::StringRef fract_part; - llvm::StringRef exponent_part; - - // Do we need to remove any special characters (digit separator or radix - // point) before interpreting the mantissa or exponent as an integer? - bool mantissa_needs_cleaning = false; - bool exponent_needs_cleaning = false; - - // True if we found a `-` before `exponent_part`. - bool exponent_is_negative = false; -}; - } // namespace Carbon #endif // LEXER_NUMERIC_LITERAL_H_ diff --git a/lexer/numeric_literal_fuzzer.cpp b/lexer/numeric_literal_fuzzer.cpp index 4edfa02b6a36..680c0bc2237b 100644 --- a/lexer/numeric_literal_fuzzer.cpp +++ b/lexer/numeric_literal_fuzzer.cpp @@ -22,22 +22,9 @@ extern "C" int LLVMFuzzerTestOneInput(const unsigned char* data, return 0; } - LexedNumericLiteral::Parser parser(NullDiagnosticEmitter(), - *token); - if (!parser.Check()) { - // Lexically OK, but token is meaningless. - return 0; - } - - // Ensure we can exercise the various queries on a valid literal. - volatile auto radix = parser.GetRadix(); - volatile auto mantissa = parser.GetMantissa(); - volatile auto exponent = parser.GetExponent(); - - (void)radix; - (void)mantissa; - (void)exponent; - + volatile auto value = + token->ComputeValue(NullDiagnosticEmitter()); + (void)value; return 0; } diff --git a/lexer/numeric_literal_test.cpp b/lexer/numeric_literal_test.cpp index 6e478f580944..357337aeb821 100644 --- a/lexer/numeric_literal_test.cpp +++ b/lexer/numeric_literal_test.cpp @@ -16,13 +16,16 @@ namespace Carbon { namespace { +using ::testing::_; +using ::testing::Field; +using ::testing::Matcher; +using ::testing::Property; +using ::testing::Truly; + struct NumericLiteralTest : ::testing::Test { NumericLiteralTest() : error_tracker(ConsoleDiagnosticConsumer()) {} ErrorTrackingDiagnosticConsumer error_tracker; - std::vector> - translators; - std::vector>> emitters; auto Lex(llvm::StringRef text) -> LexedNumericLiteral { llvm::Optional result = LexedNumericLiteral::Lex(text); @@ -31,15 +34,60 @@ struct NumericLiteralTest : ::testing::Test { return *result; } - auto Parse(llvm::StringRef text) -> LexedNumericLiteral::Parser { - translators.push_back( - std::make_unique(text)); - emitters.push_back(std::make_unique>( - *translators.back(), error_tracker)); - return LexedNumericLiteral::Parser(*emitters.back(), Lex(text)); + auto Parse(llvm::StringRef text) -> LexedNumericLiteral::Value { + Testing::SingleTokenDiagnosticTranslator translator(text); + DiagnosticEmitter emitter(translator, error_tracker); + return Lex(text).ComputeValue(emitter); } }; +// TODO: Use gmock's VariantWith once it exists. +template +auto VariantWith(M value_matcher) -> decltype(auto) { + return Truly([=](auto&& variant) { + T* value = std::get_if(&variant); + return value && ::testing::Matches(value_matcher)(*value); + }); +} + +// Matcher for signed llvm::APInt. +auto IsSignedInteger(int64_t value) -> Matcher { + return Property(&llvm::APInt::getSExtValue, value); +} + +// Matcher for unsigned llvm::APInt. +auto IsUnsignedInteger(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(&LexedNumericLiteral::IntegerValue::value, value_matcher)); +} + +struct RealMatcher { + Matcher radix = _; + Matcher mantissa = _; + Matcher exponent = _; +}; + +// Matcher for a real literal value. +auto HasRealValue(RealMatcher real_matcher) + -> Matcher { + return VariantWith(AllOf( + Field(&LexedNumericLiteral::RealValue::radix, real_matcher.radix), + Field(&LexedNumericLiteral::RealValue::mantissa, real_matcher.mantissa), + Field(&LexedNumericLiteral::RealValue::exponent, real_matcher.exponent))); +} + +// Matcher for an unrecoverable parse error. +auto HasUnrecoverableError() -> Matcher { + return VariantWith(_); +} + TEST_F(NumericLiteralTest, HandlesIntegerLiteral) { struct Testcase { llvm::StringLiteral token; @@ -54,13 +102,10 @@ TEST_F(NumericLiteralTest, HandlesIntegerLiteral) { }; for (Testcase testcase : testcases) { error_tracker.Reset(); - auto parser = Parse(testcase.token); - EXPECT_TRUE(parser.Check()) << testcase.token; + EXPECT_THAT(Parse(testcase.token), + HasIntValue(IsUnsignedInteger(testcase.value))) + << testcase.token; EXPECT_FALSE(error_tracker.SeenError()) << testcase.token; - EXPECT_EQ(parser.IsInteger(), true); - EXPECT_EQ(parser.GetMantissa().getZExtValue(), testcase.value); - EXPECT_EQ(parser.GetExponent().getSExtValue(), 0); - EXPECT_EQ(parser.GetRadix(), testcase.radix); } } @@ -81,8 +126,7 @@ TEST_F(NumericLiteralTest, ValidatesBaseSpecifier) { }; for (llvm::StringLiteral literal : valid) { error_tracker.Reset(); - auto parser = Parse(literal); - EXPECT_TRUE(parser.Check()) << literal; + EXPECT_THAT(Parse(literal), HasIntValue(_)) << literal; EXPECT_FALSE(error_tracker.SeenError()) << literal; } @@ -94,8 +138,7 @@ TEST_F(NumericLiteralTest, ValidatesBaseSpecifier) { }; for (llvm::StringLiteral literal : invalid) { error_tracker.Reset(); - auto parser = Parse(literal); - EXPECT_FALSE(parser.Check()) << literal; + EXPECT_THAT(Parse(literal), HasUnrecoverableError()) << literal; EXPECT_TRUE(error_tracker.SeenError()) << literal; } } @@ -118,8 +161,7 @@ TEST_F(NumericLiteralTest, ValidatesIntegerDigitSeparators) { }; for (llvm::StringLiteral literal : valid) { error_tracker.Reset(); - auto parser = Parse(literal); - EXPECT_TRUE(parser.Check()) << literal; + EXPECT_THAT(Parse(literal), HasIntValue(_)) << literal; EXPECT_FALSE(error_tracker.SeenError()) << literal; } @@ -146,8 +188,7 @@ TEST_F(NumericLiteralTest, ValidatesIntegerDigitSeparators) { }; for (llvm::StringLiteral literal : invalid) { error_tracker.Reset(); - auto parser = Parse(literal); - EXPECT_TRUE(parser.Check()) << literal; + EXPECT_THAT(Parse(literal), HasIntValue(_)) << literal; EXPECT_TRUE(error_tracker.SeenError()) << literal; } } @@ -200,25 +241,27 @@ TEST_F(NumericLiteralTest, HandlesRealLiteral) { }; for (Testcase testcase : testcases) { error_tracker.Reset(); - auto parser = Parse(testcase.token); - EXPECT_TRUE(parser.Check()) << testcase.token; + EXPECT_THAT(Parse(testcase.token), + HasRealValue({.radix = (testcase.radix == 10 ? 10 : 2), + .mantissa = IsUnsignedInteger(testcase.mantissa), + .exponent = IsSignedInteger(testcase.exponent)})) + << testcase.token; EXPECT_EQ(error_tracker.SeenError(), testcase.radix == 2) << testcase.token; - EXPECT_EQ(parser.IsInteger(), false); - EXPECT_EQ(parser.GetMantissa().getZExtValue(), testcase.mantissa); - EXPECT_EQ(parser.GetExponent().getSExtValue(), testcase.exponent); - EXPECT_EQ(parser.GetRadix(), testcase.radix); } } TEST_F(NumericLiteralTest, HandlesRealLiteralOverflow) { llvm::StringLiteral input = "0x1.000001p-9223372036854775800"; error_tracker.Reset(); - auto parser = Parse(input); - EXPECT_TRUE(parser.Check()); + EXPECT_THAT( + Parse(input), + HasRealValue({.radix = 2, + .mantissa = IsUnsignedInteger(0x1000001), + .exponent = Truly([](llvm::APInt exponent) { + return (exponent + 9223372036854775800).getSExtValue() == + -24; + })})); EXPECT_FALSE(error_tracker.SeenError()); - EXPECT_EQ(parser.GetMantissa(), 0x1000001); - EXPECT_EQ((parser.GetExponent() + 9223372036854775800).getSExtValue(), -24); - EXPECT_EQ(parser.GetRadix(), 16); } TEST_F(NumericLiteralTest, ValidatesRealLiterals) { @@ -229,8 +272,7 @@ TEST_F(NumericLiteralTest, ValidatesRealLiterals) { }; for (llvm::StringLiteral literal : invalid_digit_separators) { error_tracker.Reset(); - auto parser = Parse(literal); - EXPECT_TRUE(parser.Check()) << literal; + EXPECT_THAT(Parse(literal), HasRealValue({})) << literal; EXPECT_TRUE(error_tracker.SeenError()) << literal; } @@ -281,8 +323,7 @@ TEST_F(NumericLiteralTest, ValidatesRealLiterals) { }; for (llvm::StringLiteral literal : invalid) { error_tracker.Reset(); - auto parser = Parse(literal); - EXPECT_FALSE(parser.Check()) << literal; + EXPECT_THAT(Parse(literal), HasUnrecoverableError()) << literal; EXPECT_TRUE(error_tracker.SeenError()) << literal; } } diff --git a/lexer/tokenized_buffer.cpp b/lexer/tokenized_buffer.cpp index 01faf158a02a..93154ad735a8 100644 --- a/lexer/tokenized_buffer.cpp +++ b/lexer/tokenized_buffer.cpp @@ -56,6 +56,28 @@ struct UnrecognizedCharacters : SimpleDiagnostic { "Encountered unrecognized characters while parsing."; }; +// TODO: Move Overload and VariantMatch somewhere more central. + +// Form an overload set from a list of functions. For example: +// +// ``` +// auto overloaded = Overload{[] (int) {}, [] (float) {}}; +// ``` +template +struct Overload : Fs... { + using Fs::operator()...; +}; +template +Overload(Fs...) -> Overload; + +// Pattern-match against the type of the value stored in the variant `V`. Each +// element of `fs` should be a function that takes one or more of the variant +// values in `V`. +template +auto VariantMatch(V&& v, Fs&&... fs) -> decltype(auto) { + return std::visit(Overload{std::forward(fs)...}, std::forward(v)); +} + // Implementation of the lexer logic itself. // // The design is that lexing can loop over the source buffer, consuming it into @@ -203,36 +225,38 @@ class TokenizedBuffer::Lexer { set_indent = true; } - LexedNumericLiteral::Parser literal_parser(emitter, *literal); - - if (!literal_parser.Check()) { - auto token = buffer.AddToken({ - .kind = TokenKind::Error(), - .token_line = current_line, - .column = int_column, - .error_length = token_size, - }); - return token; - } - - if (literal_parser.IsInteger()) { - auto token = buffer.AddToken({.kind = TokenKind::IntegerLiteral(), - .token_line = current_line, - .column = int_column}); - buffer.GetTokenInfo(token).literal_index = - buffer.literal_int_storage.size(); - buffer.literal_int_storage.push_back(literal_parser.GetMantissa()); - return token; - } else { - auto token = buffer.AddToken({.kind = TokenKind::RealLiteral(), - .token_line = current_line, - .column = int_column}); - buffer.GetTokenInfo(token).literal_index = - buffer.literal_int_storage.size(); - buffer.literal_int_storage.push_back(literal_parser.GetMantissa()); - buffer.literal_int_storage.push_back(literal_parser.GetExponent()); - return token; - } + return VariantMatch( + literal->ComputeValue(emitter), + [&](LexedNumericLiteral::IntegerValue&& value) { + auto token = buffer.AddToken({.kind = TokenKind::IntegerLiteral(), + .token_line = current_line, + .column = int_column}); + buffer.GetTokenInfo(token).literal_index = + buffer.literal_int_storage.size(); + buffer.literal_int_storage.push_back(std::move(value.value)); + return token; + }, + [&](LexedNumericLiteral::RealValue&& value) { + auto token = buffer.AddToken({.kind = TokenKind::RealLiteral(), + .token_line = current_line, + .column = int_column}); + buffer.GetTokenInfo(token).literal_index = + buffer.literal_int_storage.size(); + buffer.literal_int_storage.push_back(std::move(value.mantissa)); + buffer.literal_int_storage.push_back(std::move(value.exponent)); + assert(buffer.GetRealLiteral(token).IsDecimal() == + (value.radix == 10)); + return token; + }, + [&](LexedNumericLiteral::UnrecoverableError) { + auto token = buffer.AddToken({ + .kind = TokenKind::Error(), + .token_line = current_line, + .column = int_column, + .error_length = token_size, + }); + return token; + }); } auto LexStringLiteral(llvm::StringRef& source_text) -> LexResult {