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.ir;
012
013import java.lang.reflect.Method;
014
015public final class MacroInvocation extends AbstractInvocation<MacroInvocation> implements ToplevelGoloElement {
016
017  private MacroInvocation(String name) {
018    super(name);
019  }
020
021  /**
022   * Calls a macro by name.
023   *
024   * <p>This is the same as a function call but tagged as being a macro.
025   *
026   * @param name the name of the macro to call
027   * @return the corresponding invocation
028   */
029  public static MacroInvocation call(Object name) {
030    if (name instanceof MacroInvocation) {
031      return (MacroInvocation) name;
032    }
033    if (name instanceof GoloFunction) {
034      return new MacroInvocation(((GoloFunction) name).getName());
035    }
036    if (name instanceof Method) {
037      Method m = (Method) name;
038      return new MacroInvocation(m.getDeclaringClass().getCanonicalName() + "." + m.getName());
039    }
040    if (name instanceof ReferenceLookup) {
041      return new MacroInvocation(((ReferenceLookup) name).getName());
042    }
043    return new MacroInvocation(name.toString());
044  }
045
046  /**
047   * Full macro invocation creation in one call.
048   *
049   * <p>Less readable than the fluent API, but useful when doing meta-generation.
050   *
051   * @param name the name of the macro to call
052   * @param arguments the call arguments
053   * @return the fully built corresponding invocation
054   */
055  public static MacroInvocation create(Object name, Object... arguments) {
056    return call(name).withArgs(arguments);
057  }
058
059  protected MacroInvocation self() { return this; }
060
061  /**
062   * {@inheritDoc}
063   */
064  @Override
065  public String toString() {
066    return String.format("MacroInvocation{name=%s}", getName());
067  }
068
069  /**
070   * {@inheritDoc}
071   */
072  @Override
073  public void accept(GoloIrVisitor visitor) {
074    visitor.visitMacroInvocation(this);
075  }
076}