1#!/bin/sh 2# 3# enumstr.sh - a tool generating a function mapping enumerator to its 4# string representation 5# 6# Copyright (C) 2019 Masatake YAMATO 7# 8# This program is free software; you can redistribute it and/or modify 9# it under the terms of the GNU General Public License as published by 10# the Free Software Foundation; either version 2 of the License, or 11# (at your option) any later version. 12# 13# This program is distributed in the hope that it will be useful, 14# but WITHOUT ANY WARRANTY; without even the implied warranty of 15# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16# GNU General Public License for more details. 17# 18# You should have received a copy of the GNU General Public License 19# along with this program. If not, see <http://www.gnu.org/licenses/>. 20# 21# Usage: 22# 23# ./enumstr.sh <input-file> <enum-name> <funname> [PREFIX_FOR_TRIMMING] [--use-lower-bits-as-is] 24# 25# Example: 26# 27# bash ./misc/enumstr.sh parsers/jscript.c eTokenType tokenTypeName 28# 29column_width=20 30 31echo 'static const char *'"$3"'(enum '$2' e)' 32printf '{ /* Generated by misc/enumstr.sh with cmdline:\n' 33printf ' %s */\n' "$*" 34echo ' switch (e)' 35echo ' {' 36./ctags --quiet --options=NONE --sort=no -o - --languages=C --kinds-C=e --map-C=.h -x --_xformat="%N enum:%s" $1 | grep $2 | while read N S; do 37 n=$N 38 if [ -n "$4" ]; then 39 n=${N#$4} 40 fi 41 printf " case %${column_width}s: return %s;\n" "$N" "\"$n\"" 42done 43shift 4 44if [[ $1 == "--use-lower-bits-as-is" ]]; then 45 printf ' default: %'"$((${column_width} + 3))s;\n" "break" 46else 47 printf ' default: %'"$((${column_width} - 3))s return %s;\n" ' ' "\"UNKNOWN\"" 48fi 49echo ' }' 50if [[ $1 == "--use-lower-bits-as-is" ]]; then 51echo ' static char buf[3];' 52echo ' if (isprint (e))' 53echo ' {' 54echo ' buf[0] = e;' 55echo " buf[1] = '\0';" 56echo ' }' 57echo " else if (e == '\\n')" 58echo ' {' 59echo " buf[0] = '\\\';" 60echo " buf[1] = 'n';" 61echo " buf[2] = '\0';" 62echo ' }' 63echo ' else' 64echo ' {' 65echo " buf[0] = '\0';" 66echo ' }' 67echo ' return buf;' 68fi 69echo '}' 70