Skip to content

Commit

Permalink
Introduce line editor library.
Browse files Browse the repository at this point in the history
This library will be used by clang-query. I can imagine LLDB becoming another
client of this library, so I think LLVM is a sensible place for it to live.
It wraps libedit, and adds tab completion support.

The code is loosely based on the line editor bits in LLDB, with a few
improvements:

 - Polymorphism for retrieving the list of tab completions, based on
   the concept pattern from the new pass manager.

 - Tab completion doesn't corrupt terminal output if the input covers
   multiple lines. Unfortunately this can only be done in a truly horrible
   way, as far as I can tell. But since the alternative is to implement our
   own line editor (which I don't think LLVM should be in the business of
   doing, at least for now) I think it may be acceptable.

 - Includes a fallback for the case where the user doesn't have libedit
   installed.

Note that this uses C stdio, mainly because libedit also uses C stdio.

Differential Revision: http://llvm-reviews.chandlerc.com/D2200

llvm-svn: 200595
  • Loading branch information
pcc committed Jan 31, 2014
1 parent f7d4101 commit c7d437c
Show file tree
Hide file tree
Showing 18 changed files with 778 additions and 5 deletions.
18 changes: 18 additions & 0 deletions llvm/autoconf/configure.ac
Original file line number Diff line number Diff line change
Expand Up @@ -1190,6 +1190,17 @@ AC_ARG_ENABLE(terminfo,AS_HELP_STRING(
esac],
llvm_cv_enable_terminfo="yes")

dnl --enable-libedit: check whether the user wants to turn off libedit.
AC_ARG_ENABLE(libedit,AS_HELP_STRING(
[--enable-libedit],
[Use libedit if available (default is YES)]),
[case "$enableval" in
yes) llvm_cv_enable_libedit="yes" ;;
no) llvm_cv_enable_libedit="no" ;;
*) AC_MSG_ERROR([Invalid setting for --enable-libedit. Use "yes" or "no"]) ;;
esac],
llvm_cv_enable_libedit="yes")

dnl --enable-libffi : check whether the user wants to turn off libffi:
AC_ARG_ENABLE(libffi,AS_HELP_STRING(
--enable-libffi,[Check for the presence of libffi (default is NO)]),
Expand Down Expand Up @@ -1506,6 +1517,13 @@ if test "$llvm_cv_enable_terminfo" = "yes" ; then
[Define if the setupterm() function is supported this platform.]))
fi

dnl The libedit library is optional; used by lib/LineEditor
if test "$llvm_cv_enable_libedit" = "yes" ; then
AC_SEARCH_LIBS(el_init,edit,
AC_DEFINE([HAVE_LIBEDIT],[1],
[Define if libedit is available on this platform.]))
fi

dnl libffi is optional; used to call external functions from the interpreter
if test "$llvm_cv_enable_libffi" = "yes" ; then
AC_SEARCH_LIBS(ffi_call,ffi,AC_DEFINE([HAVE_FFI_CALL],[1],
Expand Down
1 change: 1 addition & 0 deletions llvm/cmake/config-ix.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ if( NOT PURE_WINDOWS )
else()
set(HAVE_LIBZ 0)
endif()
check_library_exists(edit el_init "" HAVE_LIBEDIT)
if(LLVM_ENABLE_TERMINFO)
set(HAVE_TERMINFO 0)
foreach(library tinfo terminfo curses ncurses ncursesw)
Expand Down
123 changes: 122 additions & 1 deletion llvm/configure
Original file line number Diff line number Diff line change
Expand Up @@ -1451,6 +1451,7 @@ Optional Features:
all,auto,none,{binding-name} (default=auto)
--enable-terminfo Query the terminfo database if available (default is
YES)
--enable-libedit Use libedit if available (default is YES)
--enable-libffi Check for the presence of libffi (default is NO)
--enable-ltdl-install install libltdl

Expand Down Expand Up @@ -5681,6 +5682,20 @@ else
fi


# Check whether --enable-libedit was given.
if test "${enable_libedit+set}" = set; then
enableval=$enable_libedit; case "$enableval" in
yes) llvm_cv_enable_libedit="yes" ;;
no) llvm_cv_enable_libedit="no" ;;
*) { { echo "$as_me:$LINENO: error: Invalid setting for --enable-libedit. Use \"yes\" or \"no\"" >&5
echo "$as_me: error: Invalid setting for --enable-libedit. Use \"yes\" or \"no\"" >&2;}
{ (exit 1); exit 1; }; } ;;
esac
else
llvm_cv_enable_libedit="yes"
fi


# Check whether --enable-libffi was given.
if test "${enable_libffi+set}" = set; then
enableval=$enable_libffi; case "$enableval" in
Expand Down Expand Up @@ -10663,7 +10678,7 @@ else
lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
lt_status=$lt_dlunknown
cat > conftest.$ac_ext <<EOF
#line 10666 "configure"
#line 10681 "configure"
#include "confdefs.h"

#if HAVE_DLFCN_H
Expand Down Expand Up @@ -12558,6 +12573,112 @@ fi

fi

