numeric_literal.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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 "lexer/numeric_literal.h"
  5. #include <bitset>
  6. #include "llvm/ADT/StringExtras.h"
  7. #include "llvm/Support/FormatVariadic.h"
  8. namespace Carbon {
  9. namespace {
  10. struct EmptyDigitSequence : SimpleDiagnostic<EmptyDigitSequence> {
  11. static constexpr llvm::StringLiteral ShortName = "syntax-invalid-number";
  12. static constexpr llvm::StringLiteral Message =
  13. "Empty digit sequence in numeric literal.";
  14. };
  15. struct InvalidDigit {
  16. static constexpr llvm::StringLiteral ShortName = "syntax-invalid-number";
  17. char digit;
  18. int radix;
  19. auto Format() -> std::string {
  20. return llvm::formatv("Invalid digit '{0}' in {1} numeric literal.", digit,
  21. (radix == 2 ? "binary"
  22. : radix == 16 ? "hexadecimal" : "decimal"))
  23. .str();
  24. }
  25. };
  26. struct InvalidDigitSeparator : SimpleDiagnostic<InvalidDigitSeparator> {
  27. static constexpr llvm::StringLiteral ShortName = "syntax-invalid-number";
  28. static constexpr llvm::StringLiteral Message =
  29. "Misplaced digit separator in numeric literal.";
  30. };
  31. struct IrregularDigitSeparators {
  32. static constexpr llvm::StringLiteral ShortName =
  33. "syntax-irregular-digit-separators";
  34. int radix;
  35. auto Format() -> std::string {
  36. assert((radix == 10 || radix == 16) && "unexpected radix");
  37. return llvm::formatv(
  38. "Digit separators in {0} number should appear every {1} "
  39. "characters from the right.",
  40. (radix == 10 ? "decimal" : "hexadecimal"),
  41. (radix == 10 ? "3" : "4"))
  42. .str();
  43. }
  44. };
  45. struct UnknownBaseSpecifier : SimpleDiagnostic<UnknownBaseSpecifier> {
  46. static constexpr llvm::StringLiteral ShortName = "syntax-invalid-number";
  47. static constexpr llvm::StringLiteral Message =
  48. "Unknown base specifier in numeric literal.";
  49. };
  50. struct BinaryRealLiteral : SimpleDiagnostic<BinaryRealLiteral> {
  51. static constexpr llvm::StringLiteral ShortName = "syntax-invalid-number";
  52. static constexpr llvm::StringLiteral Message =
  53. "Binary real number literals are not supported.";
  54. };
  55. struct WrongRealLiteralExponent {
  56. static constexpr llvm::StringLiteral ShortName = "syntax-invalid-number";
  57. char expected;
  58. auto Format() -> std::string {
  59. return llvm::formatv("Expected '{0}' to introduce exponent.", expected)
  60. .str();
  61. }
  62. };
  63. } // namespace
  64. static bool isLower(char c) { return 'a' <= c && c <= 'z'; }
  65. auto NumericLiteralToken::Lex(llvm::StringRef source_text)
  66. -> llvm::Optional<NumericLiteralToken> {
  67. NumericLiteralToken result;
  68. if (source_text.empty() || !llvm::isDigit(source_text.front())) {
  69. return llvm::None;
  70. }
  71. bool seen_plus_minus = false;
  72. bool seen_radix_point = false;
  73. bool seen_potential_exponent = false;
  74. // Greedily consume all following characters that might be part of a numeric
  75. // literal. This allows us to produce better diagnostics on invalid literals.
  76. //
  77. // TODO(zygoloid): Update lexical rules to specify that a numeric literal
  78. // cannot be immediately followed by an alphanumeric character.
  79. int i = 1, n = source_text.size();
  80. for (; i != n; ++i) {
  81. char c = source_text[i];
  82. if (llvm::isAlnum(c) || c == '_') {
  83. if (isLower(c) && seen_radix_point && !seen_plus_minus) {
  84. result.exponent = i;
  85. seen_potential_exponent = true;
  86. }
  87. continue;
  88. }
  89. // Exactly one `.` can be part of the literal, but only if it's followed by
  90. // an alphanumeric character.
  91. if (c == '.' && i + 1 != n && llvm::isAlnum(source_text[i + 1]) &&
  92. !seen_radix_point) {
  93. result.radix_point = i;
  94. seen_radix_point = true;
  95. continue;
  96. }
  97. // A `+` or `-` continues the literal only if it's preceded by a lowercase
  98. // letter (which will be 'e' or 'p' or part of an invalid literal) and
  99. // followed by an alphanumeric character. This '+' or '-' cannot be an
  100. // operator because a literal cannot end in a lowercase letter.
  101. if ((c == '+' || c == '-') && seen_potential_exponent &&
  102. result.exponent == i - 1 && i + 1 != n &&
  103. llvm::isAlnum(source_text[i + 1])) {
  104. // This is not possible because we don't update result.exponent after we
  105. // see a '+' or '-'.
  106. assert(!seen_plus_minus && "should only consume one + or -");
  107. seen_plus_minus = true;
  108. continue;
  109. }
  110. break;
  111. }
  112. result.text = source_text.substr(0, i);
  113. if (!seen_radix_point) {
  114. result.radix_point = i;
  115. }
  116. if (!seen_potential_exponent) {
  117. result.exponent = i;
  118. }
  119. return result;
  120. }
  121. NumericLiteralToken::Parser::Parser(DiagnosticEmitter& emitter,
  122. NumericLiteralToken literal)
  123. : emitter(emitter), literal(literal) {
  124. int_part = literal.text.substr(0, literal.radix_point);
  125. if (int_part.consume_front("0x")) {
  126. radix = 16;
  127. } else if (int_part.consume_front("0b")) {
  128. radix = 2;
  129. }
  130. fract_part = literal.text.substr(literal.radix_point + 1,
  131. literal.exponent - literal.radix_point - 1);
  132. exponent_part = literal.text.substr(literal.exponent + 1);
  133. if (!exponent_part.consume_front("+")) {
  134. exponent_is_negative = exponent_part.consume_front("-");
  135. }
  136. }
  137. // Check that the numeric literal token is syntactically valid and meaningful,
  138. // and diagnose if not.
  139. auto NumericLiteralToken::Parser::Check() -> CheckResult {
  140. if (!CheckLeadingZero() || !CheckIntPart() || !CheckFractionalPart() ||
  141. !CheckExponentPart()) {
  142. return UnrecoverableError;
  143. }
  144. return recovered_from_error ? RecoverableError : Valid;
  145. }
  146. // Parse a string that is known to be a valid base-radix integer into an
  147. // APInt. If needs_cleaning is true, the string may additionally contain '_'
  148. // and '.' characters that should be ignored.
  149. //
  150. // Ignoring '.' is used when parsing a real literal. For example, when
  151. // parsing 123.456e7, we want to decompose it into an integer mantissa
  152. // (123456) and an exponent (7 - 3 = 2), and this routine is given the
  153. // "123.456" to parse as the mantissa.
  154. static auto ParseInteger(llvm::StringRef digits, int radix, bool needs_cleaning)
  155. -> llvm::APInt {
  156. llvm::SmallString<32> cleaned;
  157. if (needs_cleaning) {
  158. cleaned.reserve(digits.size());
  159. std::remove_copy_if(digits.begin(), digits.end(),
  160. std::back_inserter(cleaned),
  161. [](char c) { return c == '_' || c == '.'; });
  162. digits = cleaned;
  163. }
  164. llvm::APInt value;
  165. if (digits.getAsInteger(radix, value)) {
  166. llvm_unreachable("should never fail");
  167. }
  168. return value;
  169. }
  170. auto NumericLiteralToken::Parser::GetMantissa() -> llvm::APInt {
  171. const char* end = IsInteger() ? int_part.end() : fract_part.end();
  172. llvm::StringRef digits(int_part.begin(), end - int_part.begin());
  173. return ParseInteger(digits, radix, mantissa_needs_cleaning);
  174. }
  175. auto NumericLiteralToken::Parser::GetExponent() -> llvm::APInt {
  176. // Compute the effective exponent from the specified exponent, if any,
  177. // and the position of the radix point.
  178. llvm::APInt exponent(64, 0);
  179. if (!exponent_part.empty()) {
  180. exponent = ParseInteger(exponent_part, 10, exponent_needs_cleaning);
  181. // The exponent is a signed integer, and the number we just parsed is
  182. // non-negative, so ensure we have a wide enough representation to
  183. // include a sign bit. Also make sure the exponent isn't too narrow so
  184. // the calculation below can't lose information through overflow.
  185. if (exponent.isSignBitSet() || exponent.getBitWidth() < 64) {
  186. exponent = exponent.zext(std::max(64u, exponent.getBitWidth() + 1));
  187. }
  188. if (exponent_is_negative) {
  189. exponent.negate();
  190. }
  191. }
  192. // Each character after the decimal point reduces the effective exponent.
  193. int excess_exponent = fract_part.size();
  194. if (radix == 16) {
  195. excess_exponent *= 4;
  196. }
  197. exponent -= excess_exponent;
  198. if (exponent_is_negative && !exponent.isNegative()) {
  199. // We overflowed. Note that we can only overflow by a little, and only
  200. // from negative to positive, because exponent is at least 64 bits wide
  201. // and excess_exponent is bounded above by four times the size of the
  202. // input buffer, which we assume fits into 32 bits.
  203. exponent = exponent.zext(exponent.getBitWidth() + 1);
  204. exponent.setSignBit();
  205. }
  206. return exponent;
  207. }
  208. // Check that a digit sequence is valid: that it contains one or more digits,
  209. // contains only digits in the specified base, and that any digit separators
  210. // are present and correctly positioned.
  211. auto NumericLiteralToken::Parser::CheckDigitSequence(
  212. llvm::StringRef text, int radix, bool allow_digit_separators)
  213. -> CheckDigitSequenceResult {
  214. assert((radix == 2 || radix == 10 || radix == 16) && "unknown radix");
  215. std::bitset<256> valid_digits;
  216. if (radix == 2) {
  217. for (char c : "01") {
  218. valid_digits[static_cast<unsigned char>(c)] = true;
  219. }
  220. } else if (radix == 10) {
  221. for (char c : "0123456789") {
  222. valid_digits[static_cast<unsigned char>(c)] = true;
  223. }
  224. } else {
  225. for (char c : "0123456789ABCDEF") {
  226. valid_digits[static_cast<unsigned char>(c)] = true;
  227. }
  228. }
  229. int num_digit_separators = 0;
  230. for (int i = 0, n = text.size(); i != n; ++i) {
  231. char c = text[i];
  232. if (valid_digits[static_cast<unsigned char>(c)]) {
  233. continue;
  234. }
  235. if (c == '_') {
  236. // A digit separator cannot appear at the start of a digit sequence,
  237. // next to another digit separator, or at the end.
  238. if (!allow_digit_separators || i == 0 || text[i - 1] == '_' ||
  239. i + 1 == n) {
  240. emitter.EmitError<InvalidDigitSeparator>();
  241. recovered_from_error = true;
  242. }
  243. ++num_digit_separators;
  244. continue;
  245. }
  246. emitter.EmitError<InvalidDigit>({.digit = c, .radix = radix});
  247. return {.ok = false};
  248. }
  249. if (num_digit_separators == static_cast<int>(text.size())) {
  250. emitter.EmitError<EmptyDigitSequence>();
  251. return {.ok = false};
  252. }
  253. // Check that digit separators occur in exactly the expected positions.
  254. if (num_digit_separators) {
  255. CheckDigitSeparatorPlacement(text, radix, num_digit_separators);
  256. }
  257. return {.ok = true, .has_digit_separators = (num_digit_separators != 0)};
  258. }
  259. // Given a number with digit separators, check that the digit separators are
  260. // correctly positioned.
  261. auto NumericLiteralToken::Parser::CheckDigitSeparatorPlacement(
  262. llvm::StringRef text, int radix, int num_digit_separators) -> void {
  263. assert(std::count(text.begin(), text.end(), '_') == num_digit_separators &&
  264. "given wrong number of digit separators");
  265. if (radix == 2) {
  266. // There are no restrictions on digit separator placement for binary
  267. // literals.
  268. return;
  269. }
  270. assert((radix == 10 || radix == 16) &&
  271. "unexpected radix for digit separator checks");
  272. auto diagnose_irregular_digit_separators = [&] {
  273. emitter.EmitError<IrregularDigitSeparators>({.radix = radix});
  274. recovered_from_error = true;
  275. };
  276. // For decimal and hexadecimal digit sequences, digit separators must form
  277. // groups of 3 or 4 digits (4 or 5 characters), respectively.
  278. int stride = (radix == 10 ? 4 : 5);
  279. int remaining_digit_separators = num_digit_separators;
  280. auto pos = text.end();
  281. while (pos - text.begin() >= stride) {
  282. pos -= stride;
  283. if (*pos != '_') {
  284. diagnose_irregular_digit_separators();
  285. return;
  286. }
  287. --remaining_digit_separators;
  288. }
  289. // Check there weren't any other digit separators.
  290. if (remaining_digit_separators) {
  291. diagnose_irregular_digit_separators();
  292. }
  293. };
  294. // Check that we don't have a '0' prefix on a non-zero decimal integer.
  295. auto NumericLiteralToken::Parser::CheckLeadingZero() -> bool {
  296. if (radix == 10 && int_part.startswith("0") && int_part != "0") {
  297. emitter.EmitError<UnknownBaseSpecifier>();
  298. return false;
  299. }
  300. return true;
  301. }
  302. // Check the integer part (before the '.', if any) is valid.
  303. auto NumericLiteralToken::Parser::CheckIntPart() -> bool {
  304. auto int_result = CheckDigitSequence(int_part, radix);
  305. mantissa_needs_cleaning |= int_result.has_digit_separators;
  306. return int_result.ok;
  307. }
  308. // Check the fractional part (after the '.' and before the exponent, if any)
  309. // is valid.
  310. auto NumericLiteralToken::Parser::CheckFractionalPart() -> bool {
  311. if (IsInteger()) {
  312. return true;
  313. }
  314. if (radix == 2) {
  315. emitter.EmitError<BinaryRealLiteral>();
  316. recovered_from_error = true;
  317. // Carry on and parse the binary real literal anyway.
  318. }
  319. // We need to remove a '.' from the mantissa.
  320. mantissa_needs_cleaning = true;
  321. return CheckDigitSequence(fract_part, radix,
  322. /*allow_digit_separators=*/false)
  323. .ok;
  324. }
  325. // Check the exponent part (if any) is valid.
  326. auto NumericLiteralToken::Parser::CheckExponentPart() -> bool {
  327. if (literal.exponent == static_cast<int>(literal.text.size())) {
  328. return true;
  329. }
  330. char expected_exponent_kind = (radix == 10 ? 'e' : 'p');
  331. if (literal.text[literal.exponent] != expected_exponent_kind) {
  332. emitter.EmitError<WrongRealLiteralExponent>(
  333. {.expected = expected_exponent_kind});
  334. return false;
  335. }
  336. auto exponent_result = CheckDigitSequence(exponent_part, 10);
  337. exponent_needs_cleaning = exponent_result.has_digit_separators;
  338. return exponent_result.ok;
  339. }
  340. } // namespace Carbon