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