if test "$llvm_cv_enable_libedit" = "yes" ; then
{ echo "$as_me:$LINENO: checking for library containing el_init" >&5
echo $ECHO_N "checking for library containing el_init... $ECHO_C" >&6; }
if test "${ac_cv_search_el_init+set}" = set; then
echo $ECHO_N "(cached) $ECHO_C" >&6
else
ac_func_search_save_LIBS=$LIBS
cat >conftest.$ac_ext <<_ACEOF
/* confdefs.h. */
_ACEOF
cat confdefs.h >>conftest.$ac_ext
cat >>conftest.$ac_ext <<_ACEOF
/* end confdefs.h. */

/* Override any GCC internal prototype to avoid an error.
Use char because int might match the return type of a GCC
builtin and then its argument prototype would still apply. */
#ifdef __cplusplus
extern "C"
#endif
char el_init ();
int
main ()
{
return el_init ();
;
return 0;
}
_ACEOF
for ac_lib in '' edit; do
if test -z "$ac_lib"; then
ac_res="none required"
else
ac_res=-l$ac_lib
LIBS="-l$ac_lib $ac_func_search_save_LIBS"
fi
rm -f conftest.$ac_objext conftest$ac_exeext
if { (ac_try="$ac_link"
case "(($ac_try" in
*\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
*) ac_try_echo=$ac_try;;
esac
eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
(eval "$ac_link") 2>conftest.er1
ac_status=$?
grep -v '^ *+' conftest.er1 >conftest.err
rm -f conftest.er1
cat conftest.err >&5
echo "$as_me:$LINENO: \$? = $ac_status" >&5
(exit $ac_status); } &&
{ ac_try='test -z "$ac_c_werror_flag" || test ! -s conftest.err'
{ (case "(($ac_try" in
*\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
*) ac_try_echo=$ac_try;;
esac
eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
(eval "$ac_try") 2>&5
ac_status=$?
echo "$as_me:$LINENO: \$? = $ac_status" >&5
(exit $ac_status); }; } &&
{ ac_try='test -s conftest$ac_exeext'
{ (case "(($ac_try" in
*\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
*) ac_try_echo=$ac_try;;
esac
eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
(eval "$ac_try") 2>&5
ac_status=$?
echo "$as_me:$LINENO: \$? = $ac_status" >&5
(exit $ac_status); }; }; then
ac_cv_search_el_init=$ac_res
else
echo "$as_me: failed program was:" >&5
sed 's/^/| /' conftest.$ac_ext >&5


fi

rm -f core conftest.err conftest.$ac_objext \
conftest$ac_exeext
if test "${ac_cv_search_el_init+set}" = set; then
break
fi
done
if test "${ac_cv_search_el_init+set}" = set; then
:
else
ac_cv_search_el_init=no
fi
rm conftest.$ac_ext
LIBS=$ac_func_search_save_LIBS
fi
{ echo "$as_me:$LINENO: result: $ac_cv_search_el_init" >&5
echo "${ECHO_T}$ac_cv_search_el_init" >&6; }
ac_res=$ac_cv_search_el_init
if test "$ac_res" != no; then
test "$ac_res" = "none required" || LIBS="$ac_res $LIBS"

cat >>confdefs.h <<\_ACEOF
#define HAVE_LIBEDIT 1
_ACEOF

fi

fi

if test "$llvm_cv_enable_libffi" = "yes" ; then
{ echo "$as_me:$LINENO: checking for library containing ffi_call" >&5
echo $ECHO_N "checking for library containing ffi_call... $ECHO_C" >&6; }
Expand Down
3 changes: 3 additions & 0 deletions llvm/include/llvm/Config/config.h.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,9 @@
/* Define to 1 if you have the 'z' library (-lz). */
#cmakedefine HAVE_LIBZ ${HAVE_LIBZ}

/* Define to 1 if you have the 'edit' library (-ledit). */
#cmakedefine HAVE_LIBEDIT ${HAVE_LIBEDIT}

/* Define to 1 if you have the <limits.h> header file. */
#cmakedefine HAVE_LIMITS_H ${HAVE_LIMITS_H}

Expand Down
3 changes: 3 additions & 0 deletions llvm/include/llvm/Config/config.h.in
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,9 @@
/* Define if you have the libdl library or equivalent. */
#undef HAVE_LIBDL

/* Define if libedit is available on this platform. */
#undef HAVE_LIBEDIT

/* Define to 1 if you have the `imagehlp' library (-limagehlp). */
#undef HAVE_LIBIMAGEHLP

Expand Down
152 changes: 152 additions & 0 deletions llvm/include/llvm/LineEditor/LineEditor.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
//===-- llvm/LineEditor/LineEditor.h - line editor --------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#ifndef LLVM_LINEEDITOR_LINEEDITOR_H
#define LLVM_LINEEDITOR_LINEEDITOR_H

#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/OwningPtr.h"
#include <stdio.h>
#include <string>
#include <vector>

