Esempio n. 1
0
File: Test.java Progetto: TOSPIO/GF
  public static void main(String[] args) throws IOException {
    PGF gr = null;
    try {
      gr =
          PGF.readPGF(
              "/home/krasimir/www.grammaticalframework.org/examples/phrasebook/Phrasebook.pgf");
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      return;
    } catch (PGFError e) {
      e.printStackTrace();
      return;
    }

    Type typ = gr.getFunctionType("Bulgarian");
    System.out.println(typ.getCategory());
    System.out.println(gr.getAbstractName());
    for (Map.Entry<String, Concr> entry : gr.getLanguages().entrySet()) {
      System.out.println(
          entry.getKey() + " " + entry.getValue() + " " + entry.getValue().getName());
    }

    Concr eng = gr.getLanguages().get("SimpleEng");
    try {
      for (ExprProb ep : eng.parse(gr.getStartCat(), "persons who work with Malmö")) {
        System.out.println("[" + ep.getProb() + "] " + ep.getExpr());
      }
    } catch (ParseError e) {
      System.out.println("Parsing failed at token \"" + e.getToken() + "\"");
    }
  }
Esempio n. 2
0
  public boolean isInstance(Object obj) {
    if (obj instanceof Values) {
      Values vals = (Values) obj;
      int pos = vals.startPos();
      int n = 0;
      if (base instanceof ItemPredicate) {
        ItemPredicate pred = (ItemPredicate) base;
        for (; ; ) {
          boolean matches;
          matches = pred.isInstancePos(vals, pos);
          pos = vals.nextPos(pos);
          if (pos == 0) {
            return n >= minOccurs && (maxOccurs < 0 || n <= maxOccurs);
          }
          if (!matches) return false;
          n++;
        }
      } else {

        for (; ; ) {
          pos = vals.nextPos(pos);
          if (pos == 0) {
            return n >= minOccurs && (maxOccurs < 0 || n <= maxOccurs);
          }
          Object value = vals.getPosPrevious(pos);
          if (!base.isInstance(value)) return false;
          n++;
        }
      }
    } else {
      if (minOccurs > 1 || maxOccurs == 0) return false;
      return base.isInstance(obj);
    }
  }
Esempio n. 3
0
 private static void addAllInterfaceTypes(
     Map<ClassDoc, Type> results,
     Type type,
     Type[] interfaceTypes,
     boolean raw,
     Configuration configuration) {
   for (int i = 0; i < interfaceTypes.length; i++) {
     Type interfaceType = interfaceTypes[i];
     ClassDoc interfaceClassDoc = interfaceType.asClassDoc();
     if (!(interfaceClassDoc.isPublic()
         || (configuration != null && isLinkable(interfaceClassDoc, configuration)))) {
       continue;
     }
     if (raw) interfaceType = interfaceType.asClassDoc();
     results.put(interfaceClassDoc, interfaceType);
     List<Type> superInterfaces = getAllInterfaces(interfaceType, configuration);
     for (Iterator<Type> iter = superInterfaces.iterator(); iter.hasNext(); ) {
       Type superInterface = iter.next();
       results.put(superInterface.asClassDoc(), superInterface);
     }
   }
   if (type instanceof ParameterizedType)
     findAllInterfaceTypes(results, (ParameterizedType) type, configuration);
   else if (((ClassDoc) type).typeParameters().length == 0)
     findAllInterfaceTypes(results, (ClassDoc) type, raw, configuration);
   else findAllInterfaceTypes(results, (ClassDoc) type, true, configuration);
 }
