numeric_literal.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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. llvm::copy_if(digits, std::back_inserter(cleaned),
  158. [](char c) { return c != '_' && c != '.'; });
  159. digits = cleaned;
  160. }
  161. llvm::APInt value;
  162. if (digits.getAsInteger(static_cast<int>(radix), value)) {
  163. llvm_unreachable("should never fail");
  164. }
  165. return value;
  166. }
  167. auto NumericLiteral::Parser::GetMantissa() -> llvm::APInt {
  168. const char* end = IsInt() ? int_part_.end() : fract_part_.end();
  169. llvm::StringRef digits(int_part_.begin(), end - int_part_.begin());
  170. return ParseInt(digits, radix_, mantissa_needs_cleaning_);
  171. }
  172. auto NumericLiteral::Parser::GetExponent() -> llvm::APInt {
  173. // Compute the effective exponent from the specified exponent, if any,
  174. // and the position of the radix point.
  175. llvm::APInt exponent(64, 0);
  176. if (!exponent_part_.empty()) {
  177. exponent =
  178. ParseInt(exponent_part_, Radix::Decimal, exponent_needs_cleaning_);
  179. // The exponent is a signed integer, and the number we just parsed is
  180. // non-negative, so ensure we have a wide enough representation to
  181. // include a sign bit. Also make sure the exponent isn't too narrow so
  182. // the calculation below can't lose information through overflow.
  183. if (exponent.isSignBitSet() || exponent.getBitWidth() < 64) {
  184. exponent = exponent.zext(std::max(64U, exponent.getBitWidth() + 1));
  185. }
  186. if (exponent_is_negative_) {
  187. exponent.negate();
  188. }
  189. }
  190. // Each character after the decimal point reduces the effective exponent.
  191. int excess_exponent = fract_part_.size();
  192. if (radix_ == Radix::Hexadecimal) {
  193. excess_exponent *= 4;
  194. }
  195. exponent -= excess_exponent;
  196. if (exponent_is_negative_ && !exponent.isNegative()) {
  197. // We overflowed. Note that we can only overflow by a little, and only
  198. // from negative to positive, because exponent is at least 64 bits wide
  199. // and excess_exponent is bounded above by four times the size of the
  200. // input buffer, which we assume fits into 32 bits.
  201. exponent = exponent.zext(exponent.getBitWidth() + 1);
  202. exponent.setSignBit();
  203. }
  204. return exponent;
  205. }
  206. // Check that a digit sequence is valid: that it contains one or more digits,
  207. // contains only digits in the specified base, and that any digit separators
  208. // are present and correctly positioned.
  209. auto NumericLiteral::Parser::CheckDigitSequence(llvm::StringRef text,
  210. Radix radix,
  211. bool allow_digit_separators)
  212. -> CheckDigitSequenceResult {
  213. std::bitset<256> valid_digits;
  214. switch (radix) {
  215. case Radix::Binary:
  216. for (char c : "01") {
  217. valid_digits[static_cast<unsigned char>(c)] = true;
  218. }
  219. break;
  220. case Radix::Decimal:
  221. for (char c : "0123456789") {
  222. valid_digits[static_cast<unsigned char>(c)] = true;
  223. }
  224. break;
  225. case Radix::Hexadecimal:
  226. for (char c : "0123456789ABCDEF") {
  227. valid_digits[static_cast<unsigned char>(c)] = true;
  228. }
  229. break;
  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. CARBON_DIAGNOSTIC(InvalidDigitSeparator, Error,
  243. "misplaced digit separator in numeric literal");
  244. emitter_.Emit(text.begin() + 1, InvalidDigitSeparator);
  245. }
  246. ++num_digit_separators;
  247. continue;
  248. }
  249. CARBON_DIAGNOSTIC(
  250. InvalidDigit, Error,
  251. "invalid digit '{0}' in {1:=2:binary|=10:decimal|=16:hexadecimal} "
  252. "numeric literal",
  253. char, IntAsSelect);
  254. emitter_.Emit(text.begin() + i, InvalidDigit, c, static_cast<int>(radix));
  255. return {.ok = false};
  256. }
  257. if (num_digit_separators == static_cast<int>(text.size())) {
  258. CARBON_DIAGNOSTIC(EmptyDigitSequence, Error,
  259. "empty digit sequence in numeric literal");
  260. emitter_.Emit(text.begin(), EmptyDigitSequence);
  261. return {.ok = false};
  262. }
  263. if (!CanLexInt(emitter_, text)) {
  264. return {.ok = false};
  265. }
  266. return {.ok = true, .has_digit_separators = (num_digit_separators != 0)};
  267. }
  268. // Check that we don't have a '0' prefix on a non-zero decimal integer.
  269. auto NumericLiteral::Parser::CheckLeadingZero() -> bool {
  270. if (radix_ == Radix::Decimal && int_part_.starts_with("0") &&
  271. int_part_ != "0") {
  272. CARBON_DIAGNOSTIC(UnknownBaseSpecifier, Error,
  273. "unknown base specifier in numeric literal");
  274. emitter_.Emit(int_part_.begin(), UnknownBaseSpecifier);
  275. return false;
  276. }
  277. return true;
  278. }
  279. // Check the integer part (before the '.', if any) is valid.
  280. auto NumericLiteral::Parser::CheckIntPart() -> bool {
  281. auto int_result = CheckDigitSequence(int_part_, radix_);
  282. mantissa_needs_cleaning_ |= int_result.has_digit_separators;
  283. return int_result.ok;
  284. }
  285. // Check the fractional part (after the '.' and before the exponent, if any)
  286. // is valid.
  287. auto NumericLiteral::Parser::CheckFractionalPart() -> bool {
  288. if (IsInt()) {
  289. return true;
  290. }
  291. if (radix_ == Radix::Binary) {
  292. CARBON_DIAGNOSTIC(BinaryRealLiteral, Error,
  293. "binary real number literals are not supported");
  294. emitter_.Emit(literal_.text_.begin() + literal_.radix_point_,
  295. BinaryRealLiteral);
  296. // Carry on and parse the binary real literal anyway.
  297. }
  298. // We need to remove a '.' from the mantissa.
  299. mantissa_needs_cleaning_ = true;
  300. return CheckDigitSequence(fract_part_, radix_,
  301. /*allow_digit_separators=*/false)
  302. .ok;
  303. }
  304. // Check the exponent part (if any) is valid.
  305. auto NumericLiteral::Parser::CheckExponentPart() -> bool {
  306. if (literal_.exponent_ == static_cast<int>(literal_.text_.size())) {
  307. return true;
  308. }
  309. char expected_exponent_kind = (radix_ == Radix::Decimal ? 'e' : 'p');
  310. if (literal_.text_[literal_.exponent_] != expected_exponent_kind) {
  311. CARBON_DIAGNOSTIC(WrongRealLiteralExponent, Error,
  312. "expected '{0}' to introduce exponent", char);
  313. emitter_.Emit(literal_.text_.begin() + literal_.exponent_,
  314. WrongRealLiteralExponent, expected_exponent_kind);
  315. return false;
  316. }
  317. auto exponent_result = CheckDigitSequence(exponent_part_, Radix::Decimal);
  318. exponent_needs_cleaning_ = exponent_result.has_digit_separators;
  319. return exponent_result.ok;
  320. }
  321. // Parse the token and compute its value.
  322. auto NumericLiteral::ComputeValue(DiagnosticEmitter<const char*>& emitter) const
  323. -> Value {
  324. Parser parser(emitter, *this);
  325. if (!parser.Check()) {
  326. return UnrecoverableError();
  327. }
  328. if (parser.IsInt()) {
  329. return IntValue{.value = parser.GetMantissa()};
  330. }
  331. return RealValue{
  332. .radix = (parser.GetRadix() == Radix::Decimal ? Radix::Decimal
  333. : Radix::Binary),
  334. .mantissa = parser.GetMantissa(),
  335. .exponent = parser.GetExponent()};
  336. }
  337. } // namespace Carbon::Lex