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.internal.objects.Global;
  49 import jdk.nashorn.internal.runtime.Context;
  50 import jdk.nashorn.internal.runtime.ScriptRuntime;
  51 
  52 // A simple source completer for nashorn
  53 final class NashornCompleter implements Completer {
  54     private final Context context;
  55     private final Global global;
  56     private final Main main;
  57     private final Parser parser;
  58 
  59     NashornCompleter(final Context context, final Global global, final Main main) {
  60         this.context = context;
  61         this.global = global;
  62         this.main = main;
  63         this.parser = Parser.create();
  64     }
  65 
  66     // Pattern to match a unfinished member selection expression. object part and "."
  67     // but property name missing pattern.
  68     private static final Pattern SELECT_PROP_MISSING = Pattern.compile(".*\\.\\s*");
  69 
  70     @Override
  71     public int complete(final String test, final int cursor, final List<CharSequence> result) {
  72         // check that cursor is at the end of test string. Do not complete in the middle!
  73         if (cursor != test.length()) {
  74             return cursor;
  75         }
  76 
  77         // get the start of the last expression embedded in the given code
  78         // using the partial parsing support - so that we can complete expressions
  79         // inside statements, function call argument lists, array index etc.
  80         final int exprStart = main.getLastExpressionStart(context, test);
  81         if (exprStart == -1) {
  82             return cursor;
  83         }
  84 
  85 
  86         // extract the last expression string
  87         final String exprStr = test.substring(exprStart);
  88 
  89         // do we have an incomplete member selection expression that misses property name?
  90         final boolean endsWithDot = SELECT_PROP_MISSING.matcher(exprStr).matches();
  91 
  92         // If this is an incomplete member selection, then it is not legal code.
  93         // Make it legal by adding a random property name "x" to it.
  94         final String completeExpr = endsWithDot? exprStr + "x" : exprStr;
  95 
  96         final ExpressionTree topExpr = getTopLevelExpression(parser, completeExpr);
  97         if (topExpr == null) {
  98             // did not parse to be a top level expression, no suggestions!
  99             return cursor;
 100         }
 101 
 102 
 103         // Find 'right most' expression of the top level expression
 104         final Tree rightMostExpr = getRightMostExpression(topExpr);
 105         if (rightMostExpr instanceof MemberSelectTree) {
 106             return completeMemberSelect(exprStr, cursor, result, (MemberSelectTree)rightMostExpr, endsWithDot);
 107         } else if (rightMostExpr instanceof IdentifierTree) {
 108             return completeIdentifier(exprStr, cursor, result, (IdentifierTree)rightMostExpr);
 109         } else {
 110             // expression that we cannot handle for completion
 111             return cursor;
 112         }
 113     }
 114 
 115     private int completeMemberSelect(final String exprStr, final int cursor, final List<CharSequence> result,
 116                 final MemberSelectTree select, final boolean endsWithDot) {
 117         final ExpressionTree objExpr = select.getExpression();
 118         final String objExprCode = exprStr.substring((int)objExpr.getStartPosition(), (int)objExpr.getEndPosition());
 119 
 120         // try to evaluate the object expression part as a script
 121         Object obj = null;
 122         try {
 123             obj = context.eval(global, objExprCode, global, "<suggestions>");
 124         } catch (Exception ignored) {
 125             // throw the exception - this is during tab-completion
 126         }
 127 
 128         if (obj != null && obj != ScriptRuntime.UNDEFINED) {
 129             if (endsWithDot) {
 130                 // no user specified "prefix". List all properties of the object
 131                 result.addAll(PropertiesHelper.getProperties(obj));
 132                 return cursor;
 133             } else {
 134                 // list of properties matching the user specified prefix
 135                 final String prefix = select.getIdentifier();
 136                 result.addAll(PropertiesHelper.getProperties(obj, prefix));
 137                 return cursor - prefix.length();
 138             }
 139         }
 140 
 141         return cursor;
 142     }
 143 
 144     private int completeIdentifier(final String test, final int cursor, final List<CharSequence> result,
 145                 final IdentifierTree ident) {
 146         final String name = ident.getName();
 147         result.addAll(PropertiesHelper.getProperties(global, name));
 148         return cursor - name.length();
 149     }
 150 
 151     // returns ExpressionTree if the given code parses to a top level expression.
 152     // Or else returns null.
 153     private ExpressionTree getTopLevelExpression(final Parser parser, final String code) {
 154         try {
 155             final CompilationUnitTree cut = parser.parse("<code>", code, null);
 156             final List<? extends Tree> stats = cut.getSourceElements();
 157             if (stats.size() == 1) {
 158                 final Tree stat = stats.get(0);
 159                 if (stat instanceof ExpressionStatementTree) {
 160                     return ((ExpressionStatementTree)stat).getExpression();
 161                 }
 162             }
 163         } catch (final NashornException ignored) {
 164             // ignore any parser error. This is for completion anyway!
 165             // And user will get that error later when the expression is evaluated.
 166         }
 167 
 168         return null;
 169     }
 170 
 171     private Tree getRightMostExpression(final ExpressionTree expr) {
 172         return expr.accept(new SimpleTreeVisitorES5_1<Tree, Void>() {
 173             @Override
 174             public Tree visitAssignment(final AssignmentTree at, final Void v) {
 175                 return getRightMostExpression(at.getExpression());
 176             }
 177 
 178             @Override
 179             public Tree visitCompoundAssignment(final CompoundAssignmentTree cat, final Void v) {
 180                 return getRightMostExpression(cat.getExpression());
 181             }
 182 
 183             @Override
 184             public Tree visitConditionalExpression(final ConditionalExpressionTree cet, final Void v) {
 185                 return getRightMostExpression(cet.getFalseExpression());
 186             }
 187 
 188             @Override
 189             public Tree visitBinary(final BinaryTree bt, final Void v) {
 190                 return getRightMostExpression(bt.getRightOperand());
 191             }
 192 
 193             @Override
 194             public Tree visitIdentifier(final IdentifierTree ident, final Void v) {
 195                 return ident;
 196             }
 197 
 198 
 199             @Override
 200             public Tree visitInstanceOf(final InstanceOfTree it, final Void v) {
 201                 return it.getType();
 202             }
 203 
 204 
 205             @Override
 206             public Tree visitMemberSelect(final MemberSelectTree select, final Void v) {
 207                 return select;
 208             }
 209 
 210             @Override
 211             public Tree visitNew(final NewTree nt, final Void v) {
 212                 final ExpressionTree call = nt.getConstructorExpression();
 213                 if (call instanceof FunctionCallTree) {
 214                     final ExpressionTree func = ((FunctionCallTree)call).getFunctionSelect();
 215                     // Is this "new Foo" or "new obj.Foo" with no user arguments?
 216                     // If so, we may be able to do completion of constructor name.
 217                     if (func.getEndPosition() == nt.getEndPosition()) {
 218                         return func;
 219                     }
 220                 }
 221                 return null;
 222             }
 223 
 224             @Override
 225             public Tree visitUnary(final UnaryTree ut, final Void v) {
 226                 return getRightMostExpression(ut.getExpression());
 227             }
 228         }, null);
 229     }
 230 }