Esempio n. 4
0
 /**
  * Return a conservative estimage on the min/max number of items of a type.
  *
  * @return {@code maxCount << 12 | minCount & 0xFFF}, where a {@code maxCount} of -1 means
  *     unbounded.
  */
 public static int itemCountRange(Type type) {
   if (type instanceof SingletonType) return (1 << 12) | 1;
   if (type instanceof OccurrenceType) {
     OccurrenceType occ = (OccurrenceType) type;
     int min = occ.minOccurs();
     int max = occ.maxOccurs();
     int bnum = itemCountRange(occ.getBase());
     if ((min == 1 && max == 1) || bnum == 0) return bnum;
     if (max > 0xfffff) max = -1;
     if (max == 0) return 0;
     int bmin = bnum & 0xfff;
     int bmax = bnum >> 12;
     if (bnum != 0x1001) {
       if (min > 0xfff) min = 0xfff;
       min = min * bmin;
       if (min > 0xfff) min = 0xfff;
       if (max < 0 || bmax < 0) max = -1;
       else max = max * bmax;
       if (max > 0xfffff) max = -1;
     }
     return (max << 12) | min;
   }
   if (type instanceof PrimType) return type.isVoid() ? 0 : 0x1001;
   if (type instanceof ArrayType) return 0x1001;
   if (type instanceof ObjectType) {
     int cmp = type.compare(Compilation.typeValues);
     if (cmp == -3) return 0x1001;
   }
   return -1 << 12;
 }
Esempio n. 5
0
 public Type inferType(List<Var> vars, List<List<Type>> varTypes) {
   Type t1 = left.inferType(vars, varTypes);
   Type t2 = right.inferType(vars, varTypes);
   if (t1 == null || t2 == null || !t1.matches(t2)) {
     inferedType = null; // update cache
     return null;
   }
   inferedType = PType.T; // update cache
   return PType.T;
 }
Esempio n. 6
0
 public Type inferType(List<Var> vars, List<List<Type>> varTypes) {
   arg.addTypeSig(vars, varTypes);
   Type t = body.inferType(vars, varTypes);
   arg.removeTypeSig(vars, varTypes);
   if (t == null || !t.subType(PType.T)) {
     inferedType = null; // update cache
     return null;
   }
   inferedType = PType.I; // update cache
   return PType.I;
 }
Esempio n. 7
0
 public Type inferType(List<Var> vars, List<List<Type>> varTypes) {
   for (Exp e : exps) {
     Type t = e.inferType(vars, varTypes);
     if (t == null || !t.subType(PType.E)) {
       inferedType = null; // update cache
       return null;
     }
   }
   inferedType = FType.ET; // update cache
   return FType.ET; // could we infer subtypes here?
 }
Esempio n. 8
0
 public String _toString() {
   Type base = t;
   int totalDims = 0;
   while (base.isArray()) {
     totalDims++;
     base = base.asArray().getElementType();
   }
   StringBuffer sb = new StringBuffer("new " + base);
   for (int i = 0; i < totalDims; i++)
     sb.append("[" + (i < dims.length ? dims[i].toString() : "") + "]");
   return sb.toString();
 }
Esempio n. 9
0
  public static void toJSON(ConfigurationAdmin admin, Writer osw, String filter) throws Exception {

    Configuration[] list = admin.listConfigurations(filter);
    Encoder encoder = codec.enc().to(osw);

    Protocol p = new Protocol();
    p.version = 1;
    p.date = new Date();
    p.size = list.length;
    encoder.put(p).append('\n');

    if (list != null)
      for (Configuration c : list) {
        Dictionary<String, Object> d = c.getProperties();
        Export export = new Export();
        export.values = new HashMap<String, Object>();
        export.factoryPid = c.getFactoryPid();
        export.pid = c.getPid();

        for (Enumeration<String> e = d.keys(); e.hasMoreElements(); ) {
          String k = e.nextElement();
          Object v = d.get(k);

          if (!(v instanceof String)) {

            if (export.types == null) export.types = new HashMap<String, Type>();

            Type type = new Type();

            Class<?> clazz = v.getClass();
            if (v instanceof Collection) {
              Collection<?> coll = (Collection<?>) v;
              clazz = String.class;
              if (coll.size() > 0) type.vectorOf = shortName(coll.iterator().next().getClass());
              else type.vectorOf = shortName(String.class);
            } else if (v.getClass().isArray()) {
              type.arrayOf = shortName(clazz.getComponentType());
            } else type.scalar = shortName(v.getClass());

            export.types.put(k, type);
          }
          export.values.put(k, v);
        }

        encoder.mark().put(export);
        // encoder.put(encoder.digest());
        encoder.append('\n');
      }
    osw.flush();
  }
