File size: 16,705 Bytes
4df4f1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
"""
ALLI Parameter and Constraint Validation Engine - Phase 5 Step 5.4.
Enforces schema-driven parameter constraints, Python identifier rules, and non-finite number rejection.
Provides 100% parity with Next.js frontend validation and UI drawer controls.
"""

import math
import re
import json
import keyword
from typing import Any, Tuple, Optional, Dict, List, Set, Union
from language_core.node_schema import ParameterDefinition, ParameterType, ParameterOption


NON_FINITE_STRINGS = {
    "nan", "+nan", "-nan",
    "inf", "+inf", "-inf",
    "infinity", "+infinity", "-infinity"
}


def is_non_finite_number(val: Any) -> Tuple[bool, Optional[str]]:
    """
    Recursively inspects val to detect non-finite numbers (NaN, Inf, -Inf).
    Returns (True, token_str) if non-finite number is found, otherwise (False, None).
    Covers primitives, strings, and nested containers (lists, tuples, sets, dicts).
    """
    if val is None or isinstance(val, bool):
        return False, None

    if isinstance(val, float):
        if math.isnan(val):
            return True, "NaN"
        if math.isinf(val):
            return True, "-Infinity" if val < 0 else "Infinity"
        return False, None

    if isinstance(val, str):
        s = val.strip().lower()
        if s in NON_FINITE_STRINGS:
            return True, val.strip()
        return False, None

    if isinstance(val, (list, tuple, set)):
        for item in val:
            found, token = is_non_finite_number(item)
            if found:
                return True, token
        return False, None

    if isinstance(val, dict):
        for k, v in val.items():
            found_k, token_k = is_non_finite_number(k)
            if found_k:
                return True, token_k
            found_v, token_v = is_non_finite_number(v)
            if found_v:
                return True, token_v
        return False, None

    return False, None


def validate_python_identifier(name: Any, field_id: str = "var_name") -> Tuple[bool, Optional[str], Optional[str], Optional[str]]:
    """
    Validates identifier according to Python 3 language rules.
    - Rejects empty, whitespace-only, leading or trailing whitespace.
    - Rejects reserved Python keywords (35 keywords in Python 3).
    - Enforces valid identifier format: starts with letter or underscore, alphanumeric + underscore.
    - Supports Unicode identifier characters per PEP 3131 (via str.isidentifier()).
    - Returns (is_valid, error_code, error_message, fix_suggestion).
    """
    err_code = (
        "FUNC-E001" if ("func" in field_id or "fn" in field_id)
        else ("OOP-E001" if "class" in field_id else "COMP-E101")
    )

    if name is None or (isinstance(name, str) and not name.strip()):
        return (
            False,
            err_code,
            "Identifier name cannot be empty.",
            "Provide a valid Python identifier like 'x' or 'my_var'."
        )

    s = str(name)
    if s != s.strip():
        return (
            False,
            err_code,
            f"Identifier '{s}' contains leading or trailing whitespace.",
            "Remove leading and trailing spaces from the identifier name."
        )

    if keyword.iskeyword(s):
        return (
            False,
            err_code,
            f"Reserved Keyword Conflict: '{s}' is a reserved Python keyword and cannot be used as an identifier.",
            f"Choose a non-reserved identifier name (e.g. 'my_{s}')."
        )

    if not s.isidentifier():
        return (
            False,
            err_code,
            f"Invalid Python identifier '{s}'. Identifiers must begin with a letter or underscore and contain only alphanumeric characters or underscores without spaces or punctuation.",
            "Use letters, numbers, and underscores (cannot start with a digit or contain spaces/punctuation)."
        )

    return True, None, None, None


