completion.go 2.53 KB
Newer Older
1
// Copyright 2016 The go-ethereum Authors
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

package jsre

import (
	"sort"
	"strings"

23
	"github.com/dop251/goja"
24 25 26 27 28 29
)

// CompleteKeywords returns potential continuations for the given line. Since line is
// evaluated, callers need to make sure that evaluating line does not have side effects.
func (jsre *JSRE) CompleteKeywords(line string) []string {
	var results []string
30
	jsre.Do(func(vm *goja.Runtime) {
Felix Lange's avatar
Felix Lange committed
31 32
		results = getCompletions(vm, line)
	})
33 34 35
	return results
}

36
func getCompletions(vm *goja.Runtime, line string) (results []string) {
37
	parts := strings.Split(line, ".")
38 39
	if len(parts) == 0 {
		return nil
40 41
	}

42 43 44 45 46
	// Find the right-most fully named object in the line. e.g. if line = "x.y.z"
	// and "x.y" is an object, obj will reference "x.y".
	obj := vm.GlobalObject()
	for i := 0; i < len(parts)-1; i++ {
		v := obj.Get(parts[i])
47
		if v == nil || goja.IsNull(v) || goja.IsUndefined(v) {
48 49 50
			return nil // No object was found
		}
		obj = v.ToObject(vm)
51
	}
52 53 54 55 56

	// Go over the keys of the object and retain the keys matching prefix.
	// Example: if line = "x.y.z" and "x.y" exists and has keys "zebu", "zebra"
	// and "platypus", then "x.y.zebu" and "x.y.zebra" will be added to results.
	prefix := parts[len(parts)-1]
57
	iterOwnAndConstructorKeys(vm, obj, func(k string) {
58
		if strings.HasPrefix(k, prefix) {
59
			if len(parts) == 1 {
60 61 62 63 64
				results = append(results, k)
			} else {
				results = append(results, strings.Join(parts[:len(parts)-1], ".")+"."+k)
			}
		}
65
	})
66 67 68 69

	// Append opening parenthesis (for functions) or dot (for objects)
	// if the line itself is the only completion.
	if len(results) == 1 && results[0] == line {
70
		obj := obj.Get(parts[len(parts)-1])
71
		if obj != nil {
72
			if _, isfunc := goja.AssertFunction(obj); isfunc {
73 74 75 76 77
				results[0] += "("
			} else {
				results[0] += "."
			}
		}
78 79 80 81 82
	}

	sort.Strings(results)
	return results
}