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
10[[ $# -eq 1 ]] || { echo "Usage: $0 OUTPUT_FILE.go" >&2; exit 1; }
11winerror="$(printf '%s\n' "/mnt/c/Program Files (x86)/Windows Kits/"/*/Include/*/shared/winerror.h | sort -Vr | head -n 1)"
12[[ -n $winerror ]] || { echo "Unable to find winerror.h" >&2; exit 1; }
13
14declare -A errors
15
16{
17	echo "// Code generated by 'go generate'; DO NOT EDIT."
18	echo
19	echo "package windows"
20	echo "import \"syscall\""
21	echo "const ("
22
23	while read -r line; do
24		unset vtype
25		if [[ $line =~ ^#define\ +([A-Z0-9_]+k?)\ +([A-Z0-9_]+\()?([A-Z][A-Z0-9_]+k?)\)? ]]; then
26			key="${BASH_REMATCH[1]}"
27			value="${BASH_REMATCH[3]}"
28		elif [[ $line =~ ^#define\ +([A-Z0-9_]+k?)\ +([A-Z0-9_]+\()?((0x)?[0-9A-Fa-f]+)L?\)? ]]; then
29			key="${BASH_REMATCH[1]}"
30			value="${BASH_REMATCH[3]}"
31			vtype="${BASH_REMATCH[2]}"
32		elif [[ $line =~ ^#define\ +([A-Z0-9_]+k?)\ +\(\(([A-Z]+)\)((0x)?[0-9A-Fa-f]+)L?\) ]]; then
33			key="${BASH_REMATCH[1]}"
34			value="${BASH_REMATCH[3]}"
35			vtype="${BASH_REMATCH[2]}"
36		else
37			continue
38		fi
39		[[ -n $key && -n $value ]] || continue
40		[[ -z ${errors["$key"]} ]] || continue
41		errors["$key"]="$value"
42		if [[ -v vtype ]]; then
43			if [[ $key == FACILITY_* || $key == NO_ERROR ]]; then
44				vtype=""
45			elif [[ $vtype == *HANDLE* || $vtype == *HRESULT* ]]; then
46				vtype="Handle"
47			else
48				vtype="syscall.Errno"
49			fi
50			last_vtype="$vtype"
51		else
52			vtype=""
53			if [[ $last_vtype == Handle && $value == NO_ERROR ]]; then
54				value="S_OK"
55			elif [[ $last_vtype == syscall.Errno && $value == NO_ERROR ]]; then
56				value="ERROR_SUCCESS"
57			fi
58		fi
59
60		echo "$key $vtype = $value"
61	done < "$winerror"
62
63	echo ")"
64} | gofmt > "$1"
65