def validate_parameter_value(
    param: ParameterDefinition,
    val: Any,
    node_label: str = "Node",
    node_id: str = "node"
) -> Tuple[bool, Optional[str], Optional[str], Optional[str]]:
    """
    Validates a parameter value against declared constraints in ParameterDefinition:
    - Non-finite check (VAL-PARAM-NON-FINITE)
    - Required parameter check (VAL-PARAM-CONSTRAINT)
    - Python identifier check (COMP-E101, FUNC-E001, OOP-E001)
    - Numeric bounds (min_value, max_value) (VAL-PARAM-CONSTRAINT)
    - Step increment (step) (VAL-PARAM-CONSTRAINT)
    - Decimal precision (precision) (VAL-PARAM-CONSTRAINT)
    - Select options & enum_values membership (VAL-PARAM-CONSTRAINT)
    - Safe regular expression pattern check (VAL-PARAM-CONSTRAINT)
    - Structured JSON list/dict check (VAL-PARAM-CONSTRAINT)
    Returns (is_valid, error_code, error_message, fix_suggestion).
    """
    # 1. Non-finite check (GAP-11)
    found_nf, token_nf = is_non_finite_number(val)
    if found_nf:
        return (
            False,
            "VAL-PARAM-NON-FINITE",
            f"Non-Finite Number Error: Parameter '{param.name}' ({param.id}) on node '{node_label}' ({node_id}) contains non-finite value '{token_nf}' (NaN or Infinity). Only finite numeric values are permitted.",
            f"Replace '{token_nf}' with a valid finite number."
        )

    # 2. Missing & Required check
    is_none = val is None
    is_empty_str = isinstance(val, str) and val.strip() == ""

    # Note: 0, 0.0, False, [], {} are NOT missing; they are valid values according to their types
    if is_none:
        if param.required:
            return (
                False,
                "VAL-PARAM-CONSTRAINT",
                f"Required Parameter Missing: Parameter '{param.name}' ({param.id}) on node '{node_label}' ({node_id}) is required but has no value.",
                f"Provide a value for '{param.name}' in the configuration drawer."
            )
        return True, None, None, None

    # Determine numeric classification
    is_int_param = param.type in (ParameterType.NUMBER, "number", "int", "integer")
    is_numeric_param = (
        is_int_param
        or param.type in ("float", "slider")
        or getattr(param, "widget", None) in ("number", "slider")
        or param.min_value is not None
        or param.max_value is not None
        or getattr(param, "step", None) is not None
        or getattr(param, "precision", None) is not None
    )

    if is_numeric_param:
        if is_empty_str:
            if param.required:
                return (
                    False,
                    "VAL-PARAM-CONSTRAINT",
                    f"Required Parameter Missing: Parameter '{param.name}' ({param.id}) on node '{node_label}' ({node_id}) requires a numeric value.",
                    f"Provide a valid finite number for '{param.name}'."
                )
            return True, None, None, None

    if not is_numeric_param and is_empty_str:
        if param.required:
            # Check if regex or identifier or select applies
            is_ident = getattr(param, "is_identifier", False) or param.id in ("var_name", "variable_name", "func_name", "fn_name", "class_name", "loop_var")
            if is_ident:
                return (
                    False,
                    "COMP-E101",
                    f"Required Identifier Missing: Parameter '{param.name}' ({param.id}) on node '{node_label}' ({node_id}) cannot be empty.",
                    "Provide a valid Python identifier."
                )
            # If plain string parameter with no regex, empty string is valid representation
            if getattr(param, "regex", None):
                try:
                    pat = re.compile(param.regex)
                    if not pat.search(""):
                        return (
                            False,
                            "VAL-PARAM-CONSTRAINT",
                            f"Parameter '{param.name}' ({param.id}) on node '{node_label}' ({node_id}) cannot be empty (must match pattern '{param.regex}').",
                            f"Provide a value matching pattern '{param.regex}'."
                        )
                except re.error:
                    pass
        else:
            return True, None, None, None

    # 3. Python Identifier check (GAP-06)
    is_identifier = (
        getattr(param, "is_identifier", False) is True
        or param.id in (
            "var_name", "variable_name", "func_name", "fn_name", "function_name",
            "class_name", "loop_var", "iter_var", "target_var"
        )
    )
    if is_identifier:
        is_valid_id, id_code, id_msg, id_fix = validate_python_identifier(val, field_id=param.id)
        if not is_valid_id:
            return False, id_code, f"{id_msg} on parameter '{param.name}' ({param.id}) of node '{node_label}' ({node_id}).", id_fix

    # 4. Numeric Constraints (bounds, integer check, safe integer, step, precision)
    if is_numeric_param and not is_empty_str:
        if isinstance(val, (int, float)) and not isinstance(val, bool):
            num = float(val)
        elif isinstance(val, str) and val.strip() != "":
            try:
                num = float(val.strip())
            except ValueError:
                return (
                    False,
                    "VAL-PARAM-CONSTRAINT",
                    f"Parameter '{param.name}' ({param.id}) on node '{node_label}' ({node_id}) must be a valid number, received '{val}'.",
                    "Provide a valid finite number."
                )
        else:
            return (
                False,
                "VAL-PARAM-CONSTRAINT",
                f"Parameter '{param.name}' ({param.id}) on node '{node_label}' ({node_id}) must be a numeric value.",
                "Provide a valid finite number."
            )

        # Check integer constraint
        if param.type in ("int", "integer") or (getattr(param, "widget", None) == "number" and isinstance(param.default, int) and not isinstance(param.default, bool)):
            if not num.is_integer():
                return (
                    False,
                    "VAL-PARAM-CONSTRAINT",
                    f"Parameter '{param.name}' ({param.id}) on node '{node_label}' ({node_id}) must be an integer, received {num}.",
                    "Provide a whole integer value."
                )
            if abs(num) > 9007199254740991:
                return (
                    False,
                    "VAL-PARAM-CONSTRAINT",
                    f"Parameter '{param.name}' ({param.id}) on node '{node_label}' ({node_id}) exceeds safe integer limits.",
                    "Provide an integer within [-9007199254740991, 9007199254740991]."
                )

        # min_value
        if param.min_value is not None and num < param.min_value:
            return (
                False,
                "VAL-PARAM-CONSTRAINT",
                f"Parameter Constraint Error: Parameter '{param.name}' value {num} on node '{node_label}' ({node_id}) is below minimum allowed value {param.min_value}.",
                f"Provide a value greater than or equal to {param.min_value}."
            )

        # max_value
        if param.max_value is not None and num > param.max_value:
            return (
                False,
                "VAL-PARAM-CONSTRAINT",
                f"Parameter Constraint Error: Parameter '{param.name}' value {num} on node '{node_label}' ({node_id}) exceeds maximum allowed value {param.max_value}.",
                f"Provide a value less than or equal to {param.max_value}."
            )

        # step
        if getattr(param, "step", None) is not None and param.step > 0:
            base = param.min_value if param.min_value is not None else 0.0
            diff = abs(num - base)
            rem = diff % param.step
            eps = 1e-6
            if rem > eps and abs(rem - param.step) > eps:
                return (
                    False,
                    "VAL-PARAM-CONSTRAINT",
                    f"Parameter Constraint Error: Parameter '{param.name}' value {num} on node '{node_label}' ({node_id}) must be an increment of step {param.step}.",
                    f"Adjust value to be an increment of step {param.step}."
                )

        # precision
        param_prec = getattr(param, "precision", None)
        if param_prec is not None and param_prec >= 0:
            str_repr = str(val).strip()
            if "." in str_repr:
                decimals = len(str_repr.split(".")[1])
                if decimals > param_prec:
                    return (
                        False,
                        "VAL-PARAM-CONSTRAINT",
                        f"Parameter Constraint Error: Parameter '{param.name}' value on node '{node_label}' ({node_id}) exceeds maximum precision of {param_prec} decimal place(s).",
                        f"Round or format value to at most {param_prec} decimal place(s)."
                    )

    # 5. Select Options & enum_values Membership
    allowed_opts: List[Any] = []
    if param.options:
        for opt in param.options:
            v = opt.value if hasattr(opt, "value") else (opt.get("value") if isinstance(opt, dict) else opt)
            allowed_opts.append(v)
    if getattr(param, "enum_values", None):
        for ev in param.enum_values:
            if ev not in allowed_opts:
                allowed_opts.append(ev)

    if allowed_opts:
        matches = any(opt == val or str(opt) == str(val) for opt in allowed_opts)
        if not matches:
            choices_str = ", ".join(repr(o) for o in allowed_opts)
            return (
                False,
                "VAL-PARAM-CONSTRAINT",
                f"Parameter Constraint Error: Parameter '{param.name}' value '{val}' on node '{node_label}' ({node_id}) is not one of the allowed options: [{choices_str}].",
                f"Select one of the allowed options: [{choices_str}]."
            )

    # 6. Regex Pattern Check
    if getattr(param, "regex", None) and isinstance(val, str):
        try:
            pat = re.compile(param.regex)
            if not pat.search(val):
                return (
                    False,
                    "VAL-PARAM-CONSTRAINT",
                    f"Parameter Constraint Error: Parameter '{param.name}' value '{val}' on node '{node_label}' ({node_id}) does not match required pattern '{param.regex}'.",
                    f"Provide a value matching pattern '{param.regex}'."
                )
        except re.error as e:
            # Handle malformed schema regex gracefully without crashing validation
            pass

    # 7. Structured JSON (list, dict) Check
    if param.type in ("list", "dict") or getattr(param, "widget", None) == "json":
        if isinstance(val, str) and val.strip():
            try:
                parsed = json.loads(val.strip())
                if param.type == "list" and not isinstance(parsed, list):
                    return (
                        False,
                        "VAL-PARAM-CONSTRAINT",
                        f"Parameter '{param.name}' ({param.id}) on node '{node_label}' ({node_id}) must be a valid JSON list (e.g. [1, 2, 3]).",
                        "Provide a valid JSON list."
                    )
                if param.type == "dict" and not isinstance(parsed, dict):
                    return (
                        False,
                        "VAL-PARAM-CONSTRAINT",
                        f"Parameter '{param.name}' ({param.id}) on node '{node_label}' ({node_id}) must be a valid JSON dictionary (e.g. {{\"key\": \"val\"}}).",
                        "Provide a valid JSON dictionary."
                    )
            except Exception as e:
                return (
                    False,
                    "VAL-PARAM-CONSTRAINT",
                    f"Invalid JSON for parameter '{param.name}' ({param.id}) on node '{node_label}' ({node_id}): {e}",
                    "Provide valid JSON syntax."
                )
        elif isinstance(val, (list, dict)):
            if param.type == "list" and not isinstance(val, list):
                return (
                    False,
                    "VAL-PARAM-CONSTRAINT",
                    f"Parameter '{param.name}' ({param.id}) on node '{node_label}' ({node_id}) must be a list.",
                    "Provide a list."
                )
            if param.type == "dict" and not isinstance(val, dict):
                return (
                    False,
                    "VAL-PARAM-CONSTRAINT",
                    f"Parameter '{param.name}' ({param.id}) on node '{node_label}' ({node_id}) must be a dictionary.",
                    "Provide a dictionary."
                )

    return True, None, None, None