Skip to content

validation

Collect the focused validation routines that emit diagnostics for assignments, calls, casts, and temporal literals.

Functions:

resolve_return

resolve_return(
    diagnostics: DiagnosticBag,
    *,
    function: SemanticFunction,
    value: AST | None,
    value_type: DataType | None,
    node: FunctionReturn,
) -> ReturnResolution
Source code in packages/irx/src/irx/analysis/validation.py
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
@typechecked
def resolve_return(
    diagnostics: DiagnosticBag,
    *,
    function: SemanticFunction,
    value: astx.AST | None,
    value_type: astx.DataType | None,
    node: astx.FunctionReturn,
) -> ReturnResolution:
    """
    title: Validate one return statement.
    parameters:
      diagnostics:
        type: DiagnosticBag
      function:
        type: SemanticFunction
      value:
        type: astx.AST | None
      value_type:
        type: astx.DataType | None
      node:
        type: astx.FunctionReturn
    returns:
      type: ReturnResolution
    """
    expected_type = function.signature.return_type
    callable_resolution = _callable_resolution(function)
    if is_none_type(expected_type):
        if _is_void_return_sentinel(value):
            return ReturnResolution(
                callable=callable_resolution,
                expected_type=expected_type,
                value_type=None,
                returns_void=True,
            )
        diagnostics.add(
            f"void function '{function.name}' cannot return a value of type "
            f"{display_type_name(value_type)}",
            node=node,
            code=DiagnosticCodes.SEMANTIC_INVALID_RETURN,
        )
        return ReturnResolution(
            callable=callable_resolution,
            expected_type=expected_type,
            value_type=value_type,
            returns_void=True,
        )

    if _is_void_return_sentinel(value):
        diagnostics.add(
            f"function '{function.name}' must return "
            f"{display_type_name(expected_type)}",
            node=node,
            code=DiagnosticCodes.SEMANTIC_INVALID_RETURN,
        )
        return ReturnResolution(
            callable=callable_resolution,
            expected_type=expected_type,
            value_type=None,
            returns_void=False,
        )

    if _is_void_call_value(value):
        diagnostics.add(
            f"return in '{function.name}' cannot use the result of a void "
            "call as a value",
            node=node,
            code=DiagnosticCodes.SEMANTIC_INVALID_RETURN,
        )
        return ReturnResolution(
            callable=callable_resolution,
            expected_type=expected_type,
            value_type=value_type,
            returns_void=False,
        )

    if not is_assignable(expected_type, value_type):
        diagnostics.add(
            f"return in '{function.name}' expects "
            f"{display_type_name(expected_type)} but got "
            f"{display_type_name(value_type)}",
            node=node,
            code=DiagnosticCodes.SEMANTIC_TYPE_MISMATCH,
            notes=_implicit_conversion_note(value_type, expected_type),
        )
        return ReturnResolution(
            callable=callable_resolution,
            expected_type=expected_type,
            value_type=value_type,
            returns_void=False,
        )

    implicit_conversion = None
    if not same_type(expected_type, value_type):
        implicit_conversion = ImplicitConversion(value_type, expected_type)
    return ReturnResolution(
        callable=callable_resolution,
        expected_type=expected_type,
        value_type=value_type,
        returns_void=False,
        implicit_conversion=implicit_conversion,
    )

validate_assignment

validate_assignment(
    diagnostics: DiagnosticBag,
    *,
    target_name: str,
    target_type: DataType | None,
    value_type: DataType | None,
    node: AST,
) -> None
Source code in packages/irx/src/irx/analysis/validation.py
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
@typechecked
def validate_assignment(
    diagnostics: DiagnosticBag,
    *,
    target_name: str,
    target_type: astx.DataType | None,
    value_type: astx.DataType | None,
    node: astx.AST,
) -> None:
    """
    title: Validate an assignment.
    parameters:
      diagnostics:
        type: DiagnosticBag
      target_name:
        type: str
      target_type:
        type: astx.DataType | None
      value_type:
        type: astx.DataType | None
      node:
        type: astx.AST
    """
    if not is_assignable(target_type, value_type):
        diagnostics.add(
            "cannot assign "
            f"{display_type_name(value_type)} to '{target_name}' of type "
            f"{display_type_name(target_type)}",
            node=node,
            code=DiagnosticCodes.SEMANTIC_TYPE_MISMATCH,
            notes=_implicit_conversion_note(value_type, target_type),
        )

validate_calendar_date

validate_calendar_date(value: str) -> date
Source code in packages/irx/src/irx/analysis/validation.py
569
570
571
572
573
574
575
576
577
578
579
@typechecked
def validate_calendar_date(value: str) -> date:
    """
    title: Validate a date component.
    parameters:
      value:
        type: str
    returns:
      type: date
    """
    return date.fromisoformat(value)

