Re: [swift-evolution] 100% bikeshed topic: DictionaryLiteral

2018-01-14 Thread Dmitri Gribenko via swift-evolution
On Mon, Jan 8, 2018 at 4:29 PM, Ben Cohen via swift-evolution
 wrote:
> There exists in the standard library a type `DictionaryLiteral` that deserves 
> naming re-consideration before we declare ABI Stability, because it’s 
> confusingly misnamed, being neither a Dictionary (it doesn’t provide 
> key-based lookup of values) nor a Literal.
>
> Instead, it’s just an immutable collection of key-value pairs you can create 
> _from_ a literal.

I was around when we were naming this type, and I don't think it is
misnamed.  However, I just read the documentation and I don't believe
it explains the intended use of the type, hence we have this
confusion.

The intended use case for DictionaryLiteral is to build DSLs.  Swift
provides types in the standard library that are efficient and lossless
representations for all literals, but are also useful as your
workhorse data types: string literal -- String, array literal --
Array, integer literal -- [U]Int64, kinda (there is some
dissatisfaction with integer literals since there is no type to
capture a >64 bit literal, which is useful for defining a bigint
type).  But there was no type that could capture a dictionary literal
in a lossless form, maintaining the order of items, not imposing
dictionary limitations like uniqueness or hashability of keys.

Therefore, we added DictionaryLiteral.  Yes, it did land together with
Mirrors in commit 50c6e936d4b94b9736a8d060ddf052ef1ba9c74d, but the
intent was that it is a generally useful library component unrelated
to Mirrors, and therefore we did not add any Mirror-related words to
the name (we couldn't nest it in Mirror because nested generics didn't
work at the time).  In fact you can see the comment in Mirrors.swift
that has been preserved to this date:

// This component could stand alone, but is used in Mirror's public interface.

Mirrors just *use* DictionaryLiteral to build a small DSL in the
initializer of Mirror, so that callers could call that initializer
representing Mirror's children with a nice intuitive syntax using a
dictionary literal.

Therefore, based on this intended use, I think that trying to hint
that this type is a general *collection* of any kind is a disservice
for users -- DictionaryLiteral wasn't intended to be a collection, and
it does not have performance characteristics anyone would reasonably
expect from it.  We could add more words to the name to paint it more
an "advanced tool shade", for example, CapturedDictionaryLiteral,
DictionaryLiteralSyntax or something along those lines, but I feel
like the impact of that to fix the confusion would be minimal.

Instead, I think the right way to fix the confusion is to adjust the
documentation to not claim that it is first and foremost a collection,
because currently documentation is only technically correct, but does
not explain the intended use of the type at all.

Dmitri
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] What're the Swift team's thoughts on Go's concurrency?

2016-08-10 Thread Dmitri Gribenko via swift-evolution
On Wed, Aug 10, 2016 at 3:50 PM, David Sweeris via swift-evolution
 wrote:
> For example, maybe you really do need to interpret a 64-bit chunk of data as 
> an Int64, even though the compiler is convinced it’s a Double. We can do that 
> in Swift through the various “unsafe” functions, which is where they belong 
> because 99.99% of the time that’s a bad idea.

"42.0.bitPattern".  Why do you think this conversion is unsafe?

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] MemoryLayout for a value

2016-08-06 Thread Dmitri Gribenko via swift-evolution
On Fri, Aug 5, 2016 at 7:35 PM, Boris Wang via swift-evolution
 wrote:
> codes in swift REPL:
>
> protocol P {
> var x:Int {get}
> }
> MemoryLayout.size
> //r0 : Int = 40
>
> struct S1 {
> var v1:Int = 0
> }
> MemoryLayout.size
> //r1: Int =8
>
> struct S2: P {
> var v2: Int
> var x:Int
> }
> MemoryLayout .size
> //r2: Int = 16
>
> ** Question:
> Why we need to known the size of a object that can't be instanced?

The size of a variable of static type S2 is not equal to the size of
the variable of static type P, even though it can dynamically contain
an instance of S2.

Consider:

var x: P = S2(v2: 0, x: 0)

The size of x is not equal to the size of S2.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] MemoryLayout for a value

2016-08-04 Thread Dmitri Gribenko via swift-evolution
On Wed, Aug 3, 2016 at 7:28 PM, Xiaodi Wu via swift-evolution
 wrote:
> Could I suggest an alternative? It's conservative in that it mimics the
> relationships we had before the proposal was implemented and also maintains
> the simplicity of the caseless enum:
>
> ```
> extension MemoryLayout {
>   static func size(ofValue _: T) -> Int { return MemoryLayout.size }
>   // etc.
> }
> ```

I like this API.  I think given all the alternatives that we explored,
it is better than those.  I also think that it nicely avoids the
following issue with the proposed MemoryLayout.of(type(of:
someExpression)).size syntax.

Imagine that you have a value whose static type differs from the
dynamic type.  For example, a protocol existential:

protocol P {}
extension Int : P {}
var x: P = 10

The question is, what does MemoryLayout.of(type(of: x)).size compute,
size of the existential box, or the size of an Int instance?  The
semantics of 'type(of:)' are "return the dynamic type", so the
straightforward conclusion is that MemoryLayout.of(type(of: x)).size
returns the size of the dynamic type instance, of Int.

What actually happens is that 'type(of: x)' returns a dynamic value of
'Int.self', statically typed as 'P.Type'.  So P gets deduced for the
generic parameter of MemoryLayout, and MemoryLayout.of(type(of:
x)).size returns the size of the protocol box.

I think due to this complex interaction, using type(of:) might lead to
confusing code, and thus I like Xiaodi's approach better.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Swift 3?] Add ContiguousArray -> Array non-copying initialiser

2016-07-28 Thread Dmitri Gribenko via swift-evolution
On Thu, Jul 28, 2016 at 11:01 AM, Karl Wagner  wrote:
> I didn't know that normally-copying initialiser was non-copying for
> ContiguousArray. That's the kind of thing we should really document
> somewhere

We would welcome a patch for the docs!

> (or it should be it's own function because it guarantees
> non-copying behaviour).

It should be the same function, so that you get this optimization even
when working from generic code, when the type of the initializer's
argument is erased to Sequence.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Swift 3?] Add ContiguousArray -> Array non-copying initialiser

2016-07-28 Thread Dmitri Gribenko via swift-evolution
On Wed, Jul 27, 2016 at 11:08 PM, Karl via swift-evolution
 wrote:
> It seems like a reasonably large hole with a simple fix. Going from
> ContiguousArray to Array is a kind-of upcasting conversion and should be
> allowed -- it seems like that's almost the whole point of the type.

Hi Karl,

Converting a ContiguousArray to Array using Array's initializer is
O(1).  Are you seeing something different?

Array.init:

https://github.com/apple/swift/blob/f8f6d61d195185f54aeba425dd0db8be4c5d163f/stdlib/public/core/Arrays.swift.gyb#L1037

ContiguousArray._copyToContiguousArray():

https://github.com/apple/swift/blob/f8f6d61d195185f54aeba425dd0db8be4c5d163f/stdlib/public/core/Arrays.swift.gyb#L1430

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Review] SE-0131: Add AnyHashable to the standard library

2016-07-25 Thread Dmitri Gribenko via swift-evolution
On Mon, Jul 25, 2016 at 1:12 PM, Nate Cook via swift-evolution
 wrote:
>>   
>> https://github.com/apple/swift-evolution/blob/master/proposals/0131-anyhashable.md
>
> +1!
>
> This proposal looks great to me. I only have one nitpick: it looks like 
> there's a '_Hashable' protocol used in the Dictionary extension to get around 
> the limit on generic subscripts. Swift has managed to remove most (all?) 
> underscored protocols from public APIs, so I would just suggest that the 
> implementation consider an alternate name that isn't underscored. Something 
> like 'HashableBase' would still imply that the protocol is more of an 
> implementation detail than a useful protocol on its own.

Hi Nate,

I don't see a benefit for this.  Nobody should be using _Hashable.
Adding it as a non-underscored protocol increases API surface for no
benefit.  _Hashable is slated for removal as soon as we get the
necessary compiler features.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Review] SE-0131: Add AnyHashable to the standard library

2016-07-25 Thread Dmitri Gribenko via swift-evolution
On Mon, Jul 25, 2016 at 1:34 PM, Pyry Jahkola via swift-evolution
 wrote:
>
> On 24 Jul 2016, at 01:26, Chris Lattner via swift-evolution
>  wrote:
>
> Hello Swift community,
>
> The review of "SE-0131: Add AnyHashable to the standard library" begins now
> and runs through July 25.  This proposal is a bit unusual, since it is a
> late additive proposal.  The reason we need to do something here is as a
> critical part of "SE-0116: Import Objective-C id as Swift Any type”,
> enabling importing untyped NSDictionary's and NSSet’s properly.  The core
> team considers this already conceptually approved for Swift 3 as part of
> SE-0116, but would greatly appreciate feedback on the details of the
> proposed design.
>
> The proposal is available here:
>
> https://github.com/apple/swift-evolution/blob/master/proposals/0131-anyhashable.md
>
> * What is your evaluation of the proposal?
>
>
> +1, this is a nice addition, and useful at times.
>
> There's one very obscure gotcha with AnyHashable that subclass instances of
> a Hashable base class should be cast to the base type before wrapping into
> AnyHashable, otherwise such wrapped values may break the equivalence law of
> symmetry (`a == b` iff `b == a`).

The implementation that I have does not suffer from this issue.  (The
initializer of AnyHashable walks the superclass chain and upcasts the
value to the correct type.)

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Add AnyHashable to the standard library

2016-07-22 Thread Dmitri Gribenko via swift-evolution
You can view the full proposal here:
https://github.com/apple/swift-evolution/pull/458/files

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


[swift-evolution] Add AnyHashable to the standard library

2016-07-22 Thread Dmitri Gribenko via swift-evolution
Hi,

The implementation of SE-0116 "Import Objective-C id as Swift Any type"
requires a type-erased container for hashable values.

We are proposing to add such a type-erased container under the name
AnyHashable to the standard library.

This proposal is additive, source-breaking changes are discussed in SE-0116.

/// A type-erased hashable value.// Forwards equality comparisons
and hashing operations to an/// underlying hashable value, hiding its
specific type.// You can store mixed-type keys in `Dictionary` and
other/// collections that require `Hashable` by wrapping mixed-type
keys in/// `AnyHashable` instances:// let descriptions:
[AnyHashable : Any] = [/// AnyHashable(""): "emoji",///
   AnyHashable(42): "an Int",/// AnyHashable(Int8(43)): "an
Int8",/// AnyHashable(Set(["a", "b"])): "a set of strings"///
   ]/// print(descriptions[AnyHashable(42)]!)  // prints "an
Int"/// print(descriptions[AnyHashable(43)])   // prints
"nil"/// print(descriptions[AnyHashable(Int8(43))]!) // prints "an
Int8"/// print(descriptions[AnyHashable(Set(["a", "b"]))]!) //
prints "a set of strings"public struct AnyHashable {
  /// Creates an opaque hashable value that wraps `base`.
  ///
  /// Example:
  ///
  /// let x = AnyHashable(Int(42))
  /// let y = AnyHashable(UInt8(42))
  ///
  /// print(x == y) // Prints "false" because `Int` and `UInt8`
  ///   // are different types.
  ///
  /// print(x == AnyHashable(Int(42))) // Prints "true".
  public init(_ base: H)

  /// The value wrapped in this `AnyHashable` instance.
  ///
  /// let anyMessage = AnyHashable("Hello")
  /// let unwrappedMessage: Any = anyMessage.base
  /// print(unwrappedMessage) // prints "hello"
  public var base: Any
}
extension AnyHashable : Equatable, Hashable {
  public static func == (lhs: AnyHashable, rhs: AnyHashable) -> Bool
  public var hashValue: Int {
}

We are adding convenience APIs to Set that allow using
existing Set APIs with concrete values that conform to Hashable. For
example:

func contains42(_ data: Set) -> Bool {
  // Works, but is too verbose:
  // return data.contains(AnyHashable(42))

  return data.contains(42) // Convenience API.
}

extension Set where Element == AnyHashable {
  public func contains(
_ member: ConcreteElement
  ) -> Bool

  public func index(
of member: ConcreteElement
  ) -> SetIndex?

  mutating func insert(
_ newMember: ConcreteElement
  ) -> (inserted: Bool, memberAfterInsert: ConcreteElement)

  @discardableResult
  mutating func update(
with newMember: ConcreteElement
  ) -> ConcreteElement?

  @discardableResult
  mutating func remove(
_ member: ConcreteElement
  ) -> ConcreteElement?
}

Convenience APIs for Dictionary:

extension Dictionary where Key == AnyHashable {
  public func index(forKey key: ConcreteKey)
-> DictionaryIndex?

  public subscript(_ key: _Hashable) -> Value? { get set }

  @discardableResult
  public mutating func updateValue(
_ value: Value, forKey key: ConcreteKey
  ) -> Value?

  @discardableResult
  public mutating func removeValue(
forKey key: ConcreteKey
  ) -> Value?
}


Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [swift-evolution-announce] [Review] SE-0127: Cleaning up stdlib Pointer and Buffer Routines

2016-07-22 Thread Dmitri Gribenko via swift-evolution
On Fri, Jul 22, 2016 at 11:16 AM, Bob Wilson via swift-evolution
 wrote:
> I have been looking at the parts of this proposal related to
> withUnsafe[Mutable]Pointer:
>
[...]

I agree with everything that Bob said, and I would like to comment on this part:

> unsafeAddressOf is removed, in favor of adding a unsafeAddress field on 
> ObjectIdentifier. ObjectIdentifier already contains a raw pointer in the 
> internal _value field and can be initialized with AnyObject just like the 
> argument of unsafeAddressOf.

I think we should not add the ObjectIdentifier.unsafeAddress API.  I
don't agree with the motivation from the proposal:

> Remove unsafeAddressOf and use Unmanaged.takeUnretainedValue(_:) instead. 
> This, however, requires the caller to deal with retain logic for something as 
> simple as getting an object address.

We want users to be explicit about their reference counting semantics
when working unsafely with object addresses.  Otherwise it is not
clear for how long the resulting pointer is valid.  Getting an unsafe
object address is not "simple", it is not commonly when working with
Swift or Objective-C APIs, and there should be no need to have
shorthand convenience syntax for it.  The current way to perform
manual reference counting and bridging of objects to the unsafe world
is through Unmanaged, so the conversion from object to a pointer
should be on Unmanaged (where it is now).

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Draft][Proposal] Formalized Ordering

2016-07-22 Thread Dmitri Gribenko via swift-evolution
On Fri, Jul 22, 2016 at 8:38 AM, Nevin Brackett-Rozinsky
 wrote:
> Excellent point Karl.
>
> In my view, floating point NaN values are really quite similar to `.none`.
>
> I would be interested in exploring a move *away* from the IEEE 754 handling
> of NaN. In particular, we could model Float and Double as optionals (maybe
> implicitly-unwrapped) with NaN bit-patterns indicating `.none`.
>
> Or we could model *just the non-NaN values* and make undefined operations
> trap, among other possibilities.

I think these are non-starters.

>>> 5. Will it be considered "ok" to define a type for which `T.areSame(a, b)
>>> == true` but `a != b`? An obvious example would be Double.nan, so I assume
>>> the answer is a resounding yes.
>>
>>
>>
>> Yes, because `==` is not a protocol requirement of Equatable, so it
>> can have domain-specific semantics.
>
>
> Per SE-0091 the operator will be the protocol requirement.

If SE-0091 removes non-protocol operators, then we will have to change
the language again to accommodate what we need.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal] Move public AutoreleasingUnsafeMutablePointer API from StdlibCore -> Objective C Overlay

