/* SHS: Syntactically Homogeneous Shell * Copyright (C) 2019 Aidan Hahn * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ package ast import ( "fmt" "gitlab.com/whom/shs/log" ) /* expected function header for any stdlib function */ type Operation func(*Token, VarTable, FuncTable) *Token /* holds a stdlib function along with relevant metadata */ type Function struct { // go function that list of args are passed to Function Operation // name of function Name string // number of times user has called this function TimesCalled int // number of args required Args int } /* holds a mapping of key to function * passed to eval and into function calls * initialized by repl at startup */ type FuncTable *map[string]*Function /* validates an individual call of a function * makes sure correct arguments are passed in */ func (f Function) ParseFunction(args *Token) bool { // handle infinite args if f.Args < 0 { return true } i := f.Args for iter := args; iter != nil; iter = iter.Next { i -= 1 } if i != 0 { log.Log(log.ERR, "Incorrect number of arguments", "eval") log.Log(log.DEBUG, fmt.Sprintf("Function %s expects %d arguments. You've provided %d arguments.", f.Name, f.Args, f.Args - i), "eval") return false } return true } /* handles a call to a function * calls ParseFunction and increments TimesCalled */ func (f Function) CallFunction(args *Token, vt VarTable, ft FuncTable) *Token { if !f.ParseFunction(args) { log.Log(log.ERR, "Couldnt call " + f.Name, "eval") return nil } f.TimesCalled += 1 return f.Function(args, vt, ft) } /* searches for function mapped to argument in FuncTable */ func GetFunction(arg string, table FuncTable) *Function { target, ok := (*table)[arg] if !ok { log.Log(log.INFO, "function " + arg + " not found", "ftable") return nil } return target } /* returns list of all functions in table */ func ListFuncs(ft FuncTable) []string { keys := make([]string, len(*ft)) i := 0 for k := range *ft { keys[i] = k i++ } return keys }