| 55 | } // namespace |
| 56 | |
| 57 | EncodeNumberStatus ParseAndEncodeIntegerNumber( |
| 58 | const char* text, const NumberType& type, |
| 59 | std::function<void(uint32_t)> emit, std::string* error_msg) { |
| 60 | if (!text) { |
| 61 | ErrorMsgStream(error_msg) << "The given text is a nullptr"; |
| 62 | return EncodeNumberStatus::kInvalidText; |
| 63 | } |
| 64 | |
| 65 | if (!IsIntegral(type)) { |
| 66 | ErrorMsgStream(error_msg) << "The expected type is not a integer type"; |
| 67 | return EncodeNumberStatus::kInvalidUsage; |
| 68 | } |
| 69 | |
| 70 | const uint32_t bit_width = AssumedBitWidth(type); |
| 71 | |
| 72 | if (bit_width > 64) { |
| 73 | ErrorMsgStream(error_msg) |
| 74 | << "Unsupported " << bit_width << "-bit integer literals"; |
| 75 | return EncodeNumberStatus::kUnsupported; |
| 76 | } |
| 77 | |
| 78 | // Either we are expecting anything or integer. |
| 79 | bool is_negative = text[0] == '-'; |
| 80 | bool can_be_signed = IsSigned(type); |
| 81 | |
| 82 | if (is_negative && !can_be_signed) { |
| 83 | ErrorMsgStream(error_msg) |
| 84 | << "Cannot put a negative number in an unsigned literal"; |
| 85 | return EncodeNumberStatus::kInvalidUsage; |
| 86 | } |
| 87 | |
| 88 | const bool is_hex = text[0] == '0' && (text[1] == 'x' || text[1] == 'X'); |
| 89 | |
| 90 | uint64_t decoded_bits; |
| 91 | if (is_negative) { |
| 92 | int64_t decoded_signed = 0; |
| 93 | |
| 94 | if (!ParseNumber(text, &decoded_signed)) { |
| 95 | ErrorMsgStream(error_msg) << "Invalid signed integer literal: " << text; |
| 96 | return EncodeNumberStatus::kInvalidText; |
| 97 | } |
| 98 | |
| 99 | if (!CheckRangeAndIfHexThenSignExtend(decoded_signed, type, is_hex, |
| 100 | &decoded_signed)) { |
| 101 | ErrorMsgStream(error_msg) |
| 102 | << "Integer " << (is_hex ? std::hex : std::dec) << std::showbase |
| 103 | << decoded_signed << " does not fit in a " << std::dec << bit_width |
| 104 | << "-bit " << (IsSigned(type) ? "signed" : "unsigned") << " integer"; |
| 105 | return EncodeNumberStatus::kInvalidText; |
| 106 | } |
| 107 | decoded_bits = decoded_signed; |
| 108 | } else { |
| 109 | // There's no leading minus sign, so parse it as an unsigned integer. |
| 110 | if (!ParseNumber(text, &decoded_bits)) { |
| 111 | ErrorMsgStream(error_msg) << "Invalid unsigned integer literal: " << text; |
| 112 | return EncodeNumberStatus::kInvalidText; |
| 113 | } |
| 114 | if (!CheckRangeAndIfHexThenSignExtend(decoded_bits, type, is_hex, |