alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Scala example source code file (Table.java)

This example Scala source code file (Table.java) is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Java - Scala tags/keywords

assemblyref, flags, flags, id, id, io, method, name, name, nio, parent, signature, string, table, table, tableset

The Scala Table.java source code

/*
 * System.Reflection-like API for acces to .NET Assemblies
 */


package ch.epfl.lamp.compiler.msil.util;

import ch.epfl.lamp.compiler.msil.PEFile;
import ch.epfl.lamp.compiler.msil.PEFile.Sig;

import java.io.PrintStream;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;

/**
 * Represents a table in a .NET assembly
 *
 * @author Nikolay Mihaylov
 * @version 1.0
 */
public abstract class Table {

    //##########################################################################

    public static final int MAX_NUMBER = 64;

    public static final long VALID_TABLES_MASK = 0x03ff3fb7ff57L;

    //##########################################################################
    // fields and methods for handling predefined sets of tables

    public static final int TABLE_SET_LENGTH = 13;

    public static final int _TypeDefOrRef = 0;
    public static final int _HasConstant = 1;
    public static final int _HasCustomAttribute = 2;
    public static final int _HasFieldMarshal = 3;
    public static final int _HasDeclSecurity = 4;
    public static final int _MemberRefParent = 5;
    public static final int _HasSemantics = 6;
    public static final int _MethodDefOrRef = 7;
    public static final int _MemberForwarded = 8;
    public static final int _Implementation = 9;
    public static final int _CustomAttributeType = 10;
    public static final int _ResolutionScope = 11;
    public static final int _TypeOrMethodDef = 12;


    public static final int[][] TableSet = new int[TABLE_SET_LENGTH][];

    static {
	TableSet[_TypeDefOrRef] =
	    new int[] {TypeDef.ID, TypeRef.ID, TypeSpec.ID};
	TableSet[_HasConstant] =
	    new int[] {FieldDef.ID, ParamDef.ID, PropertyDef.ID};
	TableSet[_HasCustomAttribute] =
	    new int[] {MethodDef.ID, FieldDef.ID, TypeRef.ID, TypeDef.ID,
		       ParamDef.ID, InterfaceImpl.ID, MemberRef.ID, ModuleDef.ID,
		       -1, PropertyDef.ID, EventDef.ID, -1, ModuleRef.ID,
		       TypeSpec.ID, AssemblyDef.ID, AssemblyRef.ID,
		       FileDef.ID, ExportedType.ID, ManifestResource.ID};
	TableSet[_HasFieldMarshal] =
	    new int[] {FieldDef.ID, ParamDef.ID};
	TableSet[_HasDeclSecurity] =
	    new int[] {TypeDef.ID, MethodDef.ID, AssemblyDef.ID};
	TableSet[_MemberRefParent] =
	    new int[] {-1, TypeRef.ID, ModuleRef.ID, MethodDef.ID, TypeSpec.ID};
	TableSet[_HasSemantics] =
	    new int[] {EventDef.ID, PropertyDef.ID};
	TableSet[_MethodDefOrRef] =
	    new int[] {MethodDef.ID, MemberRef.ID};
	TableSet[_MemberForwarded] =
	    new int[] {FieldDef.ID, MethodDef.ID};
	TableSet[_Implementation] =
	    new int[] {FileDef.ID, AssemblyRef.ID, ExportedType.ID};
	TableSet[_CustomAttributeType] =
	    new int[] {-1, -1, MethodDef.ID, MemberRef.ID, -1};
	TableSet[_ResolutionScope] =
	    new int[] {ModuleDef.ID, ModuleRef.ID, AssemblyRef.ID, TypeRef.ID};
        TableSet[_TypeOrMethodDef] =
                new int[]{TypeDef.ID, MethodDef.ID};
    }

    public static final int[] NoBits =
            new int[]{2, 2, 5, 1, 2, 3, 1, 1, 1, 2, 3, 2, 1};

    public static int getMask(int tableSetId) {
	return (1 << NoBits[tableSetId]) - 1;
    }

