generated from okp4/template-oss
-
Notifications
You must be signed in to change notification settings - Fork 128
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(logic): implements source_file/1 predicate
- Loading branch information
Showing
2 changed files
with
73 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
package predicate | ||
|
||
import ( | ||
"fmt" | ||
"reflect" | ||
"sort" | ||
|
||
"github.com/ichiban/prolog/engine" | ||
) | ||
|
||
func SourceFile(vm *engine.VM, file engine.Term, cont engine.Cont, env *engine.Env) *engine.Promise { | ||
loaded := getLoadedSources(vm) | ||
|
||
inputFile, err := getFile(env, file) | ||
if err != nil { | ||
return engine.Error(fmt.Errorf("source_file/1: %w", err)) | ||
} | ||
|
||
if inputFile != nil { | ||
if _, ok := loaded[*inputFile]; ok { | ||
return engine.Unify(vm, file, engine.NewAtom(*inputFile), cont, env) | ||
} | ||
return engine.Unify(vm, file, engine.List(), cont, env) | ||
} | ||
|
||
result := make([]engine.Term, 0, len(loaded)) | ||
for _, filename := range sortLoadedSources(loaded) { | ||
result = append(result, engine.NewAtom(filename)) | ||
} | ||
|
||
return engine.Unify( | ||
vm, | ||
file, | ||
engine.List(result...), | ||
cont, | ||
env, | ||
) | ||
} | ||
|
||
func getLoadedSources(vm *engine.VM) map[string]interface{} { | ||
loadedField := reflect.ValueOf(vm).Elem().FieldByName("loaded").MapKeys() | ||
loaded := make(map[string]interface{}, len(loadedField)) | ||
for _, value := range loadedField { | ||
loaded[value.String()] = nil | ||
} | ||
|
||
return loaded | ||
} | ||
|
||
func sortLoadedSources(sources map[string]interface{}) []string { | ||
result := make([]string, 0, len(sources)) | ||
for filename := range sources { | ||
result = append(result, filename) | ||
} | ||
sort.SliceStable(result, func(i, j int) bool { | ||
return result[i] < result[j] | ||
}) | ||
|
||
return result | ||
} | ||
|
||
func getFile(env *engine.Env, term engine.Term) (*string, error) { | ||
switch file := env.Resolve(term).(type) { | ||
case engine.Variable: | ||
case engine.Atom: | ||
strFile := file.String() | ||
return &strFile, nil | ||
default: | ||
return nil, fmt.Errorf("cannot unify file with %T", term) | ||
} | ||
return nil, nil | ||
} |