a
    LgD\                     @   sJ  d Z ddlZddlmZmZmZmZmZmZ ddl	m
Z
 ddlmZ ddlmZ ddlmZ ed	ejZeeedd
ddZeeeed
ddZeeedd
ddZdBeeeeeddddZeeedd
ddZeeeddddZeeef eeee ee ddddZeddddZeeef eedd d!d"Zedd#d$d%Z ee eedd&d'd(Z!ee eedd&d)d*Z"ee eeee dd+d,d-Z#ee eeee dd+d.d/Z$ee edd0d1d2Z%eddd3d4Z&eddd5d6Z'eddd7d8Z(eddd9d:Z)eddd;d<Z*eddd=d>Z+ee ee d?d@dAZ,dS )Ca  
Normalize and validate (context-free) QAPI schema expression structures.

`QAPISchemaParser` parses a QAPI schema into abstract syntax trees
consisting of dict, list, str, bool, and int nodes.  This module ensures
that these nested structures have the correct type(s) and key(s) where
appropriate for the QAPI context-free grammar.

The QAPI schema expression language allows for certain syntactic sugar;
this module also handles the normalization process of these nested
structures.

See `check_exprs` for the main entry point.

See `schema.QAPISchema` for processing into native Python data
structures and contextual semantic validation.
    N)DictIterableListOptionalUnioncast   )c_name)QAPISemError)QAPIExpression)QAPISourceInfoz)(__[a-z0-9.-]+_)?(x-)?([a-z][a-z0-9_-]*)$)nameinfosourcereturnc                 C   s   t | tst|d| dS )zf
    Ensure that ``name`` is a ``str``.

    :raise QAPISemError: When ``name`` fails validation.
    z%s requires a string nameN
isinstancestrr
   )r   r   r    r   </home2/Puru_Virtio_Blk/virtio-demo/qemu/scripts/qapi/expr.pycheck_name_is_str8   s    
r   c                 C   s6   t | }|rt| ddr,t|d| |dS )a  
    Ensure that ``name`` is a valid QAPI name.

    A valid name consists of ASCII letters, digits, ``-``, and ``_``,
    starting with a letter.  It may be prefixed by a downstream prefix
    of the form __RFQDN_, or the experimental prefix ``x-``.  If both
    prefixes are present, the __RFDQN_ prefix goes first.

    A valid name cannot start with ``q_``, which is reserved.

    :param name: Name to check.
    :param info: QAPI schema source file information.
    :param source: Error string describing what ``name`` belongs to.

    :raise QAPISemError: When ``name`` fails validation.
    :return: The stem of the valid name, with no prefixes.
    Fq_z%s has an invalid name   )
valid_namematchr	   
startswithr
   group)r   r   r   r   r   r   r   check_name_strD   s    
