pub struct SourceMap { /* private fields */ }
Expand description

Mapping from entity names to source locations.

Implementations§

Read-only interface which is exposed outside the parser crate.

Look up a value entity.

Examples found in repository?
src/parser.rs (line 2052)
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
    fn parse_function_body(&mut self, ctx: &mut Context) -> ParseResult<()> {
        while self.token() != Some(Token::RBrace) {
            self.parse_basic_block(ctx)?;
        }

        // Now that we've seen all defined values in the function, ensure that
        // all references refer to a definition.
        for block in &ctx.function.layout {
            for inst in ctx.function.layout.block_insts(block) {
                for value in ctx.function.dfg.inst_args(inst) {
                    if !ctx.map.contains_value(*value) {
                        return err!(
                            ctx.map.location(AnyEntity::Inst(inst)).unwrap(),
                            "undefined operand value {}",
                            value
                        );
                    }
                }
            }
        }

        for alias in &ctx.aliases {
            if !ctx.function.dfg.set_alias_type_for_parser(*alias) {
                let loc = ctx.map.location(AnyEntity::Value(*alias)).unwrap();
                return err!(loc, "alias cycle involving {}", alias);
            }
        }

        Ok(())
    }

    // Parse a basic block, add contents to `ctx`.
    //
    // extended-basic-block ::= * block-header { instruction }
    // block-header         ::= Block(block) [block-params] [block-flags] ":"
    // block-flags          ::= [Cold]
    //
    fn parse_basic_block(&mut self, ctx: &mut Context) -> ParseResult<()> {
        // Collect comments for the next block.
        self.start_gathering_comments();

        let block_num = self.match_block("expected block header")?;
        let block = ctx.add_block(block_num, self.loc)?;

        if block_num.as_u32() >= MAX_BLOCKS_IN_A_FUNCTION {
            return Err(self.error("too many blocks"));
        }

        if self.token() == Some(Token::LPar) {
            self.parse_block_params(ctx, block)?;
        }

        if self.optional(Token::Cold) {
            ctx.set_cold_block(block);
        }

        self.match_token(Token::Colon, "expected ':' after block parameters")?;

        // Collect any trailing comments.
        self.token();
        self.claim_gathered_comments(block);

        // extended-basic-block ::= block-header * { instruction }
        while match self.token() {
            Some(Token::Value(_))
            | Some(Token::Identifier(_))
            | Some(Token::LBracket)
            | Some(Token::SourceLoc(_)) => true,
            _ => false,
        } {
            let srcloc = self.optional_srcloc()?;

            // We need to parse instruction results here because they are shared
            // between the parsing of value aliases and the parsing of instructions.
            //
            // inst-results ::= Value(v) { "," Value(v) }
            let results = self.parse_inst_results()?;

            for result in &results {
                while ctx.function.dfg.num_values() <= result.index() {
                    ctx.function.dfg.make_invalid_value_for_parser();
                }
            }

            match self.token() {
                Some(Token::Arrow) => {
                    self.consume();
                    self.parse_value_alias(&results, ctx)?;
                }
                Some(Token::Equal) => {
                    self.consume();
                    self.parse_instruction(&results, srcloc, ctx, block)?;
                }
                _ if !results.is_empty() => return err!(self.loc, "expected -> or ="),
                _ => self.parse_instruction(&results, srcloc, ctx, block)?,
            }
        }

        Ok(())
    }

    // Parse parenthesized list of block parameters. Returns a vector of (u32, Type) pairs with the
    // value numbers of the defined values and the defined types.
    //
    // block-params ::= * "(" block-param { "," block-param } ")"
    fn parse_block_params(&mut self, ctx: &mut Context, block: Block) -> ParseResult<()> {
        // block-params ::= * "(" block-param { "," block-param } ")"
        self.match_token(Token::LPar, "expected '(' before block parameters")?;

        // block-params ::= "(" * block-param { "," block-param } ")"
        self.parse_block_param(ctx, block)?;

        // block-params ::= "(" block-param * { "," block-param } ")"
        while self.optional(Token::Comma) {
            // block-params ::= "(" block-param { "," * block-param } ")"
            self.parse_block_param(ctx, block)?;
        }

        // block-params ::= "(" block-param { "," block-param } * ")"
        self.match_token(Token::RPar, "expected ')' after block parameters")?;

        Ok(())
    }

    // Parse a single block parameter declaration, and append it to `block`.
    //
    // block-param ::= * Value(v) ":" Type(t) arg-loc?
    // arg-loc ::= "[" value-location "]"
    //
    fn parse_block_param(&mut self, ctx: &mut Context, block: Block) -> ParseResult<()> {
        // block-param ::= * Value(v) ":" Type(t) arg-loc?
        let v = self.match_value("block argument must be a value")?;
        let v_location = self.loc;
        // block-param ::= Value(v) * ":" Type(t) arg-loc?
        self.match_token(Token::Colon, "expected ':' after block argument")?;
        // block-param ::= Value(v) ":" * Type(t) arg-loc?

        while ctx.function.dfg.num_values() <= v.index() {
            ctx.function.dfg.make_invalid_value_for_parser();
        }

        let t = self.match_type("expected block argument type")?;
        // Allocate the block argument.
        ctx.function.dfg.append_block_param_for_parser(block, t, v);
        ctx.map.def_value(v, v_location)?;

        Ok(())
    }

    // Parse instruction results and return them.
    //
    // inst-results ::= Value(v) { "," Value(v) }
    //
    fn parse_inst_results(&mut self) -> ParseResult<SmallVec<[Value; 1]>> {
        // Result value numbers.
        let mut results = SmallVec::new();

        // instruction  ::=  * [inst-results "="] Opcode(opc) ["." Type] ...
        // inst-results ::= * Value(v) { "," Value(v) }
        if let Some(Token::Value(v)) = self.token() {
            self.consume();

            results.push(v);

            // inst-results ::= Value(v) * { "," Value(v) }
            while self.optional(Token::Comma) {
                // inst-results ::= Value(v) { "," * Value(v) }
                results.push(self.match_value("expected result value")?);
            }
        }

        Ok(results)
    }

    // Parse a value alias, and append it to `block`.
    //
    // value_alias ::= [inst-results] "->" Value(v)
    //
    fn parse_value_alias(&mut self, results: &[Value], ctx: &mut Context) -> ParseResult<()> {
        if results.len() != 1 {
            return err!(self.loc, "wrong number of aliases");
        }
        let result = results[0];
        let dest = self.match_value("expected value alias")?;

        // Allow duplicate definitions of aliases, as long as they are identical.
        if ctx.map.contains_value(result) {
            if let Some(old) = ctx.function.dfg.value_alias_dest_for_serialization(result) {
                if old != dest {
                    return err!(
                        self.loc,
                        "value {} is already defined as an alias with destination {}",
                        result,
                        old
                    );
                }
            } else {
                return err!(self.loc, "value {} is already defined");
            }
        } else {
            ctx.map.def_value(result, self.loc)?;
        }

        if !ctx.map.contains_value(dest) {
            return err!(self.loc, "value {} is not yet defined", dest);
        }

        ctx.function
            .dfg
            .make_value_alias_for_serialization(dest, result);

        ctx.aliases.push(result);
        Ok(())
    }

    // Parse an instruction, append it to `block`.
    //
    // instruction ::= [inst-results "="] Opcode(opc) ["." Type] ...
    //
    fn parse_instruction(
        &mut self,
        results: &[Value],
        srcloc: ir::SourceLoc,
        ctx: &mut Context,
        block: Block,
    ) -> ParseResult<()> {
        // Define the result values.
        for val in results {
            ctx.map.def_value(*val, self.loc)?;
        }

        // Collect comments for the next instruction.
        self.start_gathering_comments();

        // instruction ::=  [inst-results "="] * Opcode(opc) ["." Type] ...
        let opcode = if let Some(Token::Identifier(text)) = self.token() {
            match text.parse() {
                Ok(opc) => opc,
                Err(msg) => return err!(self.loc, "{}: '{}'", msg, text),
            }
        } else {
            return err!(self.loc, "expected instruction opcode");
        };
        let opcode_loc = self.loc;
        self.consume();

        // Look for a controlling type variable annotation.
        // instruction ::=  [inst-results "="] Opcode(opc) * ["." Type] ...
        let explicit_ctrl_type = if self.optional(Token::Dot) {
            if let Some(Token::Type(_t)) = self.token() {
                Some(self.match_type("expected type after 'opcode.'")?)
            } else {
                let dt = self.match_dt("expected dynamic type")?;
                self.concrete_from_dt(dt, ctx)
            }
        } else {
            None
        };

        // instruction ::=  [inst-results "="] Opcode(opc) ["." Type] * ...
        let inst_data = self.parse_inst_operands(ctx, opcode, explicit_ctrl_type)?;

        // We're done parsing the instruction now.
        //
        // We still need to check that the number of result values in the source matches the opcode
        // or function call signature. We also need to create values with the right type for all
        // the instruction results.
        let ctrl_typevar = self.infer_typevar(ctx, opcode, explicit_ctrl_type, &inst_data)?;
        let inst = ctx.function.dfg.make_inst(inst_data);
        let num_results =
            ctx.function
                .dfg
                .make_inst_results_for_parser(inst, ctrl_typevar, results);
        ctx.function.layout.append_inst(inst, block);
        ctx.map
            .def_entity(inst.into(), opcode_loc)
            .expect("duplicate inst references created");

        if !srcloc.is_default() {
            ctx.function.set_srcloc(inst, srcloc);
        }

        if results.len() != num_results {
            return err!(
                self.loc,
                "instruction produces {} result values, {} given",
                num_results,
                results.len()
            );
        }

        // Collect any trailing comments.
        self.token();
        self.claim_gathered_comments(inst);

        Ok(())
    }

    // Type inference for polymorphic instructions.
    //
    // The controlling type variable can be specified explicitly as 'splat.i32x4 v5', or it can be
    // inferred from `inst_data.typevar_operand` for some opcodes.
    //
    // Returns the controlling typevar for a polymorphic opcode, or `INVALID` for a non-polymorphic
    // opcode.
    fn infer_typevar(
        &self,
        ctx: &Context,
        opcode: Opcode,
        explicit_ctrl_type: Option<Type>,
        inst_data: &InstructionData,
    ) -> ParseResult<Type> {
        let constraints = opcode.constraints();
        let ctrl_type = match explicit_ctrl_type {
            Some(t) => t,
            None => {
                if constraints.use_typevar_operand() {
                    // This is an opcode that supports type inference, AND there was no
                    // explicit type specified. Look up `ctrl_value` to see if it was defined
                    // already.
                    // TBD: If it is defined in another block, the type should have been
                    // specified explicitly. It is unfortunate that the correctness of IR
                    // depends on the layout of the blocks.
                    let ctrl_src_value = inst_data
                        .typevar_operand(&ctx.function.dfg.value_lists)
                        .expect("Constraints <-> Format inconsistency");
                    if !ctx.map.contains_value(ctrl_src_value) {
                        return err!(
                            self.loc,
                            "type variable required for polymorphic opcode, e.g. '{}.{}'; \
                             can't infer from {} which is not yet defined",
                            opcode,
                            constraints.ctrl_typeset().unwrap().example(),
                            ctrl_src_value
                        );
                    }
                    if !ctx.function.dfg.value_is_valid_for_parser(ctrl_src_value) {
                        return err!(
                            self.loc,
                            "type variable required for polymorphic opcode, e.g. '{}.{}'; \
                             can't infer from {} which is not yet resolved",
                            opcode,
                            constraints.ctrl_typeset().unwrap().example(),
                            ctrl_src_value
                        );
                    }
                    ctx.function.dfg.value_type(ctrl_src_value)
                } else if constraints.is_polymorphic() {
                    // This opcode does not support type inference, so the explicit type
                    // variable is required.
                    return err!(
                        self.loc,
                        "type variable required for polymorphic opcode, e.g. '{}.{}'",
                        opcode,
                        constraints.ctrl_typeset().unwrap().example()
                    );
                } else {
                    // This is a non-polymorphic opcode. No typevar needed.
                    INVALID
                }
            }
        };

        // Verify that `ctrl_type` is valid for the controlling type variable. We don't want to
        // attempt deriving types from an incorrect basis.
        // This is not a complete type check. The verifier does that.
        if let Some(typeset) = constraints.ctrl_typeset() {
            // This is a polymorphic opcode.
            if !typeset.contains(ctrl_type) {
                return err!(
                    self.loc,
                    "{} is not a valid typevar for {}",
                    ctrl_type,
                    opcode
                );
            }
        // Treat it as a syntax error to specify a typevar on a non-polymorphic opcode.
        } else if ctrl_type != INVALID {
            return err!(self.loc, "{} does not take a typevar", opcode);
        }

        Ok(ctrl_type)
    }
