leo-package 4.1.0

Package parser for the Leo programming language
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
// Copyright (C) 2019-2026 Provable Inc.
// This file is part of the Leo library.

// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.

use crate::{MAX_PROGRAM_SIZE, *};

use leo_errors::Result;
use leo_span::Symbol;

use snarkvm::prelude::{Program as SvmProgram, TestnetV0};

use indexmap::{IndexMap, IndexSet};
use std::path::Path;

/// Find the latest cached edition for a program in the local registry.
/// Returns None if no cached version exists.
fn find_cached_edition(cache_directory: &Path, name: &str) -> Option<u16> {
    let program_cache = cache_directory.join(name);
    if !program_cache.exists() {
        return None;
    }

    // List edition directories and find the highest one
    std::fs::read_dir(&program_cache)
        .ok()?
        .filter_map(|entry| entry.ok())
        .filter_map(|entry| {
            let file_name = entry.file_name();
            let name = file_name.to_str()?;
            name.parse::<u16>().ok()
        })
        .max()
}

/// The kind of a Leo compilation unit: a deployable program, a library, or a test.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PackageKind {
    /// A deployable program with a `main.leo` entry point.
    Program,
    /// A library with a `lib.leo` entry point; not directly deployable.
    Library,
    /// A test file; compiled only during `leo test`.
    Test,
}

impl PackageKind {
    pub fn is_program(&self) -> bool {
        matches!(self, Self::Program)
    }

    pub fn is_library(&self) -> bool {
        matches!(self, Self::Library)
    }

    pub fn is_test(&self) -> bool {
        matches!(self, Self::Test)
    }
}

/// Information about a single Leo compilation unit.
#[derive(Clone, Debug)]
pub struct CompilationUnit {
    // The name of the program. For local packages this is the bare name (no ".aleo" suffix,
    // e.g. `my_program` or `my_lib`). For network-fetched programs this includes the ".aleo"
    // suffix (e.g. `credits.aleo`). TODO: unify the invariant so the suffix is always absent.
    pub name: Symbol,
    pub data: ProgramData,
    pub edition: Option<u16>,
    pub dependencies: IndexSet<Dependency>,
    pub is_local: bool,
    pub kind: PackageKind,
}

impl CompilationUnit {
    /// Given the location `path` of a `.aleo` file, read the filesystem
    /// to obtain a `CompilationUnit`.
    pub fn from_aleo_path<P: AsRef<Path>>(name: Symbol, path: P, map: &IndexMap<Symbol, Dependency>) -> Result<Self> {
        Self::from_aleo_path_impl(name, path.as_ref(), map)
    }

    fn from_aleo_path_impl(name: Symbol, path: &Path, map: &IndexMap<Symbol, Dependency>) -> Result<Self> {
        let bytecode = std::fs::read_to_string(path).map_err(|e| {
            crate::errors::util_file_io_error(format_args!("Trying to read aleo file at {}", path.display()), e)
        })?;

        let dependencies = parse_dependencies_from_aleo(name, &bytecode, map)?;

        Ok(CompilationUnit {
            name,
            data: ProgramData::Bytecode(bytecode),
            edition: None,
            dependencies,
            is_local: true,
            kind: PackageKind::Program,
        })
    }

    /// Given the location `path` of a local Leo package, read the filesystem
    /// to obtain a `CompilationUnit`.
    pub fn from_package_path<P: AsRef<Path>>(name: Symbol, path: P) -> Result<Self> {
        Self::from_package_path_impl(name, path.as_ref())
    }

    fn from_package_path_impl(name: Symbol, path: &Path) -> Result<Self> {
        let manifest = Manifest::read_from_file(path.join(MANIFEST_FILENAME))?;
        let manifest_symbol = crate::symbol(&manifest.program)?;
        if name != manifest_symbol {
            return Err(
                crate::errors::conflicting_manifest(format_args!("{name}"), format_args!("{manifest_symbol}")).into()
            );
        }
        let source_directory = path.join(SOURCE_DIRECTORY);
        source_directory.read_dir().map_err(|e| {
            crate::errors::util_file_io_error(
                format_args!("Failed to read directory {}", source_directory.display()),
                e,
            )
        })?;

        let main_path = source_directory.join(MAIN_FILENAME);
        let lib_path = source_directory.join(LIB_FILENAME);

        let (source_path, kind) = match (main_path.exists(), lib_path.exists()) {
            (true, true) => {
                return Err(crate::errors::ambiguous_entry_file(
                    source_directory.display(),
                    MAIN_FILENAME,
                    LIB_FILENAME,
                )
                .into());
            }
            (true, false) => (main_path, PackageKind::Program),
            (false, true) => (lib_path, PackageKind::Library),
            (false, false) => {
                return Err(
                    crate::errors::invalid_entry_file(source_directory.display(), MAIN_FILENAME, LIB_FILENAME).into()
                );
            }
        };

        Ok(CompilationUnit {
            name,
            data: ProgramData::SourcePath { directory: path.to_path_buf(), source: source_path },
            edition: None,
            dependencies: manifest
                .dependencies
                .unwrap_or_default()
                .into_iter()
                .map(|dependency| {
                    let dep = canonicalize_dependency_path_relative_to(path, dependency)?;
                    if dep.location == Location::Workspace { resolve_workspace_dependency(path, dep) } else { Ok(dep) }
                })
                .collect::<Result<IndexSet<_>, _>>()?,
            is_local: true,
            kind,
        })
    }

