-
Notifications
You must be signed in to change notification settings - Fork 58
/
Copy pathparser.rs
1548 lines (1386 loc) · 54.8 KB
/
parser.rs
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
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2020 Ghaith Hachem and Mathias Rieder
use std::ops::Range;
use plc_ast::{
ast::{
AccessModifier, ArgumentProperty, AstFactory, AstNode, AstStatement, AutoDerefType, CompilationUnit,
ConfigVariable, DataType, DataTypeDeclaration, DeclarationKind, DirectAccessType, GenericBinding,
HardwareAccessType, Identifier, Implementation, Interface, LinkageType, PolymorphismMode, Pou,
PouType, PropertyBlock, PropertyImplementation, PropertyKind, ReferenceAccess, ReferenceExpr,
TypeNature, UserTypeDeclaration, Variable, VariableBlock, VariableBlockType,
},
provider::IdProvider,
};
use plc_diagnostics::{
diagnostician::Diagnostician,
diagnostics::{Diagnostic, Severity},
};
use plc_source::{
source_location::{SourceLocation, SourceLocationFactory},
SourceCode, SourceContainer,
};
use plc_util::convention::qualified_name;
use crate::{
expect_token,
lexer::{
self, ParseSession,
Token::{self, *},
},
typesystem::DINT_TYPE,
};
use self::{
control_parser::parse_control_statement,
expressions_parser::{parse_expression, parse_expression_list},
};
mod control_parser;
pub mod expressions_parser;
#[cfg(test)]
pub mod tests;
pub type ParsedAst = (CompilationUnit, Vec<Diagnostic>);
pub fn parse_file(
source: &SourceCode,
linkage: LinkageType,
id_provider: IdProvider,
diagnostician: &mut Diagnostician,
) -> Result<CompilationUnit, Diagnostic> {
let location_factory = SourceLocationFactory::for_source(source);
let (unit, errors) = parse(
lexer::lex_with_ids(&source.source, id_provider, location_factory),
linkage,
source.get_location_str(),
);
//Register the source file with the diagnostician
//TODO: We should reduce the clone here
diagnostician.register_file(source.get_location_str().to_string(), source.source.clone()); // TODO: Remove clone here, generally passing the GlobalContext instead of the actual source here or in the handle method should be sufficient
if diagnostician.handle(&errors) == Severity::Error {
Err(Diagnostic::new("Compilation aborted due to critical parse errors").with_sub_diagnostics(errors))
} else {
Ok(unit)
}
}
pub fn parse(mut lexer: ParseSession, lnk: LinkageType, file_name: &'static str) -> ParsedAst {
let mut unit = CompilationUnit::new(file_name);
let mut linkage = lnk;
let mut constant = false;
loop {
match lexer.token {
PropertyExternal => {
linkage = LinkageType::External;
lexer.advance();
//Don't reset linkage
continue;
}
PropertyConstant => {
// parse optional const pragma (only allowed in builtins for now)
constant = true;
lexer.advance();
continue;
}
KeywordInterface => {
// We ignore any method implementations in interfaces as we do not support default impls yet
let (interfaces, _) = parse_interface(&mut lexer);
unit.interfaces.push(interfaces);
}
KeywordVarGlobal => unit.global_vars.push(parse_variable_block(&mut lexer, linkage)),
KeywordVarConfig => unit.var_config.extend(parse_config_variables(&mut lexer)),
KeywordProgram | KeywordClass | KeywordFunction | KeywordFunctionBlock => {
let params = match lexer.token {
KeywordProgram => (PouType::Program, KeywordEndProgram),
KeywordClass => (PouType::Class, KeywordEndClass),
KeywordFunction => (PouType::Function, KeywordEndFunction),
_ => (PouType::FunctionBlock, KeywordEndFunctionBlock),
};
parse_pou(&mut lexer, &mut unit, params.0, linkage, params.1, constant);
// reset const pragma
constant = false;
}
KeywordAction => {
if let Some(implementation) = parse_action(&mut lexer, linkage, None) {
unit.implementations.push(implementation);
}
}
KeywordActions => {
let last_pou = unit
.pous
.iter()
.filter(|it| {
// Only consider the last POU that is a program, function, function block
// or class
matches!(
it.kind,
PouType::Program | PouType::Function | PouType::FunctionBlock | PouType::Class
)
})
.last()
.map(|it| it.name.as_str())
.unwrap_or("__unknown__");
let mut actions = parse_actions(&mut lexer, linkage, last_pou);
unit.implementations.append(&mut actions);
}
KeywordType => {
let unit_type = parse_type(&mut lexer);
for utype in unit_type {
unit.user_types.push(utype);
}
}
KeywordEndActions | End => return (unit, lexer.diagnostics),
_ => {
lexer.accept_diagnostic(Diagnostic::unexpected_token_found(
"StartKeyword",
lexer.slice(),
lexer.location(),
));
lexer.advance();
}
};
linkage = lnk;
}
//the match in the loop will always return
}
fn parse_actions(
lexer: &mut ParseSession,
linkage: LinkageType,
default_container: &str,
) -> Vec<Implementation> {
parse_any_in_region(lexer, vec![KeywordEndActions], |lexer| {
lexer.advance();
let container =
if lexer.token == Identifier { lexer.slice_and_advance() } else { default_container.into() };
let mut impls = vec![];
//Go through each action
while lexer.token != KeywordEndActions && !lexer.is_end_of_stream() {
match lexer.token {
KeywordAction => {
if let Some(implementation) = parse_action(lexer, linkage, Some(&container)) {
impls.push(implementation);
}
}
_ => {
lexer.accept_diagnostic(Diagnostic::unexpected_token_found(
"KeywordAction",
lexer.slice(),
lexer.location(),
));
return impls;
}
}
}
impls
})
}
/// Parses an interface and its methods / properties
fn parse_interface(lexer: &mut ParseSession) -> (Interface, Vec<Implementation>) {
let location_start = lexer.range().start;
lexer.try_consume_or_report(KeywordInterface);
let (name, location_name) = match lexer.token {
Token::Identifier => parse_identifier(lexer).expect("unreachable, already matched here"),
_ => {
lexer.accept_diagnostic(
Diagnostic::new("Expected a name for the interface definition but got nothing")
.with_error_code("E006")
.with_location(lexer.last_location()),
);
// We want to keep parsing, hence we return some undefined values; the parser will yield an
// unrecoverable error though
(String::new(), SourceLocation::undefined())
}
};
let mut extensions = Vec::new();
let mut methods = Vec::new();
let mut implementations = Vec::new();
let mut properties = Vec::new();
if lexer.try_consume(KeywordExtends) {
while let Identifier = lexer.token {
let (name, location) = parse_identifier(lexer).expect("unreachable, already matched here");
extensions.push(Identifier { name, location });
lexer.try_consume(KeywordComma);
}
}
loop {
match lexer.token {
KeywordMethod => {
if let Some((method, imp)) =
parse_method(lexer, &name, DeclarationKind::Abstract, LinkageType::Internal, false)
{
// This is temporary? At some point we'll support them but for now it's a diagnostic
if !imp.statements.is_empty() {
lexer.accept_diagnostic(
Diagnostic::new("Interfaces can not have a default implementation")
.with_error_code("E113")
.with_location(&imp.statements.first().unwrap().location),
);
}
methods.push(method);
implementations.push(imp);
}
}
KeywordProperty => {
if let Some(property) = parse_property(lexer) {
for property in property.implementations.iter().filter(|imp| !imp.body.is_empty()) {
lexer.accept_diagnostic(
Diagnostic::new("Interfaces can not have a default implementation")
.with_error_code("E113")
.with_location(&property.body.first().unwrap().location),
);
}
properties.push(property);
}
}
_ => break,
}
}
lexer.try_consume_or_report(KeywordEndInterface);
let location_end = lexer.range().start;
(
Interface {
id: lexer.next_id(),
ident: Identifier { name, location: location_name },
methods,
extensions,
location: lexer.source_range_factory.create_range(location_start..location_end),
properties,
},
implementations,
)
}
///
/// parse a pou
/// # Arguments
///
/// * `lexer` - the lexer
/// * `pou_type` - the type of the pou currently parsed
/// * `linkage` - internal, external ?
/// * `expected_end_token` - the token that ends this pou
///
fn parse_pou(
lexer: &mut ParseSession,
unit: &mut CompilationUnit,
kind: PouType,
linkage: LinkageType,
expected_end_token: lexer::Token,
constant: bool,
) {
if constant && !matches!(linkage, LinkageType::BuiltIn) {
lexer.accept_diagnostic(Diagnostic::const_pragma_is_not_allowed(
lexer.last_location().span(&lexer.location()),
));
}
let start = lexer.range().start;
lexer.advance(); //Consume ProgramKeyword
let closing_tokens = vec![
expected_end_token,
KeywordEndAction,
KeywordEndProgram,
KeywordEndFunction,
KeywordEndFunctionBlock,
KeywordEndClass,
];
let result = parse_any_in_region(lexer, closing_tokens.clone(), |lexer| {
// parse polymorphism mode for all pou types
// check in validator if pou type allows polymorphism
let poly_mode = parse_polymorphism_mode(lexer, &kind);
let (name, name_location) =
parse_identifier(lexer).unwrap_or_else(|| ("".to_string(), SourceLocation::undefined())); // parse POU name
let generics = parse_generics(lexer);
with_scope(lexer, name.clone(), |lexer| {
// TODO: Parse USING directives
let super_class = parse_super_class(lexer);
let interfaces = parse_interface_declarations(lexer);
// parse an optional return type
// classes do not have a return type (check in validator)
let return_type = parse_return_type(lexer);
// parse variable declarations. note that var in/out/inout
// blocks are not allowed inside of class declarations.
let mut variable_blocks = vec![];
let allowed_var_types = [
KeywordVar,
KeywordVarInput,
KeywordVarOutput,
KeywordVarInOut,
KeywordVarTemp,
KeywordVarExternal,
];
while allowed_var_types.contains(&lexer.token) {
variable_blocks.push(parse_variable_block(lexer, LinkageType::Internal));
}
let mut impl_pous = Vec::new();
let mut implementations = Vec::new();
let mut properties = Vec::new();
// classes and function blocks can have methods. methods consist of a Pou part
// and an implementation part. That's why we get another (Pou, Implementation)
// tuple out of parse_method() that has to be added to the list of Pous and
// implementations. Note that function blocks have to start with the method
// declarations before their implementation.
// all other Pous need to be checked in the validator if they can have methods.
while matches!(lexer.token, KeywordMethod | KeywordProperty | PropertyConstant) {
if !matches!(kind, PouType::FunctionBlock | PouType::Class | PouType::Program) {
let location = lexer.source_range_factory.create_range(lexer.last_range.clone());
let pre = if matches!(lexer.token, KeywordProperty) { "Properties" } else { "Methods" };
lexer.accept_diagnostic(
Diagnostic::new(format!("{pre} cannot be declared in a {kind}"))
.with_location(location),
);
}
if lexer.token == KeywordProperty {
if let Some(property) = parse_property(lexer) {
properties.push(property);
}
} else {
let is_const = lexer.try_consume(PropertyConstant);
if let Some((pou, implementation)) =
parse_method(lexer, &name, DeclarationKind::Concrete, linkage, is_const)
{
impl_pous.push(pou);
implementations.push(implementation);
}
}
}
// a class may not contain an implementation
// check in validator
implementations.push(parse_implementation(
lexer,
linkage,
kind.clone(),
&name,
&name,
!generics.is_empty(),
name_location.clone(),
));
let mut pous = vec![Pou {
name,
id: lexer.next_id(),
kind,
variable_blocks,
return_type,
location: lexer.source_range_factory.create_range(start..lexer.range().end),
name_location,
poly_mode,
generics,
linkage,
super_class,
interfaces,
is_const: constant,
properties,
}];
pous.append(&mut impl_pous);
(pous, implementations)
})
});
//check if we ended on the right end-keyword
if closing_tokens.contains(&lexer.last_token) && lexer.last_token != expected_end_token {
lexer.accept_diagnostic(Diagnostic::unexpected_token_found(
format!("{expected_end_token:?}").as_str(),
lexer.slice_region(lexer.last_range.clone()),
lexer.source_range_factory.create_range(lexer.last_range.clone()),
));
}
let (mut pous, mut implementations) = result;
unit.pous.append(&mut pous);
unit.implementations.append(&mut implementations);
}
fn parse_generics(lexer: &mut ParseSession) -> Vec<GenericBinding> {
if lexer.try_consume(Token::OperatorLess) {
parse_any_in_region(lexer, vec![Token::OperatorGreater], |lexer| {
let mut generics = vec![];
loop {
//identifier
if let Some((name, _)) = parse_identifier(lexer) {
lexer.try_consume_or_report(Token::KeywordColon);
//Expect a type nature
if let Some(nature) = parse_identifier(lexer).map(|(it, _)| parse_type_nature(lexer, &it))
{
generics.push(GenericBinding { name, nature });
}
}
if !lexer.try_consume(Token::KeywordComma) || lexer.try_consume(Token::OperatorGreater) {
break;
}
}
generics
})
} else {
vec![]
}
}
/// Parses the comma seperated identifiers after an `IMPLEMENTS` keyword, e.g. `bar` and `baz` in
/// `INTERFACE foo IMPLEMENTS bar`
fn parse_interface_declarations(lexer: &mut ParseSession) -> Vec<Identifier> {
let mut declarations = Vec::new();
if !lexer.try_consume(KeywordImplements) {
return declarations;
}
if lexer.token != Token::Identifier {
lexer.accept_diagnostic(
Diagnostic::new(
"Expected a comma separated list of identifiers after `IMPLEMENTS` but got nothing",
)
.with_error_code("E006")
.with_location(lexer.last_location()),
);
return declarations;
}
loop {
match lexer.token {
Token::Identifier => {
let (name, location) = parse_identifier(lexer).expect("Identifier already matched");
declarations.push(Identifier { name, location });
}
Token::KeywordComma => lexer.advance(),
_ => break,
}
}
declarations
}
fn parse_type_nature(lexer: &mut ParseSession, nature: &str) -> TypeNature {
match nature {
"ANY" => TypeNature::Any,
"ANY_DERIVED" => TypeNature::Derived,
"ANY_ELEMENTARY" => TypeNature::Elementary,
"ANY_MAGNITUDE" => TypeNature::Magnitude,
"ANY_NUM" => TypeNature::Num,
"ANY_REAL" => TypeNature::Real,
"ANY_INT" => TypeNature::Int,
"ANY_SIGNED" => TypeNature::Signed,
"ANY_UNSIGNED" => TypeNature::Unsigned,
"ANY_DURATION" => TypeNature::Duration,
"ANY_BIT" => TypeNature::Bit,
"ANY_CHARS" => TypeNature::Chars,
"ANY_STRING" => TypeNature::String,
"ANY_CHAR" => TypeNature::Char,
"ANY_DATE" => TypeNature::Date,
"__ANY_VLA" => TypeNature::__VLA,
_ => {
lexer.accept_diagnostic(
Diagnostic::new(format!("Unkown type nature `{nature}`"))
.with_location(lexer.location())
.with_error_code("E063"),
);
TypeNature::Any
}
}
}
fn parse_polymorphism_mode(lexer: &mut ParseSession, pou_type: &PouType) -> Option<PolymorphismMode> {
match pou_type {
PouType::Class | PouType::FunctionBlock | PouType::Method { .. } => {
Some(
// See if the method/pou was declared FINAL or ABSTRACT
if lexer.try_consume(KeywordFinal) {
PolymorphismMode::Final
} else if lexer.try_consume(KeywordAbstract) {
PolymorphismMode::Abstract
} else {
PolymorphismMode::None
},
)
}
_ => None,
}
}
fn parse_super_class(lexer: &mut ParseSession) -> Option<Identifier> {
let mut extensions = vec![];
while lexer.try_consume(KeywordExtends) {
let name_and_location = parse_identifier(lexer)?;
extensions.push(name_and_location);
}
extensions.iter().skip(1).for_each(|(_, location)| {
lexer.accept_diagnostic(
Diagnostic::new("Multiple inheritance. POUs can only be extended once.".to_string())
.with_error_code("E114")
.with_location(location),
)
});
extensions
.first()
.map(|(name, location)| Identifier { name: name.to_string(), location: location.clone() })
}
fn parse_return_type(lexer: &mut ParseSession) -> Option<DataTypeDeclaration> {
if lexer.try_consume(KeywordColon) {
if let Some((declaration, initializer)) = parse_data_type_definition(lexer, None) {
if let Some(init) = initializer {
lexer.accept_diagnostic(
Diagnostic::new("Return types cannot have a default value, the value will be ignored")
.with_location(init.get_location())
.with_error_code("E016"),
);
}
if let DataTypeDeclaration::Definition { data_type, .. } = &declaration {
if matches!(data_type, DataType::EnumType { .. } | DataType::StructType { .. }) {
let datatype_name = declaration
.get_location()
.to_range()
.map(|range| &lexer.get_src()[range])
.expect("Expecing location to be a range during parsing");
lexer.accept_diagnostic(
////TODO: This prints a debug version of the datatype, it should have a user readable version instead
Diagnostic::new(format!(
"Data Type {datatype_name} not supported as a function return type!"
))
.with_error_code("E027")
.with_location(&declaration),
)
}
}
Some(declaration)
} else {
//missing return type
lexer.accept_diagnostic(Diagnostic::unexpected_token_found(
"Datatype",
lexer.slice(),
lexer.source_range_factory.create_range(lexer.range()),
));
None
}
} else {
None
}
}
fn parse_method(
lexer: &mut ParseSession,
parent: &str,
declaration_kind: DeclarationKind,
linkage: LinkageType,
constant: bool,
) -> Option<(Pou, Implementation)> {
parse_any_in_region(lexer, vec![KeywordEndMethod], |lexer| {
// Method declarations look like this:
// METHOD [AccessModifier] [ABSTRACT|FINAL] [OVERRIDE] [: return_type]
// ...
// END_METHOD
// constant pragma is only allowed in builtins for now
if constant {
lexer.accept_diagnostic(Diagnostic::const_pragma_is_not_allowed(
lexer.last_location().span(&lexer.location()),
));
}
let method_start = lexer.range().start;
lexer.advance(); // eat METHOD keyword
let access = Some(parse_access_modifier(lexer));
let pou_kind = PouType::Method { parent: parent.into(), property: None, declaration_kind };
let poly_mode = parse_polymorphism_mode(lexer, &pou_kind);
let overriding = lexer.try_consume(KeywordOverride);
let (name, name_location) = parse_identifier(lexer)?;
let generics = parse_generics(lexer);
let return_type = parse_return_type(lexer);
let mut variable_blocks = vec![];
while lexer.token == KeywordVar
|| lexer.token == KeywordVarInput
|| lexer.token == KeywordVarOutput
|| lexer.token == KeywordVarInOut
|| lexer.token == KeywordVarTemp
{
variable_blocks.push(parse_variable_block(lexer, LinkageType::Internal));
}
let call_name = qualified_name(parent, &name);
let implementation = parse_implementation(
lexer,
linkage,
pou_kind.clone(),
&call_name,
&call_name,
!generics.is_empty(),
name_location.clone(),
);
// parse_implementation() will default-initialize the fields it
// doesn't know. thus, we have to complete the information.
let implementation = Implementation { overriding, access, ..implementation };
let method_end = lexer.range().end;
Some((
Pou {
name: call_name,
id: lexer.next_id(),
kind: pou_kind,
variable_blocks,
return_type,
location: lexer.source_range_factory.create_range(method_start..method_end),
name_location,
poly_mode,
generics,
linkage,
super_class: None,
interfaces: Vec::new(),
properties: Vec::new(),
is_const: constant,
},
implementation,
))
})
}
fn parse_property(lexer: &mut ParseSession) -> Option<PropertyBlock> {
lexer.advance(); // Move past `PROPERTY` keyword
let mut has_error = false;
let identifier = parse_identifier(lexer);
if identifier.is_none() {
has_error = true;
lexer.accept_diagnostic(
Diagnostic::new("Property definition is missing a name").with_location(lexer.location()),
);
}
let datatype = parse_return_type(lexer);
if datatype.is_none() {
has_error = true;
lexer.accept_diagnostic(
Diagnostic::new("Property definition is missing a datatype").with_location(lexer.last_location()),
);
};
// This is kind of common, hence we parse invalid variable blocks to have useful error messages
while lexer.token.is_var() {
let block = parse_variable_block(lexer, LinkageType::Internal);
lexer.accept_diagnostic(
Diagnostic::new(
"Variable blocks may only be defined within a GET or SET block in the context of properties",
)
.with_location(&block.location)
.with_error_code("E007"),
);
}
let mut implementations = Vec::new();
while matches!(lexer.token, KeywordGet | KeywordSet) {
let location = lexer.location();
let kind = if lexer.token == KeywordGet { PropertyKind::Get } else { PropertyKind::Set };
lexer.advance(); // Move past `GET` or `SET` keyword
let mut variable_blocks = Vec::new();
while lexer.token.is_var() {
variable_blocks.push(parse_variable_block(lexer, LinkageType::Internal));
}
let statements = parse_body_in_region(
lexer,
match kind {
PropertyKind::Get => vec![Token::KeywordEndGet],
PropertyKind::Set => vec![Token::KeywordEndSet],
},
);
implementations.push(PropertyImplementation {
kind,
variable_blocks,
body: statements,
location,
end_location: lexer.last_location(),
});
}
lexer.try_consume_or_report(Token::KeywordEndProperty); // Move past `END_PROPERTY` keyword
if has_error {
return None;
};
let (name, name_location) = identifier.expect("covered above");
let datatype = datatype.expect("covered above");
Some(PropertyBlock { ident: Identifier { name, location: name_location }, datatype, implementations })
}
fn parse_access_modifier(lexer: &mut ParseSession) -> AccessModifier {
if lexer.try_consume(KeywordAccessPublic) {
AccessModifier::Public
} else if lexer.try_consume(KeywordAccessPrivate) {
AccessModifier::Private
} else if lexer.try_consume(KeywordAccessProtected) {
AccessModifier::Protected
} else if lexer.try_consume(KeywordAccessInternal) {
AccessModifier::Internal
} else {
AccessModifier::Protected
}
}
/// parse identifier and advance if successful
/// returns the identifier as a String and the SourceRange of the parsed name
fn parse_identifier(lexer: &mut ParseSession) -> Option<(String, SourceLocation)> {
let pou_name = lexer.slice().to_string();
if lexer.token == Identifier {
lexer.advance();
Some((pou_name, lexer.last_location()))
} else {
lexer.accept_diagnostic(Diagnostic::unexpected_token_found(
"Identifier",
pou_name.as_str(),
lexer.location(),
));
None
}
}
fn parse_implementation(
lexer: &mut ParseSession,
linkage: LinkageType,
pou_type: PouType,
call_name: &str,
type_name: &str,
generic: bool,
name_location: SourceLocation,
) -> Implementation {
let start = lexer.range().start;
let statements = parse_body_standalone(lexer);
let end_location = lexer.location(); //Location of the current token, which shoudl be the
//end token
Implementation {
name: call_name.into(),
type_name: type_name.into(),
linkage,
pou_type,
statements,
location: lexer.source_range_factory.create_range(start..lexer.last_range.end),
name_location,
end_location,
overriding: false,
generic,
access: None,
}
}
fn parse_action(
lexer: &mut ParseSession,
linkage: LinkageType,
container: Option<&str>,
) -> Option<Implementation> {
lexer.advance(); //Consume the Action keyword
let closing_tokens =
vec![KeywordEndAction, KeywordEndProgram, KeywordEndFunction, KeywordEndFunctionBlock];
parse_any_in_region(lexer, closing_tokens.clone(), |lexer| {
let name_or_container = lexer.slice_and_advance();
let (container, name, name_location) = if let Some(container) = container {
(container.into(), name_or_container, lexer.last_location())
} else {
let loc = lexer.last_location();
expect_token!(lexer, KeywordDot, None);
lexer.advance();
expect_token!(lexer, Identifier, None);
let name = lexer.slice_and_advance();
(name_or_container, name, loc.span(&lexer.last_location()))
};
let call_name = qualified_name(&container, &name);
let implementation = parse_implementation(
lexer,
linkage,
PouType::Action,
&call_name,
&container,
false,
name_location,
);
//lets see if we ended on the right END_ keyword
if closing_tokens.contains(&lexer.last_token) && lexer.last_token != KeywordEndAction {
lexer.accept_diagnostic(Diagnostic::unexpected_token_found(
format!("{KeywordEndAction:?}").as_str(),
lexer.slice(),
lexer.location(),
))
}
Some(implementation)
})
}
// TYPE ... END_TYPE
fn parse_type(lexer: &mut ParseSession) -> Vec<UserTypeDeclaration> {
lexer.advance(); // consume the TYPE
parse_any_in_region(lexer, vec![KeywordEndType], |lexer| {
let mut declarations = vec![];
while !lexer.closes_open_region(&lexer.token) {
let name = lexer.slice_and_advance();
let name_location = lexer.last_location();
lexer.try_consume_or_report(KeywordColon);
let result = parse_full_data_type_definition(lexer, Some(name));
if let Some((DataTypeDeclaration::Definition { data_type, .. }, initializer)) = result {
declarations.push(UserTypeDeclaration {
data_type,
initializer,
location: name_location,
scope: lexer.scope.clone(),
});
}
}
declarations
})
}
type DataTypeWithInitializer = (DataTypeDeclaration, Option<AstNode>);
fn parse_full_data_type_definition(
lexer: &mut ParseSession,
name: Option<String>,
) -> Option<DataTypeWithInitializer> {
let end_keyword = if lexer.token == KeywordStruct { KeywordEndStruct } else { KeywordSemicolon };
let parsed_datatype = parse_any_in_region(lexer, vec![end_keyword], |lexer| {
let sized = lexer.try_consume(PropertySized);
if lexer.try_consume(KeywordDotDotDot) {
Some((
DataTypeDeclaration::Definition {
data_type: DataType::VarArgs { referenced_type: None, sized },
location: lexer.last_location(),
scope: lexer.scope.clone(),
},
None,
))
} else {
parse_data_type_definition(lexer, name).map(|(type_def, initializer)| {
if lexer.try_consume(KeywordDotDotDot) {
(
DataTypeDeclaration::Definition {
data_type: DataType::VarArgs { referenced_type: Some(Box::new(type_def)), sized },
location: lexer.last_location(),
scope: lexer.scope.clone(),
},
None,
)
} else {
(type_def, initializer)
}
})
}
});
// The standard allows semicolons at the end of an `END_STRUCT` keyword, hence if we parsed
// a struct, try to also consume a semicolon if it exists
if end_keyword == KeywordEndStruct {
lexer.try_consume(KeywordSemicolon);
}
parsed_datatype
}
// TYPE xxx : 'STRUCT' | '(' | IDENTIFIER
fn parse_data_type_definition(
lexer: &mut ParseSession,
name: Option<String>,
) -> Option<DataTypeWithInitializer> {
let start = lexer.location();
if lexer.try_consume(KeywordStruct) {
// Parse struct
let variables = parse_variable_list(lexer);
Some((
DataTypeDeclaration::Definition {
data_type: DataType::StructType { name, variables },
location: start.span(&lexer.location()),
scope: lexer.scope.clone(),
},
None,
))
} else if lexer.try_consume(KeywordArray) {
parse_array_type_definition(lexer, name)
} else if lexer.try_consume(KeywordPointer) {
let start_pos = lexer.last_range.start;
//Report wrong keyword
lexer.accept_diagnostic(
Diagnostic::new("`POINTER TO` is not a standard keyword, use `REF_TO` instead")
.with_location(lexer.last_location())
.with_error_code("E015"),
);
let expect_keyword_to = |lexer: &mut ParseSession| {
expect_token!(lexer, KeywordTo, None);
Some(())
};
if expect_keyword_to(lexer).is_some() {
lexer.advance();
}
parse_pointer_definition(lexer, name, start_pos, None)
} else if lexer.try_consume(KeywordRef) {
parse_pointer_definition(lexer, name, lexer.last_range.start, None)
} else if lexer.try_consume(KeywordParensOpen) {
//enum without datatype
parse_enum_type_definition(lexer, name)
} else if lexer.token == KeywordString || lexer.token == KeywordWideString {
parse_string_type_definition(lexer, name)
} else if lexer.token == Identifier {
parse_type_reference_type_definition(lexer, name)
} else {
//no datatype?
lexer.accept_diagnostic(Diagnostic::unexpected_token_found(
"DataTypeDefinition",
format!("{:?}", lexer.token).as_str(),
lexer.location(),
));
None
}
}
fn parse_pointer_definition(
lexer: &mut ParseSession,
name: Option<String>,
start_pos: usize,
auto_deref: Option<AutoDerefType>,
) -> Option<(DataTypeDeclaration, Option<AstNode>)> {
parse_data_type_definition(lexer, None).map(|(decl, initializer)| {
(
DataTypeDeclaration::Definition {
data_type: DataType::PointerType { name, referenced_type: Box::new(decl), auto_deref },
// FIXME: this currently includes the initializer in the sourcelocation, resulting in 'REF_TO A := B' when creating a slice
location: lexer.source_range_factory.create_range(start_pos..lexer.last_range.end),
scope: lexer.scope.clone(),
},
initializer,
)
})
}
fn parse_type_reference_type_definition(
lexer: &mut ParseSession,
name: Option<String>,