Skip to content

declarations

Parse functions, classes, templates, modifiers, and related declaration constructs.

Classes:

DeclarationParserMixin

Bases: ParserMixinBase

Methods:

get_tok_precedence

get_tok_precedence() -> int
Source code in packages/arx/src/arx/parser/base.py
334
335
336
337
338
339
340
def get_tok_precedence(self) -> int:
    """
    title: Get the precedence of the pending binary operator token.
    returns:
      type: int
    """
    raise NotImplementedError

parse_assert_stmt

parse_assert_stmt() -> AssertStmt
Source code in packages/arx/src/arx/parser/base.py
502
503
504
505
506
507
508
def parse_assert_stmt(self) -> astx.AssertStmt:
    """
    title: Parse one fatal assertion statement.
    returns:
      type: astx.AssertStmt
    """
    raise NotImplementedError

parse_block

parse_block(
    allow_docstring: bool = False,
    declared_names: tuple[str, ...] = (),
    declared_lists: tuple[str, ...] = (),
    declared_tensors: dict[str, TensorBinding | None]
    | None = None,
) -> Block
Source code in packages/arx/src/arx/parser/base.py
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
def parse_block(
    self,
    allow_docstring: bool = False,
    declared_names: tuple[str, ...] = (),
    declared_lists: tuple[str, ...] = (),
    declared_tensors: dict[str, TensorBinding | None] | None = None,
) -> astx.Block:
    """
    title: Parse one block of nodes.
    parameters:
      allow_docstring:
        type: bool
      declared_names:
        type: tuple[str, Ellipsis]
      declared_lists:
        type: tuple[str, Ellipsis]
      declared_tensors:
        type: dict[str, TensorBinding | None] | None
    returns:
      type: astx.Block
    """
    del allow_docstring, declared_names, declared_lists, declared_tensors
    raise NotImplementedError

parse_class_body

parse_class_body() -> tuple[
    list[VariableDeclaration], list[FunctionDef]
]
Source code in packages/arx/src/arx/parser/declarations.py
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
def parse_class_body(
    self,
) -> tuple[list[astx.VariableDeclaration], list[astx.FunctionDef]]:
    """
    title: Parse a class body.
    returns:
      type: tuple[list[astx.VariableDeclaration], list[astx.FunctionDef]]
    """
    start_token = self.tokens.cur_tok
    if start_token.kind != TokenKind.indent:
        raise ParserException(
            "Expected indentation to start a class body."
        )

    cur_indent = start_token.value
    prev_indent = self.indent_level

    if cur_indent <= prev_indent:
        raise ParserException("There is no new class body to be parsed.")

    self.indent_level = cur_indent
    self.tokens.get_next_token()  # eat indentation

    attributes: list[astx.VariableDeclaration] = []
    methods: list[astx.FunctionDef] = []

    while True:
        if self.tokens.cur_tok.kind == TokenKind.indent:
            new_indent = self.tokens.cur_tok.value
            if new_indent < cur_indent:
                break
            if new_indent > cur_indent:
                raise ParserException("Indentation not allowed here.")
            self.tokens.get_next_token()
            continue

        if self.tokens.cur_tok.kind == TokenKind.docstring:
            try:
                validate_docstring(cast(str, self.tokens.cur_tok.value))
            except ValueError as err:
                raise ParserException(
                    f"Invalid class or member docstring: {err}"
                ) from err
            self.tokens.get_next_token()
            continue

        prefixes = ParsedDeclarationPrefixes()
        if self._is_operator("@"):
            prefixes = self.parse_declaration_prefixes(
                body_indent=cur_indent
            )

        if self.tokens.cur_tok.kind == TokenKind.kw_function:
            methods.append(
                self.parse_method_decl(
                    prefixes.modifiers,
                    prefixes.template_params,
                )
            )
        elif self.tokens.cur_tok.kind == TokenKind.identifier:
            if prefixes.template_params:
                raise ParserException(
                    "template parameter blocks are only allowed "
                    "before functions or methods"
                )
            attributes.append(self.parse_field_decl(prefixes.modifiers))
        else:
            if prefixes.modifiers is not None:
                raise ParserException(
                    "annotation must be followed by a declaration"
                )
            if prefixes.template_params:
                raise ParserException(
                    "template parameter blocks are only allowed "
                    "before functions or methods"
                )
            raise ParserException(
                "Expected a field or method declaration in class body."
            )

        while self._is_operator(";"):
            self.tokens.get_next_token()

        if cast(TokenKind, self.tokens.cur_tok.kind) != TokenKind.indent:
            break

    self.indent_level = prev_indent
    return attributes, methods