    /// Given the path to the source file of a test, create a `CompilationUnit`.
    ///
    /// Unlike `CompilationUnit::from_package_path`, the path is to the source file,
    /// and the name of the program is determined from the filename.
    ///
    /// `main_program` must be provided since every test is dependent on it.
    pub fn from_test_path<P: AsRef<Path>>(source_path: P, main_program: Dependency) -> Result<Self> {
        Self::from_path_test_impl(source_path.as_ref(), main_program)
    }

    fn from_path_test_impl(source_path: &Path, main_program: Dependency) -> Result<Self> {
        let name = filename_no_leo_extension(source_path)
            .ok_or_else(|| crate::errors::failed_path(source_path.display(), ""))?;
        let test_directory = source_path.parent().ok_or_else(|| {
            crate::errors::failed_to_open_file(format_args!(
                "Failed to find directory for test {}",
                source_path.display()
            ))
        })?;
        let package_directory = test_directory.parent().ok_or_else(|| {
            crate::errors::failed_to_open_file(format_args!(
                "Failed to find package for test {}",
                source_path.display()
            ))
        })?;
        let manifest = Manifest::read_from_file(package_directory.join(MANIFEST_FILENAME))?;
        let mut dependencies = manifest
            .dev_dependencies
            .unwrap_or_default()
            .into_iter()
            .map(|dependency| {
                let dep = canonicalize_dependency_path_relative_to(package_directory, dependency)?;
                if dep.location == Location::Workspace {
                    resolve_workspace_dependency(package_directory, dep)
                } else {
                    Ok(dep)
                }
            })
            .collect::<Result<IndexSet<_>, _>>()?;
        dependencies.insert(main_program);

        Ok(CompilationUnit {
            name: Symbol::intern(&(name.to_owned() + ".aleo")),
            edition: None,
            data: ProgramData::SourcePath {
                directory: test_directory.to_path_buf(),
                source: source_path.to_path_buf(),
            },
            dependencies,
            is_local: true,
            kind: PackageKind::Test,
        })
    }

    /// Given an Aleo program on a network, fetch it to build a `CompilationUnit`.
    /// If no edition is found, the latest edition is pulled from the network.
    pub fn fetch<P: AsRef<Path>>(
        name: Symbol,
        edition: Option<u16>,
        home_path: P,
        network: NetworkName,
        endpoint: &str,
        no_cache: bool,
        network_retries: u32,
    ) -> Result<Self> {
        Self::fetch_impl(name, edition, home_path.as_ref(), network, endpoint, no_cache, network_retries)
    }

