ethanblake4 / dart_eval

Extensible Dart interpreter for Dart with full interop
https://pub.dev/packages/dart_eval
BSD 3-Clause "New" or "Revised" License
334 stars 40 forks source link

dart_eval runtime exception: type '$int' is not a subtype of type 'int' in type cast #212

Closed imSanjaySoni closed 3 months ago

imSanjaySoni commented 4 months ago

Not able to perform simple addition if data types are different, throw an exception. 🙁

Dart code:

      String main(String input) {
        final int units = int.tryParse(input) ?? 0;
        return getTotalInvestmentAmount(units);
      }

      final double unitAmount = 8121.23;

      String getTotalInvestmentAmount(int totalUnit) {
        num amount = getTotalUnitAmount(totalUnit);
        num stampDuty = getStampDuty(totalUnit);
        return '${amount + stampDuty + 0.0}';
      }

      double getTotalUnitAmount(int totalUnit) {
        return totalUnit * unitAmount;
      }

      int getStampDuty(int totalUnit) {
        final round = getTotalUnitAmount(totalUnit) * 0.000001;
        return roundHalfUp(round);
      }

      int roundHalfUp(double value) {
        final List<String> valueSplits = value.toString().split('.');
        final integerPart = int.parse(valueSplits.first);
        final fractionalPart = int.parse(valueSplits.last[0]);
        return fractionalPart >= 5 ? integerPart + 1 : integerPart;
      }

Exception:

Exception has occurred.
RuntimeException (dart_eval runtime exception: type '$int' is not a subtype of type 'int' in type cast
#0      BoxInt.run (package:dart_eval/src/eval/runtime/ops/primitives.dart:179:50)
#1      Runtime.execute (package:dart_eval/src/eval/runtime/runtime.dart:867:12)
#2      Runtime.executeLib (package:dart_eval/src/eval/runtime/runtime.dart:854:12)
at getTotalInvestmentAmount()
at main()

RUNTIME STATE
=============
Program offset: 118
Stack sample: [L0: 1, L1: $Instance of '$double', L2: $0, *L3: null, L4: null, L5: null, L6: null, L7: null, L8: null, L9: null]
Args sample: []
Call stack: [0, -1, 107]
TRACE:
112: Call (@129)
113: PushReturnValue ()
114: BoxDouble (L1)
115: PushArg (L0)
116: Call (@140)
117: PushReturnValue ()
118: BoxInt (L2)  <<< EXCEPTION
119: Unbox (L1)
120: Unbox (L2)
121: NumAdd (L1 + L2)
)
imSanjaySoni commented 3 months ago

Fixed. The issue was with roundHalfUps line return fractionalPart >= 5 ? integerPart + 1 : integerPart; because of ternary operators not supported by the package so I replaced this line with,

if (fractionalPart >= 5 ) { 
   return  integerPart + 1;
 } 
else { 
   return integerPart; 
}

and this worked for me.