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
use crate::lexer::token::LexToken;
use crate::macros::EntityMacroDefinition;
use crate::parser::Parser;
use crate::syntax::entity::LazyParsedEntityDatabase;
use crate::syntax::expression::ident::HirIdentifier;
use crate::syntax::expression::scope::ExpressionScope;
use crate::syntax::expression::{HirExpression, ParsedStatement};
use crate::syntax::guard::Guard;
use crate::syntax::sigil::{Equals, Let};
use crate::syntax::skip_newline::SkipNewline;
use crate::syntax::Syntax;
use derive_new::new;
use lark_collections::{FxIndexMap, Seq};
use lark_debug_derive::DebugWith;
use lark_entity::Entity;
use lark_error::ErrorReported;
use lark_error::WithError;
use lark_hir as hir;
use lark_span::FileName;
use lark_span::Spanned;
use lark_string::GlobalIdentifier;
use lark_string::Text;
use std::sync::Arc;

// # True grammar:
//
// Expression = Place | Value
//
// Value = Block
//    | Expression `(` (Expression),* `)`
//    | Expression BinaryOp Expression
//    | UnaryOp Expression
//    | Place `=` Expression
//    | Literal
//
// Place = Identifier
//    | Value // temporary
//    | Place `.` Identifier // field
//
// # Factored into "almost LL" form:
//
// Expression = {
//   Expression5,
//   Expression5 `=` Expression5,
// }
//
// Expression5 = {
//   Expression4,
//   Expression4 \n* `==` Expression4,
//   Expression4 \n* `!=` Expression4,
// }
//
// Expression4 = {
//   Expression3,
//   Expression4 \n* `+` Expression3,
//   Expression4 \n* `-` Expression3,
// }
//
// Expression3 = {
//   Expression2,
//   Expression3 \n* `*` Expression2,
//   Expression3 \n* `/` Expression2,
// }
//
// Expression2 = {
//   Expression1,
//   UnaryOp Expression0,
// }
//
// Expression1 = {
//   Expression0 `(` Comma(Expression) `)`
//   Expression0 `(` Comma(Field) `)`
//   Expression0 MemberAccess*
// }
//
// MemberAccess = {
//   \n* `.` Identifier,
//   `(` Comma(Expression) `)`,
// }
//
// Expression0 = {
//   Literal
//   Identifier,
//   `(` \n* Expression \n* `)`,  // Should we allow newlines *anywhere* here?
//   Block,
//   "if" Expression Block [ "else" Block ]
// }
//
// Block = {
//   `{` Statement* \n* `}`
// }
//
// Statement = {
//   \n* Expression Terminator,
//   \n* `let` Identifier [`:` Ty ] `=` Expression Terminator,
// }
//
// Terminator = {
//   `;`
//   \n
// }
//

/// Parses an expression to create a `hir::FnBody`. Despite the name,
/// this can be used for any "free-standing" expression, such as the
/// value of a `const` and so forth.
crate fn parse_fn_body(
    item_entity: Entity,
    db: &dyn LazyParsedEntityDatabase,
    entity_macro_definitions: &FxIndexMap<GlobalIdentifier, Arc<dyn EntityMacroDefinition>>,
    input: &Text,                              // complete Text of file
    tokens: &Seq<Spanned<LexToken, FileName>>, // subset of Token corresponding to this expression
    self_argument: Option<Spanned<GlobalIdentifier, FileName>>,
    arguments: Seq<Spanned<GlobalIdentifier, FileName>>, // names of the arguments
) -> WithError<hir::FnBody> {
    let mut scope = ExpressionScope {
        db,
        item_entity,
        variables: Default::default(),
        fn_body_tables: Default::default(),
    };

    let arguments: Vec<_> = self_argument
        .iter()
        .chain(arguments.iter())
        .map(|&argument| {
            let name = scope.add(
                argument.span,
                hir::IdentifierData {
                    text: argument.value,
                },
            );
            let variable = scope.add(argument.span, hir::VariableData { name });
            scope.introduce_variable(variable);
            variable
        })
        .collect();
    let arguments = hir::List::from_iterator(&mut scope.fn_body_tables, arguments);

    let file_name = item_entity.input_file(&db).unwrap();
    let mut parser = Parser::new(file_name, db, entity_macro_definitions, input, tokens, 0);

    let root_expression = match parser.expect(HirExpression::new(&mut scope)) {
        Ok(e) => e,
        Err(err) => {
            let error = scope.add(err.span(), hir::ErrorData::Misc);
            scope.add(err.span(), hir::ExpressionData::Error { error })
        }
    };

    if let Some(span) = parser.parse_extra_input() {
        parser.report_error("extra input after end of expression", span);
    }

    parser.into_with_error(hir::FnBody {
        arguments: Ok(arguments),
        root_expression,
        tables: scope.fn_body_tables,
    })
}

#[derive(new, DebugWith)]
crate struct Statement<'me, 'parse> {
    scope: &'me mut ExpressionScope<'parse>,
}

impl Syntax<'parse> for Statement<'me, 'parse> {
    type Data = ParsedStatement;

    fn test(&mut self, parser: &Parser<'parse>) -> bool {
        parser.test(LetStatement::new(self.scope)) || parser.test(HirExpression::new(self.scope))
    }

    fn expect(&mut self, parser: &mut Parser<'parse>) -> Result<Self::Data, ErrorReported> {
        if let Some(r) = parser.parse_if_present(LetStatement::new(self.scope)) {
            return r;
        }

        let expression = parser.expect(HirExpression::new(self.scope))?;
        Ok(ParsedStatement::Expression(expression))
    }
}

#[derive(new, DebugWith)]
struct LetStatement<'me, 'parse> {
    scope: &'me mut ExpressionScope<'parse>,
}

impl Syntax<'parse> for LetStatement<'me, 'parse> {
    type Data = ParsedStatement;

    fn test(&mut self, parser: &Parser<'parse>) -> bool {
        parser.test(Let)
    }

    fn expect(&mut self, parser: &mut Parser<'parse>) -> Result<Self::Data, ErrorReported> {
        let let_keyword = parser.expect(Let)?;
        let name = parser.expect(HirIdentifier::new(self.scope))?;

        let mut initializer = None;
        if let Some(expression) =
            parser.parse_if_present(Guard(Equals, SkipNewline(HirExpression::new(self.scope))))
        {
            initializer = Some(expression?);
        }

        let span = let_keyword.span.extended_until_end_of(parser.peek_span());

        let name_span = self.scope.span(name);
        let variable = self.scope.add(name_span, hir::VariableData { name });

        // Subtle: This is a "side effect" that is visible to other
        // parsers that come after us within the same scope. Note that
        // entering a block (or other lexical scope) saves/restores
        // the set of variable bindings.
        self.scope.introduce_variable(variable);

        Ok(ParsedStatement::Let(span, variable, initializer))
    }
}