More examples
Hide additional examples
src/sourcemap.rs (line 87)
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
    pub fn lookup_str(&self, name: &str) -> Option<AnyEntity> {
        split_entity_name(name).and_then(|(ent, num)| match ent {
            "v" => Value::with_number(num).and_then(|v| {
                if !self.contains_value(v) {
                    None
                } else {
                    Some(v.into())
                }
            }),
            "block" => Block::with_number(num).and_then(|block| {
                if !self.contains_block(block) {
                    None
                } else {
                    Some(block.into())
                }
            }),
            "ss" => StackSlot::with_number(num).and_then(|ss| {
                if !self.contains_ss(ss) {
                    None
                } else {
                    Some(ss.into())
                }
            }),
            "gv" => GlobalValue::with_number(num).and_then(|gv| {
                if !self.contains_gv(gv) {
                    None
                } else {
                    Some(gv.into())
                }
            }),
            "heap" => Heap::with_number(num).and_then(|heap| {
                if !self.contains_heap(heap) {
                    None
                } else {
                    Some(heap.into())
                }
            }),
            "table" => Table::with_number(num).and_then(|table| {
                if !self.contains_table(table) {
                    None
                } else {
                    Some(table.into())
                }
            }),
            "sig" => SigRef::with_number(num).and_then(|sig| {
                if !self.contains_sig(sig) {
                    None
                } else {
                    Some(sig.into())
                }
            }),
            "fn" => FuncRef::with_number(num).and_then(|fn_| {
                if !self.contains_fn(fn_) {
                    None
                } else {
                    Some(fn_.into())
                }
            }),
            "jt" => JumpTable::with_number(num).and_then(|jt| {
                if !self.contains_jt(jt) {
                    None
                } else {
                    Some(jt.into())
                }
            }),
            _ => None,
        })
    }

Look up a block entity.

