Examples

This following OCL constraints can be parsed and evaluated by this implementation of OCL. Please note, that you need to define a proper object model beside of the given constraints.

Person

class Person {
    name : String;
    age : Number;
    children : Person[];
    isMarried : Boolean;
    husband : Person;
    wife : Person;
}
-- Check that underage persons are not married
context Person inv:
    age < 18 implies isMarried = false

-- Check that each and every children is younger than 18 years old
context Person inv:
    children->select(age >= 18)->isEmpty()

-- If a person is married, wife or husband has to be at least 18 years old
context Person inv:
    self.wife->notEmpty() implies self.wife.age >= 18 and
    self.husband->notEmpty() implies self.husband.age >= 18

-- If there are children, one should be named Stephan ;)
context Person inv:
    self.children->exists(child | child.name = 'Stephan')
import OCLEngine from "@stekoe/ocl.js"

const oclEngine = new OclEngine();

oclEngine.addOclExpression(`
    -- Check that underage persons are not married
    context Person inv:
        age < 18 implies isMarried = false
    
    -- Check that each and every children is younger than 18 years old
    context Person inv:
        children->select(age >= 18)->isEmpty()
    
    -- If a person is married, wife or husband has to be at least 18 years old
    context Person inv:
        self.wife->notEmpty() implies self.wife.age >= 18 and
        self.husband->notEmpty() implies self.husband.age >= 18
    
    -- If there are children, one should be named Stephan ;)
    context Person inv:
        self.children->exists(child | child.name = 'Stephan')
`);

let person = new Person();
oclEngine.evaluate(person);

Company

class Company {
    name : String;
    employee: Person[]
}

class Person {
    name : String;
    age : Number;
    isMarried : Boolean;
}
-- No one should work that long...
context Company inv:
    self.employee->forAll(p : Person | p.age <= 65 )

-- We only accept a company as valid if every employee is married
context Company inv:
    self.employee->reject(p | p.isMarried )->isEmpty()
import OCLEngine from "@stekoe/ocl.js"

const oclEngine = new OclEngine();

oclEngine.addOclExpression(`
    -- No one should work that long...
    context Company inv:
        self.employee->forAll(p : Person | p.age <= 65 )
    
    -- We only accept a company as valid if every employee is married
    context Company inv:
        self.employee->reject(p | p.isMarried )->isEmpty()
`);

let company = new Company();
company.employee.push(new Person());

oclEngine.evaluate(company);