class Opal::Nodes::StringNode
def compile
def compile string_value = value sanitized_value = string_value.inspect.gsub(/\\u\{([0-9a-f]+)\}/) do code_point = Regexp.last_match(1).to_i(16) to_utf16(code_point) end push translate_escape_chars(sanitized_value) if RUBY_ENGINE != 'opal' encoding = string_value.encoding unless encoding == Encoding::UTF_8 helper :enc wrap "$enc(", ", \"#{encoding.name}\")" end end unless value.valid_encoding? helper :binary wrap "$binary(", ")" end end
def to_utf16(code_point)
def to_utf16(code_point) ten_bits = 0b1111111111 u = ->(code_unit) { '\\u' + code_unit.to_s(16).upcase } return u.call(code_point) if code_point <= 0xFFFF code_point -= 0x10000 # Shift right to get to most significant 10 bits lead_surrogate = 0xD800 + (code_point >> 10) # Mask to get least significant 10 bits tail_surrogate = 0xDC00 + (code_point & ten_bits) u.call(lead_surrogate) + u.call(tail_surrogate) end
def translate_escape_chars(inspect_string)
def translate_escape_chars(inspect_string) inspect_string.gsub(ESCAPE_REGEX) do |original| if Regexp.last_match(1).length.even? original else Regexp.last_match(1).chop + ESCAPE_CHARS[Regexp.last_match(2)] end end end