esl_compiler/builder/
component.rs

1//! Component instance builder module
2use crate::builder::subject::Subject;
3use crate::builder::variable::build_some_variable;
4use crate::context::Context;
5use crate::cursor::{Cursor, Error, Token};
6use crate::location::FileLocation;
7use crate::parser::Rule;
8use crate::reference::{ComponentDefinitionTarget, Reference, VariableTarget};
9
10/// Component instance within a component definition.
11#[derive(Clone, Debug, Default, PartialEq)]
12pub struct Component {
13    /// Name of the component instance.
14    pub name: Token,
15    /// Location of the entire component instantiation (with arguments).
16    pub loc: FileLocation,
17    /// Definition to which this component instance should adhere.
18    pub definition: Reference<Token, ComponentDefinitionTarget>,
19    /// Provided arguments, which should resolve to variables.
20    pub arguments: Vec<Reference<Subject, VariableTarget>>,
21}
22impl std::fmt::Display for Component {
23    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24        write!(f, "{}", self.name)
25    }
26}
27
28/// Build a relation instance from a cursor into a relations mapping.
29pub fn build_component_instantiation(
30    ctx: &mut Context,
31    component_instantiation: Cursor,
32) -> Result<Component, Error> {
33    let loc = component_instantiation.as_location();
34    let mut cs = component_instantiation.into_inner();
35    let name = cs.req_first(Rule::some_name)?.into();
36    let definition = cs.req_first(Rule::some_name)?.into();
37    let arguments = match cs.find_first(Rule::with_arguments) {
38        Some(c) => build_arguments(ctx, c)?,
39        None => Default::default(),
40    };
41    Ok(Component {
42        name,
43        loc,
44        definition,
45        arguments,
46    })
47}
48
49/// Build with_arguments from a cursor.
50pub fn build_arguments(
51    ctx: &mut Context,
52    arguments: Cursor,
53) -> Result<Vec<Reference<Subject, VariableTarget>>, Error> {
54    arguments
55        .into_inner()
56        .get_all(Rule::some_variable)
57        .map(|some_variable| build_some_variable(ctx, some_variable))
58        .collect()
59}