numeric_literal.cpp 13 KB

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