Exemplo n.º 1
0
public interface IParserTest {
  public static final IValueFactory VF = ValueFactoryFactory.getValueFactory();

  ITree executeParser();

  IValue getExpectedResult() throws IOException;
}
Exemplo n.º 2
0
 @Override
 void executeCallback() {
   cbenv.executeRascalCallBackSingleArgument(
       callback,
       TypeFactory.getInstance().integerType(),
       ValueFactoryFactory.getValueFactory().integer(widget.getSelection()));
 }
Exemplo n.º 3
0
  static {
    heap = new GlobalEnvironment();
    root = heap.addModule(new ModuleEnvironment("___test___", heap));
    modules = new TestModuleResolver();

    stderr = new PrintWriter(System.err);
    stdout = new PrintWriter(System.out);
    evaluator = new Evaluator(ValueFactoryFactory.getValueFactory(), stderr, stdout, root, heap);

    evaluator.addRascalSearchPathContributor(StandardLibraryContributor.getInstance());
    URIResolverRegistry resolverRegistry = URIResolverRegistry.getInstance();

    evaluator.addRascalSearchPath(URIUtil.rootLocation("test-modules"));
    resolverRegistry.registerInput(modules);

    evaluator.addRascalSearchPath(URIUtil.rootLocation("benchmarks"));
    resolverRegistry.registerInput(
        new ClassResourceInput("benchmarks", Evaluator.class, "/org/rascalmpl/benchmark"));
    try {
      assert (false);
      throw new RuntimeException(
          "Make sure you enable the assert statement in your run configuration ( add -ea )");
    } catch (AssertionError e) {

    }
  }
Exemplo n.º 4
0
  @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);
  }
Exemplo n.º 5
0
  public static void main(String[] args) {

    RVM rvm = new RVM(ValueFactoryFactory.getValueFactory());
    IValueFactory vf = rvm.vf;
    TypeFactory tf = TypeFactory.getInstance();

    rvm.declare(
        new Function(
            "main",
            tf.valueType(),
            null,
            1,
            1,
            6,
            new CodeBlock(vf).LOADCON(3).LOADCON("abc").PRINTLN(1).HALT()));

    rvm.declare(
        new Function(
            "#module_init",
            tf.valueType(),
            null,
            1,
            1,
            6,
            new CodeBlock(vf).LOADLOC(0).CALL("main", 1).RETURN1(1).HALT()));

    rvm.executeProgram("main", new IValue[] {});
  }
Exemplo n.º 6
0
 public IList getProfileData() {
   IValueFactory VF = ValueFactoryFactory.getValueFactory();
   IListWriter w = VF.listWriter();
   for (Map.Entry<ISourceLocation, Count> e : sortData(ast)) {
     w.insert(VF.tuple(e.getKey(), VF.integer(e.getValue().getTicks())));
   }
   return w.done();
 }
Exemplo n.º 7
0
 public IValue getExpectedResult() throws IOException {
   String expectedInput =
       "appl(prod(sort(\"S\"),[\\iter-star-seps(sort(\"A\"),[lit(\"b\")])],{}),[appl(regular(\\iter-star-seps(sort(\"A\"),[lit(\"b\")])),[appl(prod(sort(\"A\"),[lit(\"a\")],{}),[appl(prod(lit(\"a\"),[\\char-class([single(97)])],{}),[char(97)])]),appl(prod(lit(\"b\"),[\\char-class([single(98)])],{}),[char(98)]),appl(prod(sort(\"A\"),[lit(\"a\")],{}),[appl(prod(lit(\"a\"),[\\char-class([single(97)])],{}),[char(97)])]),appl(prod(lit(\"b\"),[\\char-class([single(98)])],{}),[char(98)]),appl(prod(sort(\"A\"),[lit(\"a\")],{}),[appl(prod(lit(\"a\"),[\\char-class([single(97)])],{}),[char(97)])])])])";
   return new StandardTextReader()
       .read(
           ValueFactoryFactory.getValueFactory(),
           Factory.uptr,
           Factory.Tree,
           new StringReader(expectedInput));
 }
Exemplo n.º 8
0
 public IValue getExpectedResult() throws IOException {
   String expectedInput =
       "amb({appl(prod(sort(\"S\"),[lit(\"a\")],{}),[appl(prod(lit(\"a\"),[\\char-class([single(97)])],{}),[char(97)])]),appl(prod(sort(\"S\"),[sort(\"A\")],{}),[appl(prod(sort(\"A\"),[lit(\"a\")],{}),[appl(prod(lit(\"a\"),[\\char-class([single(97)])],{}),[char(97)])])])})";
   return new StandardTextReader()
       .read(
           ValueFactoryFactory.getValueFactory(),
           RascalValueFactory.uptr,
           RascalValueFactory.Tree,
           new StringReader(expectedInput));
 }
Exemplo n.º 9
0
 public RascalTutor() {
   GlobalEnvironment heap = new GlobalEnvironment();
   ModuleEnvironment root = heap.addModule(new ModuleEnvironment("___TUTOR___", heap));
   PrintWriter stderr = new PrintWriter(System.err);
   PrintWriter stdout = new PrintWriter(System.out);
   eval = new Evaluator(ValueFactoryFactory.getValueFactory(), stderr, stdout, root, heap);
   eval.addRascalSearchPathContributor(StandardLibraryContributor.getInstance());
   eval.addRascalSearchPath(URIUtil.rootScheme("tutor"));
   eval.addRascalSearchPath(URIUtil.rootScheme("courses"));
 }
Exemplo n.º 10
0
 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();
 }
Exemplo n.º 11
0
public class ReportView extends ViewPart implements IAmbiDexterMonitor {
  public static final String ID = ID_AMBIDEXTER_REPORT_VIEW_PART;
  private static final IValueFactory VF = ValueFactoryFactory.getValueFactory();
  private final PrintStream out = RuntimePlugin.getInstance().getConsoleStream();
  private TableColumn nonterminals;
  private TableColumn sentences;
  private Table table;
  private final StandardTextReader reader = new StandardTextReader();
  private volatile boolean canceling;
  private AmbiDexterJob job;

  public ReportView() {
    super();
    job = new AmbiDexterJob("AmbiDexter");
  }

  public void run(final Grammar grammar, final AmbiDexterConfig cfg) {
    table.removeAll();

    println("Running AmbiDexter...");
    grammar.printSize(this);

    canceling = false;
    job.init(grammar, cfg);
    job.schedule();
  }

  @Override
  public void createPartControl(Composite parent) {
    table = new Table(parent, SWT.BORDER);
    nonterminals = new TableColumn(table, SWT.CENTER);
    sentences = new TableColumn(table, SWT.CENTER);
    nonterminals.setText("Symbol");
    sentences.setText("Sentence");
    nonterminals.setWidth(70);
    sentences.setWidth(70);
    table.setHeaderVisible(true);

    IToolBarManager toolbar = getViewSite().getActionBars().getToolBarManager();
    installAction(toolbar, new EditSentenceAction());
    installAction(toolbar, new EditTreeAction());
    installAction(toolbar, new BrowseTreeAction());
    installAction(toolbar, new DiagnoseAction());
  }

  private void installAction(IToolBarManager toolbar, AbstractAmbidexterAction edit) {
    table.addSelectionListener(edit);
    toolbar.add(edit);
  }

  @Override
  public void setFocus() {
    // TODO Auto-generated method stub
  }

  @Override
  public void println() {
    out.println();
  }

  @Override
  public void println(Object o) {
    out.println(o);
  }

  @Override
  public void errPrintln() {
    out.println("error:");
  }

  @Override
  public void errPrintln(Object o) {
    out.println("error:" + o);
  }

  @Override
  public void ambiguousString(
      final AmbiDexterConfig cfg, final SymbolString s, final NonTerminal n, String messagePrefix) {
    try {
      final IConstructor sym =
          (IConstructor)
              reader.read(
                  VF,
                  RascalValueFactory.uptr,
                  RascalValueFactory.Symbol,
                  new StringReader(n.prettyPrint()));
      final String ascii = toascci(s);
      final String module = getModuleName(cfg.filename);
      final String project = getProjectName(cfg.filename);

      addItem(sym, ascii, module, project, null);
    } catch (FactTypeUseException e) {
      Activator.getInstance().logException("failed to register ambiguity", e);
    } catch (IOException e) {
      Activator.getInstance().logException("failed to register ambiguity", e);
    }
  }

  private void addItem(
      final IConstructor sym,
      final String ascii,
      final String module,
      final String project,
      final IConstructor tree) {
    PlatformUI.getWorkbench()
        .getDisplay()
        .asyncExec(
            new Runnable() {
              @Override
              public void run() {
                TableItem item = new TableItem(table, SWT.NONE);
                item.setText(new String[] {SymbolAdapter.toString(sym, false), ascii});
                item.setData("nonterminal", sym);
                item.setData("sentence", ascii);
                item.setData("module", module);
                item.setData("project", project);
                item.setData("tree", tree);
              }
            });
  }

  private String getProjectName(String filename) {
    int i = filename.indexOf('/');
    if (i != -1) {
      return filename.substring(0, i);
    }
    return null;
  }

  private String getModuleName(String filename) {
    int i = filename.indexOf('/');
    if (i != -1) {
      return filename.substring(i + 1);
    }
    return null;
  }

  private String toascci(SymbolString s) {
    StringBuilder b = new StringBuilder();
    for (int i = 0; i < s.size(); i++) {
      Character ch = (Character) s.get(i);
      b.append(ch.toAscii());
    }
    return b.toString();
  }

