-
-
Notifications
You must be signed in to change notification settings - Fork 934
Expand file tree
/
Copy pathexpression.rs
More file actions
2848 lines (2573 loc) · 102 KB
/
expression.rs
File metadata and controls
2848 lines (2573 loc) · 102 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 num_bigint::BigInt;
use vec1::Vec1;
use super::{decision::ASSIGNMENT_VAR, *};
use crate::{
ast::*,
exhaustiveness::StringEncoding,
line_numbers::LineNumbers,
pretty::*,
type_::{
ModuleValueConstructor, Type, TypedCallArg, ValueConstructor, ValueConstructorVariant,
},
};
use std::sync::Arc;
#[derive(Debug, Clone)]
pub enum Position {
/// We are compiling the last expression in a function, meaning that it should
/// use `return` to return the value it produces from the function.
Tail,
/// We are inside a function, but the value of this expression isn't being
/// used, so we don't need to do anything with the returned value.
Statement,
/// The value of this expression needs to be used inside another expression,
/// so we need to use the value that is returned by this expression.
Expression(Ordering),
/// We are compiling an expression inside a block, meaning we must assign
/// to the `_block` variable at the end of the scope, because blocks are not
/// expressions in JS.
/// Since JS doesn't have variable shadowing, we must store the name of the
/// variable being used, which will include the incrementing counter.
/// For example, `block$2`
Assign(EcoString),
}
impl Position {
/// Returns `true` if the position is [`Tail`].
///
/// [`Tail`]: Position::Tail
#[must_use]
pub fn is_tail(&self) -> bool {
matches!(self, Self::Tail)
}
#[must_use]
pub fn ordering(&self) -> Ordering {
match self {
Self::Expression(ordering) => *ordering,
Self::Tail | Self::Assign(_) | Self::Statement => Ordering::Loose,
}
}
}
#[derive(Debug, Clone, Copy)]
/// Determines whether we can lift blocks into statement level instead of using
/// immediately invoked function expressions. Consider the following piece of code:
///
/// ```gleam
/// some_function(function_with_side_effect(), {
/// let a = 10
/// other_function_with_side_effects(a)
/// })
/// ```
/// Here, if we lift the block that is the second argument of the function, we
/// would end up running `other_function_with_side_effects` before
/// `function_with_side_effects`. This would be invalid, as code in Gleam should be
/// evaluated left-to-right, top-to-bottom. In this case, the ordering would be
/// `Strict`, indicating that we cannot lift the block.
///
/// However, in this example:
///
/// ```gleam
/// let value = !{
/// let value = False
/// some_function_with_side_effect()
/// value
/// }
/// ```
/// The only expression is the block, meaning it can be safely lifted without
/// changing the evaluation order of the program. So the ordering is `Loose`.
///
pub enum Ordering {
Strict,
Loose,
}
/// Tracking where the current function is a module function or an anonymous function.
#[derive(Debug)]
enum CurrentFunction {
/// The current function is a module function
///
/// ```gleam
/// pub fn main() -> Nil {
/// // we are here
/// }
/// ```
Module,
/// The current function is a module function, but one of its arguments shadows
/// the reference to itself so it cannot recurse.
///
/// ```gleam
/// pub fn main(main: fn() -> Nil) -> Nil {
/// // we are here
/// }
/// ```
ModuleWithShadowingArgument,
/// The current function is an anonymous function
///
/// ```gleam
/// pub fn main() -> Nil {
/// fn() {
/// // we are here
/// }
/// }
/// ```
Anonymous,
}
impl CurrentFunction {
#[inline]
fn can_recurse(&self) -> bool {
match self {
CurrentFunction::Module => true,
CurrentFunction::ModuleWithShadowingArgument => false,
CurrentFunction::Anonymous => false,
}
}
}
#[derive(Debug)]
pub(crate) struct Generator<'module, 'ast> {
module_name: EcoString,
src_path: EcoString,
line_numbers: &'module LineNumbers,
function_name: EcoString,
function_arguments: Vec<Option<&'module EcoString>>,
current_function: CurrentFunction,
pub current_scope_vars: im::HashMap<EcoString, usize>,
pub function_position: Position,
pub scope_position: Position,
// We register whether these features are used within an expression so that
// the module generator can output a suitable function if it is needed.
pub tracker: &'module mut UsageTracker,
// We track whether tail call recursion is used so that we can render a loop
// at the top level of the function to use in place of pushing new stack
// frames.
pub tail_recursion_used: bool,
/// Statements to be compiled when lifting blocks into statement scope.
/// For example, when compiling the following code:
/// ```gleam
/// let a = {
/// let b = 1
/// b + 1
/// }
/// ```
/// There will be 2 items in `statement_level`: The first will be `let _block;`
/// The second will be the generated code for the block being assigned to `a`.
/// This lets use return `_block` as the value that the block evaluated to,
/// while still including the necessary code in the output at the right place.
///
/// Once the `let` statement has compiled its value, it will add anything accumulated
/// in `statement_level` to the generated code, so it will result in:
///
/// ```javascript
/// let _block;
/// {...}
/// let a = _block;
/// ```
///
statement_level: Vec<Document<'ast>>,
/// This will be true if we've generated a `let assert` statement that we know
/// is guaranteed to throw.
/// This means we can stop code generation for all the following statements
/// in the same block!
pub let_assert_always_panics: bool,
}
impl<'module, 'a> Generator<'module, 'a> {
#[allow(clippy::too_many_arguments)] // TODO: FIXME
pub fn new(
module_name: EcoString,
src_path: EcoString,
line_numbers: &'module LineNumbers,
function_name: EcoString,
function_arguments: Vec<Option<&'module EcoString>>,
tracker: &'module mut UsageTracker,
mut current_scope_vars: im::HashMap<EcoString, usize>,
) -> Self {
let mut current_function = CurrentFunction::Module;
for &name in function_arguments.iter().flatten() {
// Initialise the function arguments
let _ = current_scope_vars.insert(name.clone(), 0);
// If any of the function arguments shadow the current function then
// recursion is no longer possible.
if function_name.as_ref() == name {
current_function = CurrentFunction::ModuleWithShadowingArgument;
}
}
Self {
tracker,
module_name,
src_path,
line_numbers,
function_name,
function_arguments,
tail_recursion_used: false,
current_scope_vars,
current_function,
function_position: Position::Tail,
scope_position: Position::Tail,
statement_level: Vec::new(),
let_assert_always_panics: false,
}
}
pub fn local_var(&mut self, name: &EcoString) -> EcoString {
match self.current_scope_vars.get(name) {
None => {
let _ = self.current_scope_vars.insert(name.clone(), 0);
maybe_escape_identifier(name)
}
Some(0) => maybe_escape_identifier(name),
Some(n) if name == "$" => eco_format!("${n}"),
Some(n) => eco_format!("{name}${n}"),
}
}
pub fn next_local_var(&mut self, name: &EcoString) -> EcoString {
let next = self.current_scope_vars.get(name).map_or(0, |i| i + 1);
let _ = self.current_scope_vars.insert(name.clone(), next);
self.local_var(name)
}
pub fn function_body(
&mut self,
body: &'a [TypedStatement],
arguments: &'a [TypedArg],
) -> Document<'a> {
let body = self.statements(body);
if self.tail_recursion_used {
self.tail_call_loop(body, arguments)
} else {
body
}
}
fn tail_call_loop(&mut self, body: Document<'a>, arguments: &'a [TypedArg]) -> Document<'a> {
let loop_assignments = concat(arguments.iter().flat_map(Arg::get_variable_name).map(
|name| {
let var = maybe_escape_identifier(name);
docvec!["let ", var, " = loop$", name, ";", line()]
},
));
docvec![
"while (true) {",
docvec![line(), loop_assignments, body].nest(INDENT),
line(),
"}"
]
}
fn statement(&mut self, statement: &'a TypedStatement) -> Document<'a> {
let expression_doc = match statement {
Statement::Expression(expression) => self.expression(expression),
Statement::Assignment(assignment) => self.assignment(assignment),
Statement::Use(use_) => self.expression(&use_.call),
Statement::Assert(assert) => self.assert(assert),
};
self.add_statement_level(expression_doc)
}
fn add_statement_level(&mut self, expression: Document<'a>) -> Document<'a> {
if self.statement_level.is_empty() {
expression
} else {
let mut statements = std::mem::take(&mut self.statement_level);
statements.push(expression);
join(statements, line())
}
}
pub fn expression(&mut self, expression: &'a TypedExpr) -> Document<'a> {
let document = match expression {
TypedExpr::String { value, .. } => string(value),
TypedExpr::Int { value, .. } => int(value),
TypedExpr::Float { float_value, .. } => float_from_value(float_value.value()),
TypedExpr::List { elements, tail, .. } => {
self.not_in_tail_position(Some(Ordering::Strict), |this| match tail {
Some(tail) => {
this.tracker.prepend_used = true;
let tail = this.wrap_expression(tail);
prepend(
elements.iter().map(|element| this.wrap_expression(element)),
tail,
)
}
None => {
this.tracker.list_used = true;
list(elements.iter().map(|element| this.wrap_expression(element)))
}
})
}
TypedExpr::Tuple { elements, .. } => self.tuple(elements),
TypedExpr::TupleIndex { tuple, index, .. } => self.tuple_index(tuple, *index),
TypedExpr::Case {
subjects,
clauses,
compiled_case,
..
} => decision::case(compiled_case, clauses, subjects, self),
TypedExpr::Call { fun, arguments, .. } => self.call(fun, arguments),
TypedExpr::Fn {
arguments, body, ..
} => self.fn_(arguments, body),
TypedExpr::RecordAccess { record, label, .. } => self.record_access(record, label),
TypedExpr::PositionalAccess { record, index, .. } => {
self.positional_access(record, *index)
}
TypedExpr::RecordUpdate {
record_assignment,
constructor,
arguments,
..
} => self.record_update(record_assignment, constructor, arguments),
TypedExpr::Var {
name, constructor, ..
} => self.variable(name, constructor),
TypedExpr::Pipeline {
first_value,
assignments,
finally,
..
} => self.pipeline(first_value, assignments.as_slice(), finally),
TypedExpr::Block { statements, .. } => self.block(statements),
TypedExpr::BinOp {
name, left, right, ..
} => self.bin_op(name, left, right),
TypedExpr::Todo {
message, location, ..
} => self.todo(message.as_ref().map(|m| &**m), location),
TypedExpr::Panic {
location, message, ..
} => self.panic(location, message.as_ref().map(|m| &**m)),
TypedExpr::BitArray { segments, .. } => self.bit_array(segments),
TypedExpr::ModuleSelect {
module_alias,
label,
constructor,
..
} => self.module_select(module_alias, label, constructor),
TypedExpr::NegateBool { value, .. } => self.negate_with("!", value),
TypedExpr::NegateInt { value, .. } => self.negate_with("- ", value),
TypedExpr::Echo {
expression,
message,
location,
..
} => {
let expression = expression
.as_ref()
.expect("echo with no expression outside of pipe");
let expresion_doc =
self.not_in_tail_position(None, |this| this.wrap_expression(expression));
self.echo(expresion_doc, message.as_deref(), location)
}
TypedExpr::Invalid { .. } => {
panic!("invalid expressions should not reach code generation")
}
};
if expression.handles_own_return() {
document
} else {
self.wrap_return(document)
}
}
fn negate_with(&mut self, with: &'static str, value: &'a TypedExpr) -> Document<'a> {
self.not_in_tail_position(None, |this| docvec![with, this.wrap_expression(value)])
}
fn bit_array(&mut self, segments: &'a [TypedExprBitArraySegment]) -> Document<'a> {
self.tracker.bit_array_literal_used = true;
// Collect all the values used in segments.
let segments_array = array(segments.iter().map(|segment| {
let value = self.not_in_tail_position(Some(Ordering::Strict), |this| {
this.wrap_expression(&segment.value)
});
let details = self.bit_array_segment_details(segment);
match details.type_ {
BitArraySegmentType::BitArray => {
if segment.size().is_some() {
self.tracker.bit_array_slice_used = true;
docvec!["bitArraySlice(", value, ", 0, ", details.size, ")"]
} else {
value
}
}
BitArraySegmentType::Int => match (details.size_value, segment.value.as_ref()) {
(Some(size_value), TypedExpr::Int { int_value, .. })
if size_value <= SAFE_INT_SEGMENT_MAX_SIZE.into()
&& (&size_value % BigInt::from(8) == BigInt::ZERO) =>
{
let bytes = bit_array_segment_int_value_to_bytes(
int_value.clone(),
size_value,
segment.endianness(),
);
u8_slice(&bytes)
}
(Some(size_value), _) if size_value == 8.into() => value,
(Some(size_value), _) if size_value <= 0.into() => nil(),
_ => {
self.tracker.sized_integer_segment_used = true;
let size = details.size;
let is_big = bool(segment.endianness().is_big());
docvec!["sizedInt(", value, ", ", size, ", ", is_big, ")"]
}
},
BitArraySegmentType::Float => {
self.tracker.float_bit_array_segment_used = true;
let size = details.size;
let is_big = bool(details.endianness.is_big());
docvec!["sizedFloat(", value, ", ", size, ", ", is_big, ")"]
}
BitArraySegmentType::String(StringEncoding::Utf8) => {
self.tracker.string_bit_array_segment_used = true;
docvec!["stringBits(", value, ")"]
}
BitArraySegmentType::String(StringEncoding::Utf16) => {
self.tracker.string_utf16_bit_array_segment_used = true;
let is_big = bool(details.endianness.is_big());
docvec!["stringToUtf16(", value, ", ", is_big, ")"]
}
BitArraySegmentType::String(StringEncoding::Utf32) => {
self.tracker.string_utf32_bit_array_segment_used = true;
let is_big = bool(details.endianness.is_big());
docvec!["stringToUtf32(", value, ", ", is_big, ")"]
}
BitArraySegmentType::UtfCodepoint(StringEncoding::Utf8) => {
self.tracker.codepoint_bit_array_segment_used = true;
docvec!["codepointBits(", value, ")"]
}
BitArraySegmentType::UtfCodepoint(StringEncoding::Utf16) => {
self.tracker.codepoint_utf16_bit_array_segment_used = true;
let is_big = bool(details.endianness.is_big());
docvec!["codepointToUtf16(", value, ", ", is_big, ")"]
}
BitArraySegmentType::UtfCodepoint(StringEncoding::Utf32) => {
self.tracker.codepoint_utf32_bit_array_segment_used = true;
let is_big = bool(details.endianness.is_big());
docvec!["codepointToUtf32(", value, ", ", is_big, ")"]
}
}
}));
docvec!["toBitArray(", segments_array, ")"]
}
fn bit_array_segment_details(
&mut self,
segment: &'a TypedExprBitArraySegment,
) -> BitArraySegmentDetails<'a> {
let size = segment.size();
let unit = segment.unit();
let (size_value, size) = match size {
Some(TypedExpr::Int { int_value, .. }) => {
let size_value = int_value * unit;
let size = eco_format!("{}", size_value).to_doc();
(Some(size_value), size)
}
Some(size) => {
let mut size = self.not_in_tail_position(Some(Ordering::Strict), |this| {
this.wrap_expression(size)
});
if unit != 1 {
size = size.group().append(" * ".to_doc().append(unit.to_doc()));
}
(None, size)
}
None => {
let size_value: usize = if segment.type_.is_int() { 8 } else { 64 };
(Some(BigInt::from(size_value)), docvec![size_value])
}
};
let type_ = BitArraySegmentType::from_segment(segment);
BitArraySegmentDetails {
type_,
size,
size_value,
endianness: segment.endianness(),
}
}
pub fn wrap_return(&mut self, document: Document<'a>) -> Document<'a> {
match &self.scope_position {
Position::Tail => docvec!["return ", document, ";"],
Position::Expression(_) | Position::Statement => document,
Position::Assign(name) => docvec![name.clone(), " = ", document, ";"],
}
}
pub fn not_in_tail_position<CompileFn, Output>(
&mut self,
// If ordering is None, it is inherited from the parent scope.
// It will be None in cases like `!x`, where `x` can be lifted
// only if the ordering is already loose.
ordering: Option<Ordering>,
compile: CompileFn,
) -> Output
where
CompileFn: Fn(&mut Self) -> Output,
{
let new_ordering = ordering.unwrap_or(self.scope_position.ordering());
let function_position = std::mem::replace(
&mut self.function_position,
Position::Expression(new_ordering),
);
let scope_position =
std::mem::replace(&mut self.scope_position, Position::Expression(new_ordering));
let result = compile(self);
self.function_position = function_position;
self.scope_position = scope_position;
result
}
/// Use the `_block` variable if the expression is JS statement.
pub fn wrap_expression(&mut self, expression: &'a TypedExpr) -> Document<'a> {
match (expression, &self.scope_position) {
(_, Position::Tail | Position::Assign(_)) => self.expression(expression),
(
TypedExpr::Panic { .. }
| TypedExpr::Todo { .. }
| TypedExpr::Case { .. }
| TypedExpr::Pipeline { .. }
| TypedExpr::RecordUpdate {
// Record updates that assign a variable generate multiple statements
record_assignment: Some(_),
..
},
Position::Expression(Ordering::Loose),
) => self.wrap_block(|this| this.expression(expression)),
(
TypedExpr::Panic { .. }
| TypedExpr::Todo { .. }
| TypedExpr::Case { .. }
| TypedExpr::Pipeline { .. }
| TypedExpr::RecordUpdate {
// Record updates that assign a variable generate multiple statements
record_assignment: Some(_),
..
},
Position::Expression(Ordering::Strict),
) => self.immediately_invoked_function_expression(expression, |this, expr| {
this.expression(expr)
}),
_ => self.expression(expression),
}
}
/// Wrap an expression using the `_block` variable if required due to being
/// a JS statement, or in parens if required due to being an operator or
/// a function literal.
pub fn child_expression(&mut self, expression: &'a TypedExpr) -> Document<'a> {
match expression {
TypedExpr::BinOp { name, .. } if name.is_operator_to_wrap() => {}
TypedExpr::Fn { .. } => {}
TypedExpr::Int { .. }
| TypedExpr::Float { .. }
| TypedExpr::String { .. }
| TypedExpr::Block { .. }
| TypedExpr::Pipeline { .. }
| TypedExpr::Var { .. }
| TypedExpr::List { .. }
| TypedExpr::Call { .. }
| TypedExpr::BinOp { .. }
| TypedExpr::Case { .. }
| TypedExpr::RecordAccess { .. }
| TypedExpr::PositionalAccess { .. }
| TypedExpr::ModuleSelect { .. }
| TypedExpr::Tuple { .. }
| TypedExpr::TupleIndex { .. }
| TypedExpr::Todo { .. }
| TypedExpr::Panic { .. }
| TypedExpr::Echo { .. }
| TypedExpr::BitArray { .. }
| TypedExpr::RecordUpdate { .. }
| TypedExpr::NegateBool { .. }
| TypedExpr::NegateInt { .. }
| TypedExpr::Invalid { .. } => return self.wrap_expression(expression),
}
let document = self.expression(expression);
match &self.scope_position {
// Here the document is a return statement: `return <expr>;`
// or an assignment: `_block = <expr>;`
Position::Tail | Position::Assign(_) | Position::Statement => document,
Position::Expression(_) => docvec!["(", document, ")"],
}
}
/// Wrap an expression in an immediately invoked function expression
fn immediately_invoked_function_expression<T, ToDoc>(
&mut self,
statements: &'a T,
to_doc: ToDoc,
) -> Document<'a>
where
ToDoc: FnOnce(&mut Self, &'a T) -> Document<'a>,
{
// Save initial state
let scope_position = std::mem::replace(&mut self.scope_position, Position::Tail);
let statement_level = std::mem::take(&mut self.statement_level);
// Set state for in this iife
let current_scope_vars = self.current_scope_vars.clone();
// Generate the expression
let result = to_doc(self, statements);
let doc = self.add_statement_level(result);
let doc = immediately_invoked_function_expression_document(doc);
// Reset
self.current_scope_vars = current_scope_vars;
self.scope_position = scope_position;
self.statement_level = statement_level;
self.wrap_return(doc)
}
fn wrap_block<CompileFn>(&mut self, compile: CompileFn) -> Document<'a>
where
CompileFn: Fn(&mut Self) -> Document<'a>,
{
let block_variable = self.next_local_var(&BLOCK_VARIABLE.into());
// Save initial state
let scope_position = std::mem::replace(
&mut self.scope_position,
Position::Assign(block_variable.clone()),
);
let function_position = std::mem::replace(
&mut self.function_position,
Position::Expression(Ordering::Strict),
);
// Generate the expression
let statement_doc = compile(self);
// Reset
self.scope_position = scope_position;
self.function_position = function_position;
self.statement_level
.push(docvec!["let ", block_variable.clone(), ";"]);
self.statement_level.push(statement_doc);
self.wrap_return(block_variable.to_doc())
}
fn variable(&mut self, name: &'a EcoString, constructor: &'a ValueConstructor) -> Document<'a> {
match &constructor.variant {
ValueConstructorVariant::Record { arity, .. } => {
let type_ = constructor.type_.clone();
let tracker = &mut self.tracker;
record_constructor(type_, None, name, *arity, tracker)
}
ValueConstructorVariant::ModuleFn { .. }
| ValueConstructorVariant::ModuleConstant { .. }
| ValueConstructorVariant::LocalVariable { .. } => self.local_var(name).to_doc(),
}
}
fn pipeline(
&mut self,
first_value: &'a TypedPipelineAssignment,
assignments: &'a [(TypedPipelineAssignment, PipelineAssignmentKind)],
finally: &'a TypedExpr,
) -> Document<'a> {
let count = assignments.len();
let mut documents = Vec::with_capacity((count + 2) * 2);
let all_assignments = std::iter::once(first_value)
.chain(assignments.iter().map(|(assignment, _kind)| assignment));
let mut latest_local_var: Option<EcoString> = None;
for assignment in all_assignments {
// An echo in a pipeline won't result in an assignment, instead it
// just prints the previous variable assigned in the pipeline.
if let TypedExpr::Echo {
expression: None,
message,
location,
..
} = assignment.value.as_ref()
{
documents.push(self.not_in_tail_position(Some(Ordering::Strict), |this| {
let var = latest_local_var
.as_ref()
.expect("echo with no previous step in a pipe");
this.echo(var.to_doc(), message.as_deref(), location)
}))
} else {
// Otherwise we assign the intermediate pipe value to a variable.
let assignment_document = self
.not_in_tail_position(Some(Ordering::Strict), |this| {
this.simple_variable_assignment(&assignment.name, &assignment.value)
});
documents.push(self.add_statement_level(assignment_document));
latest_local_var = Some(self.local_var(&assignment.name));
}
documents.push(line());
}
if let TypedExpr::Echo {
expression: None,
message,
location,
..
} = finally
{
let var = latest_local_var.expect("echo with no previous step in a pipe");
documents.push(self.echo(var.to_doc(), message.as_deref(), location));
} else {
let finally = self.expression(finally);
documents.push(self.add_statement_level(finally))
}
documents.to_doc().force_break()
}
pub(crate) fn expression_flattening_blocks(
&mut self,
expression: &'a TypedExpr,
) -> Document<'a> {
if let TypedExpr::Block { statements, .. } = expression {
self.statements(statements)
} else {
let expression_document = self.expression(expression);
self.add_statement_level(expression_document)
}
}
fn block(&mut self, statements: &'a Vec1<TypedStatement>) -> Document<'a> {
if statements.len() == 1 {
match statements.first() {
Statement::Expression(expression) => return self.child_expression(expression),
Statement::Assignment(assignment) => match &assignment.kind {
AssignmentKind::Let | AssignmentKind::Generated => {
return self.child_expression(&assignment.value);
}
// We can't just return the right-hand side of a `let assert`
// assignment; we still need to check that the pattern matches.
AssignmentKind::Assert { .. } => {}
},
Statement::Use(use_) => return self.child_expression(&use_.call),
// Similar to `let assert`, we can't immediately return the value
// that is asserted; we have to actually perform the assertion.
Statement::Assert(_) => {}
}
}
match &self.scope_position {
Position::Tail | Position::Assign(_) | Position::Statement => {
self.block_document(statements)
}
Position::Expression(Ordering::Strict) => self
.immediately_invoked_function_expression(statements, |this, statements| {
this.statements(statements)
}),
Position::Expression(Ordering::Loose) => self.wrap_block(|this| {
// Save previous scope
let current_scope_vars = this.current_scope_vars.clone();
let document = this.block_document(statements);
// Restore previous state
this.current_scope_vars = current_scope_vars;
document
}),
}
}
fn block_document(&mut self, statements: &'a Vec1<TypedStatement>) -> Document<'a> {
let statements = self.statements(statements);
docvec!["{", docvec![line(), statements].nest(INDENT), line(), "}"]
}
fn statements(&mut self, statements: &'a [TypedStatement]) -> Document<'a> {
// If there are any statements that need to be printed at statement level, that's
// for an outer scope so we don't want to print them inside this one.
let statement_level = std::mem::take(&mut self.statement_level);
let count = statements.len();
let mut documents = Vec::with_capacity(count * 3);
for (i, statement) in statements.iter().enumerate() {
if i + 1 < count {
let function_position =
std::mem::replace(&mut self.function_position, Position::Statement);
let scope_position =
std::mem::replace(&mut self.scope_position, Position::Statement);
documents.push(self.statement(statement));
self.function_position = function_position;
self.scope_position = scope_position;
if requires_semicolon(statement) {
documents.push(";".to_doc());
}
documents.push(line());
} else {
documents.push(self.statement(statement));
}
// If we've generated code for a statement that always throws, we
// can skip code generation for all the following ones.
if self.let_assert_always_panics {
self.let_assert_always_panics = false;
break;
}
}
self.statement_level = statement_level;
if count == 1 {
documents.to_doc()
} else {
documents.to_doc().force_break()
}
}
fn simple_variable_assignment(
&mut self,
name: &'a EcoString,
value: &'a TypedExpr,
) -> Document<'a> {
// Subject must be rendered before the variable for variable numbering
let subject =
self.not_in_tail_position(Some(Ordering::Loose), |this| this.wrap_expression(value));
let js_name = self.next_local_var(name);
let assignment = docvec!["let ", js_name.clone(), " = ", subject, ";"];
let assignment = match &self.scope_position {
Position::Expression(_) | Position::Statement => assignment,
Position::Tail => docvec![assignment, line(), "return ", js_name, ";"],
Position::Assign(block_variable) => docvec![
assignment,
line(),
block_variable.clone(),
" = ",
js_name,
";"
],
};
assignment.force_break()
}
fn assignment(&mut self, assignment: &'a TypedAssignment) -> Document<'a> {
let TypedAssignment {
pattern,
kind,
value,
compiled_case,
annotation: _,
location: _,
} = assignment;
// In case the pattern is just a variable, we special case it to
// generate just a simple assignment instead of using the decision tree
// for the code generation step.
if let TypedPattern::Variable { name, .. } = pattern {
return self.simple_variable_assignment(name, value);
}
decision::let_(compiled_case, value, kind, self, pattern)
}
fn assert(&mut self, assert: &'a TypedAssert) -> Document<'a> {
let TypedAssert {
location,
value,
message,
} = assert;
let message = match message {
Some(m) => self.not_in_tail_position(
Some(Ordering::Strict),
|this: &mut Generator<'module, 'a>| this.expression(m),
),
None => string("Assertion failed."),
};
let check = self.not_in_tail_position(Some(Ordering::Loose), |this| {
this.assert_check(value, &message, *location)
});
match &self.scope_position {
Position::Expression(_) | Position::Statement => check,
Position::Tail | Position::Assign(_) => {
docvec![check, line(), self.wrap_return("undefined".to_doc())]
}
}
}
fn assert_check(
&mut self,
subject: &'a TypedExpr,
message: &Document<'a>,
location: SrcSpan,
) -> Document<'a> {
let (subject_document, mut fields) = match subject {
TypedExpr::Call { fun, arguments, .. } => {
let argument_variables = arguments
.iter()
.map(|element| {
self.not_in_tail_position(Some(Ordering::Strict), |this| {
this.assign_to_variable(&element.value)
})
})
.collect_vec();
(
self.call_with_doc_arguments(fun, argument_variables.clone()),
vec![
("kind", string("function_call")),
(
"arguments",
array(argument_variables.into_iter().zip(arguments).map(
|(variable, argument)| {
self.asserted_expression(
AssertExpression::from_expression(&argument.value),
Some(variable),
argument.location(),
)
},
)),
),
],
)
}
TypedExpr::BinOp {
name, left, right, ..
} => {
match name {
BinOp::And => return self.assert_and(left, right, message, location),
BinOp::Or => return self.assert_or(left, right, message, location),
BinOp::Eq
| BinOp::NotEq
| BinOp::LtInt
| BinOp::LtEqInt
| BinOp::LtFloat
| BinOp::LtEqFloat
| BinOp::GtEqInt
| BinOp::GtInt
| BinOp::GtEqFloat
| BinOp::GtFloat
| BinOp::AddInt
| BinOp::AddFloat
| BinOp::SubInt