unicode.h 9.99 KB
Newer Older
1
// Copyright 2011 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4

5 6
#ifndef V8_STRINGS_UNICODE_H_
#define V8_STRINGS_UNICODE_H_
7 8

#include <sys/types.h>
9

10
#include "src/base/bit-field.h"
11
#include "src/base/vector.h"
12
#include "src/common/globals.h"
13
#include "src/third_party/utf8-decoder/utf8-decoder.h"
14 15 16 17 18 19 20
/**
 * \file
 * Definitions and convenience functions for working with unicode.
 */

namespace unibrow {

21 22
using uchar = unsigned int;
using byte = unsigned char;
23 24 25 26 27

/**
 * The max length of the result of converting the case of a single
 * character.
 */
28
const int kMaxMappingSize = 4;
29

30
#ifndef V8_INTL_SUPPORT
31 32 33
template <class T, int size = 256>
class Predicate {
 public:
34
  inline Predicate() = default;
35
  inline bool get(uchar c);
36

37 38 39
 private:
  friend class Test;
  bool CalculateValue(uchar c);
40 41 42 43
  class CacheEntry {
   public:
    inline CacheEntry()
        : bit_field_(CodePointField::encode(0) | ValueField::encode(0)) {}
44
    inline CacheEntry(uchar code_point, bool value)
45 46 47 48 49 50
        : bit_field_(
              CodePointField::encode(CodePointField::kMask & code_point) |
              ValueField::encode(value)) {
      DCHECK_IMPLIES((CodePointField::kMask & code_point) != code_point,
                     code_point == static_cast<uchar>(-1));
    }
51 52 53 54 55

    uchar code_point() const { return CodePointField::decode(bit_field_); }
    bool value() const { return ValueField::decode(bit_field_); }

   private:
56 57
    using CodePointField = v8::base::BitField<uchar, 0, 21>;
    using ValueField = v8::base::BitField<bool, 21, 1>;
58 59