2016-07-22 Thread Dmitri Gribenko via swift-evolution
On Fri, Jul 22, 2016 at 8:23 AM, Félix Cloutier
 wrote:
> I agree on principle for moving it out of stdlib, but what's the Objective-C
> overlay?

It is the overlay for the 'ObjectiveC' module where NSObject is defined.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Draft][Proposal] Formalized Ordering

2016-07-22 Thread Dmitri Gribenko via swift-evolution
On Fri, Jul 22, 2016 at 2:13 AM, Pyry Jahkola via swift-evolution
 wrote:
> 5. Will it be considered "ok" to define a type for which `T.areSame(a, b) == 
> true` but `a != b`? An obvious example would be Double.nan, so I assume the 
> answer is a resounding yes.

Yes, because `==` is not a protocol requirement of Equatable, so it
can have domain-specific semantics.

> 6. Similarly, will it be "ok" to define a type for which `T.areSame(a, b) == 
> false` but `a == b`? One possible example could be the comparison of `-0.0 
> <=> +0.0`. Should those be `.same` or not?
>
> 7. What, in fact, is the proposed total order for the stdlib's floating-point 
> types?

The IEEE 754 definition.

https://github.com/apple/swift/blob/f318fe853d7898246db24d501f1ddc03c9eb8651/stdlib/public/core/FloatingPoint.swift.gyb#L855

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Draft][Proposal] Formalized Ordering

2016-07-22 Thread Dmitri Gribenko via swift-evolution
On Thu, Jul 21, 2016 at 11:09 PM, Brent Royal-Gordon via
swift-evolution  wrote:
>> On Jul 21, 2016, at 6:11 PM, Robert Widmann via swift-evolution 
>>  wrote:
>>
>> Hello Swift Community,
>>
>> Harlan Haskins, Jaden Geller, and I have been working on a proposal to clean 
>> up the semantics of ordering relations in the standard library.  We have a 
>> draft that you can get as a gist.  Any feedback you might have about this 
>> proposal helps - though please keeps your comments on Swift-Evolution and 
>> not on the gist.
>
> My thoughts on this are not yet fully formed, but I have a couple questions 
> concerning `isSame(_:_:)` and `==`:
>
> * Should calls like `index(of:)` and `split(separator:)` use `==` or 
> `isSame(_:_:)`?

Use sites should always use `==`.  They will pick up the semantics
appropriate for the generic constraints they see.

> * Should `Hashable` use `==` or `isSame(_:_:)`?

Code generic over Hashable will not see a difference.

> * Do we know of any use cases where a type conforms to `Equatable` but not 
> `Comparable` and needs separate `isSame(_:_:)` and `==` operators?

No, but I can easily imagine that one exists.

> Essentially, I'm wondering if we can leave `Equatable`'s definition alone and 
> only change `Comparable` to require `<=>`, with a generic operator to provide 
> a default `==` which uses `<=>`.

We can't do that, because two values equal according to `<=>` should
be equal according to Equatable.  Otherwise protocols don't make any
sense.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Draft][Proposal] Formalized Ordering

2016-07-21 Thread Dmitri Gribenko via swift-evolution
On Thu, Jul 21, 2016 at 10:17 PM, Xiaodi Wu  wrote:
> Robert, the gist is notably vague on this point, so I'm hoping you will
> clarify. Are you proposing that FloatingPoint will break with IEEE754
> semantics? What will be the result of `Float.nan == Float.nan`?
>
> (My guess at the sanest outcome is that areSame/Equivalent() and <=> will be
> totally ordered but FloatingPoint types will override == and the standard
> comparison operators to maintain IEEE754 semantics, yes?)

Right, == (and !=, <, >, <=, >=) can be customized with
domain-specific semantics, and floating point does this.  In addition,
floating point protocols will list == as a requirement, so generic
code generic over floating point types will get IEEE 754 semantics
when using == syntax, but code that only has an Equatable requirement
will use the total ordering semantics.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Pitch] Rename Mirror

2016-07-21 Thread Dmitri Gribenko via swift-evolution
On Thu, Jul 21, 2016 at 4:49 PM, Anton Zhilin  wrote:
> 2016-07-22 2:39 GMT+03:00 Dmitri Gribenko :
>>
>> On Thu, Jul 21, 2016 at 4:06 PM, Anton Zhilin 
>> wrote:
>> > Moreover, types can completely customize contents of their
>> > 'Mirror's. This is incompatible with laziness and with how reflection
>> > should
>> > work, based on experience from other languages.
>>
>> That is actually viewed as a weakness of reflection in other
>> languages.  Allowing reflection to access other types' internal data
>> and APIs creates barriers for optimization, and facilitates creating
>> binary compatibility problems when apps include code that uses
>> reflection to poke at internal data of library types.
>
>
> I talked about Swift here.

I am also talking about Swift.  If we build a reflection mechanism
that would allow third party code to poke at Array or Dictionary
implementation details (or any other type for that matter), we would
be exposing us to the same pitfalls as other languages have now.  I
would be opposed to doing that.

> Types can completely customize contents of their
> Mirrors in Swift.

This is desirable, for implementation hiding reasons.  Nobody should
be able to observe implementation details of Array, Dictionary, or any
other library types through programmatic mechanisms.

> A type, which pretends to be used for reflection, can't
> afford that.

Why not?

You see, we (as a community) don't have a shared long-term vision
about what "reflection" means.  Establishing that agreement would be
the prerequisite to starting any formal proposal process.
Speculatively making changes based on hypothetical designs that were
not discussed yet will not bring us to a better place.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Pitch] Rename Mirror

2016-07-21 Thread Dmitri Gribenko via swift-evolution
On Thu, Jul 21, 2016 at 4:06 PM, Anton Zhilin  wrote:
> 2016-07-22 1:34 GMT+03:00 Dmitri Gribenko :
>>
>> > Mirror.DisplayStyle contains optional and set as special cases, but does
>> > not
>> > contain function
>> > Mirror collects all information possible at initialization, while for
>> > true
>> > reflection we want laziness
>> > Mirror allows customization. For example, Array is represented with a
>> > field for each of its elements. Do we want this for “true” reflection we
>> > want to add in the future?
>>
>> Why can't we add these features to Mirror in future?
>
>
> Reflection in some other languages works as follows: we have a type (let's
> name it 'Reflection'). Each instance of it contains ID of one type and can,
> for example, retrieve an array of its static or normal methods.

I understand.  But we don't know how reflection will work in Swift, we
haven't designed it yet.  You are assuming it will work like it does
in other languages, which will not necessarily be the case.

> Moreover, types can completely customize contents of their
> 'Mirror's. This is incompatible with laziness and with how reflection should
> work, based on experience from other languages.

That is actually viewed as a weakness of reflection in other
languages.  Allowing reflection to access other types' internal data
and APIs creates barriers for optimization, and facilitates creating
binary compatibility problems when apps include code that uses
reflection to poke at internal data of library types.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Pitch] Rename Mirror

2016-07-21 Thread Dmitri Gribenko via swift-evolution
On Thu, Jul 21, 2016 at 3:25 PM, Anton Zhilin via swift-evolution
 wrote:
> https://github.com/Anton3/swift-evolution/blob/master/proposals/-rename-mirror.md
>
> Rename Mirror
>
> Proposal: SE-
> Author: Anton Zhilin, Adrian Zubarev
> Status: Awaiting review
> Review manager: TBD
>
> Introduction
>
> Rename Mirror to DebugRepresentation and CustomReflectable to
> CustomDebugRepresentable.
>
> Motivation
>
> Name of Mirror does not reflect (no pun) what it is intended to do, i.e.
> providing full featured reflection, which we want to see in Swift 4. Other
> than that, it is only intended to serve for debugging purposes, e.g.
> building trees for selected objects. Some evidence to that:
>
> Mirror.DisplayStyle contains optional and set as special cases, but does not
> contain function
> Mirror collects all information possible at initialization, while for true
> reflection we want laziness
> Mirror allows customization. For example, Array is represented with a
> field for each of its elements. Do we want this for “true” reflection we
> want to add in the future?

Why can't we add these features to Mirror in future?

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal] Move public AutoreleasingUnsafeMutablePointer API from StdlibCore -> Objective C Overlay

2016-07-21 Thread Dmitri Gribenko via swift-evolution
On Thu, Jul 21, 2016 at 10:02 AM, Michael Gottesman via
swift-evolution  wrote:
> Hello everyone.
>
> This is a proposal to move AutoreleasingUnsafeMutablePointer from StdlibCore 
> to the Objective C overlay.

+1.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Change Request: Make myString.hasPrefix("") and myString.hasSuffix("") return true

2016-07-20 Thread Dmitri Gribenko via swift-evolution
On Mon, Jul 18, 2016 at 3:29 PM, Dave Abrahams via swift-evolution
 wrote:
>
> on Mon Jul 18 2016, Kevin Nattinger  wrote:
>
>> I agree, true is definitely the expected behavior. In particular, it
>> seems absurd to me that `a.hasPrefix(b)` and `a.hasSuffix(b)` could be
>> false when `a == b` is true.
>
> I expect to be reworking Strings for Swift 4, and this is one of the
> many things we plan to address.

Why not implement the change right now so that we change the semantics
in Swift 3 rather than in Swift 4?

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Review] SE-0122: Use colons for subscript declarations

2016-07-20 Thread Dmitri Gribenko via swift-evolution
On Tue, Jul 19, 2016 at 10:50 PM, Chris Lattner via swift-evolution
 wrote:
> Hello Swift community,
>
> The review of "SE-0122: Use colons for subscript declarations " begins now 
> and runs through July 24. The proposal is available here:
>
> 
> https://github.com/apple/swift-evolution/blob/master/proposals/0122-use-colons-for-subscript-type-declarations.md

Weakly against.

The subscript is a crossover between a function and a computed
property, and depending how you look at it, you will find either ":"
to be a better fit if you argue that they are closer to properties, or
that "->" is better, if you argue that subscripts are closer to
functions.  I don't find either argument to be more convincing that
the other, so I don't see a reason to change this part of the
language.

I wouldn't mind if the change would be made though, but I think by
changing subscripts to use colons we would end in the opposite, but
totally symmetrical situation compared to what we have now.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [swift-evolution-announce] [Review] SE-0125: Remove NonObjectiveCBase and isUniquelyReferenced

2016-07-20 Thread Dmitri Gribenko via swift-evolution
On Tue, Jul 19, 2016 at 10:51 PM, Chris Lattner  wrote:
> The review of "SE-0125: Remove NonObjectiveCBase and isUniquelyReferenced" 
> begins now and runs through July 22. The proposal is available here:
>
> 
> https://github.com/apple/swift-evolution/blob/master/proposals/0125-remove-nonobjectivecbase.md

I like the API simplification.  A few thoughts that I have after
reading the proposal that could take the simplification it even
further:

- I find it a little strange to see a mention of Objective-C, and a
negation in `isUniquelyReferencedNonObjC`.  For example, if we get C++
import, would we need to rename it to
`isUniquelyReferencedNonObjCAndNonCXX`?  I think that is the issue
with negation.  If we want to emphasize that the API will work only
with Swift types, we can do something
`isUniquelyReferencedSwiftReference`.  But I would probably suggest
that we just go with just `isUniquelyReferenced` and mention the
Swift-only requirement in the documentation.

- I find the use of different names in `isUniquelyReferenced()` and
`ManagedBufferPointer.holdsUniqueReference()` to be strange.  Why not
call the latter `ManagedBufferPointer. isUniquelyReferenced()`?  It is
true that we are not checking that pointer is not uniquely referenced,
if we want to emphasize that, maybe something like
`ManagedBufferPointer.isBufferUniquelyReferenced()` or
`isPointeeUniquelyReferenced()` will work?

The reason why I'm suggesting this is that `isUniquelyReferenced` and
`holdsUniqueReference` don't immediately strike me as performing the
same operation, the immediate impression I get is that these
operations are related, but subtly different, and it is not obvious
what the difference is (but after reading the docs I figure out that
there is no difference... until I need to use these APIs again).

- We have `ManagedBufferPointer.holdsUniqueOrPinnedReference()`, but
don't have an equivalent free function `isUniquelyReferencedOrPinned`
(we actually have one, but it is internal).  Do we need a public one?
If we do, we could as well add it as a part of this proposal, while we
are cleaning up this library subsystem.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] : [Proposal] Change UnicodeScalar initializer to failable

2016-07-19 Thread Dmitri Gribenko via swift-evolution
On Tue, Jul 19, 2016 at 10:14 AM, Xin Tong via swift-evolution
 wrote:
> Hi,
>
> I would like to propose changing unicodescalar initializer to failable.
>
> Currently, when you pass an invalid value to the UnicodeScalar initializer
> the swift stdlib crashes the program by calling _precondition. This is bad
> if you construct a unicode scalar from unknown input.
>
> As a result. I would like to propose to mark the initializer as failable and
> return nil in case of a failure.

+1, thank you for working on this improvement!

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Pitch] Set of AnyObject by reference

2016-07-17 Thread Dmitri Gribenko via swift-evolution
On Sun, Jul 17, 2016 at 2:00 AM, 张国晔 via swift-evolution
 wrote:
> I'm building an document-based app, and I'm having a problem regarding to Set.
>
> What I hope to achieve is to have a Set of unique objects by their references.

Try this:

public final class ReferenceEqualityBox : Hashable {
  public var value: Wrapped
  public init(_ value: Wrapped) {
self.value = value
  }
  public var hashValue: Int {
return ObjectIdentifier(self).hashValue
  }
}
public func ==  (
  lhs: ReferenceEqualityBox,
  rhs: ReferenceEqualityBox
) -> Bool {
  return ObjectIdentifier(lhs) == ObjectIdentifier(rhs)
}

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Pitch: Remove `NonObjectiveCBase` and replace `isUniquelyReferenced` by `isUniquelyReferencedUnsafe`

2016-07-16 Thread Dmitri Gribenko via swift-evolution
On Sat, Jul 16, 2016 at 12:47 PM, Arnold Schwaighofer via
swift-evolution  wrote:
> ## Proposed solution
>
> Replace `isUniquelyReferenced` by
> `isUniquelyReferencedUnsafe` and remove the `NonObjectiveCBase`
> class from the standard library.

Thank you for this proposal!

For presentation and clarity, could you show the full family of
`isUniquely*` functions in the design section, including those
functions that you are not proposing to change?  This will make it
easier to see what choices users will get.  It would be also great to
include the API of similar ManagedBuffer and ManagedBufferPointer
APIs, if any exist.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [swift-dev] Endgame for Swift 3

2016-07-15 Thread Dmitri Gribenko via swift-evolution
On Fri, Jul 15, 2016 at 11:44 AM, Ted kremenek via swift-dev
 wrote:
> Good question.
>
> Dave/Dmitri: do you have a recommendation here?  I can see either the JIRA
> issues referencing the proposal (if one exists) or updating the gist.  I
> prefer the former.

Updating the JIRA sounds good to me, too.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Pitch] `Int.init(ObjectIdentifier)` and `UInt.init(ObjectIdentifier)` should have a `bitPattern:` label

2016-07-15 Thread Dmitri Gribenko via swift-evolution
On Wed, Jul 13, 2016 at 4:39 PM, Arnold Schwaighofer via
swift-evolution  wrote:
> Int.init(ObjectIdentifier) and UInt.init(ObjectIdentifier) should have a 
> 'bitPattern:’ label to make it clear at the use site that we interpret the 
> value as a bit pattern.

+1!

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


[swift-evolution] Fixing the confusion between non-mutating algorithms and single-pass sequences

2016-07-12 Thread Dmitri Gribenko via swift-evolution
Hi,

I'd like to continue the discussion of the issue raised by David Waite
inhttp://thread.gmane.org/gmane.comp.lang.swift.evolution/21295/:

