lutra-compiler 0.6.0

Compiler for Lutra query language
Documentation
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
#![allow(unused_variables)]
//! Printer that converts AST to Lutra source code.
//!
//! Goal is to provide full code formatting, with indentation, wrapping to
//! prevent long lines and preservation of whitespace and comments.
//!
//! The printer uses a recursive descent approach to traverse the AST and
//! generate the corresponding source code. It defines a [PrintSource] trait
//! that is implemented for most AST node types.
//! The [PrintSource::print] method takes a [Printer] object which contains
//! printing configuration (ident size, max line width), buffer for generated
//! source code and constraints for further code printing.
//!
//! For example, when `max_width` is 80 and we insert `let a = ` (8 chars) into
//! the buffer, constrains are updated to reflect that current line has only
//! 72 remaining unused chars.
//!
//! When printing nodes, we first try to print them inline (without new lines).
//! If that succeeds, it will return `Some(Printer)` that contains generated
//! code and new constrains. This printer is then merged into parent printer.
//! If that fails, it will return `None` and we will retry by splitting expr
//! into multiple lines.

mod common;
mod defs;
mod expr;
mod test;
mod types;

use crate::codespan;
use crate::parser::{Token, TokenKind};
use crate::pr;

pub use defs::print_def_signature;

pub fn print_ty(ty: &pr::Ty) -> String {
    let mut p = Printer::new(&CONFIG_NO_WRAP, None);
    ty.print(&mut p).unwrap();

    assert!(p.edits.is_empty());
    p.buffer
}

pub fn print_source(
    source: &pr::Source,
    trivia: Option<&[Token]>,
) -> Vec<codespan::TextEdit<'static>> {
    let mut p = Printer::new(&CONFIG_PRETTY, trivia);
    p.buffer_span.source_id = source.span.source_id;

    source.print(&mut p).unwrap();

    p.finish_edit();
    p.edits
}

/// Print source code of an AST node, within constrains of a printer
/// (e.g. remaining line width). If this is not possible, return `None`.
trait PrintSource {
    #[must_use]
    fn print<'c>(&self, p: &mut Printer<'c>) -> Option<()>;

    /// Return span of the AST node.
    /// Used for emitting leading & following trivia (comments, new lines).
    fn span(&self) -> Option<crate::Span>;
}

struct Printer<'c> {
    /// Printer configuration (indent size, max line width)
    config: &'c Config,

    /// Buffer for generated code.
    buffer: String,

    /// Span of the original code that the buffer contains code for.
    /// Note that this is not consistent at every step - only when *particular*
    /// nodes are finished, we increase this value.
    buffer_span: crate::Span,

    /// Remaining width of the current line.
    rem_width: u16,

    /// Number of indentation steps the next line should be prefixed with.
    indent: u16,

    /// When true, generated code must not contain new lines.
    single_line: bool,

    /// Width of suffix that is needed to complete current node.
    /// When using single_line mode, this width can be subtracted before
    /// printing sub-nodes.
    pending_suffix: u16,

    /// Trivia tokens from original source (e.g. comments, new lines)
    trivia: Option<&'c [Token]>,

    /// Finished edits of preceding nodes, whose code might not be contingent to
    /// the code of the nodes in the current [Self::buffer].
    edits: Vec<codespan::TextEdit<'static>>,
}

struct Config {
    indent_size: u16,
    max_width: u16,
}

const CONFIG_PRETTY: Config = Config {
    indent_size: 2,
    max_width: 80,
};

const CONFIG_NO_WRAP: Config = Config {
    indent_size: 2,
    max_width: u16::MAX,
};