  public static void listAmbiguities(
      final String project,
      final String module,
      final IConstructor parseTree,
      final IProgressMonitor monitor) {
    PlatformUI.getWorkbench()
        .getDisplay()
        .asyncExec(
            new Runnable() {
              @Override
              public void run() {
                try {
                  ReportView part =
                      (ReportView)
                          PlatformUI.getWorkbench()
                              .getActiveWorkbenchWindow()
                              .getActivePage()
                              .showView(ID);

                  part.list(project, module, parseTree, monitor);
                } catch (PartInitException e) {
                  RuntimePlugin.getInstance().logException("could not parse module", e);
                }
              }
            });
  }

  public void list(
      final String project,
      final String module,
      IConstructor parseTree,
      final IProgressMonitor monitor) {
    table.removeAll();

    try {
      parseTree.accept(
          new IdentityTreeVisitor<Exception>() {
            int ambTreesSeen = 0;

            @Override
            public ITree visitTreeAppl(ITree arg) throws Exception {
              if (monitor.isCanceled()) {
                throw new Exception("interrupted");
              }

              monitor.worked(1);

              for (IValue child : TreeAdapter.getArgs(arg)) {
                child.accept(this);
              }
              return arg;
            }

            @Override
            public ITree visitTreeAmb(ITree arg) throws Exception {
              ambTreesSeen++;
              if (ambTreesSeen > 100) {
                throw new RuntimeException(
                    "Lets stop collecting, the user get's the point, it is VERY ambigious");
              }
              IConstructor sym = null;
              String sentence = TreeAdapter.yield(arg);

              for (IValue child : TreeAdapter.getAlternatives(arg)) {
                sym = TreeAdapter.getType((ITree) child);
                child.accept(this);
              }

              addItem(sym, sentence, module, project, arg);
              return arg;
            }
          });
    } catch (Exception e) {
      // do nothing
    }
  }

  @Override
  public void setTaskName(String name, int work) {
    IProgressMonitor m = job.monitor;
    if (m != null) {
      m.beginTask(name, work);
    }
  }

  @Override
  public void worked(int work) {
    IProgressMonitor m = job.monitor;
    if (m != null) {
      m.worked(work);
    }
  }

  @Override
  public boolean canceling() {
    return canceling;
  }

  private class AmbiDexterJob extends Job {

    private Main main;
    volatile IProgressMonitor monitor;

    public AmbiDexterJob(String name) {
      super(name);
    }

    public void init(Grammar grammar, AmbiDexterConfig config) {
      main = new Main(ReportView.this);
      main.setGrammar(grammar);
      main.setConfig(config);
    }

    @Override
    protected IStatus run(IProgressMonitor monitor) {
      this.monitor = monitor;

      // main.printGrammar();
      try {
        main.checkGrammar();
      } catch (OutOfMemoryError e) {
        Activator.log("out of memory while checking grammar for ambiguity", e);
        main = null; // help the GC in this case
        System.gc();
      }

      monitor.done();
      this.monitor = null;
      return Status.OK_STATUS;
    }

    @Override
    protected void canceling() {
      ReportView.this.canceling = true;
    }
  }
}
public class RascalRuntimeException {

  private static TypeFactory TF = TypeFactory.getInstance();
  private static IValueFactory VF = ValueFactoryFactory.getValueFactory();

  public static final TypeStore TS = new TypeStore();
  public static final Type Exception = TF.abstractDataType(TS, "RuntimeException");

  public static final Type StackOverflow = TF.constructor(TS, Exception, "StackOverflow");
  public static final Type IndexOutOfBounds =
      TF.constructor(TS, Exception, "IndexOutOfBounds", TF.integerType(), "index");
  public static final Type AssertionFailed = TF.constructor(TS, Exception, "AssertionFailed");
  public static final Type LabeledAssertionFailed =
      TF.constructor(TS, Exception, "AssertionFailed", TF.stringType(), "label");
  public static final Type EmptyList = TF.constructor(TS, Exception, "EmptyList");
  public static final Type EmptySet = TF.constructor(TS, Exception, "EmptySet");
  public static final Type EmptyMap = TF.constructor(TS, Exception, "EmptyMap");
  public static final Type NoSuchElement =
      TF.constructor(TS, Exception, "NoSuchElement", TF.valueType(), "v");
  public static final Type UnavailableInformation =
      TF.constructor(TS, Exception, "UnavailableInformation", TF.stringType(), "message");
  public static final Type IllegalArgument =
      TF.constructor(
          TS, Exception, "IllegalArgument", TF.valueType(), "v", TF.stringType(), "message");
  public static final Type IllegalTypeArgument =
      TF.constructor(
          TS,
          Exception,
          "IllegalTypeArgument",
          TF.stringType(),
          "type",
          TF.stringType(),
          "message");

  public static final Type AnonymousIllegalArgument =
      TF.constructor(TS, Exception, "IllegalArgument");
  public static final Type IO = TF.constructor(TS, Exception, "IO", TF.stringType(), "message");
  public static final Type PathNotFound =
      TF.constructor(TS, Exception, "PathNotFound", TF.sourceLocationType(), "location");

  public static final Type LocationNotFound =
      TF.constructor(TS, Exception, "LocationNotFound", TF.sourceLocationType(), "location");
  public static final Type PermissionDenied =
      TF.constructor(TS, Exception, "PermissionDenied", TF.stringType(), "message");
  public static final Type AnonymousPermissionDenied =
      TF.constructor(TS, Exception, "PermissionDenied");
  public static final Type ModuleNotFound =
      TF.constructor(TS, Exception, "ModuleNotFound", TF.stringType(), "name");
  public static final Type MultipleKey =
      TF.constructor(TS, Exception, "MultipleKey", TF.valueType(), "key");
  public static final Type NoSuchKey =
      TF.constructor(TS, Exception, "NoSuchKey", TF.valueType(), "key");
  public static final Type NoSuchAnnotation =
      TF.constructor(TS, Exception, "NoSuchAnnotation", TF.stringType(), "label");
  public static final Type NoSuchField =
      TF.constructor(TS, Exception, "NoSuchField", TF.stringType(), "label");
  public static final Type ParseError =
      TF.constructor(TS, Exception, "ParseError", TF.sourceLocationType(), "location");
  public static final Type IllegalIdentifier =
      TF.constructor(TS, Exception, "IllegalIdentifier", TF.stringType(), "name");
  public static final Type IllegalChar =
      TF.constructor(TS, Exception, "IllegalCharacter", TF.integerType(), "character");
  public static final Type SchemeNotSupported =
      TF.constructor(TS, Exception, "SchemeNotSupported", TF.sourceLocationType(), "location");
  public static final Type MalFormedURI =
      TF.constructor(TS, Exception, "MalFormedURI", TF.stringType(), "malFormedUri");
  public static final Type NoParent =
      TF.constructor(TS, Exception, "NoParent", TF.sourceLocationType(), "noParentUri");
  public static final Type NameMismatch =
      TF.constructor(
          TS,
          Exception,
          "NameMismatch",
          TF.stringType(),
          "expectedName",
          TF.stringType(),
          "gotName");
  public static final Type ArityMismatch =
      TF.constructor(
          TS,
          Exception,
          "ArityMismatch",
          TF.integerType(),
          "expectedArity",
          TF.integerType(),
          "gotArity");

  public static final Type Java =
      TF.constructor(TS, Exception, "Java", TF.stringType(), "class", TF.stringType(), "message");
  public static final Type JavaWithCause =
      TF.constructor(
          TS,
          Exception,
          "Java",
          TF.stringType(),
          "class",
          TF.stringType(),
          "message",
          Exception,
          "cause");

  public static final Type Subversion =
      TF.constructor(TS, Exception, "Subversion", TF.stringType(), "message");
  public static final Type JavaBytecodeError =
      TF.constructor(TS, Exception, "JavaBytecodeError", TF.stringType(), "message");

  public static final Type InvalidUseOfDate =
      TF.constructor(TS, Exception, "InvalidUseOfDate", TF.dateTimeType(), "msg");
  public static final Type InvalidUseOfTime =
      TF.constructor(TS, Exception, "InvalidUseOfTime", TF.dateTimeType(), "msg");
  public static final Type InvalidUseOfDateTime =
      TF.constructor(TS, Exception, "InvalidUseOfDateTime", TF.dateTimeType(), "msg");
  public static final Type InvalidUseOfLocation =
      TF.constructor(TS, Exception, "InvalidUseOfLocation", TF.stringType(), "message");
  public static final Type DateTimeParsingError =
      TF.constructor(TS, Exception, "DateTimeParsingError", TF.stringType(), "message");
  public static final Type DateTimePrintingError =
      TF.constructor(TS, Exception, "DateTimePrintingError", TF.stringType(), "message");
  public static final Type Timeout = TF.constructor(TS, Exception, "Timeout");
  public static final Type Figure =
      TF.constructor(TS, Exception, "Figure", TF.stringType(), "message", TF.valueType(), "figure");

  public static final Type ImplodeError =
      TF.constructor(TS, Exception, "ImplodeError", TF.stringType(), "message");

  public static final Type ArithmeticException =
      TF.constructor(TS, Exception, "ArithmeticException", TF.stringType(), "message");

  public static final Type UninitializedVariable =
      TF.constructor(TS, Exception, "UninitializedVariable", TF.stringType(), "name");

  public static final Type NoMainFunction = TF.constructor(TS, Exception, "NoMainFunction");