parse_class_decl

parse_class_decl(
    annotations: ParsedAnnotation | None = None,
) -> ClassDefStmt
Source code in packages/arx/src/arx/parser/declarations.py
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
def parse_class_decl(
    self,
    annotations: ParsedAnnotation | None = None,
) -> astx.ClassDefStmt:
    """
    title: Parse one class declaration.
    parameters:
      annotations:
        type: ParsedAnnotation | None
    returns:
      type: astx.ClassDefStmt
    """
    class_loc = self.tokens.cur_tok.location
    self._validate_modifier_target(
        annotations, CLASS_ALLOWED_MODIFIERS, "class"
    )
    self.tokens.get_next_token()  # eat class

    if self.tokens.cur_tok.kind != TokenKind.identifier:
        raise ParserException("Parser: Expected class name after 'class'.")

    class_name = cast(str, self.tokens.cur_tok.value)
    self.tokens.get_next_token()  # eat class name

    bases: list[astx.ClassType] = []
    if self._is_operator("("):
        self._consume_operator("(")
        if self._is_operator(")"):
            raise ParserException("Parser: Expected base class name.")

        while True:
            if self.tokens.cur_tok.kind != TokenKind.identifier:
                raise ParserException("Parser: Expected base class name.")
            bases.append(
                astx.ClassType(cast(str, self.tokens.cur_tok.value))
            )
            self.tokens.get_next_token()

            if self._is_operator(")"):
                break

            self._consume_operator(",")

        self._consume_operator(")")

    self._consume_operator(":")
    attributes, methods = self.parse_class_body()
    declaration = astx.ClassDefStmt(
        class_name,
        bases=bases,
        attributes=attributes,
        methods=methods,
        visibility=self._resolve_visibility(annotations),
        loc=class_loc,
    )
    self._apply_class_modifiers(declaration, annotations)
    return declaration

parse_declaration_prefix

parse_declaration_prefix() -> ParsedDeclarationPrefixes
Source code in packages/arx/src/arx/parser/declarations.py
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
def parse_declaration_prefix(self) -> ParsedDeclarationPrefixes:
    """
    title: Parse one declaration prefix.
    returns:
      type: ParsedDeclarationPrefixes
    """
    next_token = self._peek_token()
    if next_token == Token(TokenKind.operator, "["):
        annotation = self.parse_modifier_list()
        return ParsedDeclarationPrefixes(
            modifiers=annotation,
            loc=annotation.loc,
            description="annotation",
        )

    if next_token == Token(TokenKind.operator, "<"):
        template_loc = self.tokens.cur_tok.location
        return ParsedDeclarationPrefixes(
            template_params=self.parse_template_param_block(),
            loc=template_loc,
            description="template parameter block",
        )

    raise ParserException("Expected '[' or '<' after '@'.")

parse_declaration_prefixes

