File: read_declare.py

package info (click to toggle)
python-mcstasscript 0.0.46%2Bgit20250402111921.bfa5a26-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 11,440 kB
  • sloc: python: 13,421; makefile: 14
file content (284 lines) | stat: -rw-r--r-- 10,561 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
from mcstasscript.instr_reader.util import SectionReader


class DeclareReader(SectionReader):
    """
    Reads the declare section of a McStas instrument file and adds
    the found parameters / functions / structs to the McStasScript
    Instr instance. The information can also be written to a python
    file for reproduction of a McStas instrument.
    """

    def __init__(self, Instr, write_file, product_filename,
                 get_next_line, return_line):

        super().__init__(Instr, write_file, product_filename,
                         get_next_line, return_line)

        self.in_declare_function = False
        self.in_struct_definition = False
        self.bracket_counter = 0

    def read_declare_line(self, line):
        """
        Reads line of instrument declare, returns bolean.  If it encounters
        the end of the declare section, it returns False, otherwise True.

        The contents of the declare section is written to the McStasScript
        Instr object.
        """

        continue_declare = True

        # Remove comments
        if "//" in line:
            line = line.split("//", 1)[0]

        # Remove %} and signify end if this is found
        if "%}" in line:
            continue_declare = False
            line = line.split("%}", 1)[0]

        if "/*" in line:
            line = line.split("/*", 1)[0].strip()

        if self.in_declare_function:
            if "{" in line:
                self.bracket_counter += 1

            if "}" in line:
                self.bracket_counter -= 1

            if self.bracket_counter == 0:
                self.in_declare_function = False

            self.Instr.append_declare(line)
            self._write_declare_line(line)

        # Check for functions
        if ("(" in line and ";" not in line and " " in line.strip()
                and not self.in_declare_function and "#pragma" not in line):

            # If in function, it will define a block
            n_curly_brackets = line.count("{")
            n_curly_brackets -= line.count("}")

            while n_curly_brackets != 0 or ("{" not in line):
                next_line = self.get_next_line()
                line += next_line

                n_curly_brackets = line.count("{")
                n_curly_brackets -= line.count("}")

            after_curly_bracket = line.split("}")[-1]

            declare_lines = line.split("\n")
            for declare_line in declare_lines:
                declare_line = declare_line.rstrip()
                declare_line = declare_line.replace('\\n', "\\\\n")
                declare_line = declare_line.replace('"', "\\\"")
                self.Instr.append_declare(declare_line)
                self._write_declare_line(declare_line)

            line = after_curly_bracket

        # Check for struct / function that returns struct
        if line.strip().startswith("struct "):
            # Can be a function returning struct or struct definition

            # If struct definition, no parenthesis and ; after )
            n_curly_brackets = line.count("{")
            n_curly_brackets -= line.count("}")

            # Add lines until end of block found
            while n_curly_brackets != 0 or ("{" not in line):

                next_line = self.get_next_line()
                line += next_line

                n_curly_brackets = line.count("{")
                n_curly_brackets -= line.count("}")

                if "{" in line:
                    before_curly_bracket = line.split("{", 1)[0]
                    if "(" in before_curly_bracket and ")" in before_curly_bracket:
                        # This is a function that returns a struct!
                        self.in_declare_function = True

            after_curly_bracket = line.split("}")[-1]

            # if not in function, add until ; is found
            while ";" not in after_curly_bracket and not self.in_declare_function:
                # It is surely a struct, find ;
                line += self.get_next_line()
                after_curly_bracket = line.split("}")[-1]

            declare_lines = line.split("\n")
            for declare_line in declare_lines:
                declare_line = declare_line.rstrip()
                declare_line = declare_line.replace('\\n', "\\\\n")
                declare_line = declare_line.replace('"', "\\\"")
                self.Instr.append_declare(declare_line)
                self._write_declare_line(declare_line)

            if self.in_declare_function:
                line = line.split("}")[-1].strip()
            else:
                line = line.split(";")[-1].strip()

            # if in function, stop now
            self.in_declare_function = False

        # Grab defines and pragmas
        if line.strip().startswith("#define") or line.strip().startswith("#pragma"):
            # Include define statements as declare append
            line = line.rstrip()
            line = line.replace('\\n', "\\\\n")
            line = line.replace('"', "\\\"")
            self.Instr.append_declare(line)
            self._write_declare_line(line)

        if "\n" in line:
            line = line.strip("\n")

        # Read single line parameter definitions
        if ";" in line and not self.in_declare_function:
            # This line contains c statements
            statements = line.split(";")

            for statement in statements:
                statement = statement.strip()
                if (statement != "\n" and statement != " "
                        and len(statement) > 1):
                    self._read_declare_statement(statement)

        return continue_declare

    def _read_declare_statement(self, statement):
        """
        Reads single declare statements, which can have multiple
        variables.
        """

        statement = statement.strip()

        # Find type (same for all parameters in one statement)
        this_type = statement.split(" ", 1)[0]
        statement = statement.split(" ", 1)[1].strip()

        if this_type == "const":  # other c keywords to consider?
            this_type += " " + statement.split(" ", 1)[0]
            statement = statement.split(" ", 1)[1].strip()

        # Check for bracket initialization of arrays
        if "," in statement:
            variables = statement.split(",")
            fixed_variables = []
            array_mode = False
            for variable in variables:

                if "{" not in variable and array_mode is False:
                    fixed_variables.append(variable)
                elif "{" in variable:
                    temp_variable = variable + ","
                    array_mode = True
                elif "}" not in variable:
                    temp_variable += variable + ","
                else:
                    temp_variable += variable
                    fixed_variables.append(temp_variable)
                    array_mode = False

            variables = fixed_variables

        else:
            # No commas means just one parameter
            variables = [statement]

        # Treat each variable independently
        for variable in variables:
            variable = variable.strip()

            dynamic_size = False
            kw_args = {}

            if "=" in variable:
                value = variable.split("=")[1].strip()
                # remove the value part before proceeding
                variable = variable.split("=")[0].strip()

                if "{" in value:
                    # handle array as value
                    value = value.split("{")[1]
                    if "{" in value:
                        raise ValueError("Can not load arrays with larger"
                                         + "than 1 dimension yet.")
                    value = value.split("}")[0]
                    values = value.split(",")
                    return_value = []
                    for val in values:
                        return_value.append(float(val))
                else:
                    try:
                        return_value = float(value)
                    except:
                        value = value.replace('"', "\\\"")
                        #return_value = '"' + value + '"'
                        return_value = value

                kw_args["value"] = return_value

            # Handle array
            if "[" in variable:
                array_sizes = []
                array_size_strings = variable.split("[")
                # remove the array size part before proceeding
                variable = variable.split("[", 1)[0].strip()
                for array_size_string in array_size_strings:
                    if "]" in array_size_string:
                        this_size = array_size_string.split("]")[0]
                        try:
                            # Size declared normally
                            array_sizes.append(int(this_size))
                        except:
                            # No size declared means the size is automatic
                            dynamic_size = True

                if len(array_sizes) > 1:
                    raise ValueError("Can not handle arrays with larger"
                                     + " than 1 dimension yet")
                if not dynamic_size:
                    kw_args["array"] = array_sizes[0]

            if dynamic_size:
                # McStasScript needs size of array, so it is found manually
                kw_args["array"] = len(kw_args["value"])

            # value, array and typeremoved, all that remians is the name
            variable_name = variable
            self.Instr.add_declare_var(this_type, variable_name, **kw_args)

            # Also write it to a file?
            write_string = []
            write_string.append(self.instr_name)
            write_string.append(".add_declare_var(")
            write_string.append("\"" + this_type + "\"")
            write_string.append(", ")
            write_string.append("\"" + variable_name + "\"")
            write_string.append(self._kw_to_string(kw_args))
            write_string.append(")\n")

            # Write declare parameter to python file
            self._write_to_file(write_string)

    def _write_declare_line(self, string):

        string = string.rstrip()

        write_string = []
        write_string.append(self.instr_name)
        write_string.append(".append_declare(")
        write_string.append("\"" + string + "\"")
        write_string.append(")\n")

        self._write_to_file(write_string)