node: implement var_dump, var_export, print_r, max, min, floor, substr, rename

This commit is contained in:
mappu 2020-04-16 18:38:38 +12:00
parent a839ceaf30
commit 23e06f517c

63
node.go
View File

@ -1208,6 +1208,69 @@ func (this *conversionState) convertNoFreeFloating(n_ node.Node) (string, error)
} else if funcName == `extract` {
return "", parseErr{n, fmt.Errorf("Unsupported dynamic function `\\extract()`")}
} else if funcName == `var_dump` {
// This is mostly called for debugging purposes. Printf should be good enough
this.importPackages["fmt"] = struct{}{}
callParams = append([]string{`"%#v\n"`}, callParams...) // Insert extra 1st parameter
funcName = `fmt.Printf`
} else if funcName == `max` {
this.importPackages["math"] = struct{}{}
funcName = `math.Max` // n.b. only works on 2 integers, not as wide as PHP's version
} else if funcName == `min` {
this.importPackages["math"] = struct{}{}
funcName = `math.Max` // n.b. only works on 2 integers, not as wide as PHP's version
} else if funcName == `floor` {
this.importPackages["math"] = struct{}{}
funcName = `math.Floor`
} else if funcName == `var_export` || funcName == `print_r` {
if len(callParams) == 1 {
this.importPackages["fmt"] = struct{}{}
callParams = append([]string{`"%#v\n"`}, callParams...) // Insert extra 1st parameter
funcName = `fmt.Printf`
} else if len(callParams) == 2 {
// Returning form
this.importPackages["fmt"] = struct{}{}
callParams = append([]string{`"%#v\n"`}, callParams...) // Insert extra 1st parameter
funcName = `fmt.Sprintf`
} else {
return "", parseErr{n, fmt.Errorf("Call to '%s' expected 3 or 4 argument(s), got %d", funcName, len(callParams))}
}
} else if funcName == `substr` {
// substr($string, $start [, $length]) => new string
// In Go all strings are immutable, and slicing an existing string produces a new immutable string so that works out
if len(callParams) == 2 {
return "(" + callParams[0] + ")[" + callParams[1] + ":]", nil
} else if len(callParams) == 3 {
// if lnum, ok := n.ArgumentList.Arguments[1].
// WARNING: We are doubling up on the first parameter
// This is a problem if it's not necessarily constant
return "(" + callParams[0] + ")[" + callParams[1] + ":" + callParams[1] + `+` + callParams[2] + "]", nil
} else {
return "", parseErr{n, fmt.Errorf("Call to '%s' expected 2 or 3 argument(s), got %d", funcName, len(callParams))}
}
} else if funcName == `rename` {
if len(callParams) != 2 {
return "", parseErr{n, fmt.Errorf("Call to '%s' expected 2 argument(s), got %d", funcName, len(callParams))}
}
this.importPackages["os"] = struct{}{}
funcName = `os.Rename`
}
return funcName + "(" + strings.Join(callParams, ", ") + ")", nil // expr only, no semicolon/newline