001/*
002 * Copyright (c) 2012-2018 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.ir;
012
013import java.util.Arrays;
014import java.util.List;
015import gololang.Tuple;
016
017public final class WhenClause<T extends GoloElement<?>> extends GoloElement<WhenClause<T>> {
018  private ExpressionStatement<?> condition;
019  private T action;
020
021  WhenClause(ExpressionStatement<?> condition, T action) {
022    this.condition = makeParentOf(condition);
023    setAction(action);
024  }
025
026  protected WhenClause<T> self() { return this; }
027
028  public ExpressionStatement<?> condition() { return this.condition; }
029
030  public T action() { return this.action; }
031
032  private void setAction(T a) {
033    this.action = makeParentOf(a);
034  }
035
036  public WhenClause<T> then(T action) {
037    setAction(action);
038    return this;
039  }
040
041  @Override
042  public String toString() {
043    return String.format("when %s then %s", condition, action);
044  }
045
046  /**
047   * {@inheritDoc}
048   */
049  @Override
050  protected void replaceElement(GoloElement<?> original, GoloElement<?> newElement) {
051    if (this.condition.equals(original)) {
052      if (!(newElement instanceof ExpressionStatement)) {
053        throw cantConvert("ExpressionStatement", newElement);
054      }
055      this.condition = makeParentOf(ExpressionStatement.of(newElement));
056    } else if (this.action.equals(original)) {
057      @SuppressWarnings("unchecked")
058      T element = (T) newElement;
059      setAction(element);
060    } else {
061      throw doesNotContain(original);
062    }
063  }
064
065  /**
066   * {@inheritDoc}
067   */
068  @Override
069  public void accept(GoloIrVisitor visitor) {
070    visitor.visitWhenClause(this);
071  }
072
073  /**
074   * {@inheritDoc}
075   */
076  @Override
077  public List<GoloElement<?>> children() {
078    return Arrays.asList(condition, action);
079  }
080
081  public Tuple destruct() {
082    return new Tuple(condition, action);
083  }
084}
085
086