  public static final Type RegExpSyntaxError =
      TF.constructor(TS, Exception, "RegExpSyntaxError", TF.stringType(), "message");

  public static Thrown arithmeticException(String msg, List<Frame> stacktrace) {
    return Thrown.getInstance(VF.constructor(ArithmeticException, VF.string(msg)), stacktrace);
  }

  public static Thrown assertionFailed(ISourceLocation loc, List<Frame> stacktrace) {
    return Thrown.getInstance(VF.constructor(AssertionFailed), loc, stacktrace);
  }

  public static Thrown assertionFailed(IString msg, ISourceLocation loc, List<Frame> stacktrace) {
    return Thrown.getInstance(VF.constructor(LabeledAssertionFailed, msg), loc, stacktrace);
  }

  public static Thrown emptyList(List<Frame> stacktrace) {
    return Thrown.getInstance(VF.constructor(EmptyList), stacktrace);
  }

  public static Thrown emptySet(List<Frame> stacktrace) {
    return Thrown.getInstance(VF.constructor(EmptySet), stacktrace);
  }

  public static Thrown emptyMap(List<Frame> stacktrace) {
    return Thrown.getInstance(VF.constructor(EmptyMap), stacktrace);
  }

  public static Thrown illegalArgument(List<Frame> stacktrace) {
    return Thrown.getInstance(VF.constructor(AnonymousIllegalArgument), stacktrace);
  }

  public static Thrown illegalArgument(IValue v, List<Frame> stacktrace) {
    return Thrown.getInstance(VF.constructor(IllegalArgument), stacktrace);
  }

  public static Thrown illegalArgument(IValue v, List<Frame> stacktrace, String message) {
    return Thrown.getInstance(VF.constructor(IllegalArgument, v, VF.string(message)), stacktrace);
  }

  public static Thrown indexOutOfBounds(IInteger i, List<Frame> stacktrace) {
    return Thrown.getInstance(VF.constructor(IndexOutOfBounds, i), stacktrace);
  }

  public static Thrown io(IString msg, List<Frame> stacktrace) {
    return Thrown.getInstance(VF.constructor(IO, msg), stacktrace);
  }

  private static Thrown javaException(
      String clazz, String message, IValue cause, ISourceLocation loc, List<Frame> stacktrace) {
    return Thrown.getInstance(
        VF.constructor(Java, VF.string(clazz), VF.string(message), cause), loc, stacktrace);
  }

  private static Thrown javaException(
      String clazz, String message, ISourceLocation loc, List<Frame> stacktrace) {
    return Thrown.getInstance(
        VF.constructor(Java, VF.string(clazz), VF.string(message)), loc, stacktrace);
  }

  public static Thrown javaException(
      Throwable targetException, ISourceLocation loc, List<Frame> stacktrace) throws CompilerError {
    try {
      String clazz = targetException.getClass().getSimpleName();
      String msg = targetException.getMessage();
      List<Frame> trace = buildTrace(targetException, stacktrace);
      Throwable cause = targetException.getCause();

      if (cause != null && cause != targetException) {
        Thrown throwCause =
            cause instanceof Thrown ? (Thrown) cause : javaException(cause, loc, trace);
        return javaException(clazz, msg != null ? msg : "", throwCause.value, loc, trace);
      } else {
        return javaException(clazz, msg != null ? msg : "", loc, trace);
      }
    } catch (IOException e) {
      throw new CompilerError("Could not create stack trace: " + e);
    }
  }

  private static List<Frame> buildTrace(Throwable targetException, List<Frame> stacktrace)
      throws IOException {
    StackTraceElement[] elements = targetException.getStackTrace();
    List<Frame> trace = new ArrayList<Frame>();
    for (StackTraceElement elem : elements) {
      if (elem.getMethodName().equals("invoke")) {
        break;
      }
      Function function =
          new Function(
              elem.getClassName() + "." + elem.getMethodName(),
              null,
              null,
              -1,
              -1,
              null,
              -1,
              null,
              null);
      trace.add(new Frame(-1, null, -1, function));
    }
    trace.addAll(stacktrace);
    return trace;
  }

  //    private static ISourceLocation robustSourceLocation(String path, int offset, int length, int
  // beginLine, int endLine, int beginCol, int endCol) {
  //    	if (path == null) {
  //    		path = "UNKNOWN_FILENAME";
  //    	}
  //    	if (!path.startsWith("/")) {
  //			path = "/" + path;
  //		}
  //    	URI uri = null;
  //		try {
  //			uri = new URI("file", "", path, null);
  //		} catch (URISyntaxException e) {
  //			// TODO Auto-generated catch block
  //		}
  //
  //    	if (offset < 0)
  //    		offset = 0;
  //		if (length < 0)
  //			length = 0;
  //		if (beginLine < 0)
  //			beginLine = 0;
  //		if (beginCol < 0)
  //			beginCol = 0;
  //		if (endCol < 0)
  //			endCol = 0;
  //		if (endLine < beginLine)
  //			endLine = beginLine;
  //		if (endLine == beginLine && endCol < beginCol)
  //			endCol = beginCol;
  //		return VF.sourceLocation(uri, offset, length, beginLine, endLine, beginCol, endCol);
  //    }

  //	public static Thrown moduleNotFound(IString module, ISourceLocation loc, List<Frame>
  // stacktrace) {
  //		return Thrown.getInstance(VF.constructor(ModuleNotFound, module), loc, stacktrace);
  //	}

  public static Thrown noMainFunction(List<Frame> stacktrace) {
    return Thrown.getInstance(VF.constructor(NoMainFunction), stacktrace);
  }

  public static Thrown noSuchAnnotation(String label, List<Frame> stacktrace) {
    return Thrown.getInstance(VF.constructor(NoSuchAnnotation, VF.string(label)), stacktrace);
  }

  public static Thrown noSuchKey(IValue v, List<Frame> stacktrace) {
    return Thrown.getInstance(VF.constructor(NoSuchKey, v), stacktrace);
  }

  public static Thrown parseError(ISourceLocation parseloc, List<Frame> stacktrace) {
    return Thrown.getInstance(VF.constructor(ParseError, parseloc), stacktrace);
  }

  //	public static Thrown pathNotFound(ISourceLocation parseloc, ISourceLocation loc, List<Frame>
  // stacktrace) {
  //		return Thrown.getInstance(VF.constructor(PathNotFound, parseloc), loc, stacktrace);
  //	}

  //	public static Thrown stackOverflow(ISourceLocation loc, List<Frame> stacktrace) {
  //		return Thrown.getInstance(VF.constructor(StackOverflow), loc, stacktrace);
  //	}

  //	public static Thrown arityMismatch(int expected, int got, ISourceLocation loc, List<Frame>
  // stacktrace) {
  //		return Thrown.getInstance(VF.constructor(ArityMismatch, VF.integer(expected),
  // VF.integer(got)), loc, stacktrace);
  //	}

  //	public static Thrown dateTimeParsingError(String message, ISourceLocation loc, List<Frame>
  // stacktrace) {
  //		return Thrown.getInstance(VF.constructor(DateTimeParsingError, VF.string(message)), loc,
  // stacktrace);
  //	}

  //	public static Thrown dateTimePrintingError(String message, ISourceLocation loc, List<Frame>
  // stacktrace) {
  //		return Thrown.getInstance(VF.constructor(DateTimePrintingError, VF.string(message)), loc,
  // stacktrace);
  //	}

  //	public static Thrown figureException(String message, IValue v, ISourceLocation loc, List<Frame>
  // stacktrace) {
  //		return Thrown.getInstance(VF.constructor(Figure, VF.string(message), v), loc, stacktrace);
  //	}

  //	public static Thrown illegalCharacter(IInteger i, ISourceLocation loc, List<Frame> stacktrace)
  // {
  //		return Thrown.getInstance(VF.constructor(IllegalChar, i), loc, stacktrace);
  //	}

  //	public static Thrown illegalTypeArgument(String type, String message, ISourceLocation loc,
  // List<Frame> stacktrace) {
  //		return
  // Thrown.getInstance(VF.constructor(IllegalTypeArgument,VF.string(type),VF.string(message)), loc,
  // stacktrace);
  //	}

  //	public static Thrown illegalTypeArgument(String type, ISourceLocation loc, List<Frame>
  // stacktrace){
  //		return Thrown.getInstance(VF.constructor(IllegalTypeArgument,VF.string(type)), loc,
  // stacktrace);
  //	}

  //	public static Thrown implodeError(String msg, ISourceLocation loc, List<Frame> stacktrace) {
  //		return Thrown.getInstance(VF.constructor(ImplodeError, VF.string(msg)), loc, stacktrace);
  //	}

  public static Thrown invalidUseOfLocation(String msg, List<Frame> stacktrace) {
    return Thrown.getInstance(VF.constructor(InvalidUseOfLocation, VF.string(msg)), stacktrace);
  }

  public static Thrown invalidUseOfDateException(String message, List<Frame> stacktrace) {
    return Thrown.getInstance(VF.constructor(InvalidUseOfDate, VF.string(message)), stacktrace);
  }

  public static Thrown invalidUseOfTimeException(String message, List<Frame> stacktrace) {
    return Thrown.getInstance(VF.constructor(InvalidUseOfTime, VF.string(message)), stacktrace);
  }

  public static Thrown invalidUseOfDateTimeException(String message, List<Frame> stacktrace) {
    return Thrown.getInstance(VF.constructor(InvalidUseOfDateTime, VF.string(message)), stacktrace);
  }