parse_declaration_prefixes(
    *, body_indent: int | None = None
) -> ParsedDeclarationPrefixes
Source code in packages/arx/src/arx/parser/declarations.py
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
def parse_declaration_prefixes(
    self,
    *,
    body_indent: int | None = None,
) -> ParsedDeclarationPrefixes:
    """
    title: Parse declaration prefixes that precede one declaration.
    parameters:
      body_indent:
        type: int | None
    returns:
      type: ParsedDeclarationPrefixes
    """
    prefixes = ParsedDeclarationPrefixes()

    while self._is_operator("@"):
        prefix = self.parse_declaration_prefix()
        if prefix.modifiers is not None:
            if prefixes.modifiers is not None:
                raise ParserException("duplicate annotation block")
            prefixes.modifiers = prefix.modifiers
        if prefix.template_params:
            if prefixes.template_params:
                raise ParserException("duplicate template parameter block")
            prefixes.template_params = prefix.template_params

        prefixes.loc = prefix.loc
        prefixes.description = prefix.description

        if self.tokens.cur_tok.kind == TokenKind.eof:
            raise ParserException(
                f"{prefix.description} must be followed by a declaration"
            )
        if prefix.loc is not None and (
            self.tokens.cur_tok.location.line == prefix.loc.line
        ):
            raise ParserException(
                f"{prefix.description} must appear on its own line "
                "before a declaration"
            )

        if body_indent is None or (
            self.tokens.cur_tok.kind != TokenKind.indent
        ):
            continue

        next_indent = self.tokens.cur_tok.value
        if next_indent < body_indent:
            raise ParserException(
                f"{prefix.description} must be followed by a declaration"
            )
        if next_indent > body_indent:
            raise ParserException("Indentation not allowed here.")
        self.tokens.get_next_token()

    return prefixes

parse_expression

parse_expression() -> AST
Source code in packages/arx/src/arx/parser/base.py
342
343
344
345
346
347
348
def parse_expression(self) -> astx.AST:
    """
    title: Parse one expression.
    returns:
      type: astx.AST
    """
    raise NotImplementedError

parse_extern

parse_extern() -> FunctionPrototype
Source code in packages/arx/src/arx/parser/declarations.py
150
151
152
153
154
155
156
157
158
159
def parse_extern(self) -> astx.FunctionPrototype:
    """
    title: Parse the extern expression.
    returns:
      type: astx.FunctionPrototype
    """
    self.tokens.get_next_token()  # eat extern
    prototype = self.parse_prototype(expect_colon=False)
    setattr(prototype, "is_extern", True)
    return prototype

parse_field_decl

parse_field_decl(
    modifiers: ParsedAnnotation | None = None,
) -> VariableDeclaration
Source code in packages/arx/src/arx/parser/declarations.py
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
def parse_field_decl(
    self,
    modifiers: ParsedAnnotation | None = None,
) -> astx.VariableDeclaration:
    """
    title: Parse one class field declaration.
    parameters:
      modifiers:
        type: ParsedAnnotation | None
    returns:
      type: astx.VariableDeclaration
    """
    field_loc = self.tokens.cur_tok.location
    self._validate_modifier_target(
        modifiers, FIELD_ALLOWED_MODIFIERS, "field"
    )

    name = cast(str, self.tokens.cur_tok.value)
    self.tokens.get_next_token()  # eat field name

    if not self._is_operator(":"):
        raise ParserException(
            f"Parser: Expected type annotation for field '{name}'."
        )

    self._consume_operator(":")
    field_type = self.parse_type(type_context=TypeUseContext.FIELD)

    initializer: astx.Expr | None = None
    if self._is_operator("="):
        self._consume_operator("=")
        try:
            initializer = coerce_expression(
                cast(astx.Expr, self.parse_expression()),
                field_type,
                context=f"field '{name}'",
            )
        except ValueError as err:
            raise ParserException(str(err)) from err
    elif is_tensor_type(field_type):
        try:
            initializer = cast(
                astx.Expr,
                self._default_value_for_type(field_type),
            )
        except ValueError as err:
            raise ParserException(str(err)) from err

    field_kwargs: dict[str, object] = {
        "mutability": self._resolve_field_mutability(modifiers),
        "visibility": self._resolve_visibility(modifiers),
        "loc": field_loc,
    }
    if initializer is not None:
        field_kwargs["value"] = initializer

    field = astx.VariableDeclaration(
        name,
        field_type,
        **field_kwargs,
    )
    self._apply_field_modifiers(field, modifiers)
    return field

