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 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 boolean isFromSameHeader(Tree def, Tree decl) {
  69         SourceLocation locDef = def.location();
  70         SourceLocation locDecl = decl.location();
  71         return locDef != null && locDecl != null &&
  72                 Objects.equals(locDecl.getFileLocation().path(), locDef.getFileLocation().path());




  73     }
  74 
  75     @Override
  76     public HeaderTree transform(HeaderTree ht) {

  77         // Process all header declarations are collect potential
  78         // declarations that will go into transformed HeaderTree
  79         // into the this.decls field.
  80         ht.accept(this, null);
  81 
  82         // Replace trees from this.decls with Trees found in this.replacements.
  83         // We need this two step process so that named StructTree instances
  84         // will replace with original unnamed StructTree instances.
  85         List<Tree> newDecls = decls.stream().map(tx -> {
  86             if (replacements.containsKey(tx.cursor())) {
  87                 return replacements.get(tx.cursor());
  88             } else {
  89                 return tx;
  90             }
  91         }).collect(Collectors.toList());
  92 
  93         return treeMaker.createHeader(ht.cursor(), ht.path(), newDecls);
  94     }
  95 
  96     @Override
  97     public Void defaultAction(Tree tree, Void v) {
  98         decls.add(tree);
  99         return null;
 100     }
 101 
 102     @Override
 103     public Void visitEnum(EnumTree e, Void v) {
 104         /*
 105          * If we're seeing a forward/backward declaration of an
 106          * enum which is definied elsewhere in this compilation
 107          * unit, ignore it. If no definition is found, we want to
 108          * leave the declaration so that dummy definition will be
 109          * generated.
 110          *
 111          * Example:
 112          *
 113          *  enum Color ; // <-- forward declaration
 114          *  struct Point { int i; int j; };
 115          *  struct Point3D { int i; int j; int k; };
 116          *  struct Point3D; // <-- backward declaration
 117          */
 118 
 119         // include this only if this is a definition or a declaration
 120         // for which no definition is found elsewhere in this header.
 121         if (e.isDefinition()) {
 122             decls.add(e);
 123         } else {
 124             Optional<Tree> def = e.definition();
 125             if (!def.isPresent() || !isFromSameHeader(def.get(), e)) {
 126                 decls.add(e);
 127             }
 128         }
 129         return null;
 130     }
 131 
 132     @Override
 133     public Void visitHeader(HeaderTree ht, Void v) {
 134         ht.declarations().forEach(decl -> decl.accept(this, null));
 135         return null;
 136     }
 137 
 138     @Override
 139     public Void visitStruct(StructTree s, Void v) {
 140         List<Tree> oldDecls = decls;
 141         List<Tree> structDecls = new ArrayList<>();
 142         try {
 143             decls = structDecls;
 144             s.declarations().forEach(t -> t.accept(this, null));
 145         } finally {
 146             decls = oldDecls;
 147         }
 148 
 149         /*
 150          * If we're seeing a forward/backward declaration of
 151          * a struct which is definied elsewhere in this compilation
 152          * unit, ignore it. If no definition is found, we want to
 153          * leave the declaration so that dummy definition will be
 154          * generated.
 155          *
 156          * Example:
 157          *
 158          *  struct Point; // <-- forward declaration
 159          *  struct Point { int i; int j; };
 160          *  struct Point3D { int i; int j; int k; };
 161          *  struct Point3D; // <-- backward declaration
 162          */
 163 
 164         // include this only if this is a definition or a declaration
 165         // for which no definition is found elsewhere in this header.
 166         if (s.isDefinition()) {
 167             decls.add(s.withNameAndDecls(s.name(), structDecls));
 168         } else {
 169             Optional<Tree> def = s.definition();
 170             if (!def.isPresent() || !isFromSameHeader(def.get(), s)) {
 171                 decls.add(s.withNameAndDecls(s.name(), structDecls));
 172             }
 173         }
 174         return null;
 175     }
 176 
 177     @Override
 178     public Void visitTypedef(TypedefTree tt, Void v) {
 179         Optional<Tree> def = tt.typeDefinition();
 180         if (def.isPresent()) {
 181             Tree defTree = def.get();
 182             if (defTree instanceof StructTree && defTree.name().isEmpty()) {
 183                 /*
 184                  * typedef struct { int x; int y; } Point
 185                  *
 186                  * is mapped to two Cursors by clang. First one for anonymous struct decl.
 187                  * and second one for typedef decl. We map it as a single named struct
 188                  * declaration.
 189                  */
 190                 replacements.put(defTree.cursor(), ((StructTree)defTree).withName(tt.name()));
 191                 return null;
 192             } else if (defTree.name().equals(tt.name())) {
 193                 /*
 194                  * Remove redundant typedef like:
 195                  *
 196                  * typedef struct Point { int x; int y; } Point
 197                  * typedef enum Color { R, G, B} Color
 198                  * typedef struct Undef Undef
 199                  */
 200                 return null;
 201             }
 202         }
 203 
 204         decls.add(tt);
 205         return null;
 206     }
 207 
 208     // test main to manually check this visitor
 209     public static void main(String[] args) {
 210         if (args.length == 0) {
 211             System.err.println("Expected a header file");
 212             return;
 213         }
 214 
 215         Context context = new Context();
 216         Parser p = new Parser(context, true);
 217         List<Path> paths = Arrays.stream(args).map(Paths::get).collect(Collectors.toList());
 218         Path builtinInc = Paths.get(System.getProperty("java.home"), "conf", "jextract");
 219         List<String> clangArgs = List.of("-I" + builtinInc);
 220         List<HeaderTree> headers = p.parse(paths, clangArgs);
 221         TreePrinter printer = new TreePrinter();
 222         TypedefHandler handler = new TypedefHandler();
 223         for (HeaderTree ht : headers) {
 224             handler.transform(ht).accept(printer, null);
 225         }
 226     }
 227 }
--- EOF ---