// Copyright 2024 The Libc Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package libc is a partial reimplementation of C libc in pure Go.
//
// # READ THIS BEFORE UPGRADING
//
// This package is to ccgo what the runtime package is to Go. It is not a
// library you happen to link against, it is the other half of the compiler.
// Code that ccgo produced and the libc it was produced for are one artifact
// split across two modules, and they are only ever tested as a pair.
//
// That is why the version numbers here do not mean what semver says they mean.
// A release that bumps only the patch or the minor number can still change the
// contract between generated code and this package, which by semver's own rules
// it must not. Read every libc version as though it were a major one.
//
// None of this is new. It has been documented for as long as this package has
// carried ccgo's runtime, and it holds for every release. What is new is how it
// fails.
//
// Upgrading libc alone used to change behaviour quietly. It can now stop the
// build. The setjmp/longjmp support changed shape: LongjmpRetval went from an
// integer to a struct naming the jump buffer a longjmp targeted, because a
// region recovering that panic has no other way to tell whether the longjmp was
// meant for it or for a setjmp further out, and recovering one meant for another
// region resumes the program at the wrong place. Code generated by an older ccgo
// does not compile against it, failing on the conversion between LongjmpRetval
// and int32. That is the intended outcome rather than an oversight: a refusal to
// build, in place of a program that would have built and then jumped to the
// wrong setjmp.
//
// This is a correctness fix and there is no backward compatible way to make it.
// Deciding which region a longjmp belongs to needs information the old panic
// value did not carry, so any fix has to change what that value is. Keeping the
// old shape working alongside the new one would leave every consumer silently on
// the broken path, which is the bug.
//
// The remedy is what it has always been, and it is not to pin an old libc and
// hope: recompile your C to Go with a ccgo new enough to depend on the libc you
// want, then use that pair together. If you consume translated code produced by
// someone else, modernc.org/sqlite for instance, take the libc version from that
// package's go.mod and do not bump it on your own just because a newer libc is
// tagged.
package libc // import "modernc.org/libc"

import (
	"math"
	"sync/atomic"
	"unsafe"
)

type integer interface {
	~int | ~int32 | ~int64 | ~uint | ~uint32 | ~uint64 | ~uintptr
}

func X__sync_add_and_fetch[T integer](t *TLS, p uintptr, v T) T {
	switch unsafe.Sizeof(v) {
	case 4:
		return T(atomic.AddInt32((*int32)(unsafe.Pointer(p)), int32(v)))
	case 8:
		return T(atomic.AddInt64((*int64)(unsafe.Pointer(p)), int64(v)))
	default:
		panic(todo(""))
	}
}

func X__sync_sub_and_fetch[T integer](t *TLS, p uintptr, v T) T {
	switch unsafe.Sizeof(v) {
	case 4:
		return T(atomic.AddInt32((*int32)(unsafe.Pointer(p)), -int32(v)))
	case 8:
		return T(atomic.AddInt64((*int64)(unsafe.Pointer(p)), -int64(v)))
	default:
		panic(todo(""))
	}
}

// GoString returns the value of a C string at s.
func GoString(s uintptr) string {
	if s == 0 {
		return ""
	}

	if n := strlen(s); n != 0 {
		return string(unsafe.Slice((*byte)(unsafe.Pointer(s)), n))
	}

	return ""
}

// GoBytes returns a byte slice from a C char* having length len bytes.
func GoBytes(s uintptr, len int) []byte {
	return unsafe.Slice((*byte)(unsafe.Pointer(s)), len)
}

func X__isfinitef(tls *TLS, f float32) int32 {
	d := float64(f)
	if !math.IsInf(d, 0) && !math.IsNaN(d) {
		return 1
	}

	return 0
}

func X__isfinite(tls *TLS, d float64) int32 {
	if !math.IsInf(d, 0) && !math.IsNaN(d) {
		return 1
	}

	return 0
}

func X__isfinitel(tls *TLS, d float64) int32 {
	if !math.IsInf(d, 0) && !math.IsNaN(d) {
		return 1
	}

	return 0
}

func strlen(s uintptr) (r Tsize_t) {
	if s == 0 {
		return 0
	}

	if strlenUseIndexByte {
		return strlenIndexByte(s)
	}

	return strlenWords(s)
}

// size_t strlen(const char *s)
func Xstrlen(t *TLS, s uintptr) (r Tsize_t) {
	if __ccgo_strace {
		trc("t=%v s=%v, (%v:)", t, s, origin(2))
		defer func() { trc("-> %v", r) }()
	}
	return strlen(s)

}

func _strlen(t *TLS, s uintptr) (r Tsize_t) {
	return strlen(s)
}

func X__builtin_ilogb(tls *TLS, x float64) int32 {
	return int32(math.Ilogb(x))
}

func X__builtin_ilogbl(tls *TLS, x float64) int32 {
	return int32(math.Ilogb(x))
}

func X__builtin_ilogbf(tls *TLS, x float32) int32 {
	// Casting to float64 is safe and mathematically correct here.
	// Subnormal float32 values become normal float64 values,
	// which allows math.Ilogb to correctly return their negative exponent.
	return int32(math.Ilogb(float64(x)))
}

