File size: 6,739 Bytes
2ef05ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
#!/usr/bin/env python3
"""Best-effort compile/syntax checks per language for SecureCodePairs.

Toolchains available on the build host are used for real checks:
  Python (ast), C/C++ (gcc/g++ -fsyntax-only), Rust (rustc), Ruby (ruby -c),
  JavaScript (node --check), Go (go vet) for standalone code,
  Java (javac) for standalone code.
Framework-dependent snippets (Flask/Spring/Gin/Rails/Express/Next/ASP.NET/TS
modules) are detected via markers and fall back to a brace/paren heuristic so
the build stays reproducible without those packages installed.
Missing toolchains degrade gracefully (reported as warnings).
"""
import os
import shutil
import subprocess
import tempfile

# Markers that indicate a framework-dependent snippet unsuitable for standalone compile.
FRAMEWORK_MARKERS = {
    "Java": ("org.springframework", "@RestController", "@Controller", "@Service",
             "@SpringBootApplication", "@GetMapping", "@PostMapping", "@RequestMapping",
             "@Repository", "import org."),
    "Go": ("gin.", "github.com/gin-gonic", "google.golang.org/grpc", "func "),
    "TypeScript": ("import ", "export ", "@"),
    "C#": ("using Microsoft", "[ApiController]", "ControllerBase", "using "),
    "PHP": ("Laravel", "Illuminate", "Artisan", "<?php", "namespace "),
    "Kotlin": ("android.", "import androidx", "findViewById", "import "),
    "Swift": ("import UIKit", "import SwiftUI", "@objc", "import "),
    "Scala": ("akka", "play.api", "import scala", "object "),
    "Rust": ("actix", "use actix", "use ", "rocket", "tokio", "impl "),
    "Ruby": ("Rails", "ActiveRecord", "gem ", "class ", "def "),
    "Python": ("from flask", "from django", "from fastapi", "import "),
    "JavaScript": ("require(", "import ", "app.", "module.exports", "@Controller", "@Injectable", "@Get", "@Post"),
    "C++": ("QProcess", "QString", "Qt", "QApplication", "#include <Q"),
    "C": ("#include", "func "),
}

CHECKERS = {}


def _have(cmd):
    return shutil.which(cmd) is not None


def _write_temp(ext, code):
    fd, path = tempfile.mkstemp(suffix=ext)
    with os.fdopen(fd, "w", encoding="utf-8") as f:
        f.write(code)
    return path


def _framework(language, code):
    for m in FRAMEWORK_MARKERS.get(language, ()):
        if m in code:
            return True
    return False


def _heuristic(code, lang):
    if code.count("{") != code.count("}"):
        return False, f"brace mismatch {code.count('{')}/{code.count('}')}"
    if code.count("(") != code.count(")"):
        return False, "paren mismatch"
    if code.count("[") != code.count("]"):
        return False, "bracket mismatch"
    return True, f"{lang}: heuristic (no/limited compiler)"


def check_python(code):
    try:
        import ast
        ast.parse(code)
        return True, ""
    except SyntaxError as e:
        return False, str(e)


def check_java(code):
    if _framework("Java", code):
        return _heuristic(code, "java")
    if not _have("javac"):
        return None, "javac missing"
    p = _write_temp(".java", code)
    try:
        r = subprocess.run(["javac", "-d", tempfile.gettempdir(), p],
                           capture_output=True, text=True, timeout=60)
        return (r.returncode == 0, r.stderr[:300])
    except Exception as e:  # noqa
        return False, str(e)
    finally:
        os.remove(p)


def check_go(code):
    if _framework("Go", code):
        return _heuristic(code, "go")
    if not _have("go"):
        return None, "go missing"
    p = _write_temp(".go", code)
    try:
        r = subprocess.run(["go", "vet", p], capture_output=True, text=True, timeout=120)
        return (r.returncode == 0, r.stderr[:300])
    except Exception as e:  # noqa
        return False, str(e)
    finally:
        os.remove(p)


def check_rust(code):
    if not _have("rustc"):
        return None, "rustc missing"
    p = _write_temp(".rs", code)
    try:
        r = subprocess.run(["rustc", "--edition", "2021", "-o", os.devnull, p],
                           capture_output=True, text=True, timeout=120)
        return (r.returncode == 0, r.stderr[:300])
    except Exception as e:  # noqa
        return False, str(e)
    finally:
        os.remove(p)


def check_c(code):
    if _framework("C", code):
        return _heuristic(code, "c")
    if not _have("gcc"):
        return None, "gcc missing"
    p = _write_temp(".c", code)
    try:
        r = subprocess.run(["gcc", "-fsyntax-only", p], capture_output=True, text=True, timeout=60)
        return (r.returncode == 0, r.stderr[:300])
    except Exception as e:  # noqa
        return False, str(e)
    finally:
        os.remove(p)


def check_cpp(code):
    if _framework("C++", code):
        return _heuristic(code, "cpp")
    if not _have("g++"):
        return None, "g++ missing"
    p = _write_temp(".cpp", code)
    try:
        r = subprocess.run(["g++", "-fsyntax-only", p], capture_output=True, text=True, timeout=60)
        return (r.returncode == 0, r.stderr[:300])
    except Exception as e:  # noqa
        return False, str(e)
    finally:
        os.remove(p)


def check_ruby(code):
    if not _have("ruby"):
        return None, "ruby missing"
    p = _write_temp(".rb", code)
    try:
        r = subprocess.run(["ruby", "-c", p], capture_output=True, text=True, timeout=30)
        return (r.returncode == 0, r.stderr[:300])
    except Exception as e:  # noqa
        return False, str(e)
    finally:
        os.remove(p)


def check_js(code):
    if not _have("node"):
        return None, "node missing"
    p = _write_temp(".js", code)
    try:
        r = subprocess.run(["node", "--check", p], capture_output=True, text=True, timeout=30)
        return (r.returncode == 0, r.stderr[:300])
    except Exception as e:  # noqa
        return False, str(e)
    finally:
        os.remove(p)


def check_ts(code):
    # tsc needs module types; use heuristic for TS modules.
    return _heuristic(code, "ts")


def check_csharp(code):
    return _heuristic(code, "csharp")


def check_scala(code):
    return _heuristic(code, "scala")


def check_kotlin(code):
    return _heuristic(code, "kotlin")


def check_swift(code):
    return _heuristic(code, "swift")


def check_php(code):
    return _heuristic(code, "php")


CHECKERS = {
    "Python": check_python,
    "Java": check_java,
    "Go": check_go,
    "Rust": check_rust,
    "C": check_c,
    "C++": check_cpp,
    "Ruby": check_ruby,
    "JavaScript": check_js,
    "TypeScript": check_ts,
    "C#": check_csharp,
    "Scala": check_scala,
    "Kotlin": check_kotlin,
    "Swift": check_swift,
    "PHP": check_php,
}


def check(language: str, code: str):
    fn = CHECKERS.get(language)
    if not fn:
        return None, "no checker"
    return fn(code)