Struct evmil::Compiler

source ·
pub struct Compiler<'a> { /* private fields */ }

Implementations§

Examples found in repository?
src/bytecode.rs (line 131)
129
130
131
132
133
134
135
136
137
138
fn try_from(terms: &[Term]) -> Result<Bytecode,compiler::Error> {
    let mut bytecode = Bytecode::new();
    let mut compiler = Compiler::new(&mut bytecode);
    // Translate statements one-by-one
    for t in terms {
        compiler.translate(t)?;
    }
    // Done
    Ok(bytecode)
}

Get the underlying bytecode label for a given label identifier. If necessary, this allocates that label in the Bytecode object.

Examples found in repository?
src/compiler.rs (line 155)
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
    fn translate_goto(&mut self, label: &str) -> Result {
        // Allocate labels branch target
        let lab = self.label(label);
        // Translate unconditional branch
        self.bytecode.push(Instruction::PUSHL(lab));
        self.bytecode.push(Instruction::JUMP);
        //
        Ok(())
    }

    fn translate_ifgoto(&mut self, expr: &Term, label: &str) -> Result {
        // Allocate labels for true/false outcomes
        let lab = self.label(label);
        // Translate conditional branch
        self.translate_conditional(expr,Some(lab),None)
    }

    fn translate_label(&mut self, label: &str) -> Result {
        // Determine underlying index of label
        let lab = self.label(label);
        // Construct corresponding JumpDest
        self.bytecode.push(Instruction::JUMPDEST(lab));
        // Done
        Ok(())
    }
