Example #1
0
File: compile.go Project: jbert/gol
func (gb *GolangBackend) compileLambdaApplication(nl *gol.NodeLambda, vals *gol.NodeList) (string, error) {
	bindings := make(map[string]gol.Node)

	args := nl.Args

	if args.Len() != vals.Len() {
		return "", fmt.Errorf("Wrong number of args for lambda. [%s] != [%s]",
			args.String(), vals.String())
	}

	for vals.Len() > 0 {
		id := args.First().String()
		bindings[id] = vals.First()

		vals = vals.Rest()
		args = args.Rest()
	}

	letForLambda := &gol.NodeLet{
		//		NodeList: nl.NodeList,
		Bindings: bindings,
		Body:     nl.Body,
	}
	lambdaVarType, ok := nl.Type().(*typ.Var)
	if !ok {
		// Not an error if it's a functype, but we assign vars to all nodes....
		return "", fmt.Errorf("Odd - not a var, instead a %T: %s\n", nl.Type(), nl.Type())
	}
	lambdaType, err := lambdaVarType.Lookup()
	if err != nil {
		return "", fmt.Errorf("Can't look up lambda var: %s [%T]\n", lambdaVarType, lambdaVarType)
	}
	funcType, ok := lambdaType.(typ.Func)
	if !ok {
		return "", fmt.Errorf("Lambda doesn't have function type: %s [%T]\n", nl.Type(), nl.Type())
	}

	letForLambda.NodeList = gol.NewNodeListType(funcType.Result)
	return gb.compileLet(letForLambda)
}
Example #2
0
File: compile.go Project: jbert/gol
func (gb *GolangBackend) compileAnonOrNamedLambda(nl *gol.NodeLambda, name string) (string, error) {

	lambdaType, err := typ.Resolve(nl.Type())
	if err != nil {
		return "", fmt.Errorf("Can't resolve lambda var: %s [%T]\n", lambdaType, lambdaType)
	}

	funcType, ok := lambdaType.(typ.Func)
	if !ok {
		return "", fmt.Errorf("Lambda doesn't have function type: %s [%T]\n", nl.Type(), nl.Type())
	}

	if nl.Args.Len() != len(funcType.Args) {
		return "", fmt.Errorf("Arg/type mismatch: %d != %d\n", nl.Args.Len(), len(funcType.Args))
	}

	i := 0
	strArgs := make([]string, len(funcType.Args))
	err = nl.Args.Foreach(func(child gol.Node) error {
		golangType, err := golangStringForType(funcType.Args[i])
		if err != nil {
			return err
		}

		id := child.String()
		strArgs[i] = fmt.Sprintf("%s %s", mangleIdentifier(id), golangType)
		i++
		return nil
	})
	if err != nil {
		return "", err
	}

	golangRetType, err := golangStringForType(funcType.Result)
	if err != nil {
		return "", err
	}
	s := fmt.Sprintf("func %s(%s) %s {", mangleIdentifier(name), strings.Join(strArgs, ", "), golangRetType)
	body, err := gb.compile(nl.Body)
	if err != nil {
		return "", err
	}
	s += "return " + body
	s += "}"
	return s, nil
}