001/*
002 * Copyright (c) 2012-2017 Institut National des Sciences Appliquées de Lyon (INSA-Lyon)
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 */
009
010package org.eclipse.golo.compiler.ir;
011
012import org.eclipse.golo.compiler.PackageAndClass;
013
014import java.util.Collection;
015import java.util.Set;
016import java.util.LinkedHashSet;
017import org.eclipse.golo.compiler.parser.GoloASTNode;
018
019import static java.util.Arrays.asList;
020import static java.util.Collections.unmodifiableSet;
021
022public final class Union extends GoloElement {
023
024  private PackageAndClass moduleName;
025  private final String name;
026  private final Set<UnionValue> values = new LinkedHashSet<>();
027
028  Union(String name) {
029    super();
030    this.name = name;
031  }
032
033  @Override
034  public Union ofAST(GoloASTNode node) {
035    super.ofAST(node);
036    return this;
037  }
038
039  public String getName() {
040    return name;
041  }
042
043  public PackageAndClass getPackageAndClass() {
044    return moduleName.createSubPackage("types").createSubPackage(name);
045  }
046
047  public void setModuleName(PackageAndClass module) {
048    this.moduleName = module;
049  }
050
051  public UnionValue createValue(String name) {
052    return new UnionValue(this, name);
053  }
054
055  public boolean addValue(UnionValue value) {
056    makeParentOf(value);
057    return values.add(value);
058  }
059
060  public Collection<UnionValue> getValues() {
061    return unmodifiableSet(values);
062  }
063
064  public Union value(String name, Member... members) {
065    UnionValue value = new UnionValue(this, name);
066    value.addMembers(asList(members));
067    values.add(value);
068    return this;
069  }
070
071  @Override
072  public void accept(GoloIrVisitor visitor) {
073    visitor.visitUnion(this);
074  }
075
076  @Override
077  public void walk(GoloIrVisitor visitor) {
078    for (UnionValue value : getValues()) {
079      value.accept(visitor);
080    }
081  }
082
083  @Override
084  protected void replaceElement(GoloElement original, GoloElement newElement) {
085    if (values.contains(original) && newElement instanceof UnionValue) {
086      values.remove(original);
087      addValue((UnionValue) newElement);
088    } else {
089      throw cantReplace(original, newElement);
090    }
091  }
092
093}