> My main motivation for proposing this is the potential for developer 
> confusion. As stated during one of the previous threads on the naming of map, 
> flatMap, filter, etc. methods on Sequence, Sequence has a naming requirement 
> not typical of the rest of the Swift standard library in that many methods on 
> Sequence may or may not be destructive. As such, naming methods for any 
> extensions on Sequence is challenging as the names need to not imply 
> immutability.

I'd like to focus on a particular point: methods on Sequence can
consume elements, but the APIs are not markedmutating.

Dave Abrahams, Max Moiseev, and I have discussed this issue and we
agree this problem is severe and worth solving, we also think that the
likely solutions would be source-breaking, so it is important that we
discuss it now.

We have discussed a few options.

- Rejected option: remove Sequence, let IteratorProtocol model
single-pass data streams

- Rejected option: use a syntactic marker, like sequence.consumedIn.map {}

- Rejected option: mutating APIs on Sequence, non-mutating APIs on Collection

Proposed: rename Sequence to IterableOnce or TraversableOnce. We think
that Sequence does not convey the single-pass restriction clearly. The
term "sequence" has been used in math (as in "integer sequence"), and
since the math domain does not have mutation, "sequence" can be
understood to mean "multi-pass", since you can traverse a sequence of
integers an arbitrary number of times.

We think that only the last option is viable in the Swift language as
it exists now, without creating an undue burden for API vendors and
users.

For more details about rejection options, please see the full writeup:
https://gist.github.com/gribozavr/47f4717f3afc762549383e94da7f748b

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Pitch] Removing the empty initialiser requirement from RangeReplaceableCollection

2016-07-07 Thread Dmitri Gribenko via swift-evolution
On Thu, Jul 7, 2016 at 6:14 PM, Dave Abrahams via swift-evolution
 wrote:
>
> on Wed Jul 06 2016, Tim Vermeulen  wrote:
>
>> This is a follow up from this swift-users thread: 
>> https://lists.swift.org/pipermail/swift-users/Week-of-Mon-20160704/002489.html
>>
>> As it stands, RangeReplaceableCollection requires an implementation
>> for init(), which is used in the default implementations of (as far as
>> I can tell) init(_:), init(repeating:count:) and
>> removeAll(keepingCapacity:). The latter of these methods should be
>> implementable with removeSubrange(_:) instead.
>
> You can't implement `removeAll(keepingCapacity: false)` with
> `removeSubrange(_:)`.  How do you propose to provide the other default
> implementations?
>
>> I would like to propose to *remove* all three initialisers from this
>> protocol, because it makes it impossible for some collections to
>> conform to it that need extra data for its initialisation, but are
>> otherwise perfectly capable of having arbitrary subranges replaced by
>> elements from another collection.
>
> I agree with the goal, but I'd like to see an implementation before I
> agree that it's acheivable.

I agree that we need to see an implementation to be able to evaluate
the suggestion.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Review] SE-0077 v2: Improved operator declarations

2016-07-07 Thread Dmitri Gribenko via swift-evolution
On Thu, Jul 7, 2016 at 9:27 AM, John McCall <rjmcc...@apple.com> wrote:
> On Jul 7, 2016, at 9:23 AM, Dmitri Gribenko via swift-evolution
> <swift-evolution@swift.org> wrote:
>> Proposal link:
>>
>>
>> https://github.com/apple/swift-evolution/blob/master/proposals/0077-operator-precedence.md
>
> Dave, Max and I discussed SE-0077 and reviewed the names of precedence
> groups.
> Here's our recommendation.
>
> In general, we think some names don't read well and have some ambiguities,
> for
> example, "LogicalAndPrecedence" (looks like a conjunction),
> "AdditivePrecedence" ("additive" is an adjective that modifies
> "precedence"),
> "RangePrecedence" ("range" is not an adjective, stands out).
>
> We think that two directions would be fruitful:
>
> 1.  If the names of precedence groups will be in the same namespace as
> types,
> then we recommend pushing the names of precedence groups into a
> "namespace",
> for example "Precedence.Assignment".
>
>
> We don't have any language features that would allow this.