Esempio n. 10
0
 /** The documentation for values() and valueOf() in Enums are set by the doclet. */
 public static void setEnumDocumentation(Configuration configuration, ClassDoc classDoc) {
   MethodDoc[] methods = classDoc.methods();
   for (int j = 0; j < methods.length; j++) {
     MethodDoc currentMethod = methods[j];
     if (currentMethod.name().equals("values") && currentMethod.parameters().length == 0) {
       currentMethod.setRawCommentText(
           configuration.getText("doclet.enum_values_doc", classDoc.name()));
     } else if (currentMethod.name().equals("valueOf") && currentMethod.parameters().length == 1) {
       Type paramType = currentMethod.parameters()[0].type();
       if (paramType != null && paramType.qualifiedTypeName().equals(String.class.getName())) {
         currentMethod.setRawCommentText(configuration.getText("doclet.enum_valueof_doc"));
       }
     }
   }
 }
Esempio n. 11
0
  private File compileOne(Type type) {
    if (this.flags.contains(Flags.USECACHE)) {
      File dir = cache.get(type.getName());
      if (dir != null) {
        return dir;
      }
    }
    List<JavaFileObject> files = new ArrayList<>();
    SourceProcessor accum = (name, src) -> files.add(new SourceFile(name, src));

    for (Type dep : type.typeDependencies()) {
      dep.generateAsDependency(accum, type.methodDependencies());
    }

    type.generate(accum);

    JavacTask ct =
        (JavacTask) this.systemJavaCompiler.getTask(null, this.fm, null, null, null, files);
    File destDir = null;
    do {
      int value = counter.incrementAndGet();
      destDir = new File(root, Integer.toString(value));
    } while (destDir.exists());

    if (this.flags.contains(Flags.VERBOSE)) {
      System.out.println("Compilation unit for " + type.getName() + " : compiled into " + destDir);
      for (JavaFileObject jfo : files) {
        System.out.println(jfo.toString());
      }
    }

    try {
      destDir.mkdirs();
      this.fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(destDir));
    } catch (IOException e) {
      throw new RuntimeException(
          "IOException encountered during compilation: " + e.getMessage(), e);
    }
    Boolean result = ct.call();
    if (result == Boolean.FALSE) {
      throw new RuntimeException("Compilation failure in " + type.getName() + " unit");
    }
    if (this.flags.contains(Flags.USECACHE)) {
      File existing = cache.putIfAbsent(type.getName(), destDir);
      if (existing != null) {
        deleteDir(destDir);
        return existing;
      }
    } else {
      this.tempDirs.add(destDir);
    }
    return destDir;
  }
Esempio n. 12
0
 public TypeBitmap(int[] array) {
   this();
   for (int i = 0; i < array.length; i++) {
     Type.check(array[i]);
     types.add(new Integer(array[i]));
   }
 }
Esempio n. 13
0
  /** Creates a <tt>BloatContext</tt> that loads classes from a given CLASSPATH. */
  static BloatContext makeContext(final String classpath, final String outputDirName) {
    final ClassFileLoader loader = new ClassFileLoader();
    if (classpath != null) {
      loader.prependClassPath(classpath);
    }

    // if(TRACE) {
    // loader.setVerbose(true);
    // }

    BloatBenchmark.tr("  Creating a BloatContext for CLASSPATH: " + loader.getClassPath());

    if (outputDirName != null) {
      loader.setOutputDir(new File(outputDirName));
    }
    final BloatContext context = new CachingBloatContext(loader, BloatBenchmark.CLASSES, true);

    // Always ignore the sun packages and the opj stuff for
    // interprocedural stuff
    if (!BloatBenchmark.SUN) {
      context.addIgnorePackage("sun");
    }

    context.addIgnorePackage("java.lang.ref");
    context.addIgnorePackage("org.opj.system");

    if (BloatBenchmark.USE1_1) {
      // Toba can't deal with java.lang.Character
      context.addIgnoreClass(Type.getType("Ljava/lang/Character;"));
    }

    return (context);
  }
