#!/bin/bash

function convert_types {
    # Convert the various styles of typing found in docstrings into
    # actual typing types.
    sed -r -i \
        -e '/# type:/s/`([^`]+)`/\1/g' \
        -e '/# type:/s/~//g' \
        -e '/# type:/s/<>//g' \
        -e '/# type:/s/:obj://g' \
        -e '/# type:/s/:py:obj://g' \
        -e '/# type:/s/:class://g' \
        -e '/# type:/s/:exc://g' \
        -e '/# type:/s/obj://g' \
        -e '/# type:/s/boolean/bool/g' \
        -e '/# type:/s/string/str/g' \
        -e '/# type:/s/:pystr/str/g' \
        -e '/# type:/s/callable/Callable/g' \
        -e '/# type:/s/seq<([^>]+)>/Sequence[\1]/g' \
        -e '/# type:/s/sequence<([^\\>]+)>/Sequence[\1]/g' \
        -e '/# type:/s/list ?<([^\\>]+)\\?>/List[\1]/g' \
        -e '/# type:/s/list\(([^\\>]+)\)/List[\1]/g' \
        -e '/# type:/s/set ?<([^\\>]+)\\?>/Set[\1]/g' \
        -e '/# type:/s/dict ?<([^\\>]+)\\?>/Dict[\1]/g' \
        -e '/# type:/s/dict ?\{([a-z]+): ?([a-z]+)\}/Dict[\1, \2]/g' \
        -e '/# type:/s/dict/Dict/g' \
        -e '/# type:/s/<list>/List/g' \
        -e '/# type:/s/list/List/g' \
        -e '/# type:/s/tuple<([^>]+)\\?>/Tuple[\1]/g' \
        -e '/# type:/s/tuple\(([^>]+)\)/Tuple[\1]/g' \
        -e '/# type:/s/iter ?<([^\\>]+)\\?>/Iterator[\1]/g' \
        -e '/# type:/s/position\(float\?\) ?/float/g' \
        -e '/# type:/s/value\(float\?\) ?/float/g' \
        -e '/# type:/s/([][A-Za-z.]+) or None/Optional[\1]/g' \
        -e '/# type:/s/([][A-Za-z.]+) or ([][A-Za-z.]+)/Union[\1, \2]/g' \
        $1
}

DOCTYPED_MODULES=$(rgrep -Icl "    :r\?type" src/sardana)

for MODULE in ${DOCTYPED_MODULES[@]}
do
    echo $MODULE
    doc484 $MODULE -f rest -w
    convert_types $MODULE
    com2ann $MODULE
done
