Skip to content

Instantly share code, notes, and snippets.

@aniruddha-a
Last active February 13, 2019 04:18
C REPL
#!/bin/bash
# A REPL for C
# Mon Feb 11, 2019
# Aniruddha. A (aniruddha.a@gmail.com)
if [[ -z $(which gcc) ]]; then
echo gcc not installed
exit 1
fi
readonly FG_BLUE=""
readonly FG_RESET=""
readonly FG_GREEN=""
readonly FG_YELLOW=""
readonly FG_RED=""
readonly LPS1="${FG_BLUE}C> $FG_RESET"
readonly LPS2="${FG_YELLOW}C>> $FG_RESET"
readonly TMPB=$(mktemp --suffix='_creplbuf')
readonly TMPF=$(mktemp --suffix='_crepl.c')
readonly HIST=$(mktemp --suffix='_creplhist')
LPS=$LPS1
cleanup() {
rm -f /tmp/{*_crepl.c,*_creplbuf,*_creplhist}
exit 0
}
trap cleanup SIGINT SIGTERM SIGHUP EXIT
create_tempf() {
truncate -s 0 $TMPF
for i in stdio stdlib stdarg stdbool stddef stdfix stdint string strings limits; do
echo "#include<${i}.h>" >> $TMPF
done
echo "int main() {" >> $TMPF
cat $TMPB >> $TMPF
echo "return 0; }" >> $TMPF
}
dorun() {
local EOUT=$(mktemp --suffix='_crepltmp')
rm -f a.out
create_tempf
gcc $TMPF >& $EOUT
if [[ $? -ne 0 ]]; then
LPS=$LPS2
else
echo -en "$FG_RED"
cat $EOUT | sed "s|$TMPF|<code>|"
./a.out
rm -f a.out
echo -en "$FG_RESET"
LPS=$LPS1
fi
rm -f $EOUT
}
echo -e "Help:\n.clear - start afresh\n.quit - end\n"
while [[ true ]]; do
read -r LINE < <($(dirname $0)/rl -p "$LPS" -H $HIST \
"for(i=0;i<n;i++){}" "while(){}" "return 0;" \
int char float double \
printf scanf strlen sizeof exit struct typedef void true false bool \
.clear .exit .quit)
if [[ $LINE =~ ^[.] ]]; then
if [[ $LINE == '.clear' ]]; then
truncate -s 0 $TMPB
elif [[ $LINE == '.exit' ]] || [[ $LINE == '.quit' ]]; then
rm -f $TMPB $TMPF
echo Bye
exit 0
fi
else
echo -E "$LINE" >> $TMPB
dorun
fi
done
@aniruddha-a
Copy link
Author

aniruddha-a commented Feb 12, 2019

To use:
Compile the C program in the other gist (rl.c) as rl, and save it to the same directory as this script.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment