github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/internal/jsre/completion.go (about) 1 // Copyright 2018 The go-ethereum Authors 2 // Copyright 2019 The go-aigar Authors 3 // This file is part of the go-aigar library. 4 // 5 // The go-aigar library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Lesser General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // The go-aigar library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public License 16 // along with the go-aigar library. If not, see <http://www.gnu.org/licenses/>. 17 18 package jsre 19 20 import ( 21 "sort" 22 "strings" 23 24 "github.com/robertkrimen/otto" 25 ) 26 27 // CompleteKeywords returns potential continuations for the given line. Since line is 28 // evaluated, callers need to make sure that evaluating line does not have side effects. 29 func (jsre *JSRE) CompleteKeywords(line string) []string { 30 var results []string 31 jsre.Do(func(vm *otto.Otto) { 32 results = getCompletions(vm, line) 33 }) 34 return results 35 } 36 37 func getCompletions(vm *otto.Otto, line string) (results []string) { 38 parts := strings.Split(line, ".") 39 objRef := "this" 40 prefix := line 41 if len(parts) > 1 { 42 objRef = strings.Join(parts[0:len(parts)-1], ".") 43 prefix = parts[len(parts)-1] 44 } 45 46 obj, _ := vm.Object(objRef) 47 if obj == nil { 48 return nil 49 } 50 iterOwnAndConstructorKeys(vm, obj, func(k string) { 51 if strings.HasPrefix(k, prefix) { 52 if objRef == "this" { 53 results = append(results, k) 54 } else { 55 results = append(results, strings.Join(parts[:len(parts)-1], ".")+"."+k) 56 } 57 } 58 }) 59 60 // Append opening parenthesis (for functions) or dot (for objects) 61 // if the line itself is the only completion. 62 if len(results) == 1 && results[0] == line { 63 obj, _ := vm.Object(line) 64 if obj != nil { 65 if obj.Class() == "Function" { 66 results[0] += "(" 67 } else { 68 results[0] += "." 69 } 70 } 71 } 72 73 sort.Strings(results) 74 return results 75 }