namespace llvm {

class LineEditor {
public:
/// Create a LineEditor object.
///
/// \param ProgName The name of the current program. Used to form a default
/// prompt.
/// \param HistoryPath Path to the file in which to store history data, if
/// possible.
/// \param In The input stream used by the editor.
/// \param Out The output stream used by the editor.
/// \param Err The error stream used by the editor.
LineEditor(StringRef ProgName, StringRef HistoryPath = "", FILE *In = stdin,
FILE *Out = stdout, FILE *Err = stderr);
~LineEditor();

/// Reads a line.
///
/// \return The line, or llvm::Optional<std::string>() on EOF.
llvm::Optional<std::string> readLine() const;

void saveHistory();
void loadHistory();

static std::string getDefaultHistoryPath(StringRef ProgName);

/// The action to perform upon a completion request.
struct CompletionAction {
enum ActionKind {
/// Insert Text at the cursor position.
AK_Insert,
/// Show Completions, or beep if the list is empty.
AK_ShowCompletions
};

ActionKind Kind;

/// The text to insert.
std::string Text;

/// The list of completions to show.
std::vector<std::string> Completions;
};

/// A possible completion at a given cursor position.
struct Completion {
Completion() {}
Completion(const std::string &TypedText, const std::string &DisplayText)
: TypedText(TypedText), DisplayText(DisplayText) {}

/// The text to insert. If the user has already input some of the
/// completion, this should only include the rest of the text.
std::string TypedText;

/// A description of this completion. This may be the completion itself, or
/// maybe a summary of its type or arguments.
std::string DisplayText;
};

/// Set the completer for this LineEditor. A completer is a function object
/// which takes arguments of type StringRef (the string to complete) and
/// size_t (the zero-based cursor position in the StringRef) and returns a
/// CompletionAction.
template <typename T> void setCompleter(T Comp) {
Completer.reset(new CompleterModel<T>(Comp));
}

/// Set the completer for this LineEditor to the given list completer.
/// A list completer is a function object which takes arguments of type
/// StringRef (the string to complete) and size_t (the zero-based cursor
/// position in the StringRef) and returns a std::vector<Completion>.
template <typename T> void setListCompleter(T Comp) {
Completer.reset(new ListCompleterModel<T>(Comp));
}

/// Use the current completer to produce a CompletionAction for the given
/// completion request. If the current completer is a list completer, this
/// will return an AK_Insert CompletionAction if each completion has a common
/// prefix, or an AK_ShowCompletions CompletionAction otherwise.
///
/// \param Buffer The string to complete
/// \param Pos The zero-based cursor position in the StringRef
CompletionAction getCompletionAction(StringRef Buffer, size_t Pos) const;

const std::string &getPrompt() const { return Prompt; }
void setPrompt(const std::string &P) { Prompt = P; }

// Public so callbacks in LineEditor.cpp can use it.
struct InternalData;

private:
std::string Prompt;
std::string HistoryPath;
OwningPtr<InternalData> Data;

struct CompleterConcept {
virtual ~CompleterConcept();
virtual CompletionAction complete(StringRef Buffer, size_t Pos) const = 0;
};

struct ListCompleterConcept : CompleterConcept {
~ListCompleterConcept();
CompletionAction complete(StringRef Buffer, size_t Pos) const;
static std::string getCommonPrefix(const std::vector<Completion> &Comps);
virtual std::vector<Completion> getCompletions(StringRef Buffer,
size_t Pos) const = 0;
};

template <typename T>
struct CompleterModel : CompleterConcept {
CompleterModel(T Value) : Value(Value) {}
CompletionAction complete(StringRef Buffer, size_t Pos) const {
return Value(Buffer, Pos);
}
T Value;
};

template <typename T>
struct ListCompleterModel : ListCompleterConcept {
ListCompleterModel(T Value) : Value(Value) {}
std::vector<Completion> getCompletions(StringRef Buffer, size_t Pos) const {
return Value(Buffer, Pos);
}
T Value;
};

llvm::OwningPtr<const CompleterConcept> Completer;
};

}

#endif
1 change: 1 addition & 0 deletions llvm/lib/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,4 @@ add_subdirectory(DebugInfo)
add_subdirectory(ExecutionEngine)
add_subdirectory(Target)
add_subdirectory(AsmParser)
add_subdirectory(LineEditor)
2 changes: 1 addition & 1 deletion llvm/lib/LLVMBuild.txt
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
;===------------------------------------------------------------------------===;

[common]
subdirectories = Analysis AsmParser Bitcode CodeGen DebugInfo ExecutionEngine Linker IR IRReader LTO MC Object Option Support TableGen Target Transforms
subdirectories = Analysis AsmParser Bitcode CodeGen DebugInfo ExecutionEngine LineEditor Linker IR IRReader LTO MC Object Option Support TableGen Target Transforms

[component_0]
type = Group
Expand Down
7 changes: 7 additions & 0 deletions llvm/lib/LineEditor/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
add_llvm_library(LLVMLineEditor
LineEditor.cpp
)

if(HAVE_LIBEDIT)
target_link_libraries(LLVMLineEditor edit)
endif()
Loading

0 comments on commit c7d437c

Please sign in to comment.