createFlatArrayForProjectNodes function

Expression createFlatArrayForProjectNodes(
  1. List<Expression> expressions, {
  2. bool constForEmpty = true,
})

Do not use this function outside of projectedNodes.

Implementation

o.Expression createFlatArrayForProjectNodes(
  List<o.Expression> expressions, {
  bool constForEmpty = true,
}) {
  // Simplify: No items.
  if (expressions.isEmpty) {
    return o.literalArr(
      const [],
      o.ArrayType(
        o.OBJECT_TYPE,
        constForEmpty ? const [o.TypeModifier.Const] : const [],
      ),
    );
  }
  // Check for [].addAll([x,y,z]) case and optimize.
  if (expressions.length == 1) {
    final expression = expressions.first;
    if (expression.type is o.ArrayType) {
      return expression;
    } else {
      return o.literalArr([expression], o.OBJECT_TYPE);
    }
  }
  var lastNonArrayExpressions = <o.Expression>[];
  o.Expression result = o.literalArr([], o.OBJECT_TYPE);
  var initialEmptyArray = true;
  for (final expr in expressions) {
    if (expr.type is o.ArrayType) {
      if (lastNonArrayExpressions.isNotEmpty) {
        if (initialEmptyArray) {
          result = o.literalArr(lastNonArrayExpressions, o.OBJECT_TYPE);
          initialEmptyArray = false;
        } else {
          result = result.callMethod(o.BuiltinMethod.ConcatArray,
              [o.literalArr(lastNonArrayExpressions, o.OBJECT_TYPE)]);
        }
        lastNonArrayExpressions = [];
      }
      result = initialEmptyArray
          ? o.literalArr([expr], o.OBJECT_TYPE)
          : result.callMethod(o.BuiltinMethod.ConcatArray, [unsafeCast(expr)]);
      initialEmptyArray = false;
    } else {
      lastNonArrayExpressions.add(expr);
    }
  }
  if (lastNonArrayExpressions.isNotEmpty) {
    if (initialEmptyArray) {
      result = o.literalArr(lastNonArrayExpressions, o.OBJECT_TYPE);
    } else {
      result = result.callMethod(o.BuiltinMethod.ConcatArray,
          [o.literalArr(lastNonArrayExpressions, o.OBJECT_TYPE)]);
    }
  }
  return result;
}