scarb 0.1.0

The Cairo package manager
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
use std::collections::{BTreeMap, HashSet};
use std::fs;

use anyhow::{bail, ensure, Context, Result};
use camino::{Utf8Path, Utf8PathBuf};
use itertools::Itertools;
use semver::{Version, VersionReq};
use serde::{Deserialize, Serialize};
use smol_str::SmolStr;
use std::str::FromStr;
use toml::Value;
use tracing::trace;
use url::Url;

use crate::core::manifest::scripts::ScriptDefinition;
use crate::core::manifest::{
    ManifestCompilerConfig, ManifestDependency, ManifestMetadata, Summary, Target,
};
use crate::core::package::PackageId;
use crate::core::source::{GitReference, SourceId};
use crate::core::PackageName;
use crate::internal::fsx;
use crate::internal::fsx::PathUtf8Ext;
use crate::internal::to_version::ToVersion;
use crate::DEFAULT_SOURCE_PATH;

use super::Manifest;

/// This type is used to deserialize `Scarb.toml` files.
#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct TomlManifest {
    pub package: Option<Box<TomlPackage>>,
    pub dependencies: Option<BTreeMap<PackageName, TomlDependency>>,
    pub lib: Option<TomlTarget<TomlLibTargetParams>>,
    pub target: Option<BTreeMap<TomlTargetKind, Vec<TomlTarget<TomlExternalTargetParams>>>>,
    pub cairo: Option<TomlCairo>,
    pub tool: Option<BTreeMap<SmolStr, Value>>,
    pub scripts: Option<BTreeMap<SmolStr, String>>,
}

/// Represents the `package` section of a `Scarb.toml`.
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct TomlPackage {
    pub name: PackageName,
    pub version: Version,
    pub authors: Option<Vec<String>>,
    pub urls: Option<BTreeMap<String, String>>,
    pub description: Option<String>,
    pub documentation: Option<String>,
    pub homepage: Option<String>,
    pub keywords: Option<Vec<String>>,
    pub license: Option<String>,
    pub license_file: Option<String>,
    pub readme: Option<String>,
    pub repository: Option<String>,
    /// **UNSTABLE** This package does not depend on Cairo's `core`.
    pub no_core: Option<bool>,
}

#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum TomlDependency {
    /// [`VersionReq`] specified as a string, eg. `package = "<version>"`.
    Simple(VersionReq),
    /// Detailed specification as a table, eg. `package = { version = "<version>" }`.
    Detailed(DetailedTomlDependency),
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct DetailedTomlDependency {
    pub version: Option<VersionReq>,

    /// Relative to the file it appears in.
    pub path: Option<Utf8PathBuf>,

    pub git: Option<Url>,
    pub branch: Option<String>,
    pub tag: Option<String>,
    pub rev: Option<String>,
}

#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[serde(into = "SmolStr", try_from = "SmolStr")]
pub struct TomlTargetKind(SmolStr);

impl TomlTargetKind {
    pub fn try_new(name: SmolStr) -> Result<Self> {
        ensure!(name != Target::LIB, "target kind `{name}` is reserved");
        Ok(Self(name))
    }

    pub fn to_smol_str(&self) -> SmolStr {
        self.0.clone()
    }

    pub fn into_smol_str(self) -> SmolStr {
        self.0
    }
}

impl From<TomlTargetKind> for SmolStr {
    fn from(value: TomlTargetKind) -> Self {
        value.into_smol_str()
    }
}

impl TryFrom<SmolStr> for TomlTargetKind {
    type Error = anyhow::Error;

    fn try_from(value: SmolStr) -> Result<Self> {
        TomlTargetKind::try_new(value)
    }
}

#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct TomlTarget<P> {
    pub name: Option<SmolStr>,

    #[serde(flatten)]
    pub params: P,
}

#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct TomlLibTargetParams {
    pub sierra: Option<bool>,
    pub casm: Option<bool>,
}

pub type TomlExternalTargetParams = BTreeMap<SmolStr, Value>;

