コード例 #1
0
ファイル: TupleResult.java プロジェクト: BertLisser/rascal
  @Override
  public Result<IValue> fieldSelect(Field[] selectedFields) {
    int nFields = selectedFields.length;
    int fieldIndices[] = new int[nFields];
    Type baseType = this.getType();

    for (int i = 0; i < nFields; i++) {
      Field f = selectedFields[i];
      if (f.isIndex()) {
        fieldIndices[i] =
            ((IInteger) f.getFieldIndex().interpret(this.ctx.getEvaluator()).getValue()).intValue();
      } else {
        String fieldName = org.rascalmpl.interpreter.utils.Names.name(f.getFieldName());
        try {
          fieldIndices[i] = baseType.getFieldIndex(fieldName);
        } catch (UndeclaredFieldException e) {
          throw new UndeclaredFieldError(fieldName, baseType, ctx.getCurrentAST());
        }
      }

      if (fieldIndices[i] < 0 || fieldIndices[i] > baseType.getArity()) {
        throw org.rascalmpl.interpreter.utils.RuntimeExceptionFactory.indexOutOfBounds(
            ValueFactoryFactory.getValueFactory().integer(fieldIndices[i]),
            ctx.getCurrentAST(),
            ctx.getStackTrace());
      }
    }

    return this.fieldSelect(fieldIndices);
  }
コード例 #2
0
ファイル: IO.java プロジェクト: reflectionalist/rascal
 private void checkRecord(Type eltType, Record record, IEvaluatorContext ctx) {
   // TODO: not all inconsistencies are detected yet
   // probably because absent values get type void
   // but are nevertheless initialized eventually
   // to 0, false, or "".
   if (record.getType().isSubtypeOf(eltType)) {
     return;
   }
   if (eltType.isTuple()) {
     int expectedArity = eltType.getArity();
     int actualArity = record.getType().getArity();
     if (expectedArity == actualArity) {
       return;
     }
     throw RuntimeExceptionFactory.illegalTypeArgument(
         "Arities of actual type and requested type are different ("
             + actualArity
             + " vs "
             + expectedArity
             + ")",
         ctx.getCurrentAST(),
         ctx.getStackTrace());
   }
   throw RuntimeExceptionFactory.illegalTypeArgument(
       "Invalid tuple " + record + " for requested field " + eltType,
       ctx.getCurrentAST(),
       ctx.getStackTrace());
 }
コード例 #3
0
ファイル: Set.java プロジェクト: CognitiveScale/pdb.values
  public ISet intersect(ISet other) {
    ShareableValuesHashSet commonData = new ShareableValuesHashSet();
    Iterator<IValue> setIterator;

    ISet theOtherSet;

    if (other.size() <= size()) {
      setIterator = other.iterator();
      theOtherSet = this;
    } else {
      setIterator = iterator();
      theOtherSet = other;
    }

    Type newElementType = TypeFactory.getInstance().voidType();
    while (setIterator.hasNext()) {
      IValue value = setIterator.next();
      if (theOtherSet.contains(value)) {
        newElementType = newElementType.lub(value.getType());
        commonData.add(value);
      }
    }

    return new SetWriter(newElementType, commonData).done();
  }
コード例 #4
0
 @Override
 protected <U extends IValue> Result<U> joinRelation(RelationResult that) {
   // Note the reverse of arguments, we need "that join this"
   int arity1 = that.getValue().arity();
   Type eltType = getType().getElementType();
   Type tupleType = that.getType().getElementType();
   Type fieldTypes[] = new Type[arity1 + 1];
   for (int i = 0; i < arity1; i++) {
     fieldTypes[i] = tupleType.getFieldType(i);
   }
   fieldTypes[arity1] = eltType;
   Type resultTupleType = getTypeFactory().tupleType(fieldTypes);
   ISetWriter writer = getValueFactory().setWriter(resultTupleType);
   IValue fieldValues[] = new IValue[arity1 + 1];
   for (IValue relValue : that.getValue()) {
     for (IValue setValue : this.getValue()) {
       for (int i = 0; i < arity1; i++) {
         fieldValues[i] = ((ITuple) relValue).get(i);
       }
       fieldValues[arity1] = setValue;
       writer.insert(getValueFactory().tuple(fieldValues));
     }
   }
   Type resultType = getTypeFactory().relTypeFromTuple(resultTupleType);
   return makeResult(resultType, writer.done(), ctx);
 }
コード例 #5
0
ファイル: Profiler.java プロジェクト: BertLisser/rascal
 public IList getProfileData() {
   TypeFactory TF = TypeFactory.getInstance();
   Type elemType = TF.tupleType(TF.sourceLocationType(), TF.integerType());
   Type listType = TF.listType(elemType);
   IValueFactory VF = ValueFactoryFactory.getValueFactory();
   IListWriter w = listType.writer(VF);
   for (Map.Entry<AbstractAST, Count> e : sortData()) {
     w.insert(VF.tuple(e.getKey().getLocation(), VF.integer(e.getValue().getTicks())));
   }
   return w.done();
 }
コード例 #6
0
ファイル: Set.java プロジェクト: CognitiveScale/pdb.values
  public ISet subtract(ISet other) {
    ShareableValuesHashSet newData = new ShareableValuesHashSet(data);

    Iterator<IValue> setIterator = other.iterator();
    while (setIterator.hasNext()) {
      newData.remove(setIterator.next());
    }
    Type newElementType = TypeFactory.getInstance().voidType();
    for (IValue el : newData) newElementType = newElementType.lub(el.getType());
    return new SetWriter(newElementType, newData).done();
  }
