#!/usr/bin/python

##
# Copyright 2010-2017 JetBrains s.r.o.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

#
# (lldb) command script import llvmDebugInfoC/src/scripts/konan_lldb.py
# (lldb) show_variable
#

import lldb
import commands
import optparse
import shlex

def show_variable(debugger, command, result, internal_dict):
    debugger.GetCommandInterpreter().HandleCommand('expr -- Konan_DebugPrint(%s)' % command, result)
    return result

def __lldb_init_module(debugger, internal_dict):
    debugger.HandleCommand('command script add -f konan_lldb.show_variable show_variable')


@@ -682,20 +682,24 @@
  (lldb) 
-show
+p kotlin
 _variabl
@@ -727,364 +727,1136 @@
 rt c
-ommands%0Aimport optparse%0Aimport shlex%0A%0Adef show_variable(debugger, command, result, internal_dict):%0A    debugger.GetCommandInterpreter().HandleCommand('expr -- Konan_DebugPrint(%25s)' %25 command, result)%0A    return result%0A%0Adef __lldb_init_module(debugger, internal_dict):%0A    debugger.HandleCommand('command script add -f konan_lldb.show_variable show_variable
+types%0A%0Adef kotlin_object_type_summary(lldb_val, internal_dict):%0A    %22%22%22Hook that is run by lldb to display a Kotlin object.%22%22%22%0A    fallback = lldb_val.GetValue()%0A    if str(lldb_val.type) != %22struct ObjHeader *%22:%0A        return fallback%0A%0A    def evaluate(expr):%0A        return lldb_val.GetTarget().EvaluateExpression(expr, lldb.SBExpressionOptions())%0A%0A    buff_len = evaluate(%0A        %22Konan_DebugObjectToUtf8Array((struct ObjHeader *) %25s, Konan_DebugBuffer(), Konan_DebugBufferSize());%22 %25 lldb_val.GetValueAsUnsigned()%0A    ).GetValueAsUnsigned()%0A%0A    if not buff_len:%0A        return fallback%0A%0A    buff_addr = evaluate(%22Konan_DebugBuffer()%22).GetValueAsUnsigned()%0A%0A    error = lldb.SBError()%0A    s = lldb_val.GetProcess().ReadCStringFromMemory(buff_addr, buff_len, error)%0A    return s if error.Success() else fallback%0A%0A%0Adef __lldb_init_module(debugger, internal_dict):%0A    debugger.HandleCommand('%5C%0A        type summary add %5C%0A        --no-value %5C%0A        --python-function konan_lldb.kotlin_object_type_summary %5C%0A        -x %22ObjHeader %5C*%22 %5C%0A        --category Kotlin%5C%0A    ')%0A    debugger.HandleCommand('type category enable Kotlin
 ')%0A
-%0A

add Kotlin Object pretty printers for lldb