How is it that the val() and rep() functions are called in this code(there's no definition for them)? - abstract-syntax-tree

I'm using a parser generator called CUP. I was provided with the grammar (CUP specification) and this piece of supporting code (Expr.java) for the class definitions.
In the CUP specification, the grammar productions have a semantic action associated with them like this:
expr ::= expr:e1 PLUS expr:e2
{: RESULT = new OpExpr(e1,e2,sym.PLUS); :};
The class definition is something like this:
package java_cup.output;
abstract class Expr {
protected static String symbols[] = new String[12];
.
.
.
public abstract Integer val();
public abstract String rep();
}
There's a class for Integer expressions
class IntExpr extends Expr{
Integer intExpr;
public IntExpr(Integer e) { intExpr = e; }
public Integer val() { return intExpr; }
public String rep() { return "Integer{"+intExpr.toString()+"}"; }
}
And then, there are classes like:
class ParaExpr extends Expr {
Expr paraExpr;
public ParaExpr(Expr e) { paraExpr = e; }
public Integer val() { return paraExpr.val(); }
public String rep() { return "ParaExpr{("+paraExpr.rep()+")}"; }
}
Essentially, my question is this: There is no definition given for the rep() function of the Expr class (because it is abstract). Then what does this function call do ? paraExpr.rep()
When I create a project, build the parser and and parse an input string, it creates an AST and prints it out like this:
ParaExpr{(IntExpr{(1)}+IntExpr{(2)})}

Nothing, it's an abstract method so doesn't have any implementation. but you already knew that.
You won't have an instance of Expr when you are calling paraExpr.rep(), paraExp will be a subclass of Expr, one which does implement rep() .e.g. IntExpr

Related

Haxe: Binding pattern with abstract fields access methods

I'd like to make wrapper to implement simple data binding pattern -- while some data have been modified all registered handlers are got notified. I have started with this (for js target):
class Main {
public static function main() {
var target = new Some();
var binding = new Bindable(target);
binding.one = 5;
// binding.two = 0.12; // intentionally unset field
binding.three = []; // wrong type
binding.four = 'str'; // no such field in wrapped class
trace(binding.one, binding.two, binding.three, binding.four, binding.five);
// outputs: 5, null, [], str, null
trace(target.one, target.two, target.three);
// outputs: 5, null, []
}
}
class Some {
public var one:Int;
public var two:Float;
public var three:Bool;
public function new() {}
}
abstract Bindable<TClass>(TClass) {
public inline function new(source) { this = source; }
#:op(a.b) public function setField<T>(name:String, value:T) {
Reflect.setField(this, name, value);
// TODO notify handlers
return value;
}
#:op(a.b) public function getField<T>(name:String):T {
return cast Reflect.field(this, name);
}
}
So I have some frustrating issues: interface of wrapped object doesn't expose to wrapper, so there's no auto completion or strict type checking, some necessary attributes can be easily omitted or even misspelled.
Is it possible to fix my solution or should I better move to the macros?
I almost suggested here to open an issue regarding this problem. Because some time ago, there was a #:followWithAbstracts meta available for abstracts, which could be (or maybe was?) used to forward fields and call #:op(a.b) at the same time. But that's not really necessary, Haxe is powerful enough already.
abstract Binding<TClass>(TClass) {
public function new(source:TClass) { this = source; }
#:op(a.b) public function setField<T>(name:String, value:T) {
Reflect.setField(this, name, value);
// TODO notify handlers
trace("set: $name -> $value");
return value;
}
#:op(a.b) public function getField<T>(name:String):T {
trace("get: $name");
return cast Reflect.field(this, name);
}
}
#:forward
#:multiType
abstract Bindable<TClass>(TClass) {
public function new(source:TClass);
#:to function to(t:TClass) return new Binding(t);
}
We use here multiType abstract to forward fields, but resolved type is actually regular abstract. In effect, you have completion working and #:op(a.b) called at the same time.
You need #:forward meta on your abstract. However, this will not make auto-completion working unless you remove #:op(A.B) because it shadows forwarded fields.
EDIT: it seems that shadowing happened first time I added #:forward to your abstract, afterwards auto-completion worked just fine.