r   c                 C   s*   t | ||}td|r&t|d| dS )a  
    Ensure that ``name`` is a valid event name.

    This means it must be a valid QAPI name as checked by
    `check_name_str()`, but where the stem prohibits lowercase
    characters and ``-``.

    :param name: Name to check.
    :param info: QAPI schema source file information.
    :param source: Error string describing what ``name`` belongs to.

    :raise QAPISemError: When ``name`` fails validation.
    z[a-z-]z(name of %s must not use lowercase or '-'Nr   researchr
   r   r   r   stemr   r   r   check_name_upper^   s
    r#   F)r   r   r   permit_upperpermit_underscorer   c                 C   s:   t | ||}|std|s(|s6d|v r6t|d| dS )a  
    Ensure that ``name`` is a valid command or member name.

    This means it must be a valid QAPI name as checked by
    `check_name_str()`, but where the stem prohibits uppercase
    characters and ``_``.

    :param name: Name to check.
    :param info: QAPI schema source file information.
    :param source: Error string describing what ``name`` belongs to.
    :param permit_upper: Additionally permit uppercase.
    :param permit_underscore: Additionally permit ``_``.

    :raise QAPISemError: When ``name`` fails validation.
    z[A-Z]_z(name of %s must not use uppercase or '_'Nr   )r   r   r   r$   r%   r"   r   r   r   check_name_lowerr   s    r'   c                 C   s*   t | ||}td|s&t|d| dS )a  
    Ensure that ``name`` is a valid user-defined type name.

    This means it must be a valid QAPI name as checked by
    `check_name_str()`, but where the stem must be in CamelCase.

    :param name: Name to check.
    :param info: QAPI schema source file information.
    :param source: Error string describing what ``name`` belongs to.

    :raise QAPISemError: When ``name`` fails validation.
    z#[A-Z][A-Za-z0-9]*[a-z][A-Za-z0-9]*$zname of %s must use CamelCaseN)r   r   r   r
   r!   r   r   r   check_name_camel   s    r(   )r   r   metar   c                 C   s`   |dkrt | || nF|dkr8t| ||| |jjv d n$t| || | dr\t|d| dS )a  
    Ensure that ``name`` is a valid definition name.

    Based on the value of ``meta``, this means that:
      - 'event' names adhere to `check_name_upper()`.
      - 'command' names adhere to `check_name_lower()`.
      - Else, meta is a type, and must pass `check_name_camel()`.
        These names must not end with ``List``.

    :param name: Name to check.
    :param info: QAPI schema source file information.
    :param meta: Meta-type name of the QAPI expression.

    :raise QAPISemError: When ``name`` fails validation.
    eventcommand)r%   r   z %s name should not end in 'List'N)r#   r'   pragmacommand_name_exceptionsr(   endswithr
   )r   r   r)   r   r   r   check_defn_name_str   s    

r/   )valuer   r   requiredoptionalr   c           	      C   s   t t tddd}t|t|  }|rPt|d|t|dkr@dnd||f t|t|B }t| | }|rt|d|t|dkrdnd||||f d	S )
ak  
    Ensure that a dict has a specific set of keys.

    :param value: The dict to check.
    :param info: QAPI schema source file information.
    :param source: Error string describing this ``value``.
    :param required: Keys that *must* be present.
    :param optional: Keys that *may* be present.

    :raise QAPISemError: When unknown keys are present.
    )elemsr   c                 S   s   d dd t| D S )Nz, c                 s   s   | ]}d | d  V  qdS )'Nr   ).0er   r   r   	<genexpr>       z-check_keys.<locals>.pprint.<locals>.<genexpr>)joinsorted)r3   r   r   r   pprint   s    zcheck_keys.<locals>.pprintz%s misses key%s %sr   s z*%s has unknown key%s %s
Valid keys are %s.N)r   r   setr
   len)	r0   r   r   r1   r2   r;   missingallowedunknownr   r   r   
check_keys   s,    rC   )exprr   c                 C   s|   dD ](}|| v r| | durt | jd| qdD ](}|| v r2| | dur2t | jd| q2d| v rxd| v rxt | jd	d
S )z
    Ensure flag members (if present) have valid values.

    :param expr: The expression to validate.

    :raise QAPISemError:
        When certain flags have an invalid value, or when
        incompatible flags are present.
    )gensuccess-responseFz"flag '%s' may only use false value)boxed	allow-ooballow-preconfig	coroutineTz!flag '%s' may only use true valuerH   rJ   z2flags 'allow-oob' and 'coroutine' are incompatibleN)r
   r   )rD   keyr   r   r   check_flags   s    


rL   )rD   r   r   r   c                    s^   t ttf dd fdd ttdd fdd| d}|du rRdS  | dS )	a  
    Validate the ``if`` member of an object.

    The ``if`` member may be either a ``str`` or a dict.

    :param expr: The expression containing the ``if`` member to validate.
    :param info: QAPI schema source file information.
    :param source: Error string describing ``expr``.

    :raise QAPISemError:
        When the "if" member fails validation, or when there are no
        non-empty conditions.
    :return: None
    N)condr   c                    s   t | tr,td| s(td| f d S t | tsDtd t| d g g d t| dkrvtd d| v r | d  n&d	| v rd	| d	  nd
| d
  d S )Nz[A-Z][A-Z0-9_]*z3'if' condition '%s' of %s is not a valid identifierz2'if' condition of %s must be a string or an objectz'if' condition of %s)allanynotr   z)'if' condition of %s has conflicting keysrP   rN   rO   )r   r   r   	fullmatchr
   dictrC   r?   )rM   	_check_if_check_infixr   r   r   r   rT     s6    

zcheck_if.<locals>._check_if)operatoroperandsr   c                    sD   t |tstd| f |s.td |D ]} | q2d S )Nz%'%s' condition of %s must be an arrayz"'if' condition [] of %s is useless)r   listr
   )rV   rW   operand)rT   r   r   r   r   rU   &  s    
zcheck_if.<locals>._check_infixif)r   r   objectget)rD   r   r   ifcondr   rS   r   check_if   s    "
r^   )membersr   c                 C   s8   t | tr4|  D ] \}}t |tr&qd|i| |< qdS )a  
    Normalize a "members" value.

    If ``members`` is a dict, for every value in that dict, if that
    value is not itself already a dict, normalize it to
    ``{'type': value}``.

    :forms:
      :sugared: ``Dict[str, Union[str, TypeRef]]``
      :canonical: ``Dict[str, TypeRef]``

    :param members: The members value to normalize.

    :return: None, ``members`` is normalized in-place as needed.
    typeN)r   rR   items)r_   rK   argr   r   r   normalize_members9  s
    

rc   )r0   r   r   r   c                 C   s$   | d ur t | ts t|d| d S )Nz%s should be a type namer   r0   r   r   r   r   r   check_type_nameP  s    re   c                 C   sZ   | d u st | trd S t | ts.t|d| t| dksHt | d tsVt|d| d S )Nz!%s should be a type name or arrayr   r   z,%s: array type must contain single type name)r   r   rX   r
   r?   rd   r   r   r   check_type_name_or_arrayV  s    
rf   )r0   r   r   parent_namer   c                 C   s   | du rdS t | ts$t|d| ||jjv }|  D ]\}}d||f }|drb|dd }t|||||d t|ddkst|dd	rt|d
| t	|||dgddg t
||| t|d| t|d || q8dS )aK  
    Normalize and validate an optional implicit struct type.

    Accept ``None`` or a ``dict`` defining an implicit struct type.
    The latter is normalized in place.

    :param value: The value to check.
    :param info: QAPI schema source file information.
    :param source: Error string describing this ``value``.
    :param parent_name:
        When the value of ``parent_name`` is in pragma
        ``member-name-exceptions``, an implicit struct type may
        violate the member naming rules.

    :raise QAPISemError: When ``value`` fails validation.
    :return: None
    Nz#%s should be an object or type namez%s member '%s'*r   r$   r%   FuZhas_z%s uses reserved namer`   rZ   features)r   rR   r
   r,   member_name_exceptionsra   r   r'   r	   rC   r^   check_featuresr\   rf   )r0   r   r   rg   