コード例 #7
0
ファイル: Set.java プロジェクト: CognitiveScale/pdb.values
  public ISet delete(IValue value) {
    if (contains(value)) {
      ShareableValuesHashSet newData = new ShareableValuesHashSet(data);
      newData.remove(value);

      Type newElementType = TypeFactory.getInstance().voidType();
      for (IValue el : newData) {
        newElementType = newElementType.lub(el.getType());
      }
      return new SetWriter(newElementType, newData).done();
    } else {
      return this;
    }
  }
コード例 #8
0
ファイル: IO.java プロジェクト: reflectionalist/rascal
 /**
  * @param fieldTypes as inferred for the whole relation.
  * @return The tuple value for this record
  */
 ITuple getTuple(Type fieldTypes) {
   IValue fieldValues[] = new IValue[rfields.size()];
   for (int i = 0; i < rfields.size(); i++) {
     if (rfields.get(i) == null) {
       if (fieldTypes.getFieldType(i).isBool()) rfields.set(i, values.bool(false));
       else if (fieldTypes.getFieldType(i).isInteger()) rfields.set(i, values.integer(0));
       else if (fieldTypes.getFieldType(i).isReal()) rfields.set(i, values.real(0));
       else rfields.set(i, values.string(""));
     }
     if (fieldTypes.getFieldType(i).isString() && !rfields.get(i).getType().isString())
       rfields.set(i, values.string(rfields.get(i).toString()));
     fieldValues[i] = rfields.get(i);
   }
   return values.tuple(fieldValues);
 }
コード例 #9
0
 /* (non-Javadoc)
  * @see org.rascalmpl.tasks.ITaskRegistry#getProducer(Type, IValue)
  */
 @Override
 public ITask<Type, IValue, IValue> getProducer(Type key, IValue name) {
   lock.lock();
   try {
     Map<Type, ITask<Type, IValue, IValue>> producerMap = keyedProducers.get(key);
     if (producerMap != null) {
       Type nameType = name.getType();
       if (producerMap.containsKey(nameType)) return producerMap.get(nameType);
       for (Map.Entry<Type, ITask<Type, IValue, IValue>> t : producerMap.entrySet()) {
         if (nameType.isSubtypeOf(t.getKey())) return t.getValue();
       }
     }
     throw new ImplementationError("No suitable producer found for " + key + "(" + name + ")");
   } finally {
     lock.unlock();
   }
 }
コード例 #10
0
ファイル: IO.java プロジェクト: reflectionalist/rascal
  public IValue buildCollection(Type type, List<Record> records, IEvaluatorContext ctx) {
    IWriter writer;
    while (type.isAliased()) {
      type = type.getAliased();
    }

    if (type.isList()) {
      writer = values.listWriter(type.getElementType());
    } else if (type.isRelation()) {
      writer = values.relationWriter(type.getElementType());
    } else {
      throw RuntimeExceptionFactory.illegalTypeArgument(
          "Invalid result type for CSV reading: " + type, ctx.getCurrentAST(), ctx.getStackTrace());
    }

    // reverse traversal so that the order in case of ListWriter is correct
    // (IWriter only supports inserts at the front).
    Type eltType = type.getElementType();
    for (int i = records.size() - 1; i >= 0; i--) {
      Record record = records.get(i);
      checkRecord(eltType, record, ctx);
      writer.insert(record.getTuple(eltType));
    }
    return writer.done();
  }
コード例 #11
0
ファイル: TupleResult.java プロジェクト: BertLisser/rascal
  @Override
  public <U extends IValue, V extends IValue> Result<U> fieldUpdate(
      String name, Result<V> repl, TypeStore store) {
    if (!getType().hasFieldNames()) {
      throw new UndeclaredFieldError(name, getType(), ctx.getCurrentAST());
    }

    try {
      int index = getType().getFieldIndex(name);
      Type type = getType().getFieldType(index);
      if (!type.isSubtypeOf(repl.getType())) {
        throw new UnexpectedTypeError(type, repl.getType(), ctx.getCurrentAST());
      }
      return makeResult(getType(), getValue().set(index, repl.getValue()), ctx);
    } catch (UndeclaredFieldException e) {
      throw new UndeclaredFieldError(name, getType(), ctx.getCurrentAST());
    }
  }
コード例 #12
0
  public void testIntersectISet() {
    ISet empty1 = vf.set(tf.tupleType(tf.integerType()));
    ISet empty2 = vf.set(tf.tupleType(tf.realType()));

    try {
      final ISet intersection = empty1.intersect(empty2);
      if (!intersection.isEmpty()) {
        fail("empty intersection failed");
      }

      Type type = intersection.getType();
      if (!type.getFieldType(0).isSubtypeOf(tf.numberType())) {
        fail("intersection should produce lub types");
      }
    } catch (FactTypeUseException e) {
      fail("intersecting types which have a lub should be possible");
    }

    try {
      if (!integerRelation.intersect(doubleRelation).isEmpty()) {
        fail("non-intersecting relations should produce empty intersections");
      }

      ISet oneTwoThree = vf.set(integerTuples[0], integerTuples[1], integerTuples[2]);
      ISet threeFourFive = vf.set(integerTuples[2], integerTuples[3], integerTuples[4]);
      ISet result = vf.set(integerTuples[2]);

      if (!oneTwoThree.intersect(threeFourFive).isEqual(result)) {
        fail("intersection failed");
      }
      if (!threeFourFive.intersect(oneTwoThree).isEqual(result)) {
        fail("intersection should be commutative");
      }

      if (!oneTwoThree
          .intersect(vf.set(tf.tupleType(tf.integerType(), tf.integerType())))
          .isEmpty()) {
        fail("intersection with empty set should produce empty");
      }

    } catch (FactTypeUseException e) {
      fail("the above should all be type safe");
    }
  }
