forked from tjdevries/vim9jit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
1959 lines (1729 loc) · 62.1 KB
/
lib.rs
File metadata and controls
1959 lines (1729 loc) · 62.1 KB
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
use std::{collections::HashMap, fmt::Write as _, path::Path};
use lexer::Lexer;
use parser::{
self, new_parser, ArrayLiteral, AssignStatement, AugroupCommand, AutocmdCommand, Body,
BreakCommand, CallCommand, CallExpression, ContinueCommand, DeclCommand, DefCommand,
DeferCommand, DictAccess, DictLiteral, EchoCommand, ElseCommand, ElseIfCommand, ExCommand,
ExecuteCommand, Expandable, ExportCommand, Expression, ForCommand, GroupedExpression, Heredoc,
Identifier, IfCommand, ImportCommand, IndexExpression, IndexType, InfixExpression, Lambda,
Literal, MethodCall, MutationStatement, Operator, PrefixExpression, Program, RawIdentifier,
Register, ReturnCommand, ScopedIdentifier, SharedCommand, Signature, StatementCommand, Ternary,
TryCommand, Type, UnpackIdentifier, UserCommand, VarCommand, Vim9ScriptCommand, VimBoolean,
VimKey, VimNumber, VimOption, VimScope, VimString, WhileCommand,
};
pub mod call_expr;
mod test_harness;
pub type GenResult = Result<(), std::fmt::Error>;
#[derive(Debug, PartialEq)]
pub enum ParserMode {
Test,
Autoload { prefix: String },
Standalone,
}
#[derive(Debug)]
pub struct ParserOpts {
pub mode: ParserMode,
}
#[derive(Debug)]
pub struct Output {
pub lua: String,
pub vim: String,
}
// Writing related impls
impl Output {
pub fn new() -> Self {
Self {
lua: String::new(),
vim: String::new(),
}
}
pub fn write(&mut self, generator: impl Generate, state: &mut State) {
match state.opts.mode {
ParserMode::Standalone => generator.write_default(state, self),
ParserMode::Test => generator.write_test(state, self),
ParserMode::Autoload { .. } => generator.write_autoload(state, self),
}
}
pub fn write_lua(&mut self, contents: &str) {
let _ = write!(self.lua, "{contents}");
}
pub fn write_vim(&mut self, contents: &str) {
let _ = write!(self.vim, "{contents}");
}
}
impl Default for Output {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug)]
pub struct State {
pub opts: ParserOpts,
pub command_depth: i32,
pub method_depth: i32,
// TODO: Consider moving augroup -> scopes
// with a new scope type of augroup.
//
// That might be a nicer strategy (and mirrors
// the same thing as we've done before).
pub augroup: Option<Literal>,
// TODO: We could modify the state as we are generating code.
// As we generate the code and notice certain identifiers are certain
// types, we can use that to do *some* optimizations
pub scopes: Vec<Scope>,
}
impl State {
fn is_top_level(&self) -> bool {
self.scopes.len() == 1
}
pub fn push_defer(&mut self) {
let s = self
.scopes
.iter_mut()
.rev()
.find(|s| s.kind == ScopeKind::Function)
.unwrap();
s.deferred += 1
}
pub fn find_relevant_scope<F>(&self, filter: F) -> Option<&Scope>
where
F: Fn(&&Scope) -> bool,
{
self.scopes.iter().rev().find(filter)
}
fn with_scope<F, T>(&mut self, kind: ScopeKind, f: F) -> (T, Scope)
where
F: Fn(&mut State) -> T,
{
self.scopes.push(Scope::new(kind));
let res = f(self);
(res, self.scopes.pop().expect("balanced scopes"))
}
fn push_declaration(&mut self, expr_1: &Expression, expr_2: Type) -> Type {
self.scopes
.last_mut()
.unwrap()
.push_declaration(expr_1, expr_2)
}
#[allow(unused)]
fn lookup_declaration(&self, expr_1: &Expression) -> Option<Type> {
match Scope::declaration_key(expr_1) {
Some(key) => self
.scopes
.iter()
.rev()
.find_map(|s| s.declarations.get(&key).cloned()),
None => None,
}
}
}
macro_rules! find_scope {
($state:ident, $m:pat) => {{
use ScopeKind::*;
let scope = $state.find_relevant_scope(|s| matches!(s.kind, $m));
match scope {
Some(scope) => scope,
None => panic!("Unexpected failure to find scope: {:#?}", $state),
}
}};
}
macro_rules! scope_or_empty {
($state:ident, $m:pat) => {{
use ScopeKind::*;
let scope = $state.find_relevant_scope(|s| matches!(s.kind, $m));
match scope {
Some(scope) => scope,
None => &$state.scopes[0],
}
}};
}
#[derive(PartialEq, Eq, Debug, Default)]
pub enum ScopeKind {
#[default]
TopLevel,
Function,
While {
has_continue: bool,
},
For {
has_continue: bool,
},
If,
}
#[derive(Debug, Default)]
pub struct Scope {
kind: ScopeKind,
deferred: usize,
declarations: HashMap<String, Type>,
}
impl Scope {
pub fn new(kind: ScopeKind) -> Self {
Self {
kind,
..Default::default()
}
}
/// Whether the current scope contains any unique behavior for embedded continues
pub fn has_continue(&self) -> bool {
match self.kind {
ScopeKind::While { has_continue } => has_continue,
ScopeKind::For { has_continue } => has_continue,
_ => false,
}
}
pub fn declaration_key(expr: &Expression) -> Option<String> {
match expr {
Expression::Identifier(ident) => match &ident {
Identifier::Raw(raw) => Some(raw.name.clone()),
Identifier::Scope(_) => None,
Identifier::Unpacked(_) => None,
Identifier::Ellipsis => None,
},
_ => None,
}
}
pub fn push_declaration(&mut self, expr: &Expression, ty: Type) -> Type {
let key = match Self::declaration_key(expr) {
Some(key) => key,
None => return ty,
};
self.declarations.insert(key, ty.clone());
ty
}
}
pub trait Generate {
fn write(&self, state: &mut State, output: &mut Output) {
match state.opts.mode {
ParserMode::Standalone => self.write_default(state, output),
ParserMode::Test => self.write_test(state, output),
ParserMode::Autoload { .. } => self.write_autoload(state, output),
}
}
fn write_default(&self, state: &mut State, output: &mut Output);
fn write_test(&self, state: &mut State, output: &mut Output) {
self.write_default(state, output)
}
fn write_autoload(&self, state: &mut State, output: &mut Output) {
self.write_default(state, output)
}
fn gen(&self, state: &mut State) -> String {
let mut output = Output::new();
self.write(state, &mut output);
output.lua
}
}
impl Generate for ExCommand {
fn write_default(&self, state: &mut State, output: &mut Output) {
match self {
ExCommand::NoOp(token) => {
if !token.kind.is_whitespace() {
output.write_lua(&format!("\n-- {token:?}"))
}
}
ExCommand::Comment(token) => output.write_lua(&format!("-- {}", token.text)),
ExCommand::Finish(_) => output.write_lua("return M"),
ExCommand::Vim9Script(cmd) => cmd.write(state, output),
ExCommand::Var(cmd) => cmd.write(state, output),
ExCommand::Echo(cmd) => cmd.write(state, output),
ExCommand::Statement(cmd) => cmd.write(state, output),
ExCommand::Return(cmd) => cmd.write(state, output),
ExCommand::Def(cmd) => cmd.write(state, output),
ExCommand::If(cmd) => cmd.write(state, output),
ExCommand::Augroup(cmd) => cmd.write(state, output),
ExCommand::Autocmd(cmd) => cmd.write(state, output),
ExCommand::Call(cmd) => cmd.write(state, output),
ExCommand::Decl(cmd) => cmd.write(state, output),
ExCommand::Heredoc(heredoc) => heredoc.write(state, output),
ExCommand::UserCommand(usercmd) => usercmd.write(state, output),
ExCommand::SharedCommand(shared) => shared.write(state, output),
ExCommand::ExportCommand(export) => export.write(state, output),
ExCommand::ImportCommand(import) => import.write(state, output),
ExCommand::For(f) => f.write(state, output),
ExCommand::Try(t) => t.write(state, output),
ExCommand::While(w) => w.write(state, output),
ExCommand::Break(b) => b.write(state, output),
ExCommand::Continue(c) => c.write(state, output),
ExCommand::Defer(defer) => defer.write(state, output),
ExCommand::Execute(exec) => exec.write(state, output),
ExCommand::Eval(eval) => output.write_lua(&format!("{};", eval.expr.gen(state))),
_ => todo!("Have not yet handled: {:?}", self),
}
}
}
impl Generate for DeferCommand {
fn write_default(&self, state: &mut State, output: &mut Output) {
state.push_defer();
let mut temp = Output::new();
self.call.write(state, &mut temp);
let expr = self.call.gen(state);
output.write_lua(&format!(
"table.insert(nvim9_deferred, 1, function() {expr} end)"
))
}
}
impl Generate for ContinueCommand {
fn write_default(&self, state: &mut State, output: &mut Output) {
let scope = find_scope!(state, Function | While { .. } | For { .. });
assert!(scope.kind != ScopeKind::Function, "continue: While/For");
assert!(scope.has_continue(), "must have continue...");
output.write_lua("return vim9.ITER_CONTINUE")
}
}
impl Generate for BreakCommand {
fn write_default(&self, state: &mut State, output: &mut Output) {
let scope = find_scope!(state, Function | While { .. } | For { .. });
assert!(
scope.kind != ScopeKind::Function,
"continue: While/For {self:#?} // {scope:?}"
);
if scope.has_continue() {
output.write_lua("return vim9.ITER_BREAK")
} else {
output.write_lua("break")
}
}
}
impl Generate for WhileCommand {
fn write_default(&self, state: &mut State, output: &mut Output) {
let has_continue = continue_exists_in_scope(&self.body);
let (body, _) = state.with_scope(ScopeKind::While { has_continue }, |s| self.body.gen(s));
if has_continue {
// let condition = self.condition.gen(state);
let condition = self.condition.gen(state);
return output.write_lua(&format!(
r#"
local body = function()
{body}
return 0
end
while {condition} do
local nvim9_status, nvim9_ret = body()
if nvim9_status == 2 then
break
elseif nvim9_status == 3 then
return nvim9_ret
end
end
"#,
));
}
// output.write_lua(&format!(
// "while {}\ndo\n{}\nend",
// self.condition.gen(state),
// body
// ))
output.write_lua("while ");
output.write_lua(&self.condition.gen(state));
output.write_lua(&format!("\ndo\n{body}\nend"));
}
}
impl Generate for TryCommand {
fn write_default(&self, state: &mut State, output: &mut Output) {
// TODO: try and catch LUL
// self.body.gen(state)
output.write(&self.body, state)
}
}
fn continue_exists_in_scope(body: &Body) -> bool {
body.commands.iter().any(|c| match c {
ExCommand::If(ex) => continue_exists_in_scope(&ex.body),
ExCommand::Continue(_) => true,
_ => false,
})
}
impl Generate for ForCommand {
// 0 => nothing
// 1 => continue
// 2 => break
// 3 => return
fn write_default(&self, state: &mut State, output: &mut Output) {
let has_continue = continue_exists_in_scope(&self.body);
let (body, _) = state.with_scope(ScopeKind::For { has_continue }, |s| self.body.gen(s));
let expr = &self.for_expr.gen(state);
let (ident, unpacked) = match &self.for_identifier {
Identifier::Unpacked(unpacked) => (
"__unpack_result".to_string(),
format!(
"local {} = unpack(__unpack_result)",
identifier_list(state, unpacked)
),
),
_ => (self.for_identifier.gen(state), "".to_string()),
};
let result = if has_continue {
format!(
r#"
local body = function(_, {ident})
{unpacked}
{body}
return vim9.ITER_DEFAULT
end
for _, {ident} in vim9.iter({expr}) do
{unpacked}
local nvim9_status, nvim9_ret = body(_, {ident})
if nvim9_status == vim9.ITER_BREAK then
break
elseif nvim9_status == vim9.ITER_RETURN then
return nvim9_ret
end
end
"#
)
} else {
format!(
r#"
for _, {ident} in vim9.iter({expr}) do
{body}
end
"#,
)
};
output.write_lua(&result);
}
}
impl Generate for ImportCommand {
fn write_default(&self, state: &mut State, output: &mut Output) {
output.write_lua(&match self {
ImportCommand::ImportImplicit {
file,
name,
autoload,
..
} => match name {
Some(name) => {
let var = name.gen(state);
format!(
"local {var} = vim9.import({{ name = {file:?}, autoload = {autoload} }})"
)
}
None => {
let filepath = Path::new(file);
let stem = filepath.file_stem().unwrap().to_str().unwrap();
format!(
"local {stem} = vim9.import({{ name = {file:?}, autoload = {autoload} }})"
)
}
},
ImportCommand::ImportUnpacked { names, file, .. } => names
.iter()
.map(|name| {
let name = name.gen(state);
format!("local {name} = vim9.import({{ name = {file:?} }})['{name}']")
})
.collect::<Vec<String>>()
.join("\n"),
})
}
}
impl Generate for ExportCommand {
fn write_default(&self, state: &mut State, output: &mut Output) {
let exported = self.command.gen(state);
let ident = match self.command.as_ref() {
ExCommand::Var(var) => var.name.gen(state),
ExCommand::Def(def) => def.name.gen(state),
// ExCommand::Heredoc(_) => todo!(),
// ExCommand::Decl(_) => todo!(),
_ => {
unreachable!("not a valid export command: {:#?}", self.command)
}
};
output.write_lua(&format!("{exported};\nM['{ident}'] = {ident};"))
}
fn write_autoload(&self, state: &mut State, output: &mut Output) {
// Write the default output for a file
self.write_default(state, output);
let prefix = match &state.opts.mode {
ParserMode::Autoload { prefix } => prefix.clone(),
_ => unreachable!("not in autoload mode"),
};
match self.command.as_ref() {
ExCommand::Def(def) => {
let name = def.name.gen(state);
let sig = def
.args
.params
.iter()
.map(|p| p.name.gen(state))
.collect::<Vec<String>>()
.join(", ");
let call = def
.args
.params
.iter()
.map(|p| "a:".to_string() + &p.name.gen(state))
.collect::<Vec<String>>()
.join(", ");
output.write_vim(&format!(
r#"
function! {prefix}#{name}({sig}) abort
return s:nvim_module.{name}({call})
endfunction
"#
))
}
_ => unreachable!("not a valid export command: {:#?}", self.command),
}
}
}
impl Generate for SharedCommand {
fn write_default(&self, _: &mut State, output: &mut Output) {
// Temp
output.write_lua(&format!("pcall(vim.cmd, [[ {} ]])", self.contents.trim()))
}
}
fn make_user_command_arg(state: &State) -> String {
format!("__vim9_arg_{}", state.command_depth)
}
fn to_str_or_nil(s: &Option<String>) -> String {
if let Some(complete) = s {
format!("'{complete}'")
} else {
"nil".to_string()
}
}
impl Generate for UserCommand {
fn write_default(&self, state: &mut State, output: &mut Output) {
state.command_depth += 1;
let complete = to_str_or_nil(&self.command_complete);
let nargs = match &self.command_nargs {
Some(nargs) => match nargs.as_str() {
"0" => "0".to_string(),
"1" => "1".to_string(),
_ => format!("'{nargs}'"),
},
None => "nil".to_string(),
};
let result = format!(
r#"
vim.api.nvim_create_user_command(
"{}",
function({})
{}
end,
{{
bang = {},
nargs = {nargs},
complete = {complete},
}}
)"#,
self.name,
make_user_command_arg(state),
self.command.gen(state),
self.command_bang,
);
state.command_depth -= 1;
output.write_lua(&result)
}
}
fn get_local(state: &State, name: &Identifier) -> String {
if state.is_top_level() || !name.is_valid_local() {
""
} else {
"local"
}
.to_string()
}
impl Generate for DeclCommand {
fn write_default(&self, state: &mut State, output: &mut Output) {
let local = get_local(state, &self.name);
// TODO: default value should not be nil for everything here
// i think?
output.write_lua(&format!(
"{local} {} = {}",
self.name.gen(state),
match &self.ty {
Some(ty) => match ty {
Type::Any => "0",
Type::Bool => "false",
Type::BoolOrNumber => "false",
Type::Number => "0",
Type::Float => "0",
Type::String => "''",
Type::List { .. } => "{}",
Type::Dict { .. } => "vim.empty_dict()",
Type::Job => todo!(),
Type::Channel => todo!(),
Type::Void => "nil",
Type::Func(_) => "function() end",
Type::Blob => unreachable!(),
},
None => "nil",
}
))
}
}
impl Generate for Heredoc {
fn write_default(&self, state: &mut State, output: &mut Output) {
// this works for non-trim and non-eval heredocs perfect
let inner = self
.contents
.iter()
.map(|line| format!("[==[{line}]==]"))
.collect::<Vec<String>>()
.join(", ");
let mut list = format!("{{ {inner} }}");
if self.trim {
list = format!("vim9.heredoc.trim({list})")
}
output.write_lua(&format!("local {} = {}", self.name.gen(state), list))
}
}
impl Generate for CallCommand {
fn write_default(&self, state: &mut State, output: &mut Output) {
let call: CallExpression = self.into();
output.write(call, state);
output.write_lua(";");
}
}
impl Generate for AugroupCommand {
fn write_default(&self, state: &mut State, output: &mut Output) {
state.augroup = Some(self.augroup_name.clone());
let group = self.augroup_name.token.text.clone();
let result = format!(
r#"
vim.api.nvim_create_augroup("{}", {{ clear = false }})
{}
"#,
group,
self.body.gen(state)
);
state.augroup = None;
output.write_lua(&result)
}
}
impl Generate for AutocmdCommand {
fn write_default(&self, state: &mut State, output: &mut Output) {
let group = match &state.augroup {
Some(group) => format!("group = '{}',", group.token.text),
None => "".to_string(),
};
let event_list = self
.events
.iter()
.map(|e| format!("'{}'", e.token.text))
.collect::<Vec<String>>()
.join(", ");
let callback = match &self.block {
parser::AutocmdBlock::Command(cmd) => {
format!("function()\n{}\nend", cmd.gen(state))
}
parser::AutocmdBlock::Block(block) => {
format!("function()\n{}\nend", block.body.gen(state))
}
};
output.write_lua(&format!(
r#"
vim.api.nvim_create_autocmd({{ {event_list} }}, {{
{group}
callback = {callback},
}})
"#
))
}
}
impl Generate for ReturnCommand {
fn write_default(&self, state: &mut State, output: &mut Output) {
let scope = scope_or_empty!(state, Function | While { .. } | For { .. });
output.write_lua(&if scope.has_continue() {
match &self.expr {
Some(expr) => {
format!("return vim9.ITER_RETURN, {}", expr.gen(state))
}
None => "return vim9.ITER_RETURN".to_string(),
}
} else {
match &self.expr {
Some(expr) => format!("return {}", expr.gen(state)),
None => "return".to_string(),
}
})
}
}
impl Generate for DefCommand {
fn write_default(&self, state: &mut State, output: &mut Output) {
let name = self.name.gen(state);
let (body, scope) = state.with_scope(ScopeKind::Function, |s| self.body.gen(s));
let (signature, sig_statements) = gen_signature(state, &self.args);
let local = get_local(state, &self.name);
let result = if scope.deferred > 0 {
// TODO: Should probably handle errors in default statements or body
format!(
r#"
{local} {name} = function({signature})
{sig_statements}
local nvim9_deferred = {{}}
local _, ret = pcall(function()
{body}
end)
for _, nvim9_defer in ipairs(nvim9_deferred) do
pcall(nvim9_defer)
end
return ret
end
"#
)
} else {
// TODO: If this command follows certain patterns,
// we will also need to define a vimscript function,
// so that this function is available.
//
// this could be something just like:
// function <NAME>(...)
// return luaeval('...', ...)
// endfunction
//
// but we haven't done this part yet.
// This is a "must-have" aspect of what we're doing.
format!(
r#"
{local} {name} = function({signature})
{sig_statements}
{body}
end
"#,
)
};
output.write_lua(&result);
}
fn write_test(&self, state: &mut State, output: &mut Output) {
let name = self.name.gen(state);
if state.opts.mode != ParserMode::Test || !name.starts_with("Test") {
return self.write_default(state, output);
}
let (body, scope) = state.with_scope(ScopeKind::Function, |s| self.body.gen(s));
assert!(scope.deferred == 0, "have not handled deferred in tests");
output.write_lua(&format!(
r#"
it("{name}", function()
-- Set errors to empty
vim.v.errors = {{}}
-- Actual test
{body}
-- Assert that errors is still empty
assert.are.same({{}}, vim.v.errors)
end)
"#,
))
}
}
fn gen_signature(state: &mut State, args: &Signature) -> (String, String) {
(
args.params
.iter()
.map(|p| p.name.gen(state))
.collect::<Vec<String>>()
.join(", "),
args.params
.iter()
.filter(|p| p.default_val.is_some() || matches!(p.ty, Some(Type::BoolOrNumber)))
.map(|p| {
// TODO: What about val=true defaults?
match p.ty {
Some(Type::BoolOrNumber) => {
let name = p.name.gen(state);
format!("{name} = vim9.bool({name})")
}
_ => {
let name = p.name.gen(state);
let default_val = p.default_val.clone().unwrap();
let default_val = default_val.gen(state);
format!("{name} = vim.F.if_nil({name}, {default_val}, {name})")
}
}
})
.collect::<Vec<String>>()
.join("\n"),
)
}
impl Generate for StatementCommand {
fn write_default(&self, state: &mut State, output: &mut Output) {
match self {
StatementCommand::Assign(assign) => assign.write(state, output),
StatementCommand::Mutate(mutate) => mutate.write(state, output),
}
}
}
fn statement_lhs(expr: &Expression, state: &mut State) -> String {
match &expr {
Expression::Index(idx) => {
format!(
"{}[vim9.index_expr({})]",
idx.container.gen(state),
match idx.index.as_ref() {
IndexType::Item(item) => item.gen(state),
IndexType::Slice(_) => todo!("Unknown index type"),
}
)
}
_ => expr.gen(state),
}
}
impl Generate for MutationStatement {
fn write_default(&self, state: &mut State, output: &mut Output) {
// format!("--[[ {:#?} ]]", self)
let left = statement_lhs(&self.left, state);
let operator = match self.modifier.kind {
lexer::TokenKind::PlusEquals => parser::Operator::Plus,
lexer::TokenKind::MinusEquals => parser::Operator::Minus,
lexer::TokenKind::MulEquals => parser::Operator::Multiply,
lexer::TokenKind::DivEquals => parser::Operator::Divide,
lexer::TokenKind::PercentEquals => parser::Operator::Modulo,
lexer::TokenKind::StringConcatEquals => parser::Operator::StringConcat,
_ => unreachable!(),
};
// TODO(clone)
let infix = InfixExpression::new(
operator,
self.left.clone().into(),
self.right.clone().into(),
)
.gen(state);
output.write_lua(&format!("{left} = {infix}"))
}
}
impl Generate for AssignStatement {
fn write_default(&self, state: &mut State, output: &mut Output) {
let left = statement_lhs(&self.left, state);
let right = self.right.gen(state);
output.write_lua(&format!("{left} = {right}"))
}
}
impl Generate for IfCommand {
fn write_default(&self, state: &mut State, output: &mut Output) {
let else_result = match &self.else_command {
Some(e) => e.gen(state),
None => "".to_string(),
};
let condition = self.condition.gen(state);
// TODO: Numbers are automatically coerced into bools for vim
// so sometimes the type system lies to us.
//
// Perhaps I need an additional type: BoolNumber that we use
// for most cases of vim, and we only escalate to Bool when we're confident
// that this what is happening.
//
// This would allow us to remove the vim9.bool condition (assuming the type
// system is correct in vim9script)
let condition = match guess_type_of_expr(state, &self.condition) {
Type::Bool => condition,
_ => format!("vim9.bool({condition})"),
};
output.write_lua(
format!(
r#"
if {condition} then
{}
{}
{}
end"#,
self.body.gen(state),
self.elseifs
.iter()
.map(|e| e.gen(state))
.collect::<Vec<String>>()
.join("\n"),
else_result,
)
.trim(),
)
}
}
impl Generate for ElseIfCommand {
fn write_default(&self, state: &mut State, output: &mut Output) {
output.write_lua(&format!(
r#"
elseif vim9.bool({}) then
{}
"#,
self.condition.gen(state),
self.body.gen(state)
))
}
}
impl Generate for ElseCommand {
fn write_default(&self, state: &mut State, output: &mut Output) {
output.write_lua(&format!("else\n{}\n", self.body.gen(state)))
}
}
impl Generate for Body {
fn write_default(&self, state: &mut State, output: &mut Output) {
(&self).write(state, output)
}
}
impl Generate for &Body {
fn write_default(&self, state: &mut State, output: &mut Output) {
output.write_lua(
&self
.commands
.iter()
.map(|cmd| cmd.gen(state))
.collect::<Vec<String>>()
.join("\n"),
)
}
}
impl Generate for EchoCommand {
fn write_default(&self, state: &mut State, output: &mut Output) {
// TODO: Probably should add some function that
// pretty prints these the way they would get printed in vim
// or maybe just call vim.cmd [[echo <...>]] ?
// Not sure.
// Maybe have to expose something to get exactly the same
// results
//
// format!("vim.api.nvim_echo({}, false, {{}})", chunks)
output.write_lua(&format!("print({})", self.expr.gen(state)))
}
}