parse_for_stmt

parse_for_stmt() -> AST
Source code in packages/arx/src/arx/parser/base.py
486
487
488
489
490
491
492
def parse_for_stmt(self) -> astx.AST:
    """
    title: Parse one for-loop expression.
    returns:
      type: astx.AST
    """
    raise NotImplementedError

parse_function

parse_function(
    template_params: tuple[TemplateParam, ...] = (),
) -> FunctionDef
Source code in packages/arx/src/arx/parser/declarations.py
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
def parse_function(
    self,
    template_params: tuple[astx.TemplateParam, ...] = (),
) -> astx.FunctionDef:
    """
    title: Parse the function definition expression.
    parameters:
      template_params:
        type: tuple[astx.TemplateParam, Ellipsis]
    returns:
      type: astx.FunctionDef
    """
    self.tokens.get_next_token()  # eat fn
    self._push_template_scope(template_params)
    pushed_return_type = False
    try:
        proto = self.parse_prototype(expect_colon=True)
        if template_params:
            astx.set_template_params(proto, template_params)
        self._push_return_type_scope(
            cast(astx.DataType, proto.return_type)
        )
        pushed_return_type = True
        body = self.parse_block(
            allow_docstring=True,
            declared_names=tuple(arg.name for arg in proto.args.nodes),
            declared_lists=self._list_names_for_arguments(
                proto.args.nodes
            ),
            declared_tensors=self._tensor_bindings_for_arguments(
                proto.args.nodes
            ),
        )
    finally:
        if pushed_return_type:
            self._pop_return_type_scope()
        self._pop_template_scope()

    function = astx.FunctionDef(proto, body)
    if template_params:
        astx.set_template_params(function, template_params)
    return function

parse_if_stmt

parse_if_stmt() -> IfStmt
Source code in packages/arx/src/arx/parser/base.py
470
471
472
473
474
475
476
def parse_if_stmt(self) -> astx.IfStmt:
    """
    title: Parse one if expression.
    returns:
      type: astx.IfStmt
    """
    raise NotImplementedError

parse_import_stmt

parse_import_stmt() -> ImportStmt | ImportFromStmt
Source code in packages/arx/src/arx/parser/base.py
419
420
421
422
423
424
425
426
427
def parse_import_stmt(
    self,
) -> astx.ImportStmt | astx.ImportFromStmt:
    """
    title: Parse one import statement.
    returns:
      type: astx.ImportStmt | astx.ImportFromStmt
    """
    raise NotImplementedError

parse_method_decl

