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.Optional;
  33 import java.util.stream.Collectors;
  34 import com.sun.tools.jextract.parser.Parser;
  35 import com.sun.tools.jextract.tree.EnumTree;
  36 import com.sun.tools.jextract.tree.HeaderTree;
  37 import com.sun.tools.jextract.tree.SimpleTreeVisitor;
  38 import com.sun.tools.jextract.tree.StructTree;
  39 import com.sun.tools.jextract.tree.Tree;
  40 import com.sun.tools.jextract.tree.TreeMaker;
  41 import com.sun.tools.jextract.tree.TreePhase;
  42 import com.sun.tools.jextract.tree.TreePrinter;
  43 import com.sun.tools.jextract.tree.TypedefTree;
  44 import jdk.internal.clang.Cursor;
  45 
  46 /**
  47  * This visitor handles certain typedef declarations.
  48  *
  49  * 1. Remove redundant typedefs.
  50  * 2. Rename typedef'ed anonymous type definitions like
  51  *        typedef struct { int x; int y; } Point;
  52  * 3. Remove redundant struct/union/enum forward/backward declarations
  53  */
  54 final class TypedefHandler extends SimpleTreeVisitor<Void, Void>
  55         implements TreePhase {
  56     private final TreeMaker treeMaker = new TreeMaker();
  57 
  58     // Potential Tree instances that will go into transformed HeaderTree
  59     // are collected in this list.
  60     private final List<Tree> decls = new ArrayList<>();
  61 
  62     // Tree instances that are to be replaced from "decls" list are
  63     // saved in the following Map.
  64     private final Map<Cursor, Tree> replacements = new HashMap<>();
  65 
  66     @Override
  67     public HeaderTree transform(HeaderTree ht) {
  68         // Process all header declarations are collect potential
  69         // declarations that will go into transformed HeaderTree
  70         // into the this.decls field.
  71         ht.accept(this, null);
  72 
  73         // Replace trees from this.decls with Trees found in this.replacements.
  74         // We need this two step process so that named StructTree instances
  75         // will replace with original unnamed StructTree instances.
  76         List<Tree> newDecls = decls.stream().map(tx -> {
  77             if (replacements.containsKey(tx.cursor())) {
  78                 return replacements.get(tx.cursor());
  79             } else {
  80                 return tx;
  81             }
  82         }).collect(Collectors.toList());
  83 
  84         return treeMaker.createHeader(ht.cursor(), ht.path(), newDecls);
  85     }
  86 
  87     @Override
  88     public Void defaultAction(Tree tree, Void v) {
  89         decls.add(tree);
  90         return null;
  91     }
  92 
  93     @Override
  94     public Void visitEnum(EnumTree e, Void v) {
  95         /*
  96          * If we're seeing a forward/backward declaration of an
  97          * enum which is definied elsewhere in this compilation
  98          * unit, ignore it. If no definition is found, we want to
  99          * leave the declaration so that dummy definition will be
 100          * generated.
 101          *
 102          * Example:
 103          *
 104          *  enum Color ; // <-- forward declaration
 105          *  struct Point { int i; int j; };
 106          *  struct Point3D { int i; int j; int k; };
 107          *  struct Point3D; // <-- backward declaration
 108          */
 109 
 110         // include this only if this is a definition or a declaration
 111         // for which no definition is found elsewhere.
 112         if (e.isDefinition() || !e.definition().isPresent()) {
 113             decls.add(e);
 114         }
 115         return null;
 116     }
 117 
 118     @Override
 119     public Void visitHeader(HeaderTree ht, Void v) {
 120         ht.declarations().forEach(decl -> decl.accept(this, null));
 121         return null;
 122     }
 123 
 124     @Override
 125     public Void visitStruct(StructTree s, Void v) {
 126         /*
 127          * If we're seeing a forward/backward declaration of
 128          * a struct which is definied elsewhere in this compilation
 129          * unit, ignore it. If no definition is found, we want to
 130          * leave the declaration so that dummy definition will be
 131          * generated.
 132          *
 133          * Example:
 134          *
 135          *  struct Point; // <-- forward declaration
 136          *  struct Point { int i; int j; };
 137          *  struct Point3D { int i; int j; int k; };
 138          *  struct Point3D; // <-- backward declaration
 139          */
 140 
 141         // include this only if this is a definition or a declaration
 142         // for which no definition is found elsewhere.
 143         if (s.isDefinition() || !s.definition().isPresent()) {
 144             decls.add(s);
 145         }
 146         return null;
 147     }
 148 
 149     @Override
 150     public Void visitTypedef(TypedefTree tt, Void v) {
 151         Optional<Tree> def = tt.typeDefinition();
 152         if (def.isPresent()) {
 153             Tree defTree = def.get();
 154             if (defTree instanceof StructTree) {
 155                 if (defTree.name().isEmpty()) {
 156                     /**
 157                      * typedef struct { int x; int y; } Point
 158                      *
 159                      * is mapped to two Cursors by clang. First one for anonymous struct decl.
 160                      * and second one for typedef decl. We map it as a single named struct
 161                      * declaration.
 162                      */
 163                     replacements.put(defTree.cursor(), ((StructTree)defTree).withName(tt.name()));
 164                     return null;
 165                 } else if (defTree.name().equals(tt.name())) {
 166                     /*
 167                      * Remove redundant typedef like:
 168                      *
 169                      * typedef struct Point { int x; int y; } Point
 170                      */
 171                     return null;
 172                 }
 173             } else if (defTree instanceof EnumTree && defTree.name().equals(tt.name())) {
 174                 /*
 175                  * Remove redundant typedef like:
 176                  *
 177                  * typedef enum Color { R, G, B} Color
 178                  */
 179                 return null;
 180             }
 181         }
 182 
 183         decls.add(tt);
 184         return null;
 185     }
 186 
 187     // test main to manually check this visitor
 188     public static void main(String[] args) {
 189         if (args.length == 0) {
 190             System.err.println("Expected a header file");
 191             return;
 192         }
 193 
 194         Parser p = new Parser(true);
 195         List<Path> paths = Arrays.stream(args).map(Paths::get).collect(Collectors.toList());
 196         Path builtinInc = Paths.get(System.getProperty("java.home"), "conf", "jextract");
 197         List<String> clangArgs = List.of("-I" + builtinInc);
 198         List<HeaderTree> headers = p.parse(paths, clangArgs);
 199         TreePrinter printer = new TreePrinter();
 200         TypedefHandler handler = new TypedefHandler();
 201         for (HeaderTree ht : headers) {
 202             handler.transform(ht).accept(printer, null);
 203         }
 204     }
 205 }