full support of varArgs (the ellipse)

This commit is contained in:
hneemann 2018-03-18 08:48:11 +01:00
parent 0161e7e562
commit 4fda2edf0d
2 changed files with 34 additions and 14 deletions

View File

@ -10,6 +10,7 @@ import de.neemann.digital.hdl.hgs.Expression;
import de.neemann.digital.hdl.hgs.HGSEvalException;
import de.neemann.digital.hdl.hgs.HGSMap;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
@ -56,6 +57,7 @@ public final class JavaClass<T> {
private final int argCount;
private final int javaArgCount;
private final boolean isVarArgs;
private Class<?> compType;
private MyMethod(Method method, boolean isStatic) {
this.method = method;
@ -68,6 +70,7 @@ public final class JavaClass<T> {
isVarArgs = method.isVarArgs();
if (isVarArgs) {
argCount = -1;
compType = argTypes[argTypes.length - 1].getComponentType();
} else {
if (addContext)
argCount = argTypes.length - 1;
@ -95,18 +98,24 @@ public final class JavaClass<T> {
i++;
}
} else {
// ellipse
int fixed = javaArgCount - i - 1;
for (int n = 0; n < fixed; n++) {
a[i] = args.get(n).value(c);
i++;
}
final int numVarArgs = args.size() - fixed;
String[] varArgs = new String[numVarArgs];
for (int n = fixed; n < args.size(); n++)
varArgs[n - fixed] = args.get(n).value(c).toString();
try {
// ellipse
int fixed = javaArgCount - i - 1;
for (int n = 0; n < fixed; n++) {
a[i] = args.get(n).value(c);
i++;
}
final int numVarArgs = args.size() - fixed;
Object varArgs = Array.newInstance(compType, numVarArgs);
for (int n = fixed; n < args.size(); n++)
Array.set(varArgs, n - fixed, args.get(n).value(c));
a[i] = varArgs;
a[i] = varArgs;
} catch (RuntimeException e) {
throw new HGSEvalException("type error assigning value to var array in "
+ method.getName() + ". Type "
+ compType.getSimpleName() + " is required.");
}
}
try {

View File

@ -432,12 +432,19 @@ public class ParserTest extends TestCase {
inner -= n;
}
public static String mean(String... value) {
public static String concat(String... value) {
String sum = "";
for (int i = 0; i < value.length; i++)
sum += value[i];
return sum;
}
public static long mean(long... value) {
long sum = 0;
for (int i = 0; i < value.length; i++)
sum += value[i];
return sum / value.length;
}
}
public void testJavaClass() throws ParserException, IOException, HGSEvalException {
@ -453,9 +460,13 @@ public class ParserTest extends TestCase {
assertEquals(3L, TestClassStatic.inner);
Context c = exec("<? print(z.mean(\"a\"), z.mean(\"a\",\"b\"), z.mean(\"a\",\"b\",\"c\")); ?>",
Context c = exec("<? print(z.concat(\"a\"), z.concat(\"a\",\"b\"), z.concat(\"a\",\"b\",\"c\")); ?>",
new Context().declareVar("z", jcs.createMap(null)));
assertEquals("aababc",c.toString());
assertEquals("aababc", c.toString());
c = exec("<? print(z.mean(1),\",\",z.mean(3,5),\",\",z.mean(3,4,5)); ?>",
new Context().declareVar("z", jcs.createMap(null)));
assertEquals("1,4,4", c.toString());
}