'precedencegroup' that is being proposed is a new language feature, we
can choose to use any syntax we like with it.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j<i;j++){if(!(i%j)){j=0;break;}}if
(j){printf("%d\n",i);}}} /*Dmitri Gribenko <griboz...@gmail.com>*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Review] SE-0077 v2: Improved operator declarations

2016-07-07 Thread Dmitri Gribenko via swift-evolution
> Proposal link:
>
>
https://github.com/apple/swift-evolution/blob/master/proposals/0077-operator-precedence.md

Dave, Max and I discussed SE-0077 and reviewed the names of precedence
groups.
Here's our recommendation.

In general, we think some names don't read well and have some ambiguities,
for
example, "LogicalAndPrecedence" (looks like a conjunction),
"AdditivePrecedence" ("additive" is an adjective that modifies
"precedence"),
"RangePrecedence" ("range" is not an adjective, stands out).

We think that two directions would be fruitful:

1.  If the names of precedence groups will be in the same namespace as
types,
then we recommend pushing the names of precedence groups into a
"namespace",
for example "Precedence.Assignment".

2.  If (1) is not workable, we suggest incrementally improving existing
names
to make them more readable and less ambiguous.  We think that making the
names less technical by naming the groups after a representative
operation
will be easier for users to understand (instead of "AdditivePrecence" we
are proposing "AdditionPrecedence").  We also think that using an
adjective
before "Precedence" does not read well in many cases
("NilCoalescingPrecedence": precedence that coalesces nils).


Current name| Namespacing | Incremental
improvement
|-|-
AssignmentPrecedence| Precedence.Assignment   | no change
TernaryPrecedence   | Precedence.Ternary  | no change
DefaultPrecedence   | Precedence.Default  | no change
LogicalOrPrecedence | Precedence.LogicalOr|
DisjunctionPrecedence
LogicalAndPrecedence| Precedence.LogicalAnd   |
ConjunctionPrecedence
ComparativePrecedence   | Precedence.Comparison   | ComparisonPrecedence
NilCoalescingPrecedence | Precedence.NilCoalescing| no change
CastPrecedence  | Precedence.Casting  | no change
RangePrecedence | Precedence.RangeForming |
RangeFormationPrecedence
AdditivePrecedence  | Precedence.Addition | AdditionPrecedence
MultiplicativePrecedence| Precedence.Multiplication   |
MultiplicationPrecedence
BitwiseShiftPrecedence  | Precedence.BitwiseShift |
BitwiseShiftPrecedence

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Discussion] Cleaning up stdlib pointer and buffer routines (Open Issues Affecting Standard Library API Stability)

2016-07-07 Thread Dmitri Gribenko via swift-evolution
On Wed, Jul 6, 2016 at 9:57 PM, Charlie Monroe via swift-evolution
 wrote:
>
> On Jul 7, 2016, at 12:46 AM, Jordan Rose via swift-evolution
>  wrote:
>
>
> On Jul 6, 2016, at 11:03, Jacob Bandes-Storch via swift-evolution
>  wrote:
>
>
>> * Remove unsafeAddressOf. "We are not aware of any real use cases for it.
>> If there are any, it should be renamed to unsafeAddress(of:) to follow the
>> guidelines." (https://bugs.swift.org/browse/SR-1957 rdar://problem/18589289)
>>
>
> Oops, I just responded to this on another thread. Pasting:
>
> It's minor, but I use unsafeAddressOf regularly for writing `description`
> methods:
>
> var description: String {
> return "<\(self.dynamicType): \(unsafeAddressOf(self))>{ more info
> here... }"
> }
>
> I guess this would be covered by some generalized solution for format
> specifiers in string interpolations, but I gather that won't happen for
> quite a while...
>
>
> I believe `ObjectIdentifier(self)` prints basically the same way.
>
> Jordan
>
>
> Unfortunately, it doesn't:
>
> print("\(ObjectIdentifier(obj))")
>
> --> ObjectIdentifier(_value: (Opaque Value))

We should absolutely fix that (does not even require a swift-evolution
proposal).  This string that it converts to is completely useless.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Open Issues Affecting Standard Library API Stability

2016-07-06 Thread Dmitri Gribenko via swift-evolution
On Wed, Jul 6, 2016 at 6:15 PM, Karl  wrote:
>
> On 7 Jul 2016, at 02:06, Dmitri Gribenko  wrote:
>
> On Wed, Jul 6, 2016 at 4:21 AM, Karl  wrote:
>
> I had a PR open for this which added a Collection specialisation, but you
> said this could be handled in a more general way which allows for more
> optimised mutations. I’m curious how this would work; how does
> `RangeReplaceableCollection.replaceSubrange(range:, with: S)`
> call a more optimised implementation if S also conforms to Collection, if
> not by adding a specialisation?
>
>
> The RRC can call into S.someCustomizationPoint(), which will
> initialize a region of memory in the most efficient way possible,
> since it has complete knowledge about the memory layout of S.
>
> Dmitri
>
> --
> main(i,j){for(i=2;;i++){for(j=2;j (j){printf("%d\n",i);}}} /*Dmitri Gribenko */
>
>
> Sorry, it’s been a little while since I looked at it
> (https://github.com/apple/swift/pull/3067). Actually, the issue is with the
> append() function specifically - it only has a Sequence specialisation.
> That’s the point; we were losing type information and not calling the more
> optimised replaceSubrange — which is exactly the specialisation point you
> are talking about, Dmitry (I think everything funnels down in to
> replaceSubrange).

I'm talking about a different customization point.  RRC.append() calls
RRC.replaceSubrange(), which, in our thinking, would call
S._copyContents(initializing: RRC.getInnerPointer()).  _copyContents()
is the customization point on the argument that would initialize
memory with the contents of the sequence.

> I must have misunderstood what you were saying at the time. I’ll have to
> test, but I think it’s still an issue. I thought there was some more general
> work on RRC planned, so when I saw the bullet I thought maybe that was it.

I will be sending a draft proposal soon that will indirectly fix this
performance issue.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Open Issues Affecting Standard Library API Stability

2016-07-06 Thread Dmitri Gribenko via swift-evolution
On Wed, Jul 6, 2016 at 4:21 AM, Karl  wrote:
> I had a PR open for this which added a Collection specialisation, but you
> said this could be handled in a more general way which allows for more
> optimised mutations. I’m curious how this would work; how does
> `RangeReplaceableCollection.replaceSubrange(range:, with: S)`
> call a more optimised implementation if S also conforms to Collection, if
> not by adding a specialisation?

The RRC can call into S.someCustomizationPoint(), which will
initialize a region of memory in the most efficient way possible,
since it has complete knowledge about the memory layout of S.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Open Issues Affecting Standard Library API Stability

2016-07-06 Thread Dmitri Gribenko via swift-evolution
On Wed, Jul 6, 2016 at 11:30 AM, Harlan Haskins 
wrote:

> I’ve also seen unsafeAddressOf(_:) used when interfacing with C function
> pointers when the lifetime of an object is guaranteed. Many C APIs vend an
> API like:
>
> void perform_action(void (*callback)(void *data), void *initial_data);
>
> For which it is expected to use unsafeAddressOf on a class instance, like:
>
> perform_action({ data in
>   let _self = unsafeBitCast(data, to: MyClass.self)
>   _self.foo()
> }, data: unsafeAddressOf(self))
>
> It’s unsafe and error-prone, sure, but that’s why we have `unsafe` in the
> name  — I’ve had to use this to interface with libclang.
>

Hi Harlan,

For this case, Unmanaged is the recommended API.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Open Issues Affecting Standard Library API Stability

2016-07-05 Thread Dmitri Gribenko via swift-evolution
On Tue, Jul 5, 2016 at 9:24 PM, Chris Lattner <clatt...@apple.com> wrote:
> On Jul 5, 2016, at 6:57 PM, Dmitri Gribenko via swift-evolution 
> <swift-evolution@swift.org> wrote:
>>
>> Hi swift-evolution,
>>
>> Dave, Max and I have compiled a list of open issues in the standard
>> library for which the resolutions could result non-additive API
>> changes.  Having a resolution (and an implementation of the
>> resolution!) for these issues is blocking API stability.
>>
>> https://gist.github.com/gribozavr/37e811f12b27c6365fc88e6f9645634d
>
> Thank you for collecting this Dmitri!  For the issues in the “low hanging 
> fruit” list, are the changes all sufficiently "obvious”?  If so, having one 
> proposal tackle all of them in one sweep would be preferable to reduce 
> process overhead.

My subjective assessment:

> The global function withUnsafe[Mutable]Pointer() should have an argument 
> label “to”.
Obvious.

> UnicodeScalar.init(Int) should be failable.
Obvious.

> withUnsafePointer shouldn't take its argument as inout.
Jordan has objections, see https://bugs.swift.org/browse/SR-1956

> Remove unsafeAddressOf. We are not aware of any real usecases for it. If 
> there are any, it should be renamed to unsafeAddress(of:) to follow the 
> guidelines.
Obvious, unless someone comes up with use cases during the review period.

> Consider renaming or eliminating ManagedProtoBuffer.
> The reason why ManagedProtoBuffer exists is to give the users an extra bit of 
> type safety inside of the closure passed to ManagedBuffer.create().
Debatable.

> String.CharacterView.Iterator should be a custom type rather than the 
> default, to allow performance optimizations. Audit all other collections for 
> such opportunities.
Obvious.

> String(count:, repeatedValue:) and String.append() are ambiguous without an 
> explicit cast to Character.
Obvious.

> Rename the ~LiteralConvertible protocols according to the resolution of the 
> proposal currently under review.
A separate review.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j<i;j++){if(!(i%j)){j=0;break;}}if
(j){printf("%d\n",i);}}} /*Dmitri Gribenko <griboz...@gmail.com>*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


[swift-evolution] Open Issues Affecting Standard Library API Stability

2016-07-05 Thread Dmitri Gribenko via swift-evolution
Hi swift-evolution,

Dave, Max and I have compiled a list of open issues in the standard
library for which the resolutions could result non-additive API
changes.  Having a resolution (and an implementation of the
resolution!) for these issues is blocking API stability.

https://gist.github.com/gribozavr/37e811f12b27c6365fc88e6f9645634d

This is not an exhaustive list.  The first two sections ("Low-Hanging
Fruit" and "Moderate") list issues with low and moderate difficulty.
It should be possible to resolve them with minimal design work.

**We are strongly encouraging the community to pick up these issues.
Please do not reply to this thread.  Instead, start a new thread for
the issue you would like to discuss, and include the original
description and the bugs.swift.org link in your email.**

For the issues in the "Hard" section, we would like to post the
following commentary:

- The issue about algorithms not marked mutating consuming a
single-pass Sequences.  We have figured out a design that we think is
a good trade-off.  We will post it for public discussion within a few
days.


- An extension to the collections subsystem that would allow us to
model infinite data streams.  We think that the answer to this problem
should try hard to handle both single- and multi-pass collections, or
provide a very convincing explanation why it is desired to enable only
one of them (only multi-pass or only single-pass) to be infinite.

We see four possible solutions to this problem:

1. No change (disallow infinite data streams).

2. Allow infinite single-pass streams (as Iterators) and infinite
multi-pass streams (as Collections).

3. #2, and, for QoI, to catch mistakes in a non-guaranteed,
best-effort fashion, add a property 'isKnownToBeInfinite' or
'isKnownToBeFinite' that would be checked before the whole dataset is
iterated.  If the dataset is known to be infinite, issue a trap.

4. #2, and introduce new protocols for finite iterators and finite collections.

Unfortunately we don't have time to investigate the question about
infinite collections further.  We suggest interested community members
to drive the discussion on this topic.


- Dave Abrahams has been investigating whether it would be an
improvement to remove Comparable requirement from collection indices,
he will post an update separately.


- Naming of algorithms on sequences and collections is important, and
we are thankful for the community for working on these issues.  We
hope that these efforts would result in proposals!


- The spaceship <=> operator is an important, but also complex topic.
If someone wants to work on this item, we think that writing a
prototype and showing how it integrates with existing code,
investigating whether it solves issues with floating point min() and
NaNs, figuring out what the migration experience is etc. is critical
before opening a discussion.

The general design direction is clear -- we want to require users to
define just one operator, <=>, to conform to Comparable, but there are
many details that would only be found in a prototype implementation.
These small issues need concrete answers.



I'd like to thank the community again for all work that you are doing,
and encourage to pick up the issues from the list, and start
discussions in new threads.  I'd like to emphasize low and moderate
difficulty items.  We believe that for these issues the design space
is small, and consensus can be reached without a lot of discussion.
The associated API changes have a good chance to land in Swift 3.x.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Idea] Large integer literals

2016-07-04 Thread Dmitri Gribenko via swift-evolution
On Sun, Jul 3, 2016 at 9:20 PM, Brent Royal-Gordon via swift-evolution
 wrote:
> 2. Use a tuple/array of `Int`s/`UInts`
>
> Like `String`, this lends itself to becoming variable-width in a later 
> version; unlike `String`, it's relatively compact. But also unlike `String`, 
> it would be hard to get this working in Swift 3: tuples cannot be conformed 
> to protocols like `_BuiltinIntegerLiteralConvertible`, and there's no 
> conditional conformances to make `[Int]`/`[UInt]` conform to it either.

My recommended approach is to follow the example of DictionaryLiteral,
and define a "transport" data type that can accurately capture the
literal contents.  The transport data type should not have any
operations beyond the bare minimum (not even the BinaryInteger
conformance), so that the users are not tempted to use it as a
big-integer type.

The IntegerLiteral type would probably just wrap an
UnsafeBufferPointer to the readonly data segment, where the compiler
would lay out the literal.  (Very much like StaticString.  Maybe it
should be renamed to StringLiteral?)

I would not recommend wrapping a Builtin.Int2048 by value, this leads
to very inefficient code.  When it comes from the standard library,
this code is currently cleaned up by the optimizer because everything
that touches Builtin.Int2048 is marked @_transparent; but ordinary
frameworks can't do that.



A related issue is that the generic entry point that accepts
Builtin.Int2048 is still emitted by the compiler, and it is actually
called from unspecialized generic code when creating literals of
generic types.

func f() -> T{
  let x: T = 0
  return x
}

It would be great if we introduced another entry point in
IntegerLiteralConvertible that accepted [U]Int64 (and/or [U]Int128),
which the compiler would prefer if the literal is small (and it
usually is).

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal Draft] Literal Syntax Protocols

2016-07-01 Thread Dmitri Gribenko via swift-evolution
On Fri, Jul 1, 2016 at 1:35 PM, Dave Abrahams via swift-evolution
 wrote:
> I think if `Syntax.IntegerLiteral` is actually unclear then the best
> cure is `ExpressibleAsIntegerLiteral` (no namespace needed).  None of
> the other suggestions I've seen describe what the protocol means as well
> as that.  I've asked Matthew to update the proposal accordingly.

I also like `ExpressibleAsIntegerLiteral`.  It uses the ~ible/~able
convention which suggests a capability, and when the name is worded
like this, it is definitely describing a capability of the type.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] renaming CustomStringConvertible

2016-07-01 Thread Dmitri Gribenko via swift-evolution
On Fri, Jul 1, 2016 at 12:48 PM, Vladimir.S <sva...@gmail.com> wrote:
> On 01.07.2016 22:22, Dmitri Gribenko via swift-evolution wrote:
>>
>> On Fri, Jul 1, 2016 at 12:16 PM, Eric Habberstad via swift-evolution
>> <swift-evolution@swift.org> wrote:
>>>
>>>
>>> To the Swift community,
>>>
>>> May I put forth a couple of new names for the following protocol:
>>>
>>>
>>> - CustomStringConvertible  —   rename as ‘Descriptive’ or as ‘Revealable’
>>>
>>>
>>> Two goals for Swift is clarity and joy in use of the language, so I
>>> strongly
>>> feel that ‘Custom-‘ not be part of any new name here since it contributes
>>> little except verbosity
>>
>>
>> Hi Eric,
>>
>> This protocol was called Printable before, but it caused a lot of
>> confusion for developers, and was guiding the developers toward
>> writing incorrect APIs.  We have seen a lot of developers writing code
>> like this:
>>
>> func printAll(_ values: [Printable]) {
>>   for v in values { print(v) }
>> }
>>
>> This code is unnecessarily restrictive since in Swift everything can
>> be converted into a String.
>
>
> Yes, but IMO someone, who don't know this can still write
>
> func printAll(_ values: [CustomStringConvertible]) {
>   for v in values { print(v) }
> }
>
> So, I don't see how this name should help to understand that "everything can
> be converted into a String". This is a knowledge that one should read in
> docs, IMO.

They can still write this code, the compiler will accept it.  In
practice we found that changing the name helped and developers are now
much less likely to code APIs against CustomStringConvertible.  The
old name, Printable, strongly implied a capability (like Equatable,
Comparable, Hashable).  The new name does not suggest that
printability is a capability provided by this protocol.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j<i;j++){if(!(i%j)){j=0;break;}}if
(j){printf("%d\n",i);}}} /*Dmitri Gribenko <griboz...@gmail.com>*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal draft] NSError bridging

2016-06-29 Thread Dmitri Gribenko via swift-evolution
On Wed, Jun 29, 2016 at 4:13 AM, Charles Srstka
<cocoa...@charlessoft.com> wrote:
> On Jun 29, 2016, at 2:50 AM, Dmitri Gribenko via swift-evolution
> <swift-evolution@swift.org> wrote:
>
>
> I'm not sure I really want '.url' and '.stringEncoding' on every
> Error.  'var underlying' is universally useful, but providing it
> requires a implementing conformance to CustomNSError, which has to
> vend a weakly-typed dictionary.  Is this really the API we want to
> expose?
>
>
> We need to expose the dictionary in order to provide full compatibility with
> NSError.

The full compatibility argument is universal, and it can be applied to
anything.  Not always the answer is "dump the compatibility APIs onto
the Swift type".

> Also, the underlying error has to be stored somewhere, which
> effectively prevents implementers of CustomNSError from being enums.
>
>
> Not at all. Your enum can implement a dynamic errorUserInfo property that
> will populate the dictionary with the appropriate values. If you need to
> actually store something, that can be done with enum cases as well.

You would need to store the underlying error in every enum case, which
creates boilerplate, and you'd lose the raw representable conformance.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j<i;j++){if(!(i%j)){j=0;break;}}if
(j){printf("%d\n",i);}}} /*Dmitri Gribenko <griboz...@gmail.com>*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal draft] NSError bridging

2016-06-29 Thread Dmitri Gribenko via swift-evolution
On Mon, Jun 27, 2016 at 11:17 AM, Douglas Gregor via swift-evolution
 wrote:
> extension ErrorProtocol {
>   // Note: for exposition only. Not actual API.
>   private var userInfo: [NSObject : AnyObject] {
> return (self as! NSError).userInfo
>   }
>
>   var localizedDescription: String {
> return (self as! NSError).localizedDescription
>   }
>
>   var filePath: String? {
> return userInfo[NSFilePathErrorKey] as? String
>   }
>
>   var stringEncoding: String.Encoding? {
> return (userInfo[NSStringEncodingErrorKey] as? NSNumber)
>  .map { String.Encoding(rawValue: $0.uintValue) }
>   }
>
>   var underlying: ErrorProtocol? {
> return (userInfo[NSUnderlyingErrorKey] as? NSError)?.asError
>   }
>
>   var url: URL? {
> return userInfo[NSURLErrorKey] as? URL
>   }
> }

I'm not sure I really want '.url' and '.stringEncoding' on every
Error.  'var underlying' is universally useful, but providing it
requires a implementing conformance to CustomNSError, which has to
vend a weakly-typed dictionary.  Is this really the API we want to
expose?

Also, the underlying error has to be stored somewhere, which
effectively prevents implementers of CustomNSError from being enums.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Partial list of open Swift 3 design topics

2016-06-28 Thread Dmitri Gribenko via swift-evolution
On Tue, Jun 28, 2016 at 10:03 PM, David Waite
<da...@alkaline-solutions.com> wrote:
>
> On Jun 28, 2016, at 10:15 PM, Dmitri Gribenko via swift-evolution
> <swift-evolution@swift.org> wrote:
>
> On Tue, Jun 28, 2016 at 3:49 PM, David Hart via swift-evolution
> <swift-evolution@swift.org> wrote:
>
>
> I am also for removing associated type inference, and I guess if it needs to
> be done, its now. Concerning SubSequence, isn’t that supposed to be away
> post Swift-3 once we have some of the more powerful generics?
>
>
> I'm not aware of any generics features that will allow us to remove
> SubSequence.
>
>
> Generalized existentials provide an intelligent default value on Sequence
> for SubSequence and Iterator, if Element was an associated type. There would
> still be efficiencies possible if you were able to specify these associated
> types as concrete types.

I would be very concerned about performance regressions because of
SubSequence being defined as an existential.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j<i;j++){if(!(i%j)){j=0;break;}}if
(j){printf("%d\n",i);}}} /*Dmitri Gribenko <griboz...@gmail.com>*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Draft] UnsafeRawPointer API

2016-06-28 Thread Dmitri Gribenko via swift-evolution
On Tue, Jun 28, 2016 at 2:17 PM, Andrew Trick  wrote:
>
>> On Jun 28, 2016, at 1:53 PM, Dmitri Gribenko  wrote:
>>
>> Hi Andy,
>>
>> Everything is clear now, thank you!
>>
>> On Tue, Jun 28, 2016 at 1:02 PM, Andrew Trick  wrote:
>>> Initializing via a typed pointer, in addition to changing the temporal 
>>> memory state, also imposes a type on the allocated memory for the entire 
>>> lifetime of the memory itself, from allocation to deallocation.
>>
>> I see.  Given that UnsafeMutablePoiner.initialize() has this very
>> important difference in semantics, did you consider reflecting it in
>> the name?  Something like '.bindTypeAndInitialize()' -- but I'm sure a
>> better wording is possible.
>
> Yes, I did consider that. I’m still open to it--maybe 
> ‘.typedInitialize(with:). But...
>
> (1) It’s awkward. The developer isn’t interested in binding the type at that 
> point. It’s just a side effect of the way their unsafe pointer is being used.
>
> (2) It would imply that the ‘.bindAndInitialize' entry point is the only way 
> to bind the type of allocated memory. But once you have a typed pointer, it’s 
> easy to initialize memory via a simple assignment:
> ptrToA[0] = A() // where A is trivial
> If ptrToA was in an uninitialized state, then that also binds the type.

It would be good to call this out in the proposal (I did not get this
part from the clarifications that you posted this morning.)  So the
rule is that every typed store binds the type?

> Instead, I tried to focus on discouraging the unsafe pointer cast that leads 
> to this situation. The important thing is that we have an alternate “safe” 
> API so that most developers just don’t need to think about it.

That's a good goal.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Draft] UnsafeRawPointer API

2016-06-28 Thread Dmitri Gribenko via swift-evolution
Hi Andy,

Everything is clear now, thank you!

On Tue, Jun 28, 2016 at 1:02 PM, Andrew Trick  wrote:
> Initializing via a typed pointer, in addition to changing the temporal memory 
> state, also imposes a type on the allocated memory for the entire lifetime of 
> the memory itself, from allocation to deallocation.

I see.  Given that UnsafeMutablePoiner.initialize() has this very
important difference in semantics, did you consider reflecting it in
the name?  Something like '.bindTypeAndInitialize()' -- but I'm sure a
better wording is possible.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Draft] UnsafeRawPointer API

2016-06-27 Thread Dmitri Gribenko via swift-evolution
Hi Andy,

Thank you for the proposal!  A few comments from me.

- In the "Custom memory allocation section" you write:

> Note: The same allocated raw memory cannot be used both for this custom 
> memory allocation case and for the C buffer case above because the C buffer 
> requries that the allocated raw memory is always initialized to the same type.

Could you provide more explanation?  I'm not quite getting it.  Is
this because of binding -- are you saying that there is no way to
un-bind the type?

- In the "Accessing uninitialized memory with a typed pointer (binding
the type)" section you write

> This cast explicitly signals the intention to bind the raw memory to the 
> destination type.

I think that "signals the intention" is not a strong enough wording,
it is open to interpretations.  Either it is a no-op "intention" (that
can be retracted) or it is the actual binding.  From other discussions
in this thread, I think you are proposing that the .toType() method
actually binds the memory to a type.  Is this right?  Here's what made
me think this way:

> The following code is undefined:
> ```
> ptrA = rawPtr.cast(to: UnsafePointer.self)
> ptrA.initialize(with: A())
> ptrA.deinitialize()
> ptrB = rawPtr.cast(to: UnsafePointer.self)
> ptrB.initialize(with: B())
> ```
> It is hard to spot the difference between the two styles without drawing 
> attention to the unsafe cast.

- In the same section, in the table, it is not clear whether the
"tptr.deinitialize" operation un-binds the memory type, or does not
have effect on it.  Which way is it?  Can I replace
"tptr.initialize(t2: T)" with "tptr.initialize(u1: U)"?

- Is it valid to access an ARC reference to a class MyClass that
conforms to MyProtocol with aliasing pointers,
UnsafeMutablePointer, UnsafeMutablePointer, and
'UnsafeMutablePointer' ?  What about
'UnsafeMutablePointer' ?

- There's no API to convert from UnsafeMutableRawPointer to
UnsafeMutablePointer without either doing an initialization, or
binding the type.  Is this on purpose?  The reason why I'm asking is
that initialization does not seem to be binding the type (I couldn't
find that in the proposal), but still performs the conversion,
allowing further code to use typed memory access.  If this allows the
optimizer to get the desired guarantees about memory, why is binding
important?  (I'm probably completely confused about this point.)

- Just wanted to mention that we'd probably need 'raw' variants of
atomic operations for stdlib-internal use, but you probably already
noticed that while working on the branch.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Pitch] Remove type inference for associated types

2016-06-25 Thread Dmitri Gribenko via swift-evolution
On Fri, Jun 24, 2016 at 10:50 PM, Austin Zheng via swift-evolution
 wrote:
> Hello all,
>
> Per Chris Lattner's list of open Swift 3 design topics
> (http://article.gmane.org/gmane.comp.lang.swift.evolution/21369), I've put
> together a proposal for removing type inference for associated types.

Hi Austin,

Thank you for starting this discussion!  There's one other alternative
that I mentioned in one of the previous threads on this subject.  The
idea is to limit the inference so that the sizes and the complexity of
the problems that the type checker has to solve become tractable with
a simple algorithm, not a full constrain solver.

Currently, as far as I understand, the type checker solves for all
associated types for a protocol conformance in a single giant step,
during which every decision can affect every other decision.  My
suggestion is that we keep associated type inference for the simple
cases where it is obvious what the user meant.  The author of the
protocol would be able to identify these simple cases and define how
exactly the inference should happen.  For example:

protocol Collection {
  associatedtype Index

  @infers(Index)
  var startIndex: Index

  // Does not affect associated type inference, types have to match
with decisions made by other declarations.
  var endIndex: Index

  // Does not affect associated type inference.
  subscript(i: Index) -> Iterator.Element

  associatedtype Iterator

  @infers(Iterator)
  func iterator() -> Iterator
}

Under the current system, every declaration in a conforming type that
matches a requirement that mentions 'Index' can affect the inference.
That is, 'Index' is inferred from all declarations in the conforming
type.   But there is no reason to make it that general -- the protocol
author knows that 'var startIndex' in the conforming type has be of
the right type, and there is no reason for other declaration to affect
the decision about what 'Index' is resolved to.  Under the proposed
rule, there is at most one declaration that the protocol author is
allowed to designate with @infers, that is allowed to affect the
inference.  If there is no @infers for a certain associated type, then
it is never inferred and should always be specified explicitly.

This is the basic idea, I'm sure there are corner cases I haven't
thought about (e.g., how does this interact with constrained
extension, can we still solve everything with a simple algorithm?)
But the reason why I'm suggesting this alternative is that I'm
concerned that in simple cases like inferring the 'Index' and
'Iterator' typealiases having to specify them manually is just
boilerplate, that does not add to clarity, and, I believe, can be
inferred by the type checker without involving a heavy constrain
solver.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Shorthand unwrap proposal

2016-06-23 Thread Dmitri Gribenko via swift-evolution
On Thu, Jun 23, 2016 at 9:25 AM, James Campbell via swift-evolution
 wrote:
> So if the function I run inside of the map has a return value of Void will
> that still compile ?

Yes.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Shorthand unwrap proposal

2016-06-23 Thread Dmitri Gribenko via swift-evolution
On Thu, Jun 23, 2016 at 8:36 AM, James Campbell via swift-evolution
 wrote:
> I was wondering if people would be open to adding an unwrap method to the
> Optional type,  I already have a method like this which shortens code for
> me.
>
> So this:
>
> let myReallyLongOptionalName: String? = "Hey"
>
> if let string = myReallyLongOptionalName {
>   doSomethingWith(string)
> }
>
> Could become"
>
> let myReallyLongOptionalName: String? = "Hey"
>
> myReallyLongOptionalName.unwrap {
>   doSomethingWith($0)
> }

We have that, it is called '.map'.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Revisiting SE-0041 Names

2016-06-23 Thread Dmitri Gribenko via swift-evolution
On Thu, Jun 23, 2016 at 2:00 AM, Xiaodi Wu  wrote:
> On Thu, Jun 23, 2016 at 1:26 AM, David Sweeris via swift-evolution
>  wrote:
>>
>>
>> > On Jun 22, 2016, at 19:35, Dmitri Gribenko  wrote:
>> >
>> >> On Wed, Jun 22, 2016 at 5:15 PM, David Sweeris 
>> >> wrote:
>> >> That's a really interesting idea. Is "Syntax" a placeholder, or is that
>> >> the intended name?
>> >
>> > It is the best name we could come up with, we are open to better
>> > suggestions.
>>
>> I guess it depends on the intended semantics of the "namespace". If the
>> purpose is to be a container for the various LiteralConvertible protocols,
>> then maybe something like `AcceptsLiteralType.Integer` might be better? It's
>> a bit wordy, though.
>
>
> I get what's being aimed at here, but I think the meaning of `Syntax` in
> this context is indecipherable. IIUC, the point to be conveyed by the term
> is that a literal has no type until it is supplied as an argument to the
> initializer and becomes typed.

The point of using "Syntax" is to emphasize that this protocol is for
integration with the language syntax.  The "Syntax" pseudo-namespace
groups protocols that provide a special kind of a capability --
changing the meaning of builtin language syntax.  This protocol is not
meant to be coded against, used in other APIs or handled by the code
in any other way except by being adopted (except maybe in the standard
library code itself).

Should we add any other compiler interfaces that affect how builtin
syntax works, they would also go into the "Syntax" namespace.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Revisiting SE-0041 Names

2016-06-22 Thread Dmitri Gribenko via swift-evolution
On Wed, Jun 22, 2016 at 7:42 PM, Matthew Johnson  wrote:
>
> On Jun 22, 2016, at 1:55 PM, Dmitri Gribenko  wrote:
>
> On Wed, Jun 22, 2016 at 11:04 AM, Erica Sadun via swift-evolution
>  wrote:
>
> Proposal:
> https://github.com/apple/swift-evolution/blob/master/proposals/0041-conversion-protocol-conventions.md
>
> Rejection: "The feedback on the proposal was generally positive about the
> idea of renaming these protocols, but the specific names in the proposal are
> not well received, and there is no apparent confluence in the community on
> better names.  The core team prefers discussion to continue -- if/when there
> is a strong proposal for a better naming approach, we can reconsider
> renaming these."
>
> John McCall: "To be clear, I don't care about the name.  If you want to
> rename IntegerLiteralConvertible to IntegerLiteral or whatever, I won't drag
> the conversation into the muck again. :)  It's the design of the
> requirements that I'm pretty opposed to revisiting."
>
> The Problem: This is really the last chance to rationalize this across the
> language and to evaluate whether other protocol groups should have a core
> scheme for naming.
>
>
> Hi Erica,
>
> I would like to re-state the feedback from Dave Abrahams, Max Moiseev
> and me from the last time this was discussed.  Unfortunately I can't
> find the exact email, so I can't provide a link.
>
> - The "literal" protocols are not about conversion, they are about
> adopting a certain syntax provided by the language.  "Convertible" in
> the name is a red herring: a type can't be convertible from an integer
> literal because there is no "IntegerLiteral" entity in the type
> system.  The literal *becomes* typed as the corresponding literal type
> (e.g., Int or String), and as far as the user at the call site is
> concerned, there is no visible conversion (even if one is happening
> behind the scenes).
>
> Our suggestion was to focus on the "adopting the syntax" part.  We
> suggested moving the "literal convertible" protocols into a
> pseudo-namespace "Syntax".  It could be implemented like this:
>
> protocol _IntegerLiteralSyntax {}
> enum Syntax {
>  typealias IntegerLiteral = _IntegerLiteralSyntax
> }
>
> And used like this:
>
> struct Int : Syntax.IntegerLiteral {}
>
>
> I’m working on a draft of this proposal right now.  I have a couple
> questions.
>
> First, I’d like to list the standard library team as co-authors if you
> desire because this is really your idea.  Let me know what you would prefer.

Thank you.  I don't mind either way.

> Second, I wonder if it might make more sense to name the protocols
> `Syntax.IntegerLiteralInitializable`.  Dave has opposed `Initializable` as a
> general convention because it implies pure syntax and doesn’t carry any
> semantics.  But in this case the semantics *are* essentially the syntax.
> Erica pointed out to me off list that at the usage site the
> `Syntax.IntegerLiteral` names could confuse somebody into thinking in terms
> of *isa* rather than *can do* (i.e. Int is an IntegerLiteral rather than Int
> can be *initialized* with an IntegerLiteral).
>
> Please let me know if this name change would be acceptable to the standard
> library team or may be met with resistance.  I want this proposal to be
> acceptable to the team from the start.

IIRC the consensus that Dave, Max and I reached was
`Syntax.IntegerLiteral`, but this does not represent the opinion of
the core team.  (We did not talk to the whole team, just the three of
us.)

I think the possibility of confusion is very small because users will
not refer to the protocol as 'IntegerLiteral', it will be qualified as
'Syntax.IntegerLiteral'.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Revisiting SE-0041 Names

2016-06-22 Thread Dmitri Gribenko via swift-evolution
On Wed, Jun 22, 2016 at 4:43 PM, Matthew Johnson  wrote:
>
> On Jun 22, 2016, at 1:55 PM, Dmitri Gribenko  wrote:
> protocol _IntegerLiteralSyntax {}
> enum Syntax {
>  typealias IntegerLiteral = _IntegerLiteralSyntax
> }
>
> And used like this:
>
> struct Int : Syntax.IntegerLiteral {}
>
>
> Is anyone on the core team planning to write up a proposal for this change?

Your help would be most appreciated!

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Revisiting SE-0041 Names

2016-06-22 Thread Dmitri Gribenko via swift-evolution
On Wed, Jun 22, 2016 at 5:15 PM, David Sweeris  wrote:
> That's a really interesting idea. Is "Syntax" a placeholder, or is that the 
> intended name?

It is the best name we could come up with, we are open to better suggestions.

> Also, why an enum? Especially one without any cases...

It is not possible to create an instance of an enum that does not have
cases.  It becomes essentially a namespace.

> Was all this already discussed in a thread that I missed (or have otherwise 
> forgotten about)?

This feedback was provided in one of the threads about SE-0041, but I
can't find the link.  It did not get much discussion at that time.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Revisiting SE-0041 Names

2016-06-22 Thread Dmitri Gribenko via swift-evolution
On Wed, Jun 22, 2016 at 12:57 PM, David Sweeris <daveswee...@mac.com> wrote:
>
>> On Jun 22, 2016, at 1:55 PM, Dmitri Gribenko via swift-evolution 
>> <swift-evolution@swift.org> wrote:
>>
>> On Wed, Jun 22, 2016 at 11:04 AM, Erica Sadun via swift-evolution
>> <swift-evolution@swift.org> wrote:
>>
>> Hi Erica,
>>
>> I would like to re-state the feedback from Dave Abrahams, Max Moiseev
>> and me from the last time this was discussed.  Unfortunately I can't
>> find the exact email, so I can't provide a link.
>>
>> - The "literal" protocols are not about conversion, they are about
>> adopting a certain syntax provided by the language.  "Convertible" in
>> the name is a red herring: a type can't be convertible from an integer
>> literal because there is no "IntegerLiteral" entity in the type
>> system.  The literal *becomes* typed as the corresponding literal type
>> (e.g., Int or String), and as far as the user at the call site is
>> concerned, there is no visible conversion (even if one is happening
>> behind the scenes).
>>
>> Our suggestion was to focus on the "adopting the syntax" part.  We
>> suggested moving the "literal convertible" protocols into a
>> pseudo-namespace "Syntax".  It could be implemented like this:
>>
>> protocol _IntegerLiteralSyntax {}
>> enum Syntax {
>>  typealias IntegerLiteral = _IntegerLiteralSyntax
>> }
>>
>> And used like this:
>>
>> struct Int : Syntax.IntegerLiteral {}
>>
>> - For protocols that are representing conversions between types that
>> actually exist in the library, there is not enough precedent yet to
>> make a general conclusion and standardize a pattern.
>
> I’m not sure I understand… In this example, has “IntegerLiteralConvertible” 
> been renamed to “_IntegerLiteralSyntax”?

That's right.  But we want users to refer to the protocol as
'Syntax.IntegerLiteral'.  If/once we get either submodules or
protocols nested in enums, we can move the actual definition to be
nested.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j<i;j++){if(!(i%j)){j=0;break;}}if
(j){printf("%d\n",i);}}} /*Dmitri Gribenko <griboz...@gmail.com>*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Revisiting SE-0041 Names

2016-06-22 Thread Dmitri Gribenko via swift-evolution
On Wed, Jun 22, 2016 at 11:04 AM, Erica Sadun via swift-evolution
 wrote:
> Proposal:
> https://github.com/apple/swift-evolution/blob/master/proposals/0041-conversion-protocol-conventions.md
>
> Rejection: "The feedback on the proposal was generally positive about the
> idea of renaming these protocols, but the specific names in the proposal are
> not well received, and there is no apparent confluence in the community on
> better names.  The core team prefers discussion to continue -- if/when there
> is a strong proposal for a better naming approach, we can reconsider
> renaming these."
>
> John McCall: "To be clear, I don't care about the name.  If you want to
> rename IntegerLiteralConvertible to IntegerLiteral or whatever, I won't drag
> the conversation into the muck again. :)  It's the design of the
> requirements that I'm pretty opposed to revisiting."
>
> The Problem: This is really the last chance to rationalize this across the
> language and to evaluate whether other protocol groups should have a core
> scheme for naming.

Hi Erica,

I would like to re-state the feedback from Dave Abrahams, Max Moiseev
and me from the last time this was discussed.  Unfortunately I can't
find the exact email, so I can't provide a link.

- The "literal" protocols are not about conversion, they are about
adopting a certain syntax provided by the language.  "Convertible" in
the name is a red herring: a type can't be convertible from an integer
literal because there is no "IntegerLiteral" entity in the type
system.  The literal *becomes* typed as the corresponding literal type
(e.g., Int or String), and as far as the user at the call site is
concerned, there is no visible conversion (even if one is happening
behind the scenes).

Our suggestion was to focus on the "adopting the syntax" part.  We
suggested moving the "literal convertible" protocols into a
pseudo-namespace "Syntax".  It could be implemented like this:

protocol _IntegerLiteralSyntax {}
enum Syntax {
  typealias IntegerLiteral = _IntegerLiteralSyntax
}

And used like this:

struct Int : Syntax.IntegerLiteral {}

- For protocols that are representing conversions between types that
actually exist in the library, there is not enough precedent yet to
make a general conclusion and standardize a pattern.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Pitch] Remove transparent bridging between Swift strings and char *

2016-06-22 Thread Dmitri Gribenko via swift-evolution
On Wed, Jun 22, 2016 at 9:37 AM, Kenny Leung via swift-evolution
 wrote:
> Hi All.
>
> In the spirit of Chris’ focus on Swift 3 message…
>
> I’ve been working on calling C code that takes “const char * const *” 
> arguments, and it ain’t easy, but that can be left for a future proposal…
>
> What does surprise me is that Swift String bridges directly into “char *” 
> arguments in C as nul-terminated C strings, apparently preserving unicode and 
> all. I can find nothing on bridging to “char *” in “Using Swift with Cocoa 
> and Objective-C"

I think it is too useful for the C interop that it would not be
feasible for it to be removed completely.  One tweak that I think we
should consider making is removing this implicit conversion when
calling Swift code, and only leave it for calling imported functions.
The reasoning is that Swift code should not be using
UnsafePointer to pass strings around.

We might need to leave an escape hatch (an underscored attribute) to
opt into this behavior for the overlays though.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Pitch] remove(at: Set)

2016-06-19 Thread Dmitri Gribenko via swift-evolution
On Sat, Jun 18, 2016 at 10:59 PM, Karl  wrote:
> What exactly are the guarantees for index safety across mutations? Both
> Collection and Indexable stop short of making any kind of guarantees about
> what happens to indexes after you mutate. For example, popFirst() has the
> potential to invalidate all stored indexes, but you wouldn’t know that if
> you were just working in terms of Collection.

https://github.com/apple/swift/blob/master/docs/IndexInvalidation.rst

Mutating a collection invalidates all indices.  Specific types and
protocols relax this:

- Replacing an element in a MutableCollection does not invalidate any indices.

- RangeReplaceableCollection only invalidates indices after the one
where the structural mutation happened.  For example,
replaceRange(a.. If we can guarantee tail-end removal is safe, a minimalist’s solution could
> be:
>
> extension RangeReplaceableCollection {
>
> mutating func remove(at
> indexes: S) {
>
> for idx in indexes.sorted(isOrderedBefore: >) {
> remove(at: idx)
> }
> }
> }

Yes, this works, but it is O(n^2).  We can do better.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Pitch] remove(at: Set)

2016-06-18 Thread Dmitri Gribenko via swift-evolution
On Sat, Jun 18, 2016 at 9:09 PM, Karl via swift-evolution
 wrote:
> So like most good pitches, this one comes about because of a bug I recently 
> fixed which seems common and subtle enough that I think it would be nice to 
> include in the standard library.
>
> Removing a collection of elements at once from a collection. You might want 
> to do this in some kind of advanced filtering code. In my case, our code was 
> merging adjacent elements in-place, and storing a list of indexes that were 
> no longer required because they were now part of a merged element, and then 
> we cleaned up the duplicates by removing those indexes.
>
> A näive implementation might look like this:
>
> for index in indexesToRemove {
> myArray.remove(at: index)
> }
>
> However, as the array is mutated, those indexes won’t make sense any more. 
> You’ll end up with invalid results - for example, if you have the array 
> [0,1,2] and indexesToRemove is [0,1], your resulting array will actually be 
> [1] (not [2], as expected). Actually removing a batch of indexes is subtly 
> more complex. Here’s my generic implementation:
>
> extension RangeReplaceableCollection where Index:Hashable, 
> Self:BidirectionalIndexable {
>
> mutating func remove(at indexes: Set) {

Hi Karl,

This sounds like a good idea to me.  You can make this method even
more useful by making it generic over collections of appropriate
indices.  Then you can drop the Hashable requirement for indices.

> var removed : IndexDistance = 0
> for idx in indexes.sorted() {
> remove(at: index(idx, offsetBy: -removed))
> removed = removed.advanced(by: 1)

This implementation will not work correctly for all collections, since
removing an element at the beginning of the collection invalidates the
indices pointing at the tail.  Adjusting the index by "-removed" won't
help, the indices are invalidated already.  (Consider what happens in
a UnicodeScalar String view where indices have to jump over variable
number of code units in the underlying storage.)

You can make it correct (and work even faster, in O(n)) by walking
from the start, and moving the elements into place, and then
truncating the collection.  You will need to require
MutableCollection.

You can make a variant that works for collections that are not
MutableCollections, but then the runtime will be O(n^2).  You will
need to remove elements one by one walking from the end and shifting
the tail of the collection.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Discussion] Type hierarchy translation consistency

2016-06-12 Thread Dmitri Gribenko via swift-evolution
On Sun, Jun 12, 2016 at 3:33 AM, Adrian Zubarev via swift-evolution
 wrote:
> Just looked up the current implementation of this:
>
> extension String {
>   /// The index type for subscripting a string.
>   public typealias Index = CharacterView.Index
>
>   /// A type used to represent the number of steps between two
> `String.Index`
>   /// values, where one value is reachable from the other.
>   ///
>   /// In Swift, *reachability* refers to the ability to produce one value
> from
>   /// the other through zero or more applications of `index(after:)`.
>   public typealias IndexDistance = CharacterView.IndexDistance
>
> So the whole thing is somehow a wrong translation I’d guess.
>
> Should I file a bug?

Yes, please!

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [swift-evolution-announce] [Returned for revision] SE-0089: Renaming String.init(_: T)

2016-05-30 Thread Dmitri Gribenko via swift-evolution
On Sun, May 29, 2016 at 11:23 PM, Brent Royal-Gordon via
swift-evolution  wrote:
> There are *very* few conformances to Streamable in the standard library—just 
> Character, String, and UnicodeScalar. I think that Streamable is for data 
> that can be *directly* written to an output stream, whereas 
> CustomStringConvertible is a way to convert an instance that *isn't* directly 
> Streamable into something Streamable.

Right, this was the intent.  The intent was that Streamable is
something that is a container of string-like data, as opposed to other
things that have-a string representation.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Pitch] Remove associated type inference

2016-05-25 Thread Dmitri Gribenko via swift-evolution
On Wed, May 25, 2016 at 3:42 PM, Leonardo Pessoa <m...@lmpessoa.com> wrote:

> On Wednesday, 25 May 2016, Dmitri Gribenko via swift-evolution <
> swift-evolution@swift.org> wrote:
>
>> On Wed, May 25, 2016 at 2:52 PM, David Hart <da...@hartbit.com> wrote:
>> >
>> >> On 25 May 2016, at 23:47, Dmitri Gribenko <griboz...@gmail.com> wrote:
>> >>
>> >> On Wed, May 25, 2016 at 2:43 PM, David Hart via swift-evolution
>> >> <swift-evolution@swift.org> wrote:
>> >>> Impact on Existing Code
>> >>>
>> >>> This is a breaking change that will require conforming types which
>> relied on
>> >>> the inference, including in the Standard Library, to explicitly
>> declare
>> >>> associated types. A Fix-It could be introduced to add the typealias
>> and
>> >>> leave the type to be filled in. That way, all the type inference
>> could be
>> >>> removed from the compiler.
>> >>
>> >> Please show an example -- for example, what a smallest collection type
>> >> will look like.
>> >
>> > Isn’t that the example in the Detailed Design section? What other
>> example were you thinking of?
>>
>> You are showing an iterator.  Try doing a collection, it has many more
>> associated types most of which are defaulted.
>>
>> >>> Alternatives Considered
>> >>>
>> >>> The only alternative is to keep the inference with the known
>> consequences on
>> >>> the compiler.
>> >>
>> >> Sorry, that's not fair :)  There is a middle ground -- limited
>> >> inference.  For example, in Collection, we don't need Index to be
>> >> inferrable from every declaration that mentions it.  We can add a
>> >> feature to declare that the type of 'var startIndex' infers
>> >> 'associatedtype Index' (via an appropriate attribute).  It is true
>> >> that this approach would not remove global inference as such, but it
>> >> will make it a much easier problem I believe.
>> >
>> > This sounds like a more complicated solution: it does not remove global
>> inference and complicates the language with an additional attribute only to
>> help the compiler. I don’t see many advantages to this solution.
>>
>> The advantage is that we can keep the boilerplate down, and make the
>> problem easier in the compiler.
>
>
> If the issue is easing the work of the compiler, are you suggesting
> dropping the entire type inference? I don't really think removing it here
> will "solve" anything.
>

No, I'm suggesting to limit the scope.

protocol Collection {
  typealias Index
  @infers(Index)
  var startIndex: Index { get }
  var endIndex: Index { get }
  subscript(i: Index) -> Iterator.Element
}

Here, only 'var startIndex' in a conforming type would be causing 'Index'
to be inferred.  'endIndex' and subscript won't have any effect on the
inference.  My suggestion is that we will only allow one such declaration
to exist.  This is a much simpler problem, I think, than solving a
constraint system that involves all declarations that mention Index (as it
is now).

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j<i;j++){if(!(i%j)){j=0;break;}}if
(j){printf("%d\n",i);}}} /*Dmitri Gribenko <griboz...@gmail.com>*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Pitch] Remove associated type inference

2016-05-25 Thread Dmitri Gribenko via swift-evolution
On Wed, May 25, 2016 at 2:52 PM, David Hart  wrote:
>
>> On 25 May 2016, at 23:47, Dmitri Gribenko  wrote:
>>
>> On Wed, May 25, 2016 at 2:43 PM, David Hart via swift-evolution
>>  wrote:
>>> Impact on Existing Code
>>>
>>> This is a breaking change that will require conforming types which relied on
>>> the inference, including in the Standard Library, to explicitly declare
>>> associated types. A Fix-It could be introduced to add the typealias and
>>> leave the type to be filled in. That way, all the type inference could be
>>> removed from the compiler.
>>
>> Please show an example -- for example, what a smallest collection type
>> will look like.
>
> Isn’t that the example in the Detailed Design section? What other example 
> were you thinking of?

You are showing an iterator.  Try doing a collection, it has many more
associated types most of which are defaulted.

>>> Alternatives Considered
>>>
>>> The only alternative is to keep the inference with the known consequences on
>>> the compiler.
>>
>> Sorry, that's not fair :)  There is a middle ground -- limited
>> inference.  For example, in Collection, we don't need Index to be
>> inferrable from every declaration that mentions it.  We can add a
>> feature to declare that the type of 'var startIndex' infers
>> 'associatedtype Index' (via an appropriate attribute).  It is true
>> that this approach would not remove global inference as such, but it
>> will make it a much easier problem I believe.
>
> This sounds like a more complicated solution: it does not remove global 
> inference and complicates the language with an additional attribute only to 
> help the compiler. I don’t see many advantages to this solution.

The advantage is that we can keep the boilerplate down, and make the
problem easier in the compiler.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Pitch] Remove associated type inference

2016-05-25 Thread Dmitri Gribenko via swift-evolution
On Wed, May 25, 2016 at 2:43 PM, David Hart via swift-evolution
 wrote:
> Impact on Existing Code
>
> This is a breaking change that will require conforming types which relied on
> the inference, including in the Standard Library, to explicitly declare
> associated types. A Fix-It could be introduced to add the typealias and
> leave the type to be filled in. That way, all the type inference could be
> removed from the compiler.

Please show an example -- for example, what a smallest collection type
will look like.

> Alternatives Considered
>
> The only alternative is to keep the inference with the known consequences on
> the compiler.

Sorry, that's not fair :)  There is a middle ground -- limited
inference.  For example, in Collection, we don't need Index to be
inferrable from every declaration that mentions it.  We can add a
feature to declare that the type of 'var startIndex' infers
'associatedtype Index' (via an appropriate attribute).  It is true
that this approach would not remove global inference as such, but it
will make it a much easier problem I believe.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Review] SE-0089: Replace protocol<P1, P2> syntax with Any<P1, P2>

2016-05-25 Thread Dmitri Gribenko via swift-evolution
I like the direction about creating a unified syntax for current
implementation of existentials and future generalized existentials.  I
am concerned about the chosen syntax though, I don't think it reads
right.  I read Any as a union type.

var x1: Any // OK, 'x1' can have any dynamic type.
var x2: Any // OK, 'x2' is any value that conforms to
ErrorProtocol.

var x3: Any // 'x3' is any of the following
types.  Either a Hashable, or a Comparable.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [swift-evolution-announce] [Review] SE-0041: Updating Protocol Naming Conventions for Conversions

2016-05-15 Thread Dmitri Gribenko via swift-evolution
On Sat, May 14, 2016 at 7:45 AM, Daniel Steinberg via swift-evolution
 wrote:
> I appreciate your rework on this - I still don’t understand one thing and
> disagree with a second:
>
> (1) I don’t understand what the word “Custom” adds to
> CustomStringRepresentable and CustomDebugStringRepresentable and would drop
> that prefix (even if it remains Convertible).

In Swift, every value has a string and a debugging string
representation, synthesized by the runtime.  These protocols allow
customizing the default behavior.  We don't want users to write any
APIs against these protocols, because it is the wrong thing to do.

In Swift 1, when the protocols were named Printable and
DebugPrintable, many users wrote APIs like this:

func printAll(_ values: [Printable]) {
  for x in values { print(x) }
}

'Printable' is a wrong constraint.  Everything is printable, and
user-defined types that are happy with the default string
representation don't customize it; structural types (function types,
tuples) can not adopt a protocol at all.  Users can't pass instances
of such types to this overconstrained API.  The right API to design
is:

func printAll(_ values: [Any]) {
  for x in values { print(x) }
}

Motivation behind renaming Printable to CustomStringRepresentable was
to discourage writing APIs against these protocols.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Allow FloatLiteralType in FloatLiteralConvertible to be aliased to String

2016-05-06 Thread Dmitri Gribenko via swift-evolution
On Fri, May 6, 2016 at 2:24 AM, Morten Bek Ditlevsen via
swift-evolution  wrote:
> How does that sound? Is it completely irrational to allow the use of Strings 
> as
> the intermediary representation of float literals?
> I think that it makes good sense, since it allows for arbitrary precision.

Hi,

I think you are raising an important problem, but using String as the
intermediate type does not strike me as an efficient and clean
solution.  We already have DictionaryLiteral, and extending that
family to also include FloatLiteral seems like the right direction to
me.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Review] SE-0078: Implement a rotate algorithm, equivalent to std::rotate() in C++

2016-05-06 Thread Dmitri Gribenko via swift-evolution
On Fri, May 6, 2016 at 12:53 AM, Nate Cook  wrote:
> That brings up the question of which protocol to add the requirement to?
> Without a MutableBidirectionalProtocol (which we don't want, right?), we'd
> need to add it to MutableCollection. While a mutating reverse() is possible
> for a forward collection, it has significant space complexity, since it
> works either by creating an array of the indices or through recursion. We
> would also have reverse() available on some collections that don't have
> reversed(). Does that sound alright?

Good question!  I don't think we should provide reverse() on forward
collections.

I think we can play some tricks here.  We can add an underscored
_customReverse() requirement to MutableCollection, a default
implementation that traps, and two specialized implementations for
forward and bidirectional collections.  We would then add a protocol
extension (not a requirement) reverse() on MutableCollection where
Self : BidirectionalCollection that will call _customReverse().

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Review] SE-0078: Implement a rotate algorithm, equivalent to std::rotate() in C++

2016-05-05 Thread Dmitri Gribenko via swift-evolution
On Thu, May 5, 2016 at 5:11 PM, Nate Cook  wrote:
> Thanks for the feedback, Dmitri , this all looks excellent! I'll work on 
> updating the proposal.
>
>> On May 5, 2016, at 6:13 PM, Dmitri Gribenko  wrote:
>>
>> On Tue, May 3, 2016 at 8:57 PM, Chris Lattner via swift-evolution
>>  wrote:
>>> Hello Swift community,
>>>
>>> The review of "SE-0078: Implement a rotate algorithm, equivalent to 
>>> std::rotate() in C++" begins now and runs through May 9.
>>
>> Hi,
>>
>> I'm posting this feedback on behalf of Dave Abrahams, Max Moiseev and
>> myself.  We met and discussed the proposal in great detail.
>>
>> First of all, we want to thank Nate and Sergey for proposing this API,
>> which is an important and useful algorithm.  We are generally in favor
>> of the proposal, but we would like to request a few changes.
>>
>> Could you make 'func rotate' a requirement in the MutableCollection
>> protocol?  This allows selecting the best implementation for a given
>> concrete type, even when calling from generic code.
>>
>> Could you explain why do we need a special implementation of
>> 'reverse()' for RandomAccessCollection?  We couldn't think of a
>> performance reason for this.
>
> With a bidirectional collection, you have to compare the high and low index 
> at each iteration, stopping when low >= high (before indices were Comparable, 
> this required two equality comparisons per iteration). With a random-access 
> collection, you can optimize the loop to use a fixed number of iterations, 
> which should be more efficient.

Good point!  In that case, 'reverse()' should also be a protocol
requirement, to allow dispatch to the most efficient version.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Review] SE-0073: Marking closures as executing exactly once

2016-05-05 Thread Dmitri Gribenko via swift-evolution
On Thu, May 5, 2016 at 3:27 AM, Gwendal Roué  wrote:
>>> I quite expect being able to throw out of a @noescape(once) block. Maybe 
>>> the sentence "it must not be executed on any path that throws" should be 
>>> removed from the proposal, should it have the implications you describe.
>>>
>>> Here is below what I expect this proposal to allow. So you see one 
>>> problematic case?
>>
>> Hi Gwendal,
>>
>> What about the following case?
>>
>> // Function which rethrows closure errors:
>> func f1(closure: @noescape(once) () throws -> ()) rethrows {
>>  try closure()
>> }
>>
>> let x: AnyObject
>> f1 {
>>  if someCondition() { x = MyClass() }
>>  if someOtherCondition() { throw MyError.Error() }
>>  x = MyOtherClass()
>> }
>>
>> How do you handle memory management for 'x' on the path that throws?
>> If the rule is that upon returning from f1 via a throw the variable
>> 'x' should not be initialized, then the closure passed to f1 has to
>> guarantee the deinitialization.  But f1 accepts an arbitrary closure.
>
> Hello Dmitri,
>
> To reason about @noescape(once) functions, the easiest way is to replace them 
> with `do`:
>
> let x: AnyObject
> do {
> if someCondition() { x = MyClass() }
> if someOtherCondition() { throw MyError.error }
> x = MyOtherClass()
> }
>
> This code does not compile because x can't be initialized to MyOtherClass().
>
> But I don't think this is your point. Your point was "how can the compiler 
> handle memory management ?".
>
> I can't answer this question, because I'm not competent enough. But if it can 
> handle the do { … } case, can't it also handle the f { … } case?

The difference is that the do{} case is type checked and codegen'ed
together with the rest of the function.  The f{} case has two
functions that are type checked and codegen'ed more or less
separately (the function that contains the call to f, and the closure
itself).  Moreover, with do{} the placement of the code block is
fixed.  With f{}, you can save a closure in a variable and then call
f(myClosure).  How would that affect the rules?  How would you
implement the desired analysis?

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Review] SE-0073: Marking closures as executing exactly once

2016-05-04 Thread Dmitri Gribenko via swift-evolution
On Wed, May 4, 2016 at 2:24 AM, Gwendal Roué  wrote:
>
>> Le 4 mai 2016 à 08:28, Pyry Jahkola via swift-evolution 
>>  a écrit :
>>
>> Here's my review of "SE-0073: Marking closures as executing exactly once".
>>
>>> What is your evaluation of the proposal?
>>
>> +1. I think this is a good idea and should be accepted (without extending 
>> the proposed scope).
>>
>> However, I think the proposal should be more explicit about the case when 
>> (and whether) the block itself throws. Specifically, I think we should 
>> highlight that the criterion that
>>
>>> it must not be executed on any path that throws
>>
>> implies that a @noescape(once) parameter itself cannot throw (until another 
>> language change allows otherwise).
>>
>> […]
>>
>> Being able to throw out of a @noescape(once) block […] would complicate the 
>> language by requiring that no one catches the error in the scope where 
>> uninitialised variables are defined. I suggest adding this remark to the 
>> Future directions.
>
> Hello Pyry,
>
> I quite expect being able to throw out of a @noescape(once) block. Maybe the 
> sentence "it must not be executed on any path that throws" should be removed 
> from the proposal, should it have the implications you describe.
>
> Here is below what I expect this proposal to allow. So you see one 
> problematic case?

Hi Gwendal,

What about the following case?

// Function which rethrows closure errors:
func f1(closure: @noescape(once) () throws -> ()) rethrows {
  try closure()
}

let x: AnyObject
f1 {
  if someCondition() { x = MyClass() }
  if someOtherCondition() { throw MyError.Error() }
  x = MyOtherClass()
}

How do you handle memory management for 'x' on the path that throws?
If the rule is that upon returning from f1 via a throw the variable
'x' should not be initialized, then the closure passed to f1 has to
guarantee the deinitialization.  But f1 accepts an arbitrary closure.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Review] SE-0065 A New Model for Collections and Indices

2016-05-02 Thread Dmitri Gribenko via swift-evolution
On Mon, May 2, 2016 at 3:08 PM, Karl via swift-evolution
 wrote:
> So, just confirming that the following is going to change:
>
> —
> var string= "test"
> let origLen   = 4
> let indexOne  = string.startIndex
>
> string.appendContentsOf("ANOTHERTEST")
>
> let indexTwo = indexOne.advancedBy(origLen, limit: string.endIndex)
>
> assert(indexTwo indexTwo.successor()   //<--- fatal error: cannot 
> increment endIndex
> —

Hi Karl,

Yes, this code would start working.

> Is this a consequence of the index needing to know its originating string for 
> successor() purposes?

That would be a plausible explanation, but I think that would be too
simple to be true :)  This code should even work in the current model,
but the current (buggy) behavior is caused by String indices keeping
an extra strong reference to the underlying storage, so the mutation
actually detaches the index from the updated string storage.

> Once this is implemented, will String.Index be portable across string 
> instances (presuming you bounds-check them, as I did above)?

Yes, within the prefix that was common to all strings and was created
in a common mutation history.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal] More Powerful Constraints for Associated Types

2016-04-29 Thread Dmitri Gribenko via swift-evolution
On Fri, Apr 29, 2016 at 4:02 AM, David Hart  wrote:
> But Collection has to have an extension which explicitly mentions
> IndexingIterator:
>
> extension Collection where Iterator == IndexingIterator {
> /// Returns an iterator over the elements of the collection.
> public func makeIterator() -> IndexingIterator {
> return IndexingIterator(_elements: self)
> }
> }
>
> And Array, for example, has to be explicit:
>
> public typealias Iterator = IndexingIterator<${Self}>

This might be a workaround for a compiler bug (that it couldn't infer the type).

> So I still don’t see how defining:
>
> associatedtype Iterator : IteratorProtocol = IndexingIterator
>
> has created any default behaviour.
>
> When you say "The fact that the compiler does not allow to use the inferred
> ‘Foo' type actually looks like a bug to me.”, could you give me an example
> of how you would have imagined this default behaviour to work in the case of
> Array? Would have expected Array not to have to define its typealias?

Right, I would expect Array to not need to mention Iterator at all in
its definition.

Take a look at stdlib/public/core/CollectionOfOne.swift.  It does not
define SubSequence or Indices.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal] More Powerful Constraints for Associated Types

2016-04-29 Thread Dmitri Gribenko via swift-evolution
On Fri, Apr 29, 2016 at 1:50 AM, David Hart  wrote:
> Hi Dimitri,
>
> Excuse me if I’m being dumb. I saw those example but I don’t understand
> their use.
>
> If I define a custom Collection, I still have the be explicit in the types I
> use where associated types are expected. Because I need to be explicit, I
> don’t understand how default associated types are used.
>
> Default parameters seem clear to me:
>
> func foobar(a: Int = 0) {}
> foo() // implicit uses default value
> foo(a: 1) // Explicit bypasses default value
>
> But default associated types are not:
>
> protocol Foobar {
> associatedtype Foo = Int
> func foobar(a: Foo)
> }
>
> class FoobarImpl : FooBar {
> func foobar(a: Foo) {} // error: Use of undeclared type ‘Foo’ - there is
> no such thing as an implicit use
> func foobar(a: Double) {} // This works but is explicit
> }

In a typical use, 'func foobar' would also be defaulted.  The
Collection.Iterator associated type and the makeIterator() method are
an example of this.

The fact that the compiler does not allow to use the inferred 'Foo'
type actually looks like a bug to me.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal] More Powerful Constraints for Associated Types

2016-04-29 Thread Dmitri Gribenko via swift-evolution
On Fri, Apr 29, 2016 at 12:25 AM, David Hart via swift-evolution
 wrote:
> I’ve taken some time to digest the current feedback and I’ve changed my mind. 
> The syntax for adding constraints to a sub-protocol in the protocol’s 
> definition where clause is starting to grow on me. Before I modify the 
> proposal, I'd still like to understand something:
>
> What is the use of declaring a default associated types with the `=` syntax 
> in protocols? I’ve never used them and I don’t understand what they provide.

Please take a look at the Collection protocol
(https://github.com/apple/swift/blob/master/stdlib/public/core/Collection.swift).

associatedtype Iterator : IteratorProtocol = IndexingIterator
associatedtype SubSequence : IndexableBase, Sequence = Slice
associatedtype Indices : IndexableBase, Sequence = DefaultIndices

Some collections want to customize these, but for simple ones the
defaults are usually fine.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal] More Powerful Constraints for Associated Types

2016-04-25 Thread Dmitri Gribenko via swift-evolution
On Mon, Apr 25, 2016 at 8:28 PM, Douglas Gregor via swift-evolution
 wrote:
> Did you consider an alternate syntax that puts the where clause outside the
> braces, e.g.,
>
> protocol R : Q where AssocType : P {
>   // …
> }

To me this reads like declaring a conditional conformance.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal] More Powerful Constraints for Associated Types

2016-04-25 Thread Dmitri Gribenko via swift-evolution
On Sun, Apr 24, 2016 at 1:34 PM, David Hart via swift-evolution
 wrote:
> Currently, associated type declarations can only express simple inheritance
> constraints and not the more sophisticated constraints available to generic
> types with the where expression. Some designs, including many in the
> Standard Library, require more powerful constraints for associated types to
> be truly elegant. For example, the SequenceType protocol can be declared as
> follows:

I completely support this.  This feature will unblock many
improvements in the standard library.  Currently users of some
protocols have to carry extra constraints in their own type
signatures, but we should be able to hoist these constraints into the
protocol definiton.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Review] SE-0065 A New Model for Collections and Indices

2016-04-18 Thread Dmitri Gribenko via swift-evolution
On Sun, Apr 17, 2016 at 11:14 PM, Thorsten Seitz  wrote:
> Preventing indices of one collection being used by another collection can be 
> done by using path dependent types like in Scala.
>
> Then 'i' would have type a.Index (where 'a' is the instance!) and therefore 
> b[i] would not typecheck as it would require an index of type b.Index

This is an interesting concept!  Would this work with slices?  You
should be able to use indices from slices with the base collection,
and vice-versa (when indices are in range).

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Draft] Expanded min/max algorithms

2016-04-17 Thread Dmitri Gribenko via swift-evolution
On Sat, Apr 16, 2016 at 11:50 PM, Taras Zakharko via swift-evolution
 wrote:
> Hi Nate,
>
>  I think this is a very useful addition! I also had a related proposal few
> days ago:
> https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160411/014665.html
>
>  I feel like min/max extension and element order belong to the same family
> of enhancements. If you are interested, maybe we can combine them together
> into a single proposal?

Thanks Nate and Taras!  I'd recommend to keep minmax and .order()
proposals separate.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Review] SE-0065 A New Model for Collections and Indices

2016-04-15 Thread Dmitri Gribenko via swift-evolution
On Fri, Apr 15, 2016 at 1:30 PM, Stephan Tolksdorf <s...@quanttec.com> wrote:
> On 2016-04-12 Dmitri Gribenko via swift-evolution wrote:
>>
>> Not even to mention that
>> indices are valid only in context of a particular collection instance,
>> so in this model you could validate an index against one collection
>> and use it with another one.
>
>
> The proposal requires Index values to be Comparable. Does that mean that
> indices from different collection instances should be comparable i.e. have a
> strict total order?

No, comparing indices from unrelated instances produces unspecified
results (incl. traps).

> And somewhat related: Is it safe in Swift (in contrast to C) to compare
> NativePointers into unrelated memory blocks?

Unfortunately, I don't know, but I'd like to know the answer, too :)
I don't think this is documented anywhere though, so it is technically
unspecified.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j<i;j++){if(!(i%j)){j=0;break;}}if
(j){printf("%d\n",i);}}} /*Dmitri Gribenko <griboz...@gmail.com>*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Review] SE-0065 A New Model for Collections and Indices

2016-04-12 Thread Dmitri Gribenko via swift-evolution
On Tue, Apr 12, 2016 at 4:27 AM, Brent Royal-Gordon
 wrote:
>>> (On the other hand, it might be that I'm conceiving of the purpose of 
>>> `limitedBy` differently from you—I think of it as a safety measure, but you 
>>> may be thinking of it specifically as an automatic truncation mechanism.)
>>
>> Hi Brent,
>>
>> Could you explain what kind of safety do you have in mind?  Swift will
>> guarantee memory safety even if you attempt to advance an index past
>> endIndex using the non-limiting overload.
>
> By "safety" here, I mean what I will call "index safety": not accidentally 
> using an index which would violate the preconditions of the methods or 
> properties you are planning to use it with. I think it's too easy to 
> accidentally overrun the permitted range of indices, and the API should help 
> you avoid doing that.

Hi Brent,

Thank you for the explanation.  Assuming that I am interpreting you
correctly, I can't agree with your conclusions though.

I want to make a point that avoiding precondition violations by
removing preconditions is not the solution.  When you design an API,
it frequently has some constraints on the arguments or on the
execution environment, which, when violated, prevent the API from
performing the operation correctly.  As an API designer, you document
these constraints, but for the implementation you have two choices:

1.  You rigorously check the constraints, and return back some
indicator of the failure back to the caller (a nil return, a thrown
error etc.)  This decision makes the checks guaranteed, permanent,
documented part of your API behavior.  Users can now rely on these
checks for their normal logic.  In this case, the constraints are not
preconditions that the user is required to satisfy.

2.  You perform the operation anyway, relying on the caller to satisfy
the constraints.  The constraints become preconditions.  The
implementation can still check some of the constraints for either QoI
reasons or memory safety reasons.  Apart from preventing memory safety
violations, the implementation is not required to check the
constraints.

Now the question becomes, given a certain API design problem, how do
you make a choice between (1) and (2)?  In some cases, the answer is
clear:

- You can be forced to make your constraints into checks in API
behavior.  Example: a network i/o operation can fail.  This is a
completely normal thing that networks do sometimes, and the caller of
networking code should be expected to deal with networking failures,
or such code can't work on a real network.

- Some preconditions just can't be checked at all, or can't be checked
in time that is acceptable for the intended API purpose.  A trivial
example is UnsafePointer.pointee (we can't know whether the pointer
actually points to an instance of a correct type).  Another example is
sort predicates -- we can't check that the order defined by the
predicate is indeed a strict weak ordering for all values of the type.
We can check that the predicate defines a strict weak order for all
values in a particular dataset, but that requires O(n^2) time while
sort() complexity is O(n log n).

What about those cases when both (1) and (2) are implementable?  There
exists a trade-off between making the API "resilient" to programming
mistakes and hiding bugs by not stopping the application when an issue
happens.  We are very conservative in Swift about hiding errors.

If your APIs document that they check preconditions and trap if they
are not satisfied, then developers can rely on it, and you are not
allowed to weaken remove the checks in future.  If the app can recover
from a precondition failure, the recovery path just becomes a part of
the API behavior.  You can end up with a system where every API can
signal failure back to the calling code.  Now users have to handle
these failures.  There are two ways to handle them:

- force-unwrap, or 'try!'.

- follow the advice of people who advocate never using force-unwrap
and 'try!'.  The code that does so will likely have a lot of untested,
untestable, and dead branches that try to deal defensively with
situations that can't happen, but the API forces them to do so anyway.

I don't think either option leads to good code.  Thus, it is only
reasonable that we design the API based on a purpose that we intend
for this API.

Let's talk about how this applies to Collection.

For example, Collection APIs in question that work with indices are
primitive APIs that the rest of Collection APIs build upon.  One of
these APIs, basically the reason why indices exist, is
Collection.subscript(Index).  Today the behavior is unspecified if the
index is not valid.  If we follow the principle that you outlined:

> not accidentally using an index which would violate the preconditions of the 
> methods or properties you are planning to use it with.

Collection.subscript(Index) should return an optional.  Does this
match your expectations?  If so, how do you 

Re: [swift-evolution] [Review] SE-0065 A New Model for Collections and Indices

2016-04-12 Thread Dmitri Gribenko via swift-evolution
On Mon, Apr 11, 2016 at 9:56 PM, Brent Royal-Gordon via
swift-evolution  wrote:
> (On the other hand, it might be that I'm conceiving of the purpose of 
> `limitedBy` differently from you—I think of it as a safety measure, but you 
> may be thinking of it specifically as an automatic truncation mechanism.)

Hi Brent,

Could you explain what kind of safety do you have in mind?  Swift will
guarantee memory safety even if you attempt to advance an index past
endIndex using the non-limiting overload.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Review] SE-0065 A New Model for Collections and Indices

2016-04-12 Thread Dmitri Gribenko via swift-evolution
On Mon, Apr 11, 2016 at 9:56 PM, Brent Royal-Gordon via
swift-evolution  wrote:
> So, imagine that we have a type like this in the standard library:
>
> /// Represents a pre-validated index. A pre-validated index received 
> from a given collection is
> /// guaranteed to refer to a valid element in that collection, as 
> long as the collection is not mutated.
> ///
> /// -Warning:   Operations which accept a Valid assume it is 
> in bounds and do not perform
> /// bounds checks. Using a Valid on a 
> collection other than the one which created
> /// it, or on a collection which has been mutated 
> since it was created, may be unsafe.
> struct Valid {
> init(unsafeIndex index: Index) { self.index = index }
> private(set) var index: Index
> }

Hi Brent,

Index invalidation rules are much more complex than what this model
can express.  For example, Array's indices can become invalid after
you remove elements from it.  Even if you have validated indices
around, that validation is now invalidated.  Not even to mention that
indices are valid only in context of a particular collection instance,
so in this model you could validate an index against one collection
and use it with another one.  Please read
https://github.com/apple/swift/blob/master/docs/IndexInvalidation.rst
for a more detailed description of the rules.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Proposal]Make .map return the calling collection type

2016-04-12 Thread Dmitri Gribenko via swift-evolution
On Tue, Apr 12, 2016 at 1:55 AM, Yogev Sitton via swift-evolution
 wrote:
> Map is great for transforming an array of objects - it is very useful and I 
> use it a lot.
> I would love to use Map with Dictionaries and other collections as well.
>
> As an example - let’s say I have a dictionary [String : Person] - that maps a 
> person to an ID.
> I want to use the map function a get a [String : String] - a dictionary that 
> maps a person’s name to an ID.
> Currently - the map method is defined to always return an array so that is 
> not possible to do.

Hi,

We can discuss adding special-case functions to individual collections
where it makes sense, but it does not make sense to do it for
collections in general, please see
https://github.com/apple/swift/blob/master/docs/StdlibRationales.rst#high-order-functions-on-collections-return-arrays
for the rationale.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Review] SE-0065 A New Model for Collections and Indices

2016-04-11 Thread Dmitri Gribenko via swift-evolution
On Mon, Apr 11, 2016 at 9:20 AM, Dmitri Gribenko  wrote:
> Hi,
>
> On Mon, Apr 11, 2016 at 9:16 AM, Gwendal Roué  
> wrote:
>> Will it still be possible with the new protocol and types? Especially, how 
>> to I generate "BETWEEN 0 AND 17" from 0..<18 without a supporting collection 
>> that gives me the predecessor of 18?
>
> You would either design your API to accept a CountableRange, or a
> Range where Bound conforms to Strideable.

You could also make your API generic over RangeProtocol where Bound
conforms to Strideable, check if the end point is contained in the
range (detecting closed ranges), and if it is not, perform the
adjustment.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [Review] SE-0065 A New Model for Collections and Indices

2016-04-11 Thread Dmitri Gribenko via swift-evolution
Hi,

On Mon, Apr 11, 2016 at 9:16 AM, Gwendal Roué  wrote:
> Will it still be possible with the new protocol and types? Especially, how to 
> I generate "BETWEEN 0 AND 17" from 0..<18 without a supporting collection 
> that gives me the predecessor of 18?

You would either design your API to accept a CountableRange, or a
Range where Bound conforms to Strideable.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Improvement proposal: change overflow behavior in successor()/predecessor() methods for Int types

2016-04-08 Thread Dmitri Gribenko via swift-evolution
On Fri, Apr 8, 2016 at 3:49 AM, Vladimir.S  wrote:
>
>
> On 07.04.2016 21:43, Dmitri Gribenko wrote:
>>
>> There would be no need to.  Collection will have a .successor(of:)
>> method that returns the next index after the given one.
>>
>
> I see. Thank you for letting know about this.
>
>> I can see that, but when you know that you are dealing with an
>> integer, isn't "+ 1" a more common and readable notation?
>
>
> Hmm.. I believe that i++ is muuuch common used than i += 1 ;-)

The reason why I said "+ 1" is because this discussion is about
Int.successor(), which returns a new Int rather than mutating it in
place.  So i++ and i += 1 are not direct replacements for
Int.successor().

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Improvement proposal: change overflow behavior in successor()/predecessor() methods for Int types

2016-04-07 Thread Dmitri Gribenko via swift-evolution
On Thu, Apr 7, 2016 at 11:27 AM, Vladimir.S  wrote:
> OK, thank you for the clarification Dmitri.
> If these methods are going away - no possible problems :-)
> Will we have some kind of .next() method for integers in new indexing model
> and in Swift 3.0 in general?

There would be no need to.  Collection will have a .successor(of:)
method that returns the next index after the given one.

> (But actually I don't agree that there is all OK with these functions in
> current version of Swift. "Not designed" - understand, but they can be
> used(so they will! be used) "out of the box", even Int8 has these methods,
> Int32.max is just 2GB for [Int8] etc..
> Yes, in case of using successor() only with Int64 only for indices of Array
> - all looks like OK.)

I can see that, but when you know that you are dealing with an
integer, isn't "+ 1" a more common and readable notation?

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Improvement proposal: change overflow behavior in successor()/predecessor() methods for Int types

2016-04-07 Thread Dmitri Gribenko via swift-evolution
On Thu, Apr 7, 2016 at 12:20 AM, Vladimir.S via swift-evolution
 wrote:
> But. .successor() .predecessor() methods for Int values do not follow these
> rules for overflow situations. I.e. :
> let i : Int8 = Int8.max
> let k : Int8 = i.successor()
> - is OK for current Swift compiler. We have i==127 and k==-128, no run-time
> error.

This was done for performance reasons.  Array's indices are Ints, and
adding an overflow check here was causing significant performance
issues when iterating over arrays.  These methods were not designed to
be used in contexts other than indices.  When ints are used as
indices, doing an overflow check in successor() does not prevent any
mistakes, since Array's bounds are always tighter than
Int.min...Int.max.

These methods are going away in the new indexing model.
https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160229/011552.html

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Making pointer nullability explicit (using Optional)

2016-03-22 Thread Dmitri Gribenko via swift-evolution
On Mon, Mar 21, 2016 at 4:14 PM, Jordan Rose via swift-evolution
 wrote:
> I've recorded everyone's feedback so far (mostly on the UnsafeBufferPointer
> issue) and opened a pull request:
> https://github.com/apple/swift-evolution/pull/219.

Thanks, Jordan!  I have a concern about the following point:

+- `Process.unsafeArgv` is a pointer to a null-terminated C array of C strings,
+ so its type changes from `UnsafeMutablePointer` to
+ `UnsafeMutablePointer`, i.e. the inner pointer
+ type becomes optional. It is then an error to access `Process.unsafeArgv`
+ before entering `main`. (Previously you would get a null pointer value.)

I don't think that this error is defensible -- if you are writing some
library code, you just can't know whether you are being executed
before `main` or not.  This is a precondition that reusable code just
can't guarantee.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Draft of proposal for autoreleasepool signature change

2016-03-22 Thread Dmitri Gribenko via swift-evolution
On Mon, Mar 21, 2016 at 10:34 PM, Timothy Wood via swift-evolution
 wrote:
>
> I think I’ve captured the feedback and conversation so far. Please let me
> know if I’ve missed anything or if there are further concerns or ideas for
> improvement.

Hi Timothy,

Your proposal looks great -- and thank you for capturing the whole
conversation.  Please submit a PR to swift-evolution!

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] [DRAFT] Introducing a Debug Build Configuration Test

2016-03-15 Thread Dmitri Gribenko via swift-evolution
On Tue, Mar 15, 2016 at 9:31 AM, Erica Sadun  wrote:
> I would like to update my draft proposal to introduce a test for debug 
> configurations using a public function
> rather than a build configuration test.
>
> * Would the stdlib team be open to that?

No objections from me.

> * What would be an appropriate name?  `debugConfiguration`? `debugBuild`? 
> `isDebugBuild`? `isDebugConfiguration`?

It seems like this API can be a property.  "isDebug..." is a good
start, but a debug what?  Build?  Build configuration?  I remember
Jordan was trying to rename the "build configuration" feature -- I
don't know where he arrived though.

OTOH, if you are willing to allow implementation complexity, you can
use '#if'-style conditional compilation, and allow arbitrary internal
and private APIs in the #if blocks.  Just as long as uses are guarded
with same, we should be fine.  I'm not sure if we want that user
model, though.

Dmitri

>
> -- E
>
>
>> On Mar 15, 2016, at 10:21 AM, Dmitri Gribenko  wrote:
>>
>> A function can absolutely can do that, if it is implemented using a
>> builtin known to the optimizer.
>>
>> Dmitri
>>
>> On Tue, Mar 15, 2016 at 9:20 AM, Shawn Erickson  wrote:
>>> You would likely want to ensure debug related code could be optimized away /
>>> or not be included in release builds. I am not sure how a function would
>>> achieve that.
>>> On Tue, Mar 15, 2016 at 9:15 AM Erica Sadun via swift-evolution
>>>  wrote:



 On Mar 14, 2016, at 2:04 PM, Dmitri Gribenko  wrote:
 Hi Erica,

 Based on Joe's rationale that you are quoting, I think the intent is
 that we want to restrict this directive to be statement-level only.
 The API vended by a module should not be affected by the build mode.

 Dmitri



 Could the debug build test take the form of a standard non-private
 function then
 instead of _isDebugAssertConfiguration()? If the test is limited to
 methods,
 introducing #if-style tests would be ugly.

 How likely or easy is it for me to reframe the request for testing for
 debug to be as
 simple as:

 `if debugBuild() {...}`

 with `debugBuild` vended by the standard library instead of as a build
 configuration test?

 -- E

 ___
 swift-evolution mailing list
 swift-evolution@swift.org
 https://lists.swift.org/mailman/listinfo/swift-evolution
>>
>>
>>
>> --
>> main(i,j){for(i=2;;i++){for(j=2;j> (j){printf("%d\n",i);}}} /*Dmitri Gribenko */
>