impl<'c> Printer<'c> {
    fn new(config: &'c Config, trivia: Option<&'c [Token]>) -> Printer<'c> {
        Printer {
            config,

            buffer: String::new(),
            buffer_span: crate::Span {
                source_id: 0, // this is incorrect, but it is overridden later
                start: 0,
                len: 0,
            },
            indent: 0,
            rem_width: config.max_width,
            single_line: false,
            pending_suffix: 0,

            trivia,
            edits: Vec::new(),
        }
    }

    /// Appends a code snippet to generated code buffer.
    ///
    /// It will calculate `rem_width` after the snippet is applied and return
    /// `None` if the snippet overflows the line.
    #[must_use]
    fn push<S: AsRef<str>>(&mut self, snippet: S) -> Option<()> {
        for c in snippet.as_ref().chars() {
            if c == '\n' {
                self.rem_width = self.config.max_width;
                continue;
            }
            if self.rem_width == 0 {
                return None;
            }
            self.rem_width -= 1;
        }
        self.buffer += snippet.as_ref();
        Some(())
    }

    /// Appends a code snippet to generated code buffer, but does not consume
    /// width for it. This is to be used only when width was already consumed in
    /// advance.
    fn push_unchecked<S: AsRef<str>>(&mut self, snippet: S) {
        self.buffer += snippet.as_ref();
    }

    /// Mark a span as fully printed (its printed code is in [Self::buffer]).
    /// This is used for producing [codespan::TextEdit].
    fn mark_printed(&mut self, span: &Option<crate::Span>) {
        if let Some(span) = span {
            self.buffer_span.set_end_of(span);
        }
    }

    /// Mark the buffer to contain code for nodes up to some offset of the
    /// original code.
    fn mark_printed_up_to(&mut self, offset: u32) {
        self.buffer_span.set_end(offset);
    }

    /// Creates a new [Printer] for trying printing for a sub-node without
    /// affecting the original [Printer].
    /// When successful, the forked [Printer] has to be [Printer::merge]ed back.
    fn fork(&self) -> Printer<'c> {
        Printer {
            config: self.config,
            buffer: String::new(),
            buffer_span: crate::Span {
                source_id: self.buffer_span.source_id,
                start: self.buffer_span.end(),
                len: 0,
            },
            rem_width: self.rem_width,
            indent: self.indent,
            single_line: self.single_line,
            pending_suffix: self.pending_suffix,

            trivia: self.trivia,
            edits: Vec::new(),
        }
    }

    /// Merges a forked printer back into the parent.
    fn merge(&mut self, forked: Printer<'c>) {
        self.rem_width = forked.rem_width;
        self.trivia = forked.trivia;

        if forked.edits.is_empty() {
            self.buffer += &forked.buffer;
            self.buffer_span.set_end_of(&forked.buffer_span);
            return;
        }

        // Forked printer emitted standalone edits (e.g. one-per-definition).
        // Flush current buffer before importing them, then continue with the
        // fork's remaining open buffer range.
        self.finish_edit();
        self.edits.extend(forked.edits);
        self.buffer = forked.buffer;
        self.buffer_span = forked.buffer_span;
    }

    /// Subtracts remaining widths. Returns `None` when there is not enough
    /// space on the line.
    #[must_use]
    fn consume(&mut self, width: usize) -> Option<()> {
        self.rem_width = self.rem_width.checked_sub(width as u16)?;
        Some(())
    }

    /// Increase indentation level.
    fn indent(&mut self) {
        self.indent += 1;
    }

    /// Decrease indentation level.
    fn dedent(&mut self) {
        self.indent -= 1;
    }

    /// Resets rem_width and produces chars for a new line + indentation of the
    /// next line.
    fn new_line(&mut self) {
        let indent_width = self.indent * self.config.indent_size;
        self.rem_width = self.config.max_width.saturating_sub(indent_width);

        // When we insert a new line, we can assume that pending suffix will be
        // placed on another line and thus does need to be considered when
        // producing single-line outputs.
        self.pending_suffix = 0;

        let len_without_trailing_whitespace = self.buffer.trim_end_matches(' ').len();
        self.buffer.truncate(len_without_trailing_whitespace);

        self.buffer.push('\n');
        self.buffer.push_str(&" ".repeat(indent_width as usize));
    }

    /// Enables single line mode. Also consumes width of pending node suffix.
    #[must_use]
    fn require_single_line(&mut self, span: Option<crate::Span>) -> Option<()> {
        self.single_line = true;
        self.consume(self.pending_suffix as usize)?;
        self.pending_suffix = 0;

        self.validate_no_comments(span.map(|s| s.end()))?;
        Some(())
    }

    fn take_trivia(&mut self, until: u32) -> Option<&'c Token> {
        let trivia = self.trivia.as_mut()?;

        let t = trivia.first().filter(|t| t.span.end() <= until)?;

        *trivia = &trivia[1..];
        Some(t)
    }

    fn take_trivia_comment(&mut self, until: u32) -> Option<&'c str> {
        let trivia = self.trivia.as_mut()?;

        let t = trivia.first().filter(|t| t.span.end() <= until)?;

        let TokenKind::Comment(s) = &t.kind else {
            return None;
        };
        *trivia = &trivia[1..];
        Some(s)
    }

    fn take_trivia_new_line(&mut self, until: u32) -> Option<()> {
        let trivia = self.trivia.as_mut()?;

        let t = trivia.first().filter(|t| t.span.end() <= until)?;

        let TokenKind::NewLine = &t.kind else {
            return None;
        };
        *trivia = &trivia[1..];
        Some(())
    }

    fn inject_trivia_leading(&mut self, until: Option<u32>) {
        let Some(until) = until else { return };

        let mut nl_count = 0;

        while let Some(trivia) = self.take_trivia(until) {
            match &trivia.kind {
                TokenKind::NewLine => {
                    // print double empty lines
                    nl_count += 1;
                    if nl_count == 2 {
                        self.new_line();
                    }
                }
                TokenKind::Comment(comment) => {
                    self.push_unchecked("# ");
                    self.push_unchecked(comment);
                    self.new_line();
                    nl_count = 0;
                }

                _ => (),
            }
        }
    }

    fn inject_trivia_prev_inline(&mut self, until: Option<u32>) {
        let Some(until) = until else { return };

        while let Some(comment) = self.take_trivia_comment(until) {
            self.push_unchecked(" # ");
            self.push_unchecked(comment);
        }
    }

    fn inject_trivia_trailing(&mut self, until: Option<u32>) {
        let Some(until) = until else { return };

        let mut had_empty_line = false;
        while let Some(token) = self.take_trivia(until) {
            let TokenKind::Comment(comment) = &token.kind else {
                continue;
            };

            self.new_line();
            if !had_empty_line {
                self.new_line();
                had_empty_line = true;
            }

            self.push_unchecked("# ");
            self.push_unchecked(comment);
        }
    }

    fn validate_no_comments(&mut self, until: Option<u32>) -> Option<()> {
        let Some(until) = until else {
            return Some(());
        };

        while let Some(trivia) = self.take_trivia(until) {
            if let TokenKind::Comment(comment) = &trivia.kind {
                return None;
            }
        }
        Some(())
    }

    /// Convert current buffer into an [codespan::TextEdit] and save it.
    /// This is used to skip formatting of some nodes, i.e. not produce
    /// any [codespan::TextEdit] that would change it.
    fn finish_edit(&mut self) {
        if self.buffer.is_empty() && self.buffer_span.len == 0 {
            return;
        }

        let code = std::mem::take(&mut self.buffer);
        self.edits
            .push(codespan::TextEdit::new(self.buffer_span, code));
        self.buffer_span.start = self.buffer_span.end();
        self.buffer_span.len = 0;
    }
}

impl std::fmt::Debug for Printer<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Printer")
            .field("rem_width", &self.rem_width)
            .field("single_line", &self.single_line)
            .field("pending_suffix", &self.pending_suffix)
            .finish()
    }
}

impl<T> PrintSource for &T
where
    T: PrintSource,
{
    fn print<'c>(&self, p: &mut Printer<'c>) -> Option<()> {
        T::print(self, p)
    }

    fn span(&self) -> Option<crate::Span> {
        T::span(self)
    }
}