コード例 #13
0
 /* (non-Javadoc)
  * @see org.rascalmpl.tasks.ITaskRegistry#registerProducer(org.rascalmpl.tasks.ITask)
  */
 @Override
 public void registerProducer(ITask<Type, IValue, IValue> producer) {
   lock.lock();
   try {
     for (Type key : producer.getKeys()) {
       if (key.isTuple()) {
         Type key1 = key.getFieldType(0);
         Type key2 = key.getFieldType(1);
         Map<Type, ITask<Type, IValue, IValue>> map = keyedProducers.get(key1);
         if (map == null) map = new HashMap<Type, ITask<Type, IValue, IValue>>();
         map.put(key2, producer);
         keyedProducers.put(key1, map);
       } else {
         producers.put(key, producer);
       }
     }
   } finally {
     lock.unlock();
   }
 }
コード例 #14
0
ファイル: Set.java プロジェクト: CognitiveScale/pdb.values
  public ISet insert(IValue value) {
    if (!contains(value)) {
      ShareableValuesHashSet newData = new ShareableValuesHashSet(data);
      newData.add(value);

      Type type = elementType.lub(value.getType());
      return new SetWriter(type, newData).done();
    } else {
      return this;
    }
  }
コード例 #15
0
  @Override
  public Type getType(Environment env, HashMap<String, IVarPattern> patternVars) {
    if (patternSize == 0) {
      return tf.listType(tf.voidType());
    }

    Type elemType = tf.voidType();
    for (int i = 0; i < patternSize; i += delta) {
      IMatchingResult child = patternChildren.get(i);
      Type childType = child.getType(env, patternVars);
      patternVars = merge(patternVars, patternChildren.get(i).getVariables());
      boolean isMultiVar =
          child instanceof MultiVariablePattern || child instanceof TypedMultiVariablePattern;

      if (childType.isList() && isMultiVar) {
        elemType = elemType.lub(childType.getElementType());
      } else {
        elemType = elemType.lub(childType);
      }
    }
    if (debug) {
      System.err.println("ListPattern.getType: " + tf.listType(elemType));
    }
    return tf.listType(elemType);
  }
コード例 #16
0
ファイル: Resource.java プロジェクト: kevinvandervlist/rascal
  public void generateTypedInterfaceInternal(
      IString tag, ISourceLocation uriLoc, IEvaluatorContext ctx) {
    IResource handler = Resource.getResourceHandler(uriLoc);
    String tagStr = tag.getValue();
    Type t = handler.getResourceType(ctx, uriLoc);
    PrintWriter currentOutStream = ctx.getStdOut();

    // Declare an alias to the type of the resource
    TypeStore ts = ctx.getCurrentEnvt().getStore();
    Type alias2t = TypeFactory.getInstance().aliasType(ts, tagStr + "Type", t);

    currentOutStream.println(
        "Generated type alias " + alias2t.toString() + ": " + alias2t.getAliased().toString());
    currentOutStream.flush();

    // Declare a function that just uses the given URI. This way, if we provide
    // the complete URI up front, we don't need to keep providing it later.
    StringBuilder sb = new StringBuilder();
    sb.append("public ").append(tagStr).append("Type ").append(tagStr).append("() { ");
    sb.append(" return getTypedResource(")
        .append(uriLoc.toString())
        .append(",#")
        .append(tagStr)
        .append("Type); }");
    IConstructor declTree =
        ctx.getEvaluator()
            .parseCommand(
                ctx.getEvaluator().getMonitor(),
                sb.toString(),
                ctx.getCurrentAST().getLocation().getURI());
    Command cmd = ctx.getEvaluator().getBuilder().buildCommand(declTree);
    Environment env = ctx.getCurrentEnvt();
    ctx.setCurrentEnvt(env.getRoot());
    Result<IValue> fun0 = ctx.getEvaluator().eval(ctx.getEvaluator().getMonitor(), cmd);
    ctx.unwind(env);

    currentOutStream.println("Generated function " + fun0.toString());
    currentOutStream.flush();
  }
コード例 #17
0
ファイル: UserType.java プロジェクト: BertLisser/rascal
    @Override
    public Type typeOf(Environment __eval) {
      String name;
      Type type = null;
      Environment theEnv = __eval.getHeap().getEnvironmentForName(this.getName(), __eval);

      name = org.rascalmpl.interpreter.utils.Names.typeName(this.getName());

      if (theEnv != null) {
        type = theEnv.lookupAlias(name);

        if (type == null) {
          type = theEnv.lookupAbstractDataType(name);
        }
      }

      if (type != null) {
        Map<Type, Type> bindings = new HashMap<Type, Type>();
        Type[] params = new Type[this.getParameters().size()];

        int i = 0;
        for (org.rascalmpl.ast.Type param : this.getParameters()) {
          params[i++] = param.typeOf(__eval);
        }

        // __eval has side-effects that we might need?
        type.getTypeParameters().match(TF.tupleType(params), bindings);

        // Instantiate first using the type actually given in the parameter,
        // e.g., for T[str], with data T[&U] = ..., instantate the binding
        // of &U = str, and then instantate using bindings from the current
        // environment (generally meaning we are inside a function with
        // type parameters, and those parameters are now bound to real types)
        return type.instantiate(bindings).instantiate(__eval.getTypeBindings());
      }

      throw new UndeclaredTypeError(name, this);
    }