parse_method_decl(
    modifiers: ParsedAnnotation | None = None,
    template_params: tuple[TemplateParam, ...] = (),
) -> FunctionDef
Source code in packages/arx/src/arx/parser/declarations.py
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
414
415
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
def parse_method_decl(
    self,
    modifiers: ParsedAnnotation | None = None,
    template_params: tuple[astx.TemplateParam, ...] = (),
) -> astx.FunctionDef:
    """
    title: Parse one class method declaration.
    parameters:
      modifiers:
        type: ParsedAnnotation | None
      template_params:
        type: tuple[astx.TemplateParam, Ellipsis]
    returns:
      type: astx.FunctionDef
    """
    method_loc = self.tokens.cur_tok.location
    self._validate_modifier_target(
        modifiers, METHOD_ALLOWED_MODIFIERS, "method"
    )
    self.tokens.get_next_token()  # eat fn

    if template_params and (
        self._has_modifier(modifiers, "abstract")
        or self._has_modifier(modifiers, "extern")
    ):
        raise ParserException("template methods must define a body")

    is_static = self._has_modifier(modifiers, "static")
    self._push_template_scope(template_params)
    pushed_return_type = False
    try:
        prototype, receiver_name = self.parse_method_signature(
            allow_receiver=not is_static
        )
        if template_params:
            astx.set_template_params(prototype, template_params)
        prototype.visibility = self._resolve_visibility(modifiers)

        declared_names = tuple(arg.name for arg in prototype.args.nodes)
        if receiver_name is not None:
            declared_names = (receiver_name, *declared_names)

        if self._is_operator(":"):
            if self._has_modifier(modifiers, "extern"):
                raise ParserException("extern method cannot define a body")
            self._consume_operator(":")
            if self._has_modifier(modifiers, "abstract"):
                body = self.parse_block(
                    allow_docstring=True,
                    declared_names=declared_names,
                    declared_lists=self._list_names_for_arguments(
                        prototype.args.nodes
                    ),
                    declared_tensors=self._tensor_bindings_for_arguments(
                        prototype.args.nodes
                    ),
                )
                if body.nodes:
                    raise ParserException(
                        "abstract method body may only contain a docstring"
                    )
            else:
                self._push_return_type_scope(
                    cast(astx.DataType, prototype.return_type)
                )
                pushed_return_type = True
                body = self.parse_block(
                    allow_docstring=True,
                    declared_names=declared_names,
                    declared_lists=self._list_names_for_arguments(
                        prototype.args.nodes
                    ),
                    declared_tensors=self._tensor_bindings_for_arguments(
                        prototype.args.nodes
                    ),
                )
        elif not (
            self._has_modifier(modifiers, "abstract")
            or self._has_modifier(modifiers, "extern")
        ):
            raise ParserException(
                "method declaration without a body requires "
                "'abstract' or 'extern'"
            )
        else:
            body = astx.Block()
    finally:
        if pushed_return_type:
            self._pop_return_type_scope()
        self._pop_template_scope()

    method = astx.FunctionDef(prototype, body, loc=method_loc)
    if template_params:
        astx.set_template_params(method, template_params)
    self._apply_method_modifiers(method, modifiers)
    return method

parse_method_signature

parse_method_signature(
    *, allow_receiver: bool
) -> tuple[FunctionPrototype, str | None]
Source code in packages/arx/src/arx/parser/declarations.py
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
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
def parse_method_signature(
    self,
    *,
    allow_receiver: bool,
) -> tuple[astx.FunctionPrototype, str | None]:
    """
    title: Parse one class method signature.
    parameters:
      allow_receiver:
        type: bool
    returns:
      type: tuple[astx.FunctionPrototype, str | None]
    """
    if self.tokens.cur_tok.kind != TokenKind.identifier:
        raise ParserException("Parser: Expected method name in prototype")

    method_name = cast(str, self.tokens.cur_tok.value)
    method_loc = self.tokens.cur_tok.location
    self.tokens.get_next_token()  # eat method name

    self._consume_operator("(")

    args = astx.Arguments()
    implicit_receiver_name: str | None = None
    index = 0
    if not self._is_operator(")"):
        while True:
            if self.tokens.cur_tok.kind != TokenKind.identifier:
                raise ParserException("Parser: Expected argument name")

            param_name = cast(str, self.tokens.cur_tok.value)
            param_loc = self.tokens.cur_tok.location
            self.tokens.get_next_token()  # eat arg name

            if (
                index == 0
                and param_name == "self"
                and not self._is_operator(":")
            ):
                if not allow_receiver:
                    raise ParserException(
                        "static method cannot declare implicit receiver "
                        "'self'"
                    )
                implicit_receiver_name = param_name
            else:
                if not self._is_operator(":"):
                    raise ParserException(
                        "Parser: Expected type annotation for argument "
                        f"'{param_name}'."
                    )

                self._consume_operator(":")
                param_type = self.parse_type(
                    type_context=TypeUseContext.PARAMETER
                )
                self._append_argument(
                    args,
                    param_name,
                    param_type,
                    param_loc,
                )

            index += 1

            if self._is_operator(","):
                self._consume_operator(",")
                continue

            break

    self._consume_operator(")")

    if not self._is_operator("->"):
        raise ParserException(
            "Parser: Expected return type annotation with '->'."
        )

    self._consume_operator("->")
    return_type = self.parse_type(type_context=TypeUseContext.RETURN)
    return (
        astx.FunctionPrototype(
            method_name,
            args,
            cast(AnyType, return_type),
            loc=method_loc,
        ),
        implicit_receiver_name,
    )

