1 /*
   2  * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 package com.sun.tools.jextract.tree;
  24 
  25 import java.foreign.layout.Function;
  26 import java.util.Collections;
  27 import java.util.List;
  28 import java.util.ArrayList;
  29 import jdk.internal.clang.Cursor;
  30 import jdk.internal.clang.Type;
  31 
  32 public class FunctionTree extends Tree {
  33     FunctionTree(Cursor c) {
  34         this(c, c.spelling());
  35     }
  36 
  37     private FunctionTree(Cursor c, String name) {
  38         super(c, name);
  39     }
  40 
  41     @Override
  42     public FunctionTree withName(String newName) {
  43         return name().equals(newName)? this : new FunctionTree(cursor(), newName);
  44     }
  45 
  46     @Override
  47     public <R,D> R accept(TreeVisitor<R,D> visitor, D data) {
  48         return visitor.visitFunction(this, data);
  49     }
  50 
  51     public boolean isVariadic() {
  52         return type().isVariadic();
  53     }
  54 
  55     public List<Type> paramTypes() {
  56         Type t = type();
  57         int numParams = t.numberOfArgs();
  58         List<Type> res = new ArrayList<>(numParams);
  59         for (int i = 0; i < numParams; i++) {
  60             res.add(t.argType(i));
  61         }
  62         return Collections.unmodifiableList(res);
  63     }
  64 
  65     public int numParams() {
  66         return type().numberOfArgs();
  67     }
  68 
  69     public Type paramType(int idx) {
  70         return type().argType(idx);
  71     }
  72 
  73     public String paramName(int idx) {
  74         return cursor().getArgument(idx).spelling();
  75     }
  76 
  77     public Type returnType() {
  78         return type().resultType();
  79     }
  80 
  81     public Function function() {
  82         return LayoutUtils.getFunction(type());
  83     }
  84 }