-
Notifications
You must be signed in to change notification settings - Fork 0
/
pp
executable file
·70 lines (61 loc) · 1.35 KB
/
pp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/bin/bash
set -o nounset -o pipefail -o errexit
INCLUDE=()
INCLUDE+=("stddef.h")
INCLUDE+=("linux/fcntl.h")
INCLUDE+=("signal.h")
INCLUDE+=("errno.h")
INCLUDE+=("linux/unistd.h")
INCLUDE+=("linux/seccomp.h" "linux/audit.h")
INCLUDE+=("sys/mman.h" "sys/ioctl.h")
LONG=${PP_LONG-l}
FMT=%${LONG}d
NEWLINE='\n'
while getopts "nxud-" OPT; do
case $OPT in
n) NEWLINE= ;;
x) FMT=0x%${LONG}x ;;
u) FMT=%${LONG}u ;;
d) FMT=%${LONG}d ;;
-) break ;;
?) exit 2 ;;
esac
done
shift $((OPTIND-1))
src() {
for i in "${INCLUDE[@]}"; do
echo "#include <$i>"
done
cat <<EOF
#include <stdio.h>
int main() { return printf("$FMT$NEWLINE", $1), 0; }
EOF
}
expression() {
if command -v tcc > /dev/null; then
src "$1" | tcc -run -
else
TMP=$(mktemp -d)
trap 'rm -rf $TMP' EXIT
src "$1" > "$TMP/a.c"
cc -w -o "$TMP/a" "$TMP/a.c"
"$TMP/a"
fi
}
if [ "${1--}" == "-" ] || [ -f "$1" ]; then
cat "${1--}" | python3 <(cat <<EOF
import re
import sys
import subprocess
def expr(m):
p = subprocess.run(["$0", "-nx", m.group(1)], check=True, capture_output=True, text=True)
return p.stdout
i = sys.stdin.read()
o = re.sub(r'\\$\\\$([^\\$]+)\\$\\$', expr, i)
o = re.sub(r'\\\$([a-zA-Z0-9_]+)', expr, o)
sys.stdout.write(o)
EOF
)
else
expression "$1"
fi