Paolo Bonzini <[email protected]> writes:

> From: Marc-AndrĂ© Lureau <[email protected]>
>
> Generate Rust #[cfg(...)] guards from QAPI 'if' conditions.

Please mention that this isn't used, yet.  I commonly write something
like "The next commit will put it to use."

> Signed-off-by: Marc-AndrĂ© Lureau <[email protected]>
> Link: 
> https://lore.kernel.org/r/[email protected]
> Signed-off-by: Paolo Bonzini <[email protected]>
> ---
>  scripts/qapi/common.py | 16 ++++++++++++++++
>  scripts/qapi/schema.py |  4 ++++
>  2 files changed, 20 insertions(+)
>
> diff --git a/scripts/qapi/common.py b/scripts/qapi/common.py
> index d7c8aa3365c..f16b9568bb9 100644
> --- a/scripts/qapi/common.py
> +++ b/scripts/qapi/common.py
> @@ -199,6 +199,22 @@ def guardend(name: str) -> str:
>                   name=c_fname(name).upper())
>  
>  
> +def rsgen_ifcond(ifcond: Optional[Union[str, Dict[str, Any]]]) -> str:

This is the Rust-generating cousin of cgen_ifcond().

The argument is None or a tree.  The tree's leaves are str, and its
inner nodes look like

    {'all': [sub-tree, ...]}
    {'any': [sub-tree, ...]}
    {'not': sub-tree}

mypy doesn't do recursive types, so we approximate the tree as
Union[str, Dict[str, Any]].

> +
> +    def cfg(ifcond: Union[str, Dict[str, Any]]) -> str:

The argument's type is wrong.  It should be

    Union[str, List[Dict[str, Any]], Dict[str, Any]]

We'll see below why mypy doesn't complain, and where the List[...]
comes from.

The name @ifcond is misleading.  This isn't an if condition, it's the
union of if condition and list of if conditions.

I needed John Snow's help to figure this out.  Thanks, John!

Case 1: the code for str, i.e. a tree leaf:

> +        if isinstance(ifcond, str):
> +            return ifcond

Case 2: the code for List[Dict[str, Any]]:

> +        if isinstance(ifcond, list):
> +            return ', '.join([cfg(c) for c in ifcond])

Case 3: the code for Dict[str, Any]:

gen_ifcond() below has

           assert isinstance(ifcond, dict) and len(ifcond) == 1

right here to make this crystal clear.

> +        oper, operands = next(iter(ifcond.items()))

Recall @ifcond is either

    {'all': [sub-tree, ...]}
    {'any': [sub-tree, ...]}
    {'not': sub-tree}

The next(...) wizardry returns the first element of the @ifcond
dictionary.  Actually *the* element, since @ifcond has just one.

Thus:

    @oper is 'all', 'any', or 'not'

    @operands is a sub-tree when @oper is 'not', else a [sub-tree, ...],
    i.e. Dict[str, Any] or List[Dict[str, Any]]

> +        operands = cfg(operands)

We pass @operands to cfg().  That's where the List[...] comes from.

> +        return f'{oper}({operands})'
> +
> +    if not ifcond:
> +        return ''
> +    return '#[cfg(%s)]' % cfg(ifcond)

So, cfg(ifcond) returns the argument to interpolate into '#[cfg(%s)]'.

When @ifcond is str, it's @ifcond itself.  This is case 1.

When @ifcond is {'not': COND}, it's 'not(CC)', where CC is cfg(COND).
This is case 3 and case 2 with a non-list argument.

When @ifcond is {'all': [COND, ...]}, it's 'all(CC, ...)', where the CC
are cfg(COND).  This is case 3 and case 2 with a list argument.

Likewise for {'any': [COND, ...]}.

Okay apart from the incorrect type hint and the misleading name.

Less clever code would've saved me quite some review time.

But why doesn't mypy scream?  Consider again

           oper, operands = next(iter(ifcond.items()))

@ifcond's static type is Dict[str, Any].  Therefore @oper's static type
is str, and @operands is Any.  Any suppresses type checking!  The call
cfg(operands) is therefore *not* checked, and we get away with passing a
list to cfg() even though its type hint doesn't allow it.

> +
> +
>  def gen_ifcond(ifcond: Optional[Union[str, Dict[str, Any]]],
>                 cond_fmt: str, not_fmt: str,
>                 all_operator: str, any_operator: str) -> str:
> diff --git a/scripts/qapi/schema.py b/scripts/qapi/schema.py
> index 8d88b40de2e..848a7401251 100644
> --- a/scripts/qapi/schema.py
> +++ b/scripts/qapi/schema.py
> @@ -37,6 +37,7 @@
>      docgen_ifcond,
>      gen_endif,
>      gen_if,
> +    rsgen_ifcond,
>  )
>  from .error import QAPIError, QAPISemError, QAPISourceError
>  from .expr import check_exprs
> @@ -63,6 +64,9 @@ def gen_endif(self) -> str:
>      def docgen(self) -> str:
>          return docgen_ifcond(self.ifcond)
>  
> +    def rsgen(self) -> str:
> +        return rsgen_ifcond(self.ifcond)
> +
>      def is_present(self) -> bool:
>          return bool(self.ifcond)


Reply via email to