numeric_literal.cpp 13 KB

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