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
//! Abstract syntax tree for awk programs (rules + optional user functions).
use std::collections::HashMap;
#[derive(Debug, Clone, PartialEq)]
pub struct Program {
pub rules: Vec<Rule>,
pub funcs: HashMap<String, FunctionDef>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct FunctionDef {
pub name: String,
pub params: Vec<String>,
pub body: Vec<Stmt>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Rule {
pub pattern: Pattern,
pub stmts: Vec<Stmt>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Pattern {
Begin,
End,
/// gawk-style: run before each input file (after `BEGIN`).
BeginFile,
/// gawk-style: run after each input file (before `END`).
EndFile,
Expr(Expr),
Regexp(String),
/// Inclusive range: two patterns (`/a/,/b/` or `NR==1,NR==5`).
Range(Box<Pattern>, Box<Pattern>),
Empty,
}
#[derive(Debug, Clone, PartialEq)]
pub enum Stmt {
If {
cond: Expr,
then_: Vec<Stmt>,
else_: Vec<Stmt>,
},
While {
cond: Expr,
body: Vec<Stmt>,
},
/// `do { … } while (cond)` — body runs at least once; `continue` jumps to the condition test.
DoWhile {
body: Vec<Stmt>,
cond: Expr,
},
ForC {
init: Option<Expr>,
cond: Option<Expr>,
iter: Option<Expr>,
body: Vec<Stmt>,
},
ForIn {
var: String,
arr: String,
body: Vec<Stmt>,
},
Block(Vec<Stmt>),
Expr(Expr),
/// `print` / `print expr-list` with optional `> file` or `>> file`.
Print {
args: Vec<Expr>,
redir: Option<PrintRedir>,
},
/// `printf fmt, expr-list` (statement form, like `print`) with the same redirections.
Printf {
args: Vec<Expr>,
redir: Option<PrintRedir>,
},
Break,
Continue,
Next,
/// Skip remaining records in the current input file (POSIX / gawk).
NextFile,
Exit(Option<Expr>),
Delete {
name: String,
/// `None` = delete entire array; `Some(vec)` = delete one key (possibly multidimensional).
indices: Option<Vec<Expr>>,
},
Return(Option<Expr>),
/// `getline` / `getline var` / `getline < file` / `expr | getline [var]` / …
GetLine {
/// `expr | getline` — shell command string from `expr` (via `sh -c`).
pipe_cmd: Option<Box<Expr>>,
var: Option<String>,
redir: GetlineRedir,
},
/// gawk-style `switch (expr) { case … default … }` (cases do not fall through).
Switch {
expr: Expr,
arms: Vec<SwitchArm>,
},
}
/// One arm of a `switch` statement.
#[derive(Debug, Clone, PartialEq)]
pub enum SwitchArm {
Case {
label: SwitchLabel,
stmts: Vec<Stmt>,
},
Default {
stmts: Vec<Stmt>,
},
}
/// `case` label: expression equality or regex match (`case /re/`).
#[derive(Debug, Clone, PartialEq)]
pub enum SwitchLabel {
Expr(Expr),
Regexp(String),
}
/// Output redirection on `print` / `printf` statements.
#[derive(Debug, Clone, PartialEq)]
pub enum PrintRedir {
/// Truncate on first open (same as POSIX `>`).
Overwrite(Box<Expr>),
/// Append on first open (`>>`).
Append(Box<Expr>),
/// One-way pipe: `| expr` runs `sh -c` with that string; writes go to the subprocess stdin.
Pipe(Box<Expr>),
/// Two-way pipe: `|& expr` — same shell command model; stdin and stdout are both connected.
Coproc(Box<Expr>),
}
#[derive(Debug, Clone, PartialEq)]
pub enum GetlineRedir {
/// Same stream as main input (or stdin).
Primary,
/// `getline ... < expr`
File(Box<Expr>),
/// `getline ... <& expr` — read from the stdout of the coprocess (same command string as `|&`).
Coproc(Box<Expr>),
}
#[derive(Debug, Clone, PartialEq)]
pub enum Expr {
Number(f64),
/// Decimal integer from source with no `.` — preserved as digits for **`-M`** (see [`crate::bytecode::Op::PushNumDecimalStr`]).
IntegerLiteral(String),
Str(String),
/// gawk-style regexp constant: `@/pattern/` — value type is **regexp**, not string (`typeof` is **`"regexp"`**).
RegexpLiteral(String),
Var(String),
Field(Box<Expr>),
Index {
name: String,
/// One or more indices; multiple are joined with `SUBSEP` (multidimensional arrays).
indices: Vec<Expr>,
},
Binary {
op: BinOp,
left: Box<Expr>,
right: Box<Expr>,
},
Unary {
op: UnaryOp,
expr: Box<Expr>,
},
Assign {
name: String,
op: Option<BinOp>,
rhs: Box<Expr>,
},
AssignField {
field: Box<Expr>,
op: Option<BinOp>,
rhs: Box<Expr>,
},
AssignIndex {
name: String,
indices: Vec<Expr>,
op: Option<BinOp>,
rhs: Box<Expr>,
},
Call {
name: String,
args: Vec<Expr>,
},
/// Indirect call: `@expr(args)` — `expr` must yield the function name (gawk).
IndirectCall {
callee: Box<Expr>,
args: Vec<Expr>,
},
Ternary {
cond: Box<Expr>,
then_: Box<Expr>,
else_: Box<Expr>,
},
/// `key in array` — membership test (array is a name, not an expression).
In {
key: Box<Expr>,
arr: String,
},
/// Parenthesized comma list `(e1, e2, …)` — gawk: multidimensional `in` key and lone `print` arg.
Tuple(Vec<Expr>),
/// `++` / `--` on a scalar, field, or array element (gawk-style).
IncDec {
op: IncDecOp,
target: IncDecTarget,
},
/// `getline` as an expression — yields `1` (record), `0` (EOF), or `-1` (error).
/// Same shape as [`Stmt::GetLine`]; used in `if ((getline x) > 0)` and `expr | getline`.
GetLine {
pipe_cmd: Option<Box<Expr>>,
var: Option<String>,
redir: GetlineRedir,
},
}
/// Prefix or postfix `++` / `--`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IncDecOp {
PreInc,
PostInc,
PreDec,
PostDec,
}
/// Lvalue for `++` / `--` only.
#[derive(Debug, Clone, PartialEq)]
pub enum IncDecTarget {
Var(String),
Field(Box<Expr>),
Index { name: String, indices: Vec<Expr> },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinOp {
Add,
Sub,
Mul,
Div,
Mod,
/// `^` / `**` — right-associative exponentiation (POSIX awk).
Pow,
Eq,
Ne,
Lt,
Le,
Gt,
Ge,
Match,
NotMatch,
Concat,
And,
Or,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnaryOp {
Neg,
Pos,
Not,
}
pub mod parallel;
#[cfg(test)]
mod ast_tests {
use super::*;
#[test]
fn program_empty_clone_eq() {
let p = Program {
rules: vec![],
funcs: HashMap::new(),
};
assert_eq!(p, p.clone());
}
#[test]
fn pattern_range_holds_endpoints() {
let p = Pattern::Range(
Box::new(Pattern::Regexp("a".into())),
Box::new(Pattern::Regexp("b".into())),
);
assert!(matches!(
p,
Pattern::Range(ref a, ref b)
if matches!(**a, Pattern::Regexp(ref s) if s == "a")
&& matches!(**b, Pattern::Regexp(ref s) if s == "b")
));
}
}