parse_modifier_list

parse_modifier_list() -> ParsedAnnotation
Source code in packages/arx/src/arx/parser/declarations.py
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
def parse_modifier_list(self) -> ParsedAnnotation:
    """
    title: Parse one annotation-line modifier list.
    returns:
      type: ParsedAnnotation
    """
    annotation_loc = self.tokens.cur_tok.location
    self._consume_operator("@")
    self._consume_operator("[")

    if self._is_operator("]"):
        raise ParserException("empty annotation is not allowed")

    modifiers: list[str] = []
    while True:
        if self.tokens.cur_tok.kind != TokenKind.identifier:
            raise ParserException("Parser: Expected modifier name.")

        modifier_name = cast(str, self.tokens.cur_tok.value)
        if modifier_name not in SUPPORTED_MODIFIERS:
            raise ParserException(f"unknown modifier '{modifier_name}'")
        if modifier_name in modifiers:
            raise ParserException(f"duplicate modifier '{modifier_name}'")

        modifiers.append(modifier_name)
        self.tokens.get_next_token()

        if self._is_operator("]"):
            break

        self._consume_operator(",")

    self._consume_operator("]")
    self._validate_modifier_conflicts(modifiers)
    return ParsedAnnotation(tuple(modifiers), annotation_loc)

parse_prototype

parse_prototype(expect_colon: bool) -> FunctionPrototype
Source code in packages/arx/src/arx/parser/declarations.py
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
def parse_prototype(self, expect_colon: bool) -> astx.FunctionPrototype:
    """
    title: Parse function/extern prototypes.
    parameters:
      expect_colon:
        type: bool
    returns:
      type: astx.FunctionPrototype
    """
    if self.tokens.cur_tok.kind != TokenKind.identifier:
        raise ParserException(
            "Parser: Expected function name in prototype"
        )

    fn_name = cast(str, self.tokens.cur_tok.value)
    fn_loc = self.tokens.cur_tok.location
    self.tokens.get_next_token()  # eat function name

    self._consume_operator("(")

    args = astx.Arguments()
    if not self._is_operator(")"):
        while True:
            if self.tokens.cur_tok.kind != TokenKind.identifier:
                raise ParserException("Parser: Expected argument name")

            arg_name = cast(str, self.tokens.cur_tok.value)
            arg_loc = self.tokens.cur_tok.location
            self.tokens.get_next_token()  # eat arg name

            if not self._is_operator(":"):
                raise ParserException(
                    "Parser: Expected type annotation for argument "
                    f"'{arg_name}'."
                )

            self._consume_operator(":")
            arg_type = self.parse_type(
                type_context=TypeUseContext.PARAMETER
            )

            self._append_argument(args, arg_name, arg_type, arg_loc)

            if self._is_operator(","):
                self._consume_operator(",")
                continue

            break

    self._consume_operator(")")

    if not self._is_operator("->"):
        raise ParserException(
            "Parser: Expected return type annotation with '->'."
        )
    self._consume_operator("->")
    ret_type: astx.DataType = self.parse_type(
        type_context=TypeUseContext.RETURN
    )

    if expect_colon:
        self._consume_operator(":")

    return astx.FunctionPrototype(
        fn_name, args, cast(AnyType, ret_type), loc=fn_loc
    )

parse_return_function

parse_return_function() -> FunctionReturn
Source code in packages/arx/src/arx/parser/base.py
510
511
512
513
514
515
516
def parse_return_function(self) -> astx.FunctionReturn:
    """
    title: Parse one return expression.
    returns:
      type: astx.FunctionReturn
    """
    raise NotImplementedError

parse_template_argument_list