permissiverK   rb   Z
key_sourcer   r   r   check_type_implicite  s*    

ro   c                 C   s(   | d u st | trd S t| ||| d S )N)r   r   ro   )r0   r   r   rg   r   r   r   check_type_name_or_implicit  s    rp   )rk   r   r   c                 C   s   | du rdS t | ts t|ddd | D | dd< | D ]f}d}t |tsPJ t|||dgdg t|d || d||d f }t|d || t||| q:dS )	a  
    Normalize and validate the ``features`` member.

    ``features`` may be a ``list`` of either ``str`` or ``dict``.
    Any ``str`` element will be normalized to ``{'name': element}``.

    :forms:
      :sugared: ``List[Union[str, Feature]]``
      :canonical: ``List[Feature]``

    :param features: The features member value to validate.
    :param info: QAPI schema source file information.

    :raise QAPISemError: When ``features`` fails validation.
    :return: None, ``features`` is normalized in-place as needed.
    Nz'features' must be an arrayc                 S   s"   g | ]}t |tr|nd |iqS r   r   rR   )r5   fr   r   r   
<listcomp>  s   z"check_features.<locals>.<listcomp>z'features' memberr   rZ   %s '%s')r   rX   r
   rR   rC   r   r'   r^   )rk   r   featr   r   r   r   rm     s    

rm   c           	      C   s   | d }| d }|  d}| j}t|ts4t|d|durPt|tsPt|d||jjv }dd |D |dd< |D ]}d	}t|||d
gddg |d
 }t	||| d||f }|d 
 rd| }t|||||d t||| t| d| qvdS )z
    Normalize and validate this expression as an ``enum`` definition.

    :param expr: The expression to validate.

    :raise QAPISemError: When ``expr`` is not a valid ``enum``.
    :return: None, ``expr`` is normalized in-place as needed.
    enumdataprefixz'data' must be an arrayNz'prefix' must be a stringc                 S   s"   g | ]}t |tr|nd |iqS rq   rr   )r5   mr   r   r   rt     s   zcheck_enum.<locals>.<listcomp>z'data' memberr   rZ   rk   ru   r   dri   )r\   r   r   rX   r
   r   r,   rl   rC   r   isdigitr'   r^   rm   )	rD   r   r_   ry   r   rn   memberr   member_namer   r   r   
check_enum  s4    	



r   c                 C   s>   t t| d }| d }t|| jd| t| d| jd dS )z
    Normalize and validate this expression as a ``struct`` definition.

    :param expr: The expression to validate.

    :raise QAPISemError: When ``expr`` is not a valid ``struct``.
    :return: None, ``expr`` is normalized in-place as needed.
    structrx   'data'base'base'N)r   r   ro   r   re   r\   )rD   r   r_   r   r   r   check_struct  s    	r   c           	      C   s   t t| d }| d }| d }| d }| j}t||d| t||d t|tsZt|d| D ]@\}}d| }t	|||d	gd
