Ejemplo n.º 1
0
  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();
  }
Ejemplo n.º 2
0
 private Object javaObject(IValue v) {
   if (v.getType().isBoolType()) return new Boolean(((IBool) v).getValue());
   if (v.getType().isIntegerType()) return new Integer(((IInteger) v).intValue());
   if (v.getType().isStringType()) return ((IString) v).getValue();
   if (v.getType().isRealType()) return new Double(((IReal) v).doubleValue());
   if (v.getType().isListType()) return _listValue((IList) v);
   return null;
 }
  public boolean contains(IValue value) {
    Iterator<IValue> valuesIterator = iterator();
    while (valuesIterator.hasNext()) {
      IValue next = valuesIterator.next();
      if (next.isEqual(value)) return true;
    }

    return false;
  }
Ejemplo n.º 4
0
  @Override
  protected IStatus run(IProgressMonitor monitor) {
    monitor.beginTask("Parsing", 105);

    try {
      handler.clearMessages();

      IGTD<IConstructor, IConstructor, ISourceLocation> gtd = new ClojureParser();
      parseTree =
          (IConstructor)
              gtd.parse(
                  START_SORT,
                  URI.create(path.toString()),
                  input.toCharArray(),
                  new DefaultNodeFlattener<IConstructor, IConstructor, ISourceLocation>(),
                  new UPTRNodeFactory());

    } catch (ParseError pe) {
      int offset = pe.getOffset();
      if (offset == input.length()) --offset;

      handler.handleSimpleMessage(
          "parse error",
          offset,
          offset + pe.getLength(),
          pe.getBeginColumn(),
          pe.getEndColumn(),
          pe.getBeginLine() + 1,
          pe.getEndLine() + 1);
    } catch (Throw e) {
      IValue exc = e.getException();

      if (exc.getType() == RuntimeExceptionFactory.Exception) {
        if (((IConstructor) exc).getConstructorType() == RuntimeExceptionFactory.ParseError) {
          ISourceLocation loc = (ISourceLocation) ((IConstructor) e.getException()).get(0);
          handler.handleSimpleMessage(
              "parse error: " + loc,
              loc.getOffset(),
              loc.getOffset() + loc.getLength(),
              loc.getBeginColumn(),
              loc.getEndColumn(),
              loc.getBeginLine(),
              loc.getEndLine());
        } else {
          Activator.getInstance().logException(e.getMessage(), e);
        }
      }
    } catch (Throwable e) {
      Activator.getInstance().logException("parsing failed: " + e.getMessage(), e);
    } finally {
      monitor.done();
    }

    return Status.OK_STATUS;
  }
Ejemplo n.º 5
0
  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();
  }
Ejemplo n.º 6
0
  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;
    }
  }
  public boolean remove(IValue value) {
    int index = 0;
    Iterator<IValue> valuesIterator = iterator();
    while (valuesIterator.hasNext()) {
      IValue next = valuesIterator.next();
      if (next.isEqual(value)) break;

      index++;
    }

    if (index < size()) {
      remove(index);
      return true;
    }

    return false;
  }
Ejemplo n.º 8
0
 public IValue getTypedResource(ISourceLocation uriLoc, IValue type, IEvaluatorContext ctx) {
   // TODO: We may not need this here, since we already create the same type internally
   // when we create the resource. Commenting out for now...
   Type resourceType = ((ReifiedType) type.getType()).getTypeParameters().getFieldType(0);
   IResource handler = Resource.getResourceHandler(uriLoc);
   ResourceResult rr = handler.createResource(ctx, uriLoc, resourceType);
   return rr.getValue();
 }