  public static Thrown malformedURI(String uri, List<Frame> stacktrace) {
    return Thrown.getInstance(VF.constructor(MalFormedURI, VF.string(uri)), stacktrace);
  }

  //	public static Thrown MultipleKey(IValue v, ISourceLocation loc, List<Frame> stacktrace) {
  //		return Thrown.getInstance(VF.constructor(MultipleKey, v), loc, stacktrace);
  //	}

  //	public static Thrown nameMismatch(String expected, String got, ISourceLocation loc, List<Frame>
  // stacktrace) {
  //		return Thrown.getInstance(VF.constructor(NameMismatch, VF.string(expected), VF.string(got)),
  // loc, stacktrace);
  //	}

  public static Thrown noParent(ISourceLocation noparentloc, List<Frame> stacktrace) {
    return Thrown.getInstance(VF.constructor(NoParent, noparentloc), stacktrace);
  }

  //	public static Thrown noSuchElement(IValue v, ISourceLocation loc, List<Frame> stacktrace) {
  //		return Thrown.getInstance(VF.constructor(NoSuchElement,v), loc, stacktrace);
  //	}

  public static Thrown noSuchField(String name, List<Frame> stacktrace) {
    return Thrown.getInstance(VF.constructor(NoSuchField, VF.string(name)), stacktrace);
  }

  //	public static Thrown permissionDenied(ISourceLocation loc, List<Frame> stacktrace) {
  //		return Thrown.getInstance(VF.constructor(AnonymousPermissionDenied), loc, stacktrace);
  //	}

  //	public static Thrown permissionDenied(IString msg, ISourceLocation loc, List<Frame> stacktrace)
  // {
  //		return Thrown.getInstance(VF.constructor(PermissionDenied, msg), loc, stacktrace);
  //	}

  public static Thrown unavailableInformation(String message, List<Frame> stacktrace) {
    return Thrown.getInstance(
        VF.constructor(UnavailableInformation, VF.string(message)), stacktrace);
  }

  //	public static Thrown schemeNotSupported(ISourceLocation file, ISourceLocation loc, List<Frame>
  // stacktrace) {
  //		return Thrown.getInstance(VF.constructor(SchemeNotSupported, file), loc, stacktrace);
  //	}

  //	public static Thrown timeout(ISourceLocation loc, List<Frame> stacktrace) {
  //    	return Thrown.getInstance(VF.constructor(Timeout), loc, stacktrace);
  //    }

  public static Thrown uninitializedVariable(String name, List<Frame> stacktrace) {
    return Thrown.getInstance(VF.constructor(UninitializedVariable, VF.string(name)), stacktrace);
  }

  public static Thrown RegExpSyntaxError(String message, List<Frame> stacktrace) {
    return Thrown.getInstance(VF.constructor(RegExpSyntaxError, VF.string(message)), stacktrace);
  }
}
 public static Object loadWithRascal(Reader rdr, String sourcePath, String sourceName) {
   IValueFactory vf = ValueFactoryFactory.getValueFactory();
   UPTRCompiler c = new UPTRCompiler(vf, null);
   return c.load2(rdr, sourcePath, sourceName);
 }
Exemplo n.º 14
0
/** Auxiliary class to read and represent records in the file. */
class Record implements Iterable<String> {
  private static final TypeFactory types = TypeFactory.getInstance();
  private static final IValueFactory values = ValueFactoryFactory.getValueFactory();
  ArrayList<IValue> rfields = new ArrayList<IValue>();
  ArrayList<Type> fieldTypes = new ArrayList<Type>();

  /**
   * Create a record by reader all its fields using reader
   *
   * @param reader to be used.
   * @throws IOException
   */
  Record(FieldReader reader) throws IOException {

    while (reader.hasField()) {
      String field = reader.getField();
      // System.err.print("field = " + field);

      if (field.isEmpty()) {
        rfields.add(null);
        fieldTypes.add(types.voidType());
        // System.err.println(" void");
      } else if (field.matches("^[+-]?[0-9]+$")) {
        rfields.add(values.integer(field));
        fieldTypes.add(types.integerType());
        // System.err.println(" int");
      } else if (field.matches("[+-]?[0-9]+\\.[0-9]*")) {
        rfields.add(values.real(field));
        fieldTypes.add(types.realType());
        // System.err.println(" real");
      } else if (field.equals("true") || field.equals("false")) {
        rfields.add(values.bool(field.equals("true")));
        fieldTypes.add(types.boolType());
        // System.err.println(" bool");
      } else {
        rfields.add(values.string(field));
        fieldTypes.add(types.stringType());
        // System.err.println(" str");
      }
    }
  }

  /** @return the type of this record. */
  Type getType() {
    Type[] typeArray = new Type[rfields.size()];
    for (int i = 0; i < rfields.size(); i++) {
      if (rfields.get(i) == null) {
        typeArray[i] = types.voidType();
      } else {
        typeArray[i] = rfields.get(i).getType();
      }
    }
    return types.tupleType(typeArray);
  }

  /** @return a list of the types of the fields of this record. */
  ArrayList<Type> getFieldTypes() {
    return fieldTypes;
  }

  int getWidth() {
    return fieldTypes.size();
  }