Examples found in repository?
src/sourcemap.rs (line 94)
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
    pub fn lookup_str(&self, name: &str) -> Option<AnyEntity> {
        split_entity_name(name).and_then(|(ent, num)| match ent {
            "v" => Value::with_number(num).and_then(|v| {
                if !self.contains_value(v) {
                    None
                } else {
                    Some(v.into())
                }
            }),
            "block" => Block::with_number(num).and_then(|block| {
                if !self.contains_block(block) {
                    None
                } else {
                    Some(block.into())
                }
            }),
            "ss" => StackSlot::with_number(num).and_then(|ss| {
                if !self.contains_ss(ss) {
                    None
                } else {
                    Some(ss.into())
                }
            }),
            "gv" => GlobalValue::with_number(num).and_then(|gv| {
                if !self.contains_gv(gv) {
                    None
                } else {
                    Some(gv.into())
                }
            }),
            "heap" => Heap::with_number(num).and_then(|heap| {
                if !self.contains_heap(heap) {
                    None
                } else {
                    Some(heap.into())
                }
            }),
            "table" => Table::with_number(num).and_then(|table| {
                if !self.contains_table(table) {
                    None
                } else {
                    Some(table.into())
                }
            }),
            "sig" => SigRef::with_number(num).and_then(|sig| {
                if !self.contains_sig(sig) {
                    None
                } else {
                    Some(sig.into())
                }
            }),
            "fn" => FuncRef::with_number(num).and_then(|fn_| {
                if !self.contains_fn(fn_) {
                    None
                } else {
                    Some(fn_.into())
                }
            }),
            "jt" => JumpTable::with_number(num).and_then(|jt| {
                if !self.contains_jt(jt) {
                    None
                } else {
                    Some(jt.into())
                }
            }),
            _ => None,
        })
    }

Look up a stack slot entity.

Examples found in repository?
src/parser.rs (line 271)
270
271
272
273
274
275
276
    fn check_ss(&self, ss: StackSlot, loc: Location) -> ParseResult<()> {
        if !self.map.contains_ss(ss) {
            err!(loc, "undefined stack slot {}", ss)
        } else {
            Ok(())
        }
    }
More examples
Hide additional examples
src/sourcemap.rs (line 101)
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
    pub fn lookup_str(&self, name: &str) -> Option<AnyEntity> {
        split_entity_name(name).and_then(|(ent, num)| match ent {
            "v" => Value::with_number(num).and_then(|v| {
                if !self.contains_value(v) {
                    None
                } else {
                    Some(v.into())
                }
            }),
            "block" => Block::with_number(num).and_then(|block| {
                if !self.contains_block(block) {
                    None
                } else {
                    Some(block.into())
                }
            }),
            "ss" => StackSlot::with_number(num).and_then(|ss| {
                if !self.contains_ss(ss) {
                    None
                } else {
                    Some(ss.into())
                }
            }),
            "gv" => GlobalValue::with_number(num).and_then(|gv| {
                if !self.contains_gv(gv) {
                    None
                } else {
                    Some(gv.into())
                }
            }),
            "heap" => Heap::with_number(num).and_then(|heap| {
                if !self.contains_heap(heap) {
                    None
                } else {
                    Some(heap.into())
                }
            }),
            "table" => Table::with_number(num).and_then(|table| {
                if !self.contains_table(table) {
                    None
                } else {
                    Some(table.into())
                }
            }),
            "sig" => SigRef::with_number(num).and_then(|sig| {
                if !self.contains_sig(sig) {
                    None
                } else {
                    Some(sig.into())
                }
            }),
            "fn" => FuncRef::with_number(num).and_then(|fn_| {
                if !self.contains_fn(fn_) {
                    None
                } else {
                    Some(fn_.into())
                }
            }),
            "jt" => JumpTable::with_number(num).and_then(|jt| {
                if !self.contains_jt(jt) {
                    None
                } else {
                    Some(jt.into())
                }
            }),
            _ => None,
        })
    }

Look up a dynamic stack slot entity.

Examples found in repository?
src/parser.rs (line 299)
298
299
300
301
302
303
304
    fn check_dss(&self, dss: DynamicStackSlot, loc: Location) -> ParseResult<()> {
        if !self.map.contains_dss(dss) {
            err!(loc, "undefined dynamic stack slot {}", dss)
        } else {
            Ok(())
        }
    }

Look up a global value entity.

Examples found in repository?
src/parser.rs (line 336)
335
336
337
338
339
340
341
    fn check_gv(&self, gv: GlobalValue, loc: Location) -> ParseResult<()> {
        if !self.map.contains_gv(gv) {
            err!(loc, "undefined global value {}", gv)
        } else {
            Ok(())
        }
    }
More examples
Hide additional examples
src/sourcemap.rs (line 108)
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
    pub fn lookup_str(&self, name: &str) -> Option<AnyEntity> {
        split_entity_name(name).and_then(|(ent, num)| match ent {
            "v" => Value::with_number(num).and_then(|v| {
                if !self.contains_value(v) {
                    None
                } else {
                    Some(v.into())
                }
            }),
            "block" => Block::with_number(num).and_then(|block| {
                if !self.contains_block(block) {
                    None
                } else {
                    Some(block.into())
                }
            }),
            "ss" => StackSlot::with_number(num).and_then(|ss| {
                if !self.contains_ss(ss) {
                    None
                } else {
                    Some(ss.into())
                }
            }),
            "gv" => GlobalValue::with_number(num).and_then(|gv| {
                if !self.contains_gv(gv) {
                    None
                } else {
                    Some(gv.into())
                }
            }),
            "heap" => Heap::with_number(num).and_then(|heap| {
                if !self.contains_heap(heap) {
                    None
                } else {
                    Some(heap.into())
                }
            }),
            "table" => Table::with_number(num).and_then(|table| {
                if !self.contains_table(table) {
                    None
                } else {
                    Some(table.into())
                }
            }),
            "sig" => SigRef::with_number(num).and_then(|sig| {
                if !self.contains_sig(sig) {
                    None
                } else {
                    Some(sig.into())
                }
            }),
            "fn" => FuncRef::with_number(num).and_then(|fn_| {
                if !self.contains_fn(fn_) {
                    None
                } else {
                    Some(fn_.into())
                }
            }),
            "jt" => JumpTable::with_number(num).and_then(|jt| {
                if !self.contains_jt(jt) {
                    None
                } else {
                    Some(jt.into())
                }
            }),
            _ => None,
        })
    }

Look up a heap entity.

Examples found in repository?
src/parser.rs (line 363)
362
363
364
365
366
367
368
    fn check_heap(&self, heap: Heap, loc: Location) -> ParseResult<()> {
        if !self.map.contains_heap(heap) {
            err!(loc, "undefined heap {}", heap)
        } else {
            Ok(())
        }
    }
More examples
Hide additional examples
src/sourcemap.rs (line 115)
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
    pub fn lookup_str(&self, name: &str) -> Option<AnyEntity> {
        split_entity_name(name).and_then(|(ent, num)| match ent {
            "v" => Value::with_number(num).and_then(|v| {
                if !self.contains_value(v) {
                    None
                } else {
                    Some(v.into())
                }
            }),
            "block" => Block::with_number(num).and_then(|block| {
                if !self.contains_block(block) {
                    None
                } else {
                    Some(block.into())
                }
            }),
            "ss" => StackSlot::with_number(num).and_then(|ss| {
                if !self.contains_ss(ss) {
                    None
                } else {
                    Some(ss.into())
                }
            }),
            "gv" => GlobalValue::with_number(num).and_then(|gv| {
                if !self.contains_gv(gv) {
                    None
                } else {
                    Some(gv.into())
                }
            }),
            "heap" => Heap::with_number(num).and_then(|heap| {
                if !self.contains_heap(heap) {
                    None
                } else {
                    Some(heap.into())
                }
            }),
            "table" => Table::with_number(num).and_then(|table| {
                if !self.contains_table(table) {
                    None
                } else {
                    Some(table.into())
                }
            }),
            "sig" => SigRef::with_number(num).and_then(|sig| {
                if !self.contains_sig(sig) {
                    None
                } else {
                    Some(sig.into())
                }
            }),
            "fn" => FuncRef::with_number(num).and_then(|fn_| {
                if !self.contains_fn(fn_) {
                    None
                } else {
                    Some(fn_.into())
                }
            }),
            "jt" => JumpTable::with_number(num).and_then(|jt| {
                if !self.contains_jt(jt) {
                    None
                } else {
                    Some(jt.into())
                }
            }),
            _ => None,
        })
    }

Look up a table entity.