Ejemplo n.º 9
0
 /**
  * Make a new Rascal exception.
  *
  * @param value The Rascal exception value
  * @param loc A source location, or null if unavailable
  * @param trace A stack trace, or null
  */
 public Throw(IValue value, ISourceLocation loc, StackTrace trace) {
   super(value.toString());
   this.exception = value;
   this.loc = loc;
   if (trace == null) {
     trace = StackTrace.EMPTY_STACK_TRACE;
   }
   this.trace = trace;
 }
  public boolean isEqual(ShareableValuesList otherShareableValuesList) {
    if (otherShareableValuesList == null) return false;
    if (otherShareableValuesList.size() != size()) return false;

    if (otherShareableValuesList.isEmpty()) return true;

    Iterator<IValue> thisListIterator = iterator();
    Iterator<IValue> otherListIterator = otherShareableValuesList.iterator();
    while (thisListIterator.hasNext()) {
      IValue thisValue = thisListIterator.next();
      IValue otherValue = otherListIterator.next();
      if (!thisValue.isEqual(otherValue)) {
        return false;
      }
    }

    return true;
  }
Ejemplo n.º 11
0
  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;
    }
  }
Ejemplo n.º 12
0
  public void testBinaryIO() {
    try {
      for (int i = 0; i < testValues.length; i++) {
        IValue value = testValues[i];

        System.out.println(value); // Temp

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BinaryWriter binaryWriter = new BinaryWriter(value, baos, ts);
        binaryWriter.serialize();

        // PBFWriter.writeValueToFile(value, new File("/tmp/testIO"+i+".pbf")); // Temp

        byte[] data = baos.toByteArray();
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        BinaryReader binaryReader = new BinaryReader(vf, ts, bais);
        printBytes(data); // Temp
        IValue result = binaryReader.deserialize();

        System.out.println(result); // Temp
        System.out.println(); // Temp

        if (!value.isEqual(result)) {
          String message =
              "Not equal: \n\t"
                  + value
                  + " : "
                  + value.getType()
                  + "\n\t"
                  + result
                  + " : "
                  + result.getType();
          System.err.println(message);
          fail(message);
        }
      }
    } catch (IOException ioex) {
      ioex.printStackTrace();
      fail(ioex.getMessage());
    }
  }
Ejemplo n.º 13
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();
   }
 }
