Skip to content

Conversions revamped #11284

Open
Open
@axic

Description

@axic

Currently we support (an ever shrinking number of) implicit type conversions and some explicit ones. The explicit conversions mostly truncate/extend, and only a single one (integer to enum) is performing a check and panic.

During #9170 we have endlessly debated whether converting from a larger bytes should truncate or throw a panic, and finally realised we may want to review how conversions work in general. It seems that we want to make in any way ambiguous conversions explicitly understandable.

In the past we discussed new casting/conversion syntax here and here:

  • We could consider C++ism cast<byte[]>(cast<byte[32]>(cast<uint256>(1234))) to make it worse (or use convert<>)
  • And add copyof on top of it: cast<byte[]>(copyof cast<byte[32]>(cast<uint256>(1234)))
  • uint256(1234).as<byte[32]>().as<byte[]>() may be a bit more readable :)
  • I thought we had an issue proposing a syntax something like cast<toType>(val) instead of explicit conversions. I guess it is just more verbose so people would dislike it?
  • But at least would probably be easier to read cast<address payable>(..) than address payable(..).
  • If we do have cast<> as an unchecked casting, then we could later consider adding convert<> which does checks.
  • I wonder if we could use the cast syntax for multiple-step casting, i.e. cast<uint128,int128,int16>(..uint256 input..) or cast<uint128 -> int128 -> int16>(..uin256 input..) (similar to the mapping syntax)
  • But the other option we briefly discussed is explicit casting works like static_cast/reinterpret_cast and we could introduce truncation/conversion helper on the types, i.e. bytes32.truncateFrom(<dynamic bytes>).
    -Instead of the multiple step casting I suppose there could be nicer helpers in the stdlib doing that?

To summarise, the following syntactical ideas were proposed:

  • cast<to>(from)
  • convert<to>(from)
  • from.as<to>()
  • cast<intermediate1,intermediate2,final>() (in case of a series of conversions)
  • bytes32.truncateFrom(<dynamic bytes>)
  • truncate<..>()
  • extend<..>()

On todays design call there seemed consensus to rather have explicitly understandable function names (such as truncate and extend), instead of a generic cast.

(Moved from #9170 (comment))

Metadata

Metadata

Assignees

No one assigned

    Labels

    high impactChanges are very prominent and affect users or the project in a major way.language design :rage4:Any changes to the language, e.g. new featuresmedium effortDefault level of effortmust haveSomething we consider an essential part of Solidity 1.0.needs designThe proposal is too vague to be implemented right away

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions