solang 0.3.5

Solang Solidity Compiler
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
// SPDX-License-Identifier: Apache-2.0

pub(super) mod target;
use crate::codegen::{cfg::ControlFlowGraph, HostFunctions, Options};

use crate::emit::cfg::emit_cfg;
use crate::{emit::Binary, sema::ast};
use funty::Fundamental;
use inkwell::{
    context::Context,
    module::{Linkage, Module},
    types::FunctionType,
};
use soroban_sdk::xdr::{
    Limited, Limits, ScEnvMetaEntry, ScEnvMetaEntryInterfaceVersion, ScSpecEntry,
    ScSpecFunctionInputV0, ScSpecFunctionV0, ScSpecTypeDef, ScSpecTypeVec, StringM, WriteXdr,
};

const SOROBAN_ENV_INTERFACE_VERSION: ScEnvMetaEntryInterfaceVersion =
    ScEnvMetaEntryInterfaceVersion {
        protocol: 23,
        pre_release: 0,
    };

impl HostFunctions {
    pub fn function_signature<'b>(&self, bin: &Binary<'b>) -> FunctionType<'b> {
        let ty = bin.context.i64_type();
        match self {
            HostFunctions::PutContractData => bin
                .context
                .i64_type()
                .fn_type(&[ty.into(), ty.into(), ty.into()], false),
            HostFunctions::GetContractData => bin
                .context
                .i64_type()
                .fn_type(&[ty.into(), ty.into()], false),
            HostFunctions::HasContractData => bin
                .context
                .i64_type()
                .fn_type(&[ty.into(), ty.into()], false),

            HostFunctions::DeleteContractData => bin
                .context
                .i64_type()
                .fn_type(&[ty.into(), ty.into()], false),
            // https://github.com/stellar/stellar-protocol/blob/2fdc77302715bc4a31a784aef1a797d466965024/core/cap-0046-03.md#ledger-host-functions-mod-l
            // ;; If the entry's TTL is below `threshold` ledgers, extend `live_until_ledger_seq` such that TTL == `extend_to`, where TTL is defined as live_until_ledger_seq - current ledger.
            // (func $extend_contract_data_ttl (param $k_val i64) (param $t_storage_type i64) (param $threshold_u32_val i64) (param $extend_to_u32_val i64) (result i64))
            HostFunctions::ExtendContractDataTtl => bin
                .context
                .i64_type()
                .fn_type(&[ty.into(), ty.into(), ty.into(), ty.into()], false),
            // ;; If the TTL for the current contract instance and code (if applicable) is below `threshold` ledgers, extend `live_until_ledger_seq` such that TTL == `extend_to`, where TTL is defined as live_until_ledger_seq - current ledger.
            // (func $extend_current_contract_instance_and_code_ttl (param $threshold_u32_val i64) (param $extend_to_u32_val i64) (result i64))
            HostFunctions::ExtendCurrentContractInstanceAndCodeTtl => bin
                .context
                .i64_type()
                .fn_type(&[ty.into(), ty.into()], false),
            HostFunctions::LogFromLinearMemory => bin
                .context
                .i64_type()
                .fn_type(&[ty.into(), ty.into(), ty.into(), ty.into()], false),
            HostFunctions::SymbolNewFromLinearMemory => bin
                .context
                .i64_type()
                .fn_type(&[ty.into(), ty.into()], false),
            HostFunctions::VectorNew => bin.context.i64_type().fn_type(&[], false),
            HostFunctions::BytesNew => bin.context.i64_type().fn_type(&[], false),
            HostFunctions::VecPopBack => bin.context.i64_type().fn_type(&[ty.into()], false),
            HostFunctions::VecGet => bin
                .context
                .i64_type()
                .fn_type(&[ty.into(), ty.into()], false),

            HostFunctions::VecPut => bin
                .context
                .i64_type()
                .fn_type(&[ty.into(), ty.into(), ty.into()], false),
            HostFunctions::Call => bin
                .context
                .i64_type()
                .fn_type(&[ty.into(), ty.into(), ty.into()], false),
            HostFunctions::VectorNewFromLinearMemory => bin
                .context
                .i64_type()
                .fn_type(&[ty.into(), ty.into()], false),
            HostFunctions::VecUnpackToLinearMemory => bin
                .context
                .i64_type()
                .fn_type(&[ty.into(), ty.into(), ty.into()], false),
            HostFunctions::ObjToU64 => bin.context.i64_type().fn_type(&[ty.into()], false),
            HostFunctions::ObjFromU64 => bin.context.i64_type().fn_type(&[ty.into()], false),
            HostFunctions::RequireAuth => bin.context.i64_type().fn_type(&[ty.into()], false),
            HostFunctions::AuthAsCurrContract => {
                bin.context.i64_type().fn_type(&[ty.into()], false)
            }
            HostFunctions::MapNewFromLinearMemory => bin
                .context
                .i64_type()
                .fn_type(&[ty.into(), ty.into(), ty.into()], false),

            HostFunctions::MapNew => bin.context.i64_type().fn_type(&[], false),

            HostFunctions::MapPut => bin
                .context
                .i64_type()
                .fn_type(&[ty.into(), ty.into(), ty.into()], false),

            HostFunctions::VecPushBack => bin
                .context
                .i64_type()
                .fn_type(&[ty.into(), ty.into()], false),

            HostFunctions::VecLen => bin.context.i64_type().fn_type(&[ty.into()], false),

            HostFunctions::StringNewFromLinearMemory => bin
                .context
                .i64_type()
                .fn_type(&[ty.into(), ty.into()], false),
            HostFunctions::StrKeyToAddr => bin.context.i64_type().fn_type(&[ty.into()], false),
            HostFunctions::GetLedgerTimestamp => bin.context.i64_type().fn_type(&[], false),
            HostFunctions::GetCurrentContractAddress => bin.context.i64_type().fn_type(&[], false),
            HostFunctions::ObjToI128Lo64 => bin.context.i64_type().fn_type(&[ty.into()], false),
            HostFunctions::ObjToI128Hi64 => bin.context.i64_type().fn_type(&[ty.into()], false),
            HostFunctions::ObjToU128Lo64 => bin.context.i64_type().fn_type(&[ty.into()], false),
            HostFunctions::ObjToU128Hi64 => bin.context.i64_type().fn_type(&[ty.into()], false),
            HostFunctions::ObjFromI128Pieces => bin
                .context
                .i64_type()
                .fn_type(&[ty.into(), ty.into()], false),
            HostFunctions::ObjFromU128Pieces => bin
                .context
                .i64_type()
                .fn_type(&[ty.into(), ty.into()], false),
            HostFunctions::ObjToU256LoLo => bin.context.i64_type().fn_type(&[ty.into()], false),
            HostFunctions::ObjToU256LoHi => bin.context.i64_type().fn_type(&[ty.into()], false),
            HostFunctions::ObjToU256HiLo => bin.context.i64_type().fn_type(&[ty.into()], false),
            HostFunctions::ObjToU256HiHi => bin.context.i64_type().fn_type(&[ty.into()], false),
            HostFunctions::ObjFromU256Pieces => bin
                .context
                .i64_type()
                .fn_type(&[ty.into(), ty.into(), ty.into(), ty.into()], false),
            HostFunctions::ObjToI256LoLo => bin.context.i64_type().fn_type(&[ty.into()], false),
            HostFunctions::ObjToI256LoHi => bin.context.i64_type().fn_type(&[ty.into()], false),
            HostFunctions::ObjToI256HiLo => bin.context.i64_type().fn_type(&[ty.into()], false),
            HostFunctions::ObjToI256HiHi => bin.context.i64_type().fn_type(&[ty.into()], false),
            HostFunctions::ObjFromI256Pieces => bin
                .context
                .i64_type()
                .fn_type(&[ty.into(), ty.into(), ty.into(), ty.into()], false),
            HostFunctions::BytesNewFromLinearMemory => bin
                .context
                .i64_type()
                .fn_type(&[ty.into(), ty.into()], false),
            HostFunctions::BytesLen => bin.context.i64_type().fn_type(&[ty.into()], false),
            HostFunctions::BytesCopyToLinearMemory => bin
                .context
                .i64_type()
                .fn_type(&[ty.into(), ty.into(), ty.into(), ty.into()], false),
            HostFunctions::BytesGet => bin
                .context
                .i64_type()
                .fn_type(&[ty.into(), ty.into()], false),
            HostFunctions::BytesPut => bin
                .context
                .i64_type()
                .fn_type(&[ty.into(), ty.into(), ty.into()], false),
            HostFunctions::BytesPush => bin
                .context
                .i64_type()
                .fn_type(&[ty.into(), ty.into()], false),
            HostFunctions::BytesPop => bin.context.i64_type().fn_type(&[ty.into()], false),
            HostFunctions::StringLen => bin.context.i64_type().fn_type(&[ty.into()], false),
            HostFunctions::StringCopyToLinearMemory => bin
                .context
                .i64_type()
                .fn_type(&[ty.into(), ty.into(), ty.into(), ty.into()], false),
            HostFunctions::ContractEvent => bin
                .context
                .i64_type()
                .fn_type(&[ty.into(), ty.into()], false),
        }
    }
}

pub struct SorobanTarget;

impl SorobanTarget {
    fn vec_spec_type(ty: &ast::Type) -> ScSpecTypeDef {
        match ty {
            ast::Type::Array(nested, _) => {
                let nested = Self::vec_spec_type(nested.as_ref());
                ScSpecTypeDef::Vec(Box::new(ScSpecTypeVec {
                    element_type: Box::new(nested),
                }))
            }
            ast::Type::Uint(32) => ScSpecTypeDef::U32,
            ast::Type::Int(32) => ScSpecTypeDef::I32,
            ast::Type::Enum(_) => ScSpecTypeDef::U32,
            ast::Type::Uint(64) => ScSpecTypeDef::U64,
            ast::Type::Int(64) => ScSpecTypeDef::I64,
            ast::Type::Int(128) => ScSpecTypeDef::I128,
            ast::Type::Uint(128) => ScSpecTypeDef::U128,
            ast::Type::Bool => ScSpecTypeDef::Bool,
            ast::Type::Address(_) => ScSpecTypeDef::Address,
            ast::Type::Bytes(_) => ScSpecTypeDef::Bytes,
            ast::Type::String => ScSpecTypeDef::String,
            ast::Type::Ref(inner) => Self::vec_spec_type(inner.as_ref()),
            ast::Type::SorobanHandle(inner) => Self::vec_spec_type(inner.as_ref()),
            _ => panic!("unsupported array element type {ty:?}"),
        }
    }

    pub fn build<'a>(
        context: &'a Context,
        std_lib: &Module<'a>,
        contract: &'a ast::Contract,
        ns: &'a ast::Namespace,
        opt: &'a Options,
        contract_no: usize,
    ) -> Binary<'a> {
        let filename = ns.files[contract.loc.file_no()].file_name();
        let mut bin = Binary::new(
            context,
            ns,
            &contract.id.name,
            &filename,
            opt,
            std_lib,
            None,
        );

        let mut export_list = Vec::new();
        Self::declare_externals(&mut bin);
        Self::emit_functions_with_spec(contract, &mut bin, context, contract_no, &mut export_list);
        bin.internalize(export_list.as_slice());

        //Self::emit_initializer(&mut binary, ns, contract.constructors(ns).first());

        Self::emit_env_meta_entries(context, &mut bin, opt);

        bin
    }

    // In Soroban, the public functions specifications is embeded in the contract binary.
    // for each function, emit both the function spec entry and the function body.
    fn emit_functions_with_spec<'a>(
        contract: &'a ast::Contract,
        bin: &mut Binary<'a>,
        context: &'a Context,
        _contract_no: usize,
        export_list: &mut Vec<&'a str>,
    ) {
        let mut defines = Vec::new();

        for (cfg_no, cfg) in contract.cfg.iter().enumerate() {
            let ftype = bin.function_type(
                &cfg.params.iter().map(|p| p.ty.clone()).collect::<Vec<_>>(),
                &cfg.returns.iter().map(|p| p.ty.clone()).collect::<Vec<_>>(),
            );

            // For each function, determine the name and the linkage
            // Soroban has no dispatcher, so all externally addressable functions are exported and should be named the same as the original function name in the source code.
            // If there are duplicate function names, then the function name in the source is mangled to include the signature.

            // if func is a default constructor, then the function name is the contract name

            let linkage = if cfg.public {
                let name = if cfg.name.contains("::") {
                    // get the third part of the name which is the function name
                    cfg.name.split("::").collect::<Vec<&str>>()[2]
                } else {
                    &cfg.name
                };
                Self::emit_function_spec_entry(context, cfg, name.to_string(), bin);
                export_list.push(name);
                Linkage::External
            } else {
                Linkage::Internal
            };

            let func_decl = if let Some(func) = bin.module.get_function(&cfg.name) {
                // must not have a body yet
                assert_eq!(func.get_first_basic_block(), None);

                func
            } else {
                bin.module.add_function(&cfg.name, ftype, Some(linkage))
            };

            bin.functions.insert(cfg_no, func_decl);

            defines.push((func_decl, cfg));
        }

        let init_type = context.i64_type().fn_type(&[], false);
        bin.module
            .add_function("storage_initializer", init_type, None);

        for (func_decl, cfg) in defines {
            emit_cfg(&mut SorobanTarget, bin, contract, cfg, func_decl);
        }
    }

    fn emit_env_meta_entries<'a>(context: &'a Context, bin: &mut Binary<'a>, opt: &'a Options) {
        let mut meta = Limited::new(Vec::new(), Limits::none());
        let soroban_env_interface_version = opt.soroban_version;
        let soroban_env_interface_version = match soroban_env_interface_version {
            Some(version) => ScEnvMetaEntryInterfaceVersion {
                protocol: version.as_u32(),
                pre_release: 0,
            },
            None => SOROBAN_ENV_INTERFACE_VERSION,
        };
        ScEnvMetaEntry::ScEnvMetaKindInterfaceVersion(soroban_env_interface_version)
            .write_xdr(&mut meta)
            .expect("writing env meta interface version to xdr");
        Self::add_custom_section(context, &bin.module, "contractenvmetav0", meta.inner);
    }

    fn emit_function_spec_entry<'a>(
        context: &'a Context,
        cfg: &ControlFlowGraph,
        name: String,
        bin: &mut Binary<'a>,
    ) {
        if cfg.public && !cfg.is_placeholder() {
            // TODO: Emit custom type spec entries
            let mut spec = Limited::new(Vec::new(), Limits::none());
            ScSpecEntry::FunctionV0(ScSpecFunctionV0 {
                name: name
                    .try_into()
                    .unwrap_or_else(|_| panic!("function name {:?} exceeds limit", cfg.name)),
                inputs: cfg
                    .params
                    .iter()
                    .enumerate()
                    .map(|(i, p)| ScSpecFunctionInputV0 {
                        name: p
                            .id
                            .as_ref()
                            .map(|id| id.to_string())
                            .unwrap_or_else(|| i.to_string())
                            .try_into()
                            .expect("function input name exceeds limit"),
                        type_: {
                            let ty = match &p.ty {
                                ast::Type::Ref(ty) | ast::Type::SorobanHandle(ty) => ty.as_ref(),
                                _ => &p.ty,
                            };

                            match ty {
                                ast::Type::Uint(32) => ScSpecTypeDef::U32,
                                ast::Type::Int(32) => ScSpecTypeDef::I32,
                                ast::Type::Enum(_) => ScSpecTypeDef::U32,
                                ast::Type::Uint(64) => ScSpecTypeDef::U64,
                                &ast::Type::Int(64) => ScSpecTypeDef::I64,
                                ast::Type::Int(128) => ScSpecTypeDef::I128,
                                ast::Type::Uint(128) => ScSpecTypeDef::U128,
                                ast::Type::Int(256) => ScSpecTypeDef::I256,
                                ast::Type::Uint(256) => ScSpecTypeDef::U256,
                                ast::Type::Bool => ScSpecTypeDef::Bool,
                                ast::Type::Address(_) => ScSpecTypeDef::Address,
                                ast::Type::Bytes(_) | ast::Type::DynamicBytes => {
                                    ScSpecTypeDef::Bytes
                                }
                                ast::Type::String => ScSpecTypeDef::String,
                                ast::Type::Array(ty, _) => {
                                    let element = Self::vec_spec_type(ty.as_ref());

                                    ScSpecTypeDef::Vec(Box::new(ScSpecTypeVec {
                                        element_type: Box::new(element),
                                    }))
                                }
                                _ => panic!("unsupported input type {:?}", p.ty),
                            }
                        }, // TODO: Map type.
                        doc: StringM::default(), // TODO: Add doc.
                    })
                    .collect::<Vec<_>>()
                    .try_into()
                    .expect("function input count exceeds limit"),
                outputs: cfg
                    .returns
                    .iter()
                    .map(|return_type| {
                        let ret_type = return_type.ty.clone();
                        let ty = match ret_type {
                            ast::Type::Ref(ty) | ast::Type::SorobanHandle(ty) => *ty,
                            _ => ret_type,
                        };
                        match ty {
                            ast::Type::Uint(32) => ScSpecTypeDef::U32,
                            ast::Type::Int(32) => ScSpecTypeDef::I32,
                            ast::Type::Enum(_) => ScSpecTypeDef::U32,
                            ast::Type::Uint(64) => ScSpecTypeDef::U64,
                            ast::Type::Int(64) => ScSpecTypeDef::I64,
                            ast::Type::Int(128) => ScSpecTypeDef::I128,
                            ast::Type::Uint(128) => ScSpecTypeDef::U128,
                            ast::Type::Int(256) => ScSpecTypeDef::I256,
                            ast::Type::Uint(256) => ScSpecTypeDef::U256,
                            ast::Type::Int(_) => ScSpecTypeDef::I32,
                            ast::Type::Bool => ScSpecTypeDef::Bool,
                            ast::Type::Address(_) => ScSpecTypeDef::Address,
                            ast::Type::Bytes(_) | ast::Type::DynamicBytes => ScSpecTypeDef::Bytes,
                            ast::Type::String => ScSpecTypeDef::String,
                            ast::Type::Void => ScSpecTypeDef::Void,
                            ast::Type::Struct(_) => ScSpecTypeDef::Void, // TODO: Map struct types.
                            ast::Type::Array(elem, _) => {
                                let element = Self::vec_spec_type(elem.as_ref());
                                ScSpecTypeDef::Vec(Box::new(ScSpecTypeVec {
                                    element_type: Box::new(element),
                                }))
                            }
                            _ => panic!("unsupported return type {ty:?}"),
                        }
                    }) // TODO: Map type.
                    .collect::<Vec<_>>()
                    .try_into()
                    .expect("function output count exceeds limit"),
                doc: StringM::default(), // TODO: Add doc.
            })
            .write_xdr(&mut spec)
            .unwrap_or_else(|_| panic!("writing spec to xdr for function {}", cfg.name));

            Self::add_custom_section(context, &bin.module, "contractspecv0", spec.inner);
        }
    }

    fn add_custom_section<'a>(
        context: &'a Context,
        module: &Module<'a>,
        name: &'a str,
        value: Vec<u8>,
    ) {
        let value_str = unsafe {
            // TODO: Figure out the right way to generate the LLVM metadata for
            // a slice of bytes.
            String::from_utf8_unchecked(value)
        };

        module
            .add_global_metadata(
                "wasm.custom_sections",
                &context.metadata_node(&[
                    context.metadata_string(name).into(),
                    context.metadata_string(&value_str).into(),
                ]),
            )
            .expect("adding spec as metadata");
    }

    fn declare_externals(bin: &mut Binary) {
        let host_functions = [
            HostFunctions::PutContractData,
            HostFunctions::GetContractData,
            HostFunctions::HasContractData,
            HostFunctions::DeleteContractData,
            HostFunctions::ExtendContractDataTtl,
            HostFunctions::ExtendCurrentContractInstanceAndCodeTtl,
            HostFunctions::LogFromLinearMemory,
            HostFunctions::SymbolNewFromLinearMemory,
            HostFunctions::VectorNew,
            HostFunctions::BytesNew,
            HostFunctions::Call,
            HostFunctions::VectorNewFromLinearMemory,
            HostFunctions::VecUnpackToLinearMemory,
            HostFunctions::ObjToU64,
            HostFunctions::ObjFromU64,
            HostFunctions::PutContractData,
            HostFunctions::ObjToI128Lo64,
            HostFunctions::ObjToI128Hi64,
            HostFunctions::ObjToU128Lo64,
            HostFunctions::ObjToU128Hi64,
            HostFunctions::ObjFromI128Pieces,
            HostFunctions::ObjFromU128Pieces,
            HostFunctions::ObjToU256LoLo,
            HostFunctions::ObjToU256LoHi,
            HostFunctions::ObjToU256HiLo,
            HostFunctions::ObjToU256HiHi,
            HostFunctions::ObjFromU256Pieces,
            HostFunctions::ObjToI256LoLo,
            HostFunctions::ObjToI256LoHi,
            HostFunctions::ObjToI256HiLo,
            HostFunctions::ObjToI256HiHi,
            HostFunctions::ObjFromI256Pieces,
            HostFunctions::RequireAuth,
            HostFunctions::AuthAsCurrContract,
            HostFunctions::MapNewFromLinearMemory,
            HostFunctions::MapNew,
            HostFunctions::MapPut,
            HostFunctions::VecPushBack,
            HostFunctions::VecGet,
            HostFunctions::VecPut,
            HostFunctions::StringNewFromLinearMemory,
            HostFunctions::StrKeyToAddr,
            HostFunctions::GetLedgerTimestamp,
            HostFunctions::GetCurrentContractAddress,
            HostFunctions::BytesNewFromLinearMemory,
            HostFunctions::BytesCopyToLinearMemory,
            HostFunctions::BytesLen,
            HostFunctions::BytesGet,
            HostFunctions::BytesPut,
            HostFunctions::BytesPush,
            HostFunctions::BytesPop,
            HostFunctions::StringLen,
            HostFunctions::StringCopyToLinearMemory,
            HostFunctions::VecLen,
            HostFunctions::VecPopBack,
            HostFunctions::ContractEvent,
        ];

        for func in &host_functions {
            bin.module.add_function(
                func.name(),
                func.function_signature(bin),
                Some(Linkage::External),
            );
        }
    }
}