Ejemplo n.º 14
0
  /*
   * Perform a list match. When forward=true we move to the right in the pattern
   * and try to match the corresponding elements of the subject. When the end of the pattern
   * and the subject are reaching, match returns true.
   *
   * When a non-matching element is encountered, we switch to moving to the left (forward==false)
   * and try to find alternative options in list variables.
   *
   * When the left-hand side of the pattern is reached while moving to the left, match return false,
   * and no more options are available: hasNext() will return false.
   *
   * @see org.meta_environment.rascal.interpreter.MatchPattern#match()
   */
  @Override
  public boolean next() {
    if (debug) System.err.println("List.next: entering");
    checkInitialized();
    if (debug) System.err.println("AbstractPatternList.match: " + subject);

    if (!hasNext) return false;

    forward = firstMatch;
    firstMatch = false;

    do {

      /*
       * Determine the various termination conditions.
       */

      if (debug)
        System.err.println(
            "List.do: patternCursor=" + patternCursor + ", subjectCursor=" + subjectCursor);

      if (forward) {
        if (patternCursor >= patternSize) {
          if (subjectCursor >= subjectSize) {
            if (debug) System.err.println(">>> match returns true");
            //            hasNext = (subjectCursor > subjectSize) && (patternCursor > patternSize);
            // // JURGEN GUESSES THIS COULD BE RIGHT
            return true;
          }
          forward = false;
          patternCursor -= delta;
        }
      } else {
        if (patternCursor >= patternSize) {
          patternCursor -= delta;
          subjectCursor -= delta; // Ok?
        }
      }

      if (patternCursor < 0 || subjectCursor < 0) {
        hasNext = false;
        if (debug)
          System.err.println(
              ">>> match returns false: patternCursor="
                  + patternCursor
                  + ", forward="
                  + forward
                  + ", subjectCursor="
                  + subjectCursor);
        return false;
      }

      /*
       * Perform actions for the current pattern element
       */

      IMatchingResult child = patternChildren.get(patternCursor);
      if (debug) {
        System.err.println(this);
        System.err.println(
            "loop: patternCursor="
                + patternCursor
                + ", forward="
                + forward
                + ", subjectCursor= "
                + subjectCursor
                + ", child="
                + child
                + ", isListVar="
                + isListVar[patternCursor]
                + ", class="
                + child.getClass());
      }

      /*
       * A binding occurrence of a list variable
       */

      if (isListVar[patternCursor] && isBindingVar[patternCursor]) {
        if (forward) {
          listVarStart[patternCursor] = subjectCursor;
          if (patternCursor == patternSize - 1) {
            if (debug) {
              System.err.println("subjectSize=" + subjectSize);
              System.err.println("subjectCursor=" + subjectCursor);
            }
            listVarLength[patternCursor] = Math.max(subjectSize - subjectCursor, 0);
          } else {
            listVarLength[patternCursor] = listVarMinLength[patternCursor];
          }
        } else {
          listVarLength[patternCursor] += delta;
          forward = true;
        }
        if (debug)
          System.err.println(
              "list var: start: "
                  + listVarStart[patternCursor]
                  + ", len="
                  + listVarLength[patternCursor]
                  + ", minlen="
                  + listVarMinLength[patternCursor]
                  + ", maxlen="
                  + listVarMaxLength[patternCursor]);
        if (listVarLength[patternCursor] > listVarMaxLength[patternCursor]
            || listVarStart[patternCursor] + listVarLength[patternCursor] >= subjectSize + delta) {

          subjectCursor = listVarStart[patternCursor];
          if (debug) System.err.println("Length failure, subjectCursor=" + subjectCursor);

          forward = false;
          listVarLength[patternCursor] = 0;
          patternCursor -= delta;
        } else {
          matchBindingListVar(child);
        }

        /*
         * Reference to a previously defined list variable
         */
      } else if (isListVar[patternCursor]
          && !isBindingVar[patternCursor]
          && ctx.getCurrentEnvt().getVariable(varName[patternCursor]).getType().isList()) {
        if (forward) {
          listVarStart[patternCursor] = subjectCursor;

          Result<IValue> varRes = ctx.getCurrentEnvt().getVariable(varName[patternCursor]);
          IValue varVal = varRes.getValue();

          if (varRes.getType().isList()) {
            assert varVal != null && varVal.getType().isList();

            int varLength = ((IList) varVal).length();
            listVarLength[patternCursor] = varLength;

            if (subjectCursor + varLength > subjectSize) {
              forward = false;
              patternCursor -= delta;
            } else {
              matchBoundListVar((IList) varVal);
            }
          }
        } else {
          subjectCursor = listVarStart[patternCursor];
          patternCursor -= delta;
        }

        /*
         * Any other element of the pattern
         */
      } else {
        if (forward && subjectCursor < subjectSize) {
          if (debug)
            System.err.println(
                "AbstractPatternList.match: init child "
                    + patternCursor
                    + " with "
                    + listSubject.get(subjectCursor));
          IValue childValue = listSubject.get(subjectCursor);
          // TODO: check if we can use a static type here?!
          child.initMatch(ResultFactory.makeResult(childValue.getType(), childValue, ctx));
          if (child.next()) {
            subjectCursor += delta;
            patternCursor += delta;
            if (debug)
              System.err.println(
                  "AbstractPatternList.match: child matches, subjectCursor=" + subjectCursor);
          } else {
            forward = false;
            //  why is here no subjectCursor -= delta;  needed?
            patternCursor -= delta;
          }
        } else {
          if (subjectCursor < subjectSize && child.next()) {
            if (debug) System.err.println("child has next:" + child);
            forward = true;
            subjectCursor += delta;
            patternCursor += delta;
          } else {
            if (debug) System.err.println("child has no next:" + child);
            forward = false;
            subjectCursor -= delta;
            patternCursor -= delta;
          }
        }
      }

    } while (true);
  }
Ejemplo n.º 15
0
 private IValue computeType(ISourceLocation loc, IMap options, IEvaluatorContext ctx) {
   IValue csvResult = this.read(null, loc, options, ctx);
   return ((IConstructor)
       new TypeReifier(values).typeToValue(csvResult.getType(), ctx).getValue());
 }
