gitee.com/liu-zhao234568/cntest@v1.0.0/internal/jsre/completion.go (about) 1 // Copyright 2016 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package jsre 18 19 import ( 20 "sort" 21 "strings" 22 23 "github.com/dop251/goja" 24 ) 25 26 // CompleteKeywords returns potential continuations for the given line. Since line is 27 // evaluated, callers need to make sure that evaluating line does not have side effects. 28 func (jsre *JSRE) CompleteKeywords(line string) []string { 29 var results []string 30 jsre.Do(func(vm *goja.Runtime) { 31 results = getCompletions(vm, line) 32 }) 33 return results 34 } 35 36 func getCompletions(vm *goja.Runtime, line string) (results []string) { 37 parts := strings.Split(line, ".") 38 if len(parts) == 0 { 39 return nil 40 } 41 42 // Find the right-most fully named object in the line. e.g. if line = "x.y.z" 43 // and "x.y" is an object, obj will reference "x.y". 44 obj := vm.GlobalObject() 45 for i := 0; i < len(parts)-1; i++ { 46 v := obj.Get(parts[i]) 47 if v == nil { 48 return nil // No object was found 49 } 50 obj = v.ToObject(vm) 51 } 52 53 // Go over the keys of the object and retain the keys matching prefix. 54 // Example: if line = "x.y.z" and "x.y" exists and has keys "zebu", "zebra" 55 // and "platypus", then "x.y.zebu" and "x.y.zebra" will be added to results. 56 prefix := parts[len(parts)-1] 57 iterOwnAndConstructorKeys(vm, obj, func(k string) { 58 if strings.HasPrefix(k, prefix) { 59 if len(parts) == 1 { 60 results = append(results, k) 61 } else { 62 results = append(results, strings.Join(parts[:len(parts)-1], ".")+"."+k) 63 } 64 } 65 }) 66 67 // Append opening parenthesis (for functions) or dot (for objects) 68 // if the line itself is the only completion. 69 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 results[0] += "(" 74 } else { 75 results[0] += "." 76 } 77 } 78 } 79 80 sort.Strings(results) 81 return results 82 }