g t
||| t|d	 || qbdS )z
    Normalize and validate this expression as a ``union`` definition.

    :param expr: The expression to validate.

    :raise QAPISemError: when ``expr`` is not a valid ``union``.
    :return: None, ``expr`` is normalized in-place as needed.
    unionr   discriminatorrx   r   z'discriminator''data' must be an object'data' member '%s'r`   rZ   N)r   r   r   rp   r   r   rR   r
   ra   rC   r^   re   )	rD   r   r   r   r_   r   rK   r0   r   r   r   r   check_union  s    	

r   c                 C   s   | d }| j }|st|dt|ts0t|d| D ]L\}}d| }t||| t|||dgdg t||| t|d || q8dS )a  
    Normalize and validate this expression as an ``alternate`` definition.

    :param expr: The expression to validate.

    :raise QAPISemError: When ``expr`` is not a valid ``alternate``.
    :return: None, ``expr`` is normalized in-place as needed.
    rx   z'data' must not be emptyr   r   r`   rZ   N)	r   r
   r   rR   ra   r'   rC   r^   rf   )rD   r_   r   rK   r0   r   r   r   r   check_alternate  s    	


r   c                 C   sj   |  d}|  d}|  dd}|rH|du r8t| jdt|| jd nt|| jdd t|| jd dS )	z
    Normalize and validate this expression as a ``command`` definition.

    :param expr: The expression to validate.

    :raise QAPISemError: When ``expr`` is not a valid ``command``.
    :return: None, ``expr`` is normalized in-place as needed.
    rx   returnsrG   FN'boxed': true requires 'data'r   z	'returns')r\   r
   r   re   rp   rf   )rD   argsretsrG   r   r   r   check_command)  s    	

r   c                 C   sR   |  d}|  dd}|r>|du r.t| jdt|| jd nt|| jdd dS )z
    Normalize and validate this expression as an ``event`` definition.

    :param expr: The expression to validate.

    :raise QAPISemError: When ``expr`` is not a valid ``event``.
    :return: None, ``expr`` is normalized in-place as needed.
    rx   rG   FNr   r   )r\   r
   r   re   rp   )rD   r   rG   r   r   r   check_event?  s    	
r   )exprsr   c                 C   sN  | D ]B}|j }|j}d|v r q| h d@ }t|dkrFt|d| }t|| |d|  tt|| }|	|| t
||| |r|j|krt|d|j || n|jjrt|d|dkrt|||dd	gg d
 t| n4|dkr6t|||g dddg t|d t|d	  t| n|dkrnt|||dd	gddg t|d	  t| n|dkrt|||dd	gg d t|d	  t| n~|dkrt|||dgg d t|d	 t| nF|dkrt|||dgg d t|d	 t| nds$J dt||| t|d| t| q| S )a  
    Validate and normalize a list of parsed QAPI schema expressions.

    This function accepts a list of expressions and metadata as returned
    by the parser.  It destructively normalizes the expressions in-place.

    :param exprs: The list of expressions to normalize and validate.

    :raise QAPISemError: When any expression fails validation.
    :return: The same list of expressions (now modified).
    include>   	alternater   r+   rw   r*   r   r   z_expression must have exactly one key 'enum', 'struct', 'union', 'alternate', 'command', 'event'z'%s'z!documentation comment is for '%s'zdocumentation comment requiredrw   rx   )rZ   rk   ry   r   )r   r   r   rx   rZ   rk   r   r   r   )r   rZ   rk   r+   )
rx   r   rG   rZ   rk   rE   rF   rH   rI   rJ   r*   )rx   rG   rZ   rk   Fzunexpected meta type)r   dockeysr?   r
   popr   r   r   set_defnr/   ZsymbolZ
check_exprr,   doc_requiredrC   r   rc   r\   r   r   r   r   r   r^   rm   rL   )r   rD   r   r   Zmetasr)   r   r   r   r   check_exprsS  s    














r   )FF)-__doc__r   typingr   r   r   r   r   r   commonr	   errorr
   parserr   r   r   compile
IGNORECASEr   r[   r   r   r   r#   boolr'   r(   r/   rC   rL   r^   rc   re   rf   ro   rp   rm   r   r   r   r   r   r   r   r   r   r   r   <module>   st    	  
%
?,	"'