Parse parameter names and body from a stringified lambda.
Extracts identifiers from the parameter list by stripping type tokens (everything up to and including the last space or * before the identifier). Extracts body as the text between the first { and the matching closing }.
154 {
155 KernelSource ks;
156 ks.raw = std::string(stringified);
157
158
159 const auto bracket = stringified.find('[');
160 const auto paren_open = stringified.find('(', bracket);
161 if (paren_open == std::string_view::npos)
162 return ks;
163
164 std::size_t depth = 1;
165 std::size_t paren_close = paren_open + 1;
166 while (paren_close < stringified.size() && depth > 0) {
167 if (stringified[paren_close] == '(') {
168 ++depth;
169 } else if (stringified[paren_close] == ')') {
170 --depth;
171 }
172 ++paren_close;
173 }
174 --paren_close;
175
176 const auto params_text = stringified.substr(paren_open + 1, paren_close - paren_open - 1);
177
178
179 auto extract_name = [](std::string_view param) -> std::string {
180
181 auto end = param.find_last_not_of(" \t\n\r");
182 if (end == std::string_view::npos)
183 return {};
184 param = param.substr(0, end + 1);
185
186 auto sep = param.find_last_of(" *\t");
187 if (sep == std::string_view::npos)
188 return std::string(param);
189 return std::string(param.substr(sep + 1));
190 };
191
192 std::size_t start = 0;
193 while (start < params_text.size()) {
194
195 int angle = 0, paren = 0;
196 std::size_t pos = start;
197 while (pos < params_text.size()) {
198 char c = params_text[pos];
199 if (c == '<') {
200 ++angle;
201 } else if (c == '>') {
202 --angle;
203 } else if (c == '(') {
204 ++paren;
205 } else if (c == ')') {
206 --paren;
207 } else if (c == ',' && angle == 0 && paren == 0) {
208 break;
209 }
210 ++pos;
211 }
212 auto name = extract_name(params_text.substr(start, pos - start));
213 if (!name.empty())
214 ks.param_names.push_back(std::move(name));
215 start = (pos < params_text.size()) ? pos + 1 : pos;
216 }
217
218
219 const auto brace_open = stringified.find('{', paren_close);
220 if (brace_open == std::string_view::npos)
221 return ks;
222
223 depth = 1;
224 std::size_t brace_close = brace_open + 1;
225 while (brace_close < stringified.size() && depth > 0) {
226 if (stringified[brace_close] == '{') {
227 ++depth;
228 } else if (stringified[brace_close] == '}') {
229 --depth;
230 }
231 ++brace_close;
232 }
233 --brace_close;
234
235 ks.body = std::string(stringified.substr(brace_open + 1, brace_close - brace_open - 1));
236 return ks;
237 }