  /**
   * @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);
  }

  @Override
  public Iterator<String> iterator() {
    return new Iterator<String>() {
      private final Iterator<IValue> iter = rfields.iterator();

      @Override
      public boolean hasNext() {
        return iter.hasNext();
      }

      @Override
      public String next() {
        IValue x = iter.next();
        if (x == null) {
          return "";
        }
        return x + "";
      }

      @Override
      public void remove() {
        throw new UnsupportedOperationException();
      }
    };
  }
}
Exemplo n.º 15
0
/**
 * 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;
  }
}
Exemplo n.º 16
0
public abstract class JavaToRascalConverter extends ASTVisitor {
  protected static final IValueFactory values = ValueFactoryFactory.getValueFactory();
  protected static final TypeFactory TF = TypeFactory.getInstance();

  protected final TypeStore typeStore;

  protected IValue ownValue;
  private static final String DATATYPE_RASCAL_AST_TYPE_NODE = "Type";
  private static final String DATATYPE_RASCAL_AST_MODIFIER_NODE = "Modifier";
  private static final String DATATYPE_RASCAL_AST_DECLARATION_NODE = "Declaration";
  private static final String DATATYPE_RASCAL_AST_EXPRESSION_NODE = "Expression";
  private static final String DATATYPE_RASCAL_AST_STATEMENT_NODE = "Statement";
  private static final String DATATYPE_RASCAL_MESSAGE = "Message";
  private static final String DATATYPE_RASCAL_MESSAGE_ERROR = "error";

  private final org.rascalmpl.value.type.Type DATATYPE_RASCAL_AST_DECLARATION_NODE_TYPE;
  private final org.rascalmpl.value.type.Type DATATYPE_RASCAL_AST_EXPRESSION_NODE_TYPE;
  private final org.rascalmpl.value.type.Type DATATYPE_RASCAL_AST_STATEMENT_NODE_TYPE;
  protected static org.rascalmpl.value.type.Type DATATYPE_RASCAL_AST_TYPE_NODE_TYPE;
  protected static org.rascalmpl.value.type.Type DATATYPE_RASCAL_AST_MODIFIER_NODE_TYPE;
  protected static org.rascalmpl.value.type.Type DATATYPE_RASCAL_MESSAGE_DATA_TYPE;
  protected static org.rascalmpl.value.type.Type DATATYPE_RASCAL_MESSAGE_ERROR_NODE_TYPE;

  protected CompilationUnit compilUnit;
  protected ISourceLocation loc;

  protected final BindingsResolver bindingsResolver;
  protected final boolean collectBindings;

  protected IListWriter messages;
  protected final Map<String, ISourceLocation> locationCache;

  JavaToRascalConverter(
      final TypeStore typeStore, Map<String, ISourceLocation> cache, boolean collectBindings) {
    super(true);
    this.typeStore = typeStore;
    this.bindingsResolver = new BindingsResolver(typeStore, cache, collectBindings);
    this.collectBindings = collectBindings;
    DATATYPE_RASCAL_AST_TYPE_NODE_TYPE =
        this.typeStore.lookupAbstractDataType(DATATYPE_RASCAL_AST_TYPE_NODE);
    DATATYPE_RASCAL_AST_MODIFIER_NODE_TYPE =
        this.typeStore.lookupAbstractDataType(DATATYPE_RASCAL_AST_MODIFIER_NODE);
    this.DATATYPE_RASCAL_AST_DECLARATION_NODE_TYPE =
        typeStore.lookupAbstractDataType(DATATYPE_RASCAL_AST_DECLARATION_NODE);
    this.DATATYPE_RASCAL_AST_EXPRESSION_NODE_TYPE =
        typeStore.lookupAbstractDataType(DATATYPE_RASCAL_AST_EXPRESSION_NODE);
    this.DATATYPE_RASCAL_AST_STATEMENT_NODE_TYPE =
        typeStore.lookupAbstractDataType(DATATYPE_RASCAL_AST_STATEMENT_NODE);
    JavaToRascalConverter.DATATYPE_RASCAL_MESSAGE_DATA_TYPE =
        typeStore.lookupAbstractDataType(DATATYPE_RASCAL_MESSAGE);
    JavaToRascalConverter.DATATYPE_RASCAL_MESSAGE_ERROR_NODE_TYPE =
        typeStore
            .lookupConstructor(DATATYPE_RASCAL_MESSAGE_DATA_TYPE, DATATYPE_RASCAL_MESSAGE_ERROR)
            .iterator()
            .next();
    this.locationCache = cache;

    messages = values.listWriter();
  }

  protected ISourceLocation resolveBinding(String packageComponent) {
    ISourceLocation packageBinding =
        new BindingsResolver(typeStore, locationCache, this.collectBindings) {
          public ISourceLocation resolveBinding(String packageC) {
            try {
              if (collectBindings) {
                if (locationCache.containsKey(packageC)) {
                  return locationCache.get(packageC);
                }
                return values.sourceLocation("java+package", null, packageC);
              }
              return values.sourceLocation("unknown", null, null);
            } catch (URISyntaxException e) {
              throw new RuntimeException("Should not happen", e);
            }
          }
        }.resolveBinding(packageComponent);
    locationCache.put(packageComponent, packageBinding);
    return packageBinding;
  }

  protected ISourceLocation resolveBinding(CompilationUnit node) {
    ISourceLocation compilationUnit =
        new BindingsResolver(typeStore, locationCache, true) {
          public ISourceLocation resolveBinding(CompilationUnit node) {
            return makeBinding("java+compilationUnit", null, loc.getPath());
          }
        }.resolveBinding(node);

    return compilationUnit;
  }

  protected ISourceLocation resolveBinding(IBinding binding) {
    ISourceLocation resolvedBinding = bindingsResolver.resolveBinding(binding);
    if (binding != null) locationCache.put(binding.getKey(), resolvedBinding);
    return resolvedBinding;
  }

  protected ISourceLocation resolveDeclaringClass(IBinding binding) {
    ISourceLocation resolvedBinding;
    if (binding instanceof ITypeBinding) {
      resolvedBinding =
          bindingsResolver.resolveBinding(((ITypeBinding) binding).getDeclaringClass());
    } else if (binding instanceof IMethodBinding) {
      resolvedBinding =
          bindingsResolver.resolveBinding(((IMethodBinding) binding).getDeclaringClass());
    } else if (binding instanceof IVariableBinding) {
      resolvedBinding =
          bindingsResolver.resolveBinding(((IVariableBinding) binding).getDeclaringClass());
    } else {
      binding = null;
      resolvedBinding = bindingsResolver.resolveBinding(binding);
    }
    return resolvedBinding;
  }

  protected ISourceLocation resolveBinding(ASTNode node) {
    if (node instanceof CompilationUnit) {
      return resolveBinding((CompilationUnit) node);
    }
    return bindingsResolver.resolveBinding(node);
  }

  protected ISourceLocation getSourceLocation(ASTNode node) {
    try {
      int nodeLength = compilUnit.getExtendedLength(node);

      if (nodeLength > 0) {
        int start = compilUnit.getExtendedStartPosition(node);
        int end = start + nodeLength - 1;

        if (end < start && ((node.getFlags() & 9) > 0)) {
          insert(
              messages,
              values.constructor(
                  DATATYPE_RASCAL_MESSAGE_ERROR_NODE_TYPE,
                  values.string("Recovered/Malformed node, guessing the length"),
                  values.sourceLocation(loc, 0, 0)));

          nodeLength = node.toString().length();
          end = start + nodeLength - 1;
        }

        return values.sourceLocation(
            loc,
            start,
            nodeLength,
            compilUnit.getLineNumber(start),
            compilUnit.getLineNumber(end),
            // TODO: only adding 1 at the end seems to work, need to test.
            compilUnit.getColumnNumber(start),
            compilUnit.getColumnNumber(end) + 1);
      }
    } catch (IllegalArgumentException e) {
      insert(
          messages,
          values.constructor(
              DATATYPE_RASCAL_MESSAGE_ERROR_NODE_TYPE,
              values.string("Most probably missing dependency"),
              values.sourceLocation(loc, 0, 0)));
    }
    return values.sourceLocation(loc, 0, 0, 0, 0, 0, 0);
  }

  protected IValue[] removeNulls(IValue... withNulls) {
    List<IValue> withOutNulls = new ArrayList<IValue>();
    for (IValue child : withNulls) {
      if (!(child == null)) {
        withOutNulls.add(child);
      }
    }
    return withOutNulls.toArray(new IValue[withOutNulls.size()]);
  }

  protected IValueList parseModifiers(int modifiers) {
    IValueList extendedModifierList = new IValueList(values);

    for (String constructor : java.lang.reflect.Modifier.toString(modifiers).split(" ")) {
      Set<org.rascalmpl.value.type.Type> exConstr =
          typeStore.lookupConstructor(DATATYPE_RASCAL_AST_MODIFIER_NODE_TYPE, constructor);
      for (org.rascalmpl.value.type.Type con : exConstr) {
        extendedModifierList.add(values.constructor(con));
      }
    }

    return extendedModifierList;
  }

  @SuppressWarnings({"rawtypes"})
  protected IValueList parseExtendedModifiers(List ext) {
    IValueList extendedModifierList = new IValueList(values);

    for (Iterator it = ext.iterator(); it.hasNext(); ) {
      ASTNode p = (ASTNode) it.next();
      IValue val = visitChild(p);
      if (p instanceof Annotation) {
        val = constructModifierNode("annotation", val);
      }
      extendedModifierList.add(val);
    }
    return extendedModifierList;
  }

  @SuppressWarnings("deprecation")
  protected IValueList parseExtendedModifiers(BodyDeclaration node) {
    if (node.getAST().apiLevel() == AST.JLS2) {
      return parseModifiers(node.getModifiers());
    } else {
      return parseExtendedModifiers(node.modifiers());
    }
  }

  protected IValue visitChild(ASTNode node) {
    node.accept(this);
    return this.getValue();
  }

  public IValue getValue() {
    return this.ownValue;
  }

  protected IConstructor constructModifierNode(String constructor, IValue... children) {
    org.rascalmpl.value.type.Type args = TF.tupleType(removeNulls(children));
    org.rascalmpl.value.type.Type constr =
        typeStore.lookupConstructor(DATATYPE_RASCAL_AST_MODIFIER_NODE_TYPE, constructor, args);
    return values.constructor(constr, removeNulls(children));
  }

  protected void setAnnotation(String annoName, IValue annoValue) {
    if (this.ownValue == null) {
      return;
    }
    if (annoValue != null && ownValue.getType().declaresAnnotation(this.typeStore, annoName)) {
      ownValue = ((IConstructor) ownValue).asAnnotatable().setAnnotation(annoName, annoValue);
    }
  }

  protected void setAnnotation(String annoName, IValueList annoList) {
    IList annos = (IList) annoList.asList();
    if (this.ownValue == null) {
      return;
    }
    if (annoList != null
        && this.ownValue.getType().declaresAnnotation(this.typeStore, annoName)
        && !annos.isEmpty()) {
      this.ownValue = ((IConstructor) this.ownValue).asAnnotatable().setAnnotation(annoName, annos);
    }
  }

  protected IValue constructDeclarationNode(String constructor, IValue... children) {
    org.rascalmpl.value.type.Type args = TF.tupleType(removeNulls(children));
    org.rascalmpl.value.type.Type constr =
        typeStore.lookupConstructor(DATATYPE_RASCAL_AST_DECLARATION_NODE_TYPE, constructor, args);
    return values.constructor(constr, removeNulls(children));
  }

  protected IValue constructExpressionNode(String constructor, IValue... children) {
    org.rascalmpl.value.type.Type args = TF.tupleType(removeNulls(children));
    org.rascalmpl.value.type.Type constr =
        typeStore.lookupConstructor(DATATYPE_RASCAL_AST_EXPRESSION_NODE_TYPE, constructor, args);
    return values.constructor(constr, removeNulls(children));
  }

  protected IValue constructStatementNode(String constructor, IValue... children) {
    org.rascalmpl.value.type.Type args = TF.tupleType(removeNulls(children));
    org.rascalmpl.value.type.Type constr =
        typeStore.lookupConstructor(DATATYPE_RASCAL_AST_STATEMENT_NODE_TYPE, constructor, args);
    return values.constructor(constr, removeNulls(children));
  }

  protected IValue constructTypeNode(String constructor, IValue... children) {
    org.rascalmpl.value.type.Type args = TF.tupleType(removeNulls(children));
    org.rascalmpl.value.type.Type constr =
        typeStore.lookupConstructor(DATATYPE_RASCAL_AST_TYPE_NODE_TYPE, constructor, args);
    return values.constructor(constr, removeNulls(children));
  }

  protected void insertCompilationUnitMessages(boolean insertErrors, IList otherMessages) {
    org.rascalmpl.value.type.Type args = TF.tupleType(TF.stringType(), TF.sourceLocationType());

    IValueList result = new IValueList(values);

    if (otherMessages != null) {
      for (IValue message : otherMessages) {
        result.add(message);
      }
    }

    if (insertErrors) {
      int i;

      IProblem[] problems = compilUnit.getProblems();
      for (i = 0; i < problems.length; i++) {
        int offset = problems[i].getSourceStart();
        int length = problems[i].getSourceEnd() - offset + 1;
        int sl = problems[i].getSourceLineNumber();
        ISourceLocation pos = values.sourceLocation(loc, offset, length, sl, sl, 0, 0);
        org.rascalmpl.value.type.Type constr;
        if (problems[i].isError()) {
          constr =
              typeStore.lookupConstructor(
                  this.typeStore.lookupAbstractDataType("Message"), "error", args);
        } else {
          constr =
              typeStore.lookupConstructor(
                  this.typeStore.lookupAbstractDataType("Message"), "warning", args);
        }
        result.add(values.constructor(constr, values.string(problems[i].getMessage()), pos));
      }
    }
    setAnnotation("messages", result.asList());
  }

  public void insert(IListWriter listW, IValue message) {
    if (message.getType().isConstructor()
        && message.getType().getAbstractDataType().getName().equals("Message")) {
      listW.insert(message);
    }
  }

  public void convert(CompilationUnit root, ASTNode node, ISourceLocation loc) {
    this.compilUnit = root;
    this.loc = loc;
    node.accept(this);
  }
}
Exemplo n.º 17
0
public abstract class BaseRascalREPL extends BaseREPL {
  protected enum State {
    FRESH,
    CONTINUATION,
    DEBUG,
    DEBUG_CONTINUATION
  }

  private State currentState = State.FRESH;

  protected State getState() {
    return currentState;
  }

  private static final int LINE_LIMIT = 200;
  private static final int CHAR_LIMIT = LINE_LIMIT * 20;
  protected String currentPrompt = ReadEvalPrintDialogMessages.PROMPT;
  private StringBuffer currentCommand;
  private final StandardTextWriter indentedPrettyPrinter;
  private final StandardTextWriter singleLinePrettyPrinter;
  private static final IValueFactory VF = ValueFactoryFactory.getValueFactory();

  public BaseRascalREPL(
      InputStream stdin,
      OutputStream stdout,
      boolean prettyPrompt,
      boolean allowColors,
      File persistentHistory,
      Terminal terminal)
      throws IOException {
    super(stdin, stdout, prettyPrompt, allowColors, persistentHistory, terminal);
    if (terminal.isAnsiSupported() && allowColors) {
      indentedPrettyPrinter = new ReplTextWriter();
      singleLinePrettyPrinter = new ReplTextWriter(false);
    } else {
      indentedPrettyPrinter = new StandardTextWriter();
      singleLinePrettyPrinter = new StandardTextWriter(false);
    }
  }

  @Override
  protected String getPrompt() {
    return currentPrompt;
  }

  @Override
  protected void handleInput(String line) throws InterruptedException {
    assert line != null;

    try {
      if (line.trim().length() == 0) {
        // cancel command
        getErrorWriter().println(ReadEvalPrintDialogMessages.CANCELLED);
        currentPrompt = ReadEvalPrintDialogMessages.PROMPT;
        currentCommand = null;
        currentState = State.FRESH;
        return;
      }
      if (currentCommand == null) {
        // we are still at a new command so let's see if the line is a full command
        if (isStatementComplete(line)) {
          printResult(evalStatement(line, line));
        } else {
          currentCommand = new StringBuffer(line);
          currentPrompt = ReadEvalPrintDialogMessages.CONTINUE_PROMPT;
          currentState = State.CONTINUATION;
          return;
        }
      } else {
        currentCommand.append('\n');
        currentCommand.append(line);
        if (isStatementComplete(currentCommand.toString())) {
          printResult(evalStatement(currentCommand.toString(), line));
          currentPrompt = ReadEvalPrintDialogMessages.PROMPT;
          currentCommand = null;
          currentState = State.FRESH;
          return;
        }
      }
    } catch (IOException ie) {
      throw new RuntimeException(ie);
    }
  }

  @Override
  protected void handleReset() throws InterruptedException {
    handleInput("");
  }

  private void printResult(IRascalResult result) throws IOException {
    if (result == null) {
      return;
    }
    PrintWriter out = getOutputWriter();
    IValue value = result.getValue();
    if (value == null) {
      out.println("ok");
      out.flush();
      return;
    }
    Type type = result.getType();

    if (type.isAbstractData() && type.isStrictSubtypeOf(RascalValueFactory.Tree)) {
      out.print(type.toString());
      out.print(": ");
      // we unparse the tree
      out.print("(" + type.toString() + ") `");
      TreeAdapter.yield((IConstructor) result.getValue(), true, out);
      out.print("`");
    } else {
      out.print(type.toString());
      out.print(": ");
      // limit both the lines and the characters
      try (Writer wrt = new LimitedWriter(new LimitedLineWriter(out, LINE_LIMIT), CHAR_LIMIT)) {
        indentedPrettyPrinter.write(value, wrt);
      } catch (IOLimitReachedException e) {
        // ignore since this is what we wanted
      }
    }
    out.println();
    out.flush();
  }

  protected abstract PrintWriter getErrorWriter();

  protected abstract PrintWriter getOutputWriter();

  protected abstract boolean isStatementComplete(String command);

  protected abstract IRascalResult evalStatement(String statement, String lastLine)
      throws InterruptedException;

  /**
   * provide which :set flags (:set profiling true for example)
   *
   * @return strings that can be set
   */
  protected abstract SortedSet<String> getCommandLineOptions();