コード例 #18
0
 /* (non-Javadoc)
  * @see org.rascalmpl.tasks.ITaskRegistry#produce(org.rascalmpl.interpreter.IRascalMonitor, org.rascalmpl.tasks.ITransaction, Type, IValue)
  */
 @Override
 public boolean produce(
     IRascalMonitor monitor, ITransaction<Type, IValue, IValue> tr, Type key, IValue name) {
   ITask<Type, IValue, IValue> producer = null;
   lock.lock();
   try {
     producer = getProducer(key, name);
   } finally {
     lock.unlock();
   }
   if (producer == null)
     throw new ImplementationError("No registered fact producer for " + key.toString());
   return producer.produce(monitor, tr, key, name);
 }
コード例 #19
0
 /* (non-Javadoc)
  * @see org.rascalmpl.tasks.ITaskRegistry#unregisterProducer(org.rascalmpl.tasks.ITask)
  */
 @Override
 public void unregisterProducer(ITask<Type, IValue, IValue> producer) {
   lock.lock();
   try {
     for (Type key : producer.getKeys()) {
       if (key.isTuple()) {
         Type key1 = key.getFieldType(0);
         Map<Type, ITask<Type, IValue, IValue>> map = keyedProducers.get(key1);
         if (map != null) {
           for (Map.Entry<Type, ITask<Type, IValue, IValue>> entry : map.entrySet()) {
             if (entry.getValue().equals(producer)) map.remove(entry.getKey());
           }
           if (map.isEmpty()) keyedProducers.remove(key1);
           else keyedProducers.put(key1, map);
         }
       } else {
         if (producers.get(key) == producer) producers.remove(key);
       }
     }
   } finally {
     lock.unlock();
   }
 }
コード例 #20
0
ファイル: TupleResult.java プロジェクト: BertLisser/rascal
  @Override
  protected <U extends IValue> Result<U> addTuple(TupleResult that) {
    // Note reversed args
    TupleResult left = that;
    TupleResult right = this;
    Type leftType = left.getType();
    Type rightType = right.getType();

    int leftArity = leftType.getArity();
    int rightArity = rightType.getArity();
    int newArity = leftArity + rightArity;

    Type fieldTypes[] = new Type[newArity];
    String fieldNames[] = new String[newArity];
    IValue fieldValues[] = new IValue[newArity];

    boolean consistentLabels = true;
    for (int i = 0; i < leftArity; i++) {
      fieldTypes[i] = leftType.getFieldType(i);
      fieldNames[i] = leftType.getFieldName(i);
      fieldValues[i] = left.getValue().get(i);
      consistentLabels = fieldNames[i] != null;
    }

    for (int i = 0; i < rightArity; i++) {
      fieldTypes[leftArity + i] = rightType.getFieldType(i);
      fieldNames[leftArity + i] = rightType.getFieldName(i);
      fieldValues[leftArity + i] = right.getValue().get(i);
      consistentLabels = fieldNames[i] != null;
      if (consistentLabels) {
        for (int j = 0; j < leftArity; j++) {
          if (fieldNames[j].equals(fieldNames[i])) {
            // duplicate field name, so degenerate to unlabeled tuple
            consistentLabels = false;
          }
        }
      }
    }

    Type newTupleType;
    if (consistentLabels) {
      newTupleType = getTypeFactory().tupleType(fieldTypes, fieldNames);
    } else {
      newTupleType = getTypeFactory().tupleType(fieldTypes);
    }
    return makeResult(newTupleType, getValueFactory().tuple(fieldValues), ctx);
  }
コード例 #21
0
ファイル: Set.java プロジェクト: CognitiveScale/pdb.values
  public ISet union(ISet other) {
    ShareableValuesHashSet newData;
    Iterator<IValue> setIterator;

    Set otherSet = (Set) other;

    if (otherSet.size() <= size()) {
      newData = new ShareableValuesHashSet(data);
      setIterator = otherSet.iterator();
    } else {
      newData = new ShareableValuesHashSet(otherSet.data);
      setIterator = iterator();
    }

    while (setIterator.hasNext()) {
      newData.add(setIterator.next());
    }

    Type newElementType = elementType.lub(otherSet.elementType);
    return new SetWriter(newElementType, newData).done();
  }
コード例 #22
0
ファイル: JavaBridge.java プロジェクト: jeroenpeeters/rascal
 private Class<?> toJavaClass(org.eclipse.imp.pdb.facts.type.Type type) {
   return type.accept(javaClasses);
 }
