numeric_literal.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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/lex/numeric_literal.h"
  5. #include <bitset>
  6. #include "common/check.h"
  7. #include "llvm/ADT/StringExtras.h"
  8. #include "llvm/Support/FormatVariadicDetails.h"
  9. #include "toolchain/diagnostics/format_providers.h"
  10. #include "toolchain/lex/character_set.h"
  11. #include "toolchain/lex/helpers.h"
  12. namespace Carbon::Lex {
  13. auto NumericLiteral::Lex(llvm::StringRef source_text)
  14. -> std::optional<NumericLiteral> {
  15. NumericLiteral result;
  16. if (source_text.empty() || !IsDecimalDigit(source_text.front())) {
  17. return std::nullopt;
  18. }
  19. bool seen_plus_minus = false;
  20. bool seen_radix_point = false;
  21. bool seen_potential_exponent = false;
  22. // Greedily consume all following characters that might be part of a numeric
  23. // literal. This allows us to produce better diagnostics on invalid literals.
  24. //
  25. // TODO(zygoloid): Update lexical rules to specify that a numeric literal
  26. // cannot be immediately followed by an alphanumeric character.
  27. int i = 1;
  28. int n = source_text.size();
  29. for (; i != n; ++i) {
  30. char c = source_text[i];
  31. if (IsAlnum(c) || c == '_') {
  32. if (IsLower(c) && seen_radix_point && !seen_plus_minus) {
  33. result.exponent_ = i;
  34. seen_potential_exponent = true;
  35. }
  36. continue;
  37. }
  38. // Exactly one `.` can be part of the literal, but only if it's followed by
  39. // an alphanumeric character.
  40. if (c == '.' && i + 1 != n && IsAlnum(source_text[i + 1]) &&
  41. !seen_radix_point) {
  42. result.radix_point_ = i;
  43. seen_radix_point = true;
  44. continue;
  45. }
  46. // A `+` or `-` continues the literal only if it's preceded by a lowercase
  47. // letter (which will be 'e' or 'p' or part of an invalid literal) and
  48. // followed by an alphanumeric character. This '+' or '-' cannot be an
  49. // operator because a literal cannot end in a lowercase letter.
  50. if ((c == '+' || c == '-') && seen_potential_exponent &&
  51. result.exponent_ == i - 1 && i + 1 != n &&
  52. IsAlnum(source_text[i + 1])) {
  53. // This is not possible because we don't update result.exponent after we
  54. // see a '+' or '-'.
  55. CARBON_CHECK(!seen_plus_minus, "should only consume one + or -");
  56. seen_plus_minus = true;
  57. continue;
  58. }
  59. break;
  60. }
  61. result.text_ = source_text.substr(0, i);
  62. if (!seen_radix_point) {
  63. result.radix_point_ = i;
  64. }
  65. if (!seen_potential_exponent) {
  66. result.exponent_ = i;
  67. }
  68. return result;
  69. }
  70. // Parser for numeric literal tokens.
  71. //
  72. // Responsible for checking that a numeric literal is valid and meaningful and
  73. // either diagnosing or extracting its meaning.
  74. class NumericLiteral::Parser {
  75. public:
  76. Parser(DiagnosticEmitter<const char*>& emitter, NumericLiteral literal);
  77. auto IsInt() -> bool {
  78. return literal_.radix_point_ == static_cast<int>(literal_.text_.size());
  79. }
  80. // Check that the numeric literal token is syntactically valid and
  81. // meaningful, and diagnose if not. Returns `true` if the token was
  82. // sufficiently valid that we could determine its meaning. If `false` is
  83. // returned, a diagnostic has already been issued.
  84. auto Check() -> bool;
  85. // Get the radix of this token. One of 2, 10, or 16.
  86. auto GetRadix() -> Radix { return radix_; }
  87. // Get the mantissa of this token's value.
  88. auto GetMantissa() -> llvm::APInt;
  89. // Get the exponent of this token's value. This is always zero for an integer
  90. // literal.
  91. auto GetExponent() -> llvm::APInt;
  92. private:
  93. struct CheckDigitSequenceResult {
  94. bool ok;
  95. bool has_digit_separators = false;
  96. };
  97. auto CheckDigitSequence(llvm::StringRef text, Radix radix,
  98. bool allow_digit_separators = true)
  99. -> CheckDigitSequenceResult;
  100. auto CheckLeadingZero() -> bool;
  101. auto CheckIntPart() -> bool;
  102. auto CheckFractionalPart() -> bool;
  103. auto CheckExponentPart() -> bool;
  104. DiagnosticEmitter<const char*>& emitter_;
  105. NumericLiteral literal_;
  106. // The radix of the literal: 2, 10, or 16, for a prefix of '0b', no prefix,
  107. // or '0x', respectively.
  108. Radix radix_ = Radix::Decimal;
  109. // The various components of a numeric literal:
  110. //
  111. // [radix] int_part [. fract_part [[ep] [+-] exponent_part]]
  112. llvm::StringRef int_part_;
  113. llvm::StringRef fract_part_;
  114. llvm::StringRef exponent_part_;
  115. // Do we need to remove any special characters (digit separator or radix
  116. // point) before interpreting the mantissa or exponent as an integer?
  117. bool mantissa_needs_cleaning_ = false;
  118. bool exponent_needs_cleaning_ = false;
  119. // True if we found a `-` before `exponent_part`.
  120. bool exponent_is_negative_ = false;
  121. };
  122. NumericLiteral::Parser::Parser(DiagnosticEmitter<const char*>& emitter,
  123. NumericLiteral 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_ = Radix::Hexadecimal;
  128. } else if (int_part_.consume_front("0b")) {
  129. radix_ = Radix::Binary;
  130. }
  131. fract_part_ = literal.text_.substr(
  132. literal.radix_point_ + 1, 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 NumericLiteral::Parser::Check() -> bool {
  141. return CheckLeadingZero() && CheckIntPart() && CheckFractionalPart() &&
  142. CheckExponentPart();
  143. }
  144. // Parse a string that is known to be a valid base-radix integer into an
  145. // APInt. If needs_cleaning is true, the string may additionally contain '_'
  146. // and '.' characters that should be ignored.
  147. //
  148. // Ignoring '.' is used when parsing a real literal. For example, when
  149. // parsing 123.456e7, we want to decompose it into an integer mantissa
  150. // (123456) and an exponent (7 - 3 = 4), and this routine is given the
  151. // "123.456" to parse as the mantissa.
  152. static auto ParseInt(llvm::StringRef digits, NumericLiteral::Radix radix,
  153. bool needs_cleaning) -> llvm::APInt {
  154. llvm::SmallString<32> cleaned;
  155. if (needs_cleaning) {
  156. cleaned.reserve(digits.size());
  157. std::remove_copy_if(digits.begin(), digits.end(),
  158. std::back_inserter(cleaned),
  159. [](char c) { return c == '_' || c == '.'; });
  160. digits = cleaned;
  161. }
  162. llvm::APInt value;
  163. if (digits.getAsInteger(static_cast<int>(radix), value)) {
  164. llvm_unreachable("should never fail");
  165. }
  166. return value;
  167. }
  168. auto NumericLiteral::Parser::GetMantissa() -> llvm::APInt {
  169. const char* end = IsInt() ? int_part_.end() : fract_part_.end();
  170. llvm::StringRef digits(int_part_.begin(), end - int_part_.begin());
  171. return ParseInt(digits, radix_, mantissa_needs_cleaning_);
  172. }
  173. auto NumericLiteral::Parser::GetExponent() -> llvm::APInt {
  174. // Compute the effective exponent from the specified exponent, if any,
  175. // and the position of the radix point.
  176. llvm::APInt exponent(64, 0);
  177. if (!exponent_part_.empty()) {
  178. exponent =
  179. ParseInt(exponent_part_, Radix::Decimal, 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_ == Radix::Hexadecimal) {
  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 NumericLiteral::Parser::CheckDigitSequence(llvm::StringRef text,
  211. Radix radix,
  212. bool allow_digit_separators)
  213. -> CheckDigitSequenceResult {
  214. std::bitset<256> valid_digits;
  215. switch (radix) {
  216. case Radix::Binary:
  217. for (char c : "01") {
  218. valid_digits[static_cast<unsigned char>(c)] = true;
  219. }
  220. break;
  221. case Radix::Decimal:
  222. for (char c : "0123456789") {
  223. valid_digits[static_cast<unsigned char>(c)] = true;
  224. }
  225. break;
  226. case Radix::Hexadecimal:
  227. for (char c : "0123456789ABCDEF") {
  228. valid_digits[static_cast<unsigned char>(c)] = true;
  229. }
  230. break;
  231. }
  232. int num_digit_separators = 0;
  233. for (int i = 0, n = text.size(); i != n; ++i) {
  234. char c = text[i];
  235. if (valid_digits[static_cast<unsigned char>(c)]) {
  236. continue;
  237. }
  238. if (c == '_') {
  239. // A digit separator cannot appear at the start of a digit sequence,
  240. // next to another digit separator, or at the end.
  241. if (!allow_digit_separators || i == 0 || text[i - 1] == '_' ||
  242. i + 1 == n) {
  243. CARBON_DIAGNOSTIC(InvalidDigitSeparator, Error,
  244. "misplaced digit separator in numeric literal");
  245. emitter_.Emit(text.begin() + 1, InvalidDigitSeparator);
  246. }
  247. ++num_digit_separators;
  248. continue;
  249. }
  250. CARBON_DIAGNOSTIC(
  251. InvalidDigit, Error,
  252. "invalid digit '{0}' in {1:=2:binary|=10:decimal|=16:hexadecimal} "
  253. "numeric literal",
  254. char, IntAsSelect);
  255. emitter_.Emit(text.begin() + i, InvalidDigit, c, static_cast<int>(radix));
  256. return {.ok = false};
  257. }
  258. if (num_digit_separators == static_cast<int>(text.size())) {
  259. CARBON_DIAGNOSTIC(EmptyDigitSequence, Error,
  260. "empty digit sequence in numeric literal");
  261. emitter_.Emit(text.begin(), EmptyDigitSequence);
  262. return {.ok = false};
  263. }
  264. if (!CanLexInt(emitter_, text)) {
  265. return {.ok = false};
  266. }
  267. return {.ok = true, .has_digit_separators = (num_digit_separators != 0)};
  268. }
  269. // Check that we don't have a '0' prefix on a non-zero decimal integer.
  270. auto NumericLiteral::Parser::CheckLeadingZero() -> bool {
  271. if (radix_ == Radix::Decimal && int_part_.starts_with("0") &&
  272. int_part_ != "0") {
  273. CARBON_DIAGNOSTIC(UnknownBaseSpecifier, Error,
  274. "unknown base specifier in numeric literal");
  275. emitter_.Emit(int_part_.begin(), UnknownBaseSpecifier);
  276. return false;
  277. }
  278. return true;
  279. }
  280. // Check the integer part (before the '.', if any) is valid.
  281. auto NumericLiteral::Parser::CheckIntPart() -> bool {
  282. auto int_result = CheckDigitSequence(int_part_, radix_);
  283. mantissa_needs_cleaning_ |= int_result.has_digit_separators;
  284. return int_result.ok;
  285. }
  286. // Check the fractional part (after the '.' and before the exponent, if any)
  287. // is valid.
  288. auto NumericLiteral::Parser::CheckFractionalPart() -> bool {
  289. if (IsInt()) {
  290. return true;
  291. }
  292. if (radix_ == Radix::Binary) {
  293. CARBON_DIAGNOSTIC(BinaryRealLiteral, Error,
  294. "binary real number literals are not supported");
  295. emitter_.Emit(literal_.text_.begin() + literal_.radix_point_,
  296. BinaryRealLiteral);
  297. // Carry on and parse the binary real literal anyway.
  298. }
  299. // We need to remove a '.' from the mantissa.
  300. mantissa_needs_cleaning_ = true;
  301. return CheckDigitSequence(fract_part_, radix_,
  302. /*allow_digit_separators=*/false)
  303. .ok;
  304. }
  305. // Check the exponent part (if any) is valid.
  306. auto NumericLiteral::Parser::CheckExponentPart() -> bool {
  307. if (literal_.exponent_ == static_cast<int>(literal_.text_.size())) {
  308. return true;
  309. }
  310. char expected_exponent_kind = (radix_ == Radix::Decimal ? 'e' : 'p');
  311. if (literal_.text_[literal_.exponent_] != expected_exponent_kind) {
  312. CARBON_DIAGNOSTIC(WrongRealLiteralExponent, Error,
  313. "expected '{0}' to introduce exponent", char);
  314. emitter_.Emit(literal_.text_.begin() + literal_.exponent_,
  315. WrongRealLiteralExponent, expected_exponent_kind);
  316. return false;
  317. }
  318. auto exponent_result = CheckDigitSequence(exponent_part_, Radix::Decimal);
  319. exponent_needs_cleaning_ = exponent_result.has_digit_separators;
  320. return exponent_result.ok;
  321. }
  322. // Parse the token and compute its value.
  323. auto NumericLiteral::ComputeValue(DiagnosticEmitter<const char*>& emitter) const
  324. -> Value {
  325. Parser parser(emitter, *this);
  326. if (!parser.Check()) {
  327. return UnrecoverableError();
  328. }
  329. if (parser.IsInt()) {
  330. return IntValue{.value = parser.GetMantissa()};
  331. }
  332. return RealValue{
  333. .radix = (parser.GetRadix() == Radix::Decimal ? Radix::Decimal
  334. : Radix::Binary),
  335. .mantissa = parser.GetMantissa(),
  336. .exponent = parser.GetExponent()};
  337. }
  338. } // namespace Carbon::Lex