  protected abstract Collection<String> completePartialIdentifier(
      String line, int cursor, String qualifier, String identifier);

  protected abstract Collection<String> completeModule(String qualifier, String partialModuleName);

  protected boolean isREPLCommand(String line) {
    return line.startsWith(":");
  }

  @Override
  protected CompletionResult completeFragment(String line, int cursor) {
    if (currentState == State.FRESH) {
      String trimmedLine = line.trim();
      if (isREPLCommand(trimmedLine)) {
        return completeREPLCommand(line, cursor);
      }
      if (trimmedLine.startsWith("import ") || trimmedLine.startsWith("extend ")) {
        return completeModule(line, cursor);
      }
    }
    int locationStart = StringUtils.findRascalLocationStart(line, cursor);
    if (locationStart != -1) {
      return completeLocation(line, locationStart);
    }
    return completeIdentifier(line, cursor);
  }

  protected CompletionResult completeIdentifier(String line, int cursor) {
    OffsetLengthTerm identifier = StringUtils.findRascalIdentifierAtOffset(line, cursor);
    if (identifier != null) {
      String[] qualified = StringUtils.splitQualifiedName(unescapeKeywords(identifier.term));
      String qualifier = qualified.length == 2 ? qualified[0] : "";
      String qualifee = qualified.length == 2 ? qualified[1] : qualified[0];
      Collection<String> suggestions = completePartialIdentifier(line, cursor, qualifier, qualifee);
      if (suggestions != null && !suggestions.isEmpty()) {
        return new CompletionResult(identifier.offset, escapeKeywords(suggestions));
      }
    }
    return null;
  }

  private static final Pattern splitIdentifiers = Pattern.compile("[:][:]");

  private static Collection<String> escapeKeywords(Collection<String> suggestions) {
    return suggestions
        .stream()
        .map(
            s ->
                splitIdentifiers
                    .splitAsStream(s + " ") // add space such that the ending "::" is not lost
                    .map(BaseRascalREPL::escapeKeyword)
                    .collect(Collectors.joining("::"))
                    .trim())
        .collect(Collectors.toList());
  }

  private static String unescapeKeywords(String term) {
    return splitIdentifiers
        .splitAsStream(term + " ") // add space such that the ending "::" is not lost
        .map(BaseRascalREPL::unescapeKeyword)
        .collect(Collectors.joining("::"))
        .trim();
  }

  private static final Set<String> RASCAL_KEYWORDS = new HashSet<String>();

  private static void assureKeywordsAreScrapped() {
    if (RASCAL_KEYWORDS.isEmpty()) {
      synchronized (RASCAL_KEYWORDS) {
        if (!RASCAL_KEYWORDS.isEmpty()) {
          return;
        }

        String rascalGrammar = "";
        try (Reader grammarReader =
            URIResolverRegistry.getInstance()
                .getCharacterReader(
                    ValueFactoryFactory.getValueFactory()
                        .sourceLocation("std", "", "/lang/rascal/syntax/Rascal.rsc"))) {
          StringBuilder res = new StringBuilder();
          char[] chunk = new char[8 * 1024];
          int read;
          while ((read = grammarReader.read(chunk, 0, chunk.length)) != -1) {
            res.append(chunk, 0, read);
          }
          rascalGrammar = res.toString();
        } catch (IOException | URISyntaxException e) {
          e.printStackTrace();
        }
        if (!rascalGrammar.isEmpty()) {
          /*
           * keyword RascalKeywords
           * = "o"
           * | "syntax"
           * | "keyword"
           * | "lexical"
           * ...
           * ;
           */
          Pattern findKeywordSection =
              Pattern.compile(
                  "^\\s*keyword([^=]|\\s)*=(?<keywords>([^;]|\\s)*);", Pattern.MULTILINE);
          Matcher m = findKeywordSection.matcher(rascalGrammar);
          if (m.find()) {
            String keywords = "|" + m.group("keywords");
            Pattern keywordEntry = Pattern.compile("\\s*[|]\\s*[\"](?<keyword>[^\"]*)[\"]");
            m = keywordEntry.matcher(keywords);
            while (m.find()) {
              RASCAL_KEYWORDS.add(m.group("keyword"));
            }
          }
          /*
           * syntax BasicType
          = \value: "value"
          | \loc: "loc"
          | \node: "node"
           */
          Pattern findBasicTypeSection =
              Pattern.compile(
                  "^\\s*syntax\\s*BasicType([^=]|\\s)*=(?<keywords>([^;]|\\s)*);",
                  Pattern.MULTILINE);
          m = findBasicTypeSection.matcher(rascalGrammar);
          if (m.find()) {
            String keywords = "|" + m.group("keywords");
            Pattern keywordEntry = Pattern.compile("\\s*[|][^:]*:\\s*[\"](?<keyword>[^\"]*)[\"]");
            m = keywordEntry.matcher(keywords);
            while (m.find()) {
              RASCAL_KEYWORDS.add(m.group("keyword"));
            }
          }
        }
        if (RASCAL_KEYWORDS.isEmpty()) {
          RASCAL_KEYWORDS.add("syntax");
        }
      }
    }
  }

