summary refs log tree commit diff
path: root/bin/c.sh
blob: f1143fd32a5ba68a928e4233d78cefb96437a40c (plain) (blame)
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#!/bin/sh
set -eu

temp=$(mktemp -d)
trap 'rm -r "${temp}"' EXIT

exec 3>>"${temp}/run.c"

cat >&3 <<EOF
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <inttypes.h>
#include <limits.h>
#include <locale.h>
#include <math.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <wchar.h>
#include <wctype.h>

#include <fcntl.h>
#include <strings.h>
#include <unistd.h>
EOF

expr=
while getopts 'e:i:' opt; do
	case "${opt}" in
		(e) expr=$OPTARG;;
		(i) echo "#include <${OPTARG}>" >&3;;
		(?) exit 1;;
	esac
done
shift $((OPTIND - 1))

cat >&3 <<EOF
int main(int argc, char *argv[]) {
	(void)argc;
	(void)argv;
	$*;
EOF

if [ -n "${expr}" ]; then
	cat >&3 <<EOF
	printf(
		_Generic(
			${expr},
			char: "%c\n",
			char *: "%s\n",
			const char *: "%s\n",
			wchar_t *: "%ls\n",
			const wchar_t *: "%ls\n",
			signed char: "%hhd\n",
			short: "%hd\n",
			int: "%d\n",
			long: "%ld\n",
			long long: "%lld\n",
			unsigned char: "%hhu\n",
			unsigned short: "%hu\n",
			unsigned int: "%u\n",
			unsigned long: "%lu\n",
			unsigned long long: "%llu\n",
			double: "%g\n",
			default: "%p\n"
		),
		${expr}
	);
EOF
fi

if [ $# -eq 0 -a -z "${expr}" ]; then
	cat >&3
fi

echo '}' >&3

cat >"${temp}/Makefile" <<EOF
CFLAGS += -Wall -Wextra -Wpedantic
EOF

make -s -C "${temp}" run
"${temp}/run"