[Python] 轉化gcc extension中的case range

來源:互聯網
上載者:User

gcc extension中有case range的用法,如:

case 0x10 ... 0x1f:

這種用法在一些編譯器中無法支援,如MSVC。下面是一個自動將case range自動轉化為非case range且等價用法的指令碼。可以處理一行多個case的情況。

 

如有main.c:

#include <stdio.h>int main(){    int x;    scanf("%d", &x);        switch(x) {        case 0x01:  case 0x03 ... 0x10:            printf("case 1\n");            break;        case 0x1f ... 0x2f:            printf("case 2\n");            break;        default:            printf("case 3\n");            break;    }    return 0;}

指令碼case_range_converter.py:

#!/usr/bin/pythonimport rewhile True:    try:        text = raw_input()    except EOFError:        break    leading_space = ""    result = re.findall(r"(\s*)case\s+0x([\da-f]+)(\s*\.\.\.\s*0x([\da-f]+))?", text)    if result:        for elem in result:            if elem[0] and not leading_space:                leading_space = elem[0]            low_bound_str = elem[1]             if elem[2]:                high_bound_str = elem[3]            else:                high_bound_str = elem[1]            low_bound = int(low_bound_str, 16)            high_bound = int(high_bound_str, 16)#    print low_bound#    print high_bound            for i in range(low_bound, high_bound + 1):                print "%scase 0x%x:" % (leading_space, i)    else:        print text

運行:

./case_range_converter.py < main.c | tee main_no_case_range.c 

 

得到main_no_case_range.c:

#include <stdio.h>int main(){    int x;    scanf("%d", &x);        switch(x) {        case 0x1:        case 0x3:        case 0x4:        case 0x5:        case 0x6:        case 0x7:        case 0x8:        case 0x9:        case 0xa:        case 0xb:        case 0xc:        case 0xd:        case 0xe:        case 0xf:        case 0x10:            printf("case 1\n");            break;        case 0x1f:        case 0x20:        case 0x21:        case 0x22:        case 0x23:        case 0x24:        case 0x25:        case 0x26:        case 0x27:        case 0x28:        case 0x29:        case 0x2a:        case 0x2b:        case 0x2c:        case 0x2d:        case 0x2e:        case 0x2f:            printf("case 2\n");            break;        default:            printf("case 3\n");            break;    }    return 0;}

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.