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 log_tools import warning_log
20from parse_arguments import parse_argument
21from parse_method import parse_method_or_constructor
22from text_tools import (
23    smart_split_by,
24    find_first_not_restricted_character,
25    smart_find_first_of_characters,
26    find_first_of_characters,
27    find_scope_borders,
28)
29
30
31def parse_struct_body(data: str) -> list:
32    res = []
33    for x in smart_split_by(data, ";"):
34        if x.find("(") != -1:
35            res.append(parse_method_or_constructor(x, 0)[1])
36        else:
37            res.append(parse_argument(x))
38    return [x for x in res if x]
39
40
41def parse_struct(data: str, start: int = 0) -> Tuple[int, Dict]:
42    res: Dict[str, Any] = {}
43    check = data.find("struct ", start)
44
45    if check == -1:
46        raise RuntimeError("Error! No need to parse struct.")
47
48    start_of_name = find_first_not_restricted_character(" ", data, check + len("struct "))
49    end_of_name = find_first_of_characters(" ;{\n", data, start_of_name)
50    struct_name = data[start_of_name:end_of_name]
51
52    if struct_name == "":
53        raise RuntimeError("Error! No name in struct\n")
54
55    res["name"] = struct_name
56    start_of_body = smart_find_first_of_characters("{", data, end_of_name)
57    next_semicolon = smart_find_first_of_characters(";", data, end_of_name)
58
59    if start_of_body == len(data) or next_semicolon < start_of_body:
60        warning_log("Empty body in struct '" + struct_name + "'")
61        return end_of_name, res
62
63    start_of_body, end_of_body = find_scope_borders(data, start_of_body)
64
65    struct_members = parse_struct_body(data[start_of_body + 1 : end_of_body])
66    res["members"] = struct_members
67
68    return end_of_body, res
69