    public static int getTableId(int tableSet, int index) {
	return TableSet[tableSet][index & getMask(tableSet)];
    }

    public static int getTableIndex(int tableSet, int index) {
	return index >> NoBits[tableSet];
    }

    public static int encodeIndex(int index, int tableSetId, int tableId) {
	int[] tableSet = TableSet[tableSetId];
	for (int i = 0; i < tableSet.length; i++) {
	    if (tableSet[i] == tableId)
		return (index << NoBits[tableSetId]) | i;
	}
	throw new RuntimeException("Cannot find table #" + tableId +
				   " in table set #" + tableSetId);
    }

    //##########################################################################

    private static final String [] tableName = {
	"Module",              "TypeRef",          "TypeDef", "   FieldTrans",
	"Field",               "MethodTrans",      "Method",      "",
	"Param",               "InterfaceImpl",    "MemberRef",   "Constant",
	"CustomAttribute",     "FieldMarshal",     "DeclSecurity","ClassLayout",
	"FieldLayout",         "StandAloneSig",    "EventMap",    "",
	"Event",               "PropertyMap",      "",            "Property",
	"MethodSemantics",     "MethodImpl",       "ModuleRef",   "TypeSpec",
	"ImplMap",             "FieldRVA",         "",            "",
	"Assembly",            "AssemblyProcessor","AssemblyOS",  "AssemblyRef",
	"AssemblyRefProcessor","AssemblyRefOS",    "File",        "ExportedType",
            "ManifestResource", "NestedClass", "GenericParam", "MethodSpec",
            "GenericParamConstraint", "", "", "",
	"",                    "",                 "",            "",
	"",                    "",                 "",            "",//0x30-0x37
	"",                    "",                 "",            "",
	"",                    "",                 "",            "" //0x37-0x3f
    };

    /** Creates a table with the given id and number of rows.
     */
    public static Table newTable(PEFile file, int id, int rows) {
	Table table = null;
	switch(id) {
	case ModuleDef.ID:         table = new ModuleDef(file, rows); break;
 	case TypeRef.ID:           table = new TypeRef(file, rows); break;
 	case TypeDef.ID:           table = new TypeDef(file, rows); break;
	case FieldTrans.ID:        table = new FieldTrans(file, rows); break;
	case FieldDef.ID:          table = new FieldDef(file, rows); break;
	case MethodTrans.ID:       table = new MethodTrans(file, rows); break;
	case MethodDef.ID:         table = new MethodDef(file, rows); break;
	case ParamDef.ID:          table = new ParamDef(file, rows); break;
	case InterfaceImpl.ID:     table = new InterfaceImpl(file, rows); break;
	case MemberRef.ID:         table = new MemberRef(file, rows); break;
	case Constant.ID:          table = new Constant(file, rows); break;
	case CustomAttribute.ID:   table = new CustomAttribute(file, rows); break;
	case FieldMarshal.ID:      table = new FieldMarshal(file, rows); break;
	case DeclSecurity.ID:      table = new DeclSecurity(file, rows); break;
	case ClassLayout.ID:       table = new ClassLayout(file, rows); break;
	case FieldLayout.ID:       table = new FieldLayout(file, rows); break;
	case StandAloneSig.ID:     table = new StandAloneSig(file, rows); break;
	case EventMap.ID:          table = new EventMap(file, rows); break;
	case EventDef.ID:          table = new EventDef(file, rows); break;
	case PropertyMap.ID:       table = new PropertyMap(file, rows); break;
	case PropertyDef.ID:       table = new PropertyDef(file, rows); break;
	case MethodSemantics.ID:   table = new MethodSemantics(file, rows); break;
	case MethodImpl.ID:        table = new MethodImpl(file, rows); break;
	case ModuleRef.ID:         table = new ModuleRef(file, rows); break;
	case TypeSpec.ID:          table = new TypeSpec(file, rows); break;
	case ImplMap.ID:           table = new ImplMap(file, rows); break;
	case FieldRVA.ID:          table = new FieldRVA(file, rows); break;
	case AssemblyDef.ID:       table = new AssemblyDef(file, rows); break;
	case AssemblyProcessor.ID: table = new AssemblyProcessor(file, rows); break;
	case AssemblyOS.ID:        table = new AssemblyOS(file, rows); break;
	case AssemblyRef.ID:       table = new AssemblyRef(file, rows); break;
	case AssemblyRefProcessor.ID:
	    table = new AssemblyRefProcessor(file, rows); break;
	case AssemblyRefOS.ID:     table = new AssemblyRefOS(file, rows); break;
	case FileDef.ID:           table = new FileDef(file, rows); break;
	case ExportedType.ID:      table = new ExportedType(file, rows); break;
	case ManifestResource.ID:  table = new ManifestResource(file, rows); break;
	case NestedClass.ID:       table = new NestedClass(file, rows); break;
    case GenericParam.ID:
        table = new GenericParam(file, rows);
        break;
    case MethodSpec.ID:
        table = new MethodSpec(file, rows);
        break;
    case GenericParamConstraint.ID:
        table = new GenericParamConstraint(file, rows);
        break;
	default:
	    table = new Empty(id);
	}
// 	System.out.println("created table " + table.getName() + " with "
// 			   + table.rows + " rows");
	return table;
    }


