Skip to main content

module Validator

rascal-0.28.2

Usage

import util::Validator;

Dependencies

import Type;
import Node;
import List;
import Exception;
import IO;

Synopsis

Generic validator function that can convert values of the node type to instances of abstract data type constructors.

Description

The intended use-case is to read structured data externally, say an XML or JSON or YAML file, as generic node values and then to use the validate function to map the untyped representation to a typed representation, if it can be validated accordingly.

data RuntimeException

data RuntimeException  
= invalid(str \type, value v, list[value] path=[])
;

data RuntimeException

data RuntimeException  
= none()
;

function validate

The general and simple validation case is when a value's run-time type already matches the expected static type

&T validate(type[&T] expected, value v, list[value] path=[], bool relaxed=false)

&T validate(type[&T] expected, node v, list[value] path = [], bool relaxed=false)

default &T validate(type[&T] expected, value v, list[value] path=[], bool relaxed=false)

Tests

test simpleInt

test bool simpleInt() {
value x = 1;

return int _ := validate(#int, x);
}

test defaultNode

test bool defaultNode() {
value x = "hello"();

return node _ := validate(#node, x);
}

test adtTest

test bool adtTest() {
value x = "invalid"("XXX", [[[]]],path=[1,0,0]);

return RuntimeException _ := validate(#RuntimeException, x);
}

test adtRelaxedTest

test bool adtRelaxedTest() {
value x = "object"("XXX", [[[]]],path=[1,0,0]);

return RuntimeException _ := validate(#RuntimeException, x, relaxed=true);
}

test adtTestFail

test bool adtTestFail() {
value x = "invali"("XXX", [[[]]],path=[1,0,0]);

try {
validate(#RuntimeException, x);
return false;
}
catch invalid(_,_) :
return true;

}

test adtTestFailNested

test bool adtTestFailNested() {
value x = "invalid"(2, [[[]]],path=[1,0,0]);

try {
validate(#RuntimeException, x);
return false;
}
catch invalid(_,_) :
return true;

}

test adtTestFailKeyword

test bool adtTestFailKeyword() {
value x = "invalid"("hello", [[[]]],path="[1,0,0]");

try {
validate(#RuntimeException, x);
return false;
}
catch invalid(_,_) :
return true;

}