  private static String escapeKeyword(String s) {
    assureKeywordsAreScrapped();
    if (RASCAL_KEYWORDS.contains(s)) {
      return "\\" + s;
    }
    return s;
  }

  private static String unescapeKeyword(String s) {
    assureKeywordsAreScrapped();
    if (s.startsWith("\\") && !s.contains("-")) {
      return s.substring(1);
    }
    return s;
  }

  @Override
  protected boolean supportsCompletion() {
    return true;
  }

  @Override
  protected boolean printSpaceAfterFullCompletion() {
    return false;
  }

  private CompletionResult completeLocation(String line, int locationStart) {
    int locationEnd = StringUtils.findRascalLocationEnd(line, locationStart);
    try {
      String locCandidate = line.substring(locationStart + 1, locationEnd + 1);
      if (!locCandidate.contains("://")) {
        return null;
      }
      ISourceLocation directory = VF.sourceLocation(new URI(locCandidate));
      String fileName = "";
      URIResolverRegistry reg = URIResolverRegistry.getInstance();
      if (!reg.isDirectory(directory)) {
        // split filename and directory
        String fullPath = directory.getPath();
        int lastSeparator = fullPath.lastIndexOf('/');
        fileName = fullPath.substring(lastSeparator + 1);
        fullPath = fullPath.substring(0, lastSeparator);
        directory = VF.sourceLocation(directory.getScheme(), directory.getAuthority(), fullPath);
        if (!reg.isDirectory(directory)) {
          return null;
        }
      }
      String[] filesInPath = reg.listEntries(directory);
      URI directoryURI = directory.getURI();
      Set<String> result = new TreeSet<>(); // sort it up
      for (String currentFile : filesInPath) {
        if (currentFile.startsWith(fileName)) {
          URI currentDir = URIUtil.getChildURI(directoryURI, currentFile);
          boolean isDirectory = reg.isDirectory(VF.sourceLocation(currentDir));
          result.add(currentDir.toString() + (isDirectory ? "/" : "|"));
        }
      }
      if (result.size() > 0) {
        return new CompletionResult(locationStart + 1, result);
      }
      return null;
    } catch (URISyntaxException | IOException e) {
      return null;
    }
  }

  protected CompletionResult completeModule(String line, int cursor) {
    OffsetLengthTerm identifier = StringUtils.findRascalIdentifierAtOffset(line, line.length());
    if (identifier != null) {
      String[] qualified = StringUtils.splitQualifiedName(unescapeKeywords(identifier.term));
      String qualifier = qualified.length == 2 ? qualified[0] : "";
      String qualifee = qualified.length == 2 ? qualified[1] : qualified[0];
      Collection<String> suggestions = completeModule(qualifier, qualifee);
      if (suggestions != null && !suggestions.isEmpty()) {
        return new CompletionResult(identifier.offset, escapeKeywords(suggestions));
      }
    }
    return null;
  }

  protected CompletionResult completeREPLCommand(String line, int cursor) {
    return RascalCommandCompletion.complete(
        line,
        cursor,
        getCommandLineOptions(),
        (l, i) -> completeIdentifier(l, i),
        (l, i) -> completeModule(l, i));
  }
}
Exemplo n.º 18
0
  private static void assureKeywordsAreScrapped() {
    if (RASCAL_KEYWORDS.isEmpty()) {
      synchronized (RASCAL_KEYWORDS) {
        if (!RASCAL_KEYWORDS.isEmpty()) {
          return;
        }

        String rascalGrammar = "";
        try (Reader grammarReader =
            URIResolverRegistry.getInstance()
                .getCharacterReader(
                    ValueFactoryFactory.getValueFactory()
                        .sourceLocation("std", "", "/lang/rascal/syntax/Rascal.rsc"))) {
          StringBuilder res = new StringBuilder();
          char[] chunk = new char[8 * 1024];
          int read;
          while ((read = grammarReader.read(chunk, 0, chunk.length)) != -1) {
            res.append(chunk, 0, read);
          }
          rascalGrammar = res.toString();
        } catch (IOException | URISyntaxException e) {
          e.printStackTrace();
        }
        if (!rascalGrammar.isEmpty()) {
          /*
           * keyword RascalKeywords
           * = "o"
           * | "syntax"
           * | "keyword"
           * | "lexical"
           * ...
           * ;
           */
          Pattern findKeywordSection =
              Pattern.compile(
                  "^\\s*keyword([^=]|\\s)*=(?<keywords>([^;]|\\s)*);", Pattern.MULTILINE);
          Matcher m = findKeywordSection.matcher(rascalGrammar);
          if (m.find()) {
            String keywords = "|" + m.group("keywords");
            Pattern keywordEntry = Pattern.compile("\\s*[|]\\s*[\"](?<keyword>[^\"]*)[\"]");
            m = keywordEntry.matcher(keywords);
            while (m.find()) {
              RASCAL_KEYWORDS.add(m.group("keyword"));
            }
          }
          /*
           * syntax BasicType
          = \value: "value"
          | \loc: "loc"
          | \node: "node"
           */
          Pattern findBasicTypeSection =
              Pattern.compile(
                  "^\\s*syntax\\s*BasicType([^=]|\\s)*=(?<keywords>([^;]|\\s)*);",
                  Pattern.MULTILINE);
          m = findBasicTypeSection.matcher(rascalGrammar);
          if (m.find()) {
            String keywords = "|" + m.group("keywords");
            Pattern keywordEntry = Pattern.compile("\\s*[|][^:]*:\\s*[\"](?<keyword>[^\"]*)[\"]");
            m = keywordEntry.matcher(keywords);
            while (m.find()) {
              RASCAL_KEYWORDS.add(m.group("keyword"));
            }
          }
        }
        if (RASCAL_KEYWORDS.isEmpty()) {
          RASCAL_KEYWORDS.add("syntax");
        }
      }
    }
  }
Exemplo n.º 19
0
public class JavaToRascal {

  private GlobalEnvironment heap = new GlobalEnvironment();

  private final Evaluator evaluator;

  protected static final IValueFactory vf = ValueFactoryFactory.getValueFactory();

  protected static final TypeFactory TF = TypeFactory.getInstance();

  private static final Hashtable<String, Type> toType =
      new Hashtable<String, Type>() {
        private static final long serialVersionUID = 1L;

        {
          put("str", TF.stringType());
          put("int", TF.integerType());
          put("void", TF.voidType());
          put("real", TF.realType());
          put("rational", TF.rationalType());
          put("num", TF.numberType());
        }
      };

  public Evaluator getEvaluator() {
    return evaluator;
  }

  public JavaToRascal(PrintWriter stdout, PrintWriter stderr) {
    this.evaluator =
        new Evaluator(
            vf, stderr, stdout, new ModuleEnvironment(ModuleEnvironment.SHELL_MODULE, heap), heap);
  }

  public JavaToRascal(Evaluator evaluator) {
    this.evaluator = evaluator;
  }

  public Object callJava(String name, Object... args) {
    IValue[] vals = new IValue[args.length];
    for (int i = 0; i < args.length; i++) vals[i] = rascalObject(args[i]);
    return javaObject(evaluator.call(name, vals));
  }

  public IValue call(String name, IValue... args) {
    return evaluator.call(name, args);
  }

  public void voidValue(String command, String location) {
    evaluator.eval(null, command, URIUtil.assumeCorrect(location));
  }

  /**
   * Evaluates Rascal Command without returning a result.
   *
   * @param command Rascal command.
   */
  public void voidValue(String command) {
    voidValue(command, "stdin");
  }

  public String stringValue(String command, String scheme) {
    Result<IValue> result = evaluator.eval(null, command, URIUtil.rootScheme(scheme));
    return ((IString) (result.getValue())).getValue();
  }

  /**
   * @param command
   * @return result of Rascal Command evaluation which has type string
   */
  public String stringValue(String command) {
    return stringValue(command, "stdin");
  }

  public int intValue(String command, String scheme) {
    Result<IValue> result = evaluator.eval(null, command, URIUtil.rootScheme(scheme));
    return ((IInteger) (result.getValue())).intValue();
  }

  /**
   * @param command
   * @return result of Rascal Command evaluation which has type int
   */
  public int intValue(String command) {
    return intValue(command, "stdin");
  }

  public boolean boolValue(String command, String scheme) {
    Result<IValue> result = evaluator.eval(null, command, URIUtil.rootScheme(scheme));
    return ((IBool) (result.getValue())).getValue();
  }

  /**
   * @param command
   * @return result of Rascal Command evaluation which has type boolean
   */
  public boolean boolValue(String command) {
    return boolValue(command, "stdin");
  }

  private Object[] _listValue(IList q) {
    ArrayList<Object> r = new ArrayList<Object>();
    for (IValue v : q) {
      r.add(javaObject(v));
    }
    return r.toArray(new Object[] {});
  }

  public Object[] listValue(String command, String scheme) {
    Result<IValue> result = evaluator.eval(null, command, URIUtil.rootScheme(scheme));
    return _listValue((IList) (result.getValue()));
  }

  /**
   * @param command
   * @return result of Rascal Command evaluation which has type Object[]
   */
  public Object[] listValue(String command) {
    return listValue(command, "stdin");
  }