Examples found in repository?
src/parser.rs (line 387)
386
387
388
389
390
391
392
    fn check_table(&self, table: Table, loc: Location) -> ParseResult<()> {
        if !self.map.contains_table(table) {
            err!(loc, "undefined table {}", table)
        } else {
            Ok(())
        }
    }
More examples
Hide additional examples
src/sourcemap.rs (line 122)
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
    pub fn lookup_str(&self, name: &str) -> Option<AnyEntity> {
        split_entity_name(name).and_then(|(ent, num)| match ent {
            "v" => Value::with_number(num).and_then(|v| {
                if !self.contains_value(v) {
                    None
                } else {
                    Some(v.into())
                }
            }),
            "block" => Block::with_number(num).and_then(|block| {
                if !self.contains_block(block) {
                    None
                } else {
                    Some(block.into())
                }
            }),
            "ss" => StackSlot::with_number(num).and_then(|ss| {
                if !self.contains_ss(ss) {
                    None
                } else {
                    Some(ss.into())
                }
            }),
            "gv" => GlobalValue::with_number(num).and_then(|gv| {
                if !self.contains_gv(gv) {
                    None
                } else {
                    Some(gv.into())
                }
            }),
            "heap" => Heap::with_number(num).and_then(|heap| {
                if !self.contains_heap(heap) {
                    None
                } else {
                    Some(heap.into())
                }
            }),
            "table" => Table::with_number(num).and_then(|table| {
                if !self.contains_table(table) {
                    None
                } else {
                    Some(table.into())
                }
            }),
            "sig" => SigRef::with_number(num).and_then(|sig| {
                if !self.contains_sig(sig) {
                    None
                } else {
                    Some(sig.into())
                }
            }),
            "fn" => FuncRef::with_number(num).and_then(|fn_| {
                if !self.contains_fn(fn_) {
                    None
                } else {
                    Some(fn_.into())
                }
            }),
            "jt" => JumpTable::with_number(num).and_then(|jt| {
                if !self.contains_jt(jt) {
                    None
                } else {
                    Some(jt.into())
                }
            }),
            _ => None,
        })
    }

Look up a signature entity.

Examples found in repository?
src/parser.rs (line 412)
411
412
413
414
415
416
417
    fn check_sig(&self, sig: SigRef, loc: Location) -> ParseResult<()> {
        if !self.map.contains_sig(sig) {
            err!(loc, "undefined signature {}", sig)
        } else {
            Ok(())
        }
    }
More examples
Hide additional examples
src/sourcemap.rs (line 129)
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
    pub fn lookup_str(&self, name: &str) -> Option<AnyEntity> {
        split_entity_name(name).and_then(|(ent, num)| match ent {
            "v" => Value::with_number(num).and_then(|v| {
                if !self.contains_value(v) {
                    None
                } else {
                    Some(v.into())
                }
            }),
            "block" => Block::with_number(num).and_then(|block| {
                if !self.contains_block(block) {
                    None
                } else {
                    Some(block.into())
                }
            }),
            "ss" => StackSlot::with_number(num).and_then(|ss| {
                if !self.contains_ss(ss) {
                    None
                } else {
                    Some(ss.into())
                }
            }),
            "gv" => GlobalValue::with_number(num).and_then(|gv| {
                if !self.contains_gv(gv) {
                    None
                } else {
                    Some(gv.into())
                }
            }),
            "heap" => Heap::with_number(num).and_then(|heap| {
                if !self.contains_heap(heap) {
                    None
                } else {
                    Some(heap.into())
                }
            }),
            "table" => Table::with_number(num).and_then(|table| {
                if !self.contains_table(table) {
                    None
                } else {
                    Some(table.into())
                }
            }),
            "sig" => SigRef::with_number(num).and_then(|sig| {
                if !self.contains_sig(sig) {
                    None
                } else {
                    Some(sig.into())
                }
            }),
            "fn" => FuncRef::with_number(num).and_then(|fn_| {
                if !self.contains_fn(fn_) {
                    None
                } else {
                    Some(fn_.into())
                }
            }),
            "jt" => JumpTable::with_number(num).and_then(|jt| {
                if !self.contains_jt(jt) {
                    None
                } else {
                    Some(jt.into())
                }
            }),
            _ => None,
        })
    }

Look up a function entity.

Examples found in repository?
src/parser.rs (line 435)
434
435
436
437
438
439
440
    fn check_fn(&self, fn_: FuncRef, loc: Location) -> ParseResult<()> {
        if !self.map.contains_fn(fn_) {
            err!(loc, "undefined function {}", fn_)
        } else {
            Ok(())
        }
    }
More examples
Hide additional examples
src/sourcemap.rs (line 136)
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
    pub fn lookup_str(&self, name: &str) -> Option<AnyEntity> {
        split_entity_name(name).and_then(|(ent, num)| match ent {
            "v" => Value::with_number(num).and_then(|v| {
                if !self.contains_value(v) {
                    None
                } else {
                    Some(v.into())
                }
            }),
            "block" => Block::with_number(num).and_then(|block| {
                if !self.contains_block(block) {
                    None
                } else {
                    Some(block.into())
                }
            }),
            "ss" => StackSlot::with_number(num).and_then(|ss| {
                if !self.contains_ss(ss) {
                    None
                } else {
                    Some(ss.into())
                }
            }),
            "gv" => GlobalValue::with_number(num).and_then(|gv| {
                if !self.contains_gv(gv) {
                    None
                } else {
                    Some(gv.into())
                }
            }),
            "heap" => Heap::with_number(num).and_then(|heap| {
                if !self.contains_heap(heap) {
                    None
                } else {
                    Some(heap.into())
                }
            }),
            "table" => Table::with_number(num).and_then(|table| {
                if !self.contains_table(table) {
                    None
                } else {
                    Some(table.into())
                }
            }),
            "sig" => SigRef::with_number(num).and_then(|sig| {
                if !self.contains_sig(sig) {
                    None
                } else {
                    Some(sig.into())
                }
            }),
            "fn" => FuncRef::with_number(num).and_then(|fn_| {
                if !self.contains_fn(fn_) {
                    None
                } else {
                    Some(fn_.into())
                }
            }),
            "jt" => JumpTable::with_number(num).and_then(|jt| {
                if !self.contains_jt(jt) {
                    None
                } else {
                    Some(jt.into())
                }
            }),
            _ => None,
        })
    }

Look up a jump table entity.

Examples found in repository?
src/parser.rs (line 454)
453
454
455
456
457
458
459
    fn check_jt(&self, jt: JumpTable, loc: Location) -> ParseResult<()> {
        if !self.map.contains_jt(jt) {
            err!(loc, "undefined jump table {}", jt)
        } else {
            Ok(())
        }
    }
More examples
Hide additional examples
src/sourcemap.rs (line 143)
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
    pub fn lookup_str(&self, name: &str) -> Option<AnyEntity> {
        split_entity_name(name).and_then(|(ent, num)| match ent {
            "v" => Value::with_number(num).and_then(|v| {
                if !self.contains_value(v) {
                    None
                } else {
                    Some(v.into())
                }
            }),
            "block" => Block::with_number(num).and_then(|block| {
                if !self.contains_block(block) {
                    None
                } else {
                    Some(block.into())
                }
            }),
            "ss" => StackSlot::with_number(num).and_then(|ss| {
                if !self.contains_ss(ss) {
                    None
                } else {
                    Some(ss.into())
                }
            }),
            "gv" => GlobalValue::with_number(num).and_then(|gv| {
                if !self.contains_gv(gv) {
                    None
                } else {
                    Some(gv.into())
                }
            }),
            "heap" => Heap::with_number(num).and_then(|heap| {
                if !self.contains_heap(heap) {
                    None
                } else {
                    Some(heap.into())
                }
            }),
            "table" => Table::with_number(num).and_then(|table| {
                if !self.contains_table(table) {
                    None
                } else {
                    Some(table.into())
                }
            }),
            "sig" => SigRef::with_number(num).and_then(|sig| {
                if !self.contains_sig(sig) {
                    None
                } else {
                    Some(sig.into())
                }
            }),
            "fn" => FuncRef::with_number(num).and_then(|fn_| {
                if !self.contains_fn(fn_) {
                    None
                } else {
                    Some(fn_.into())
                }
            }),
            "jt" => JumpTable::with_number(num).and_then(|jt| {
                if !self.contains_jt(jt) {
                    None
                } else {
                    Some(jt.into())
                }
            }),
            _ => None,
        })
    }

