1#!/bin/bash
2
3# Copyright 2019 The Go Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style
5# license that can be found in the LICENSE file.
6
7set -e
8shopt -s nullglob
9
10winerror="$(printf '%s\n' "/mnt/c/Program Files (x86)/Windows Kits/"/*/Include/*/shared/winerror.h | sort -Vr | head -n 1)"
11[[ -n $winerror ]] || { echo "Unable to find winerror.h" >&2; exit 1; }
12
13declare -A errors
14
15{
16	echo "// Code generated by 'mkerrors.bash'; DO NOT EDIT."
17	echo
18	echo "package windows"
19	echo "import \"syscall\""
20	echo "const ("
21
22	while read -r line; do
23		unset vtype
24		if [[ $line =~ ^#define\ +([A-Z0-9_]+k?)\ +([A-Z0-9_]+\()?([A-Z][A-Z0-9_]+k?)\)? ]]; then
25			key="${BASH_REMATCH[1]}"
26			value="${BASH_REMATCH[3]}"
27		elif [[ $line =~ ^#define\ +([A-Z0-9_]+k?)\ +([A-Z0-9_]+\()?((0x)?[0-9A-Fa-f]+)L?\)? ]]; then
28			key="${BASH_REMATCH[1]}"
29			value="${BASH_REMATCH[3]}"
30			vtype="${BASH_REMATCH[2]}"
31		elif [[ $line =~ ^#define\ +([A-Z0-9_]+k?)\ +\(\(([A-Z]+)\)((0x)?[0-9A-Fa-f]+)L?\) ]]; then
32			key="${BASH_REMATCH[1]}"
33			value="${BASH_REMATCH[3]}"
34			vtype="${BASH_REMATCH[2]}"
35		else
36			continue
37		fi
38		[[ -n $key && -n $value ]] || continue
39		[[ -z ${errors["$key"]} ]] || continue
40		errors["$key"]="$value"
41		if [[ -v vtype ]]; then
42			if [[ $key == FACILITY_* || $key == NO_ERROR ]]; then
43				vtype=""
44			elif [[ $vtype == *HANDLE* || $vtype == *HRESULT* ]]; then
45				vtype="Handle"
46			else
47				vtype="syscall.Errno"
48			fi
49			last_vtype="$vtype"
50		else
51			vtype=""
52			if [[ $last_vtype == Handle && $value == NO_ERROR ]]; then
53				value="S_OK"
54			elif [[ $last_vtype == syscall.Errno && $value == NO_ERROR ]]; then
55				value="ERROR_SUCCESS"
56			fi
57		fi
58
59		echo "$key $vtype = $value"
60	done < "$winerror"
61
62	echo ")"
63} | gofmt > "zerrors_windows.go"
64