| 1 | //===--- NumericLiteralInfo.cpp ---------------------------------*- C++ -*-===// |
| 2 | // |
| 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | /// |
| 9 | /// \file |
| 10 | /// This file implements the functionality of getting information about a |
| 11 | /// numeric literal string, including 0-based positions of the base letter, the |
| 12 | /// decimal/hexadecimal point, the exponent letter, and the suffix, or npos if |
| 13 | /// absent. |
| 14 | /// |
| 15 | //===----------------------------------------------------------------------===// |
| 16 | |
| 17 | #include "NumericLiteralInfo.h" |
| 18 | #include "llvm/ADT/StringExtras.h" |
| 19 | #include <algorithm> |
| 20 | |
| 21 | namespace clang { |
| 22 | namespace format { |
| 23 | |
| 24 | using namespace llvm; |
| 25 | |
| 26 | NumericLiteralInfo::NumericLiteralInfo(StringRef Text, char Separator) { |
| 27 | if (Text.size() < 2) |
| 28 | return; |
| 29 | |
| 30 | bool IsHex = false; |
| 31 | if (Text[0] == '0') { |
| 32 | switch (Text[1]) { |
| 33 | case 'x': |
| 34 | case 'X': |
| 35 | IsHex = true; |
| 36 | [[fallthrough]]; |
| 37 | case 'b': |
| 38 | case 'B': |
| 39 | case 'o': // JavaScript octal. |
| 40 | case 'O': |
| 41 | BaseLetterPos = 1; // e.g. 0xF |
| 42 | break; |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | DotPos = Text.find(C: '.', From: BaseLetterPos + 1); // e.g. 0x.1 or .1 |
| 47 | |
| 48 | // e.g. 1.e2 or 0xFp2 |
| 49 | const auto Pos = DotPos != StringRef::npos ? DotPos + 1 : BaseLetterPos + 2; |
| 50 | // Trim C++ user-defined suffix as in `1_Pa`. |
| 51 | const auto TrimmedText = |
| 52 | Separator == '\'' ? Text.take_front(N: Text.find(C: '_')) : Text; |
| 53 | |
| 54 | // Clamp searches due to possible incomplete literals. |
| 55 | ExponentLetterPos = TrimmedText.find_insensitive( |
| 56 | C: IsHex ? 'p' : 'e', From: std::min(a: Pos, b: TrimmedText.size())); |
| 57 | |
| 58 | const bool HasExponent = ExponentLetterPos != StringRef::npos; |
| 59 | SuffixPos = Text.find_if_not( |
| 60 | F: [&](char C) { |
| 61 | return (HasExponent || !IsHex ? isDigit : isHexDigit)(C) || |
| 62 | C == Separator; |
| 63 | }, |
| 64 | From: std::min(a: HasExponent ? ExponentLetterPos + 2 : Pos, |
| 65 | b: Text.size())); // e.g. 1e-2f |
| 66 | } |
| 67 | |
| 68 | } // namespace format |
| 69 | } // namespace clang |
| 70 | |