Skip to content

Commit

Permalink
Merge branch 'dev' into feature/control-flow-graphs-plus-re-entrancy-…
Browse files Browse the repository at this point in the history
…detector
  • Loading branch information
TilakMaddy committed Oct 5, 2024
2 parents 866ee2e + 0279da5 commit 235f900
Show file tree
Hide file tree
Showing 185 changed files with 2,937 additions and 2,765 deletions.
12 changes: 12 additions & 0 deletions .git-blame-ignore-revs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Since version 2.23 (released in August 2019), git-blame has a feature
# to ignore or bypass certain commits.
#
# This file contains a list of commits that are not likely what you
# are looking for in a blame, such as mass reformatting or renaming.
# You can set this file as a default ignore file for blame by running
# the following command.
#
# $ git config blame.ignoreRevsFile .git-blame-ignore-revs

# fmt: all (#3398)
748ae7fc6da5bd63f1955cb1a7b5eb6b36e0ad61
26 changes: 12 additions & 14 deletions .github/workflows/cargo.yml
Original file line number Diff line number Diff line change
Expand Up @@ -64,11 +64,6 @@ jobs:
run: |
git submodule update --init --recursive
- uses: Swatinem/rust-cache@v2
- name: Run cargo test
run: |
cargo test _by_loading_contract_directly
- uses: Swatinem/rust-cache@v2
- name: Run cargo test
run: |
Expand Down Expand Up @@ -272,23 +267,26 @@ jobs:
- name: Checkout sources
uses: actions/checkout@v2

- name: Install stable toolchain
- name: Install nightly toolchain
uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: stable
components: rustfmt, clippy
toolchain: nightly
components: rustfmt
override: true

- name: Install git submodules
- name: Run cargo fmt
run: |
git submodule update --init --recursive
cargo +nightly fmt --all --check
- name: Run cargo fmt
uses: actions-rs/cargo@v1
- name: Install stable toolchain
uses: actions-rs/toolchain@v1
with:
command: fmt
args: --all -- --check
profile: minimal
toolchain: stable
components: clippy
override: true