Esempio n. 14
0
 /** Converts the RRSIG/SIG Record to a String */
 public String rdataToString() {
   StringBuffer sb = new StringBuffer();
   if (signature != null) {
     sb.append(Type.string(covered));
     sb.append(" ");
     sb.append(alg);
     sb.append(" ");
     sb.append(labels);
     sb.append(" ");
     sb.append(origttl);
     sb.append(" ");
     if (Options.check("multiline")) sb.append("(\n\t");
     sb.append(FormattedTime.format(expire));
     sb.append(" ");
     sb.append(FormattedTime.format(timeSigned));
     sb.append(" ");
     sb.append(footprint);
     sb.append(" ");
     sb.append(signer);
     if (Options.check("multiline")) {
       sb.append("\n");
       sb.append(base64.formatString(signature, 64, "\t", true));
     } else {
       sb.append(" ");
       sb.append(base64.toString(signature));
     }
   }
   return sb.toString();
 }
Esempio n. 15
0
 public SIGBase(
     Name name,
     int type,
     int dclass,
     long ttl,
     int covered,
     int alg,
     long origttl,
     Date expire,
     Date timeSigned,
     int footprint,
     Name signer,
     byte[] signature) {
   super(name, type, dclass, ttl);
   Type.check(covered);
   checkU8("alg", alg);
   checkU8("labels", labels);
   TTL.check(origttl);
   checkU16("footprint", footprint);
   this.covered = covered;
   this.alg = alg;
   this.labels = name.labels();
   this.origttl = origttl;
   this.expire = expire;
   this.timeSigned = timeSigned;
   this.footprint = footprint;
   if (!signer.isAbsolute()) throw new RelativeNameException(signer);
   this.signer = signer;
   this.signature = signature;
 }
Esempio n. 16
0
 public JSONObject toJSON() throws JSONException {
   final JSONObject root = new JSONObject();
   root.put("type", type.name());
   root.put("name", LengthUtils.safeString(name, "auto"));
   root.put("timestamp", SDF.format(timestamp));
   return root;
 }
Esempio n. 17
0
  /**
   * Builds a new Record from its textual representation
   *
   * @param name The owner name of the record.
   * @param type The record's type.
   * @param dclass The record's class.
   * @param ttl The record's time to live.
   * @param st A tokenizer containing the textual representation of the rdata.
   * @param origin The default origin to be appended to relative domain names.
   * @return The new record
   * @throws IOException The text format was invalid.
   */
  public static Record fromString(
      Name name, int type, int dclass, long ttl, Tokenizer st, Name origin) throws IOException {
    Record rec;

    if (!name.isAbsolute()) throw new RelativeNameException(name);
    Type.check(type);
    DClass.check(dclass);
    TTL.check(ttl);

    Tokenizer.Token t = st.get();
    if (t.type == Tokenizer.IDENTIFIER && t.value.equals("\\#")) {
      int length = st.getUInt16();
      byte[] data = st.getHex();
      if (data == null) {
        data = new byte[0];
      }
      if (length != data.length)
        throw st.exception("invalid unknown RR encoding: " + "length mismatch");
      DNSInput in = new DNSInput(data);
      return newRecord(name, type, dclass, ttl, length, in);
    }
    st.unget();
    rec = getEmptyRecord(name, type, dclass, ttl, true);
    rec.rdataFromString(st, origin);
    t = st.get();
    if (t.type != Tokenizer.EOL && t.type != Tokenizer.EOF) {
      throw st.exception("unexpected tokens at end of record");
    }
    return rec;
  }
