File size: 7,520 Bytes
234f07a
 
 
 
fa26615
234f07a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa26615
 
 
 
 
234f07a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa26615
234f07a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa26615
 
 
 
234f07a
 
 
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
"""Fixed base-model code completion. No reference/test fields are read."""
import io
import re
import tokenize
PROMPT_VERSION='smolscript-base-completion-v3'
SIGNATURES={
 'python':{'scalar':'def solve(n):','string':'def solve(s):','array':'def solve(values):'},
 'javascript':{'scalar':'function solve(n)','string':'function solve(s)','array':'function solve(values)','dom':'function setup()'},
 'cpp':{'scalar':'long long solve(long long n)','string':'std::string solve(std::string s)','array':'long long solve(const std::vector<long long>& values)'},
 'c':{'scalar':'long long solve(long long n)','string':'const char *solve(const char *input)','array':'long long solve(const long long *values, int length)'},
 'lua':{'scalar':'function solve(n)','string':'function solve(s)','array':'function solve(values)'},
 'csharp':{'scalar':'public static long Solve(long n)','string':'public static string Solve(string s)','array':'public static long Solve(long[] values)'},
 'rust':{'scalar':'fn solve(mut n: i64) -> i64','string':'fn solve(mut s: String) -> String','array':'fn solve(values: Vec<i64>) -> i64'},
}

def prefix(row):
    lang=row['language'];kind=row['metadata']['family']
    if lang=='html':return '<'
    if lang=='css':return ''
    header=SIGNATURES[lang][kind]
    if lang=='python':return header+'\n'
    if lang=='lua':return header+'\n'
    if kind=='dom':return header+' {\n'
    if lang=='csharp':return 'public class Solution {\n'+header+' {\n'
    return header+' {\n'

def prompt(row):
    from runners.protocol import HEADERS
    lang=row['language'];meta=row['metadata']
    task=re.sub(r'^In [^,]+,\s*','',row['prompt'])
    task=task.replace(' Return CSS only.','').replace(' Return an HTML fragment.','')
    task=task.removeprefix('Implement setup(). ')
    details=[task]
    if meta.get('input_domain'):details.append(meta['input_domain'])
    context=[]
    if meta.get('fixture'):context.append('HTML fixture: '+meta['fixture'])
    if meta.get('base_css'):context.append('Existing CSS: '+meta['base_css'])
    details=context+details
    if lang=='html':comment='<!-- '+ ' '.join(details).replace('-->','-- >')+' -->\n'
    elif lang=='css':comment='/* '+ ' '.join(details).replace('*/','* /')+' */\n'
    else:
        marker='#' if lang=='python' else '--' if lang=='lua' else '//'
        comment='\n'.join(marker+' '+line for line in details)+'\n'
    return comment+HEADERS.get(lang,'')+prefix(row)


def _brace_end(source):
    """First complete braced function/class, ignoring quoted strings/comments.

    Lexer-only delimiting: never evaluate, fix or choose code by test success.
    """
    depth=0;opened=False;i=0;previous=''
    while i<len(source):
        if source.startswith('//',i):
            end=source.find('\n',i);i=len(source) if end<0 else end+1;continue
        if source.startswith('/*',i):
            end=source.find('*/',i+2)
            if end<0:return len(source)
            i=end+2;continue
        # C/C++/C#/JS/Rust strings and character literals; Rust lifetimes are
        # identifiers, not single-quoted characters.
        ch=source[i]
        raw=re.match(r'(?:u8|u|U|L)?R"([^\s()\\]{0,16})\(',source[i:])
        if raw:
            end=source.find(')'+raw.group(1)+'"',i+raw.end())
            if end<0:return len(source)
            i=end+len(raw.group(1))+2;previous='v';continue
        word=re.match(r'[A-Za-z_$][\w$]*',source[i:])
        if word:
            previous=word.group();i+=len(previous);continue
        if ch in ('"','`') or (ch=="'" and re.match(r"'(?:\\.|[^'\\\n])'",source[i:])):
            quote=ch;verbatim=quote=='"' and i>0 and source[i-1]=='@';i+=1
            while i<len(source):
                if source[i]=='\\' and not verbatim:i+=2;continue
                if source[i]==quote:
                    if quote=='"' and i+1<len(source) and source[i+1]=='"' and verbatim:
                        i+=2;continue
                    i+=1;break
                i+=1
            previous='v';continue
        # JS regular-expression literals occurring where an expression begins.
        if ch=='/' and previous in ('=', '(', ',', ':', '[', '!', '?', 'return', 'throw', 'case', '=>'):
            j=i+1;inside=False
            while j<len(source) and source[j]!='\n':
                if source[j]=='\\':j+=2;continue
                if source[j]=='[':inside=True
                if source[j]==']':inside=False
                if source[j]=='/' and not inside:i=j+1;break
                j+=1
            else:i+=1
            previous='v';continue
        if ch=='{':depth+=1;opened=True
        elif ch=='}':
            depth-=1
            if opened and depth==0:return i+1
        if not ch.isspace():previous='=>' if ch=='>' and previous=='=' else ch
        i+=1
    return len(source)