#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct TomlCairo {
    /// Replace all names in generated Sierra code with dummy counterparts, representing the
    /// expanded information about the named items.
    ///
    /// For libfuncs and types that would be recursively opening their generic arguments.
    /// For functions, that would be their original name in Cairo.
    /// For example, while the Sierra name be `[6]`, with this flag turned on it might be:
    /// - For libfuncs: `felt252_const<2>` or `unbox<Box<Box<felt252>>>`.
    /// - For types: `felt252` or `Box<Box<felt252>>`.
    /// - For user functions: `test::foo`.
    ///
    /// Defaults to `false`.
    pub sierra_replace_ids: Option<bool>,
}

impl TomlManifest {
    pub fn read_from_path(path: &Utf8Path) -> Result<Self> {
        let contents = fs::read_to_string(path)
            .with_context(|| format!("failed to read manifest at `{path}`"))?;

        Self::read_from_str(&contents)
            .with_context(|| format!("failed to parse manifest at `{path}`"))
    }

    pub fn read_from_str(contents: &str) -> Result<Self> {
        toml::from_str(contents).map_err(Into::into)
    }
}

impl TomlDependency {
    fn resolve(&self) -> DetailedTomlDependency {
        match self {
            TomlDependency::Simple(version) => DetailedTomlDependency {
                version: Some(version.clone()),
                ..Default::default()
            },
            TomlDependency::Detailed(detailed) => detailed.clone(),
        }
    }
}

impl TomlManifest {
    pub fn to_manifest(&self, manifest_path: &Utf8Path, source_id: SourceId) -> Result<Manifest> {
        let root = manifest_path
            .parent()
            .expect("manifest path parent must always exist");

        let Some(package) = self.package.as_deref() else {
            bail!("no `package` section found");
        };

        let package_id = {
            let name = package.name.clone();
            let version = package.version.clone().to_version()?;
            PackageId::new(name, version, source_id)
        };

        let mut dependencies = Vec::new();
        for (name, toml_dep) in self.dependencies.iter().flatten() {
            dependencies.push(toml_dep.to_dependency(name.clone(), manifest_path)?);
        }

        let no_core = package.no_core.unwrap_or(false);

        let targets = self.collect_targets(package.name.to_smol_str(), root)?;

        let compiler_config = self.collect_compiler_config();

        let scripts: BTreeMap<SmolStr, ScriptDefinition> = self
            .scripts
            .clone()
            .unwrap_or_default()
            .into_iter()
            .map(|(name, script)| -> Result<(SmolStr, ScriptDefinition)> {
                Ok((name, ScriptDefinition::from_str(&script)?))
            })
            .try_collect()?;

        Ok(Manifest {
            summary: Summary::build(package_id)
                .with_dependencies(dependencies)
                .no_core(no_core)
                .finish(),
            targets,
            metadata: ManifestMetadata {
                authors: package.authors.clone(),
                urls: package.urls.clone(),
                description: package.description.clone(),
                documentation: package.documentation.clone(),
                homepage: package.homepage.clone(),
                keywords: package.keywords.clone(),
                license: package.license.clone(),
                license_file: package.license_file.clone(),
                readme: package.readme.clone(),
                repository: package.repository.clone(),
                tool_metadata: self.tool.clone(),
            },
            compiler_config,
            scripts,
        })
    }

