1 /*
   2  * Copyright (c) 2015, 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.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package jdk.nashorn.tools.jjs;
  27 
  28 import java.util.List;
  29 import java.util.regex.Pattern;
  30 import jdk.internal.jline.console.completer.Completer;
  31 import jdk.nashorn.api.tree.AssignmentTree;
  32 import jdk.nashorn.api.tree.BinaryTree;
  33 import jdk.nashorn.api.tree.CompilationUnitTree;
  34 import jdk.nashorn.api.tree.CompoundAssignmentTree;
  35 import jdk.nashorn.api.tree.ConditionalExpressionTree;
  36 import jdk.nashorn.api.tree.ExpressionTree;
  37 import jdk.nashorn.api.tree.ExpressionStatementTree;
  38 import jdk.nashorn.api.tree.FunctionCallTree;
  39 import jdk.nashorn.api.tree.IdentifierTree;
  40 import jdk.nashorn.api.tree.InstanceOfTree;
  41 import jdk.nashorn.api.tree.MemberSelectTree;
  42 import jdk.nashorn.api.tree.NewTree;
  43 import jdk.nashorn.api.tree.SimpleTreeVisitorES5_1;
  44 import jdk.nashorn.api.tree.Tree;
  45 import jdk.nashorn.api.tree.UnaryTree;
  46 import jdk.nashorn.api.tree.Parser;
  47 import jdk.nashorn.api.scripting.NashornException;
  48 import jdk.nashorn.tools.PartialParser;
  49 import jdk.nashorn.internal.objects.Global;
  50 import jdk.nashorn.internal.runtime.Context;
  51 import jdk.nashorn.internal.runtime.ScriptRuntime;
  52 
  53 // A simple source completer for nashorn
  54 final class NashornCompleter implements Completer {
  55     private final Context context;
  56     private final Global global;
  57     private final PartialParser partialParser;
  58     private final Parser parser;
  59 
  60     NashornCompleter(final Context context, final Global global, final PartialParser partialParser) {
  61         this.context = context;
  62         this.global = global;
  63         this.partialParser = partialParser;
  64         this.parser = Parser.create();
  65     }
  66 
  67     // Pattern to match a unfinished member selection expression. object part and "."
  68     // but property name missing pattern.
  69     private static final Pattern SELECT_PROP_MISSING = Pattern.compile(".*\\.\\s*");
  70 
  71     @Override
  72     public int complete(final String test, final int cursor, final List<CharSequence> result) {
  73         // check that cursor is at the end of test string. Do not complete in the middle!
  74         if (cursor != test.length()) {
  75             return cursor;
  76         }
  77 
  78         // get the start of the last expression embedded in the given code
  79         // using the partial parsing support - so that we can complete expressions
  80         // inside statements, function call argument lists, array index etc.
  81         final int exprStart = partialParser.getLastExpressionStart(context, test);
  82         if (exprStart == -1) {
  83             return cursor;
  84         }
  85 
  86 
  87         // extract the last expression string
  88         final String exprStr = test.substring(exprStart);
  89 
  90         // do we have an incomplete member selection expression that misses property name?
  91         final boolean endsWithDot = SELECT_PROP_MISSING.matcher(exprStr).matches();
  92 
  93         // If this is an incomplete member selection, then it is not legal code.
  94         // Make it legal by adding a random property name "x" to it.
  95         final String completeExpr = endsWithDot? exprStr + "x" : exprStr;
  96 
  97         final ExpressionTree topExpr = getTopLevelExpression(parser, completeExpr);
  98         if (topExpr == null) {
  99             // did not parse to be a top level expression, no suggestions!
 100             return cursor;
 101         }
 102 
 103 
 104         // Find 'right most' expression of the top level expression
 105         final Tree rightMostExpr = getRightMostExpression(topExpr);
 106         if (rightMostExpr instanceof MemberSelectTree) {
 107             return completeMemberSelect(exprStr, cursor, result, (MemberSelectTree)rightMostExpr, endsWithDot);
 108         } else if (rightMostExpr instanceof IdentifierTree) {
 109             return completeIdentifier(exprStr, cursor, result, (IdentifierTree)rightMostExpr);
 110         } else {
 111             // expression that we cannot handle for completion
 112             return cursor;
 113         }
 114     }
 115 
 116     private int completeMemberSelect(final String exprStr, final int cursor, final List<CharSequence> result,
 117                 final MemberSelectTree select, final boolean endsWithDot) {
 118         final ExpressionTree objExpr = select.getExpression();
 119         final String objExprCode = exprStr.substring((int)objExpr.getStartPosition(), (int)objExpr.getEndPosition());
 120 
 121         // try to evaluate the object expression part as a script
 122         Object obj = null;
 123         try {
 124             obj = context.eval(global, objExprCode, global, "<suggestions>");
 125         } catch (Exception ignored) {
 126             // throw the exception - this is during tab-completion
 127         }
 128 
 129         if (obj != null && obj != ScriptRuntime.UNDEFINED) {
 130             if (endsWithDot) {
 131                 // no user specified "prefix". List all properties of the object
 132                 result.addAll(PropertiesHelper.getProperties(obj));
 133                 return cursor;
 134             } else {
 135                 // list of properties matching the user specified prefix
 136                 final String prefix = select.getIdentifier();
 137                 result.addAll(PropertiesHelper.getProperties(obj, prefix));
 138                 return cursor - prefix.length();
 139             }
 140         }
 141 
 142         return cursor;
 143     }
 144 
 145     private int completeIdentifier(final String test, final int cursor, final List<CharSequence> result,
 146                 final IdentifierTree ident) {
 147         final String name = ident.getName();
 148         result.addAll(PropertiesHelper.getProperties(global, name));
 149         return cursor - name.length();
 150     }
 151 
 152     // returns ExpressionTree if the given code parses to a top level expression.
 153     // Or else returns null.
 154     private ExpressionTree getTopLevelExpression(final Parser parser, final String code) {
 155         try {
 156             final CompilationUnitTree cut = parser.parse("<code>", code, null);
 157             final List<? extends Tree> stats = cut.getSourceElements();
 158             if (stats.size() == 1) {
 159                 final Tree stat = stats.get(0);
 160                 if (stat instanceof ExpressionStatementTree) {
 161                     return ((ExpressionStatementTree)stat).getExpression();
 162                 }
 163             }
 164         } catch (final NashornException ignored) {
 165             // ignore any parser error. This is for completion anyway!
 166             // And user will get that error later when the expression is evaluated.
 167         }
 168 
 169         return null;
 170     }
 171 
 172     private Tree getRightMostExpression(final ExpressionTree expr) {
 173         return expr.accept(new SimpleTreeVisitorES5_1<Tree, Void>() {
 174             @Override
 175             public Tree visitAssignment(final AssignmentTree at, final Void v) {
 176                 return getRightMostExpression(at.getExpression());
 177             }
 178 
 179             @Override
 180             public Tree visitCompoundAssignment(final CompoundAssignmentTree cat, final Void v) {
 181                 return getRightMostExpression(cat.getExpression());
 182             }
 183 
 184             @Override
 185             public Tree visitConditionalExpression(final ConditionalExpressionTree cet, final Void v) {
 186                 return getRightMostExpression(cet.getFalseExpression());
 187             }
 188 
 189             @Override
 190             public Tree visitBinary(final BinaryTree bt, final Void v) {
 191                 return getRightMostExpression(bt.getRightOperand());
 192             }
 193 
 194             @Override
 195             public Tree visitIdentifier(final IdentifierTree ident, final Void v) {
 196                 return ident;
 197             }
 198 
 199 
 200             @Override
 201             public Tree visitInstanceOf(final InstanceOfTree it, final Void v) {
 202                 return it.getType();
 203             }
 204 
 205 
 206             @Override
 207             public Tree visitMemberSelect(final MemberSelectTree select, final Void v) {
 208                 return select;
 209             }
 210 
 211             @Override
 212             public Tree visitNew(final NewTree nt, final Void v) {
 213                 final ExpressionTree call = nt.getConstructorExpression();
 214                 if (call instanceof FunctionCallTree) {
 215                     final ExpressionTree func = ((FunctionCallTree)call).getFunctionSelect();
 216                     // Is this "new Foo" or "new obj.Foo" with no user arguments?
 217                     // If so, we may be able to do completion of constructor name.
 218                     if (func.getEndPosition() == nt.getEndPosition()) {
 219                         return func;
 220                     }
 221                 }
 222                 return null;
 223             }
 224 
 225             @Override
 226             public Tree visitUnary(final UnaryTree ut, final Void v) {
 227                 return getRightMostExpression(ut.getExpression());
 228             }
 229         }, null);
 230     }
 231 }