def _python_end(source):
    depth=0;body=False
    try:
        for token in tokenize.generate_tokens(io.StringIO(source).readline):
            if token.type==tokenize.INDENT:depth+=1;body=True
            elif token.type==tokenize.DEDENT:
                depth-=1
                if body and depth==0:return sum(len(x) for x in source.splitlines(keepends=True)[:token.start[0]-1])
    except (tokenize.TokenError,IndentationError):pass
    return len(source)


def _lua_end(source):
    # Tokenize strings/comments first, then count Lua's block delimiters.
    pattern=r'--\[\[.*?\]\]|--[^\n]*|\[(=*)\[.*?\]\1\]|"(?:\\.|[^"\\])*"|\'(?:\\.|[^\'\\])*\'|\b(?:function|if|for|while|do|repeat|end|until)\b'
    depth=0;loops=0
    for match in re.finditer(pattern,source,re.S):
        word=match.group()
        if word in ('function','if','repeat'):depth+=1
        elif word in ('for','while'):depth+=1;loops+=1
        elif word=='do':
            if loops:loops-=1
            else:depth+=1
        elif word in ('end','until'):
            depth-=1
            if depth==0:return match.end()
    return len(source)


def assemble(row,continuation):
    """Attach the supplied header; keep the first completed entry-point scope.

    No indentation, expressions, missing delimiters or return values are repaired.
    A complete function emitted from scratch is accepted as a format alternative.
    """
    lang=row['language']
    text=continuation
    if text.lstrip().startswith('```'):
        from runners.common import extract_code
        text=extract_code(text,preserve_indentation=True)
    expected=prefix(row)
    starts={
       'python':r'^def\s+solve\s*\(', 'javascript':r'^(?:async\s+)?function\s+(?:solve|setup)\s*\(',
       'lua':r'^function\s+solve\s*\(', 'csharp':r'^public\s+class\s+Solution\b',
       'rust':r'^fn\s+solve\s*\(', 'cpp':r'^(?:long\s+long|std::string)\s+solve\s*\(',
       'c':r'^(?:long\s+long|const\s+char\s*\*)\s*solve\s*\(',
    }
    complete_python=False
    if lang=='python':
        import ast
        try:complete_python=any(isinstance(n,ast.FunctionDef) and n.name=='solve' for n in ast.parse(text).body)
        except SyntaxError:pass
    if complete_python:code=text.lstrip()
    elif lang in starts and re.match(starts[lang],text.lstrip()):code=text.lstrip()
    elif lang=='html' and text.lstrip().startswith('<'):code=text.lstrip()
    else:code=expected+text
    if lang=='python' and not complete_python:
        import ast
        try:ast.parse(code)
        except SyntaxError:code=code[:_python_end(code)]
    elif lang=='lua':code=code[:_lua_end(code)]
    elif lang not in ('html','css','python'):code=code[:_brace_end(code)]
    return code.rstrip()+'\n'