-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Add an ifPresent function to Optional

2016-03-14 Thread Dmitri Gribenko via swift-evolution
On Mon, Mar 14, 2016 at 5:51 PM,  <daveswee...@mac.com> wrote:
>
> On Mar 14, 2016, at 5:51 PM, Dmitri Gribenko via swift-evolution
> <swift-evolution@swift.org> wrote:
>
> Optional.map returns an Optional.
>
> Array.map returns an Array.
> Set.map returns an Array.
> .map returns an Array.
>
> I can't say that it is not valid to think about an Optional as a tiny
> collection, but as implemented in Swift, .map() does objectively
> behave differently...
>
> That behavior is, at least partially, because protocols don’t currently
> support this:
> protocol CollectionType {
> typealias T
> func map(transform: T->U) -> Self // error: Cannot specialize
> non-generic type 'Self'
> }

This feature is called higher-kinded types, and it is not planned for
design or implementation in the near future.

> I *think* I remember reading on here somewhere that the intent is to change
> map and flatMap to return “Self" pretty much as soon as the language
> supports it.

As a standard library engineer I can with certainty that this is not
the plan.  We like the current formulation of map() that returns an
Array.

https://github.com/apple/swift/blob/master/docs/StdlibRationales.rst#high-order-functions-on-collections-return-arrays

