mirror of
https://github.com/gristlabs/grist-core.git
synced 2024-10-27 20:44:07 +00:00
(core) Use grist syntactic sugar in AI generated formulas
Summary: Converts `rec.` to `$` in AI generated formulas, and removes redundant `return` at the end. Test Plan: Expanded unit test. Reviewers: dsagal Reviewed By: dsagal Differential Revision: https://phab.getgrist.com/D3933
This commit is contained in:
parent
25b71c4e57
commit
3defb89866
@ -4,6 +4,7 @@ import re
|
|||||||
import textwrap
|
import textwrap
|
||||||
|
|
||||||
import asttokens
|
import asttokens
|
||||||
|
import asttokens.util
|
||||||
import six
|
import six
|
||||||
|
|
||||||
from column import is_visible_column, BaseReferenceColumn
|
from column import is_visible_column, BaseReferenceColumn
|
||||||
@ -230,10 +231,29 @@ def convert_completion(completion):
|
|||||||
if imports:
|
if imports:
|
||||||
result = imports + "\n" + result
|
result = imports + "\n" + result
|
||||||
|
|
||||||
# Check that we still have valid code.
|
# Now convert `rec.` to `$` and remove redundant `return ` at the end.
|
||||||
try:
|
try:
|
||||||
ast.parse(result)
|
atok = asttokens.ASTTokens(result, parse=True)
|
||||||
except SyntaxError:
|
except SyntaxError:
|
||||||
return ""
|
# In case the above extraction somehow messed things up
|
||||||
|
return ""
|
||||||
|
|
||||||
|
replacements = []
|
||||||
|
for node in ast.walk(atok.tree):
|
||||||
|
if isinstance(node, ast.Attribute):
|
||||||
|
start, end = atok.get_text_range(node.value)
|
||||||
|
end += 1
|
||||||
|
if result[start:end] == "rec.":
|
||||||
|
replacements.append((start, end, "$"))
|
||||||
|
|
||||||
|
last_stmt = atok.tree.body[-1]
|
||||||
|
if isinstance(last_stmt, ast.Return):
|
||||||
|
start, _ = atok.get_text_range(last_stmt)
|
||||||
|
expected = "return "
|
||||||
|
end = start + len(expected)
|
||||||
|
if result[start:end] == expected:
|
||||||
|
replacements.append((start, end, ""))
|
||||||
|
|
||||||
|
result = asttokens.util.replace(result, replacements)
|
||||||
|
|
||||||
return result.strip()
|
return result.strip()
|
||||||
|
@ -236,10 +236,12 @@ from x import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def foo():
|
def foo(rec):
|
||||||
'''This is a docstring'''
|
'''This is a docstring'''
|
||||||
x = 5
|
x = f"hello {rec.name} " + rec.name + "!"
|
||||||
return 1
|
if rec.bar.spam:
|
||||||
|
return 0
|
||||||
|
return rec.a * rec.b
|
||||||
```
|
```
|
||||||
|
|
||||||
Hope you like it!
|
Hope you like it!
|
||||||
@ -251,5 +253,7 @@ from x import (
|
|||||||
z,
|
z,
|
||||||
)
|
)
|
||||||
|
|
||||||
x = 5
|
x = f"hello {rec.name} " + $name + "!"
|
||||||
return 1""")
|
if $bar.spam:
|
||||||
|
return 0
|
||||||
|
$a * $b""")
|
||||||
|
Loading…
Reference in New Issue
Block a user