Ejemplo n.º 16
0
    public String getText(Object element) {
      IValue value = (IValue) element;
      return value.accept(
          new IValueVisitor<String, RuntimeException>() {

            public String visitBoolean(IBool boolValue) {
              return boolValue.toString();
            }

            public String visitConstructor(IConstructor o) {
              return o.getConstructorType().toString();
            }

            public String visitExternal(IExternalValue externalValue) {
              return externalValue.getType().toString();
            }

            public String visitInteger(IInteger o) {
              return o.toString();
            }

            public String visitRational(IRational o) {
              return o.toString();
            }

            public String visitList(IList o) {
              return o.getType().toString();
            }

            public String visitMap(IMap o) {
              return o.getType().toString();
            }

            public String visitNode(INode o) {
              return o.getName();
            }

            public String visitReal(IReal o) {
              return o.toString();
            }

            public String visitRelation(ISet o) {
              return o.getType().toString();
            }

            public String visitSet(ISet o) {
              return o.getType().toString();
            }

            public String visitSourceLocation(ISourceLocation o) {
              return o.toString();
            }

            public String visitString(IString o) {
              return o.toString();
            }

            public String visitTuple(ITuple o) {
              return o.getType().toString();
            }

            public String visitDateTime(IDateTime o) {
              return o.toString();
            }

            public String visitListRelation(IList o) {
              return o.getType().toString();
            }
          });
    }
  @Override
  protected Result<IBool> equalToConcreteSyntax(ConcreteSyntaxResult that) {
    IConstructor left = this.getValue();
    IConstructor right = that.getValue();

    if (TreeAdapter.isLayout(left) && TreeAdapter.isLayout(right)) {
      return bool(true, ctx);
    }

    if (TreeAdapter.isAppl(left) && TreeAdapter.isAppl(right)) {
      IConstructor p1 = TreeAdapter.getProduction(left);
      IConstructor p2 = TreeAdapter.getProduction(right);

      if (!p1.isEqual(p2)) {
        return bool(false, ctx);
      }

      IList l1 = TreeAdapter.getArgs(left);
      IList l2 = TreeAdapter.getArgs(right);

      if (l1.length() != l2.length()) {
        return bool(false, ctx);
      }
      for (int i = 0; i < l1.length(); i++) {
        IValue kid1 = l1.get(i);
        IValue kid2 = l2.get(i);
        // Recurse here on kids to reuse layout handling etc.
        Result<IBool> result =
            makeResult(kid1.getType(), kid1, ctx).equals(makeResult(kid2.getType(), kid2, ctx));
        if (!result.getValue().getValue()) {
          return bool(false, ctx);
        }
        if (TreeAdapter.isContextFree(left)) {
          i++; // skip layout
        }
      }
      return bool(true, ctx);
    }

    if (TreeAdapter.isChar(left) && TreeAdapter.isChar(right)) {
      return bool((TreeAdapter.getCharacter(left) == TreeAdapter.getCharacter(right)), ctx);
    }

    if (TreeAdapter.isAmb(left) && TreeAdapter.isAmb(right)) {
      ISet alts1 = TreeAdapter.getAlternatives(left);
      ISet alts2 = TreeAdapter.getAlternatives(right);

      if (alts1.size() != alts2.size()) {
        return bool(false, ctx);
      }

      // TODO: this is very inefficient
      again:
      for (IValue alt1 : alts1) {
        for (IValue alt2 : alts2) {
          Result<IBool> result =
              makeResult(alt1.getType(), alt1, ctx).equals(makeResult(alt2.getType(), alt2, ctx));
          if (result.getValue().getValue()) {
            // As soon an alt1 is equal to an alt2
            // continue the outer loop.
            continue again;
          }
        }
        // If an alt1 is not equal to any of the the alt2's return false;
        return bool(false, ctx);
      }
      return bool(true, ctx);
    }

    return bool(false, ctx);
  }
Ejemplo n.º 18
0
  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);
        }
      }
    }
  }