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.Set;
015import org.eclipse.golo.compiler.parser.GoloASTNode;
016
017import static org.eclipse.golo.compiler.ir.Builders.*;
018
019public final class Struct extends TypeWithMembers {
020
021  public static final String IMMUTABLE_FACTORY_METHOD = "$_immutable";
022
023  private PackageAndClass moduleName;
024
025  @Override
026  public Struct ofAST(GoloASTNode node) {
027    super.ofAST(node);
028    return this;
029  }
030
031  Struct(String name) {
032    super(name);
033  }
034
035  @Override
036  public PackageAndClass getPackageAndClass() {
037    return moduleName.createSubPackage("types").createSubPackage(getName());
038  }
039
040  // TODO: refactor to use the parent node
041  public void setModuleName(PackageAndClass module) {
042    this.moduleName = module;
043  }
044
045  private GoloFunction createDefaultConstructor() {
046    return functionDeclaration(getName()).synthetic().returns(call(getFactoryDelegateName()));
047  }
048
049  private String getImmutableName() {
050    return "Immutable" + getName();
051  }
052
053  private GoloFunction createFullArgsImmutableConstructor() {
054    return functionDeclaration(getImmutableName()).synthetic()
055      .withParameters(getMemberNames())
056      .returns(call(getFactoryDelegateName() + "." + IMMUTABLE_FACTORY_METHOD).withArgs(getFullArgs()));
057  }
058
059
060  public Set<GoloFunction> createFactories() {
061    Set<GoloFunction> factories = super.createFactories();
062    factories.add(createDefaultConstructor());
063    factories.add(createFullArgsImmutableConstructor());
064    return factories;
065  }
066
067  @Override
068  public void accept(GoloIrVisitor visitor) {
069    visitor.visitStruct(this);
070  }
071}