numeric_literal.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "toolchain/lexer/numeric_literal.h"
  5. #include <bitset>
  6. #include "common/check.h"
  7. #include "llvm/ADT/StringExtras.h"
  8. #include "llvm/Support/FormatVariadic.h"
  9. #include "toolchain/lexer/character_set.h"
  10. #include "toolchain/lexer/lex_helpers.h"
  11. namespace Carbon {
  12. // Adapts radix for use with formatv.
  13. auto operator<<(llvm::raw_ostream& out, LexedNumericLiteral::Radix radix)
  14. -> llvm::raw_ostream& {
  15. switch (radix) {
  16. case LexedNumericLiteral::Radix::Binary:
  17. out << "binary";
  18. break;
  19. case LexedNumericLiteral::Radix::Decimal:
  20. out << "decimal";
  21. break;
  22. case LexedNumericLiteral::Radix::Hexadecimal:
  23. out << "hexadecimal";
  24. break;
  25. }
  26. return out;
  27. }
  28. namespace {
  29. struct EmptyDigitSequence : DiagnosticBase<EmptyDigitSequence> {
  30. static constexpr llvm::StringLiteral ShortName = "syntax-invalid-number";
  31. static constexpr llvm::StringLiteral Message =
  32. "Empty digit sequence in numeric literal.";
  33. };
  34. struct InvalidDigit : DiagnosticBase<InvalidDigit> {
  35. static constexpr llvm::StringLiteral ShortName = "syntax-invalid-number";
  36. auto Format() -> std::string {
  37. return llvm::formatv("Invalid digit '{0}' in {1} numeric literal.", digit,
  38. radix)
  39. .str();
  40. }
  41. char digit;
  42. LexedNumericLiteral::Radix radix;
  43. };
  44. struct InvalidDigitSeparator : DiagnosticBase<InvalidDigitSeparator> {
  45. static constexpr llvm::StringLiteral ShortName = "syntax-invalid-number";
  46. static constexpr llvm::StringLiteral Message =
  47. "Misplaced digit separator in numeric literal.";
  48. };
  49. struct IrregularDigitSeparators : DiagnosticBase<IrregularDigitSeparators> {
  50. static constexpr llvm::StringLiteral ShortName =
  51. "syntax-irregular-digit-separators";
  52. auto Format() -> std::string {
  53. CHECK((radix == LexedNumericLiteral::Radix::Decimal ||
  54. radix == LexedNumericLiteral::Radix::Hexadecimal))
  55. << "unexpected radix: " << radix;
  56. return llvm::formatv(
  57. "Digit separators in {0} number should appear every {1} "
  58. "characters from the right.",
  59. radix,
  60. (radix == LexedNumericLiteral::Radix::Decimal ? "3" : "4"))
  61. .str();
  62. }
  63. LexedNumericLiteral::Radix radix;
  64. };
  65. struct UnknownBaseSpecifier : DiagnosticBase<UnknownBaseSpecifier> {
  66. static constexpr llvm::StringLiteral ShortName = "syntax-invalid-number";
  67. static constexpr llvm::StringLiteral Message =
  68. "Unknown base specifier in numeric literal.";
  69. };
  70. struct BinaryRealLiteral : DiagnosticBase<BinaryRealLiteral> {
  71. static constexpr llvm::StringLiteral ShortName = "syntax-invalid-number";
  72. static constexpr llvm::StringLiteral Message =
  73. "Binary real number literals are not supported.";
  74. };
  75. struct WrongRealLiteralExponent : DiagnosticBase<WrongRealLiteralExponent> {
  76. static constexpr llvm::StringLiteral ShortName = "syntax-invalid-number";
  77. auto Format() -> std::string {
  78. return llvm::formatv("Expected '{0}' to introduce exponent.", expected)
  79. .str();
  80. }
  81. char expected;
  82. };
  83. } // namespace
  84. auto LexedNumericLiteral::Lex(llvm::StringRef source_text)
  85. -> llvm::Optional<LexedNumericLiteral> {
  86. LexedNumericLiteral result;
  87. if (source_text.empty() || !IsDecimalDigit(source_text.front())) {
  88. return llvm::None;
  89. }
  90. bool seen_plus_minus = false;
  91. bool seen_radix_point = false;
  92. bool seen_potential_exponent = false;
  93. // Greedily consume all following characters that might be part of a numeric
  94. // literal. This allows us to produce better diagnostics on invalid literals.
  95. //
  96. // TODO(zygoloid): Update lexical rules to specify that a numeric literal
  97. // cannot be immediately followed by an alphanumeric character.
  98. int i = 1, n = source_text.size();
  99. for (; i != n; ++i) {
  100. char c = source_text[i];
  101. if (IsAlnum(c) || c == '_') {
  102. if (IsLower(c) && seen_radix_point && !seen_plus_minus) {
  103. result.exponent_ = i;
  104. seen_potential_exponent = true;
  105. }
  106. continue;
  107. }
  108. // Exactly one `.` can be part of the literal, but only if it's followed by
  109. // an alphanumeric character.
  110. if (c == '.' && i + 1 != n && IsAlnum(source_text[i + 1]) &&
  111. !seen_radix_point) {
  112. result.radix_point_ = i;
  113. seen_radix_point = true;
  114. continue;
  115. }
  116. // A `+` or `-` continues the literal only if it's preceded by a lowercase
  117. // letter (which will be 'e' or 'p' or part of an invalid literal) and
  118. // followed by an alphanumeric character. This '+' or '-' cannot be an
  119. // operator because a literal cannot end in a lowercase letter.
  120. if ((c == '+' || c == '-') && seen_potential_exponent &&
  121. result.exponent_ == i - 1 && i + 1 != n &&
  122. IsAlnum(source_text[i + 1])) {
  123. // This is not possible because we don't update result.exponent after we
  124. // see a '+' or '-'.
  125. CHECK(!seen_plus_minus) << "should only consume one + or -";
  126. seen_plus_minus = true;
  127. continue;
  128. }
  129. break;
  130. }
  131. result.text_ = source_text.substr(0, i);
  132. if (!seen_radix_point) {
  133. result.radix_point_ = i;
  134. }
  135. if (!seen_potential_exponent) {
  136. result.exponent_ = i;
  137. }
  138. return result;
  139. }
  140. // Parser for numeric literal tokens.
  141. //
  142. // Responsible for checking that a numeric literal is valid and meaningful and
  143. // either diagnosing or extracting its meaning.
  144. class LexedNumericLiteral::Parser {
  145. public:
  146. Parser(DiagnosticEmitter<const char*>& emitter, LexedNumericLiteral literal);
  147. auto IsInteger() -> bool {
  148. return literal_.radix_point_ == static_cast<int>(literal_.text_.size());
  149. }
  150. // Check that the numeric literal token is syntactically valid and
  151. // meaningful, and diagnose if not. Returns `true` if the token was
  152. // sufficiently valid that we could determine its meaning. If `false` is
  153. // returned, a diagnostic has already been issued.
  154. auto Check() -> bool;
  155. // Get the radix of this token. One of 2, 10, or 16.
  156. auto GetRadix() -> Radix { return radix_; }
  157. // Get the mantissa of this token's value.
  158. auto GetMantissa() -> llvm::APInt;
  159. // Get the exponent of this token's value. This is always zero for an integer
  160. // literal.
  161. auto GetExponent() -> llvm::APInt;
  162. private:
  163. struct CheckDigitSequenceResult {
  164. bool ok;
  165. bool has_digit_separators = false;
  166. };
  167. auto CheckDigitSequence(llvm::StringRef text, Radix radix,
  168. bool allow_digit_separators = true)
  169. -> CheckDigitSequenceResult;
  170. auto CheckDigitSeparatorPlacement(llvm::StringRef text, Radix radix,
  171. int num_digit_separators) -> void;
  172. auto CheckLeadingZero() -> bool;
  173. auto CheckIntPart() -> bool;
  174. auto CheckFractionalPart() -> bool;
  175. auto CheckExponentPart() -> bool;
  176. DiagnosticEmitter<const char*>& emitter_;
  177. LexedNumericLiteral literal_;
  178. // The radix of the literal: 2, 10, or 16, for a prefix of '0b', no prefix,
  179. // or '0x', respectively.
  180. Radix radix_ = Radix::Decimal;
  181. // The various components of a numeric literal:
  182. //
  183. // [radix] int_part [. fract_part [[ep] [+-] exponent_part]]
  184. llvm::StringRef int_part_;
  185. llvm::StringRef fract_part_;
  186. llvm::StringRef exponent_part_;
  187. // Do we need to remove any special characters (digit separator or radix
  188. // point) before interpreting the mantissa or exponent as an integer?
  189. bool mantissa_needs_cleaning_ = false;
  190. bool exponent_needs_cleaning_ = false;
  191. // True if we found a `-` before `exponent_part`.
  192. bool exponent_is_negative_ = false;
  193. };
  194. LexedNumericLiteral::Parser::Parser(DiagnosticEmitter<const char*>& emitter,
  195. LexedNumericLiteral literal)
  196. : emitter_(emitter), literal_(literal) {
  197. int_part_ = literal.text_.substr(0, literal.radix_point_);
  198. if (int_part_.consume_front("0x")) {
  199. radix_ = Radix::Hexadecimal;
  200. } else if (int_part_.consume_front("0b")) {
  201. radix_ = Radix::Binary;
  202. }
  203. fract_part_ = literal.text_.substr(
  204. literal.radix_point_ + 1, literal.exponent_ - literal.radix_point_ - 1);
  205. exponent_part_ = literal.text_.substr(literal.exponent_ + 1);
  206. if (!exponent_part_.consume_front("+")) {
  207. exponent_is_negative_ = exponent_part_.consume_front("-");
  208. }
  209. }
  210. // Check that the numeric literal token is syntactically valid and meaningful,
  211. // and diagnose if not.
  212. auto LexedNumericLiteral::Parser::Check() -> bool {
  213. return CheckLeadingZero() && CheckIntPart() && CheckFractionalPart() &&
  214. CheckExponentPart();
  215. }
  216. // Parse a string that is known to be a valid base-radix integer into an
  217. // APInt. If needs_cleaning is true, the string may additionally contain '_'
  218. // and '.' characters that should be ignored.
  219. //
  220. // Ignoring '.' is used when parsing a real literal. For example, when
  221. // parsing 123.456e7, we want to decompose it into an integer mantissa
  222. // (123456) and an exponent (7 - 3 = 2), and this routine is given the
  223. // "123.456" to parse as the mantissa.
  224. static auto ParseInteger(llvm::StringRef digits,
  225. LexedNumericLiteral::Radix radix, bool needs_cleaning)
  226. -> llvm::APInt {
  227. llvm::SmallString<32> cleaned;
  228. if (needs_cleaning) {
  229. cleaned.reserve(digits.size());
  230. std::remove_copy_if(digits.begin(), digits.end(),
  231. std::back_inserter(cleaned),
  232. [](char c) { return c == '_' || c == '.'; });
  233. digits = cleaned;
  234. }
  235. llvm::APInt value;
  236. if (digits.getAsInteger(static_cast<int>(radix), value)) {
  237. llvm_unreachable("should never fail");
  238. }
  239. return value;
  240. }
  241. auto LexedNumericLiteral::Parser::GetMantissa() -> llvm::APInt {
  242. const char* end = IsInteger() ? int_part_.end() : fract_part_.end();
  243. llvm::StringRef digits(int_part_.begin(), end - int_part_.begin());
  244. return ParseInteger(digits, radix_, mantissa_needs_cleaning_);
  245. }
  246. auto LexedNumericLiteral::Parser::GetExponent() -> llvm::APInt {
  247. // Compute the effective exponent from the specified exponent, if any,
  248. // and the position of the radix point.
  249. llvm::APInt exponent(64, 0);
  250. if (!exponent_part_.empty()) {
  251. exponent =
  252. ParseInteger(exponent_part_, Radix::Decimal, exponent_needs_cleaning_);
  253. // The exponent is a signed integer, and the number we just parsed is
  254. // non-negative, so ensure we have a wide enough representation to
  255. // include a sign bit. Also make sure the exponent isn't too narrow so
  256. // the calculation below can't lose information through overflow.
  257. if (exponent.isSignBitSet() || exponent.getBitWidth() < 64) {
  258. exponent = exponent.zext(std::max(64u, exponent.getBitWidth() + 1));
  259. }
  260. if (exponent_is_negative_) {
  261. exponent.negate();
  262. }
  263. }
  264. // Each character after the decimal point reduces the effective exponent.
  265. int excess_exponent = fract_part_.size();
  266. if (radix_ == Radix::Hexadecimal) {
  267. excess_exponent *= 4;
  268. }
  269. exponent -= excess_exponent;
  270. if (exponent_is_negative_ && !exponent.isNegative()) {
  271. // We overflowed. Note that we can only overflow by a little, and only
  272. // from negative to positive, because exponent is at least 64 bits wide
  273. // and excess_exponent is bounded above by four times the size of the
  274. // input buffer, which we assume fits into 32 bits.
  275. exponent = exponent.zext(exponent.getBitWidth() + 1);
  276. exponent.setSignBit();
  277. }
  278. return exponent;
  279. }
  280. // Check that a digit sequence is valid: that it contains one or more digits,
  281. // contains only digits in the specified base, and that any digit separators
  282. // are present and correctly positioned.
  283. auto LexedNumericLiteral::Parser::CheckDigitSequence(
  284. llvm::StringRef text, Radix radix, bool allow_digit_separators)
  285. -> CheckDigitSequenceResult {
  286. std::bitset<256> valid_digits;
  287. switch (radix) {
  288. case Radix::Binary:
  289. for (char c : "01") {
  290. valid_digits[static_cast<unsigned char>(c)] = true;
  291. }
  292. break;
  293. case Radix::Decimal:
  294. for (char c : "0123456789") {
  295. valid_digits[static_cast<unsigned char>(c)] = true;
  296. }
  297. break;
  298. case Radix::Hexadecimal:
  299. for (char c : "0123456789ABCDEF") {
  300. valid_digits[static_cast<unsigned char>(c)] = true;
  301. }
  302. break;
  303. }
  304. int num_digit_separators = 0;
  305. for (int i = 0, n = text.size(); i != n; ++i) {
  306. char c = text[i];
  307. if (valid_digits[static_cast<unsigned char>(c)]) {
  308. continue;
  309. }
  310. if (c == '_') {
  311. // A digit separator cannot appear at the start of a digit sequence,
  312. // next to another digit separator, or at the end.
  313. if (!allow_digit_separators || i == 0 || text[i - 1] == '_' ||
  314. i + 1 == n) {
  315. emitter_.EmitError<InvalidDigitSeparator>(text.begin() + i);
  316. }
  317. ++num_digit_separators;
  318. continue;
  319. }
  320. emitter_.EmitError<InvalidDigit>(text.begin() + i,
  321. {.digit = c, .radix = radix});
  322. return {.ok = false};
  323. }
  324. if (num_digit_separators == static_cast<int>(text.size())) {
  325. emitter_.EmitError<EmptyDigitSequence>(text.begin());
  326. return {.ok = false};
  327. }
  328. // Check that digit separators occur in exactly the expected positions.
  329. if (num_digit_separators) {
  330. CheckDigitSeparatorPlacement(text, radix, num_digit_separators);
  331. }
  332. if (!CanLexInteger(emitter_, text)) {
  333. return {.ok = false};
  334. }
  335. return {.ok = true, .has_digit_separators = (num_digit_separators != 0)};
  336. }
  337. // Given a number with digit separators, check that the digit separators are
  338. // correctly positioned.
  339. auto LexedNumericLiteral::Parser::CheckDigitSeparatorPlacement(
  340. llvm::StringRef text, Radix radix, int num_digit_separators) -> void {
  341. DCHECK(std::count(text.begin(), text.end(), '_') == num_digit_separators)
  342. << "given wrong number of digit separators: " << num_digit_separators;
  343. if (radix == Radix::Binary) {
  344. // There are no restrictions on digit separator placement for binary
  345. // literals.
  346. return;
  347. }
  348. auto diagnose_irregular_digit_separators = [&]() {
  349. emitter_.EmitError<IrregularDigitSeparators>(text.begin(),
  350. {.radix = radix});
  351. };
  352. // For decimal and hexadecimal digit sequences, digit separators must form
  353. // groups of 3 or 4 digits (4 or 5 characters), respectively.
  354. int stride = (radix == Radix::Decimal ? 4 : 5);
  355. int remaining_digit_separators = num_digit_separators;
  356. auto pos = text.end();
  357. while (pos - text.begin() >= stride) {
  358. pos -= stride;
  359. if (*pos != '_') {
  360. diagnose_irregular_digit_separators();
  361. return;
  362. }
  363. --remaining_digit_separators;
  364. }
  365. // Check there weren't any other digit separators.
  366. if (remaining_digit_separators) {
  367. diagnose_irregular_digit_separators();
  368. }
  369. };
  370. // Check that we don't have a '0' prefix on a non-zero decimal integer.
  371. auto LexedNumericLiteral::Parser::CheckLeadingZero() -> bool {
  372. if (radix_ == Radix::Decimal && int_part_.startswith("0") &&
  373. int_part_ != "0") {
  374. emitter_.EmitError<UnknownBaseSpecifier>(int_part_.begin());
  375. return false;
  376. }
  377. return true;
  378. }
  379. // Check the integer part (before the '.', if any) is valid.
  380. auto LexedNumericLiteral::Parser::CheckIntPart() -> bool {
  381. auto int_result = CheckDigitSequence(int_part_, radix_);
  382. mantissa_needs_cleaning_ |= int_result.has_digit_separators;
  383. return int_result.ok;
  384. }
  385. // Check the fractional part (after the '.' and before the exponent, if any)
  386. // is valid.
  387. auto LexedNumericLiteral::Parser::CheckFractionalPart() -> bool {
  388. if (IsInteger()) {
  389. return true;
  390. }
  391. if (radix_ == Radix::Binary) {
  392. emitter_.EmitError<BinaryRealLiteral>(literal_.text_.begin() +
  393. literal_.radix_point_);
  394. // Carry on and parse the binary real literal anyway.
  395. }
  396. // We need to remove a '.' from the mantissa.
  397. mantissa_needs_cleaning_ = true;
  398. return CheckDigitSequence(fract_part_, radix_,
  399. /*allow_digit_separators=*/false)
  400. .ok;
  401. }
  402. // Check the exponent part (if any) is valid.
  403. auto LexedNumericLiteral::Parser::CheckExponentPart() -> bool {
  404. if (literal_.exponent_ == static_cast<int>(literal_.text_.size())) {
  405. return true;
  406. }
  407. char expected_exponent_kind = (radix_ == Radix::Decimal ? 'e' : 'p');
  408. if (literal_.text_[literal_.exponent_] != expected_exponent_kind) {
  409. emitter_.EmitError<WrongRealLiteralExponent>(
  410. literal_.text_.begin() + literal_.exponent_,
  411. {.expected = expected_exponent_kind});
  412. return false;
  413. }
  414. auto exponent_result = CheckDigitSequence(exponent_part_, Radix::Decimal);
  415. exponent_needs_cleaning_ = exponent_result.has_digit_separators;
  416. return exponent_result.ok;
  417. }
  418. // Parse the token and compute its value.
  419. auto LexedNumericLiteral::ComputeValue(
  420. DiagnosticEmitter<const char*>& emitter) const -> Value {
  421. Parser parser(emitter, *this);
  422. if (!parser.Check()) {
  423. return UnrecoverableError();
  424. }
  425. if (parser.IsInteger()) {
  426. return IntegerValue{.value = parser.GetMantissa()};
  427. }
  428. return RealValue{
  429. .radix = (parser.GetRadix() == Radix::Decimal ? Radix::Decimal
  430. : Radix::Binary),
  431. .mantissa = parser.GetMantissa(),
  432. .exponent = parser.GetExponent()};
  433. }
  434. } // namespace Carbon