001/* 002 * Copyright (c) 2012-2021 Institut National des Sciences Appliquées de Lyon (INSA Lyon) and others 003 * 004 * This program and the accompanying materials are made available under the 005 * terms of the Eclipse Public License 2.0 which is available at 006 * http://www.eclipse.org/legal/epl-2.0. 007 * 008 * SPDX-License-Identifier: EPL-2.0 009 */ 010 011package gololang; 012 013import org.eclipse.golo.runtime.InvalidDestructuringException; 014 015/** 016 * Base class for Golo union objects. 017 * <p> 018 * This class defines common behavior. 019 */ 020public abstract class Union { 021 022 private static final Object[] EMPTY = new Object[0]; 023 /** 024 * Array conversion. 025 * 026 * @return an array containing the values (in member orders) 027 */ 028 public Object[] toArray() { 029 return EMPTY; 030 } 031 032 /** 033 * Destructuration helper. 034 * 035 * @return a tuple with the current values. 036 * @deprecated This method should not be called directly and is no more used by new style destructuring. 037 */ 038 @Deprecated 039 public Tuple destruct() { 040 return Tuple.fromArray(toArray()); 041 } 042 043 /** 044 * New style destructuring helper. 045 * 046 * The number of variables to be affected must be the number of members. 047 * No remainer syntax is allowed. 048 * 049 * @param number number of variable that will be affected. 050 * @param substruct whether the destructuring is complete or should contains a sub structure. 051 * @param toSkip a boolean array indicating the elements to skip. 052 * @return an array containing the values to assign. 053 */ 054 public Object[] __$$_destruct(int number, boolean substruct, Object[] toSkip) { 055 Object[] fields = toArray(); 056 if (fields.length == 0) { 057 throw new InvalidDestructuringException("This union has no field"); 058 } 059 if (number == fields.length && !substruct) { 060 return fields; 061 } 062 if (number <= fields.length) { 063 throw InvalidDestructuringException.notEnoughValues(number, fields.length, substruct); 064 } 065 throw InvalidDestructuringException.tooManyValues(number); 066 } 067}