// The __builtin_ forms of the <math.h> functions below are what ccgo emits
// when a call resolves to a compiler builtin. They forward to the libc
// implementations. See https://gitlab.com/cznic/libc/-/issues/56 and
// https://gitlab.com/cznic/ccgo/-/issues/62.

func X__builtin_acosh(t *TLS, x float64) float64 { return Xacosh(t, x) }

func X__builtin_asinh(t *TLS, x float64) float64 { return Xasinh(t, x) }

func X__builtin_asinhf(t *TLS, x float32) float32 { return Xasinhf(t, x) }

func X__builtin_atanh(t *TLS, x float64) float64 { return Xatanh(t, x) }

func X__builtin_cbrt(t *TLS, x float64) float64 { return Xcbrt(t, x) }

func X__builtin_erf(t *TLS, x float64) float64 { return Xerf(t, x) }

func X__builtin_erfc(t *TLS, x float64) float64 { return Xerfc(t, x) }

func X__builtin_exp2(t *TLS, x float64) float64 { return Xexp2(t, x) }

func X__builtin_expm1(t *TLS, x float64) float64 { return Xexpm1(t, x) }

func X__builtin_fdim(t *TLS, x, y float64) float64 { return Xfdim(t, x, y) }

func X__builtin_fmaf(t *TLS, x, y, z float32) float32 { return Xfmaf(t, x, y, z) }

func X__builtin_lgamma(t *TLS, x float64) float64 { return Xlgamma(t, x) }

func X__builtin_log1p(t *TLS, x float64) float64 { return Xlog1p(t, x) }

func X__builtin_log1pf(t *TLS, x float32) float32 { return Xlog1pf(t, x) }

func X__builtin_logb(t *TLS, x float64) float64 { return Xlogb(t, x) }

func X__builtin_nextafter(t *TLS, x, y float64) float64 { return Xnextafter(t, x, y) }

func X__builtin_nextafterf(t *TLS, x, y float32) float32 { return Xnextafterf(t, x, y) }

func X__builtin_nexttoward(t *TLS, x, y float64) float64 { return Xnexttoward(t, x, y) }

func X__builtin_remainder(t *TLS, x, y float64) float64 { return Xremainder(t, x, y) }

func X__builtin_remquo(t *TLS, x, y float64, quo uintptr) float64 { return Xremquo(t, x, y, quo) }

func X__builtin_rint(t *TLS, x float64) float64 { return Xrint(t, x) }

func X__builtin_scalbn(t *TLS, x float64, n int32) float64 { return Xscalbn(t, x, n) }

func X__builtin_tgamma(t *TLS, x float64) float64 { return Xtgamma(t, x) }

// int __flt_rounds(void)
//
// The value of FLT_ROUNDS. Rounding to nearest is the only mode supported,
// fesetround is not available.
func X__flt_rounds(t *TLS) int32 {
	return 1
}

func X__builtin_flt_rounds(t *TLS) int32 {
	return 1
}

// float fmaf(float x, float y, float z)
//
// The product of two floats is exact in double precision and adding z to it
// rounds once. Converting that double to float would round a second time,
// which gives a wrong result when the double is exactly halfway between two
// floats. Rounding an inexact double to odd first makes the final conversion
// correctly rounded (Boldo, Melquiond: Emulation of a FMA and correctly
// rounded sums: proved algorithms using rounding to odd).
func Xfmaf(t *TLS, x, y, z float32) (r float32) {
	if __ccgo_strace {
		trc("t=%v x=%v y=%v z=%v, (%v:)", t, x, y, z, origin(2))
		defer func() { trc("-> %v", r) }()
	}
	xy := float64(x) * float64(y) // exact
	fz := float64(z)
	s := xy + fz
	if math.IsNaN(s) || math.IsInf(s, 0) {
		return float32(s)
	}

	// TwoSum: s+err == xy+fz exactly.
	bb := s - xy
	err := (xy - (s - bb)) + (fz - bb)
	if err != 0 {
		if u := math.Float64bits(s); u&1 == 0 {
			// Round to odd: move s by one ulp towards the exact sum.
			if (err > 0) == (s > 0) {
				u++
			} else {
				u--
			}
			s = math.Float64frombits(u)
		}
	}
	return float32(s)
}

// char *__builtin___strncat_chk(char *dest, const char *src, size_t n, size_t destlen)
func X__builtin___strncat_chk(t *TLS, dest, src uintptr, n, destlen Tsize_t) (r uintptr) {
	if __ccgo_strace {
		trc("t=%v dest=%v src=%v n=%v destlen=%v, (%v:)", t, dest, src, n, destlen, origin(2))
		defer func() { trc("-> %v", r) }()
	}
	dlen := strlen(dest)
	var slen Tsize_t
	for slen < n && *(*byte)(unsafe.Pointer(src + uintptr(slen))) != 0 {
		slen++
	}
	if destlen != ^Tsize_t(0) && dlen+slen+1 > destlen {
		Xabort(t)
	}

	d := dest + uintptr(dlen)
	for i := Tsize_t(0); i < slen; i++ {
		*(*byte)(unsafe.Pointer(d + uintptr(i))) = *(*byte)(unsafe.Pointer(src + uintptr(i)))
	}
	*(*byte)(unsafe.Pointer(d + uintptr(slen))) = 0
	return dest
}
