Skip to main content

module util::Validator

rascal-0.34.0

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

Usage

import util::Validator;

Dependencies

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

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)

function validate

To validate nodes we can try whether or not it can be matched to a constructor of a defined data type with the same name and (resp. validating) children.

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

function validate

if a (sub)value can not be validated we report the expected type, the not-matching value and the path that led us there

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;

}