Skip to content
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 11 additions & 19 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 4 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -449,7 +449,7 @@ rexpect = { git = "https://github.com/rust-cli/rexpect", rev = "2ed0b1898d7edaf6
# foundry-fork-db = { git = "https://github.com/foundry-rs/foundry-fork-db", rev = "be95912" }

# solar
# solar = { package = "solar-compiler", git = "https://github.com/paradigmxyz/solar.git", branch = "main" }
# solar-interface = { package = "solar-interface", git = "https://github.com/paradigmxyz/solar.git", branch = "main" }
# solar-ast = { package = "solar-ast", git = "https://github.com/paradigmxyz/solar.git", branch = "main" }
# solar-sema = { package = "solar-sema", git = "https://github.com/paradigmxyz/solar.git", branch = "main" }
solar = { package = "solar-compiler", git = "https://github.com/paradigmxyz/solar.git", branch = "main" }
solar-interface = { package = "solar-interface", git = "https://github.com/paradigmxyz/solar.git", branch = "main" }
solar-ast = { package = "solar-ast", git = "https://github.com/paradigmxyz/solar.git", branch = "main" }
solar-sema = { package = "solar-sema", git = "https://github.com/paradigmxyz/solar.git", branch = "main" }
2 changes: 1 addition & 1 deletion crates/cli/src/opts/build/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ mod paths;
pub use self::paths::ProjectPathOpts;

mod utils;
pub use self::utils::{configure_pcx, configure_pcx_from_compile_output, configure_pcx_from_solc};
pub use self::utils::*;

// A set of solc compiler settings that can be set via command line arguments, which are intended
// to be merged into an existing `foundry_config::Config`.
Expand Down
34 changes: 27 additions & 7 deletions crates/cli/src/opts/build/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@ use foundry_compilers::{
};
use foundry_config::{Config, semver::Version};
use rayon::prelude::*;
use solar::sema::ParsingContext;
use solar::{interface::MIN_SOLIDITY_VERSION as MSV, sema::ParsingContext};
use std::{
collections::{HashSet, VecDeque},
path::{Path, PathBuf},
};

const MIN_SUPPORTED_VERSION: Version = Version::new(MSV.0, MSV.1, MSV.2);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we make this a semver Version in solar instead of ints?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sure, let's do that since we haven't released yet and ended up patching the version


/// Configures a [`ParsingContext`] from [`Config`].
///
/// - Configures include paths, remappings
Expand Down Expand Up @@ -59,10 +61,16 @@ pub fn configure_pcx(
.ok_or_else(|| eyre::eyre!("no Solidity sources"))?
.1
.into_iter()
// Filter unsupported versions
.filter(|(v, _, _)| v >= &MIN_SUPPORTED_VERSION)
// Always pick the latest version
.max_by(|(v1, _, _), (v2, _, _)| v1.cmp(v2))
.unwrap();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this could panic now

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

addressed in 80e9697 (#12065)


if sources.is_empty() {
sh_warn!("no files found. Solar doesn't support Solidity versions prior to 0.8.0")?;
}

let solc = SolcVersionedInput::build(
sources,
config.solc_settings()?,
Expand All @@ -75,18 +83,17 @@ pub fn configure_pcx(
Ok(())
}

/// Configures a [`ParsingContext`] from a [`ProjectCompileOutput`] and [`SolcVersionedInput`].
/// Extracts Solar-compatible sources from a [`ProjectCompileOutput`].
///
/// # Note:
/// uses `output.graph().source_files()` and `output.artifact_ids()` rather than `output.sources()`
/// because sources aren't populated when build is skipped when there are no changes in the source
/// code. <https://github.com/foundry-rs/foundry/issues/12018>
pub fn configure_pcx_from_compile_output(
pcx: &mut ParsingContext<'_>,
pub fn get_solar_sources_from_compile_output(
config: &Config,
output: &ProjectCompileOutput,
target_paths: Option<&[PathBuf]>,
) -> Result<()> {
) -> Result<SolcVersionedInput> {
let is_solidity_file = |path: &Path| -> bool {
path.extension().and_then(|s| s.to_str()).is_some_and(|ext| SOLC_EXTENSIONS.contains(&ext))
};
Expand Down Expand Up @@ -125,12 +132,14 @@ pub fn configure_pcx_from_compile_output(

// Read all sources and find the latest version.
let (version, sources) = {
let (mut max_version, mut sources) = (Version::new(0, 0, 0), Sources::new());
let (mut max_version, mut sources) = (MIN_SUPPORTED_VERSION, Sources::new());
for (id, _) in output.artifact_ids() {
if let Ok(path) = dunce::canonicalize(&id.source)
&& source_paths.remove(&path)
{
if id.version > max_version {
if id.version < MIN_SUPPORTED_VERSION {
continue;
} else if max_version < id.version {
max_version = id.version;
};

Expand All @@ -149,6 +158,17 @@ pub fn configure_pcx_from_compile_output(
version,
);

Ok(solc)
}

/// Configures a [`ParsingContext`] from a [`ProjectCompileOutput`].
pub fn configure_pcx_from_compile_output(
pcx: &mut ParsingContext<'_>,
config: &Config,
output: &ProjectCompileOutput,
target_paths: Option<&[PathBuf]>,
) -> Result<()> {
let solc = get_solar_sources_from_compile_output(config, output, target_paths)?;
configure_pcx_from_solc(pcx, &config.project_paths(), &solc, true);
Ok(())
}
Expand Down
29 changes: 25 additions & 4 deletions crates/forge/src/cmd/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use clap::Parser;
use eyre::{Context, Result};
use forge_lint::{linter::Linter, sol::SolidityLinter};
use foundry_cli::{
opts::BuildOpts,
opts::{BuildOpts, configure_pcx_from_solc, get_solar_sources_from_compile_output},
utils::{LoadConfig, cache_local_signatures},
};
use foundry_common::{compile::ProjectCompiler, shell};
Expand Down Expand Up @@ -174,10 +174,31 @@ impl BuildArgs {
})
.collect::<Vec<_>>();

if !input_files.is_empty() {
let compiler = output.parser_mut().solc_mut().compiler_mut();
linter.lint(&input_files, config.deny, compiler)?;
let solar_sources =
get_solar_sources_from_compile_output(config, output, Some(&input_files))?;
if solar_sources.input.sources.is_empty() {
if !input_files.is_empty() {
sh_warn!(
"unable to lint. Solar only supports Solidity versions prior to 0.8.0"
)?;
}
return Ok(());
}

// NOTE(rusowsky): Once solar can drop unsupported versions, rather than creating a new
// compiler, we should reuse the parser from the project output.
let mut compiler = solar::sema::Compiler::new(
solar::interface::Session::builder().with_stderr_emitter().build(),
);

// Load the solar-compatible sources to the pcx before linting
compiler.enter_mut(|compiler| {
let mut pcx = compiler.parse();
configure_pcx_from_solc(&mut pcx, &config.project_paths(), &solar_sources, true);
pcx.set_resolve_imports(true);
pcx.parse();
});
linter.lint(&input_files, config.deny, &mut compiler)?;
}

Ok(())
Expand Down
33 changes: 26 additions & 7 deletions crates/forge/src/cmd/lint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use forge_lint::{
sol::{SolLint, SolLintError, SolidityLinter},
};
use foundry_cli::{
opts::BuildOpts,
opts::{BuildOpts, configure_pcx_from_solc, get_solar_sources_from_compile_output},
utils::{FoundryPathExt, LoadConfig},
};
use foundry_common::{compile::ProjectCompiler, shell};
Expand Down Expand Up @@ -69,15 +69,15 @@ impl LintArgs {
} else if path.is_sol() {
inputs.push(path.to_path_buf());
} else {
warn!("Cannot process path {}", path.display());
warn!("cannot process path {}", path.display());
}
}
inputs
}
};

if input.is_empty() {
sh_println!("Nothing to lint")?;
sh_println!("nothing to lint")?;
return Ok(());
}

Expand All @@ -95,7 +95,7 @@ impl LintArgs {
let severity = self.severity.unwrap_or(config.lint.severity.clone());

if project.compiler.solc.is_none() {
return Err(eyre!("Linting not supported for this language"));
return Err(eyre!("linting not supported for this language"));
}

let linter = SolidityLinter::new(path_config)
Expand All @@ -106,9 +106,28 @@ impl LintArgs {
.with_severity(if severity.is_empty() { None } else { Some(severity) })
.with_mixed_case_exceptions(&config.lint.mixed_case_exceptions);

let mut output = ProjectCompiler::new().files(input.iter().cloned()).compile(&project)?;
let compiler = output.parser_mut().solc_mut().compiler_mut();
linter.lint(&input, config.deny, compiler)?;
let output = ProjectCompiler::new().files(input.iter().cloned()).compile(&project)?;
let solar_sources = get_solar_sources_from_compile_output(&config, &output, Some(&input))?;
if solar_sources.input.sources.is_empty() {
return Err(eyre!(
"unable to lint. Solar only supports Solidity versions prior to 0.8.0"
));
}

// NOTE(rusowsky): Once solar can drop unsupported versions, rather than creating a new
// compiler, we should reuse the parser from the project output.
let mut compiler = solar::sema::Compiler::new(
solar::interface::Session::builder().with_stderr_emitter().build(),
);

// Load the solar-compatible sources to the pcx before linting
compiler.enter_mut(|compiler| {
let mut pcx = compiler.parse();
pcx.set_resolve_imports(true);
configure_pcx_from_solc(&mut pcx, &config.project_paths(), &solar_sources, true);
pcx.parse();
});
linter.lint(&input, config.deny, &mut compiler)?;

Ok(())
}
Expand Down
5 changes: 1 addition & 4 deletions crates/forge/src/multi_runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -575,10 +575,7 @@ impl MultiContractRunnerBuilder {
if files.is_empty() { None } else { Some(&files) },
)?;
pcx.parse();
// Check if any sources exist, to avoid logging `error: no files found`
if !compiler.sess().source_map().is_empty() {
let _ = compiler.lower_asts();
}
let _ = compiler.lower_asts();
Ok(())
})?;

Expand Down
44 changes: 44 additions & 0 deletions crates/forge/tests/cli/lint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,10 @@ import { ContractWithLints } from "./ContractWithLints.sol";

import { _PascalCaseInfo } from "./ContractWithLints.sol";
import "./ContractWithLints.sol";

contract Dummy {
bool foo;
}
"#;

const COUNTER_A: &str = r#"
Expand Down Expand Up @@ -778,3 +782,43 @@ fn ensure_no_privileged_lint_id() {
assert_ne!(lint.id(), "all", "lint-id 'all' is reserved. Please use a different id");
}
}

forgetest!(skips_linting_for_old_solidity_versions, |prj, cmd| {
prj.wipe_contracts();

// Add a contract with Solidity 0.7.x which has lint issues
const OLD_CONTRACT: &str = r#"
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;

contract OldContract {
uint256 VARIABLE_MIXED_CASE_INFO;

function FUNCTION_MIXED_CASE_INFO() public {}
}
"#;

prj.add_source("OldContract", OLD_CONTRACT);

// Configure linter to show all severities
prj.update_config(|config| {
config.lint = LinterConfig {
severity: vec![],
exclude_lints: vec![],
ignore: vec![],
lint_on_build: true,
..Default::default()
};
});

// Run forge build - should SUCCEED without linting
cmd.arg("build").assert_success().stderr_eq(
"Warning: unable to lint. Solar only supports Solidity versions prior to 0.8.0\n",
);

// Run forge lint - should FAIL
cmd.forge_fuse()
.arg("lint")
.assert_failure()
.stderr_eq("Error: unable to lint. Solar only supports Solidity versions prior to 0.8.0\n");
});
Loading
Loading