MCPcopy
hub / github.com/marimo-team/marimo / to_cell_def

Method to_cell_def

marimo/_ast/parse.py:266–394  ·  view source on GitHub ↗
(
        self, node: FnNode, kwargs: dict[str, Any]
    )

Source from the content-addressed store, hash-verified

264 return ParseResult(fixed_dedent(code), violations=violations)
265
266 def to_cell_def(
267 self, node: FnNode, kwargs: dict[str, Any]
268 ) -> ParseResult[CellDef]:
269 # A general note on the apparent brittleness of this code:
270 # - Ast line reference and col index is on a 1-indexed basis
271 # - Multiline statements need to be accounted for
272 # - Painstaking testing can be found in test/_ast/test_{load, parse}
273
274 function_code_result = self.extract_from_code(node)
275 violations = function_code_result.violations
276 function_code = function_code_result.unwrap()
277
278 lineno_offset, col_offset = extract_offsets_post_colon(
279 function_code,
280 block_start="def",
281 )
282 start_lineno = node.lineno + lineno_offset
283
284 end_lineno = _none_to_0(node.end_lineno)
285 end_col_offset = node.end_col_offset
286 assert len(node.body) > 0
287 if node.lineno - node.body[0].lineno == 0:
288 # Quirk where the ellipse token seems to have a line index at
289 # the end of the dots ...<
290 if _is_ellipsis(getattr(node.body[0], "value", None)):
291 col_offset += node.body[0].col_offset - 3
292 else:
293 col_offset += node.body[0].col_offset - 1
294 else:
295 col_offset = 0
296
297 has_return = isinstance(node.body[-1], ast.Return)
298 single_line = node.lineno - node.body[-1].lineno == 0
299 if has_return:
300 # we need to adjust for the trailing return statement
301 # which is not included in the function body
302 if len(node.body) > 1:
303 end_lineno = max(
304 _none_to_0(node.body[-2].end_lineno),
305 node.body[-1].lineno - 1,
306 )
307 end_col_offset = len(self.lines[end_lineno - 1]) + 1
308 if node.body[-1].end_lineno == end_lineno:
309 end_lineno = node.body[-1].lineno
310 end_col_offset = node.body[-1].col_offset
311
312 # We're in the case where we have something like
313 # @app.cell
314 # def foo():
315 # # Just comments
316 # return
317 else:
318 # If we are on the same line as the return statement,
319 # just return a blank cell.
320 if start_lineno == node.body[0].lineno:
321 return ParseResult(
322 CellDef(
323 code="",

Callers 1

to_cellMethod · 0.95

Calls 12

extract_from_codeMethod · 0.95
extract_from_offsetsMethod · 0.95
CellDefClass · 0.90
_none_to_0Function · 0.85
_is_ellipsisFunction · 0.85
rangeFunction · 0.85
fixed_dedentFunction · 0.85
unwrapMethod · 0.80
stripMethod · 0.80
ParseResultClass · 0.70
joinMethod · 0.45

Tested by

no test coverage detected