コード例 #23
0
  @Override
  public void initMatch(Result<IValue> subject) {
    if (debug) {
      System.err.println("List: initMatch: subject=" + subject);
    }

    //    This is an experiment to add abstract list matching for concrete subjects
    //    if (subject.getType().isSubtypeOf(Factory.Tree)) {
    //      IConstructor tree = (IConstructor) subject.getValue();
    //      if (TreeAdapter.isList(tree)) {
    //        subject = ResultFactory.makeResult(Factory.Args, TreeAdapter.getArgs(tree), ctx);
    //        IConstructor rhs = TreeAdapter.getType(tree);
    //
    //        if (SymbolAdapter.isIterPlusSeps(rhs) || SymbolAdapter.isIterStarSeps(rhs)) {
    //          this.delta = SymbolAdapter.getSeparators(rhs).length() + 1;
    //        }
    //      }
    //      else {
    //        hasNext = false;
    //        return;
    //      }
    //    }

    super.initMatch(subject);

    if (!subject.getValue().getType().isList()) {
      hasNext = false;
      return;
    }
    listSubject = (IList) subject.getValue();
    listSubjectType = listSubject.getType();
    staticListSubjectType = subject.getType();
    staticListSubjectElementType =
        staticListSubjectType.isList() ? subject.getType().getElementType() : tf.valueType();

    subjectCursor = 0;
    patternCursor = 0;
    subjectSize = ((IList) subject.getValue()).length();
    reducedSubjectSize = (subjectSize + delta - 1) / delta;

    if (debug) {
      System.err.println("reducedPatternSize=" + reducedPatternSize);
      System.err.println("reducedSubjectSize=" + reducedSubjectSize);
    }

    isListVar = new boolean[patternSize];
    isBindingVar = new boolean[patternSize];
    varName = new String[patternSize];
    allVars = new HashSet<String>();
    listVarStart = new int[patternSize];
    listVarLength = new int[patternSize];
    listVarMinLength = new int[patternSize];
    listVarMaxLength = new int[patternSize];
    listVarOccurrences = new int[patternSize];

    int nListVar = 0;
    /*
     * Pass #1: determine the list variables
     */
    for (int i = 0; i < patternSize; i += delta) {
      IMatchingResult child = patternChildren.get(i);
      isListVar[i] = false;
      isBindingVar[i] = false;
      Environment env = ctx.getCurrentEnvt();

      if (child instanceof TypedMultiVariablePattern) {
        TypedMultiVariablePattern tmvVar = (TypedMultiVariablePattern) child;
        Type tmvType = tmvVar.getType(env, null);
        String name = tmvVar.getName();

        varName[i] = name;
        isListVar[i] = true;
        listVarOccurrences[i] = 1;
        ++nListVar;

        if (!tmvVar.isAnonymous() && allVars.contains(name)) {
          throw new RedeclaredVariable(name, getAST());
        } else if (tmvType.comparable(listSubject.getType().getElementType())
            || (tmvVar.bindingInstance() && tmvType.comparable(listSubject.getType()))) {
          tmvVar.convertToListType();
          if (!tmvVar.isAnonymous()) {
            allVars.add(name);
          }
          isBindingVar[i] = true;
        } else {
          hasNext = false;
          return;
        }
      } else if (child instanceof MultiVariablePattern) {
        MultiVariablePattern multiVar = (MultiVariablePattern) child;
        String name = multiVar.getName();
        varName[i] = name;
        isListVar[i] = true;
        nListVar++;

        if (!multiVar.isAnonymous() && allVars.contains(name)) {
          isBindingVar[i] = false;
        } else if (multiVar.isAnonymous()) {
          isBindingVar[i] = true;
        } else {
          allVars.add(name);
          Result<IValue> varRes = env.getVariable(name);

          if (varRes == null || multiVar.bindingInstance()) {
            isBindingVar[i] = true;
          } else {
            isBindingVar[i] = false;
            Type varType = varRes.getType();
            if (isAnyListType(varType)) {
              if (!varType.comparable(listSubjectType)) {
                hasNext = false;
                return;
              }
            } else {
              if (!(varType instanceof NonTerminalType)
                  && !(varType.comparable(staticListSubjectElementType))) {
                hasNext = false;
                return;
              }
            }
          }
        }
      } else if (child instanceof ConcreteListVariablePattern) {
        ConcreteListVariablePattern listVar = (ConcreteListVariablePattern) child;
        String name = listVar.getName();
        varName[i] = name;
        isListVar[i] = true;
        if (!listVar.isAnonymous()) allVars.add(name);
        isBindingVar[i] = true;
        listVarOccurrences[i] = 1;
        nListVar++;
      } else if (child instanceof QualifiedNamePattern) {
        QualifiedNamePattern qualName = (QualifiedNamePattern) child;
        String name = qualName.getName();
        varName[i] = name;
        if (!qualName.isAnonymous() && allVars.contains(name)) {
          /*
           * A variable that was declared earlier in the pattern
           */
          isListVar[i] = true;
          nListVar++;
          listVarOccurrences[i]++;
        } else if (qualName.isAnonymous()) {
          /*
           * Nothing to do
           */
        } else {
          Result<IValue> varRes = env.getVariable(name);

          if (varRes == null || qualName.bindingInstance()) {
            // A completely new non-list variable, nothing to do
          } else {
            Type varType = varRes.getType();
            if (isAnyListType(varType)) {
              /*
               * A variable declared in the current scope.
               */
              if (varType.comparable(listSubjectType)) {
                isListVar[i] = true;
                isBindingVar[i] = varRes.getValue() == null;
                nListVar++;
              } else {
                hasNext = false;
                return;
              }
            } else {
              if (varType instanceof NonTerminalType) {
                // suppress comparable test for Nonterminal types
                // TODO: this should be done better
              } else if (!varType.comparable(staticListSubjectElementType)) {
                hasNext = false;
                return;
              }
            }
          }
        }
      } else if (child instanceof VariableBecomesPattern) {
        // Nothing to do
      } else {
        if (debug) {
          System.err.println("List: child " + child);
          System.err.println("List: child is a" + child.getClass());
        }
        Type childType = child.getType(env, null);

        // TODO: pattern matching should be specialized such that matching appl(prod...)'s does not
        // need to use list matching on the fixed arity children of the application of a production
        if (!(childType instanceof NonTerminalType)
            && !childType.comparable(staticListSubjectElementType)) {
          hasNext = false;
          return;
        }
        java.util.List<IVarPattern> childVars = child.getVariables();
        if (!childVars.isEmpty()) {
          for (IVarPattern vp : childVars) { // TODO: This does not profit from extra information
            allVars.add(vp.name());
          }
          isListVar[i] = false;
          nListVar++;
        }
      }
    }
    /*
     * Pass #2: assign minimum and maximum length to each list variable
     */
    for (int i = 0; i < patternSize; i += delta) {
      if (isListVar[i]) {
        // TODO: reduce max length according to number of occurrences
        listVarMaxLength[i] =
            delta * Math.max(reducedSubjectSize - (reducedPatternSize - nListVar), 0);
        listVarLength[i] = 0;
        listVarMinLength[i] =
            delta
                * ((nListVar == 1) ? Math.max(reducedSubjectSize - reducedPatternSize - 1, 0) : 0);

        if (debug) {
          System.err.println(
              "listvar " + i + " min= " + listVarMinLength[i] + " max=" + listVarMaxLength[i]);
        }
      }
    }

    firstMatch = true;

    hasNext =
        subject.getValue().getType().isList()
            && reducedSubjectSize >= reducedPatternSize - nListVar;

    if (debug) {
      System.err.println("List: hasNext=" + hasNext);
    }
  }