    fn collect_targets(&self, package_name: SmolStr, root: &Utf8Path) -> Result<Vec<Target>> {
        let default_source_path = root.join(DEFAULT_SOURCE_PATH);

        let mut targets = Vec::new();

        if let Some(lib_toml) = &self.lib {
            let name = lib_toml
                .name
                .clone()
                .unwrap_or_else(|| package_name.clone());

            let target = Target::try_from_structured_params(
                Target::LIB,
                name,
                default_source_path.clone(),
                &lib_toml.params,
            )?;
            targets.push(target);
        }

        for (kind_toml, ext_toml) in self
            .target
            .iter()
            .flatten()
            .flat_map(|(k, vs)| vs.iter().map(|v| (k.clone(), v)))
        {
            let name = ext_toml
                .name
                .clone()
                .unwrap_or_else(|| package_name.clone());

            let target = Target::try_from_structured_params(
                kind_toml,
                name,
                default_source_path.clone(),
                &ext_toml.params,
            )?;
            targets.push(target);
        }

        Self::check_unique_targets(&targets, &package_name)?;

        if targets.is_empty() {
            trace!("manifest has no targets, assuming default `lib` target");
            let target = Target::without_params(Target::LIB, package_name, default_source_path);
            targets.push(target);
        }

        Ok(targets)
    }

    fn check_unique_targets(targets: &[Target], package_name: &str) -> Result<()> {
        let mut used = HashSet::with_capacity(targets.len());
        for target in targets {
            if !used.insert((target.kind.as_str(), target.name.as_str())) {
                if target.name == package_name {
                    bail!(
                        "manifest contains duplicate target definitions `{}`, \
                        consider explicitly naming targets with the `name` field",
                        target.kind
                    )
                } else {
                    bail!(
                        "manifest contains duplicate target definitions `{} ({})`, \
                        use different target names to resolve the conflict",
                        target.kind,
                        target.name
                    )
                }
            }
        }
        Ok(())
    }

    fn collect_compiler_config(&self) -> ManifestCompilerConfig {
        let mut config = ManifestCompilerConfig::default();
        if let Some(cairo) = &self.cairo {
            if let Some(sierra_replace_ids) = cairo.sierra_replace_ids {
                config.sierra_replace_ids = sierra_replace_ids;
            }
        }
        config
    }
}

impl TomlDependency {
    fn to_dependency(
        &self,
        name: PackageName,
        manifest_path: &Utf8Path,
    ) -> Result<ManifestDependency> {
        self.resolve().to_dependency(name, manifest_path)
    }
}

impl DetailedTomlDependency {
    fn to_dependency(
        &self,
        name: PackageName,
        manifest_path: &Utf8Path,
    ) -> Result<ManifestDependency> {
        let version_req = self.version.to_owned().unwrap_or(VersionReq::STAR);

        if self.branch.is_some() || self.tag.is_some() || self.rev.is_some() {
            ensure!(
                self.git.is_some(),
                "dependency ({name}) is non-Git, but provides `branch`, `tag` or `rev`"
            );

            ensure!(
                [&self.branch, &self.tag, &self.rev]
                    .iter()
                    .filter(|o| o.is_some())
                    .count()
                    <= 1,
                "dependency ({name}) specification is ambiguous, \
                only one of `branch`, `tag` or `rev` is allowed"
            );
        }

        let source_id = match (self.version.as_ref(), self.git.as_ref(), self.path.as_ref()) {
            (None, None, None) => bail!(
                "dependency ({name}) must be specified providing a local path, Git repository, \
                or version to use"
            ),

            (_, Some(_), Some(_)) => bail!(
                "dependency ({name}) specification is ambiguous, \
                only one of `git` or `path` is allowed"
            ),

            (_, None, Some(path)) => {
                let root = manifest_path
                    .parent()
                    .expect("manifest path must always have parent");
                let path = root.join(path);
                let path = fsx::canonicalize(path)?;
                let path = path.try_as_utf8()?;
                SourceId::for_path(path)?
            }

            (_, Some(git), None) => {
                let reference = if let Some(branch) = &self.branch {
                    GitReference::Branch(branch.into())
                } else if let Some(tag) = &self.tag {
                    GitReference::Tag(tag.into())
                } else if let Some(rev) = &self.rev {
                    GitReference::Rev(rev.into())
                } else {
                    GitReference::DefaultBranch
                };

                SourceId::for_git(git, &reference)?
            }

            (Some(_), None, None) => SourceId::default_registry(),
        };

        Ok(ManifestDependency {
            name,
            version_req,
            source_id,
        })
    }
}