User defined value type with operators and/or forward references or aliases for types in libraries
- Dominant language
- C++
- Stars
- 25.7k
- Forks
- 6.2k
- Avg merge
- 1d 11h
- Merged PRs (30d)
- 21
Description
## Abstract
For type safety reasons, such as when using uint256 et al as a slot, or as an index into a specific storage array (pseudo pointer), it is often desirable to declare a type such as:
type SpecificArrayIndex is uint64;
With additional work, this avoids errors where a variable storing the index of one array is accidentally used to index, or do arithmetic on the index of, a different array. The additional work is to either (a) declare internal function accessors to the arrays that take typed index parameters, or (b) use the [editorial: super cumbersom] wrap/unwrap calls in arithmetic.
I propose:
type SpecificArrayIndex is uint64 with_operators;
## Motivation
Enhance type safety. Readable code.
SpecificArrayIndex MAX = SpecificArrayIndex.wrap(type(uint64).max);
SpecificArrayIndex HIGH_BIT_FLAG = SpecificArrayIndex.wrap(SpecificArrayIndex.unwrap(MAX)&(SpecificArrayIndex.unwrap(MAX)>>1));
becomes (when combined with my other feature request to allow type() to accept simple value types, perhaps only those with_operators):
SpecificArrayIndex MAX = type(SpecificArrayIndex).max;
SpecificArrayIndex HIGH_BIT_FLAG = MAX & (MAX>>1);
or, if you also support type(SpecificArrayIndex).numBits:
SpecificArrayIndex HIGH_BIT_FLAG =SpecificArrayIndex.wrap(1<<(type(SpecificArrayIndex.numBits)-1));
## Specification
add with_operators to grammar. user defined value types that carry this flag get all of the standard arithmetic and comparison operators.
## Backwards Compatibility
New code won't compile under old compilers. Old compilers won't understand new code. All good.
Contributor guide
Research direction
Start by reviewing the proposed `with_operators` grammar addition and the specification for user-defined value types. Define the supported arithmetic and comparison operators and verify that the feature provides the stated type-safety and readability benefits without changing existing code behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- solidity
- Domain
- blockchain, compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100