コード例 #24
0
 public static boolean isAnyListType(Type type) {
   return type.isList() || isConcreteListType(type);
 }
コード例 #25
0
ファイル: IO.java プロジェクト: reflectionalist/rascal
  public void write(IValue rel, ISourceLocation loc, IEvaluatorContext ctx) {

    OutputStream out = null;

    Type paramType = ctx.getCurrentEnvt().getTypeBindings().get(types.parameterType("T"));
    if (!paramType.isRelation() && !paramType.isListRelation()) {
      throw RuntimeExceptionFactory.illegalTypeArgument(
          "A relation type is required instead of " + paramType,
          ctx.getCurrentAST(),
          ctx.getStackTrace());
    }

    try {
      boolean isListRel = rel instanceof IList;
      out = ctx.getResolverRegistry().getOutputStream(loc.getURI(), false);
      ISet irel = null;
      IList lrel = null;
      if (isListRel) {
        lrel = (IList) rel;
      } else {
        irel = (ISet) rel;
      }

      int nfields = isListRel ? lrel.asRelation().arity() : irel.asRelation().arity();
      if (header) {
        for (int i = 0; i < nfields; i++) {
          if (i > 0) out.write(separator);
          String label = paramType.getFieldName(i);
          if (label == null || label.isEmpty()) label = "field" + i;
          writeString(out, label);
        }
        out.write('\n');
      }
      String separatorAsString = new String(Character.toChars(separator));
      for (IValue v : (isListRel ? lrel : irel)) {
        ITuple tup = (ITuple) v;
        int sep = 0;
        for (IValue w : tup) {
          if (sep == 0) sep = separator;
          else out.write(sep);
          if (w.getType().isString()) {
            String s = ((IString) w).getValue();

            if (s.contains(separatorAsString)
                || s.contains("\n")
                || s.contains("\r")
                || s.contains("\"")) {
              s = s.replaceAll("\"", "\"\"");
              out.write('"');
              writeString(out, s);
              out.write('"');
            } else writeString(out, s);
          } else {
            writeString(out, w.toString());
          }
        }
        out.write('\n');
      }
      out.flush();
      out.close();
    } catch (IOException e) {
      throw RuntimeExceptionFactory.io(values.string(e.getMessage()), null, null);
    } finally {
      if (out != null) {
        try {
          out.flush();
          out.close();
        } catch (IOException ioex) {
          throw RuntimeExceptionFactory.io(values.string(ioex.getMessage()), null, null);
        }
      }
    }
  }
コード例 #26
0
ファイル: Factory.java プロジェクト: BertLisser/rascal
/**
 * UPTR stands for Universal Parse Node Representation (formerly known as AsFix). It is an abstract
 * syntax for SDF productions, completed with constructors for parse forests.
 *
 * <p>UPTR is produced by the SGLR parser, by the ASF+SDF interpreter and by compiled ASF+SDF
 * programs. UPTR is consumed by tools that manipulate parse trees in general (such as automatic
 * syntax high-lighters) or tools that manipulate specific parse trees (such as the Rascal
 * interpreter).
 */
public class Factory {
  public static final TypeStore uptr =
      new TypeStore(
          org.rascalmpl.values.errors.Factory.getStore(),
          org.rascalmpl.values.locations.Factory.getStore());
  private static final TypeFactory tf = TypeFactory.getInstance();
  private static final Type str = tf.stringType();

  public static final Type TypeParam = tf.parameterType("T");
  public static final Type Type = new ReifiedType(TypeParam);

  static {
    uptr.declareAbstractDataType(Type);
  }

  public static final Type Tree = tf.abstractDataType(uptr, "Tree");
  public static final Type Production = tf.abstractDataType(uptr, "Production");
  public static final Type Attributes = tf.abstractDataType(uptr, "Attributes");
  public static final Type Attr = tf.abstractDataType(uptr, "Attr");
  public static final Type Associativity = tf.abstractDataType(uptr, "Associativity");
  public static final Type Symbol = tf.abstractDataType(uptr, "Symbol");
  public static final Type CharRange = tf.abstractDataType(uptr, "CharRange");
  public static final Type Args = tf.listType(Tree);
  public static final Type Attrs = tf.setType(Attr);
  public static final Type Symbols = tf.listType(Symbol);
  public static final Type CharRanges = tf.listType(CharRange);
  public static final Type Alternatives = tf.setType(Tree);

  public static final Type Type_Reified =
      tf.constructor(
          uptr, Type, "type", Symbol, "symbol", tf.mapType(Symbol, Production), "definitions");

