numeric_literal.cpp 13 KB

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