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;
  24 
  25 import java.nio.file.Path;
  26 import java.nio.file.Paths;
  27 import java.util.ArrayList;
  28 import java.util.Arrays;
  29 import java.util.HashMap;
  30 import java.util.List;
  31 import java.util.Map;
  32 import java.util.Objects;
  33 import java.util.Optional;
  34 import java.util.stream.Collectors;
  35 import com.sun.tools.jextract.parser.Parser;
  36 import com.sun.tools.jextract.tree.EnumTree;
  37 import com.sun.tools.jextract.tree.HeaderTree;
  38 import com.sun.tools.jextract.tree.SimpleTreeVisitor;
  39 import com.sun.tools.jextract.tree.StructTree;
  40 import com.sun.tools.jextract.tree.Tree;
  41 import com.sun.tools.jextract.tree.TreeMaker;
  42 import com.sun.tools.jextract.tree.TreePhase;
  43 import com.sun.tools.jextract.tree.TreePrinter;
  44 import com.sun.tools.jextract.tree.TypedefTree;
  45 import jdk.internal.clang.Cursor;
  46 import jdk.internal.clang.SourceLocation;
  47 
  48 /**
  49  * This visitor handles certain typedef declarations.
  50  *
  51  * 1. Remove redundant typedefs.
  52  * 2. Rename typedef'ed anonymous type definitions like
  53  *        typedef struct { int x; int y; } Point;
  54  * 3. Remove redundant struct/union/enum forward/backward declarations
  55  */
  56 final class TypedefHandler extends SimpleTreeVisitor<Void, Void>
  57         implements TreePhase {
  58     private final TreeMaker treeMaker = new TreeMaker();
  59 
  60     // Potential Tree instances that will go into transformed HeaderTree
  61     // are collected in this list.
  62     private final List<Tree> decls = new ArrayList<>();
  63 
  64     // Tree instances that are to be replaced from "decls" list are
  65     // saved in the following Map.
  66     private final Map<Cursor, Tree> replacements = new HashMap<>();
  67 
  68     private Path headerPath;
  69 
  70     private static boolean isFromPath(Tree tree, Path path) {
  71         SourceLocation loc = tree.location();
  72         return loc != null? Objects.equals(path, loc.getFileLocation().path()) : false;
  73     }
  74 
  75     private boolean isFromThisHeader(Tree tree) {
  76         return isFromPath(tree, headerPath);
  77     }
  78 
  79     @Override
  80     public HeaderTree transform(HeaderTree ht) {
  81         this.headerPath = ht.path();
  82         // Process all header declarations are collect potential
  83         // declarations that will go into transformed HeaderTree
  84         // into the this.decls field.
  85         ht.accept(this, null);
  86 
  87         // Replace trees from this.decls with Trees found in this.replacements.
  88         // We need this two step process so that named StructTree instances
  89         // will replace with original unnamed StructTree instances.
  90         List<Tree> newDecls = decls.stream().map(tx -> {
  91             if (replacements.containsKey(tx.cursor())) {
  92                 return replacements.get(tx.cursor());
  93             } else {
  94                 return tx;
  95             }
  96         }).collect(Collectors.toList());
  97 
  98         return treeMaker.createHeader(ht.cursor(), ht.path(), newDecls);
  99     }
 100 
 101     @Override
 102     public Void defaultAction(Tree tree, Void v) {
 103         decls.add(tree);
 104         return null;
 105     }
 106 
 107     @Override
 108     public Void visitEnum(EnumTree e, Void v) {
 109         /*
 110          * If we're seeing a forward/backward declaration of an
 111          * enum which is definied elsewhere in this compilation
 112          * unit, ignore it. If no definition is found, we want to
 113          * leave the declaration so that dummy definition will be
 114          * generated.
 115          *
 116          * Example:
 117          *
 118          *  enum Color ; // <-- forward declaration
 119          *  struct Point { int i; int j; };
 120          *  struct Point3D { int i; int j; int k; };
 121          *  struct Point3D; // <-- backward declaration
 122          */
 123 
 124         // include this only if this is a definition or a declaration
 125         // for which no definition is found elsewhere in this header.
 126         if (e.isDefinition()) {
 127             decls.add(e);
 128         } else {
 129             Optional<Tree> def = e.definition();
 130             if (!def.isPresent() || !isFromThisHeader(def.get())) {
 131                 decls.add(e);
 132             }
 133         }
 134         return null;
 135     }
 136 
 137     @Override
 138     public Void visitHeader(HeaderTree ht, Void v) {
 139         ht.declarations().forEach(decl -> decl.accept(this, null));
 140         return null;
 141     }
 142 
 143     @Override
 144     public Void visitStruct(StructTree s, Void v) {









 145         /*
 146          * If we're seeing a forward/backward declaration of
 147          * a struct which is definied elsewhere in this compilation
 148          * unit, ignore it. If no definition is found, we want to
 149          * leave the declaration so that dummy definition will be
 150          * generated.
 151          *
 152          * Example:
 153          *
 154          *  struct Point; // <-- forward declaration
 155          *  struct Point { int i; int j; };
 156          *  struct Point3D { int i; int j; int k; };
 157          *  struct Point3D; // <-- backward declaration
 158          */
 159 
 160         // include this only if this is a definition or a declaration
 161         // for which no definition is found elsewhere in this header.
 162         if (s.isDefinition()) {
 163             decls.add(s);
 164         } else {
 165             Optional<Tree> def = s.definition();
 166             if (!def.isPresent() || !isFromThisHeader(def.get())) {
 167                 decls.add(s);
 168             }
 169         }
 170         return null;
 171     }
 172 
 173     @Override
 174     public Void visitTypedef(TypedefTree tt, Void v) {
 175         Optional<Tree> def = tt.typeDefinition();
 176         if (def.isPresent()) {
 177             Tree defTree = def.get();
 178             if (defTree instanceof StructTree && defTree.name().isEmpty()) {
 179                 /*
 180                  * typedef struct { int x; int y; } Point
 181                  *
 182                  * is mapped to two Cursors by clang. First one for anonymous struct decl.
 183                  * and second one for typedef decl. We map it as a single named struct
 184                  * declaration.
 185                  */
 186                 replacements.put(defTree.cursor(), ((StructTree)defTree).withName(tt.name()));
 187                 return null;
 188             } else if (defTree.name().equals(tt.name())) {
 189                 /*
 190                  * Remove redundant typedef like:
 191                  *
 192                  * typedef struct Point { int x; int y; } Point
 193                  * typedef enum Color { R, G, B} Color
 194                  * typedef struct Undef Undef
 195                  */
 196                 return null;
 197             }
 198         }
 199 
 200         decls.add(tt);
 201         return null;
 202     }
 203 
 204     // test main to manually check this visitor
 205     public static void main(String[] args) {
 206         if (args.length == 0) {
 207             System.err.println("Expected a header file");
 208             return;
 209         }
 210 
 211         Parser p = new Parser(true);

 212         List<Path> paths = Arrays.stream(args).map(Paths::get).collect(Collectors.toList());
 213         Path builtinInc = Paths.get(System.getProperty("java.home"), "conf", "jextract");
 214         List<String> clangArgs = List.of("-I" + builtinInc);
 215         List<HeaderTree> headers = p.parse(paths, clangArgs);
 216         TreePrinter printer = new TreePrinter();
 217         TypedefHandler handler = new TypedefHandler();
 218         for (HeaderTree ht : headers) {
 219             handler.transform(ht).accept(printer, null);
 220         }
 221     }
 222 }
--- EOF ---