  public static final Type Tree_Appl =
      tf.constructor(uptr, Tree, "appl", Production, "prod", tf.listType(Tree), "args");
  public static final Type Tree_Cycle =
      tf.constructor(uptr, Tree, "cycle", Symbol, "symbol", tf.integerType(), "cycleLength");
  public static final Type Tree_Amb =
      tf.constructor(uptr, Tree, "amb", Alternatives, "alternatives");
  public static final Type Tree_Char =
      tf.constructor(uptr, Tree, "char", tf.integerType(), "character");

  public static final Type Production_Default =
      tf.constructor(
          uptr,
          Production,
          "prod",
          Symbol,
          "def",
          tf.listType(Symbol),
          "symbols",
          tf.setType(Attr),
          "attributes");
  public static final Type Production_Regular =
      tf.constructor(uptr, Production, "regular", Symbol, "def");
  public static final Type Production_Error =
      tf.constructor(uptr, Production, "error", Production, "prod", tf.integerType(), "dot");
  public static final Type Production_Skipped = tf.constructor(uptr, Production, "skipped");
  public static final Type Production_Cons =
      tf.constructor(
          uptr,
          Production,
          "cons",
          Symbol,
          "def",
          tf.listType(Symbol),
          "symbols",
          tf.setType(Attr),
          "attributes");
  public static final Type Production_Func =
      tf.constructor(
          uptr,
          Production,
          "func",
          Symbol,
          "def",
          tf.listType(Symbol),
          "symbols",
          tf.setType(Attr),
          "attributes");
  public static final Type Production_Choice =
      tf.constructor(
          uptr, Production, "choice", Symbol, "def", tf.setType(Production), "alternatives");
  public static final Type Production_Priority =
      tf.constructor(
          uptr, Production, "priority", Symbol, "def", tf.listType(Production), "choices");
  public static final Type Production_Associativity =
      tf.constructor(
          uptr,
          Production,
          "associativity",
          Symbol,
          "def",
          Associativity,
          "assoc",
          tf.setType(Production),
          "alternatives");

  public static final Type Attr_Assoc = tf.constructor(uptr, Attr, "assoc", Associativity, "assoc");
  public static final Type Attr_Tag = tf.constructor(uptr, Attr, "tag", tf.valueType(), "tag");
  public static final Type Attr_Bracket = tf.constructor(uptr, Attr, "bracket");

  public static final Type Associativity_Left = tf.constructor(uptr, Associativity, "left");
  public static final Type Associativity_Right = tf.constructor(uptr, Associativity, "right");
  public static final Type Associativity_Assoc = tf.constructor(uptr, Associativity, "assoc");
  public static final Type Associativity_NonAssoc =
      tf.constructor(uptr, Associativity, "non-assoc");

  public static final Type Condition = tf.abstractDataType(uptr, "Condition");
  public static final Type Condition_Follow =
      tf.constructor(uptr, Condition, "follow", Symbol, "symbol");
  public static final Type Condition_NotFollow =
      tf.constructor(uptr, Condition, "not-follow", Symbol, "symbol");
  public static final Type Condition_Precede =
      tf.constructor(uptr, Condition, "precede", Symbol, "symbol");
  public static final Type Condition_NotPrecede =
      tf.constructor(uptr, Condition, "not-precede", Symbol, "symbol");
  public static final Type Condition_Delete =
      tf.constructor(uptr, Condition, "delete", Symbol, "symbol");
  public static final Type Condition_EndOfLine = tf.constructor(uptr, Condition, "end-of-line");
  public static final Type Condition_StartOfLine = tf.constructor(uptr, Condition, "begin-of-line");
  public static final Type Condition_AtColumn =
      tf.constructor(uptr, Condition, "at-column", tf.integerType(), "column");
  public static final Type Condition_Except =
      tf.constructor(uptr, Condition, "except", tf.stringType(), "label");

  public static final Type Symbol_Label =
      tf.constructor(uptr, Symbol, "label", str, "name", Symbol, "symbol");
  public static final Type Symbol_Start_Sort =
      tf.constructor(uptr, Symbol, "start", Symbol, "start");
  public static final Type Symbol_START = tf.constructor(uptr, Symbol, "START");
  public static final Type Symbol_Lit = tf.constructor(uptr, Symbol, "lit", str, "string");
  public static final Type Symbol_CiLit = tf.constructor(uptr, Symbol, "cilit", str, "string");
  public static final Type Symbol_Empty = tf.constructor(uptr, Symbol, "empty");
  public static final Type Symbol_Seq =
      tf.constructor(uptr, Symbol, "seq", tf.listType(Symbol), "symbols");
  public static final Type Symbol_Opt = tf.constructor(uptr, Symbol, "opt", Symbol, "symbol");
  public static final Type Symbol_Alt =
      tf.constructor(uptr, Symbol, "alt", tf.setType(Symbol), "alternatives");
  public static final Type Symbol_Sort = tf.constructor(uptr, Symbol, "sort", str, "name");
  public static final Type Symbol_Lex = tf.constructor(uptr, Symbol, "lex", str, "name");
  public static final Type Symbol_Keyword = tf.constructor(uptr, Symbol, "keywords", str, "name");
  public static final Type Symbol_Meta = tf.constructor(uptr, Symbol, "meta", Symbol, "symbol");
  public static final Type Symbol_Conditional =
      tf.constructor(
          uptr, Symbol, "conditional", Symbol, "symbol", tf.setType(Condition), "conditions");
  public static final Type Symbol_IterSepX =
      tf.constructor(
          uptr, Symbol, "iter-seps", Symbol, "symbol", tf.listType(Symbol), "separators");
  public static final Type Symbol_IterStarSepX =
      tf.constructor(
          uptr, Symbol, "iter-star-seps", Symbol, "symbol", tf.listType(Symbol), "separators");
  public static final Type Symbol_IterPlus = tf.constructor(uptr, Symbol, "iter", Symbol, "symbol");
  public static final Type Symbol_IterStar =
      tf.constructor(uptr, Symbol, "iter-star", Symbol, "symbol");
  public static final Type Symbol_ParameterizedSort =
      tf.constructor(
          uptr, Symbol, "parameterized-sort", str, "name", tf.listType(Symbol), "parameters");
  public static final Type Symbol_Parameter =
      tf.constructor(uptr, Symbol, "parameter", str, "name");
  public static final Type Symbol_LayoutX = tf.constructor(uptr, Symbol, "layouts", str, "name");

