numeric_literal.cpp 16 KB

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