lang: Add module imports and more

This enables imports in mcl code, and is one of last remaining blockers
to using mgmt. Now we can start writing standalone modules, and adding
standard library functions as needed. There's still lots to do, but this
was a big missing piece. It was much harder to get right than I had
expected, but I think it's solid!

This unfortunately large commit is the result of some wild hacking I've
been doing for the past little while. It's the result of a rebase that
broke many "wip" commits that tracked my private progress, into
something that's not gratuitously messy for our git logs. Since this was
a learning and discovery process for me, I've "erased" the confusing git
history that wouldn't have helped. I'm happy to discuss the dead-ends,
and a small portion of that code was even left in for possible future
use.

This patch includes:

* A change to the cli interface:
You now specify the front-end explicitly, instead of leaving it up to
the front-end to decide when to "activate". For example, instead of:

mgmt run --lang code.mcl

we now do:

mgmt run lang --lang code.mcl

We might rename the --lang flag in the future to avoid the awkward word
repetition. Suggestions welcome, but I'm considering "input". One
side-effect of this change, is that flags which are "engine" specific
now must be specified with "run" before the front-end name. Eg:

mgmt run --tmp-prefix lang --lang code.mcl

instead of putting --tmp-prefix at the end. We also changed the GAPI
slightly, but I've patched all code that used it. This also makes things
consistent with the "deploy" command.

* The deploys are more robust and let you deploy after a run
This has been vastly improved and let's mgmt really run as a smart
engine that can handle different workloads. If you don't want to deploy
when you've started with `run` or if one comes in, you can use the
--no-watch-deploy option to block new deploys.

* The import statement exists and works!
We now have a working `import` statement. Read the docs, and try it out.
I think it's quite elegant how it fits in with `SetScope`. Have a look.
As a result, we now have some built-in functions available in modules.
This also adds the metadata.yaml entry-point for all modules. Have a
look at the examples or the tests. The bulk of the patch is to support
this.

* Improved lang input parsing code:
I re-wrote the parsing that determined what ran when we passed different
things to --lang. Deciding between running an mcl file or raw code is
now handled in a more intelligent, and re-usable way. See the inputs.go
file if you want to have a look. One casualty is that you can't stream
code from stdin *directly* to the front-end, it's encapsulated into a
deploy first. You can still use stdin though! I doubt anyone will notice
this change.

* The scope was extended to include functions and classes:
Go forth and import lovely code. All these exist in scopes now, and can
be re-used!

* Function calls actually use the scope now. Glad I got this sorted out.

* There is import cycle detection for modules!
Yes, this is another dag. I think that's #4. I guess they're useful.

* A ton of tests and new test infra was added!
This should make it much easier to add new tests that run mcl code. Have
a look at TestAstFunc1 to see how to add more of these.

As usual, I'll try to keep these commits smaller in the future!
This commit is contained in:
James Shubin
2018-11-22 16:48:10 -05:00
parent 948a3c6d08
commit 96dccca475
146 changed files with 5301 additions and 1112 deletions

View File

@@ -18,8 +18,8 @@
package lang // TODO: move this into a sub package of lang/$name?
import (
"bytes"
"fmt"
"io"
"sync"
"github.com/purpleidea/mgmt/engine"
@@ -28,14 +28,12 @@ import (
"github.com/purpleidea/mgmt/lang/interfaces"
"github.com/purpleidea/mgmt/lang/unification"
"github.com/purpleidea/mgmt/pgraph"
"github.com/purpleidea/mgmt/util"
errwrap "github.com/pkg/errors"
)
const (
// FileNameExtension is the filename extension used for languages files.
FileNameExtension = "mcl" // alternate suggestions welcome!
// make these available internally without requiring the import
operatorFuncName = funcs.OperatorFuncName
historyFuncName = funcs.HistoryFuncName
@@ -44,7 +42,17 @@ const (
// Lang is the main language lexer/parser object.
type Lang struct {
Input io.Reader // os.Stdin or anything that satisfies this interface
Fs engine.Fs // connected fs where input dir or metadata exists
// Input is a string which specifies what the lang should run. It can
// accept values in several different forms. If is passed a single dash
// (-), then it will use `os.Stdin`. If it is passed a single .mcl file,
// then it will attempt to run that. If it is passed a directory path,
// then it will attempt to run from there. Instead, if it is passed the
// path to a metadata file, then it will attempt to parse that and run
// from that specification. If none of those match, it will attempt to
// run the raw string as mcl code.
Input string
Hostname string
World engine.World
Prefix string
@@ -76,9 +84,36 @@ func (obj *Lang) Init() error {
once := &sync.Once{}
loadedSignal := func() { close(obj.loadedChan) } // only run once!
if obj.Debug {
obj.Logf("input: %s", obj.Input)
tree, err := util.FsTree(obj.Fs, "/") // should look like gapi
if err != nil {
return err
}
obj.Logf("run tree:\n%s", tree)
}
// we used to support stdin passthrough, but we we got rid of it for now
// the fs input here is the local fs we're reading to get the files from
// which is usually etcdFs.
output, err := parseInput(obj.Input, obj.Fs)
if err != nil {
return errwrap.Wrapf(err, "could not activate an input parser")
}
if len(output.Workers) > 0 {
// either programming error, or someone hacked in something here
// by the time *this* parseInput runs, we should be standardized
return fmt.Errorf("input contained file system workers")
}
reader := bytes.NewReader(output.Main)
// no need to run recursion detection since this is the beginning
// TODO: do the paths need to be cleaned for "../" before comparison?
// run the lexer/parser and build an AST
obj.Logf("lexing/parsing...")
ast, err := LexParse(obj.Input)
// this reads an io.Reader, which might be a stream of multiple files...
ast, err := LexParse(reader)
if err != nil {
return errwrap.Wrapf(err, "could not generate AST")
}
@@ -86,10 +121,29 @@ func (obj *Lang) Init() error {
obj.Logf("behold, the AST: %+v", ast)
}
importGraph, err := pgraph.NewGraph("importGraph")
if err != nil {
return errwrap.Wrapf(err, "could not create graph")
}
importVertex := &pgraph.SelfVertex{
Name: "", // first node is the empty string
Graph: importGraph, // store a reference to ourself
}
importGraph.AddVertex(importVertex)
obj.Logf("init...")
// init and validate the structure of the AST
data := &interfaces.Data{
Debug: obj.Debug,
Fs: obj.Fs,
Base: output.Base, // base dir (absolute path) the metadata file is in
Files: output.Files,
Imports: importVertex,
Metadata: output.Metadata,
Modules: "/" + interfaces.ModuleDirectory, // do not set from env for a deploy!
//World: obj.World, // TODO: do we need this?
Prefix: obj.Prefix,
Debug: obj.Debug,
Logf: func(format string, v ...interface{}) {
// TODO: is this a sane prefix to use here?
obj.Logf("ast: "+format, v...)
@@ -115,6 +169,8 @@ func (obj *Lang) Init() error {
// TODO: change to a func when we can change hostname dynamically!
"hostname": &ExprStr{V: obj.Hostname},
},
// all the built-in top-level, core functions enter here...
Functions: funcs.LookupPrefix(""),
}
obj.Logf("building scope...")