Look up a constant entity.

Examples found in repository?
src/parser.rs (line 484)
483
484
485
486
487
488
489
    fn check_constant(&self, c: Constant, loc: Location) -> ParseResult<()> {
        if !self.map.contains_constant(c) {
            err!(loc, "undefined constant {}", c)
        } else {
            Ok(())
        }
    }

Look up an entity by source name. Returns the entity reference corresponding to name, if it exists.

Get the source location where an entity was defined.

Examples found in repository?
src/parser.rs (line 2054)
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
    fn parse_function_body(&mut self, ctx: &mut Context) -> ParseResult<()> {
        while self.token() != Some(Token::RBrace) {
            self.parse_basic_block(ctx)?;
        }

        // Now that we've seen all defined values in the function, ensure that
        // all references refer to a definition.
        for block in &ctx.function.layout {
            for inst in ctx.function.layout.block_insts(block) {
                for value in ctx.function.dfg.inst_args(inst) {
                    if !ctx.map.contains_value(*value) {
                        return err!(
                            ctx.map.location(AnyEntity::Inst(inst)).unwrap(),
                            "undefined operand value {}",
                            value
                        );
                    }
                }
            }
        }

        for alias in &ctx.aliases {
            if !ctx.function.dfg.set_alias_type_for_parser(*alias) {
                let loc = ctx.map.location(AnyEntity::Value(*alias)).unwrap();
                return err!(loc, "alias cycle involving {}", alias);
            }
        }

        Ok(())
    }

Create a new empty SourceMap.

Examples found in repository?
src/parser.rs (line 253)
250
251
252
253
254
255
256
    fn new(f: Function) -> Self {
        Self {
            function: f,
            map: SourceMap::new(),
            aliases: Vec::new(),
        }
    }

Define the value entity.

Examples found in repository?
src/parser.rs (line 2186)
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
    fn parse_block_param(&mut self, ctx: &mut Context, block: Block) -> ParseResult<()> {
        // block-param ::= * Value(v) ":" Type(t) arg-loc?
        let v = self.match_value("block argument must be a value")?;
        let v_location = self.loc;
        // block-param ::= Value(v) * ":" Type(t) arg-loc?
        self.match_token(Token::Colon, "expected ':' after block argument")?;
        // block-param ::= Value(v) ":" * Type(t) arg-loc?

        while ctx.function.dfg.num_values() <= v.index() {
            ctx.function.dfg.make_invalid_value_for_parser();
        }

        let t = self.match_type("expected block argument type")?;
        // Allocate the block argument.
        ctx.function.dfg.append_block_param_for_parser(block, t, v);
        ctx.map.def_value(v, v_location)?;

        Ok(())
    }

    // Parse instruction results and return them.
    //
    // inst-results ::= Value(v) { "," Value(v) }
    //
    fn parse_inst_results(&mut self) -> ParseResult<SmallVec<[Value; 1]>> {
        // Result value numbers.
        let mut results = SmallVec::new();

        // instruction  ::=  * [inst-results "="] Opcode(opc) ["." Type] ...
        // inst-results ::= * Value(v) { "," Value(v) }
        if let Some(Token::Value(v)) = self.token() {
            self.consume();

            results.push(v);

            // inst-results ::= Value(v) * { "," Value(v) }
            while self.optional(Token::Comma) {
                // inst-results ::= Value(v) { "," * Value(v) }
                results.push(self.match_value("expected result value")?);
            }
        }

        Ok(results)
    }

    // Parse a value alias, and append it to `block`.
    //
    // value_alias ::= [inst-results] "->" Value(v)
    //
    fn parse_value_alias(&mut self, results: &[Value], ctx: &mut Context) -> ParseResult<()> {
        if results.len() != 1 {
            return err!(self.loc, "wrong number of aliases");
        }
        let result = results[0];
        let dest = self.match_value("expected value alias")?;

        // Allow duplicate definitions of aliases, as long as they are identical.
        if ctx.map.contains_value(result) {
            if let Some(old) = ctx.function.dfg.value_alias_dest_for_serialization(result) {
                if old != dest {
                    return err!(
                        self.loc,
                        "value {} is already defined as an alias with destination {}",
                        result,
                        old
                    );
                }
            } else {
                return err!(self.loc, "value {} is already defined");
            }
        } else {
            ctx.map.def_value(result, self.loc)?;
        }

        if !ctx.map.contains_value(dest) {
            return err!(self.loc, "value {} is not yet defined", dest);
        }

        ctx.function
            .dfg
            .make_value_alias_for_serialization(dest, result);

        ctx.aliases.push(result);
        Ok(())
    }

    // Parse an instruction, append it to `block`.
    //
    // instruction ::= [inst-results "="] Opcode(opc) ["." Type] ...
    //
    fn parse_instruction(
        &mut self,
        results: &[Value],
        srcloc: ir::SourceLoc,
        ctx: &mut Context,
        block: Block,
    ) -> ParseResult<()> {
        // Define the result values.
        for val in results {
            ctx.map.def_value(*val, self.loc)?;
        }

        // Collect comments for the next instruction.
        self.start_gathering_comments();

        // instruction ::=  [inst-results "="] * Opcode(opc) ["." Type] ...
        let opcode = if let Some(Token::Identifier(text)) = self.token() {
            match text.parse() {
                Ok(opc) => opc,
                Err(msg) => return err!(self.loc, "{}: '{}'", msg, text),
            }
        } else {
            return err!(self.loc, "expected instruction opcode");
        };
        let opcode_loc = self.loc;
        self.consume();

        // Look for a controlling type variable annotation.
        // instruction ::=  [inst-results "="] Opcode(opc) * ["." Type] ...
        let explicit_ctrl_type = if self.optional(Token::Dot) {
            if let Some(Token::Type(_t)) = self.token() {
                Some(self.match_type("expected type after 'opcode.'")?)
            } else {
                let dt = self.match_dt("expected dynamic type")?;
                self.concrete_from_dt(dt, ctx)
            }
        } else {
            None
        };

        // instruction ::=  [inst-results "="] Opcode(opc) ["." Type] * ...
        let inst_data = self.parse_inst_operands(ctx, opcode, explicit_ctrl_type)?;

        // We're done parsing the instruction now.
        //
        // We still need to check that the number of result values in the source matches the opcode
        // or function call signature. We also need to create values with the right type for all
        // the instruction results.
        let ctrl_typevar = self.infer_typevar(ctx, opcode, explicit_ctrl_type, &inst_data)?;
        let inst = ctx.function.dfg.make_inst(inst_data);
        let num_results =
            ctx.function
                .dfg
                .make_inst_results_for_parser(inst, ctrl_typevar, results);
        ctx.function.layout.append_inst(inst, block);
        ctx.map
            .def_entity(inst.into(), opcode_loc)
            .expect("duplicate inst references created");

        if !srcloc.is_default() {
            ctx.function.set_srcloc(inst, srcloc);
        }

        if results.len() != num_results {
            return err!(
                self.loc,
                "instruction produces {} result values, {} given",
                num_results,
                results.len()
            );
        }

        // Collect any trailing comments.
        self.token();
        self.claim_gathered_comments(inst);

        Ok(())
    }