    //##########################################################################
    // public fields

    /** Number of rows in the table. */
    public final int rows;

    /** Table ID as specified in Partition II. */
    public final int id;

    /** The file to which the table belongs. */
    protected final PEFile file;

    /** Memory mapped buffer wrapping the table. */
    protected ByteBuffer buffer;

    /**
     * specified wheter a new memory-mapped byte buffer should be created
     * for this table.
     */
    protected boolean newMapping = false;

    /** Tells wheter the table is indexed by 2-byte (short) integer
     *  or by 4-byte integer. */
    public final boolean isShort;

    private int rowSize = -1;

    // the starting position of the table relative to the beginning of the file
    private long start = -1;

    // the number of the row who can be accessed via the fields of the table
    private int currentRow = 0;

    //##########################################################################

    protected Table(PEFile file, int id, int rows) {
	this.file = file;
	this.id = id;
	this.rows = rows;//file.readInt();
	this.isShort = rows < (1 << 16);
// 	assert ((1L << id) & VALID_TABLES_MASK) != 0
// 	    : "Table does not have a vaid ID: " + byte2hex(id);
    }

    /**
     * Additional table initialization.
     * @return the starting position of the next table in the stream.
     */
    public final long init(long start) {
	if (rows < 1)
	    return start;
	if (this.start == -1)
	    this.start = start;
	else throw new RuntimeException
		 ("Cannot re-initialize table \'" + getTableName() + "\'");
	rowSize = getRowSize();
	int size = rows * rowSize();
	buffer = this.newMapping ? file.mapBuffer(start, size)
	    : file.getBuffer(start, size);
	return start + size;
    }