Esempio n. 18
0
  private Record parseRR(MyStringTokenizer st, boolean useLast, Record last, Name origin)
      throws IOException {
    Name name;
    int ttl;
    short type, dclass;

    if (!useLast) name = new Name(st.nextToken(), origin);
    else name = last.getName();

    String s = st.nextToken();

    try {
      ttl = TTL.parseTTL(s);
      s = st.nextToken();
    } catch (NumberFormatException e) {
      if (!useLast || last == null) ttl = defaultTTL;
      else ttl = last.getTTL();
    }

    if ((dclass = DClass.value(s)) > 0) s = st.nextToken();
    else dclass = DClass.IN;

    if ((type = Type.value(s)) < 0) throw new IOException("Parse error");

    return Record.fromString(name, type, dclass, ttl, st, origin);
  }
Esempio n. 19
0
  public void read(JmeImporter e) throws IOException {
    destroy();
    // System.out.println("Test");

    instances =
        new SafeArrayList(Type.class, e.getCapsule(this).readSavableArrayList("instances", null));
    hash = new Hashtable<String, Type>();

    if (instances != null) {
      // System.out.println("LALALA");
      for (Type t : instances.getArray()) {
        hash.put(t.getId(), t);
        //     System.out.println("LALALA"+ t.getId());
      }
    }
    myclass = (e.getCapsule(this).readSavable("myclass", null)).getClass();
  }
Esempio n. 20
0
  /**
   * Creates a new empty record, with the given parameters.
   *
   * @param name The owner name of the record.
   * @param type The record's type.
   * @param dclass The record's class.
   * @param ttl The record's time to live.
   * @return An object of a subclass of Record
   */
  public static Record newRecord(Name name, int type, int dclass, long ttl) {
    if (!name.isAbsolute()) throw new RelativeNameException(name);
    Type.check(type);
    DClass.check(dclass);
    TTL.check(ttl);

    return getEmptyRecord(name, type, dclass, ttl, false);
  }
Esempio n. 21
0
 public String toString() {
   StringBuffer sb = new StringBuffer();
   if (type == 0) sb.append("NXDOMAIN " + name);
   else sb.append("NXRRSET " + name + " " + Type.string(type));
   sb.append(" cl = ");
   sb.append(credibility);
   return sb.toString();
 }