    fn fetch_impl(
        name: Symbol,
        edition: Option<u16>,
        home_path: &Path,
        network: NetworkName,
        endpoint: &str,
        no_cache: bool,
        network_retries: u32,
    ) -> Result<Self> {
        // Callers may pass the name with or without the ".aleo" suffix; normalise to bare name
        // here so cache paths and network URLs are constructed consistently.
        let name = Symbol::intern(name.to_string().strip_suffix(".aleo").unwrap_or(&name.to_string()));

        // It's not a local program; let's check the cache.
        let cache_directory = home_path.join(format!("registry/{network}"));

        // If the edition is not specified, try to find a cached version first,
        // then fall back to querying the network for the latest edition.
        let edition = match edition {
            // Credits program always has edition 0.
            _ if name == Symbol::intern("credits") => 0,
            Some(edition) => edition,
            None if !no_cache => {
                // Check if we have a cached version - avoid network call if possible.
                match find_cached_edition(&cache_directory, &name.to_string()) {
                    Some(cached_edition) => cached_edition,
                    None => crate::fetch_latest_edition(&name.to_string(), endpoint, network, network_retries)?,
                }
            }
            // no_cache is set - user wants fresh data from network.
            None => crate::fetch_latest_edition(&name.to_string(), endpoint, network, network_retries)?,
        };

        // Define the full cache path for the program.

        // Build cache paths.
        let cache_directory = cache_directory.join(format!("{name}/{edition}"));
        let full_cache_path = cache_directory.join(format!("{name}.aleo"));
        if !cache_directory.exists() {
            // Create directory if it doesn't exist.
            std::fs::create_dir_all(&cache_directory).map_err(|err| {
                crate::errors::util_file_io_error(format!("Could not write path {}", cache_directory.display()), err)
            })?;
        }

        // Get the existing bytecode if the file exists.
        let existing_bytecode = match full_cache_path.exists() {
            false => None,
            true => {
                let existing_contents = std::fs::read_to_string(&full_cache_path).map_err(|e| {
                    crate::errors::util_file_io_error(
                        format_args!("Trying to read cached file at {}", full_cache_path.display()),
                        e,
                    )
                })?;
                Some(existing_contents)
            }
        };

        let bytecode = match (existing_bytecode, no_cache) {
            // If we are using the cache, we can just return the bytecode.
            (Some(bytecode), false) => bytecode,
            // Otherwise, we need to fetch it from the network.
            (existing, _) => {
                // Define the primary URL to fetch the program from.
                let primary_url = if name == Symbol::intern("credits") {
                    format!("{endpoint}/{network}/program/credits.aleo")
                } else {
                    format!("{endpoint}/{network}/program/{name}.aleo/{edition}")
                };
                let secondary_url = format!("{endpoint}/{network}/program/{name}.aleo");
                let contents = fetch_from_network(&primary_url, network_retries)
                    .or_else(|_| fetch_from_network(&secondary_url, network_retries))
                    .map_err(|err| {
                        crate::errors::failed_to_retrieve_from_endpoint(
                            primary_url,
                            format_args!("Failed to fetch program `{name}` from network `{network}`: {err}"),
                        )
                    })?;

                // If the file already exists, compare it to the new contents.
                if let Some(existing_contents) = existing
                    && existing_contents != contents
                {
                    println!(
                        "Warning: The cached file at `{}` is different from the one fetched from the network. The cached file will be overwritten.",
                        full_cache_path.display()
                    );
                }

                // Write the bytecode to the cache.
                std::fs::write(&full_cache_path, &contents).map_err(|err| {
                    crate::errors::util_file_io_error(
                        format_args!("Could not open file `{}`", full_cache_path.display()),
                        err,
                    )
                })?;

                contents
            }
        };

        let dependencies = parse_dependencies_from_aleo(name, &bytecode, &IndexMap::new())?;

        Ok(CompilationUnit {
            // Network programs store the name with the ".aleo" suffix (unlike local packages).
            // TODO: unify the invariant so the suffix is always absent.
            name: Symbol::intern(&(name.to_string() + ".aleo")),
            data: ProgramData::Bytecode(bytecode),
            edition: Some(edition),
            dependencies,
            is_local: false,
            kind: PackageKind::Program,
        })
    }
}

/// If `dependency` has a relative path, assume it's relative to `base` and canonicalize it.
///
/// This needs to be done when collecting local dependencies from manifests which
/// may be located at different places on the file system.
pub(crate) fn canonicalize_dependency_path_relative_to(base: &Path, mut dependency: Dependency) -> Result<Dependency> {
    if let Some(path) = &mut dependency.path
        && !path.is_absolute()
    {
        let joined = base.join(&path);
        *path = joined.canonicalize().map_err(|e| crate::errors::failed_path(joined.display(), e))?;
    }
    Ok(dependency)
}

/// Parse the `.aleo` file's imports and construct `Dependency`s.
fn parse_dependencies_from_aleo(
    name: Symbol,
    bytecode: &str,
    existing: &IndexMap<Symbol, Dependency>,
) -> Result<IndexSet<Dependency>> {
    // Check if the program size exceeds the maximum allowed limit.
    let program_size = bytecode.len();

    if program_size > MAX_PROGRAM_SIZE {
        return Err(leo_errors::LeoError::Backtraced(crate::errors::program_size_limit_exceeded(
            name,
            program_size,
            MAX_PROGRAM_SIZE,
        )));
    }

    // Parse the bytecode into an SVM program.
    let svm_program: SvmProgram<TestnetV0> =
        bytecode.parse().map_err(|_| crate::errors::snarkvm_parsing_error(name))?;
    let dependencies = svm_program
        .imports()
        .keys()
        .map(|program_id| {
            // If the dependency already exists, use it.
            // Otherwise, assume it's a network dependency.
            if let Some(dependency) = existing.get(&Symbol::intern(&program_id.to_string())) {
                dependency.clone()
            } else {
                let name = program_id.to_string();
                Dependency { name, location: Location::Network, path: None, edition: None }
            }
        })
        .collect();
    Ok(dependencies)
}