Examples found in repository?
src/bytecode.rs (line 134)
129
130
131
132
133
134
135
136
137
138
fn try_from(terms: &[Term]) -> Result<Bytecode,compiler::Error> {
    let mut bytecode = Bytecode::new();
    let mut compiler = Compiler::new(&mut bytecode);
    // Translate statements one-by-one
    for t in terms {
        compiler.translate(t)?;
    }
    // Done
    Ok(bytecode)
}
More examples
Hide additional examples
src/compiler.rs (line 108)
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
    fn translate_assignment(&mut self, lhs: &Term, rhs: &Term) -> Result {
        // Translate value being assigned
        self.translate(rhs)?;
        // Translate assignent itself
        match lhs {
            Term::ArrayAccess(src,idx) => {
                self.translate_assignment_array(&src,&idx)?;
            }
            _ => {
                return Err(Error::InvalidLVal);
            }
        }
        //
        Ok(())
    }

    fn translate_assignment_array(&mut self, src: &Term, index: &Term) -> Result {
        match src {
            Term::MemoryAccess(r) => {
                self.translate_assignment_memory(*r,index)
            }
            _ => {
                Err(Error::InvalidMemoryAccess)
            }
        }
    }

    fn translate_assignment_memory(&mut self, region: Region, address: &Term) -> Result {
        // Translate index expression
        self.translate(address)?;
        // Dispatch based on region
        match region {
            Region::Memory => self.bytecode.push(Instruction::MSTORE),
            Region::Storage => self.bytecode.push(Instruction::SSTORE),
            _ => {
                return Err(Error::InvalidMemoryAccess);
            }
        };
        //
        Ok(())
    }

    fn translate_fail(&mut self) -> Result {
        self.bytecode.push(Instruction::INVALID);
        Ok(())
    }

    fn translate_goto(&mut self, label: &str) -> Result {
        // Allocate labels branch target
        let lab = self.label(label);
        // Translate unconditional branch
        self.bytecode.push(Instruction::PUSHL(lab));
        self.bytecode.push(Instruction::JUMP);
        //
        Ok(())
    }

    fn translate_ifgoto(&mut self, expr: &Term, label: &str) -> Result {
        // Allocate labels for true/false outcomes
        let lab = self.label(label);
        // Translate conditional branch
        self.translate_conditional(expr,Some(lab),None)
    }

    fn translate_label(&mut self, label: &str) -> Result {
        // Determine underlying index of label
        let lab = self.label(label);
        // Construct corresponding JumpDest
        self.bytecode.push(Instruction::JUMPDEST(lab));
        // Done
        Ok(())
    }

    fn translate_revert(&mut self, exprs: &[Term]) -> Result {
        self.translate_succeed_revert(Instruction::REVERT,exprs)
    }

    fn translate_succeed(&mut self, exprs: &[Term]) -> Result {
        if exprs.len() == 0 {
            self.bytecode.push(Instruction::STOP);
            Ok(())
        } else {
            self.translate_succeed_revert(Instruction::RETURN,exprs)
        }
    }

    fn translate_succeed_revert(&mut self, insn: Instruction, exprs: &[Term]) -> Result {
        if exprs.len() == 0 {
            self.bytecode.push(Instruction::PUSH(vec![0]));
            self.bytecode.push(Instruction::PUSH(vec![0]));
        } else {
            for i in 0 .. exprs.len() {
                let addr = (i * 0x20) as u128;
                self.translate(&exprs[i])?;
                self.bytecode.push(make_push(addr)?);
                self.bytecode.push(Instruction::MSTORE);
            }
            let len = (exprs.len() * 0x20) as u128;
            self.bytecode.push(Instruction::PUSH(vec![0]));
            self.bytecode.push(make_push(len)?);
        }
        self.bytecode.push(insn);
        Ok(())
    }

    fn translate_stop(&mut self) -> Result {
        self.bytecode.push(Instruction::STOP);
        Ok(())
    }

    // ============================================================================
    // Conditional Expressions
    // ============================================================================

    /// Translate a conditional expression using _short circuiting_
    /// semantics.  Since implementing short circuiting requires
    /// branching, we can exploit this to optimise other translations
    /// and reduce the number of branches required.  To do that, this
    /// method requires either a `true` target or a `false` target.
    /// If a `true` target is provided then, if the condition
    /// evaluates to something other than `0` (i.e. is `true`),
    /// control is transfered to this target.  Likewise, if the
    /// condition evaluates to `0` (i.e. `false`) the control is
    /// transfered to the `false` target.
    fn translate_conditional(&mut self, expr: &Term, true_lab: Option<usize>, false_lab: Option<usize>) -> Result {
	match expr {
	    Term::Binary(BinOp::LogicalAnd,l,r) => self.translate_conditional_conjunct(l,r,true_lab,false_lab),
	    Term::Binary(BinOp::LogicalOr,l,r) => self.translate_conditional_disjunct(l,r,true_lab,false_lab),		    _ => {
		self.translate_conditional_other(expr,true_lab,false_lab)
	    }
	}
    }

    /// Translate a logical conjunction as a conditional. Since
    /// such connectives require short circuiting, these must be
    /// implementing using branches.
    fn translate_conditional_conjunct(&mut self, lhs: &Term, rhs: &Term, true_lab: Option<usize>, false_lab: Option<usize>) -> Result {
	match (true_lab,false_lab) {
	    (Some(_),None) => {
		// Harder case
		let lab = self.bytecode.fresh_label();
		self.translate_conditional(lhs, None, Some(lab))?;
		self.translate_conditional(rhs, true_lab, None)?;
		self.bytecode.push(Instruction::JUMPDEST(lab));
	    }
	    (None,Some(_)) => {
		// Easy case
		self.translate_conditional(lhs, None, false_lab)?;
		self.translate_conditional(rhs, true_lab, false_lab)?;
	    }
	    (_,_) => unreachable!()
	}
        // Done
        Ok(())
    }

    /// Translate a logical disjunction as a conditional. Since
    /// such connectives require short circuiting, these must be
    /// implementing using branches.
    fn translate_conditional_disjunct(&mut self, lhs: &Term, rhs: &Term, true_lab: Option<usize>, false_lab: Option<usize>) -> Result {
	match (true_lab,false_lab) {
	    (None,Some(_)) => {
		// Harder case
		let lab = self.bytecode.fresh_label();
		self.translate_conditional(lhs, Some(lab), None)?;
		self.translate_conditional(rhs, None, false_lab)?;
		self.bytecode.push(Instruction::JUMPDEST(lab));
	    }
	    (Some(_),None) => {
		// Easy case
		self.translate_conditional(lhs, true_lab, None)?;
		self.translate_conditional(rhs, true_lab, false_lab)?;
	    }
	    (_,_) => unreachable!()
	}
        // Done
        Ok(())
    }

    /// Translate a conditional expression which cannot be translated
    /// by exploiting branches.  In such case, we have to generate the
    /// boolean value and dispatch based on that.
    fn translate_conditional_other(&mut self, expr: &Term, true_lab: Option<usize>, false_lab: Option<usize>) -> Result {
        // Translate conditional expression
        self.translate(expr)?;
        //
        match (true_lab,false_lab) {
            (Some(lab),None) => {
                self.bytecode.push(Instruction::PUSHL(lab));
                self.bytecode.push(Instruction::JUMPI);
            }
            (None,Some(lab)) => {
                self.bytecode.push(Instruction::ISZERO);
                self.bytecode.push(Instruction::PUSHL(lab));
                self.bytecode.push(Instruction::JUMPI);
            }
            (_,_) => {
                unreachable!("")
            }
        }
        //
        Ok(())
    }

    // ============================================================================
    // Binary Expressions
    // ============================================================================

    /// Translate a binary operation.  Observe that logical operations
    /// exhibit _short-circuit behaviour_.
    fn translate_binary(&mut self, bop: BinOp, lhs: &Term, rhs: &Term) -> Result {
        match bop {
            BinOp::LogicalAnd | BinOp::LogicalOr => {
                self.translate_logical_connective(bop,lhs,rhs)
            }
            _ => {
                self.translate_binary_arithmetic(bop,lhs,rhs)
            }
        }
    }

    /// Translate one of the logical connectives (e.g. `&&` or `||`).
    /// These are more challenging than standard binary operators because
    /// they exhibit _short circuiting behaviour_.
    fn translate_logical_connective(&mut self, bop: BinOp, lhs: &Term, rhs: &Term) -> Result {
        self.translate(lhs)?;
        self.bytecode.push(Instruction::DUP(1));
        if bop == BinOp::LogicalAnd {
            self.bytecode.push(Instruction::ISZERO);
        }
        // Allocate fresh label
        let lab = self.bytecode.fresh_label();
        self.bytecode.push(Instruction::PUSHL(lab));
        self.bytecode.push(Instruction::JUMPI);
        self.bytecode.push(Instruction::POP);
        self.translate(rhs)?;
        self.bytecode.push(Instruction::JUMPDEST(lab));
        // Done
        Ok(())
    }

    /// Translate a binary arithmetic operation or comparison.  This is
    /// pretty straightforward, as we just load items on the stack and
    /// perform the op.  Observe that the right-hand side is loaded onto
    /// the stack first.
    fn translate_binary_arithmetic(&mut self, bop: BinOp, lhs: &Term, rhs: &Term) -> Result {
        self.translate(rhs)?;
        self.translate(lhs)?;
        //
        match bop {
            // standard
            BinOp::Add => self.bytecode.push(Instruction::ADD),
            BinOp::Subtract => self.bytecode.push(Instruction::SUB),
            BinOp::Divide => self.bytecode.push(Instruction::DIV),
            BinOp::Multiply => self.bytecode.push(Instruction::MUL),
            BinOp::Remainder => self.bytecode.push(Instruction::MOD),
            BinOp::Equals => self.bytecode.push(Instruction::EQ),
            BinOp::LessThan => self.bytecode.push(Instruction::LT),
            BinOp::GreaterThan => self.bytecode.push(Instruction::GT),
            // non-standard
            BinOp::NotEquals => {
                self.bytecode.push(Instruction::EQ);
                self.bytecode.push(Instruction::ISZERO);
            }
            BinOp::LessThanOrEquals => {
                self.bytecode.push(Instruction::GT);
                self.bytecode.push(Instruction::ISZERO);
            }
            BinOp::GreaterThanOrEquals => {
                self.bytecode.push(Instruction::LT);
                self.bytecode.push(Instruction::ISZERO);
            }
            _ => {
                unreachable!();
            }
        }
        //
        Ok(())
    }

    // ============================================================================
    // Array Access Expressions
    // ============================================================================

    /// Translate an array access of the form `src[index]`.  The actual
    /// form of the translation depends on whether its a direct access
    /// (e.g. to storage or memory), or indirect (e.g. via a pointer to
    /// memory).
    fn translate_array_access(&mut self, src: &Term, index: &Term) -> Result {
        match src {
            Term::MemoryAccess(r) => {
                self.translate_memory_access(*r,index)
            }
            _ => {
                Err(Error::InvalidMemoryAccess)
            }
        }
    }

    fn translate_memory_access(&mut self, region: Region, index: &Term) -> Result {
        // Translate index expression
        self.translate(index)?;
        // Dispatch based on region
        match region {
            Region::Memory => {
                self.bytecode.push(Instruction::MLOAD);
            }
            Region::Storage => {
                self.bytecode.push(Instruction::SLOAD);
            }
            Region::CallData => {
                self.bytecode.push(Instruction::CALLDATALOAD);
            }
        }
        //
        Ok(())
    }

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.