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.HashMap;
  29 import java.util.List;
  30 import java.util.Map;
  31 import java.util.Objects;
  32 import java.util.Optional;
  33 import java.util.logging.Level;
  34 import java.util.logging.Logger;
  35 import java.util.stream.Collectors;
  36 import com.sun.tools.jextract.parser.Parser;
  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 
  47 /**
  48  * This visitor handles certain typedef declarations.
  49  *
  50  * 1. Remove redundant typedefs.
  51  * 2. Rename typedef'ed anonymous type definitions like
  52  *        typedef struct { int x; int y; } Point;
  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 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     private final Log log;
  67 
  68     public TypedefHandler(Context ctx) {
  69         this.log = ctx.log;
  70     }
  71 
  72     @Override
  73     public HeaderTree transform(HeaderTree ht) {
  74         // Process all header declarations are collect potential
  75         // declarations that will go into transformed HeaderTree
  76         // into the this.decls field.
  77         ht.accept(this, null);
  78 
  79         // Replace trees from this.decls with Trees found in this.replacements.
  80         // We need this two step process so that named StructTree instances
  81         // will replace with original unnamed StructTree instances.
  82         List<Tree> newDecls = decls.stream().map(tx -> {
  83             if (replacements.containsKey(tx.cursor())) {
  84                 return replacements.get(tx.cursor());
  85             } else {
  86                 return tx;
  87             }
  88         }).collect(Collectors.toList());
  89 
  90         return treeMaker.createHeader(ht.cursor(), ht.path(), newDecls);
  91     }
  92 
  93     @Override
  94     public Void defaultAction(Tree tree, Void v) {
  95         decls.add(tree);
  96         return null;
  97     }
  98 
  99     @Override
 100     public Void visitHeader(HeaderTree ht, Void v) {
 101         ht.declarations().forEach(decl -> decl.accept(this, null));
 102         return null;
 103     }
 104 
 105     @Override
 106     public Void visitTypedef(TypedefTree tt, Void v) {
 107         Optional<Tree> def = tt.typeDefinition();
 108         if (def.isPresent()) {
 109             Tree defTree = def.get();
 110             if (defTree instanceof StructTree && defTree.name().isEmpty()) {
 111                 /*
 112                  * typedef struct { int x; int y; } Point
 113                  *
 114                  * is mapped to two Cursors by clang. First one for anonymous struct decl.
 115                  * and second one for typedef decl. We map it as a single named struct
 116                  * declaration.
 117                  */
 118                 replacements.put(defTree.cursor(), ((StructTree)defTree).withName(tt.name()));
 119                 log.print(Level.FINE, () -> "Typedef " + defTree.type().spelling() + " as " + tt.name());
 120                 return null;
 121             } else if (defTree.name().equals(tt.name())) {
 122                 /*
 123                  * Remove redundant typedef like:
 124                  *
 125                  * typedef struct Point { int x; int y; } Point
 126                  * typedef enum Color { R, G, B} Color
 127                  * typedef struct Undef Undef
 128                  */
 129                 return null;
 130             }
 131         }
 132 
 133         decls.add(tt);
 134         return null;
 135     }
 136 
 137     // test main to manually check this visitor
 138     public static void main(String[] args) {
 139         if (args.length == 0) {
 140             System.err.println("Expected a header file");
 141             return;
 142         }
 143 
 144         Context context = Context.createDefault();
 145         Parser p = new Parser(context, true);
 146         Path builtinInc = Paths.get(System.getProperty("java.home"), "conf", "jextract");
 147         List<String> clangArgs = List.of("-I" + builtinInc);
 148         HeaderTree header = p.parse(Paths.get(args[0]), clangArgs);
 149         TreePrinter printer = new TreePrinter();
 150         TypedefHandler handler = new TypedefHandler(context);
 151         handler.transform(header).accept(printer, null);
 152     }
 153 }