0

Assume I have:

visit(p) { 
   case ...
   default:
       println("This should not happen. All elements should be catched. Check: <x>");
};

How can I print out (in this case as x) what could not be matched?

I tried:

x:default:

\x:default:

default:x:

\default:x:

Tx,

Jos

robert
  • 1,921
  • 2
  • 17
  • 27

2 Answers2

0

We have a library named Traversal that allows you to get back the context of a match. So, you can do something like this:

import Traversal;
import IO;

void doit() {
    m = (1:"one",2:"two",3:"three");
    bottom-up visit(m) {
        case int n : println("<n> is an int");
        default: {
            tc = getTraversalContext();
            println("Context is: <tc>");
            println("<tc[0]> is not an int");
            if (str s := tc[0]) {
                println("<s> is a string");
            }
        }
    }
}

tc is then a list of all the nodes back to the top of the term -- in this case, it will just be the current value, like "three", and the entire value of map m (or the entire map, which will also be a match for the default case). If you had something structured as a tree, such as terms formed using ADTs or nodes, you would get all the intervening structure from the point of the match back to the top (which would be the entire term).

For some reason, though, default is matching the same term multiple times. I've filed this as bug report https://github.com/cwi-swat/rascal/issues/731 on GitHub.

Mark Hills
  • 1,028
  • 5
  • 4
0

You could also try this idiom:

visit(x) {
  case ...
  case ...
  case value x: throw "default case should not happen <x>";
}

The value pattern will catch everything but only after the others are tried.

Jurgen Vinju
  • 6,393
  • 1
  • 15
  • 26
  • The other answer by Mark will give you more context information which is useful as well. But i usually start with this. – Jurgen Vinju Dec 04 '14 at 23:07
  • Agreed, I guess I was trying to do it while sticking with default, but this would obviously be easier (unless you need the traversal context anyway). – Mark Hills Dec 04 '14 at 23:59