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
// Copyright (c) 2016-2019 Fabian Schuiki

//! A parameter environment generated by an instantiation.

use crate::{
    ast_map::AstNode,
    crate_prelude::*,
    hir::{HirNode, NamedParam, PosParam},
    ty::Type,
    value::Value,
};

/// A parameter environment.
///
/// This is merely an handle that is cheap to copy and pass around. Use the
/// [`Context`] to resolve this to the actual [`ParamEnvData`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ParamEnv(pub(crate) u32);

/// A node id with corresponding parameter environment.
pub type NodeEnvId = (NodeId, ParamEnv);

/// A parameter environment.
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)]
pub struct ParamEnvData<'t> {
    values: Vec<(NodeId, ParamEnvBinding<Value<'t>>)>,
    types: Vec<(NodeId, ParamEnvBinding<Type<'t>>)>,
}

impl<'t> ParamEnvData<'t> {
    /// Find the value assigned to a node.
    pub fn find_value(&self, node_id: NodeId) -> Option<ParamEnvBinding<Value<'t>>> {
        self.values
            .iter()
            .find(|&&(id, _)| id == node_id)
            .map(|&(_, id)| id)
    }

    /// Find the type assigned to a node.
    pub fn find_type(&self, node_id: NodeId) -> Option<ParamEnvBinding<Type<'t>>> {
        self.types
            .iter()
            .find(|&&(id, _)| id == node_id)
            .map(|&(_, id)| id)
    }

    /// Assign a value to a node.
    pub fn set_value(&mut self, node_id: NodeId, value: Value<'t>) {
        self.values.retain(|&(n, _)| n != node_id);
        self.values.push((node_id, ParamEnvBinding::Direct(value)));
    }
}

/// A binding in a parameter environment.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum ParamEnvBinding<T> {
    /// A direct binding, directly assigning a type or value to a node.
    Direct(T),
    /// An indirect binding, pointing at another node's type or value.
    Indirect(NodeEnvId),
}

/// A location that implies a parameter environment.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ParamEnvSource<'hir> {
    ModuleInst {
        module: NodeId,
        inst: NodeId,
        env: ParamEnv,
        pos: &'hir [PosParam],
        named: &'hir [NamedParam],
    },
}

pub(crate) fn compute<'gcx>(
    cx: &impl Context<'gcx>,
    src: ParamEnvSource<'gcx>,
) -> Result<ParamEnv> {
    match src {
        ParamEnvSource::ModuleInst {
            module,
            inst,
            env,
            pos,
            named,
        } => {
            let module = match cx.hir_of(module)? {
                HirNode::Module(m) => m,
                _ => panic!("expected module"),
            };

            // Collect a list of module parameters.
            let module_params: Vec<_> = module
                .params
                .iter()
                .cloned()
                .chain(module.block.params.iter().cloned())
                .collect();

            // Associate the positional and named assignments with the actual
            // parameters of the module.
            let param_iter = pos
                .iter()
                .enumerate()
                .map(
                    |(index, &(span, assign_id))| match module_params.get(index) {
                        Some(&param_id) => Ok((param_id, (assign_id, env))),
                        None => {
                            cx.emit(
                                DiagBuilder2::error(format!(
                                    "{} only has {} parameter(s)",
                                    module.desc_full(),
                                    module_params.len()
                                ))
                                .span(span),
                            );
                            Err(())
                        }
                    },
                )
                .chain(named.iter().map(|&(_span, name, assign_id)| {
                    let names: Vec<_> = module_params
                        .iter()
                        .flat_map(|&id| match cx.ast_of(id) {
                            Ok(AstNode::TypeParam(_, p)) => Some((p.name.name, id)),
                            Ok(AstNode::ValueParam(_, p)) => Some((p.name.name, id)),
                            Ok(_) => unreachable!(),
                            Err(()) => None,
                        })
                        .collect();
                    match names
                        .iter()
                        .find(|&(param_name, _)| *param_name == name.value)
                    {
                        Some(&(_, param_id)) => Ok((param_id, (assign_id, env))),
                        None => {
                            cx.emit(
                                DiagBuilder2::error(format!(
                                    "no parameter `{}` in {}",
                                    name,
                                    module.desc_full(),
                                ))
                                .span(name.span)
                                .add_note(format!(
                                    "declared parameters are {}",
                                    names
                                        .iter()
                                        .map(|&(n, _)| format!("`{}`", n))
                                        .collect::<Vec<_>>()
                                        .join(", ")
                                )),
                            );
                            Err(())
                        }
                    }
                }));
            let param_iter = param_iter
                .collect::<Vec<_>>()
                .into_iter()
                .collect::<Result<Vec<_>>>()?
                .into_iter();

            // Split up type and value parameters.
            let mut types = vec![];
            let mut values = vec![];
            for (param_id, assign_id) in param_iter {
                let assign_id = match assign_id {
                    (Some(i), n) => (i, n),
                    _ => continue,
                };
                match cx.ast_of(param_id)? {
                    AstNode::TypeParam(..) => {
                        cx.set_lowering_hint(assign_id.0, hir::Hint::Type);
                        types.push((param_id, ParamEnvBinding::Indirect(assign_id)))
                    }
                    AstNode::ValueParam(..) => {
                        cx.set_lowering_hint(assign_id.0, hir::Hint::Expr);
                        values.push((param_id, ParamEnvBinding::Indirect(assign_id)))
                    }
                    _ => unreachable!(),
                }
            }

            let env = cx.intern_param_env(ParamEnvData { types, values });
            cx.add_param_env_context(env, inst);
            Ok(env)
        }
    }
}