Last active
February 13, 2019 04:18
C REPL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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="[34m" | |
readonly FG_RESET="[0m" | |
readonly FG_GREEN="[32m" | |
readonly FG_YELLOW="[1m[33m" | |
readonly FG_RED="[31m" | |
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To use:
Compile the C program in the other gist (
rl.c
) asrl
, and save it to the same directory as this script.