Using powermockito to mock a static method. What am I doing incorrectly?

I want to use powermock to state a static method on a class (fragment of class below):
public class TestService<T> {
public static <T> TestService<T> function1(Class<T> rawType, Object id) {
The relevant portion of the test class is listed below. While setting up the mock, if I explicitly set a value for the integer parameter, then call with that same value, everything works as expected. The call to function1 returns the testServiceProxy.
However, what I want to do is return that value no matter what value of the integer is passed in. To do this I comment out the first line:
// PowerMockito.when(TestService.function1(Subscription.class,id)).thenReturn(testServiceProxy);
and remove the comments from the second line.
After doing this, the calls to function1 return null.
Why??
#RunWith(PowerMockRunner.class)
#PrepareForTest(TestService.class)
public class TestServiceTest {
#Mock
private TestService<Subscription> testServiceProxy;
#Mock
private Subscription subscription;
#Test
public void testStart() throws Exception {
Integer id = new Integer(5);
PowerMockito.mockStatic(TestService.class);
PowerMockito.when(TestService.getString()).thenReturn("Hello!");
PowerMockito.when(testServiceProxy.getInt()).thenReturn(new Integer(15));
PowerMockito.when(TestService.function1(Subscription.class,id)).thenReturn(testServiceProxy);
// PowerMockito.when(TestService.function1(Subscription.class,Matchers.eq(any(Integer.class)))).thenReturn(testServiceProxy);
System.out.println("String: " + TestService.getString());
System.out.println("TestServiceProxy: "+testServiceProxy);
// id = new Integer(6);
System.out.println("Function1: "+TestService.function1(Subscription.class, id));
TestService<Subscription> foo = TestService.function1(Subscription.class, id);
if (foo != null) {
System.out.println(" foo instrumentId: "+foo.getInt());
System.out.println(" subselect instrumentId: "+testServiceProxy.getInt());
} else {
System.out.println("Foo is null");
}
}
}
After further work, I've come to understand that you can't be specific about one value and specify any for another.
Also I needed to use the Mockito class to ensure that the correct functions where being called.
PowerMockito.when(TestService.function1(Mockito.any(Class.class), Mockito.any(String.class))).thenReturn(testServiceProxy);
This method call correctly sets up the mocks to be used in my test case.

How can I check if a class belongs to Java JDK

I use an external library which return some List<?>.
I need to check if each object of this list is an Object of the JDK (String, int, Integer...).
Is this a proper solution?
List<?> list = externalLibrary.search(...);
for(clazz : list) {
if (clazz.getPackage().getName().startsWith("java.lang"))
// do something different
}
Is there a better one?
Depending on your definition of "object of the JDK" -- which could get quite fuzzy around the edges -- no, this isn't going to do it. The java.lang package is only a tiny part of all the classes included in the JDK.
You might check whether each object was loaded by the same ClassLoader that loaded java.lang.String -- i.e.,
if (theObject.getClass().getClassLoader() == "".getClass().getClassLoader()) ...
In general, a different ClassLoader will be used for system classes vs. application classes.
It is probably OK, just you have to check the following packages:
java
javax
com.sun
sun
probably others...
We use the below class to check if the classes belongs to JDK
public class JDKClass {
private static Set<String> CS = new HashSet<String>();
static {
try {
File file = new File(System.getProperty("java.home"),
"lib/classlist");
BufferedReader r = new BufferedReader(new FileReader(file));
String l;
while (true) {
l = r.readLine();
if (l == null) {
break;
} else {
CS.add(l.replace('/', '.'));
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static boolean contains(String o) {
return CS.contains(o) || o.startsWith("java") || o.startsWith("com.sun")
|| o.startsWith("sun") || o.startsWith("oracle")
|| o.startsWith("org.xml") || o.startsWith("com.oracle");
}
private JDKClass() {
}
}
You can use ClassLoader.getSystemResources and then check from what jar is the class loaded (f.g. if it comes from rt.jar).
You will get URL's such as:
jar:file:/C:/Users/user/.m2/repository/org/slf4j/slf4j-log4j12/1.6.1/slf4j-log4j12-1.6.1.jar!/org/slf4j/impl/StaticLoggerBinder.class
Example code taken from SLF4j:
private static String STATIC_LOGGER_BINDER_PATH =
"org/slf4j/impl/StaticLoggerBinder.class";
private static void singleImplementationSanityCheck() {
try {
ClassLoader loggerFactoryClassLoader = LoggerFactory.class
.getClassLoader();
Enumeration paths;
if (loggerFactoryClassLoader == null) {
paths = ClassLoader.getSystemResources(STATIC_LOGGER_BINDER_PATH);
} else {
paths = loggerFactoryClassLoader
.getResources(STATIC_LOGGER_BINDER_PATH);
}
List implementationList = new ArrayList();
while (paths.hasMoreElements()) {
URL path = (URL) paths.nextElement();
implementationList.add(path);
}
....
}
Personally I like class loader base answer. But it will return true also on StringBuilder. If you want to more narrow definition that is only "built-in" types, you can try to evaluate whether this is primitive type (such as int) or wrapper type (such as Integer) or String. You can write something like this:
import java.util.Map;
import java.util.TreeMap;
public class Utils {
private static Map<String, Class<?>> SUBST_MAP = new TreeMap<String, Class<?>>();
private static Map<String, Class<?>> SIMPLE_MAP = new TreeMap<String, Class<?>>();
static {
SUBST_MAP.put(Byte.class.getName(), Byte.TYPE);
SUBST_MAP.put(Short.class.getName(), Short.TYPE);
SUBST_MAP.put(Integer.class.getName(), Integer.TYPE);
SUBST_MAP.put(Long.class.getName(), Long.TYPE);
SUBST_MAP.put(Float.class.getName(), Float.TYPE);
SUBST_MAP.put(Double.class.getName(), Double.TYPE);
SUBST_MAP.put(Boolean.class.getName(), Boolean.TYPE);
SUBST_MAP.put(Character.class.getName(), Character.TYPE);
SIMPLE_MAP.put(String.class.getName(), Boolean.TRUE);
}
/**
* Gets the the class type of the types of the argument.
*
* if substPrimitiveWrapper is true,
* then if there is argument, that represent primitive type wrapper (such as Integer),
* then it will be substituted to primitive type (such as int).
* else no substitution will be done.
*
* #param arg object.
* #param substPrimitiveWrapper - wheteher to do primitive type substitution.
* #retrun class type.
*/
public static Class<?> getClassType(Object arg, boolean substPrimitiveWrapper){
Class<?> classType = null;
String className = null;
Class<?> substClass = null;
if(arg != null ){
//making default classType
classType = arg.getClass();
if(substPrimitiveWrapper){
className = classType.getName();
substClass = (Class<?>)SUBST_MAP.get(className);
if(substClass != null){
classType = substClass;
}
}
}
return classType;
}
/**
* This method consider JDK type any primitive type, wrapper class or String.
*
*
* #param arg object
* #return where arg is JDK type or now.
*/
public static boolean isJDKClass(Object arg){
Class<?> classType = getClassType(arg, true);
boolean isJDKClass = false;
if(classType!=null){
//if(String.class.equals(classType)){
// isJDKClass = true; //this is String, note that String is final
//}
assert classType!=null;
String className = classType.getName();
Boolean isFound = (Boolean)SIMPLE_MAP.get(className);
if(Boolean.TRUE.equals(isFound)){
isJDKClass = true; //this is predefined class
}
boolean isPrimitiveType = classType.isPrimitive();
if(isPrimitiveType){
isJDKClass = true; //this is primitive type or wrapper class
}
}
return isJDKClass;
}
}
You can also optionally add support for such classes like java.math.BigDecimal, java.util.Date, java.sql.Timestamp. Note, however, that they are not final, so I assumed that if somebody extended them even in the trivial way, it will not be considered as JDK class.
I think an easier solution is to thing of the problem this way:
write a method to identify all classes that are defined by you. In most cases, all user defined classes follow a pattern like com.something.something. Then if they do not belong to com.something.something, it is a JDK class

How to make BlazeDS name conversion to work for properties beginning with a lower-case letter followed by an upper-case one?

I have some trouble with the conversion applied by BlazeDS to the name of the properties when this name begins with a lower-case letter followed by a capital letter.
I have an ActionScript class similar to this:
package as.pkg {
[RemoteClass(alias="java.pkg.Example")]
public class Example {
private var mXRatio:Number;
public function get xRatio():Number {
return mXRatio;
}
public function set xRatio(r:Number):void {
mXRatio = r;
}
}
}
Then I have the equivalent Java class on the server:
package java.pkg;
public class Example {
private Double mXRatio;
public Double getXRatio() {
return mXRatio;
}
public void setXRatio( Double r ) {
mXRatio = r;
}
}
Sending instances from ActionScript to Java works perfectly fine. But when the instances are sent from Java to ActionScript, the following error is displayed:
ReferenceError: Error #1056: Cannot create property XRatio on as.pkg.Example.
Why BlazeDS does not convert the X of XRatio there? How can I avoid this?
BlazeDS uses reflection to inject values into your properties while serializing.
Therefore, your properties (public getter/setter pair or public variable) must have the exact same name or you will get serialization errors like the one you describe above.
Try this and it should be fine:
package as.pkg {
[RemoteClass(alias="java.pkg.Example")]
public class Example {
private var mXRatio:Number;
public function get XRatio():Number { //uppercase X i.s.o lowercase x
return mXRatio;
}
public function set XRatio(r:Number):void { //uppercase X i.s.o lowercase x
mXRatio = r;
}
}
}
Cheers

How to create a decent toString() method in scala using reflection?

To make debug-time introspection into classes easy, I'd like to make a generic toString method in the base class for the objects in question. As it's not performance critical code, I'd like to use Reflection to print out field name/value pairs ("x=1, y=2" etc).
Is there an easy way to do this? I tried several potential solutions, and ran up against security access issues, etc.
To be clear, the toString() method in the base class should reflectively iterate over public vals in any classes that inherit from it, as well as any traits that are mixed in.
Example:
override def toString() = {
getClass().getDeclaredFields().map { field:Field =>
field.setAccessible(true)
field.getName() + ": " + field.getType() + " = " + field.get(this).toString()
}.deepMkString("\n")
}
Uses Java Reflection API, so don't forget to import java.lang.reflect._
Also, you may need to catch IllegalAccessException on the field.get(this) calls in some scenarios, but this is just meant as a starting point.
Are you aware the Scala case classes get these compiler-generated methods:
toString(): String
equals(other: Any): Boolean
hashCode: Int
They also get companion objects for "new-less" constructors and pattern matching.
The generated toString() is pretty much like the one you describe.
import util._ // For Scala 2.8.x NameTransformer
import scala.tools.nsc.util._ // For Scala 2.7.x NameTransformer
/**
* Repeatedly run `f` until it returns None, and assemble results in a Stream.
*/
def unfold[A](a: A, f: A => Option[A]): Stream[A] = {
Stream.cons(a, f(a).map(unfold(_, f)).getOrElse(Stream.empty))
}
def get[T](f: java.lang.reflect.Field, a: AnyRef): T = {
f.setAccessible(true)
f.get(a).asInstanceOf[T]
}
/**
* #return None if t is null, Some(t) otherwise.
*/
def optNull[T <: AnyRef](t: T): Option[T] = if (t eq null) None else Some(t)
/**
* #return a Stream starting with the class c and continuing with its superclasses.
*/
def classAndSuperClasses(c: Class[_]): Stream[Class[_]] = unfold[Class[_]](c, (c) => optNull(c.getSuperclass))
def showReflect(a: AnyRef): String = {
val fields = classAndSuperClasses(a.getClass).flatMap(_.getDeclaredFields).filter(!_.isSynthetic)
fields.map((f) => NameTransformer.decode(f.getName) + "=" + get(f, a)).mkString(",")
}
// TEST
trait T {
val t1 = "t1"
}
class Base(val foo: String, val ?? : Int) {
}
class Derived(val d: Int) extends Base("foo", 1) with T
assert(showReflect(new Derived(1)) == "t1=t1,d=1,??=1,foo=foo")
Scala doesn't generate any public fields. They're all going to be private. The accessor methods are what will be public, reflect upon those. Given a class like:
class A {
var x = 5
}
The generated bytecode looks like:
private int x;
public void x_$eq(int);
public int x();

Resources