  public Object eval(String command, String scheme) {
    Result<IValue> result = evaluator.eval(null, command, URIUtil.rootScheme(scheme));
    if (result.getType().isBoolType()) return new Boolean(((IBool) (result.getValue())).getValue());
    if (result.getType().isIntegerType())
      return new Integer(((IInteger) (result.getValue())).intValue());
    if (result.getType().isStringType()) return ((IString) (result.getValue())).getValue();
    if (result.getType().isVoidType()) return null;
    if (result.getType().isListType()) {
      return _listValue((IList) (result.getValue()));
    }
    return result;
  }

  /**
   * @param command
   * @return result of Rascal Command evaluation which can have type: Integer, Bool, String or
   *     Object[],
   */
  public Object eval(String command) {
    return eval(command, "stdin");
  }

  /**
   * @param moduleName
   * @param variableName
   * @param variableType
   * @return true iff variableName is defined in moduleName and the list variableType contains its
   *     type
   */
  public boolean isVariableInModule(
      String moduleName, String variableName, String... variableType) {
    Environment old = evaluator.getCurrentEnvt();
    try {
      evaluator.doImport(null, moduleName);
      ModuleEnvironment env = evaluator.getCurrentEnvt().getImport(moduleName);
      Result<IValue> simpleVariable = env.getSimpleVariable(variableName);
      if (simpleVariable == null) return false;
      for (String vt : variableType) {
        Type tp = getType(env, vt);
        if (tp == null) continue;
        if (simpleVariable.getType().equivalent(tp)) return true;
      }
      return false;
    } finally {
      evaluator.unwind(old);
    }
  }

  /**
   * @param moduleName
   * @param procedureName
   * @param procedureResultType
   * @return true iff procedureName is defined in moduleName and has type procedureResultType
   */
  public boolean isProcedureInModule(
      String moduleName, String procedureName, String procedureResultType, int arity) {
    Environment old = evaluator.getCurrentEnvt();
    try {
      evaluator.doImport(null, moduleName);
      ModuleEnvironment env = evaluator.getCurrentEnvt().getImport(moduleName);
      ArrayList<AbstractFunction> funcs = new ArrayList<AbstractFunction>();
      Type typ = getType(env, procedureResultType);
      if (typ == null) return false;
      env.getAllFunctions(typ, procedureName, funcs);
      for (AbstractFunction f : funcs) {
        if (f.getArity() == arity) {
          return true;
        }
      }
      return false;
    } finally {
      evaluator.unwind(old);
    }
  }

  private Type getType(ModuleEnvironment m, String typeString) {
    Type t = toType.get(typeString);
    if (t != null) return t;
    TypeStore ts = m.getStore();
    t = ts.lookupAlias(typeString);
    if (t != null) return t;
    t = ts.lookupAbstractDataType(typeString);
    return t;
  }

  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;
  }

  private IValue rascalObject(Object v) {
    if (v == null) return null;
    if (v instanceof Integer) return vf.integer(((Integer) v).intValue());
    if (v instanceof String) return vf.string(((String) v));
    if (v instanceof Boolean) return vf.bool(((Boolean) v).booleanValue());
    if (v instanceof Double) return vf.real(((Double) v).doubleValue());
    if (v instanceof Float) return vf.real(((Float) v).floatValue());
    return null;
  }

  public static void main(String[] args) {
    final JavaToRascal jr =
        new JavaToRascal(new PrintWriter(System.out), new PrintWriter(System.err));
    jr.voidValue("import List;");
    System.out.println(jr.stringValue("\"<2+3>\";"));
    System.out.println(jr.stringValue("\"aap:<size([2,3])>\";"));
    final IInteger d1 = vf.integer(1), d2 = vf.integer(2);
    final IList l = vf.list(d1, d2);
    System.out.println(jr.call("size", l));
    // System.out.println(jr.call("+", d1, d2));
  }
}
Exemplo n.º 20
0
  public static void main(String[] args) {

    RVM rvm = new RVM(ValueFactoryFactory.getValueFactory());
    IValueFactory vf = rvm.vf;
    TypeFactory tf = TypeFactory.getInstance();
    /*
     * g (n)
     * {
     * 		while(n > 1) {
     * 			yield n;
     * 			n = n - 1;
     * 		};
     * 		return 0;
     * }
     */

    rvm.declare(
        new Function(
            "g",
            tf.valueType(),
            null,
            1,
            1,
            6,
            new CodeBlock(vf)
                .LABEL("LOOP")
                .LOADLOC(0)
                .LOADCON(0)
                .CALLPRIM(RascalPrimitive.num_greater_num, 2)
                .JMPTRUE("BODY")
                .LOADCON(0)
                .RETURN1(1)
                .LABEL("BODY")
                .LOADLOC(0)
                .YIELD1(1)
                .POP()
                .LOADLOC(0)
                .LOADCON(1)
                .CALLPRIM(RascalPrimitive.num_subtract_num, 2)
                .STORELOC(0)
                .POP()
                .JMP("LOOP")));
    /*
     * h() {
     * n = 9 + 1;
     * c = create(g);
     * c = init(c,n);
     * return c;
     * }
     */

    rvm.declare(
        new Function(
            "h",
            tf.valueType(),
            null,
            0,
            2,
            6,
            new CodeBlock(vf)
                .LOADCON(9)
                .LOADCON(1)
                .CALLPRIM(RascalPrimitive.num_add_num, 2)
                .STORELOC(0)
                .POP()
                .CREATE("g", 0)
                .STORELOC(1)
                .POP()
                .LOADLOC(0)
                .LOADLOC(1)
                .INIT(1)
                .STORELOC(1)
                .POP()
                .LOADLOC(1)
                .RETURN1(1)));

    /*
     * c1 = h();
     * c2 = h();
     *
     * count = 0;
     * while(hasNext(c1)) {
     * 		count = (next(c1) + next(c2)) + count;
     * }
     */
    /*
     * result: 110
     */
    rvm.declare(
        new Function(
            "main",
            tf.valueType(),
            null,
            1,
            4,
            6,
            new CodeBlock(vf)
                .CALL("h", 0)
                .STORELOC(1)
                .POP()
                .CALL("h", 0)
                .STORELOC(2)
                .POP()
                .LOADCON(0)
                .STORELOC(3)
                .POP()
                .LABEL("LOOP")
                .LOADLOC(1)
                .HASNEXT()
                .JMPTRUE("BODY")
                .HALT()
                .LABEL("BODY")
                .LOADLOC(1)
                .NEXT0()
                .LOADLOC(2)
                .NEXT0()
                .CALLPRIM(RascalPrimitive.num_add_num, 2)
                .LOADLOC(3)
                .CALLPRIM(RascalPrimitive.num_add_num, 2)
                .STORELOC(3)
                .POP()
                .JMP("LOOP")));

    rvm.declare(
        new Function(
            "#module_init",
            tf.valueType(),
            null,
            1,
            1,
            6,
            new CodeBlock(vf).LOADLOC(0).CALL("main", 1).RETURN1(1).HALT()));

    rvm.executeProgram("main", new IValue[] {});
  }
Exemplo n.º 21
0
  public static void main(String[] args)
      throws IOException, NoSuchRascalFunction, URISyntaxException, InterruptedException {

    //	  IValueFactory vf = ValueFactoryFactory.getValueFactory();
    //	    CommandOptions cmdOpts = new CommandOptions("CompiledRascalShell");
    //	    try {
    //	        cmdOpts
    //	        .locOption("bin").locDefault(vf.sourceLocation("home", "", "bin"))
    //	        .help("Directory for Rascal binaries")
    //
    //	        .boolOption("help")
    //	        .help("Print help message for this command")
    //	        .noModuleArgument()
    //	        .handleArgs(args);
    //
    //	    } catch (URISyntaxException e1) {
    //	        e1.printStackTrace();
    //	        System.exit(1);
    //	    }
    IValueFactory vf = ValueFactoryFactory.getValueFactory();
    CommandOptions cmdOpts = new CommandOptions("CompiledRascalShell");
    try {
      cmdOpts
          .locsOption("src")
          .locsDefault(
              cmdOpts.getDefaultStdlocs().isEmpty()
                  ? vf.list(cmdOpts.getDefaultStdlocs())
                  : cmdOpts.getDefaultStdlocs())
          .help(
              "Add (absolute!) source location, use multiple --src arguments for multiple locations")
          .locOption("bin")
          .locDefault(vf.sourceLocation("home", "", "bin"))
          .help("Directory for Rascal binaries")
          .locsOption("lib")
          .locsDefault((co) -> vf.list(co.getCommandLocOption("bin")))
          .help("Add new lib location, use multiple --lib arguments for multiple locations")
          .locOption("boot")
          .locDefault(cmdOpts.getDefaultBootLocation())
          .help("Rascal boot directory")
          .boolOption("help")
          .help("Print help message for this command")
          .noModuleArgument()
          .handleArgs(args);

    } catch (URISyntaxException e1) {
      e1.printStackTrace();
      System.exit(1);
    }

    PathConfig pcfg =
        new PathConfig(
            cmdOpts.getCommandLocsOption("src"),
            cmdOpts.getCommandLocsOption("lib"),
            cmdOpts.getCommandLocOption("bin"),
            cmdOpts.getCommandLocOption("boot"));
    IDEServices ideServices = new BasicIDEServices();
    HelpManager hm =
        new HelpManager(
            pcfg, new PrintWriter(System.out), new PrintWriter(System.err), ideServices);

    ideServices.browse(new URI("http://localhost:" + hm.getPort() + "/TutorHome/index.html"));
    Thread.sleep(864000000); // a hack a day keeps the doctor away (and the debugger close)
  }