    uint32_t bit_field_;
60 61 62 63 64 65 66 67 68 69 70 71 72
  };
  static const int kSize = size;
  static const int kMask = kSize - 1;
  CacheEntry entries_[kSize];
};

// A cache used in case conversion.  It caches the value for characters
// that either have no mapping or map to a single character independent
// of context.  Characters that map to more than one character or that
// map differently depending on context are always looked up.
template <class T, int size = 256>
class Mapping {
 public:
73
  inline Mapping() = default;
74
  inline int get(uchar c, uchar n, uchar* result);
75

76 77 78 79
 private:
  friend class Test;
  int CalculateValue(uchar c, uchar n, uchar* result);
  struct CacheEntry {
80
    inline CacheEntry() : code_point_(kNoChar), offset_(0) {}
81
    inline CacheEntry(uchar code_point, signed offset)
82
        : code_point_(code_point), offset_(offset) {}
83 84 85
    uchar code_point_;
    signed offset_;
    static const int kNoChar = (1 << 21) - 1;
86 87 88 89 90 91 92 93 94 95
  };
  static const int kSize = size;
  static const int kMask = kSize - 1;
  CacheEntry entries_[kSize];
};

class UnicodeData {
 private:
  friend class Test;
  static int GetByteCount();
96
  static const uchar kMaxCodePoint;
97 98
};

99
#endif  // !V8_INTL_SUPPORT
100

101 102
class Utf16 {
 public:
103
  static const int kNoPreviousCharacter = -1;
104 105 106
  static inline bool IsSurrogatePair(int lead, int trail) {
    return IsLeadSurrogate(lead) && IsTrailSurrogate(trail);
  }
107
  static inline bool IsLeadSurrogate(int code) {
108
    return (code & 0x1ffc00) == 0xd800;
109
  }
110
  static inline bool IsTrailSurrogate(int code) {
111
    return (code & 0x1ffc00) == 0xdc00;
112 113
  }

114
  static inline int CombineSurrogatePair(uchar lead, uchar trail) {
115 116 117 118 119 120 121 122 123 124 125 126
    return 0x10000 + ((lead & 0x3ff) << 10) + (trail & 0x3ff);
  }
  static const uchar kMaxNonSurrogateCharCode = 0xffff;
  // Encoding a single UTF-16 code unit will produce 1, 2 or 3 bytes
  // of UTF-8 data.  The special case where the unit is a surrogate
  // trail produces 1 byte net, because the encoding of the pair is
  // 4 bytes and the 3 bytes that were used to encode the lead surrogate
  // can be reclaimed.
  static const int kMaxExtraUtf8BytesForOneUtf16CodeUnit = 3;
  // One UTF-16 surrogate is endoded (illegally) as 3 UTF-8 bytes.
  // The illegality stems from the surrogate not being part of a pair.
  static const int kUtf8BytesToCodeASurrogate = 3;
127
  static inline uint16_t LeadSurrogate(uint32_t char_code) {
128 129
    return 0xd800 + (((char_code - 0x10000) >> 10) & 0x3ff);
  }
130
  static inline uint16_t TrailSurrogate(uint32_t char_code) {
131 132
    return 0xdc00 + (char_code & 0x3ff);
  }
133 134
  static inline bool HasUnpairedSurrogate(const uint16_t* code_units,
                                          size_t length);
135 136
};

137 138
class Latin1 {
 public:
139
  static const uint16_t kMaxChar = 0xff;
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
  // Convert the character to Latin-1 case equivalent if possible.
  static inline uint16_t TryConvertToLatin1(uint16_t c) {
    switch (c) {
      // This are equivalent characters in unicode.
      case 0x39c:
      case 0x3bc:
        return 0xb5;
      // This is an uppercase of a Latin-1 character
      // outside of Latin-1.
      case 0x178:
        return 0xff;
    }
    return c;
  }
};

156 157 158 159 160 161 162 163 164 165 166 167 168
enum class Utf8Variant : uint8_t {
  kLossyUtf8,  // Lossy UTF-8: Any byte sequence can be decoded without
               // error, replacing invalid UTF-8 with the replacement
               // character (U+FFFD).  Any sequence of codepoints can be
               // encoded without error, replacing surrogates with U+FFFD.
#if V8_ENABLE_WEBASSEMBLY
  kUtf8,  // UTF-8.  Decoding an invalid byte sequence or encoding a
          // surrogate codepoint signals an error.
  kWtf8,  // WTF-8: like UTF-8, but allows isolated (but not paired)
          // surrogate codepoints to be encoded and decoded.
#endif
};

169
class V8_EXPORT_PRIVATE Utf8 {
170
 public:
171 172
  using State = Utf8DfaDecoder::State;

173
  static inline uchar Length(uchar chr, int previous);
174
  static inline unsigned EncodeOneByte(char* out, uint8_t c);
175
  static inline unsigned Encode(char* out, uchar c, int previous,
176
                                bool replace_invalid = false);
177
  static uchar CalculateValue(const byte* str, size_t length, size_t* cursor);
178 179 180

  // The unicode replacement character, used to signal invalid unicode
  // sequences (e.g. an orphan surrogate) when converting to a UTF-8 encoding.
181
  static const uchar kBadChar = 0xFFFD;
182 183
  static const uchar kBufferEmpty = 0x0;
  static const uchar kIncomplete = 0xFFFFFFFC;  // any non-valid code point.
184 185 186
  static const unsigned kMaxEncodedSize = 4;
  static const unsigned kMaxOneByteChar = 0x7f;
  static const unsigned kMaxTwoByteChar = 0x7ff;
187
  static const unsigned kMaxThreeByteChar = 0xffff;
188
  static const unsigned kMaxFourByteChar = 0x1fffff;
189

190 191 192 193
  // A single surrogate is coded as a 3 byte UTF-8 sequence, but two together
  // that match are coded as a 4 byte UTF-8 sequence.
  static const unsigned kBytesSavedByCombiningSurrogates = 2;
  static const unsigned kSizeOfUnmatchedSurrogate = 3;
194 195
  // The maximum size a single UTF-16 code unit may take up when encoded as
  // UTF-8.
196
  static const unsigned kMax16BitCodeUnitSize = 3;
197 198 199
  // The maximum size a single UTF-16 code unit known to be in the range
  // [0,0xff] may take up when encoded as UTF-8.
  static const unsigned kMax8BitCodeUnitSize = 2;
200
  static inline uchar ValueOf(const byte* str, size_t length, size_t* cursor);
clemensh's avatar
clemensh committed
201

202
  using Utf8IncrementalBuffer = uint32_t;
203 204
  static inline uchar ValueOfIncremental(const byte** cursor, State* state,
                                         Utf8IncrementalBuffer* buffer);
205
  static uchar ValueOfIncrementalFinish(State* state);
206

clemensh's avatar
clemensh committed
207 208 209
  // Excludes non-characters from the set of valid code points.
  static inline bool IsValidCharacter(uchar c);

210 211 212 213 214 215 216 217 218
  // Validate if the input has a valid utf-8 encoding. Unlike JS source code
  // this validation function will accept any unicode code point, including
  // kBadChar and BOMs.
  //
  // This method checks for:
  // - valid utf-8 endcoding (e.g. no over-long encodings),
  // - absence of surrogates,
  // - valid code point range.
  static bool ValidateEncoding(const byte* str, size_t length);
219 220
};

221
#if V8_ENABLE_WEBASSEMBLY
222
class V8_EXPORT_PRIVATE Wtf8 {
223 224 225 226 227 228 229 230 231 232 233 234
 public:
  // Validate that the input has a valid WTF-8 encoding.
  //
  // This method checks for:
  // - valid utf-8 endcoding (e.g. no over-long encodings),
  // - absence of surrogate pairs,
  // - valid code point range.
  //
  // In terms of the WTF-8 specification (https://simonsapin.github.io/wtf-8/),
  // this function checks for a valid "generalized UTF-8" sequence, with the
  // additional constraint that surrogate pairs are not allowed.
  static bool ValidateEncoding(const byte* str, size_t length);
235 236 237

