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
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
468
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
558
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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
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
701
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
734
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
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Recursive descent parser for FDL."""
import warnings
from typing import List, Set
from fory_compiler.parser.ast import (
Schema,
Message,
Enum,
Field,
EnumValue,
Import,
FieldType,
PrimitiveType,
NamedType,
ListType,
MapType,
PRIMITIVE_TYPES,
)
from fory_compiler.parser.lexer import Lexer, Token, TokenType
# Known file-level options (standard protobuf options)
KNOWN_FILE_OPTIONS: Set[str] = {
"java_package",
"java_outer_classname",
"java_multiple_files",
"go_package",
"deprecated",
}
# Known Fory file-level options (extension options)
KNOWN_FORY_FILE_OPTIONS: Set[str] = {
"use_record_for_java_message",
"polymorphism",
"go_nested_type_style",
}
# Known field-level options (standard protobuf options)
KNOWN_FIELD_OPTIONS: Set[str] = {
"deprecated",
"json_name",
"packed",
"lazy",
"unverified_lazy",
"weak",
"debug_redact",
"retention",
"targets",
"edition_defaults",
"features",
}
# Known Fory field-level options (extension options)
KNOWN_FORY_FIELD_OPTIONS: Set[str] = {
"ref",
"nullable",
"deprecated",
"thread_safe_pointer",
}
# Known type-level options for inline syntax: [id=100, deprecated=true]
KNOWN_TYPE_OPTIONS: Set[str] = {
"id",
"deprecated",
}
# Known Fory message-level options (option statements inside message body)
KNOWN_FORY_MESSAGE_OPTIONS: Set[str] = {
"id",
"evolving",
"use_record_for_java",
"deprecated",
"namespace",
}
# Known Fory enum-level options (option statements inside enum body)
KNOWN_FORY_ENUM_OPTIONS: Set[str] = {
"id",
"deprecated",
}
class ParseError(Exception):
"""Error during parsing."""
def __init__(self, message: str, line: int, column: int):
self.message = message
self.line = line
self.column = column
super().__init__(f"Line {line}, Column {column}: {message}")
class Parser:
"""Recursive descent parser for FDL."""
def __init__(self, tokens: List[Token]):
self.tokens = tokens
self.pos = 0
@classmethod
def from_source(cls, source: str, filename: str = "<input>") -> "Parser":
"""Create a parser from source code."""
lexer = Lexer(source, filename)
tokens = lexer.tokenize()
return cls(tokens)
def at_end(self) -> bool:
"""Check if we've reached the end of tokens."""
return self.current().type == TokenType.EOF
def current(self) -> Token:
"""Get the current token."""
if self.pos >= len(self.tokens):
return self.tokens[-1] # Return EOF
return self.tokens[self.pos]
def previous(self) -> Token:
"""Get the previous token."""
return self.tokens[self.pos - 1]
def peek(self, offset: int = 0) -> Token:
"""Peek at a token without consuming it."""
pos = self.pos + offset
if pos >= len(self.tokens):
return self.tokens[-1] # Return EOF
return self.tokens[pos]
def check(self, token_type: TokenType) -> bool:
"""Check if the current token has the given type."""
return self.current().type == token_type
def match(self, *types: TokenType) -> bool:
"""If current token matches any of the types, consume and return True."""
for token_type in types:
if self.check(token_type):
self.advance()
return True
return False
def advance(self) -> Token:
"""Consume and return the current token."""
token = self.current()
if not self.at_end():
self.pos += 1
return token
def consume(self, token_type: TokenType, message: str = None) -> Token:
"""Consume a token of the expected type, or raise an error."""
if self.check(token_type):
return self.advance()
token = self.current()
if message is None:
message = f"Expected {token_type.name}, got {token.type.name}"
raise ParseError(message, token.line, token.column)
def error(self, message: str) -> ParseError:
"""Create a parse error at the current position."""
token = self.current()
return ParseError(message, token.line, token.column)
def parse(self) -> Schema:
"""Parse the entire input and return a Schema."""
package = None
imports = []
enums = []
messages = []
options = {}
while not self.at_end():
if self.check(TokenType.PACKAGE):
if package is not None:
raise self.error("Duplicate package declaration")
package = self.parse_package()
elif self.check(TokenType.IMPORT):
imports.append(self.parse_import())
elif self.check(TokenType.OPTION):
# File-level option
name, value = self.parse_file_option()
options[name] = value
elif self.check(TokenType.ENUM):
enums.append(self.parse_enum())
elif self.check(TokenType.MESSAGE):
messages.append(self.parse_message())
else:
raise self.error(f"Unexpected token: {self.current().value}")
return Schema(package, imports, enums, messages, options)
def parse_package(self) -> str:
"""Parse a package declaration: package foo.bar;"""
self.consume(TokenType.PACKAGE)
# Package name can be dotted: foo.bar.baz
parts = [self.consume(TokenType.IDENT).value]
while self.check(TokenType.DOT):
self.advance() # consume the dot
parts.append(
self.consume(TokenType.IDENT, "Expected identifier after '.'").value
)
self.consume(TokenType.SEMI, "Expected ';' after package name")
return ".".join(parts)
def parse_option_value(self):
"""Parse an option value (string, bool, int, or identifier)."""
if self.check(TokenType.STRING):
return self.advance().value
elif self.check(TokenType.TRUE):
self.advance()
return True
elif self.check(TokenType.FALSE):
self.advance()
return False
elif self.check(TokenType.INT):
return int(self.advance().value)
elif self.check(TokenType.IDENT):
return self.advance().value
else:
raise self.error(f"Expected option value, got {self.current().type.name}")
def parse_file_option(self) -> tuple:
"""Parse a file-level option.
Supports two syntaxes:
1. Standard: option java_package = "com.example";
2. Extension: option (fory).use_record_for_java_message = true;
Returns a tuple of (option_name, option_value).
For extension options, the name is prefixed with the extension name: "fory.use_record_for_java_message"
"""
self.consume(TokenType.OPTION)
# Check for extension syntax: (extension_name).option_name
extension_name = None
if self.check(TokenType.LPAREN):
self.advance() # consume (
extension_name = self.consume(
TokenType.IDENT, "Expected extension name"
).value
self.consume(TokenType.RPAREN, "Expected ')' after extension name")
self.consume(TokenType.DOT, "Expected '.' after extension name")
name_token = self.consume(TokenType.IDENT, "Expected option name")
option_name = name_token.value
# Build full option name for extension options
if extension_name:
full_option_name = f"{extension_name}.{option_name}"
else:
full_option_name = option_name
self.consume(TokenType.EQUALS, "Expected '=' after option name")
option_value = self.parse_option_value()
self.consume(TokenType.SEMI, "Expected ';' after option statement")
# Warn about unknown options
if extension_name:
if extension_name == "fory":
if option_name not in KNOWN_FORY_FILE_OPTIONS:
warnings.warn(
f"Line {name_token.line}: ignoring unknown fory option '{option_name}'",
stacklevel=2,
)
else:
warnings.warn(
f"Line {name_token.line}: ignoring unknown extension '{extension_name}'",
stacklevel=2,
)
else:
if option_name not in KNOWN_FILE_OPTIONS:
warnings.warn(
f"Line {name_token.line}: ignoring unknown option '{option_name}'",
stacklevel=2,
)
return (full_option_name, option_value)
def parse_import(self) -> Import:
"""Parse an import statement: import "path/to/file.fdl";"""
start = self.current()
self.consume(TokenType.IMPORT)
# Check for forbidden import modifiers (protobuf syntax)
if self.check(TokenType.PUBLIC):
raise ParseError(
"'import public' is not supported in FDL.\n"
" Reason: FDL uses a simpler import model where all imported types\n"
" are available to the importing file. Re-exporting imports is not\n"
" supported. Simply use 'import \"path/to/file.fdl\";' instead.\n"
" If you need types from multiple files, import each file directly.",
start.line,
start.column,
)
if self.check(TokenType.WEAK):
raise ParseError(
"'import weak' is not supported in FDL.\n"
" Reason: Weak imports are a protobuf-specific feature for optional\n"
" dependencies. FDL requires all imports to be present at compile time.\n"
" Use 'import \"path/to/file.fdl\";' instead.",
start.line,
start.column,
)
path_token = self.consume(TokenType.STRING, "Expected import path string")
self.consume(TokenType.SEMI, "Expected ';' after import statement")
return Import(
path=path_token.value,
line=start.line,
column=start.column,
)
def parse_enum(self) -> Enum:
"""Parse an enum: enum Color [id=101] { ... }
Supports:
- Inline type options: enum Color [id=101] { ... }
- Body option statements: option (fory).id = 100;
"""
start = self.current()
self.consume(TokenType.ENUM)
name = self.consume(TokenType.IDENT, "Expected enum name").value
# Optional inline type options: [id=101, deprecated=true]
type_id = None
inline_options = {}
if self.check(TokenType.LBRACKET):
inline_options = self.parse_type_options(name)
if "id" in inline_options:
type_id = inline_options["id"]
self.consume(TokenType.LBRACE, "Expected '{' after enum name")
values = []
body_options = {}
while not self.check(TokenType.RBRACE):
# Check for option statements
if self.check(TokenType.OPTION):
opt_name, opt_value = self.parse_enum_option(name)
body_options[opt_name] = opt_value
# Handle fory.id option to set type_id
if opt_name == "fory.id" and type_id is None:
if isinstance(opt_value, int) and opt_value > 0:
type_id = opt_value
# Check for reserved statements
elif self.check(TokenType.RESERVED):
self.parse_reserved()
else:
values.append(self.parse_enum_value())
self.consume(TokenType.RBRACE, "Expected '}' after enum values")
# Merge inline options and body options (body options take precedence)
all_options = {**inline_options, **body_options}
return Enum(
name=name,
type_id=type_id,
values=values,
options=all_options,
line=start.line,
column=start.column,
)
def parse_enum_option(self, enum_name: str) -> tuple:
"""Parse and validate an enum option statement.
Supports two syntaxes:
1. Standard: option deprecated = true;
2. Extension: option (fory).id = 100;
Forbidden options:
- allow_alias = true: Enum aliases are not supported
Returns a tuple of (option_name, option_value).
"""
option_token = self.consume(TokenType.OPTION)
# Check for extension syntax: (extension_name).option_name
extension_name = None
if self.check(TokenType.LPAREN):
self.advance() # consume (
extension_name = self.consume(
TokenType.IDENT, "Expected extension name"
).value
self.consume(TokenType.RPAREN, "Expected ')' after extension name")
self.consume(TokenType.DOT, "Expected '.' after extension name")
name_token = self.consume(TokenType.IDENT, "Expected option name")
option_name = name_token.value
# Build full option name for extension options
if extension_name:
full_option_name = f"{extension_name}.{option_name}"
else:
full_option_name = option_name
self.consume(TokenType.EQUALS, "Expected '=' after option name")
option_value = self.parse_option_value()
self.consume(TokenType.SEMI, "Expected ';' after option statement")
# Validate forbidden options
if option_name == "allow_alias" and option_value is True:
raise ParseError(
f"'option allow_alias = true' is forbidden in enum '{enum_name}'. "
"Enum aliases (multiple names for the same value) are not supported.",
option_token.line,
option_token.column,
)
# Warn about unknown options
if extension_name:
if extension_name == "fory":
if option_name not in KNOWN_FORY_ENUM_OPTIONS:
warnings.warn(
f"Line {name_token.line}: ignoring unknown fory enum option '{option_name}' in '{enum_name}'",
stacklevel=2,
)
else:
warnings.warn(
f"Line {name_token.line}: ignoring unknown extension '{extension_name}'",
stacklevel=2,
)
else:
# Standard options - currently we only recognize deprecated and allow_alias
if option_name not in {"deprecated", "allow_alias"}:
warnings.warn(
f"Line {name_token.line}: ignoring unknown enum option '{option_name}' in '{enum_name}'",
stacklevel=2,
)
return (full_option_name, option_value)
def parse_message_option(self, message_name: str) -> tuple:
"""Parse a message-level option statement.
Supports two syntaxes:
1. Standard: option deprecated = true;
2. Extension: option (fory).id = 100;
Returns a tuple of (option_name, option_value).
For extension options, the name is prefixed with the extension name.
"""
self.consume(TokenType.OPTION)
# Check for extension syntax: (extension_name).option_name
extension_name = None
if self.check(TokenType.LPAREN):
self.advance() # consume (
extension_name = self.consume(
TokenType.IDENT, "Expected extension name"
).value
self.consume(TokenType.RPAREN, "Expected ')' after extension name")
self.consume(TokenType.DOT, "Expected '.' after extension name")
name_token = self.consume(TokenType.IDENT, "Expected option name")
option_name = name_token.value
# Build full option name for extension options
if extension_name:
full_option_name = f"{extension_name}.{option_name}"
else:
full_option_name = option_name
self.consume(TokenType.EQUALS, "Expected '=' after option name")
option_value = self.parse_option_value()
self.consume(TokenType.SEMI, "Expected ';' after option statement")
# Warn about unknown options
if extension_name:
if extension_name == "fory":
if option_name not in KNOWN_FORY_MESSAGE_OPTIONS:
warnings.warn(
f"Line {name_token.line}: ignoring unknown fory message option '{option_name}' in '{message_name}'",
stacklevel=2,
)
else:
warnings.warn(
f"Line {name_token.line}: ignoring unknown extension '{extension_name}'",
stacklevel=2,
)
else:
# Standard options - currently we only recognize deprecated
if option_name not in {"deprecated"}:
warnings.warn(
f"Line {name_token.line}: ignoring unknown message option '{option_name}' in '{message_name}'",
stacklevel=2,
)
return (full_option_name, option_value)
def parse_reserved(self):
"""Parse a reserved statement.
Supports:
- reserved 2, 15, 9 to 11, 40 to max; (numbers and ranges)
- reserved "FOO", "BAR"; (field/value names)
"""
self.consume(TokenType.RESERVED)
# Parse comma-separated list of reserved items
while True:
if self.check(TokenType.STRING):
# Reserved name: "FOO"
self.advance()
elif self.check(TokenType.INT):
# Reserved number or range start: 2 or 9 to 11
self.advance()
# Check for range: N to M or N to max
if self.check(TokenType.TO):
self.advance()
if self.check(TokenType.MAX):
self.advance()
elif self.check(TokenType.INT):
self.advance()
else:
raise self.error("Expected integer or 'max' after 'to'")
else:
raise self.error(
f"Expected reserved number or string, got {self.current().type.name}"
)
# Check for comma (more items) or semicolon (end)
if self.check(TokenType.COMMA):
self.advance()
elif self.check(TokenType.SEMI):
break
else:
raise self.error("Expected ',' or ';' in reserved statement")
self.consume(TokenType.SEMI, "Expected ';' after reserved statement")
def parse_enum_value(self) -> EnumValue:
"""Parse an enum value: NAME = 0;"""
start = self.current()
name = self.consume(TokenType.IDENT, "Expected enum value name").value
self.consume(TokenType.EQUALS, "Expected '=' after enum value name")
value_token = self.consume(TokenType.INT, "Expected integer value")
value = int(value_token.value)
self.consume(TokenType.SEMI, "Expected ';' after enum value")
return EnumValue(
name=name,
value=value,
line=start.line,
column=start.column,
)
def parse_message(self) -> Message:
"""Parse a message: message Dog [id=102] { ... }
Supports:
- Inline type options: message Dog [id=102] { ... }
- Body option statements: option (fory).id = 100;
- Nested messages and enums:
message Outer {
message Inner { ... }
enum Status { ... }
Inner inner = 1;
}
"""
start = self.current()
self.consume(TokenType.MESSAGE)
name = self.consume(TokenType.IDENT, "Expected message name").value
# Optional inline type options: [id=102, deprecated=true]
type_id = None
inline_options = {}
if self.check(TokenType.LBRACKET):
inline_options = self.parse_type_options(name)
if "id" in inline_options:
type_id = inline_options["id"]
self.consume(TokenType.LBRACE, "Expected '{' after message name")
fields = []
nested_messages = []
nested_enums = []
body_options = {}
while not self.check(TokenType.RBRACE):
# Check for reserved statements
if self.check(TokenType.RESERVED):
self.parse_reserved()
# Check for option statements (message-level options)
elif self.check(TokenType.OPTION):
opt_name, opt_value = self.parse_message_option(name)
body_options[opt_name] = opt_value
# Handle fory.id option to set type_id
if opt_name == "fory.id" and type_id is None:
if isinstance(opt_value, int) and opt_value > 0:
type_id = opt_value
# Check for nested message
elif self.check(TokenType.MESSAGE):
nested_messages.append(self.parse_message())
# Check for nested enum
elif self.check(TokenType.ENUM):
nested_enums.append(self.parse_enum())
else:
fields.append(self.parse_field())
self.consume(TokenType.RBRACE, "Expected '}' after message fields")
# Merge inline options and body options (body options take precedence)
all_options = {**inline_options, **body_options}
return Message(
name=name,
type_id=type_id,
fields=fields,
nested_messages=nested_messages,
nested_enums=nested_enums,
options=all_options,
line=start.line,
column=start.column,
)
def parse_field(self) -> Field:
"""Parse a field: optional ref repeated Type name = 1 [options];
Supports:
- Keyword modifiers: optional ref repeated
- Bracket options: [deprecated=true, (fory).ref=true]
"""
start = self.current()
# Parse modifiers (optional/ref before repeated apply to the collection/field,
# optional/ref after repeated apply to elements)
optional = False
ref = False
element_optional = False
element_ref = False
repeated = False
while True:
if self.match(TokenType.OPTIONAL):
if repeated:
element_optional = True
else:
optional = True
continue
if self.match(TokenType.REF):
if repeated:
element_ref = True
else:
ref = True
continue
if self.match(TokenType.REPEATED):
if repeated:
raise self.error("Repeated modifier specified more than once")
repeated = True
continue
break
# Parse type
field_type = self.parse_type()
# Wrap in ListType if repeated
if repeated:
field_type = ListType(field_type)
# Parse field name
name = self.consume(TokenType.IDENT, "Expected field name").value
# Parse field number
self.consume(TokenType.EQUALS, "Expected '=' after field name")
number_token = self.consume(TokenType.INT, "Expected field number")
number = int(number_token.value)
# Parse optional field options: [deprecated=true, (fory).ref=true]
field_options = {}
if self.check(TokenType.LBRACKET):
field_options = self.parse_field_options(name)
# Handle fory.ref or ref option to set ref flag
if (
field_options.get("fory.ref") is True
or field_options.get("fory.tracking_ref") is True
):
ref = True
if (
field_options.get("ref") is True
or field_options.get("tracking_ref") is True
):
ref = True
# Handle fory.nullable or nullable option to set optional flag
if (
field_options.get("fory.nullable") is True
or field_options.get("nullable") is True
):
optional = True
self.consume(TokenType.SEMI, "Expected ';' after field declaration")
return Field(
name=name,
field_type=field_type,
number=number,
optional=optional,
ref=ref,
element_optional=element_optional,
element_ref=element_ref,
options=field_options,
line=start.line,
column=start.column,
)
def parse_field_options(self, field_name: str) -> dict:
"""Parse field options: [deprecated=true, (fory).ref=true]
Supports two syntaxes:
1. Standard: [deprecated=true, json_name="foo"]
2. Extension: [(fory).ref=true, (fory).nullable=true]
Returns a dict of option names to values.
For extension options, the name is prefixed: "fory.ref"
"""
self.consume(TokenType.LBRACKET)
options = {}
while True:
# Check for extension syntax: (extension_name).option_name
extension_name = None
if self.check(TokenType.LPAREN):
self.advance() # consume (
extension_name = self.consume(
TokenType.IDENT, "Expected extension name"
).value
self.consume(TokenType.RPAREN, "Expected ')' after extension name")
self.consume(TokenType.DOT, "Expected '.' after extension name")
# Parse option name (can be IDENT or keyword like 'ref', 'optional', etc.)
name_token = self.current()
if self.check(TokenType.IDENT):
self.advance()
option_name = name_token.value
elif self.check(TokenType.REF):
# 'ref' is a keyword but valid as option name
self.advance()
option_name = "ref"
elif self.check(TokenType.OPTIONAL):
# 'optional' is a keyword but valid as option name
self.advance()
option_name = "optional"
elif self.check(TokenType.REPEATED):
# 'repeated' is a keyword but valid as option name
self.advance()
option_name = "repeated"
elif self.check(TokenType.WEAK):
# 'weak' is a keyword but valid as option name
self.advance()
option_name = "weak"
elif self.check(TokenType.TRUE):
# 'true' can be used as option name in some contexts
self.advance()
option_name = "true"
elif self.check(TokenType.FALSE):
# 'false' can be used as option name in some contexts
self.advance()
option_name = "false"
else:
raise self.error(
f"Expected option name, got {self.current().type.name}"
)
# Build full option name for extension options
if extension_name:
full_option_name = f"{extension_name}.{option_name}"
else:
full_option_name = option_name
self.consume(TokenType.EQUALS, "Expected '=' after option name")
# Parse option value
option_value = self.parse_option_value()
options[full_option_name] = option_value
# Warn about unknown field options
if extension_name:
if extension_name == "fory":
if option_name not in KNOWN_FORY_FIELD_OPTIONS:
warnings.warn(
f"Line {name_token.line}: ignoring unknown fory field option '{option_name}' on field '{field_name}'",
stacklevel=2,
)
else:
warnings.warn(
f"Line {name_token.line}: ignoring unknown extension '{extension_name}'",
stacklevel=2,
)
else:
if option_name not in KNOWN_FIELD_OPTIONS:
warnings.warn(
f"Line {name_token.line}: ignoring unknown field option '{option_name}' on field '{field_name}'",
stacklevel=2,
)
# Check for comma (more options) or closing bracket (end)
if self.check(TokenType.COMMA):
self.advance()
elif self.check(TokenType.RBRACKET):
break
else:
raise self.error("Expected ',' or ']' in field options")
self.consume(TokenType.RBRACKET, "Expected ']' after field options")
return options
def parse_type_options(self, type_name: str) -> dict:
"""Parse type options: [id=100, deprecated=true]
Returns a dict of option names to values.
Warns about unknown options.
"""
self.consume(TokenType.LBRACKET)
options = {}
while True:
# Parse option name
name_token = self.consume(TokenType.IDENT, "Expected option name")
option_name = name_token.value
self.consume(TokenType.EQUALS, "Expected '=' after option name")
# Parse option value (can be string, bool, int, or identifier)
if self.check(TokenType.STRING):
option_value = self.advance().value
elif self.check(TokenType.TRUE):
self.advance()
option_value = True
elif self.check(TokenType.FALSE):
self.advance()
option_value = False
elif self.check(TokenType.INT):
option_value = int(self.advance().value)
elif self.check(TokenType.IDENT):
option_value = self.advance().value
else:
raise self.error(
f"Expected option value, got {self.current().type.name}"
)
# Validate 'id' option must be a positive integer
if option_name == "id":
if not isinstance(option_value, int):
raise self.error(
f"Type option 'id' must be an integer, got {type(option_value).__name__}"
)
if option_value <= 0:
raise self.error(
f"Type option 'id' must be a positive integer, got {option_value}"
)
# Warn about unknown type options
if option_name not in KNOWN_TYPE_OPTIONS:
warnings.warn(
f"Line {name_token.line}: ignoring unknown type option '{option_name}' on type '{type_name}'",
stacklevel=2,
)
options[option_name] = option_value
# Check for comma (more options) or closing bracket (end)
if self.check(TokenType.COMMA):
self.advance()
elif self.check(TokenType.RBRACKET):
break
else:
raise self.error("Expected ',' or ']' in type options")
self.consume(TokenType.RBRACKET, "Expected ']' after type options")
return options
def parse_type(self) -> FieldType:
"""Parse a type: int32, string, map<K, V>, Parent.Child, or a named type."""
if self.check(TokenType.MAP):
return self.parse_map_type()
if not self.check(TokenType.IDENT):
raise self.error(f"Expected type name, got {self.current().type.name}")
type_name = self.consume(TokenType.IDENT).value
# Check if it's a primitive type
if type_name in PRIMITIVE_TYPES:
return PrimitiveType(PRIMITIVE_TYPES[type_name])
# Check for qualified name (e.g., Parent.Child or Outer.Middle.Inner)
while self.check(TokenType.DOT):
self.advance() # consume the dot
if not self.check(TokenType.IDENT):
raise self.error("Expected identifier after '.'")
type_name += "." + self.consume(TokenType.IDENT).value
# It's a named type (reference to message or enum)
return NamedType(type_name)
def parse_map_type(self) -> MapType:
"""Parse a map type: map<KeyType, ValueType>"""
self.consume(TokenType.MAP)
self.consume(TokenType.LANGLE, "Expected '<' after 'map'")
key_type = self.parse_type()
self.consume(TokenType.COMMA, "Expected ',' between map key and value types")
value_type = self.parse_type()
self.consume(TokenType.RANGLE, "Expected '>' after map value type")
return MapType(key_type, value_type)
def parse(source: str, filename: str = "<input>") -> Schema:
"""Parse FDL source code and return a Schema."""
parser = Parser.from_source(source, filename)
return parser.parse()