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 
  24 package com.sun.tools.jextract;
  25 
  26 import java.foreign.memory.DoubleComplex;
  27 import java.foreign.memory.FloatComplex;
  28 import java.foreign.memory.LongDoubleComplex;
  29 import java.math.BigInteger;
  30 import java.nio.file.Path;
  31 import java.util.HashSet;
  32 import java.util.Optional;
  33 import java.util.Set;
  34 import java.util.function.Function;
  35 import java.util.HashMap;
  36 import java.util.Map;
  37 import java.util.logging.Logger;
  38 import java.util.stream.Stream;
  39 
  40 import jdk.internal.clang.Type;
  41 import jdk.internal.clang.TypeKind;
  42 
  43 /**
  44  * A dictionary that find Java type for a given native type.
  45  * Each instance of TypeDictionary presents types for a given java package.
  46  */
  47 public final class TypeDictionary {
  48     private HeaderResolver resolver;
  49     private final HeaderFile headerFile;
  50     private final Map<String, JType> functionalTypes;
  51     private final Set<String> resolutionRoots;
  52     private int serialNo;
  53 
  54     public TypeDictionary(HeaderResolver resolver, HeaderFile headerFile) {
  55         this.resolver = resolver;
  56         this.headerFile = headerFile;
  57         functionalTypes = new HashMap<>();
  58         resolutionRoots = new HashSet<>();
  59     }
  60 
  61     private int serialNo() {
  62         return ++serialNo;
  63     }
  64 
  65     private String recordOwnerClass(Type t) {
  66         try {
  67             //try resolve globally
  68             Path p = t.getDeclarationCursor().getSourceLocation().getFileLocation().path();
  69             if (p == null) {
  70                 p = Context.getBuiltinHeaderFile();
  71             }
  72             HeaderFile hf = resolver.headerFor(p);
  73             return Utils.toInternalName(hf.pkgName, hf.headerClsName);
  74         } catch (Throwable ex) {
  75             //fallback: resolve locally. This can happen for two reasons: (i) the symbol to be resolved is a builtin
  76             //symbol (e.g. no header file has its definition), or (ii) when the declaration cursor points to an header file
  77             //not previously seen by Context.
  78                 return headerClass();
  79         }
  80     }
  81 
  82     private String headerClass() {
  83         return Utils.toInternalName(headerFile.pkgName, headerFile.headerClsName);
  84     }
  85 
  86     public Stream<JType> functionalInterfaces() {
  87         return functionalTypes.entrySet().stream()
  88                 .map(Map.Entry::getValue);
  89     }
  90 
  91     public Stream<JType.ClassType> resolutionRoots() {
  92         return resolutionRoots.stream()
  93                 .filter(root -> !root.equals(headerClass()))
  94                 .map(JType.ClassType::new);
  95     }
  96 
  97     /**
  98      * @param t
  99      * @return
 100      */
 101     private JType getInternal(Type t, Function<JType.Function, JType> funcResolver) {
 102         switch(t.kind()) {
 103             case Void:
 104                 return JType.Void;
 105             // signed integer
 106             case Char_S:
 107             case SChar:
 108             case Short:
 109             case Int:
 110             case Long:
 111             case LongLong:
 112             case Int128:
 113             // unsigned integer, size-compatible at groveller level
 114             // accomodate value-range needed at civilizer level
 115             case UShort:
 116             case UInt:
 117             case UInt128:
 118             case ULong:
 119             case ULongLong:
 120             case Char_U:
 121             case UChar:
 122                 long size = t.size();
 123                 if (size <= 1) {
 124                     return JType.Byte;
 125                 } else if (size <= 2) {
 126                     return JType.Short;
 127                 } else if (size <= 4) {
 128                     return JType.Int;
 129                 } else if (size <= 8) {
 130                     return JType.Long;
 131                 } else {
 132                     return JType.of(BigInteger.class);
 133                 }
 134             case WChar:
 135             case Char16:
 136                 return JType.Char;
 137             case Bool:
 138                 return JType.Bool;
 139             case Double:
 140             case LongDouble:
 141                 return JType.Double;
 142             case Float:
 143                 return JType.Float;
 144             case Unexposed:
 145             case Elaborated:
 146                 return getInternal(t.canonicalType(), funcResolver);
 147             case ConstantArray:
 148             case IncompleteArray:
 149                 return new JType.ArrayType(getInternal(t.getElementType(), funcResolver));
 150             case FunctionProto:
 151             case FunctionNoProto:
 152                 JType[] args = new JType[t.numberOfArgs()];
 153                 for (int i = 0; i < args.length; i++) {
 154                     // argument could be function pointer declared locally
 155                     JType arg = getInternal(t.argType(i), funcResolver);
 156                     if(arg instanceof JType.Function) {
 157                         // interpret function types in parameters as function pointers
 158                         arg = JType.GenericType.ofCallback(funcResolver.apply((JType.Function) arg));
 159                     }
 160                     args[i] = arg;
 161                 }
 162                 return new JType.Function(Utils.getFunction(t), t.isVariadic(), getInternal(t.resultType(), funcResolver), args);
 163             case Enum: {
 164                 return JType.Int;
 165             }
 166             case Invalid:
 167                 throw new IllegalArgumentException("Invalid type");
 168             case Record: {
 169                 String name = Utils.toClassName(Utils.getName(t));
 170                 String owner = recordOwnerClass(t);
 171                 resolutionRoots.add(owner);
 172                 return new JType.ClassType(owner, name);
 173             }
 174             case Pointer: {
 175                 JType jt = getInternal(t.getPointeeType().canonicalType(), funcResolver);
 176                 if (jt instanceof JType.Function) {
 177                     jt = funcResolver.apply((JType.Function) jt);
 178                     return JType.GenericType.ofCallback(jt);
 179                 } else {
 180                     return JType.GenericType.ofPointer(jt);
 181                 }
 182             }
 183             case Typedef: {
 184                 Type truetype = t.canonicalType();
 185                 return getInternal(truetype, funcResolver);
 186             }
 187             case BlockPointer:
 188                 // FIXME: what is BlockPointer? A FunctionalPointer as this is closure
 189                 JType jt = getInternal(t.getPointeeType(), funcResolver);
 190                 jt = funcResolver.apply((JType.Function)jt);
 191                 return JType.GenericType.ofCallback(jt);
 192             case Complex:
 193                 TypeKind ek = t.getElementType().kind();
 194                 if (ek == TypeKind.Float) {
 195                     return JType.of(FloatComplex.class);
 196                 } else if (ek == TypeKind.Double) {
 197                     return JType.of(DoubleComplex.class);
 198                 } else if (ek == TypeKind.LongDouble) {
 199                     return JType.of(LongDoubleComplex.class);
 200                 } else {
 201                     throw new UnsupportedOperationException("_Complex kind " + ek + " not supported");
 202                 }
 203             case Vector:
 204                 switch ((int) t.size()) {
 205                     case 8:
 206                         return JType.Long;
 207                     case 16:
 208                     case 32:
 209                     case 64:
 210                     default:
 211                         throw new UnsupportedOperationException("Support for vector size: " + t.size());
 212                 }
 213             default:
 214                 throw new IllegalStateException("Unexpected type:" + t.kind());
 215         }
 216     }
 217 
 218     public JType enterIfAbsent(Type t) {
 219         return getInternal(t, this::enterFunctionIfNeeded);
 220     }
 221 
 222     //where
 223     private JType enterFunctionIfNeeded(JType.Function f) {
 224         return functionalTypes.computeIfAbsent(f.getNativeDescriptor(), _unused ->
 225             new JType.FunctionalInterfaceType(headerClass(), "FI" + serialNo(), f));
 226     }
 227 
 228     public JType lookup(Type t) {
 229         return getInternal(t, this::lookupFunction);
 230     }
 231 
 232     //where
 233     private JType lookupFunction(JType.Function f) {
 234         return Optional.ofNullable(functionalTypes.get(f.getNativeDescriptor()))
 235                 .orElseThrow(IllegalStateException::new);
 236     }
 237 }