isImmutable function

bool isImmutable(
  1. AST expression,
  2. AnalyzedClass? analyzedClass
)

Returns true if expression is immutable.

Implementation

bool isImmutable(ast.AST expression, AnalyzedClass? analyzedClass) {
  if (expression is ast.LiteralPrimitive ||
      expression is ast.StaticRead ||
      expression is ast.EmptyExpr) {
    return true;
  }
  if (expression is ast.IfNull) {
    return isImmutable(expression.condition, analyzedClass) &&
        isImmutable(expression.nullExp, analyzedClass);
  }
  if (expression is ast.Binary) {
    return isImmutable(expression.left, analyzedClass) &&
        isImmutable(expression.right, analyzedClass);
  }
  if (expression is ast.Interpolation) {
    return expression.expressions.every((e) => isImmutable(e, analyzedClass));
  }
  if (expression is ast.PropertyRead) {
    if (analyzedClass == null) return false;
    var receiver = expression.receiver;
    if (receiver is ast.ImplicitReceiver ||
        (receiver is ast.StaticRead && receiver.id.analyzedClass != null)) {
      var clazz = receiver is ast.StaticRead
          ? receiver.id.analyzedClass!
          : analyzedClass;
      var field = _getField(clazz, expression.name);
      if (field != null) {
        return !field.isSynthetic && (field.isFinal || field.isConst);
      }
      if (_getMethod(clazz, expression.name) != null) {
        // methods are immutable
        return true;
      }
    }
    return false;
  }
  return false;
}