1#!/usr/bin/env python3
2# coding=utf-8
3#
4# Copyright (c) 2024 Huawei Device Co., Ltd.
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17
18from typing import Tuple, Dict, Any
19from text_tools import find_first_not_restricted_character, find_scope_borders, find_first_of_characters, smart_split_by
20from line_iterator import LineIterator
21
22# Weakness: define define !endif! endif
23
24
25def parse_define_macros(data: str, start: int = 0) -> Tuple[int, Dict]:
26    res: Dict[str, Any] = {}
27
28    pos, res["name"] = parse_define_macros_name(data, start)
29    end_of_line = find_first_of_characters("\n", data, start)
30
31    if data[pos] == "(":
32        open_parenthesis, close_parenthesis = find_scope_borders(data, pos, "(")
33        res["arguments"] = data[open_parenthesis + 1 : close_parenthesis]
34        pos = close_parenthesis + 1
35
36    backslash_pos = find_first_of_characters("\\", data, pos)
37    if backslash_pos + 1 != end_of_line:
38        if data[pos:end_of_line].strip(" ") != "":
39            res["body"] = data[pos:end_of_line].strip(" ")
40        return end_of_line, res
41
42    it = LineIterator(data, end_of_line + 1)
43    need_to_parse = it.current_line.strip(" ").startswith("_(")
44
45    if need_to_parse:
46        res["values"] = []
47
48        while it.next_line() and it.data[it.end - 1] == "\\":
49            res["values"].append(parse_mapping_value(it.current_line))
50        res["values"].append(parse_mapping_value(it.current_line))
51        res["values"] = list(filter(None, res["values"]))
52    else:
53        while it.next_line():
54            if it.data[it.end - 1] != "\\":
55                break
56
57    return it.end, res
58
59
60def parse_mapping_value(data: str) -> list:
61    data = data.strip(" _()\\")
62    return smart_split_by(data)
63
64
65def parse_define_macros_name(data: str, start: int) -> Tuple[int, str]:
66    start_of_name = find_first_not_restricted_character(" \n", data, data.find("#define", start) + len("#define"))
67    end_of_name = find_first_of_characters(" \n({[", data, start_of_name)
68
69    if end_of_name == len(data) or start_of_name == 0:
70        raise RuntimeError("Can't find macros name.")
71
72    return end_of_name, data[start_of_name:end_of_name].strip(" \n")
73