Skip to content

Commit

Permalink
Add implicit returns to evals where last statement is an expr
Browse files Browse the repository at this point in the history
  • Loading branch information
IAmTomahawkx committed Jul 25, 2023
1 parent 806a6fb commit d7b5132
Showing 1 changed file with 20 additions and 1 deletion.
21 changes: 20 additions & 1 deletion modules/eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,10 @@
"""
from __future__ import annotations

import ast
import logging
import textwrap
import traceback

from discord.ext import commands

Expand Down Expand Up @@ -56,7 +58,24 @@ def __init__(self, bot: core.Bot, endpoint_url: str) -> None:
self.eval_endpoint: str = endpoint_url

async def perform_eval(self, code: core.Codeblock) -> str:
formatted = CODE.format(user_code=textwrap.indent(code.content.replace("\t", " "), " "))
source = code.content

try:
parsed = ast.parse(source, filename="<input>")
except SyntaxError as e:
return "".join(traceback.format_exception(type(e), e, e.__traceback__))

if isinstance(parsed.body[-1], ast.Expr):
expr: ast.Expr = parsed.body[-1]

lineno = expr.lineno - 1

co_mangled = source.splitlines()
co_mangled[lineno] = "return " + co_mangled[lineno]

source = "\n".join(co_mangled)

formatted = CODE.format(user_code=textwrap.indent(source.replace("\t", " "), " "))

async with self.bot.session.post(self.eval_endpoint, json={"input": formatted}) as eval_response:
if eval_response.status != 200:
Expand Down

0 comments on commit d7b5132

Please sign in to comment.