I don't think that having HKTs in the language would change the rationale.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j<i;j++){if(!(i%j)){j=0;break;}}if
(j){printf("%d\n",i);}}} /*Dmitri Gribenko <griboz...@gmail.com>*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Should all GeneratorTypes also be SequenceTypes?

2016-03-14 Thread Dmitri Gribenko via swift-evolution
On Mon, Mar 14, 2016 at 4:42 PM, Haravikk via swift-evolution
 wrote:
> There are quite a lot of generator implementations that also implement 
> SequenceType (since it’s as simple as returning self). Indeed, the 
> AnyGenerator type conforms to SequenceType, allowing any generator to be 
> wrapped as a sequence, though I imagine this comes with some overhead. So it 
> got me thinking, why doesn’t GeneratorType just require conformance to 
> SequenceType?

Because of compiler bugs.  We have the default implementation in the
library already, we just can't declare the conformance.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Add an ifPresent function to Optional

2016-03-14 Thread Dmitri Gribenko via swift-evolution
On Mon, Mar 14, 2016 at 3:44 PM, Erica Sadun  wrote:
>> No.  My argument is that map on collections and on optionals are two
>> completely different things.  They unify on a level that does not
>> exist in Swift (higher-kinded types).  We could name Optional.map()
>> differently, and that would be a separate decision from renaming
>> Collection.map(), but we used the name `map` primarily because of
>> precedent, not because there is a HKT notion of these two operations
>> being the same.
>
> Convergent evolution then, like tenrecs and hedgehogs?
>
> Because the way I've been thinking of it is like a teeny tiny collection that 
> either can fit one thing snugly into it or not.

Optional.map returns an Optional.

Array.map returns an Array.
Set.map returns an Array.
.map returns an Array.

I can't say that it is not valid to think about an Optional as a tiny
collection, but as implemented in Swift, .map() does objectively
behave differently...

> You're going to make me have completely different mental images when I use 
> Optional.map now, and I don't even
> have a mental metaphor to replace it with.

Don't know if it is helpful, but here's one: Optional is a result of a
computation that can fail.  .map() allows you to chain more things
onto a computation if it succeeded, and do nothing if it failed
already.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Add an ifPresent function to Optional

2016-03-14 Thread Dmitri Gribenko via swift-evolution
On Fri, Mar 11, 2016 at 7:17 PM, Howard Lovatt via swift-evolution
 wrote:
> @Dave, Yes, CollectionType would be better than SequenceType.

We already considered doing this a long time ago, and we decided against it.

1.  `for x in y {}` would start working everywhere because of T to T? promotion.

2.  Even if we forbid that specific promotion in that context, the following

for x in optionalThing {}

is also not good if the unwrapped value is a collection.  (The user
probably meant to iterate over the collection instead.)

3.  Why would one want all of the collection APIs on an optional?
index(of:)?  sorted()?  .first/.last?  Another overload of map that
returns an array?

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] Trial balloon: Ensure that String always contains valid Unicode

2016-01-04 Thread Dmitri Gribenko via swift-evolution
On Mon, Jan 4, 2016 at 9:37 PM, Kevin Ballard via swift-evolution <
swift-evolution@swift.org> wrote:

> I agree in principle that it would be great if String could enforce that
> it's always valid.
>
> But unfortunately, in practice, there's no way to do that without making
> it expensive to bridge from Obj-C. Because, as you've demonstrated, you can
> create NSStrings that contain things that aren't actually valid unicode
> sequences, every single bridge from an NSString to a String would have to
> be checked for validity. Not only that, but it's not clear what the
> behavior would be if an invalid string is found, since these bridges are
> unconditional - would Swift panic? Would it silently replace the invalid
> sequence with U+FFFD? Or something else entirely? But the question doesn't
> really matter, because turning these bridges from O(1) into O(N) would be
> an unacceptable performance penalty anyway.
>

Currently String replaces invalid sequences with U+FFFD lazily during
access, but there are corner cases related to Objective-C bridging that can
still leak invalid Unicode.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] About the PermutationGenerator

2015-12-31 Thread Dmitri Gribenko via swift-evolution
On Thu, Dec 31, 2015 at 2:01 PM, Susan Cheng via swift-evolution <
swift-evolution@swift.org> wrote:

> As I know SequenceType should have behaved as immutable structure and it
> provides method to get a mutable GeneratorType which generates value from
> start of sequence.


Sequences are not immutable.  A sequence is allowed to be consumed by
iterating over its generator.  If the type you have is a sequence, you can
only assume that you can access the elements only once.  For example, a
socket can be modeled as a sequence of bytes.  Once the bytes are consumed
from the corresponding generator, they are gone from the sequence.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] About the PermutationGenerator

2015-12-31 Thread Dmitri Gribenko via swift-evolution
On Thu, Dec 31, 2015 at 3:04 PM, Susan Cheng  wrote:
> yes for sequences are not immutable. I get confused.
>
> no for sequences should be definition of lists of values. Just like
> Fibonacci sequence, we can calculate the values form the start of the
> Fibonacci sequence one by one. But we are not accessing the values of
> Fibonacci sequence.

Those are collections.  Collections can be iterated over multiple times.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


Re: [swift-evolution] About the PermutationGenerator

2015-12-31 Thread Dmitri Gribenko via swift-evolution
On Thu, Dec 31, 2015 at 3:36 PM, Susan Cheng  wrote:
> I don't think so.
>
> As we don't say "Fibonacci collection", we know Fibonacci numbers are in
> order. But we can't tell the number immediately if I asked a specific index
> of Fibonacci sequence. The only way is calculate the sequence one by one
> from start.

That's OK, collections can have Forward indices which have exactly
these properties.

Dmitri

-- 
main(i,j){for(i=2;;i++){for(j=2;j*/
___
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution


  1   2   >