    public final String getTableName() {
	return 0 <= id && id < MAX_NUMBER ? tableName[id] : "*/ GenericParamIdxesForMethodDefIdx =
                new java.util.HashMap();
        private java.util.Map /*<Integer, java.util.Set*/ GenericParamIdxesForTypeDefIdx  =
                new java.util.HashMap();

        private void addToMap(int key, int value, java.util.Map IdxesForIdx) {
            java.util.Set /*<Integer>*/ bucket = (java.util.Set)IdxesForIdx.get(Integer.valueOf(key));
            if(bucket == null) {
                bucket = new java.util.HashSet();
                IdxesForIdx.put(Integer.valueOf(key), bucket);
            }
            bucket.add(Integer.valueOf(value));
        }

        /** Indexes of rows in the GenericParam table representing type parameters defined by the type given by
         * its row index TypeDefIdx (in the TypeDef table).
         * No need to position the current record before invoking this method.  */
        public int[] getTVarIdxes(int TypeDefIdx) {
            if(!mapsPopulated) {
                initMaps();
            }
            java.util.Set bucket = (java.util.Set)GenericParamIdxesForTypeDefIdx.get(Integer.valueOf(TypeDefIdx));
            if(bucket == null) {
                bucket = java.util.Collections.EMPTY_SET;
            }
            int[] res = new int[bucket.size()];
            java.util.Iterator /*<Integer>*/ it = bucket.iterator();
            for(int i = 0; i < bucket.size(); i++) {
                res[i] = ((Integer)it.next()).intValue();
            }
            return res;
        }

        /** Indexes of rows in the GenericParam table representing type parameters defined by the method given by
         * its row index MethodDefIdx (in the MethodDef table)
         * No need to position the current record before invoking this method.  */
        public int[] getMVarIdxes(int MethodDefIdx) {
            if(!mapsPopulated) {
                initMaps();
            }
            java.util.Set bucket = (java.util.Set)GenericParamIdxesForMethodDefIdx.get(Integer.valueOf(MethodDefIdx));
            if(bucket == null) {
                bucket = java.util.Collections.EMPTY_SET;
            }
            int[] res = new int[bucket.size()];
            java.util.Iterator /*<Integer>*/ it = bucket.iterator();
            for(int i = 0; i < bucket.size(); i++) {
                res[i] = ((Integer)it.next()).intValue();
            }
            return res;
        }

        private boolean mapsPopulated = false;

        private void initMaps() {
            mapsPopulated = true;
            for (int currentParamRow = 1; currentParamRow <= rows; currentParamRow++) {
                int currentOwner = file.GenericParam(currentParamRow).Owner;
                int targetTableId = Table.getTableId(Table._TypeOrMethodDef, currentOwner);
                int targetRow = currentOwner >> Table.NoBits[Table._TypeOrMethodDef];
                if(targetTableId == TypeDef.ID){
                    addToMap(targetRow, currentParamRow, GenericParamIdxesForTypeDefIdx);
                } else if(targetTableId == MethodDef.ID) {
                    addToMap(targetRow, currentParamRow, GenericParamIdxesForMethodDefIdx);
                } else {
                    throw new RuntimeException();
                }
            }
        }

        public GenericParam(PEFile file, int rows) {
            super(file, ID, rows);
            this.newMapping = true;
        }

        protected void populateFields() {
            Number = readShort();
            Flags = readShort();
            Owner = readTableSetIndex(_TypeOrMethodDef);
            Name = readStringIndex();
        }

        /** This method assumes populateFields() has been just called to set Flags for the current record */
        public boolean isInvariant() {
            /* 23.1.7 Flags for Generic Parameters [GenericParamAttributes tributes] */
            return (Flags & 0x0003) == 0;
        }

        /** This method assumes populateFields() has been just called to set Flags for the current record */
        public boolean isCovariant() {
            /* 23.1.7 Flags for Generic Parameters [GenericParamAttributes tributes] */
            return (Flags & 0x0003) == 1;
        }

        /** This method assumes populateFields() has been just called to set Flags for the current record */
        public boolean isContravariant() {
            /* 23.1.7 Flags for Generic Parameters [GenericParamAttributes tributes] */
            return (Flags & 0x0003) == 2;
        }

        /** This method assumes populateFields() has been just called to set Flags for the current record */
        public boolean isReferenceType() {
            /* 23.1.7 Flags for Generic Parameters [GenericParamAttributes tributes] */
            return (Flags & 0x001C) == 4;
        }

        /** This method assumes populateFields() has been just called to set Flags for the current record */
        public boolean isValueType() {
            /* 23.1.7 Flags for Generic Parameters [GenericParamAttributes tributes] */
            return (Flags & 0x001C) == 8;
        }

        /** This method assumes populateFields() has been just called to set Flags for the current record */
        public boolean hasDefaultConstructor() {
            /* 23.1.7 Flags for Generic Parameters [GenericParamAttributes tributes] */
            return (Flags & 0x001C) == 0x0010;
        }

        protected int getRowSize() {
            return 2 + 2 + file.getTableSetIndexSize(_TypeOrMethodDef) + file.getStringIndexSize();
            /* Columns:
                 Number (2 bytes),
                 Flags (2 bytes),
                 Owner (coded token of type TypeOrMethodDef),
                 Name (offset in the #Strings stream).
            */
        }

        public String getName() {
            return file.getString(Name);
        }

    } // class GenericParam