validate_call

validate_call(
    diagnostics: DiagnosticBag,
    *,
    function: SemanticFunction,
    arg_types: list[DataType | None],
    node: BaseMethodCall
    | FunctionCall
    | MethodCall
    | StaticMethodCall
    | WithStmt,
) -> CallResolution
Source code in packages/irx/src/irx/analysis/validation.py
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
@typechecked
def validate_call(
    diagnostics: DiagnosticBag,
    *,
    function: SemanticFunction,
    arg_types: list[astx.DataType | None],
    node: (
        astx.BaseMethodCall
        | astx.FunctionCall
        | astx.MethodCall
        | astx.StaticMethodCall
        | astx.WithStmt
    ),
) -> CallResolution:
    """
    title: Validate a function call.
    parameters:
      diagnostics:
        type: DiagnosticBag
      function:
        type: SemanticFunction
      arg_types:
        type: list[astx.DataType | None]
      node:
        type: >-
          astx.BaseMethodCall | astx.FunctionCall | astx.MethodCall |
          astx.StaticMethodCall | astx.WithStmt
    returns:
      type: CallResolution
    """
    signature = function.signature
    fixed_param_count = len(signature.parameters)
    required_param_count = sum(
        1
        for argument in function.prototype.args.nodes
        if isinstance(argument.default, astx.Undefined)
    )
    arg_count = len(arg_types)
    if signature.is_variadic:
        if arg_count < required_param_count:
            diagnostics.add(
                f"call to '{function.name}' expects at least "
                f"{required_param_count} arguments but got {arg_count}",
                node=node,
                code=DiagnosticCodes.SEMANTIC_CALL_ARITY,
            )
    elif arg_count < required_param_count:
        expected_count = (
            required_param_count
            if required_param_count != fixed_param_count
            else fixed_param_count
        )
        qualifier = (
            "at least " if required_param_count != fixed_param_count else ""
        )
        diagnostics.add(
            f"call to '{function.name}' expects {qualifier}{expected_count} "
            f"arguments but got {arg_count}",
            node=node,
            code=DiagnosticCodes.SEMANTIC_CALL_ARITY,
        )
    elif arg_count > fixed_param_count:
        diagnostics.add(
            f"call to '{function.name}' expects {fixed_param_count} "
            f"arguments but got {arg_count}",
            node=node,
            code=DiagnosticCodes.SEMANTIC_CALL_ARITY,
        )

    resolved_argument_types: list[astx.DataType | None] = []
    implicit_conversions: list[ImplicitConversion | None] = []
    call_args = list(getattr(node, "args", ()))

    for idx, (param, arg_type) in enumerate(
        zip(signature.parameters, arg_types)
    ):
        if not is_assignable(param.type_, arg_type):
            diagnostics.add(
                f"argument {idx + 1} of call to '{function.name}' expects "
                f"{display_type_name(param.type_)} but got "
                f"{display_type_name(arg_type)}",
                node=call_args[idx],
                code=DiagnosticCodes.SEMANTIC_TYPE_MISMATCH,
                notes=_implicit_conversion_note(arg_type, param.type_),
            )
            resolved_argument_types.append(arg_type)
            implicit_conversions.append(None)
            continue
        resolved_argument_types.append(param.type_)
        if same_type(param.type_, arg_type):
            implicit_conversions.append(None)
        else:
            implicit_conversions.append(
                ImplicitConversion(arg_type, param.type_)
            )

    for idx, arg_type in enumerate(
        arg_types[fixed_param_count:],
        start=fixed_param_count,
    ):
        promoted_type = _variadic_argument_type(arg_type)
        if signature.is_variadic and promoted_type is not None:
            resolved_argument_types.append(promoted_type)
            if same_type(promoted_type, arg_type):
                implicit_conversions.append(None)
            else:
                implicit_conversions.append(
                    ImplicitConversion(arg_type, promoted_type)
                )
            continue
        if signature.is_variadic:
            diagnostics.add(
                f"variadic argument {idx + 1} of call to '{function.name}' "
                f"uses unsupported type {display_type_name(arg_type)}",
                node=call_args[idx],
                code=DiagnosticCodes.SEMANTIC_TYPE_MISMATCH,
            )
        resolved_argument_types.append(arg_type)
        implicit_conversions.append(None)

    return CallResolution(
        callee=_callable_resolution(function),
        signature=signature,
        resolved_argument_types=tuple(resolved_argument_types),
        result_type=signature.return_type,
        implicit_conversions=tuple(implicit_conversions),
    )

validate_cast

