/
ast.rs
1891 lines (1737 loc) · 53.6 KB
/
ast.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
//! """The `ast` file contains the definitions of all KCL AST nodes
//! and operators and all AST nodes are derived from the `AST` class.
//! The main structure of a KCL program is as follows:
//!
//! ┌─────────────────────────────────────────────────────────────────┐
//! │ Program │
//! │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
//! │ │ Main Package │ │ Package1 │ │ Package2 │ │
//! │ │ ┌───────────┐ │ │ ┌───────────┐ │ │ ┌───────────┐ │ │
//! │ │ │ Module1 │ │ │ │ Module1 │ │ │ │ Module1 │ │ │
//! │ │ └───────────┘ │ │ └───────────┘ │ │ └───────────┘ │ │
//! │ │ ┌───────────┐ │ │ ┌───────────┐ │ │ ┌───────────┐ │ │
//! │ │ │ Module2 │ │ │ │ Module2 │ │ │ │ Module2 │ │ │
//! │ │ └───────────┘ │ │ └───────────┘ │ │ └───────────┘ │ │
//! │ │ ┌───────────┐ │ │ ┌───────────┐ │ │ ┌───────────┐ │ │
//! │ │ │ ... │ │ │ │ ... │ │ │ │ ... │ │ │
//! │ │ └───────────┘ │ │ └───────────┘ │ │ └───────────┘ │ │
//! │ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
//! └─────────────────────────────────────────────────────────────────┘
//! A single KCL file represents a module, which records file information,
//! package path information, and module document information, which is
//! mainly composed of all the statements in the KCL file.
//! The combination of multiple KCL files is regarded as a complete KCL
//! Program. For example, a single KCL file can be imported into KCL
//! files in other packages through statements such as import. Therefore,
//! the Program is composed of multiple modules, and each module is
//! associated with it. Corresponding to the package path.
//! :note: When the definition of any AST node is modified or the AST node
//! is added/deleted, it is necessary to modify the corresponding processing
//! in the compiler and regenerate the walker code.
//! :copyright: Copyright The KCL Authors. All rights reserved.
use serde::{ser::SerializeStruct, Deserialize, Serialize, Serializer};
use std::collections::HashMap;
use compiler_base_span::{Loc, Span};
use std::fmt::Debug;
use uuid;
use super::token;
use crate::{node_ref, pos::ContainsPos};
use kclvm_error::{diagnostic::Range, Position};
use std::cell::RefCell;
thread_local! {
static SHOULD_SERIALIZE_ID: RefCell<bool> = RefCell::new(false);
}
/// PosTuple denotes the tuple `(filename, line, column, end_line, end_column)`.
pub type PosTuple = (String, u64, u64, u64, u64);
/// Pos denotes the struct tuple `(filename, line, column, end_line, end_column)`.
#[derive(Clone)]
pub struct Pos(String, u64, u64, u64, u64);
impl From<PosTuple> for Pos {
fn from(value: PosTuple) -> Self {
Self(value.0, value.1, value.2, value.3, value.4)
}
}
impl From<Pos> for PosTuple {
fn from(val: Pos) -> Self {
(val.0, val.1, val.2, val.3, val.4)
}
}
impl From<Pos> for Range {
fn from(val: Pos) -> Self {
(
Position {
filename: val.0.clone(),
line: val.1,
column: Some(val.2),
},
Position {
filename: val.0,
line: val.3,
column: Some(val.4),
},
)
}
}
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub struct AstIndex(uuid::Uuid);
impl Serialize for AstIndex {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(&self.to_string())
}
}
impl Default for AstIndex {
fn default() -> Self {
Self(uuid::Uuid::new_v4())
}
}
impl ToString for AstIndex {
fn to_string(&self) -> String {
self.0.to_string()
}
}
/// Node is the file, line and column number information
/// that all AST nodes need to contain.
/// In fact, column and end_column are the counts of character,
/// For example, `\t` is counted as 1 character, so it is recorded as 1 here, but generally col is 4.
#[derive(Deserialize, Clone, PartialEq)]
pub struct Node<T> {
#[serde(serialize_with = "serialize_id", skip_deserializing, default)]
pub id: AstIndex,
pub node: T,
pub filename: String,
pub line: u64,
pub column: u64,
pub end_line: u64,
pub end_column: u64,
}
impl<T: Serialize> Serialize for Node<T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let should_serialize_id = SHOULD_SERIALIZE_ID.with(|f| *f.borrow());
let mut state =
serializer.serialize_struct("Node", if should_serialize_id { 7 } else { 6 })?;
if should_serialize_id {
state.serialize_field("id", &self.id)?;
}
state.serialize_field("node", &self.node)?;
state.serialize_field("filename", &self.filename)?;
state.serialize_field("line", &self.line)?;
state.serialize_field("column", &self.column)?;
state.serialize_field("end_line", &self.end_line)?;
state.serialize_field("end_column", &self.end_column)?;
state.end()
}
}
pub fn set_should_serialize_id(value: bool) {
SHOULD_SERIALIZE_ID.with(|f| {
*f.borrow_mut() = value;
});
}
impl<T: Debug> Debug for Node<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Node")
.field("node", &self.node)
.field("filename", &self.filename)
.field("line", &self.line)
.field("column", &self.column)
.field("end_line", &self.end_line)
.field("end_column", &self.end_column)
.finish()
}
}
impl<T> Node<T> {
pub fn new(
node: T,
filename: String,
line: u64,
column: u64,
end_line: u64,
end_column: u64,
) -> Self {
Self {
id: AstIndex::default(),
node,
filename,
line,
column,
end_line,
end_column,
}
}
pub fn dummy_node(node: T) -> Self {
Self {
id: AstIndex::default(),
node,
filename: "".to_string(),
line: 1,
column: 1,
end_line: 1,
end_column: 1,
}
}
pub fn node(node: T, (lo, hi): (Loc, Loc)) -> Self {
let filename = kclvm_utils::path::convert_windows_drive_letter(&format!(
"{}",
lo.file.name.prefer_remapped()
));
Self {
id: AstIndex::default(),
node,
filename,
line: lo.line as u64,
column: lo.col.0 as u64,
end_line: hi.line as u64,
end_column: hi.col.0 as u64,
}
}
pub fn node_with_pos_and_id(node: T, pos: PosTuple, id: AstIndex) -> Self {
Self {
id,
node,
filename: pos.0.clone(),
line: pos.1,
column: pos.2,
end_line: pos.3,
end_column: pos.4,
}
}
pub fn node_with_pos(node: T, pos: PosTuple) -> Self {
Self {
id: AstIndex::default(),
node,
filename: pos.0.clone(),
line: pos.1,
column: pos.2,
end_line: pos.3,
end_column: pos.4,
}
}
pub fn pos(&self) -> PosTuple {
(
self.filename.clone(),
self.line,
self.column,
self.end_line,
self.end_column,
)
}
pub fn set_pos(&mut self, pos: PosTuple) {
self.filename = pos.0.clone();
self.line = pos.1;
self.column = pos.2;
self.end_line = pos.3;
self.end_column = pos.4;
}
}
/// Spanned<T> is the span information that all AST nodes need to contain.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct Spanned<T> {
pub node: T,
#[serde(skip)]
pub span: Span,
}
impl TryInto<Node<Identifier>> for Node<Expr> {
type Error = &'static str;
fn try_into(self) -> Result<Node<Identifier>, Self::Error> {
match self.node {
Expr::Identifier(ident) => Ok(Node {
id: self.id,
node: ident,
filename: self.filename,
line: self.line,
column: self.column,
end_line: self.end_line,
end_column: self.end_column,
}),
_ => Err("invalid identifier"),
}
}
}
impl Node<Expr> {
/// Into a missing identifier.
pub fn into_missing_identifier(&self) -> Node<Identifier> {
Node {
id: self.id.clone(),
node: Identifier {
names: vec![],
pkgpath: String::new(),
ctx: ExprContext::Load,
},
filename: self.filename.clone(),
line: self.line,
column: self.column,
end_line: self.end_line,
end_column: self.end_column,
}
}
}
impl TryInto<Node<SchemaExpr>> for Node<Expr> {
type Error = &'static str;
fn try_into(self) -> Result<Node<SchemaExpr>, Self::Error> {
match self.node {
Expr::Schema(schema_expr) => Ok(Node {
id: self.id,
node: schema_expr,
filename: self.filename,
line: self.line,
column: self.column,
end_line: self.end_line,
end_column: self.end_column,
}),
_ => Err("invalid schema expr"),
}
}
}
/// NodeRef<T> is the Box reference of Node<T> with the
/// AST node type T
pub type NodeRef<T> = Box<Node<T>>;
/// KCL command line argument spec, e.g. `kcl main.k -E pkg_name=pkg_path`
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct CmdExternalPkgSpec {
pub pkg_name: String,
pub pkg_path: String,
}
/// KCL command line argument spec, e.g. `kcl main.k -D name=value`
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct CmdArgSpec {
pub name: String,
pub value: String,
}
/// KCL command line override spec, e.g. `kcl main.k -O pkgpath:path.to.field=field_value`
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct OverrideSpec {
pub pkgpath: String,
pub field_path: String,
pub field_value: String,
pub action: OverrideAction,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub enum OverrideAction {
Delete,
#[serde(other)]
CreateOrUpdate,
}
/// KCL API symbol selector Spec, eg: `pkgpath:path.to.field`
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct SymbolSelectorSpec {
pub pkg_root: String,
pub pkgpath: String,
pub field_path: String,
}
/// Program is the AST collection of all files of the running KCL program.
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq)]
pub struct Program {
pub root: String,
pub pkgs: HashMap<String, Vec<Module>>,
}
impl Program {
/// Get main entry files.
pub fn get_main_files(&self) -> Vec<String> {
match self.pkgs.get(crate::MAIN_PKG) {
Some(modules) => modules.iter().map(|m| m.filename.clone()).collect(),
None => vec![],
}
}
/// Get the first module in the main package.
pub fn get_main_package_first_module(&self) -> Option<&Module> {
match self.pkgs.get(crate::MAIN_PKG) {
Some(modules) => modules.first(),
None => None,
}
}
/// Get stmt on position
pub fn pos_to_stmt(&self, pos: &Position) -> Option<Node<Stmt>> {
for (_, v) in &self.pkgs {
for m in v {
if m.filename == pos.filename {
return m.pos_to_stmt(pos);
}
}
}
None
}
}
/// Module is an abstract syntax tree for a single KCL file.
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq)]
pub struct Module {
pub filename: String,
pub pkg: String,
pub doc: Option<NodeRef<String>>,
pub name: String,
pub body: Vec<NodeRef<Stmt>>,
pub comments: Vec<NodeRef<Comment>>,
}
impl Module {
/// Get all ast.schema_stmts from ast.module and return it in a Vec.
pub fn filter_schema_stmt_from_module(&self) -> Vec<NodeRef<SchemaStmt>> {
let mut stmts = Vec::new();
for stmt in &self.body {
if let Stmt::Schema(schema_stmt) = &stmt.node {
stmts.push(node_ref!(schema_stmt.clone(), stmt.pos()));
}
}
stmts
}
/// Get stmt on position
pub fn pos_to_stmt(&self, pos: &Position) -> Option<Node<Stmt>> {
for stmt in &self.body {
if stmt.contains_pos(pos) {
return Some(*stmt.clone());
}
}
None
}
}
/*
* Stmt
*/
/// A statement
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(tag = "type")]
pub enum Stmt {
TypeAlias(TypeAliasStmt),
Expr(ExprStmt),
Unification(UnificationStmt),
Assign(AssignStmt),
AugAssign(AugAssignStmt),
Assert(AssertStmt),
If(IfStmt),
Import(ImportStmt),
SchemaAttr(SchemaAttr),
Schema(SchemaStmt),
Rule(RuleStmt),
}
/// TypeAliasStmt represents a type alias statement, e.g.
/// ```kcl
/// type StrOrInt = str | int
/// ```
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct TypeAliasStmt {
pub type_name: NodeRef<Identifier>,
pub type_value: NodeRef<String>,
pub ty: NodeRef<Type>,
}
/// ExprStmt represents a expression statement, e.g.
/// ```kcl
/// 1
/// """A long string"""
/// ```
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct ExprStmt {
pub exprs: Vec<NodeRef<Expr>>,
}
/// UnificationStmt represents a declare statement with the union operator, e.g.
/// ```kcl
/// data: ASchema {}
/// ```
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct UnificationStmt {
pub target: NodeRef<Identifier>,
pub value: NodeRef<SchemaExpr>,
}
/// AssignStmt represents an assignment, e.g.
/// ```kcl
/// a: int = 1
/// ```
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct AssignStmt {
pub targets: Vec<NodeRef<Identifier>>,
pub value: NodeRef<Expr>,
pub ty: Option<NodeRef<Type>>,
}
/// AugAssignStmt represents an argument assignment, e.g.
/// ```kcl
/// a += 1
/// ```
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct AugAssignStmt {
pub target: NodeRef<Identifier>,
pub value: NodeRef<Expr>,
pub op: AugOp,
}
/// AssertStmt represents an assert statement, e.g.
/// ```kcl
/// assert True if condition, "Assert failed message"
/// ```
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct AssertStmt {
pub test: NodeRef<Expr>,
pub if_cond: Option<NodeRef<Expr>>,
pub msg: Option<NodeRef<Expr>>,
}
/// IfStmt, e.g.
/// ```kcl
/// if condition1:
/// if condition2:
/// a = 1
/// elif condition3:
/// b = 2
/// else:
/// c = 3
/// ```
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct IfStmt {
pub body: Vec<NodeRef<Stmt>>,
pub cond: NodeRef<Expr>,
pub orelse: Vec<NodeRef<Stmt>>,
}
/// ImportStmt, e.g.
/// ```kcl
/// import pkg as pkg_alias
/// ```
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct ImportStmt {
/// `path` is the import path, if 'import a.b.c' in kcl, `path` is a.b.c
pub path: Node<String>,
pub rawpath: String,
pub name: String,
pub asname: Option<Node<String>>,
/// `pkg_name` means the name of the package that the current import statement indexs to.
///
/// 1. If the current import statement indexs to the kcl plugins, kcl builtin methods or the internal kcl packages,
/// `pkg_name` is `__main__`
///
/// 2. If the current import statement indexs to the external kcl packages, `pkg_name` is the name of the package.
/// if `import k8s.example.apps`, `k8s` is another kcl package, `pkg_name` is `k8s`.
pub pkg_name: String,
}
/// SchemaStmt, e.g.
/// ```kcl
/// schema BaseSchema:
///
/// schema SchemaExample(BaseSchema)[arg: str]:
/// """Schema documents"""
/// attr?: str = arg
/// check:
/// len(attr) > 3 if attr, "Check failed message"
///
/// mixin MixinExample for ProtocolExample:
/// attr: int
///
/// protocol ProtocolExample:
/// attr: int
/// ```
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct SchemaStmt {
pub doc: Option<NodeRef<String>>,
pub name: NodeRef<String>,
pub parent_name: Option<NodeRef<Identifier>>,
pub for_host_name: Option<NodeRef<Identifier>>,
pub is_mixin: bool,
pub is_protocol: bool,
pub args: Option<NodeRef<Arguments>>,
pub mixins: Vec<NodeRef<Identifier>>,
pub body: Vec<NodeRef<Stmt>>,
pub decorators: Vec<NodeRef<CallExpr>>,
pub checks: Vec<NodeRef<CheckExpr>>,
pub index_signature: Option<NodeRef<SchemaIndexSignature>>,
}
impl SchemaStmt {
/// Get schema full attribute list (line, column, name) including
/// un-exported attributes.
pub fn get_left_identifier_list(&self) -> Vec<(u64, u64, String)> {
let mut attr_list: Vec<(u64, u64, String)> = vec![];
fn loop_body(body: &[NodeRef<Stmt>], attr_list: &mut Vec<(u64, u64, String)>) {
for stmt in body {
match &stmt.node {
Stmt::Unification(unification_stmt)
if !unification_stmt.target.node.names.is_empty() =>
{
attr_list.push((
unification_stmt.target.line,
unification_stmt.target.column,
unification_stmt.target.node.names[0].node.to_string(),
));
}
Stmt::Assign(assign_stmt) => {
for target in &assign_stmt.targets {
if !target.node.names.is_empty() {
attr_list.push((
target.line,
target.column,
target.node.names[0].node.to_string(),
));
}
}
}
Stmt::AugAssign(aug_assign_stmt) => {
if !aug_assign_stmt.target.node.names.is_empty() {
attr_list.push((
aug_assign_stmt.target.line,
aug_assign_stmt.target.column,
aug_assign_stmt.target.node.names[0].node.to_string(),
));
}
}
Stmt::If(if_stmt) => {
loop_body(&if_stmt.body, attr_list);
loop_body(&if_stmt.orelse, attr_list);
}
Stmt::SchemaAttr(schema_attr) => {
attr_list.push((
schema_attr.name.line,
schema_attr.name.column,
schema_attr.name.node.to_string(),
));
}
_ => {}
}
}
}
loop_body(&self.body, &mut attr_list);
attr_list
}
/// Whether the schema contains only attribute definitions.
pub fn has_only_attribute_definitions(&self) -> bool {
self.args.is_none()
&& self.mixins.is_empty()
&& self.checks.is_empty()
&& self
.body
.iter()
.all(|stmt| matches!(stmt.node, Stmt::SchemaAttr(_)))
}
}
/// SchemaIndexSignature, e.g.
/// ```kcl
/// schema SchemaIndexSignatureExample:
/// [str]: int
/// ```
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct SchemaIndexSignature {
pub key_name: Option<String>,
pub value: Option<NodeRef<Expr>>,
pub any_other: bool,
pub key_ty: NodeRef<Type>,
pub value_ty: NodeRef<Type>,
}
/// SchemaAttr, e.g.
/// ```kcl
/// schema SchemaAttrExample:
/// x: int
/// y: str
/// ```
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct SchemaAttr {
pub doc: String,
pub name: NodeRef<String>,
pub op: Option<AugOp>,
pub value: Option<NodeRef<Expr>>,
pub is_optional: bool,
pub decorators: Vec<NodeRef<CallExpr>>,
pub ty: NodeRef<Type>,
}
impl SchemaAttr {
#[inline]
pub fn is_ident_attr(&self) -> bool {
self.name.end_column - self.name.column <= self.name.node.chars().count() as u64
}
}
/// RuleStmt, e.g.
/// ```kcl
/// rule RuleExample:
/// a > 1
/// b < 0
/// ```
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct RuleStmt {
pub doc: Option<NodeRef<String>>,
pub name: NodeRef<String>,
pub parent_rules: Vec<NodeRef<Identifier>>,
pub decorators: Vec<NodeRef<CallExpr>>,
pub checks: Vec<NodeRef<CheckExpr>>,
pub args: Option<NodeRef<Arguments>>,
pub for_host_name: Option<NodeRef<Identifier>>,
}
/// A expression
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[serde(tag = "type")]
pub enum Expr {
Identifier(Identifier),
Unary(UnaryExpr),
Binary(BinaryExpr),
If(IfExpr),
Selector(SelectorExpr),
Call(CallExpr),
Paren(ParenExpr),
Quant(QuantExpr),
List(ListExpr),
ListIfItem(ListIfItemExpr),
ListComp(ListComp),
Starred(StarredExpr),
DictComp(DictComp),
ConfigIfEntry(ConfigIfEntryExpr),
CompClause(CompClause),
Schema(SchemaExpr),
Config(ConfigExpr),
Check(CheckExpr),
Lambda(LambdaExpr),
Subscript(Subscript),
Keyword(Keyword),
Arguments(Arguments),
Compare(Compare),
NumberLit(NumberLit),
StringLit(StringLit),
NameConstantLit(NameConstantLit),
JoinedString(JoinedString),
FormattedValue(FormattedValue),
/// A place holder for expression parse error.
Missing(MissingExpr),
}
impl Expr {
pub fn get_expr_name(&self) -> String {
match self {
Expr::Identifier(_) => "IdentifierExpression",
Expr::Unary(_) => "UnaryExpression",
Expr::Binary(_) => "BinaryExpression",
Expr::If(_) => "IfExpression",
Expr::Selector(_) => "SelectorExpression",
Expr::Call(_) => "CallExpression",
Expr::Paren(_) => "ParenExpression",
Expr::Quant(_) => "QuantExpression",
Expr::List(_) => "ListExpression",
Expr::ListIfItem(_) => "ListIfItemExpression",
Expr::ListComp(_) => "ListCompExpression",
Expr::Starred(_) => "StarredExpression",
Expr::DictComp(_) => "DictCompExpression",
Expr::ConfigIfEntry(_) => "ConfigIfEntryExpression",
Expr::CompClause(_) => "CompClauseExpression",
Expr::Schema(_) => "SchemaExpression",
Expr::Config(_) => "ConfigExpression",
Expr::Check(_) => "CheckExpression",
Expr::Lambda(_) => "LambdaExpression",
Expr::Subscript(_) => "SubscriptExpression",
Expr::Keyword(_) => "KeywordExpression",
Expr::Arguments(_) => "ArgumentsExpression",
Expr::Compare(_) => "CompareExpression",
Expr::NumberLit(_) => "NumberLitExpression",
Expr::StringLit(_) => "StringLitExpression",
Expr::NameConstantLit(_) => "NameConstantLitExpression",
Expr::JoinedString(_) => "JoinedStringExpression",
Expr::FormattedValue(_) => "FormattedValueExpression",
Expr::Missing(_) => "MissingExpression",
}
.to_string()
}
}
/// Identifier, e.g.
/// ```kcl
/// a
/// b
/// _c
/// pkg.a
/// ```
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct Identifier {
pub names: Vec<Node<String>>,
pub pkgpath: String,
pub ctx: ExprContext,
}
impl Identifier {
pub fn get_name(&self) -> String {
self.get_names().join(".")
}
pub fn get_names(&self) -> Vec<String> {
self.names
.iter()
.map(|node| node.node.clone())
.collect::<Vec<String>>()
}
}
/// UnaryExpr, e.g.
/// ```kcl
/// +1
/// -2
/// ~3
/// not True
/// ```
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct UnaryExpr {
pub op: UnaryOp,
pub operand: NodeRef<Expr>,
}
/// BinaryExpr, e.g.
/// ```kcl
/// 1 + 1
/// 3 - 2
/// 5 / 2
/// a is None
/// ```
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct BinaryExpr {
pub left: NodeRef<Expr>,
pub op: BinOp,
pub right: NodeRef<Expr>,
}
/// IfExpr, e.g.
/// ```kcl
/// 1 if condition else 2
/// ```
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct IfExpr {
pub body: NodeRef<Expr>,
pub cond: NodeRef<Expr>,
pub orelse: NodeRef<Expr>,
}
/// SelectorExpr, e.g.
/// ```kcl
/// x.y
/// x?.y
/// ```
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct SelectorExpr {
pub value: NodeRef<Expr>,
pub attr: NodeRef<Identifier>,
pub ctx: ExprContext,
pub has_question: bool,
}
/// CallExpr, e.g.
/// ```kcl
/// func1()
/// func2(1)
/// func3(x=2)
/// ```
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct CallExpr {
pub func: NodeRef<Expr>,
pub args: Vec<NodeRef<Expr>>,
pub keywords: Vec<NodeRef<Keyword>>,
}
/// ParenExpr, e.g.
/// ```kcl
/// 1 + (2 - 3)
/// ```
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct ParenExpr {
pub expr: NodeRef<Expr>,
}
/// QuantExpr, <op> <variables> in <target> {<test> <if_cond>} e.g.
/// ```kcl
/// all x in collection {x > 0}
/// any y in collection {y < 0}
/// map x in collection {x + 1}
/// filter x in collection {x > 1}
/// ```
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct QuantExpr {
pub target: NodeRef<Expr>,
pub variables: Vec<NodeRef<Identifier>>,
pub op: QuantOperation,
pub test: NodeRef<Expr>,
pub if_cond: Option<NodeRef<Expr>>,
pub ctx: ExprContext,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub enum QuantOperation {
All,
Any,
Filter,
Map,
}
impl From<QuantOperation> for String {
fn from(val: QuantOperation) -> Self {
let s = match val {
QuantOperation::All => "all",
QuantOperation::Any => "any",
QuantOperation::Filter => "filter",
QuantOperation::Map => "map",
};
s.to_string()
}
}
/// ListExpr, e.g.
/// ```kcl
/// [1, 2, 3]
/// ```
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct ListExpr {
pub elts: Vec<NodeRef<Expr>>,
pub ctx: ExprContext,
}
/// ListIfItemExpr, e.g.
/// ```kcl
/// [1, if condition: 2, 3]
/// ```
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct ListIfItemExpr {
pub if_cond: NodeRef<Expr>,
pub exprs: Vec<NodeRef<Expr>>,
pub orelse: Option<NodeRef<Expr>>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub enum CompType {
List,
Dict,
}
/// ListComp, e.g.
/// ```kcl
/// [x ** 2 for x in [1, 2, 3]]
/// ```
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct ListComp {
pub elt: NodeRef<Expr>,
pub generators: Vec<NodeRef<CompClause>>,
}
/// StarredExpr, e.g.
/// ```kcl
/// [1, 2, *[3, 4]]
/// ```
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct StarredExpr {
pub value: NodeRef<Expr>,
pub ctx: ExprContext,
}
/// DictComp, e.g.
/// ```kcl
/// {k: v + 1 for k, v in {k1 = 1, k2 = 2}}
/// ```
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct DictComp {
pub entry: ConfigEntry,
pub generators: Vec<NodeRef<CompClause>>,
}
/// ConfigIfEntryExpr, e.g.
/// ```kcl
/// {
/// k1 = 1
/// if condition:
/// k2 = 2
/// }
/// ```
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct ConfigIfEntryExpr {
pub if_cond: NodeRef<Expr>,
pub items: Vec<NodeRef<ConfigEntry>>,
pub orelse: Option<NodeRef<Expr>>,
}
/// CompClause, e.g.
/// ```kcl
/// i, a in [1, 2, 3] if i > 1 and a > 1
/// ```