c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. #!/bin/sh
  2. # https://causal.agency/bin/c.html
  3. set -eu
  4. temp=$(mktemp -d)
  5. trap 'rm -r "${temp}"' EXIT
  6. exec 3>>"${temp}/run.c"
  7. cat >&3 <<EOF
  8. #include <assert.h>
  9. #include <ctype.h>
  10. #include <errno.h>
  11. #include <inttypes.h>
  12. #include <limits.h>
  13. #include <locale.h>
  14. #include <math.h>
  15. #include <stdbool.h>
  16. #include <stdint.h>
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. #include <string.h>
  20. #include <time.h>
  21. #include <wchar.h>
  22. #include <wctype.h>
  23. #include <dirent.h>
  24. #include <fcntl.h>
  25. #include <strings.h>
  26. #include <unistd.h>
  27. EOF
  28. expr=
  29. type=
  30. while getopts 'e:i:t' opt; do
  31. case "${opt}" in
  32. (e) expr=$OPTARG;;
  33. (i) echo "#include <${OPTARG}>" >&3;;
  34. (t) type=1;;
  35. (?) exit 1;;
  36. esac
  37. done
  38. shift $((OPTIND - 1))
  39. cat >&3 <<EOF
  40. int main(int argc, char *argv[]) {
  41. (void)argc;
  42. (void)argv;
  43. $*;
  44. EOF
  45. if [ -n "${type}" ]; then
  46. cat >&3 <<EOF
  47. printf(
  48. _Generic(
  49. ${expr},
  50. char: "(char) ",
  51. char *: "(char *) ",
  52. const char *: "(const char *) ",
  53. wchar_t *: "(wchar_t *) ",
  54. const wchar_t *: "(const wchar_t *) ",
  55. signed char: "(signed char) ",
  56. short: "(short) ",
  57. int: "(int) ",
  58. long: "(long) ",
  59. long long: "(long long) ",
  60. unsigned char: "(unsigned char) ",
  61. unsigned short: "(unsigned short) ",
  62. unsigned int: "(unsigned int) ",
  63. unsigned long: "(unsigned long) ",
  64. unsigned long long: "(unsigned long long) ",
  65. float: "(float) ",
  66. double: "(double) ",
  67. long double: "(long double) ",
  68. default: "(void *) "
  69. )
  70. );
  71. EOF
  72. fi
  73. if [ -n "${expr}" ]; then
  74. cat >&3 <<EOF
  75. printf(
  76. _Generic(
  77. ${expr},
  78. char: "%c\n",
  79. char *: "%s\n",
  80. const char *: "%s\n",
  81. wchar_t *: "%ls\n",
  82. const wchar_t *: "%ls\n",
  83. signed char: "%hhd\n",
  84. short: "%hd\n",
  85. int: "%d\n",
  86. long: "%ld\n",
  87. long long: "%lld\n",
  88. unsigned char: "%hhu\n",
  89. unsigned short: "%hu\n",
  90. unsigned int: "%u\n",
  91. unsigned long: "%lu\n",
  92. unsigned long long: "%llu\n",
  93. float: "%g\n",
  94. double: "%g\n",
  95. long double: "%Lg\n",
  96. default: "%p\n"
  97. ),
  98. ${expr}
  99. );
  100. EOF
  101. fi
  102. if [ $# -eq 0 -a -z "${expr}" ]; then
  103. cat >&3
  104. fi
  105. echo '}' >&3
  106. cat >"${temp}/Makefile" <<EOF
  107. CFLAGS += -Wall -Wextra -Wpedantic
  108. EOF
  109. make -s -C "${temp}" run
  110. "${temp}/run"