Integer Generics: Negative literals seem broken

I was trying to create a type similar to Pascal array types where you can specify the upper bound and lower bound of the index e.g. in Pascal you can write var a: array [1 .. 8] of integerand the elements will be indexed from 1 to 8 (as opposed to 0 to 7). I am using the new integer generic parameters.

Consider the following pared down example

struct MyCollection<let lowerBound: Int, let upperBound: Int, T>
{
	init()
	{
		print("lb = \(lowerBound), ub = \(upperBound)")
	}
    // Implementation would go here but not needed to demo the problem
}

let a = MyCollection< 1, 8, Int>()
let b = MyCollection< 0, 8, Int >()
let c = MyCollection< -1, 8, Int >()
let d = MyCollection< -2, 8, Int >()
let e = MyCollection< -3, 8, Int >()
let f = MyCollection< -4, 8, Int >()
let g = MyCollection< -5, 8, Int >()

It is supposed to create successive collections with 8, 9, 10, 11… elements, each one with a more negative lower bound than the previous. However, the above code prints:

lb = 1, ub = 8
lb = 0, ub = 8
lb = 1, ub = 8
lb = 2, ub = 8
lb = 5, ub = 8
lb = 4, ub = 8
lb = 11, ub = 8

The lower bounds specified without the minus sign are fine, but the subsequent ones are, to my eye, completely wrong. The grammar from the Swift Evolution proposalsuggests I am allowed to use negative numbers

generic-argument --> '-'? integer-literal
same-type-requirement --> type-identifier '==' '-'? integer-literal

I think this is a compiler bug and I need to raise it as such. Any comments?


The above is reproducible in a Playground in Xcode 26.0.1 with Swift 6.2 on macOS 26.0

7 Likes

It appears that the bit-pattern of the observed values is the same as that of the input values with all-but-one of the leading 1-bits masked off.

Without knowing anything about the implementation, I’m guessing there’s some bit-twiddling mistake in the handling of negative values here.

2 Likes

@Alejandro has a fix up already: [IRGen] Correctly sext instead of zext for negative integer types by Azoy · Pull Request #84655 · swiftlang/swift · GitHub

9 Likes