validate_cast(
    diagnostics: DiagnosticBag,
    *,
    source_type: DataType | None,
    target_type: DataType | None,
    node: AST,
) -> None
Source code in packages/irx/src/irx/analysis/validation.py
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
@typechecked
def validate_cast(
    diagnostics: DiagnosticBag,
    *,
    source_type: astx.DataType | None,
    target_type: astx.DataType | None,
    node: astx.AST,
) -> None:
    """
    title: Validate a cast expression.
    parameters:
      diagnostics:
        type: DiagnosticBag
      source_type:
        type: astx.DataType | None
      target_type:
        type: astx.DataType | None
      node:
        type: astx.AST
    """
    if source_type is None or target_type is None:
        return
    if is_explicitly_castable(source_type, target_type):
        return
    diagnostics.add(
        f"unsupported cast from {display_type_name(source_type)} to "
        f"{display_type_name(target_type)}",
        node=node,
        code=DiagnosticCodes.SEMANTIC_TYPE_MISMATCH,
    )

validate_literal_datetime

validate_literal_datetime(value: str) -> datetime
Source code in packages/irx/src/irx/analysis/validation.py
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
@typechecked
def validate_literal_datetime(value: str) -> datetime:
    """
    title: Validate an astx datetime literal.
    parameters:
      value:
        type: str
    returns:
      type: datetime
    """
    stripped = value.strip()

    if "T" in stripped:
        date_part, time_part = stripped.split("T", 1)
    elif " " in stripped:
        date_part, time_part = stripped.split(" ", 1)
    else:
        raise ValueError("invalid datetime format")

    if "." in time_part:
        raise ValueError("fractional seconds are not supported")
    if time_part.endswith("Z") or "+" in time_part or "-" in time_part[2:]:
        raise ValueError("timezone offsets are not supported")

    try:
        year_str, month_str, day_str = date_part.split("-")
        year = int(year_str)
        month = int(month_str)
        day = int(day_str)
    except Exception as exc:
        raise ValueError("invalid date part") from exc

    if not (INT32_MIN <= year <= INT32_MAX):
        raise ValueError("year out of 32-bit range")

    try:
        time_parts = time_part.split(":")
        if len(time_parts) not in {
            TIME_PARTS_HOUR_MINUTE,
            TIME_PARTS_HOUR_MINUTE_SECOND,
        }:
            raise ValueError("invalid time part")
        hour = int(time_parts[0])
        minute = int(time_parts[1])
        second = (
            int(time_parts[2])
            if len(time_parts) == TIME_PARTS_HOUR_MINUTE_SECOND
            else 0
        )
    except Exception as exc:
        raise ValueError("invalid time part") from exc

    if not (0 <= hour <= MAX_HOUR):
        raise ValueError("hour out of range")
    if not (0 <= minute <= MAX_MINUTE_SECOND):
        raise ValueError("minute out of range")
    if not (0 <= second <= MAX_MINUTE_SECOND):
        raise ValueError("second out of range")

    try:
        return datetime(year, month, day, hour, minute, second)
    except ValueError as exc:
        raise ValueError("invalid calendar date/time") from exc

validate_literal_time

validate_literal_time(value: str) -> time
Source code in packages/irx/src/irx/analysis/validation.py
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
@typechecked
def validate_literal_time(value: str) -> time:
    """
    title: Validate an astx time literal.
    parameters:
      value:
        type: str
    returns:
      type: time
    """
    if "." in value:
        raise ValueError("fractional seconds are not supported")
    parts = value.split(":")
    if len(parts) not in {
        TIME_PARTS_HOUR_MINUTE,
        TIME_PARTS_HOUR_MINUTE_SECOND,
    }:
        raise ValueError("invalid time format")
    try:
        parsed = [int(part) for part in parts]
    except ValueError as exc:
        raise ValueError("invalid time format") from exc

    hour, minute = parsed[0], parsed[1]
    second = parsed[2] if len(parsed) == TIME_PARTS_HOUR_MINUTE_SECOND else 0

    if not (0 <= hour <= MAX_HOUR):
        raise ValueError("hour out of range")
    if not (0 <= minute <= MAX_MINUTE_SECOND):
        raise ValueError("minute out of range")
    if not (0 <= second <= MAX_MINUTE_SECOND):
        raise ValueError("second out of range")

    return time(hour, minute, second)

validate_literal_timestamp

validate_literal_timestamp(value: str) -> datetime
Source code in packages/irx/src/irx/analysis/validation.py
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
@typechecked
def validate_literal_timestamp(value: str) -> datetime:
    """
    title: Validate an astx timestamp literal.
    parameters:
      value:
        type: str
    returns:
      type: datetime
    """
    if "." in value:
        raise ValueError("fractional seconds are not supported")
    if "Z" in value or "+" in value[10:] or "-" in value[10:]:
        raise ValueError("timezone offsets are not supported")
    try:
        return datetime.fromisoformat(value)
    except ValueError as exc:
        raise ValueError(str(exc)) from exc