numeric_literal.cpp 17 KB

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