    //##########################################################################
    // table GenericParamConstraint; ID=0x2c; p139, 22.20

    public static final class GenericParamConstraint extends Table {
        public static final int ID = 0x2c;

        public int Owner; // an index into the GenericParam table
        public int Constraint; // a TypeDefOrRef (Sec 24.2.6) coded index

        public GenericParamConstraint(PEFile file, int rows) {
            super(file, ID, rows);
            this.newMapping = true;
        }

        protected void populateFields() {
            Owner = readTableIndex(GenericParam.ID);
            Constraint = readTableSetIndex(_TypeDefOrRef);
        }

        protected int getRowSize() {
            return file.getTableIndexSize(GenericParam.ID) + file.getTableSetIndexSize(_TypeDefOrRef);
            /* Columns:
                 Owner (RID in the GenericParam table),
                 Constraint (coded token of type TypeDefOrRef).
            */
        }

        private boolean mapPopulated = false;

        /** Indexes of rows (in the TypeDef, TypeRef, or TypeSpec tables) denoting the base class (if any)
         * and interfaces (if any) that the generic parameter (of TVar or MVar kind) should support,  where
         * that generic parameter is represented by its index into the GenericParam table. */
        public int[] getTypeDefOrRefIdxes(int genParamIdx) {
            if(!mapPopulated) {
                initMap();
            }
            java.util.Set bucket = (java.util.Set)TypeDefOrRefIdxesForGenParamIdx.get(Integer.valueOf(genParamIdx));
            if(bucket == null) {
                bucket = java.util.Collections.EMPTY_SET;
            }
            int[] res = new int[bucket.size()];
            java.util.Iterator /*<Integer>*/ it = bucket.iterator();
            for(int i = 0; i < bucket.size(); i++) {
                res[i] = ((Integer)it.next()).intValue();
            }
            return res;
        }


        private void initMap() {
            mapPopulated = true;
            for (int currentConstraintRow = 1; currentConstraintRow <= rows; currentConstraintRow++) {
                int targetGenericParam = file.GenericParamConstraint(currentConstraintRow).Owner;
                int value = file.GenericParamConstraint.Constraint;
                addToMap(targetGenericParam, value);
            }
        }

        private java.util.Map /*<Integer, java.util.Set*/ TypeDefOrRefIdxesForGenParamIdx  =
                new java.util.HashMap();

        private void addToMap(int key, int value) {
            java.util.Set /*<Integer>*/ bucket = (java.util.Set)TypeDefOrRefIdxesForGenParamIdx.get(Integer.valueOf(key));
            if(bucket == null) {
                bucket = new java.util.HashSet();
                TypeDefOrRefIdxesForGenParamIdx.put(Integer.valueOf(key), bucket);
            }
            bucket.add(Integer.valueOf(value));
        }

    } // class GenericParamConstraint

    //##########################################################################
    // table MethodSpec; ID=0x2b; p149, in Sec. 22.29 of Partition II

    public static final class MethodSpec extends Table {
        public static final int ID = 0x2b;

        /* an index into the MethodDef or MemberRef table, specifying which generic method this row is an instantiation of.
           A MethodDefOrRef (Sec. 24.2.6) coded index  */
        public int Method;

        /* an index into the Blob heap (Sec. 23.2.15), holding the signature of this instantiation */
        public int Instantiation;

        public MethodSpec(PEFile file, int rows) {
            super(file, ID, rows);
            this.newMapping = true;
        }

        protected void populateFields() {
            Method = readTableSetIndex(_MethodDefOrRef);
            Instantiation = readBlobIndex();
        }

        protected int getRowSize() {
            return file.getTableSetIndexSize(_MethodDefOrRef) + file.getBlobIndexSize();
        }


    } // class MethodSpec
    //##########################################################################

}  // class Table

Other Scala examples (source code examples)

Here is a short list of links related to this Scala Table.java source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.