Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion besser/generators/backend/api_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
from besser.generators.default_literals import register_default_literals
from besser.generators.action_language.RESTGenerator import bal_to_rest
from besser.generators.backend.nn_methods import collect_nn_modules, nn_method_code
from besser.generators.backend.ocl_invariants import collect_invariants
from besser.generators.structural_utils import (
get_deferred_fk_associations,
get_foreign_keys,
Expand Down Expand Up @@ -306,7 +307,12 @@ def generate_modular_api(

# database.py: engine/session setup shared by main_api.py and every router.
database_template = env.get_template("database.py.j2")
write("database.py", database_template.render(name=model.name))
# The OCL rules the schemas cannot check are checked by database.py before each commit.
invariants = [
{**inv, "name_repr": repr(inv["name"]), "expression_repr": repr(inv["expression"])}
for inv in collect_invariants(model)
]
write("database.py", database_template.render(name=model.name, invariants=invariants))

# bal_stdlib.py: BESSER Action Language standard-library helpers, shared
# by any router whose class methods use them.
Expand Down
3 changes: 2 additions & 1 deletion besser/generators/backend/backend_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,8 @@ def generate(self):
sql_alchemy = SQLAlchemyGenerator(model=self.model, output_dir=backend_folder_path)
sql_alchemy.generate()

pydantic_model = PydanticGenerator(model=self.model, output_dir=backend_folder_path, backend=True, nested_creations=self.nested_creations)
pydantic_model = PydanticGenerator(model=self.model, output_dir=backend_folder_path, backend=True, nested_creations=self.nested_creations,
rules_checked_at_commit=True)
pydantic_model.generate()

# The files of the generators this one is built from, by path in the output folder.
Expand Down
249 changes: 249 additions & 0 deletions besser/generators/backend/ocl_invariants.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,249 @@
"""OCL invariants that navigate associations, as Python checks the generated backend runs at commit.

A Pydantic schema sees one request payload, so ``pydantic_classes/ocl_utils.py`` leaves a TODO for a
rule that needs other rows. The generated backend has the rows: ``database.py`` checks each rule
translated here on the records a change touched, and their direct neighbours, before the change is
committed, and refuses a violating change with HTTP 422 naming the rule.

Translated subset, over the parse tree of B-OCL: navigation from ``self`` through attributes and
association ends; ``isEmpty``, ``notEmpty``, ``size``, ``includes``, ``excludes`` and ``isUnique``;
comparisons of numbers, strings and booleans; ``and``, ``or``, ``xor``, ``implies`` and ``not``;
literals. A rule using anything else (iterators such as ``forAll`` or ``select``, ``collect``,
``sum``, enumeration literals, dates) keeps its TODO.

One kind of rule inside the subset keeps its TODO too: one that can fail while an end of ``self``
whose records each need a record of ``self``'s class is still empty (``self.items->notEmpty()``
when every item needs an order). Enforced at commit, it would refuse creating the first record.

An ordering comparison (``<``, ``<=``, ``>``, ``>=``) that meets an empty value leaves the rule
undefined, and it is not applied to that record; ``=`` and ``<>`` compare an empty value as ``null``.
"""

import ast
import logging
import re
from typing import Dict, List, Optional, Tuple

from antlr4 import CommonTokenStream, InputStream

from besser.BUML.metamodel.ocl.ocl import (
BooleanLiteralExpression, InfixOperator, IntegerLiteralExpression, OperationCallExpression,
PropertyCallExpression, RealLiteralExpression, StringLiteralExpression, VariableExp,
)
from besser.BUML.metamodel.structural import Class, DomainModel, Property
from besser.BUML.notations.ocl.BOCLLexer import BOCLLexer
from besser.BUML.notations.ocl.BOCLParser import BOCLParser
from besser.BUML.notations.ocl.error_handling import BOCLErrorListener
from besser.BUML.notations.ocl.visitor import BOCLVisitorImpl
from besser.generators.pydantic_classes.ocl_utils import parse_ocl_constraint

logger = logging.getLogger(__name__)

_INVARIANT_HEADER = re.compile(r"^\s*context\s+\w+\s+inv\b")

_COMPARISONS = {"=": "==", "<>": "!=", "<": "<", "<=": "<=", ">": ">", ">=": ">="}
_PRIMITIVE_KINDS = {"int": "num", "float": "num", "str": "str", "bool": "bool"}

#: The only operations a rule on an end whose records need ``self`` first may use: each holds on an
#: empty collection, and none negates another (``not``, ``implies``, ``= false`` would turn
#: ``isEmpty`` into a minimum that refuses creating ``self``).
_HOLD_ON_EMPTY = {"isempty", "isunique", "excludes", "and", "or"}

#: AST nodes a translated check may contain; everything else means a translation bug.
_ALLOWED_NODES = (
ast.Expression, ast.BoolOp, ast.UnaryOp, ast.Compare, ast.Call, ast.Name, ast.Constant, ast.Load,
ast.And, ast.Or, ast.Not, ast.Eq, ast.NotEq, ast.Lt, ast.LtE, ast.Gt, ast.GtE, ast.In, ast.NotIn,
)
_ALLOWED_NAMES = {"obj", "len", "_nav", "_coll", "_is_unique", "_cmp"}


class _Unsupported(Exception):
"""The rule uses something outside the translated subset."""


def collect_invariants(model: DomainModel) -> List[Dict[str, str]]:
"""The invariants of ``model`` the backend enforces at commit, ordered by name.

Each is ``{"class_name", "name", "expression", "python"}``: ``python`` is an expression over
``obj``, a record of ``class_name`` (or of a subclass), true when the rule holds. Only rules
the Pydantic schemas skip are included, so no rule is checked twice.
"""
invariants = []
for constraint in sorted(model.constraints, key=lambda c: c.name or ""):
if constraint.language != "OCL" or not isinstance(constraint.context, Class):
continue
if not _INVARIANT_HEADER.match(constraint.expression or ""):
continue
parsed = parse_ocl_constraint(constraint, model)
if not (parsed and parsed.get("skipped")):
continue
python = translate_invariant(constraint, model)
if python is not None:
invariants.append({
"class_name": constraint.context.name,
"name": constraint.name,
"expression": " ".join(constraint.expression.split()),
"python": python,
})
return invariants


def translate_invariant(constraint, model: DomainModel) -> Optional[str]:
"""``constraint`` as a Python expression over ``obj``, or None when it is outside the subset."""
root = _parse(constraint, model)
if root is None:
return None
translator = _Translator(constraint.context)
try:
python, kind, _ = translator.expr(root)
except _Unsupported as reason:
logger.debug("OCL invariant %s not translated: %s", constraint.name, reason)
return None
if kind != "bool" or (translator.part_ends and translator.ops - _HOLD_ON_EMPTY):
return None
_check_safe(python)
return python


def _parse(constraint, model):
"""The B-OCL parse tree of ``constraint``, or None when it does not parse."""
listener = BOCLErrorListener()
lexer = BOCLLexer(InputStream(constraint.expression))
lexer.removeErrorListeners()
lexer.addErrorListener(listener)
parser = BOCLParser(CommonTokenStream(lexer))
parser.removeErrorListeners()
parser.addErrorListener(listener)
try:
tree = parser.oclFile()
if listener.has_errors():
return None
return BOCLVisitorImpl(model, None, constraint.context).visit(tree)
except Exception: # the visitor raises on what it cannot type; that rule keeps its TODO
logger.debug("OCL invariant %s does not parse", constraint.name, exc_info=True)
return None


def _check_safe(python: str) -> None:
"""Refuse to emit anything but the expression shapes the translator writes."""
tree = ast.parse(python, mode="eval")
for node in ast.walk(tree):
if not isinstance(node, _ALLOWED_NODES) or (isinstance(node, ast.Name) and node.id not in _ALLOWED_NAMES):
raise ValueError(f"unexpected node in translated OCL: {ast.dump(node)}")


class _Translator:
"""Walks a B-OCL tree into Python; each step returns ``(code, kind, element class)``.

``kind`` is ``"bool"``, ``"num"``, ``"str"``, ``"obj"`` (at most one record), ``"objs"``
(records), ``"vals"`` (attribute values of several records) or ``"other"``; the element
class is the class of the records a navigation yields, for ``isUnique``'s key.
"""

def __init__(self, context: Class):
self.context = context
self.ops = set()
self.part_ends = set()

def expr(self, node) -> Tuple[str, str, Optional[Class]]:
if isinstance(node, BooleanLiteralExpression):
return repr(bool(node.value)), "bool", None
if isinstance(node, (IntegerLiteralExpression, RealLiteralExpression)):
return repr(node.value), "num", None
if isinstance(node, StringLiteralExpression):
return repr(str(node.value)), "str", None
if isinstance(node, Property):
return self._navigate("obj", self.context, node, from_self=True)
if isinstance(node, PropertyCallExpression):
return self._property_call(node)
if isinstance(node, OperationCallExpression):
return self._operation(node)
raise _Unsupported(type(node).__name__)

def _property_call(self, node: PropertyCallExpression):
if node.source is None:
return self._navigate("obj", self.context, node.property, from_self=True)
base, kind, owner = self.expr(node.source)
if kind not in ("obj", "objs") or owner is None:
raise _Unsupported(f"navigation from a {kind}")
code, step_kind, element = self._navigate(base, owner, node.property, from_self=False)
# Navigating from several records collects from each of them, as OCL does.
if kind == "objs":
step_kind = "objs" if step_kind in ("obj", "objs") else "vals"
return code, step_kind, element

def _navigate(self, base: str, owner: Class, prop: Property, from_self: bool):
end = next((e for e in owner.all_association_ends() if e.name == prop.name), None)
if end is not None:
opposite = end.opposite_end()
# Each record there needs one of ``self``'s class, so none exists before the first ``self``.
if from_self and opposite.multiplicity.min >= 1:
self.part_ends.add(end.name)
kind = "objs" if end.multiplicity.max > 1 else "obj"
return f"_nav({base}, {end.name!r})", kind, end.type
attribute = next((a for a in owner.all_attributes() if a.name == prop.name), None)
if attribute is None:
raise _Unsupported(f"{prop.name} is not a feature of {owner.name}")
return f"_nav({base}, {attribute.name!r})", _PRIMITIVE_KINDS.get(attribute.type.name, "other"), None

def _operation(self, node: OperationCallExpression):
op = str(node.operation).lower()
self.ops.add(op)
args = list(node.arguments or [])
if op in ("and", "or", "xor", "implies"):
left, right = (self._boolean(a) for a in args)
joined = {"and": f"({left} and {right})", "or": f"({left} or {right})",
"xor": f"({left} != {right})", "implies": f"(not {left} or {right})"}[op]
return joined, "bool", None
if op == "not":
return f"(not {self._boolean(args[0])})", "bool", None
if op in _COMPARISONS:
return self._comparison(op, args)
if op in ("isempty", "notempty", "size", "includes", "excludes", "isunique"):
return self._collection(op, node.source, args)
raise _Unsupported(op)

def _boolean(self, node) -> str:
code, kind, _ = self.expr(node)
if kind != "bool":
raise _Unsupported(f"{kind} used as a condition")
return code

def _comparison(self, op: str, args: list):
operands = [a for a in args if not isinstance(a, InfixOperator)]
if len(operands) != 2:
raise _Unsupported("comparison shape")
(left, left_kind, _), (right, right_kind, _) = (self.expr(a) for a in operands)
same = left_kind == right_kind and left_kind in ("num", "str", "bool")
identity = left_kind == right_kind == "obj" and op in ("=", "<>")
if not (same or identity):
raise _Unsupported(f"comparison of {left_kind} and {right_kind}")
if op in ("=", "<>"):
return f"({left} {_COMPARISONS[op]} {right})", "bool", None
return f"_cmp({left}, {_COMPARISONS[op]!r}, {right})", "bool", None

def _collection(self, op: str, source, args: list):
if source is None:
raise _Unsupported(f"{op} without a source")
items, kind, element = self.expr(source)
if kind not in ("obj", "objs", "vals"): # String::size() is a length, not a collection's size
raise _Unsupported(f"{op} on a {kind}")
items = f"_coll({items})"
if op == "isempty":
return f"(len({items}) == 0)", "bool", None
if op == "notempty":
return f"(len({items}) > 0)", "bool", None
if op == "size":
return f"len({items})", "num", None
if op == "isunique":
key = args[0] if args else None
name = key.name if isinstance(key, (VariableExp, Property)) else None
features = set()
if element is not None: # a key with several values per record has no single value to compare
features = ({a.name for a in element.all_attributes()}
| {e.name for e in element.all_association_ends() if e.multiplicity.max == 1})
if name not in features:
raise _Unsupported("isUnique key")
return f"_is_unique({items}, {name!r})", "bool", None
value, _, _ = self.expr(args[0])
return f"({value} {'in' if op == 'includes' else 'not in'} {items})", "bool", None
Loading