parse_template_argument_list() -> tuple[DataType, ...]
Source code in packages/arx/src/arx/parser/declarations.py
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
def parse_template_argument_list(
    self,
) -> tuple[astx.DataType, ...]:
    """
    title: Parse one explicit template-argument list.
    returns:
      type: tuple[astx.DataType, Ellipsis]
    """
    self._consume_operator("<")

    if self._is_operator(">"):
        raise ParserException(
            "empty template argument list is not allowed"
        )

    template_args: list[astx.DataType] = []
    while True:
        template_args.append(
            self.parse_type(
                allow_template_vars=False,
                allow_union=False,
                type_context=TypeUseContext.TEMPLATE_ARGUMENT,
            )
        )

        if self._is_operator(">"):
            break

        self._consume_operator(",")

    self._consume_operator(">")
    return tuple(template_args)

parse_template_param_block

parse_template_param_block() -> tuple[TemplateParam, ...]
Source code in packages/arx/src/arx/parser/declarations.py
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
def parse_template_param_block(
    self,
) -> tuple[astx.TemplateParam, ...]:
    """
    title: Parse one template-parameter block.
    returns:
      type: tuple[astx.TemplateParam, Ellipsis]
    """
    self._consume_operator("@")
    self._consume_operator("<")
    self._skip_template_layout()

    if self._is_operator(">"):
        raise ParserException(
            "empty template parameter block is not allowed"
        )

    template_params: list[astx.TemplateParam] = []
    seen_names: set[str] = set()
    while True:
        if self.tokens.cur_tok.kind != TokenKind.identifier:
            raise ParserException(
                "Parser: Expected template parameter name."
            )

        param_name = cast(str, self.tokens.cur_tok.value)
        param_loc = self.tokens.cur_tok.location
        if param_name in seen_names:
            raise ParserException(
                f"duplicate template parameter '{param_name}'"
            )
        seen_names.add(param_name)
        self.tokens.get_next_token()

        if not self._is_operator(":"):
            raise ParserException(
                f"template parameter '{param_name}' must declare a bound"
            )

        self._consume_operator(":")
        bound = self.parse_type(
            allow_template_vars=False,
            allow_union=True,
            type_context=TypeUseContext.TEMPLATE_BOUND,
        )
        template_params.append(
            astx.TemplateParam(param_name, bound, loc=param_loc)
        )

        self._skip_template_layout()
        if self._is_operator(">"):
            break

        self._consume_operator(",")
        self._skip_template_layout()
        if self._is_operator(">"):
            break

    self._consume_operator(">")
    return tuple(template_params)

parse_type

parse_type(
    *,
    allow_template_vars: bool = True,
    allow_union: bool = False,
    type_context: TypeUseContext = GENERAL,
) -> DataType
Source code in packages/arx/src/arx/parser/base.py
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
def parse_type(
    self,
    *,
    allow_template_vars: bool = True,
    allow_union: bool = False,
    type_context: TypeUseContext = TypeUseContext.GENERAL,
) -> astx.DataType:
    """
    title: Parse one type annotation.
    parameters:
      allow_template_vars:
        type: bool
      allow_union:
        type: bool
      type_context:
        type: TypeUseContext
    returns:
      type: astx.DataType
    """
    del allow_template_vars, allow_union, type_context
    raise NotImplementedError

parse_var_expr

parse_var_expr() -> VariableDeclaration
Source code in packages/arx/src/arx/parser/base.py
494
495
496
497
498
499
500
def parse_var_expr(self) -> astx.VariableDeclaration:
    """
    title: Parse one typed variable declaration.
    returns:
      type: astx.VariableDeclaration
    """
    raise NotImplementedError

parse_while_stmt

parse_while_stmt() -> WhileStmt
Source code in packages/arx/src/arx/parser/base.py
478
479
480
481
482
483
484
def parse_while_stmt(self) -> astx.WhileStmt:
    """
    title: Parse one while expression.
    returns:
      type: astx.WhileStmt
    """
    raise NotImplementedError