Esempio n. 22
0
  protected void read(DataInputStream s) {
    try {
      ref = new WeakReference<DataBuffer>(this, Nd4j.bufferRefQueue());
      referencing = Collections.synchronizedSet(new HashSet<String>());
      dirty = new AtomicBoolean(false);
      allocationMode = AllocationMode.valueOf(s.readUTF());
      length = s.readInt();
      Type t = Type.valueOf(s.readUTF());
      if (t == Type.DOUBLE) {
        if (allocationMode == AllocationMode.HEAP) {
          if (this.dataType() == Type.FLOAT) { // DataBuffer type
            // double -> float
            floatData = new float[length()];
          } else if (this.dataType() == Type.DOUBLE) {
            // double -> double
            doubleData = new double[length()];
          } else {
            // double -> int
            intData = new int[length()];
          }
          for (int i = 0; i < length(); i++) {
            put(i, s.readDouble());
          }
        } else {
          wrappedBuffer = ByteBuffer.allocateDirect(length() * getElementSize());
          wrappedBuffer.order(ByteOrder.nativeOrder());
          for (int i = 0; i < length(); i++) {
            put(i, s.readDouble());
          }
        }
      } else {
        if (allocationMode == AllocationMode.HEAP) {
          if (this.dataType() == Type.FLOAT) { // DataBuffer type
            // float -> float
            floatData = new float[length()];
          } else if (this.dataType() == Type.DOUBLE) {
            // float -> double
            doubleData = new double[length()];
          } else {
            // float-> int
            intData = new int[length()];
          }
          for (int i = 0; i < length(); i++) {
            put(i, s.readFloat());
          }
        } else {
          wrappedBuffer = ByteBuffer.allocateDirect(length() * getElementSize());
          wrappedBuffer.order(ByteOrder.nativeOrder());
          for (int i = 0; i < length(); i++) {
            put(i, s.readFloat());
          }
        }
      }

    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
Esempio n. 23
0
 /**
  * Indicates whether generation is supported for this type.
  *
  * @throws InvalidTypeException The type is out of range.
  */
 public static boolean supportedType(int type) {
   Type.check(type);
   return (type == Type.PTR
       || type == Type.CNAME
       || type == Type.DNAME
       || type == Type.A
       || type == Type.AAAA
       || type == Type.NS);
 }
Esempio n. 24
0
 public String toString() {
   StringBuffer sb = new StringBuffer();
   for (Iterator it = types.iterator(); it.hasNext(); ) {
     int t = ((Integer) it.next()).intValue();
     sb.append(Type.string(t));
     if (it.hasNext()) sb.append(' ');
   }
   return sb.toString();
 }
Esempio n. 25
0
 @Override
 public int hashCode() {
   final int prime = 31;
   int result = 1;
   result = prime * result + ((name == null) ? 0 : name.hashCode());
   result = prime * result + ((timestamp == null) ? 0 : timestamp.hashCode());
   result = prime * result + ((type == null) ? 0 : type.hashCode());
   return result;
 }
Esempio n. 26
0
 public Object coerceFromObject(Object obj) {
   if (obj instanceof Values) {
   } else {
     // Assumes that base is an item type.  FIXME.
     if (minOccurs <= 1 && maxOccurs != 0) return base.coerceFromObject(obj);
   }
   // FIXME
   if (!isInstance(obj)) throw new ClassCastException();
   return obj;
 }
Esempio n. 27
0
 Record(Name name, int type, int dclass, long ttl) {
   if (!name.isAbsolute()) throw new RelativeNameException(name);
   Type.check(type);
   DClass.check(dclass);
   TTL.check(ttl);
   this.name = name;
   this.type = type;
   this.dclass = dclass;
   this.ttl = ttl;
 }
Esempio n. 28
0
  /**
   * Compiles a hierarchy, starting at 'type' and return a mapping of the name to the location where
   * the classfile for that type resides.
   */
  private Map<String, File> compileHierarchy(Type type) {
    HashMap<String, File> outputDirs = new HashMap<>();

    File outDir = compileOne(type);
    outputDirs.put(type.getName(), outDir);

    Class superClass = type.getSuperclass();
    if (superClass != null) {
      for (Map.Entry<String, File> each : compileHierarchy(superClass).entrySet()) {
        outputDirs.put(each.getKey(), each.getValue());
      }
    }
    for (Extends ext : type.getSupertypes()) {
      Type iface = ext.getType();
      for (Map.Entry<String, File> each : compileHierarchy(iface).entrySet()) {
        outputDirs.put(each.getKey(), each.getValue());
      }
    }

    return outputDirs;
  }
Esempio n. 29
0
 public int compare(Type other) {
   if (other instanceof OccurrenceType) {
     OccurrenceType occOther = (OccurrenceType) other;
     if (minOccurs == occOther.minOccurs && maxOccurs == occOther.maxOccurs)
       return base.compare(occOther.getBase());
   }
   /*
   Type primeThis = itemPrimeType(getBase());
   Type primeOther = itemPrimeType(other);
   FIXME: Compare primThis with primOther AND the occurrence numbers.
   */
   return -2;
 }
Esempio n. 30
0
 public TypeBitmap(Tokenizer st) throws IOException {
   this();
   while (true) {
     Tokenizer.Token t = st.get();
     if (!t.isString()) break;
     int typecode = Type.value(t.value);
     if (typecode < 0) {
       throw st.exception("Invalid type: " + t.value);
     }
     types.add(Mnemonic.toInteger(typecode));
   }
   st.unget();
 }