leo_ast/common/location.rs
1// Copyright (C) 2019-2026 Provable Inc.
2// This file is part of the Leo library.
3
4// The Leo library is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// The Leo library is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
16use crate::ProgramId;
17
18use itertools::Itertools;
19use leo_span::{Symbol, sym};
20use serde::Serialize;
21use snarkvm::prelude::{Locator, Network};
22use std::fmt::Display;
23
24#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)]
25pub struct Location {
26 /// The program name. e.g. `credits.aleo` or `my_library`.
27 pub program: Symbol,
28 /// The absolute path to the item that this `Location` points to.
29 pub path: Vec<Symbol>,
30}
31
32impl Location {
33 pub fn new(program: Symbol, path: Vec<Symbol>) -> Location {
34 Location { program, path }
35 }
36
37 /// Create a sentinel location representing a dynamic call's future.
38 pub fn dynamic() -> Location {
39 Location { program: sym::__dynamic__, path: vec![sym::__dynamic__] }
40 }
41
42 /// Check whether this location is the dynamic sentinel.
43 pub fn is_dynamic(&self) -> bool {
44 self.program == sym::__dynamic__
45 }
46
47 /// The portion of the path *above* the item, i.e. the module path the item lives in.
48 /// For program-block items and library top-level items the path has length 1 and
49 /// this returns an empty slice; for module items it returns the module segments.
50 pub fn module_path(&self) -> &[Symbol] {
51 match self.path.split_last() {
52 Some((_, module)) => module,
53 None => &[],
54 }
55 }
56}
57
58impl Display for Location {
59 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60 write!(f, "{}/{}", self.program, self.path.iter().format("::"))
61 }
62}
63
64impl<N: Network> From<Locator<N>> for Location {
65 fn from(locator: Locator<N>) -> Self {
66 Location {
67 program: ProgramId::from(locator.program_id()).as_symbol(),
68 path: vec![Symbol::intern(&locator.resource().to_string())],
69 }
70 }
71}