package com.ninty.runtime.heap.constantpool;

import com.ninty.classfile.constantpool.ConstantInfo;
import com.ninty.runtime.heap.NiClass;
import com.ninty.runtime.heap.NiField;

/**
 * Created by ninty on 2017/7/24.
 */
public class FieldRef extends MemberRef {
    private NiField field;

    public FieldRef(ConstantInfo.CPMemeber cp) {
        super(cp);
    }

    @Override
    public void resolve() {
        if (this.field == null) {
            resolveClass();
            NiField field = lookUpFields(clz, name, desc);
            if (field == null) {
                throw new RuntimeException("NoSuchField clz:" + clz.getClassName() + ", name:" + name + ", desc:" + desc);
            }
            if (!field.canAccess(cp.clz)) {
                throw new RuntimeException(cp.clz.getClassName() + " can not access to " + field);
            }
            this.field = field;
        }
    }

    private NiField lookUpFields(NiClass clz, String name, String desc) {
        for (NiField field : clz.getFields()) {
            if (field.getName().equals(name) && field.getDesc().equals(desc)) {
                return field;
            }
        }

        for (NiClass c : clz.getInterfaces()) {
            return lookUpFields(c, name, desc);
        }

        if (clz.getSuperClass() != null) {
            return lookUpFields(clz.getSuperClass(), name, desc);
        }

        return null;
    }

    public NiField getField() {
        return field;
    }
}

@@ -585,102 +585,40 @@
 new 
-RuntimeException(%22NoSuchField clz:%22 + clz.getClassName() + %22, name:%22 + name + %22, desc:%22 + desc
+NoSuchFieldError(this.toString()
 );%0A 
@@ -704,54 +704,41 @@
 new 
-RuntimeException(cp.clz.getClassName()
+IllegalAccessError(cp.clz
  + %22 can
  not
@@ -733,17 +733,16 @@
  + %22 can
- 
 not acce
@@ -748,11 +748,8 @@
 ess 
-to 
 %22 + 
@@ -1128,38 +1128,47 @@
 ) %7B%0A            
-return
+NiField field =
  lookUpFields(c,
@@ -1173,32 +1173,107 @@
 c, name, desc);%0A
+            if(field != null)%7B%0A                return field;%0A            %7D%0A
         %7D%0A%0A     
@@ -1322,22 +1322,31 @@
         
-return
+NiField field =
  lookUpF
@@ -1377,32 +1377,107 @@
 ), name, desc);%0A
+            if(field != null)%7B%0A                return field;%0A            %7D%0A
         %7D%0A%0A     
@@ -1558,11 +1558,250 @@
 d;%0A    %7D
+%0A%0A    @Override%0A    public String toString() %7B%0A        return %22FieldRef%7B%22 +%0A                %22className='%22 + className + '%5C'' +%0A                %22, name='%22 + name + '%5C'' +%0A                %22, desc='%22 + desc + '%5C'' +%0A                '%7D';%0A    %7D
 %0A%7D%0A

field may be null