  static void ScanForSurrogates(const v8::base::Vector<const byte>& wtf8,
                                std::vector<size_t>* surrogate_offsets);
238 239 240
};
#endif  // V8_ENABLE_WEBASSEMBLY

241 242 243 244 245 246
struct Uppercase {
  static bool Is(uchar c);
};
struct Letter {
  static bool Is(uchar c);
};
247
#ifndef V8_INTL_SUPPORT
248
struct V8_EXPORT_PRIVATE ID_Start {
249 250
  static bool Is(uchar c);
};
251
struct V8_EXPORT_PRIVATE ID_Continue {
252 253
  static bool Is(uchar c);
};
254
struct V8_EXPORT_PRIVATE WhiteSpace {
255 256
  static bool Is(uchar c);
};
257
#endif  // !V8_INTL_SUPPORT
258 259 260 261 262

// LineTerminator:       'JS_Line_Terminator' in point.properties
// ES#sec-line-terminators lists exactly 4 code points:
// LF (U+000A), CR (U+000D), LS(U+2028), PS(U+2029)
V8_INLINE bool IsLineTerminator(uchar c) {
263
  return c == 0x000A || c == 0x000D || c == 0x2028 || c == 0x2029;
264 265
}

266 267 268 269
V8_INLINE bool IsStringLiteralLineTerminator(uchar c) {
  return c == 0x000A || c == 0x000D;
}

270
#ifndef V8_INTL_SUPPORT
lybvinci's avatar
lybvinci committed
271
struct V8_EXPORT_PRIVATE ToLowercase {
272
  static const int kMaxWidth = 3;
273
  static const bool kIsToLower = true;
274
  static int Convert(uchar c, uchar n, uchar* result, bool* allow_caching_ptr);
275
};
lybvinci's avatar
lybvinci committed
276
struct V8_EXPORT_PRIVATE ToUppercase {
277
  static const int kMaxWidth = 3;
278
  static const bool kIsToLower = false;
279
  static int Convert(uchar c, uchar n, uchar* result, bool* allow_caching_ptr);
280
};
281
struct V8_EXPORT_PRIVATE Ecma262Canonicalize {
282
  static const int kMaxWidth = 1;
283
  static int Convert(uchar c, uchar n, uchar* result, bool* allow_caching_ptr);
284
};
285
struct V8_EXPORT_PRIVATE Ecma262UnCanonicalize {
286
  static const int kMaxWidth = 4;
287
  static int Convert(uchar c, uchar n, uchar* result, bool* allow_caching_ptr);
288
};
289
struct V8_EXPORT_PRIVATE CanonicalizationRange {
290
  static const int kMaxWidth = 1;
291
  static int Convert(uchar c, uchar n, uchar* result, bool* allow_caching_ptr);
292
};
293
#endif  // !V8_INTL_SUPPORT
294 295 296

}  // namespace unibrow

297
#endif  // V8_STRINGS_UNICODE_H_