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.Set; 014 015/** 016 * Represents a {@code struct} element. 017 * 018 * <p>For instance: 019 * <pre class="listing"><code class="lang-golo" data-lang="golo"> 020 * struct Point = {x, y} 021 * </code></pre> 022 */ 023public final class Struct extends TypeWithMembers<Struct> implements ToplevelGoloElement { 024 025 public static final String IMMUTABLE_FACTORY_METHOD = "$_immutable"; 026 027 protected Struct self() { return this; } 028 029 private Struct(String name) { 030 super(name); 031 } 032 033 /** 034 * Creates a structure type. 035 * 036 * <p>Typical usage: 037 * <pre class="listing"><code class="lang-java" data-lang="java"> 038 * structure("Point").members("x", "y") 039 * </code></pre> 040 * creates 041 * <pre class="listing"><code class="lang-golo" data-lang="golo"> 042 * struct Point = {x, y} 043 * </code></pre> 044 * 045 * @param name the name of the struct. 046 */ 047 public static Struct struct(String name) { 048 return new Struct(name.toString()); 049 } 050 051 private GoloFunction createDefaultConstructor() { 052 return GoloFunction.function(getName()).synthetic().returns(FunctionInvocation.of(getFactoryDelegateName())); 053 } 054 055 public String getImmutableName() { 056 return "Immutable" + getName(); 057 } 058 059 private GoloFunction createFullArgsImmutableConstructor() { 060 return GoloFunction.function(getImmutableName()).synthetic() 061 .withParameters(getMemberNames()) 062 .returns(FunctionInvocation.of(getFactoryDelegateName() + "." + IMMUTABLE_FACTORY_METHOD).withArgs(getFullArgs())); 063 } 064 065 066 public Set<GoloFunction> createFactories() { 067 Set<GoloFunction> factories = super.createFactories(); 068 factories.add(createDefaultConstructor()); 069 factories.add(createFullArgsImmutableConstructor()); 070 return factories; 071 } 072 073 /** 074 * {@inheritDoc} 075 */ 076 @Override 077 public void accept(GoloIrVisitor visitor) { 078 visitor.visitStruct(this); 079 } 080}