  public static final Type Symbol_CharClass =
      tf.constructor(uptr, Symbol, "char-class", tf.listType(CharRange), "ranges");

  public static final Type Symbol_Int = tf.constructor(uptr, Symbol, "int");
  public static final Type Symbol_Rat = tf.constructor(uptr, Symbol, "rat");
  public static final Type Symbol_Bool = tf.constructor(uptr, Symbol, "bool");
  public static final Type Symbol_Real = tf.constructor(uptr, Symbol, "real");
  public static final Type Symbol_Str = tf.constructor(uptr, Symbol, "str");
  public static final Type Symbol_Node = tf.constructor(uptr, Symbol, "node");
  public static final Type Symbol_Num = tf.constructor(uptr, Symbol, "num");
  public static final Type Symbol_Void = tf.constructor(uptr, Symbol, "void");
  public static final Type Symbol_Value = tf.constructor(uptr, Symbol, "value");
  public static final Type Symbol_Loc = tf.constructor(uptr, Symbol, "loc");
  public static final Type Symbol_Datetime = tf.constructor(uptr, Symbol, "datetime");
  public static final Type Symbol_Set = tf.constructor(uptr, Symbol, "set", Symbol, "symbol");
  public static final Type Symbol_Rel =
      tf.constructor(uptr, Symbol, "rel", tf.listType(Symbol), "symbols");
  public static final Type Symbol_Tuple =
      tf.constructor(uptr, Symbol, "tuple", tf.listType(Symbol), "symbols");
  public static final Type Symbol_List = tf.constructor(uptr, Symbol, "list", Symbol, "symbol");
  public static final Type Symbol_Map =
      tf.constructor(uptr, Symbol, "map", Symbol, "from", Symbol, "to");
  public static final Type Symbol_Bag = tf.constructor(uptr, Symbol, "bag", Symbol, "symbol");
  public static final Type Symbol_Adt =
      tf.constructor(uptr, Symbol, "adt", str, "name", tf.listType(Symbol), "parameters");
  public static final Type Symbol_ReifiedType =
      tf.constructor(uptr, Symbol, "reified", Symbol, "symbol");
  public static final Type Symbol_Func =
      tf.constructor(uptr, Symbol, "func", Symbol, "ret", tf.listType(Symbol), "parameters");
  public static final Type Symbol_Alias =
      tf.constructor(
          uptr, Symbol, "alias", str, "name", tf.listType(Symbol), "parameters", Symbol, "aliased");
  public static final Type Symbol_Cons =
      tf.constructor(
          uptr, Symbol, "cons", Symbol, "adt", str, "name", tf.listType(Symbol), "parameters");
  public static final Type Symbol_BoundParameter =
      tf.constructor(uptr, Symbol, "parameter", str, "name", Symbol, "bound");

  public static final Type CharRange_Single =
      tf.constructor(uptr, CharRange, "single", tf.integerType(), "begin");
  public static final Type CharRange_Range =
      tf.constructor(uptr, CharRange, "range", tf.integerType(), "begin", tf.integerType(), "end");

  public static final String Location = "loc";
  public static final String Length = "len";

  private static final IValueFactory vf = ValueFactoryFactory.getValueFactory();
  public static final IValue Attribute_Assoc_Left =
      Attr_Assoc.make(vf, Associativity_Left.make(vf));
  public static final IValue Attribute_Assoc_Right =
      Attr_Assoc.make(vf, Associativity_Right.make(vf));
  public static final IValue Attribute_Assoc_Non_Assoc =
      Attr_Assoc.make(vf, Associativity_NonAssoc.make(vf));
  public static final IValue Attribute_Assoc_Assoc =
      Attr_Assoc.make(vf, Associativity_Assoc.make(vf));
  public static final IValue Attribute_Bracket = Attr_Bracket.make(vf);

  private static final class InstanceHolder {
    public static final Factory factory = new Factory();
  }

  public static Factory getInstance() {
    return InstanceHolder.factory;
  }

  private Factory() {
    uptr.declareAnnotation(Tree, Location, tf.sourceLocationType());
    uptr.declareAnnotation(Tree, Length, tf.integerType());
  }

  public static TypeStore getStore() {
    return uptr;
  }
}
コード例 #27
0
ファイル: JavaBridge.java プロジェクト: jeroenpeeters/rascal
 @Override
 public Class<?> visitAlias(org.eclipse.imp.pdb.facts.type.Type type) {
   return type.getAliased().accept(this);
 }
コード例 #28
0
ファイル: JavaBridge.java プロジェクト: jeroenpeeters/rascal
 @Override
 public Class<?> visitParameter(org.eclipse.imp.pdb.facts.type.Type parameterType) {
   return parameterType.getBound().accept(this);
 }