Tuesday, April 13, 2010

OCL tips and tricks

Acceleo is entirely based on OCL (Object Constraint Language) for all of its model navigation syntax. Though we did simplify it as much as possible for Acceleo (getting rid of redundant casts, increasing the standard library, overriding operators, ...), there are still some things that might cause problems to any beginning user.

Here are a few of the most unsettling language particularities :
  • Operations or features conflicting with reserved OCL keywords (UML anyone?). For example, if your model has a class "Operation" with a feature named "body", then writing "myClass.body" in OCL will result in a somewhat cryptic error : "invalid token 'body'".

    The trick to access such features in OCL is to prefix the feature name with an underscore. For this example, you should have written "myClass._body".

    For the record, the full list of OCL reserved keywords as per the last available OCL version, 3.0, is as follows :

    • and
    • body
    • context
    • def
    • derive
    • else
    • endif
    • endpackage
    • if
    • implies
    • in
    • init
    • inv
    • let
    • not
    • or
    • package
    • post
    • pre
    • static
    • then
    • xor

  • Accessing enumeration values. This might sound obvious to OCL experts, but how would one compare feature values to set enumerated values? The trick here is to qualify the access. For example if you wish to check that an UML operation's visibility is "public", here is what you would do in Java : "if (operation.getVisibility() == VisibilityKind.PUBLIC".

    The OCL equivalent is "if (operation.visibility = VisibilityKind::public)".

  • There is no "elseif" in OCL ; remember to close each individual if properly with endifs : "if (...) then ... else if (...) then ... else ... endif endif"
I believe these are the most annoying (as in "the most subject to cause weird compilation errors") OCL features ; don't hesitate to add yours :p.


  1. Excuse me, but WTF is OCL? I know I could just google it, but I think your posts would greatly benefit from some title tags or at least define your TLAs on first usage.

    (I've read your post via the Eclipse Planet, in case you were wondering.)

  2. @PAStheLoD : it's true that this message was more aimed at modeling people, and I admit I've been totally corrupted by acronyms ... not even realizing I use TLAs anymore :p.

    I've added hyperlinks to the eclipse wiki for OCL and Acceleo ^^