- name: Run cargo clippy
uses: actions-rs/cargo@v1
Expand Down
22 changes: 11 additions & 11 deletions aderyn/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,21 +88,21 @@ fn right_pad(s: &str, by: usize) -> String {

pub static APP_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"));

pub fn aderyn_is_currently_running_newest_version() -> Result<bool, reqwest::Error> {
pub fn aderyn_is_currently_running_newest_version() -> Option<bool> {
let client = reqwest::blocking::Client::builder()
.user_agent(APP_USER_AGENT)
.build()?;
.build()
.expect("client is unable to initialize");

let latest_version_checker = client
.get("https://api.github.com/repos/Cyfrin/aderyn/releases/latest")
.send()?;
let latest_version_checker =
client.get("https://api.github.com/repos/Cyfrin/aderyn/releases/latest").send().ok()?;

let data = latest_version_checker.json::<Value>()?;
let newest =
Version::parse(data["tag_name"].as_str().unwrap().replace('v', "").as_str()).unwrap();
let current = Version::parse(env!("CARGO_PKG_VERSION")).unwrap();
let data = latest_version_checker.json::<Value>().ok()?;
let version_string = data["tag_name"].as_str()?;
let newest = Version::parse(version_string.replace('v', "").as_str()).ok()?;
let current = Version::parse(env!("CARGO_PKG_VERSION")).expect("Pkg version not available");

Ok(current >= newest)
Some(current >= newest)
}

#[cfg(test)]
Expand All @@ -111,6 +111,6 @@ mod latest_version_checker_tests {

#[test]
fn can_get_latest_version_from_crate_registry() {
assert!(aderyn_is_currently_running_newest_version().is_ok())
assert!(aderyn_is_currently_running_newest_version().is_some())
}
}
55 changes: 18 additions & 37 deletions aderyn/src/lsp.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
use log::{info, warn};
use notify_debouncer_full::notify::{Event, RecommendedWatcher, Result as NotifyResult};
use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use tokio::runtime::Builder;
use tokio::sync::mpsc::Receiver;
use tokio::sync::Mutex;
use tower_lsp::jsonrpc::Result;
use tower_lsp::{lsp_types::*, ClientSocket};
use tower_lsp::{Client, LanguageServer, LspService, Server};
use std::{collections::HashSet, path::PathBuf, sync::Arc, time::Duration};
use tokio::{
runtime::Builder,
sync::{mpsc::Receiver, Mutex},
};
use tower_lsp::{
jsonrpc::Result, lsp_types::*, Client, ClientSocket, LanguageServer, LspService, Server,
};

use aderyn_driver::driver::{self, Args};

Expand All @@ -27,10 +25,7 @@ impl LanguageServer for LanguageServerBackend {

let code_editor = self.client.lock().await;
code_editor
.log_message(
MessageType::INFO,
"Aderyn LSP received an initialization request!",
)
.log_message(MessageType::INFO, "Aderyn LSP received an initialization request!")
.await;

Ok(InitializeResult {
Expand Down Expand Up @@ -66,9 +61,7 @@ impl LanguageServer for LanguageServerBackend {
info!("TLSP shutdown");

let code_editor = self.client.lock().await;
code_editor
.log_message(MessageType::INFO, "Aderyn LSP has been shutdown")
.await;
code_editor.log_message(MessageType::INFO, "Aderyn LSP has been shutdown").await;
Ok(())
}
}
Expand All @@ -92,7 +85,8 @@ pub fn spin_up_language_server(args: Args) {

// Block on this function
async_runtime.block_on(async {
// Channel to communicate file system changes (triggered when files are added, removed, or changed)
// Channel to communicate file system changes (triggered when files are added, removed, or
// changed)
let (tx_file_change_event, rx_file_change_event) = tokio::sync::mpsc::channel(10);

// Create the async watcher
Expand All @@ -110,10 +104,7 @@ pub fn spin_up_language_server(args: Args) {

// Watch for file changes
file_system_watcher
.watch(
PathBuf::from(args.root.clone()).as_path(),
RecursiveMode::Recursive,
)
.watch(PathBuf::from(args.root.clone()).as_path(), RecursiveMode::Recursive)
.expect("unable to watch for file changes");

// Most editor's LSP clients communicate through stdout/stdin channels. Theefore use
Expand Down Expand Up @@ -169,10 +160,7 @@ fn create_lsp_service_and_react_to_file_event(
return;
};

info!(
"sending diagnostics to client {:?}",
&diagnostics_report.diagnostics
);
info!("sending diagnostics to client {:?}", &diagnostics_report.diagnostics);
let client_mutex = guarded_client.lock().await;

for (file_uri, file_diagnostics) in &diagnostics_report.diagnostics {
Expand All @@ -182,11 +170,8 @@ fn create_lsp_service_and_react_to_file_event(
}

// Clear out the diagnostics for file which had reported errors before
let current_run_file_uris = diagnostics_report
.diagnostics
.keys()
.cloned()
.collect::<HashSet<_>>();
let current_run_file_uris =
diagnostics_report.diagnostics.keys().cloned().collect::<HashSet<_>>();

let mut seen_file_uris_mutex = seen_file_uris.lock().await;
let seen_file_uris = &mut *seen_file_uris_mutex;
Expand All @@ -195,9 +180,7 @@ fn create_lsp_service_and_react_to_file_event(
if !&current_run_file_uris.contains(seen_file_uri) {
// Clear the diagnostics for this seen file uri
// It had errors in the past, but not any more
client_mutex
.publish_diagnostics(seen_file_uri.clone(), vec![], None)
.await;
client_mutex.publish_diagnostics(seen_file_uri.clone(), vec![], None).await;
}
}

Expand Down Expand Up @@ -234,9 +217,7 @@ fn create_lsp_service_and_react_to_file_event(
}
});

LanguageServerBackend {
client: guarded_client_clone,
}
LanguageServerBackend { client: guarded_client_clone }
});
(service, socket)
}
2 changes: 1 addition & 1 deletion aderyn/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ fn main() {

// Check for updates
if !cmd_args.skip_update_check {
if let Ok(yes) = aderyn_is_currently_running_newest_version() {
if let Some(yes) = aderyn_is_currently_running_newest_version() {
if !yes {
println!();
println!("NEW VERSION OF ADERYN AVAILABLE! Please run `cyfrinup` to upgrade.");
Expand Down
24 changes: 9 additions & 15 deletions aderyn/src/panic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,20 +24,16 @@ pub fn stderr_buffer_writer() -> BufferWriter {
}

pub fn add_handler() {
std::panic::set_hook(Box::new(move |info: &PanicInfo<'_>| {
print_compiler_bug_message(info)
}));
std::panic::set_hook(Box::new(move |info: &PanicInfo<'_>| print_compiler_bug_message(info)));
}

fn print_compiler_bug_message(info: &PanicInfo<'_>) {
let message = match (
info.payload().downcast_ref::<&str>(),
info.payload().downcast_ref::<String>(),
) {
(Some(s), _) => (*s).to_string(),
(_, Some(s)) => s.to_string(),
(None, None) => "unknown error".into(),
};
let message =
match (info.payload().downcast_ref::<&str>(), info.payload().downcast_ref::<String>()) {
(Some(s), _) => (*s).to_string(),
(_, Some(s)) => s.to_string(),
(None, None) => "unknown error".into(),
};

let location = match info.location() {
None => "".into(),
Expand All @@ -46,16 +42,14 @@ fn print_compiler_bug_message(info: &PanicInfo<'_>) {

let buffer_writer = stderr_buffer_writer();
let mut buffer = buffer_writer.buffer();
buffer
.set_color(ColorSpec::new().set_bold(true).set_fg(Some(Color::Red)))
.unwrap();
buffer.set_color(ColorSpec::new().set_bold(true).set_fg(Some(Color::Red))).unwrap();
write!(buffer, "error").unwrap();
buffer.set_color(ColorSpec::new().set_bold(true)).unwrap();
write!(buffer, ": Fatal compiler bug!\n\n").unwrap();
buffer.set_color(&ColorSpec::new()).unwrap();
writeln!(
buffer,
"This is a fatal bug in the Aderyn, sorry!
"This is a fatal bug in Aderyn, sorry!
Please report this crash to https://github.com/cyfrin/aderyn/issues/new and include this error message with your report.
Expand Down
3 changes: 3 additions & 0 deletions aderyn_core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,6 @@ derive_more = "0.99.18"
petgraph = "0"
serial_test = "3.0.0"
once_cell = "1.19.0"

[lib]
doctest = false
3 changes: 1 addition & 2 deletions aderyn_core/src/ast/ast.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use crate::{
ast::macros::*,
ast::*,
ast::{macros::*, *},
visitor::ast_visitor::{ASTConstVisitor, Node},
};
use eyre::Result;
Expand Down
31 changes: 16 additions & 15 deletions aderyn_core/src/ast/ast_nodes.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use super::macros::{ast_node, ast_node_no_partial_eq, expr_node, node_group, stmt_node};
use super::*;
use super::{
macros::{ast_node, ast_node_no_partial_eq, expr_node, node_group, stmt_node},
*,
};
use std::collections::{BTreeMap, HashMap};

use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -99,19 +101,17 @@ impl<'de> Deserialize<'de> for TypeName {
let type_name = node_type.unwrap().as_str().unwrap();

match type_name {
"FunctionTypeName" => Ok(TypeName::FunctionTypeName(
serde_json::from_value(json).unwrap(),
)),
"ArrayTypeName" => Ok(TypeName::ArrayTypeName(
serde_json::from_value(json).unwrap(),
)),
"FunctionTypeName" => {
Ok(TypeName::FunctionTypeName(serde_json::from_value(json).unwrap()))
}
"ArrayTypeName" => Ok(TypeName::ArrayTypeName(serde_json::from_value(json).unwrap())),
"Mapping" => Ok(TypeName::Mapping(serde_json::from_value(json).unwrap())),
"UserDefinedTypeName" => Ok(TypeName::UserDefinedTypeName(
serde_json::from_value(json).unwrap(),
)),
"ElementaryTypeName" => Ok(TypeName::ElementaryTypeName(
serde_json::from_value(json).unwrap(),
)),
"UserDefinedTypeName" => {
Ok(TypeName::UserDefinedTypeName(serde_json::from_value(json).unwrap()))
}
"ElementaryTypeName" => {
Ok(TypeName::ElementaryTypeName(serde_json::from_value(json).unwrap()))
}
_ => panic!("Unrecognized type name {type_name}"),
}
}
Expand Down Expand Up @@ -645,7 +645,8 @@ ast_node!(
stmt_node!(
#[derive(Hash)]
struct Return {
function_return_parameters: Option<NodeID>, // When returning in a modifier, this can be none
function_return_parameters: Option<NodeID>, /* When returning in a modifier, this can be
* none */
expression: Option<Expression>,
}
);
Expand Down
16 changes: 3 additions & 13 deletions aderyn_core/src/ast/impls/disp/expressions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,7 @@ impl Display for Expression {

impl Display for UnaryOperation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!(
"{}{}",
self.sub_expression,
self.operator.as_str()
))
f.write_fmt(format_args!("{}{}", self.sub_expression, self.operator.as_str()))
}
}

Expand Down Expand Up @@ -84,10 +80,7 @@ impl Display for FunctionCallOptions {
let option_count = self.options.len();

if self.names.len() != option_count {
eprintln!(
"ERROR: invalid FunctionCallOptions: {:?}, {:?}",
self.names, self.options
);
eprintln!("ERROR: invalid FunctionCallOptions: {:?}, {:?}", self.names, self.options);

return Err(std::fmt::Error);
}
Expand Down Expand Up @@ -127,10 +120,7 @@ impl Display for FunctionCallOptions {
impl Display for IndexAccess {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(index_expression) = &self.index_expression {
f.write_fmt(format_args!(
"{}[{}]",
self.base_expression, index_expression
))
f.write_fmt(format_args!("{}[{}]", self.base_expression, index_expression))
} else {
f.write_fmt(format_args!("{}[]", self.base_expression))
}
Expand Down
5 changes: 1 addition & 4 deletions aderyn_core/src/ast/impls/disp/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,6 @@ impl Display for ArrayTypeName {

impl Display for Mapping {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!(
"mapping({} => {})",
self.key_type, self.value_type
))
f.write_fmt(format_args!("mapping({} => {})", self.key_type, self.value_type))
}
}
5 changes: 1 addition & 4 deletions aderyn_core/src/ast/impls/disp/user_defined_value_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,6 @@ use std::fmt::Display;

impl Display for UserDefinedValueTypeDefinition {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!(
"type {} is {}",
self.name, self.underlying_type,
))
f.write_fmt(format_args!("type {} is {}", self.name, self.underlying_type,))
}
}
Loading

0 comments on commit 235f900

Please sign in to comment.