Define the block entity.

Examples found in repository?
src/parser.rs (line 493)
492
493
494
495
496
497
498
499
    fn add_block(&mut self, block: Block, loc: Location) -> ParseResult<Block> {
        self.map.def_block(block, loc)?;
        while self.function.dfg.num_blocks() <= block.index() {
            self.function.dfg.make_block();
        }
        self.function.layout.append_block(block);
        Ok(block)
    }

Define the stack slot entity.

Examples found in repository?
src/parser.rs (line 260)
259
260
261
262
263
264
265
266
267
    fn add_ss(&mut self, ss: StackSlot, data: StackSlotData, loc: Location) -> ParseResult<()> {
        self.map.def_ss(ss, loc)?;
        while self.function.sized_stack_slots.next_key().index() <= ss.index() {
            self.function
                .create_sized_stack_slot(StackSlotData::new(StackSlotKind::ExplicitSlot, 0));
        }
        self.function.sized_stack_slots[ss] = data;
        Ok(())
    }

Define the dynamic stack slot entity.

Examples found in repository?
src/parser.rs (line 285)
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
    fn add_dss(
        &mut self,
        ss: DynamicStackSlot,
        data: DynamicStackSlotData,
        loc: Location,
    ) -> ParseResult<()> {
        self.map.def_dss(ss, loc)?;
        while self.function.dynamic_stack_slots.next_key().index() <= ss.index() {
            self.function
                .create_dynamic_stack_slot(DynamicStackSlotData::new(
                    StackSlotKind::ExplicitDynamicSlot,
                    data.dyn_ty,
                ));
        }
        self.function.dynamic_stack_slots[ss] = data;
        Ok(())
    }

Define the dynamic type entity.

Examples found in repository?
src/parser.rs (line 308)
307
308
309
310
311
312
313
314
315
316
317
    fn add_dt(&mut self, dt: DynamicType, data: DynamicTypeData, loc: Location) -> ParseResult<()> {
        self.map.def_dt(dt, loc)?;
        while self.function.dfg.dynamic_types.next_key().index() <= dt.index() {
            self.function.dfg.make_dynamic_ty(DynamicTypeData::new(
                data.base_vector_ty,
                data.dynamic_scale,
            ));
        }
        self.function.dfg.dynamic_types[dt] = data;
        Ok(())
    }

Define the global value entity.

Examples found in repository?
src/parser.rs (line 321)
320
321
322
323
324
325
326
327
328
329
330
331
332
    fn add_gv(&mut self, gv: GlobalValue, data: GlobalValueData, loc: Location) -> ParseResult<()> {
        self.map.def_gv(gv, loc)?;
        while self.function.global_values.next_key().index() <= gv.index() {
            self.function.create_global_value(GlobalValueData::Symbol {
                name: ExternalName::testcase(""),
                offset: Imm64::new(0),
                colocated: false,
                tls: false,
            });
        }
        self.function.global_values[gv] = data;
        Ok(())
    }

Define the heap entity.

Examples found in repository?
src/parser.rs (line 345)
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
    fn add_heap(&mut self, heap: Heap, data: HeapData, loc: Location) -> ParseResult<()> {
        self.map.def_heap(heap, loc)?;
        while self.function.heaps.next_key().index() <= heap.index() {
            self.function.create_heap(HeapData {
                base: GlobalValue::reserved_value(),
                min_size: Uimm64::new(0),
                offset_guard_size: Uimm64::new(0),
                style: HeapStyle::Static {
                    bound: Uimm64::new(0),
                },
                index_type: INVALID,
            });
        }
        self.function.heaps[heap] = data;
        Ok(())
    }

Define the table entity.

Examples found in repository?
src/parser.rs (line 382)
371
372
373
374
375
376
377
378
379
380
381
382
383
    fn add_table(&mut self, table: Table, data: TableData, loc: Location) -> ParseResult<()> {
        while self.function.tables.next_key().index() <= table.index() {
            self.function.create_table(TableData {
                base_gv: GlobalValue::reserved_value(),
                min_size: Uimm64::new(0),
                bound_gv: GlobalValue::reserved_value(),
                element_size: Uimm64::new(0),
                index_type: INVALID,
            });
        }
        self.function.tables[table] = data;
        self.map.def_table(table, loc)
    }

Define the signature entity.

Examples found in repository?
src/parser.rs (line 402)
395
396
397
398
399
400
401
402
403
404
405
406
407
408
    fn add_sig(
        &mut self,
        sig: SigRef,
        data: Signature,
        loc: Location,
        defaultcc: CallConv,
    ) -> ParseResult<()> {
        self.map.def_sig(sig, loc)?;
        while self.function.dfg.signatures.next_key().index() <= sig.index() {
            self.function.import_signature(Signature::new(defaultcc));
        }
        self.function.dfg.signatures[sig] = data;
        Ok(())
    }

Define the external function entity.

Examples found in repository?
src/parser.rs (line 421)
420
421
422
423
424
425
426
427
428
429
430
431
    fn add_fn(&mut self, fn_: FuncRef, data: ExtFuncData, loc: Location) -> ParseResult<()> {
        self.map.def_fn(fn_, loc)?;
        while self.function.dfg.ext_funcs.next_key().index() <= fn_.index() {
            self.function.import_function(ExtFuncData {
                name: ExternalName::testcase(""),
                signature: SigRef::reserved_value(),
                colocated: false,
            });
        }
        self.function.dfg.ext_funcs[fn_] = data;
        Ok(())
    }

Define the jump table entity.

Examples found in repository?
src/parser.rs (line 444)
443
444
445
446
447
448
449
450
    fn add_jt(&mut self, jt: JumpTable, data: JumpTableData, loc: Location) -> ParseResult<()> {
        self.map.def_jt(jt, loc)?;
        while self.function.jump_tables.next_key().index() <= jt.index() {
            self.function.create_jump_table(JumpTableData::new());
        }
        self.function.jump_tables[jt] = data;
        Ok(())
    }

Define the jump table entity.

Examples found in repository?
src/parser.rs (line 468)
462
463
464
465
466
467
468
469
470
471
    fn add_constant(
        &mut self,
        constant: Constant,
        data: ConstantData,
        loc: Location,
    ) -> ParseResult<()> {
        self.map.def_constant(constant, loc)?;
        self.function.dfg.constants.set(constant, data);
        Ok(())
    }

Define an entity. This can be used for instructions whose numbers never appear in source, or implicitly defined signatures.

Examples found in repository?
src/sourcemap.rs (line 169)
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
    pub fn def_value(&mut self, entity: Value, loc: Location) -> ParseResult<()> {
        self.def_entity(entity.into(), loc)
    }

    /// Define the block `entity`.
    pub fn def_block(&mut self, entity: Block, loc: Location) -> ParseResult<()> {
        self.def_entity(entity.into(), loc)
    }

    /// Define the stack slot `entity`.
    pub fn def_ss(&mut self, entity: StackSlot, loc: Location) -> ParseResult<()> {
        self.def_entity(entity.into(), loc)
    }

    /// Define the dynamic stack slot `entity`.
    pub fn def_dss(&mut self, entity: DynamicStackSlot, loc: Location) -> ParseResult<()> {
        self.def_entity(entity.into(), loc)
    }

    /// Define the dynamic type `entity`.
    pub fn def_dt(&mut self, entity: DynamicType, loc: Location) -> ParseResult<()> {
        self.def_entity(entity.into(), loc)
    }

    /// Define the global value `entity`.
    pub fn def_gv(&mut self, entity: GlobalValue, loc: Location) -> ParseResult<()> {
        self.def_entity(entity.into(), loc)
    }

    /// Define the heap `entity`.
    pub fn def_heap(&mut self, entity: Heap, loc: Location) -> ParseResult<()> {
        self.def_entity(entity.into(), loc)
    }

    /// Define the table `entity`.
    pub fn def_table(&mut self, entity: Table, loc: Location) -> ParseResult<()> {
        self.def_entity(entity.into(), loc)
    }

    /// Define the signature `entity`.
    pub fn def_sig(&mut self, entity: SigRef, loc: Location) -> ParseResult<()> {
        self.def_entity(entity.into(), loc)
    }

    /// Define the external function `entity`.
    pub fn def_fn(&mut self, entity: FuncRef, loc: Location) -> ParseResult<()> {
        self.def_entity(entity.into(), loc)
    }

    /// Define the jump table `entity`.
    pub fn def_jt(&mut self, entity: JumpTable, loc: Location) -> ParseResult<()> {
        self.def_entity(entity.into(), loc)
    }

    /// Define the jump table `entity`.
    pub fn def_constant(&mut self, entity: Constant, loc: Location) -> ParseResult<()> {
        self.def_entity(entity.into(), loc)
    }
