SHS/stdlib/control_flow.go

97 lines
2.5 KiB
Go
Raw Normal View History

2020-06-30 20:27:12 -07:00
/* 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 <https://www.gnu.org/licenses/>.
*/
package stdlib
import (
"gitlab.com/whom/shs/ast"
"gitlab.com/whom/shs/log"
)
2020-06-30 20:27:12 -07:00
2020-07-18 10:44:18 -07:00
/* eval N forms. return the last one
*/
func shs_progn(in *ast.Token, vt ast.VarTable, ft ast.FuncTable) *ast.Token {
var res *ast.Token
for iter := in; iter != nil; iter = iter.Next {
res = iter.Eval(ft, vt, false)
}
return res
}
2020-06-30 20:27:12 -07:00
/* return one evaluated form or another based on the boolean statement
*/
func shs_if(in *ast.Token, vt ast.VarTable, ft ast.FuncTable) *ast.Token {
2020-06-30 20:27:12 -07:00
cond := in
t := cond.Next
f := t.Next
cond.Next = nil
t.Next = nil
cond = cond.Eval(ft, vt, false)
if cond == nil || cond.Tag != ast.BOOL {
log.Log(log.ERR,
"first argument to if must be a bool statement",
"if")
return nil
}
switch cond.Value() {
case ast.TRUE:
return t
case ast.FALSE:
return f
default:
log.Log(log.ERR,
"improper bool!",
"if")
return nil
}
}
/* continually eval n forms while element #1 evals to T
*/
func shs_while(in *ast.Token, vt ast.VarTable, ft ast.FuncTable) *ast.Token {
2020-06-30 20:27:12 -07:00
cond := in
forms := in.Next
in.Next = nil
var res *ast.Token
eval := cond.Eval(ft, vt, false)
if eval == nil || eval.Tag != ast.BOOL {
2020-06-30 20:27:12 -07:00
log.Log(log.ERR,
"first argument to while must be a bool statement",
"while")
return nil
}
// slight downside here: doesnt log when the wrong tag is set
for eval.Tag == ast.BOOL && eval.Value() == ast.TRUE {
2020-06-30 20:27:12 -07:00
// eval all forms
for i := forms; i != nil; i = i.Next {
res = i.Eval(ft, vt, false)
}
// retest eval
eval = cond.Eval(ft, vt, false)
2020-06-30 20:27:12 -07:00
}
return res
}