diff --git a/numscript.go b/numscript.go index 92101b9e..a56b02ed 100644 --- a/numscript.go +++ b/numscript.go @@ -12,8 +12,23 @@ type ParseResult struct { parseResult parser.ParseResult } -// ---- TODO useful for the playground -// func (*ParseResult) GetNeededVariables() map[string]ValueType {} +// Returns a map from a variable's name to its type. +// +// doesn't include variables whose value is already defined within the script +func (p ParseResult) GetNeededVariables() map[string]string { + m := make(map[string]string) + + for _, varDecl := range p.parseResult.Value.Vars { + if varDecl.Name == nil || varDecl.Origin != nil { + continue + } + + m[varDecl.Name.Name] = varDecl.Type.Name + } + + return m +} + // func (*ParseResult) GetDiagnostics() []Diagnostic {} type ParserError = parser.ParserError diff --git a/numscript_test.go b/numscript_test.go index f1aa0f4d..9536786f 100644 --- a/numscript_test.go +++ b/numscript_test.go @@ -11,6 +11,30 @@ import ( "github.com/stretchr/testify/require" ) +func TestGetVars(t *testing.T) { + parseResult := numscript.Parse(` + vars { + monetary $mon + account $acc + account $acc2 + + monetary $do_not_include_in_output = balance(@acc, USD/2) + } +`) + + require.Empty(t, parseResult.GetParsingErrors(), "There should not be parsing errors") + + require.Equal(t, + map[string]string{ + "mon": "monetary", + "acc": "account", + "acc2": "account", + }, + parseResult.GetNeededVariables(), + ) + +} + func TestDoNotGetWorldBalance(t *testing.T) { parseResult := numscript.Parse(`send [COIN 100] ( source = @world