More examples
Hide additional examples
src/parser.rs (line 1917)
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
    fn parse_function_decl(&mut self, ctx: &mut Context) -> ParseResult<(FuncRef, ExtFuncData)> {
        let fn_ = self.match_fn("expected function number: fn«n»")?;
        self.match_token(Token::Equal, "expected '=' in function decl")?;

        let loc = self.loc;

        // function-decl ::= FuncRef(fnref) "=" * ["colocated"] name function-decl-sig
        let colocated = self.optional(Token::Identifier("colocated"));

        // function-decl ::= FuncRef(fnref) "=" ["colocated"] * name function-decl-sig
        let name = self.parse_external_name()?;

        // function-decl ::= FuncRef(fnref) "=" ["colocated"] name * function-decl-sig
        let data = match self.token() {
            Some(Token::LPar) => {
                // function-decl ::= FuncRef(fnref) "=" ["colocated"] name * signature
                let sig = self.parse_signature()?;
                let sigref = ctx.function.import_signature(sig);
                ctx.map
                    .def_entity(sigref.into(), loc)
                    .expect("duplicate SigRef entities created");
                ExtFuncData {
                    name,
                    signature: sigref,
                    colocated,
                }
            }
            Some(Token::SigRef(sig_src)) => {
                let sig = match SigRef::with_number(sig_src) {
                    None => {
                        return err!(self.loc, "attempted to use invalid signature ss{}", sig_src);
                    }
                    Some(sig) => sig,
                };
                ctx.check_sig(sig, self.loc)?;
                self.consume();
                ExtFuncData {
                    name,
                    signature: sig,
                    colocated,
                }
            }
            _ => return err!(self.loc, "expected 'function' or sig«n» in function decl"),
        };

        // Collect any trailing comments.
        self.token();
        self.claim_gathered_comments(fn_);

        Ok((fn_, data))
    }

    // Parse a jump table decl.
    //
    // jump-table-decl ::= * JumpTable(jt) "=" "jump_table" "[" jt-entry {"," jt-entry} "]"
    fn parse_jump_table_decl(&mut self) -> ParseResult<(JumpTable, JumpTableData)> {
        let jt = self.match_jt()?;
        self.match_token(Token::Equal, "expected '=' in jump_table decl")?;
        self.match_identifier("jump_table", "expected 'jump_table'")?;
        self.match_token(Token::LBracket, "expected '[' before jump table contents")?;

        let mut data = JumpTableData::new();

        // jump-table-decl ::= JumpTable(jt) "=" "jump_table" "[" * Block(dest) {"," Block(dest)} "]"
        match self.token() {
            Some(Token::Block(dest)) => {
                self.consume();
                data.push_entry(dest);

                loop {
                    match self.token() {
                        Some(Token::Comma) => {
                            self.consume();
                            if let Some(Token::Block(dest)) = self.token() {
                                self.consume();
                                data.push_entry(dest);
                            } else {
                                return err!(self.loc, "expected jump_table entry");
                            }
                        }
                        Some(Token::RBracket) => break,
                        _ => return err!(self.loc, "expected ']' after jump table contents"),
                    }
                }
            }
            Some(Token::RBracket) => (),
            _ => return err!(self.loc, "expected jump_table entry"),
        }

        self.consume();

        // Collect any trailing comments.
        self.token();
        self.claim_gathered_comments(jt);

        Ok((jt, data))
    }

    // Parse a constant decl.
    //
    // constant-decl ::= * Constant(c) "=" ty? "[" literal {"," literal} "]"
    fn parse_constant_decl(&mut self) -> ParseResult<(Constant, ConstantData)> {
        let name = self.match_constant()?;
        self.match_token(Token::Equal, "expected '=' in constant decl")?;
        let data = if let Some(Token::Type(_)) = self.token() {
            let ty = self.match_type("expected type of constant")?;
            self.match_uimm128(ty)
        } else {
            self.match_constant_data()
        }?;

        // Collect any trailing comments.
        self.token();
        self.claim_gathered_comments(name);

        Ok((name, data))
    }

    // Parse a stack limit decl
    //
    // stack-limit-decl ::= * StackLimit "=" GlobalValue(gv)
    fn parse_stack_limit_decl(&mut self) -> ParseResult<GlobalValue> {
        self.match_stack_limit()?;
        self.match_token(Token::Equal, "expected '=' in stack limit decl")?;
        let limit = match self.token() {
            Some(Token::GlobalValue(base_num)) => match GlobalValue::with_number(base_num) {
                Some(gv) => gv,
                None => return err!(self.loc, "invalid global value number for stack limit"),
            },
            _ => return err!(self.loc, "expected global value"),
        };
        self.consume();

        // Collect any trailing comments.
        self.token();
        self.claim_gathered_comments(AnyEntity::StackLimit);

        Ok(limit)
    }

    // Parse a function body, add contents to `ctx`.
    //
    // function-body ::= * { extended-basic-block }
    //
    fn parse_function_body(&mut self, ctx: &mut Context) -> ParseResult<()> {
        while self.token() != Some(Token::RBrace) {
            self.parse_basic_block(ctx)?;
        }

        // Now that we've seen all defined values in the function, ensure that
        // all references refer to a definition.
        for block in &ctx.function.layout {
            for inst in ctx.function.layout.block_insts(block) {
                for value in ctx.function.dfg.inst_args(inst) {
                    if !ctx.map.contains_value(*value) {
                        return err!(
                            ctx.map.location(AnyEntity::Inst(inst)).unwrap(),
                            "undefined operand value {}",
                            value
                        );
                    }
                }
            }
        }

        for alias in &ctx.aliases {
            if !ctx.function.dfg.set_alias_type_for_parser(*alias) {
                let loc = ctx.map.location(AnyEntity::Value(*alias)).unwrap();
                return err!(loc, "alias cycle involving {}", alias);
            }
        }

        Ok(())
    }

    // Parse a basic block, add contents to `ctx`.
    //
    // extended-basic-block ::= * block-header { instruction }
    // block-header         ::= Block(block) [block-params] [block-flags] ":"
    // block-flags          ::= [Cold]
    //
    fn parse_basic_block(&mut self, ctx: &mut Context) -> ParseResult<()> {
        // Collect comments for the next block.
        self.start_gathering_comments();

        let block_num = self.match_block("expected block header")?;
        let block = ctx.add_block(block_num, self.loc)?;

        if block_num.as_u32() >= MAX_BLOCKS_IN_A_FUNCTION {
            return Err(self.error("too many blocks"));
        }

        if self.token() == Some(Token::LPar) {
            self.parse_block_params(ctx, block)?;
        }

        if self.optional(Token::Cold) {
            ctx.set_cold_block(block);
        }

        self.match_token(Token::Colon, "expected ':' after block parameters")?;

        // Collect any trailing comments.
        self.token();
        self.claim_gathered_comments(block);

        // extended-basic-block ::= block-header * { instruction }
        while match self.token() {
            Some(Token::Value(_))
            | Some(Token::Identifier(_))
            | Some(Token::LBracket)
            | Some(Token::SourceLoc(_)) => true,
            _ => false,
        } {
            let srcloc = self.optional_srcloc()?;

            // We need to parse instruction results here because they are shared
            // between the parsing of value aliases and the parsing of instructions.
            //
            // inst-results ::= Value(v) { "," Value(v) }
            let results = self.parse_inst_results()?;

            for result in &results {
                while ctx.function.dfg.num_values() <= result.index() {
                    ctx.function.dfg.make_invalid_value_for_parser();
                }
            }

            match self.token() {
                Some(Token::Arrow) => {
                    self.consume();
                    self.parse_value_alias(&results, ctx)?;
                }
                Some(Token::Equal) => {
                    self.consume();
                    self.parse_instruction(&results, srcloc, ctx, block)?;
                }
                _ if !results.is_empty() => return err!(self.loc, "expected -> or ="),
                _ => self.parse_instruction(&results, srcloc, ctx, block)?,
            }
        }

        Ok(())
    }

    // Parse parenthesized list of block parameters. Returns a vector of (u32, Type) pairs with the
    // value numbers of the defined values and the defined types.
    //
    // block-params ::= * "(" block-param { "," block-param } ")"
    fn parse_block_params(&mut self, ctx: &mut Context, block: Block) -> ParseResult<()> {
        // block-params ::= * "(" block-param { "," block-param } ")"
        self.match_token(Token::LPar, "expected '(' before block parameters")?;

        // block-params ::= "(" * block-param { "," block-param } ")"
        self.parse_block_param(ctx, block)?;

        // block-params ::= "(" block-param * { "," block-param } ")"
        while self.optional(Token::Comma) {
            // block-params ::= "(" block-param { "," * block-param } ")"
            self.parse_block_param(ctx, block)?;
        }

        // block-params ::= "(" block-param { "," block-param } * ")"
        self.match_token(Token::RPar, "expected ')' after block parameters")?;

        Ok(())
    }

    // Parse a single block parameter declaration, and append it to `block`.
    //
    // block-param ::= * Value(v) ":" Type(t) arg-loc?
    // arg-loc ::= "[" value-location "]"
    //
    fn parse_block_param(&mut self, ctx: &mut Context, block: Block) -> ParseResult<()> {
        // block-param ::= * Value(v) ":" Type(t) arg-loc?
        let v = self.match_value("block argument must be a value")?;
        let v_location = self.loc;
        // block-param ::= Value(v) * ":" Type(t) arg-loc?
        self.match_token(Token::Colon, "expected ':' after block argument")?;
        // block-param ::= Value(v) ":" * Type(t) arg-loc?

        while ctx.function.dfg.num_values() <= v.index() {
            ctx.function.dfg.make_invalid_value_for_parser();
        }

        let t = self.match_type("expected block argument type")?;
        // Allocate the block argument.
        ctx.function.dfg.append_block_param_for_parser(block, t, v);
        ctx.map.def_value(v, v_location)?;

        Ok(())
    }

    // Parse instruction results and return them.
    //
    // inst-results ::= Value(v) { "," Value(v) }
    //
    fn parse_inst_results(&mut self) -> ParseResult<SmallVec<[Value; 1]>> {
        // Result value numbers.
        let mut results = SmallVec::new();

        // instruction  ::=  * [inst-results "="] Opcode(opc) ["." Type] ...
        // inst-results ::= * Value(v) { "," Value(v) }
        if let Some(Token::Value(v)) = self.token() {
            self.consume();

            results.push(v);

            // inst-results ::= Value(v) * { "," Value(v) }
            while self.optional(Token::Comma) {
                // inst-results ::= Value(v) { "," * Value(v) }
                results.push(self.match_value("expected result value")?);
            }
        }

        Ok(results)
    }

    // Parse a value alias, and append it to `block`.
    //
    // value_alias ::= [inst-results] "->" Value(v)
    //
    fn parse_value_alias(&mut self, results: &[Value], ctx: &mut Context) -> ParseResult<()> {
        if results.len() != 1 {
            return err!(self.loc, "wrong number of aliases");
        }
        let result = results[0];
        let dest = self.match_value("expected value alias")?;

        // Allow duplicate definitions of aliases, as long as they are identical.
        if ctx.map.contains_value(result) {
            if let Some(old) = ctx.function.dfg.value_alias_dest_for_serialization(result) {
                if old != dest {
                    return err!(
                        self.loc,
                        "value {} is already defined as an alias with destination {}",
                        result,
                        old
                    );
                }
            } else {
                return err!(self.loc, "value {} is already defined");
            }
        } else {
            ctx.map.def_value(result, self.loc)?;
        }

        if !ctx.map.contains_value(dest) {
            return err!(self.loc, "value {} is not yet defined", dest);
        }

        ctx.function
            .dfg
            .make_value_alias_for_serialization(dest, result);

        ctx.aliases.push(result);
        Ok(())
    }

    // Parse an instruction, append it to `block`.
    //
    // instruction ::= [inst-results "="] Opcode(opc) ["." Type] ...
    //
    fn parse_instruction(
        &mut self,
        results: &[Value],
        srcloc: ir::SourceLoc,
        ctx: &mut Context,
        block: Block,
    ) -> ParseResult<()> {
        // Define the result values.
        for val in results {
            ctx.map.def_value(*val, self.loc)?;
        }

        // Collect comments for the next instruction.
        self.start_gathering_comments();

        // instruction ::=  [inst-results "="] * Opcode(opc) ["." Type] ...
        let opcode = if let Some(Token::Identifier(text)) = self.token() {
            match text.parse() {
                Ok(opc) => opc,
                Err(msg) => return err!(self.loc, "{}: '{}'", msg, text),
            }
        } else {
            return err!(self.loc, "expected instruction opcode");
        };
        let opcode_loc = self.loc;
        self.consume();

        // Look for a controlling type variable annotation.
        // instruction ::=  [inst-results "="] Opcode(opc) * ["." Type] ...
        let explicit_ctrl_type = if self.optional(Token::Dot) {
            if let Some(Token::Type(_t)) = self.token() {
                Some(self.match_type("expected type after 'opcode.'")?)
            } else {
                let dt = self.match_dt("expected dynamic type")?;
                self.concrete_from_dt(dt, ctx)
            }
        } else {
            None
        };

        // instruction ::=  [inst-results "="] Opcode(opc) ["." Type] * ...
        let inst_data = self.parse_inst_operands(ctx, opcode, explicit_ctrl_type)?;

        // We're done parsing the instruction now.
        //
        // We still need to check that the number of result values in the source matches the opcode
        // or function call signature. We also need to create values with the right type for all
        // the instruction results.
        let ctrl_typevar = self.infer_typevar(ctx, opcode, explicit_ctrl_type, &inst_data)?;
        let inst = ctx.function.dfg.make_inst(inst_data);
        let num_results =
            ctx.function
                .dfg
                .make_inst_results_for_parser(inst, ctrl_typevar, results);
        ctx.function.layout.append_inst(inst, block);
        ctx.map
            .def_entity(inst.into(), opcode_loc)
            .expect("duplicate inst references created");

        if !srcloc.is_default() {
            ctx.function.set_srcloc(inst, srcloc);
        }

        if results.len() != num_results {
            return err!(
                self.loc,
                "instruction produces {} result values, {} given",
                num_results,
                results.len()
            );
        }

        // Collect any trailing comments.
        self.token();
        self.claim_gathered_comments(inst);

        Ok(())
    }

Trait Implementations§

Formats the value using the given formatter. Read more
Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.