Skip to content

Add items callsite modifier. #7660

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: high-level-inline-macros
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
36 changes: 33 additions & 3 deletions corelib/src/test/language_features/macro_test.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,14 @@ mod test_assert_eq {
macro assert_eq {
($left:ident, $right:ident) => {
if $left != $right {
panic!("PANIC!");
// TODO(Gil): Call `panic!` directly when $callsite is supported inside plugins.
$callsite::panic();
}
};
}

fn panic() {
panic!("PANIC!");
}
#[test]
#[should_panic(expected: ("PANIC!",))]
fn test_user_defined_assert_eq() {
Expand Down Expand Up @@ -284,7 +287,10 @@ mod repetition_macro_expansion {
};

[$x:expr, $y:expr] => {
array![$x, $y]
let mut arr = $defsite::ArrayTrait::new();
arr.append($x);
arr.append($y);
arr
};
}

Expand All @@ -299,3 +305,27 @@ mod repetition_macro_expansion {
assert_eq!(expected_ident, actual_ident);
}
}

mod callsite_test {
fn foo(x: felt252) -> felt252 {
x + 100
}

mod inner {
fn foo(x: felt252) -> felt252 {
x + 200
}

pub macro call_foo {
($x:expr) => {
$callsite::foo($x)
};
}
}

#[test]
fn test_callsite_resolution() {
assert_eq!(inner::call_foo!(5), 105);
assert_eq!(inner::call_foo!((foo(5))), 205);
}
}
9 changes: 8 additions & 1 deletion crates/cairo-lang-semantic/src/diagnostic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -970,6 +970,11 @@ impl DiagnosticEntry for SemanticDiagnostic {
SemanticDiagnosticKind::EmptyPathAfterResolverModifier => {
"Empty path after `$defsite` is not allowed.".into()
}
SemanticDiagnosticKind::PathInMacroWithoutModifier => {
"Path in a macro without a resolver modifier ($callsite or $defsite) - currently \
resolving as $callsite but this will not be supported in future versions."
.into()
}
SemanticDiagnosticKind::CannotCreateInstancesOfPhantomTypes => {
"Can not create instances of phantom types.".into()
}
Expand Down Expand Up @@ -1099,7 +1104,8 @@ impl DiagnosticEntry for SemanticDiagnostic {
| SemanticDiagnosticKind::CallingShadowedFunction { .. }
| SemanticDiagnosticKind::UnusedConstant
| SemanticDiagnosticKind::UnusedUse
| SemanticDiagnosticKind::UnsupportedAllowAttrArguments => Severity::Warning,
| SemanticDiagnosticKind::UnsupportedAllowAttrArguments
| SemanticDiagnosticKind::PathInMacroWithoutModifier => Severity::Warning,
SemanticDiagnosticKind::PluginDiagnostic(diag) => diag.severity,
_ => Severity::Error,
}
Expand Down Expand Up @@ -1471,6 +1477,7 @@ pub enum SemanticDiagnosticKind {
modifier: SmolStr,
},
EmptyPathAfterResolverModifier,
PathInMacroWithoutModifier,
DerefCycle {
deref_chain: String,
},
Expand Down
21 changes: 16 additions & 5 deletions crates/cairo-lang-semantic/src/expr/compute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ use crate::items::us::get_use_path_segments;
use crate::items::visibility;
use crate::resolve::{
AsSegments, EnrichedMembers, EnrichedTypeMemberAccess, ResolutionContext, ResolvedConcreteItem,
ResolvedGenericItem, Resolver,
ResolvedGenericItem, Resolver, ResolverMacroData,
};
use crate::semantic::{self, Binding, FunctionId, LocalVariable, TypeId, TypeLongId};
use crate::substitution::SemanticRewriter;
Expand Down Expand Up @@ -481,7 +481,6 @@ fn compute_expr_inline_macro_semantic(
) -> Maybe<Expr> {
let db = ctx.db;
let macro_name = syntax.path(db).identifier(ctx.db).to_string();
let prev_macro_resolver_data = ctx.resolver.macro_defsite_data.clone();
let crate_id = ctx.resolver.owning_crate_id;
// Skipping expanding an inline macro if it had a parser error.
if syntax.as_syntax_node().descendants(db).any(|node| {
Expand All @@ -507,6 +506,9 @@ fn compute_expr_inline_macro_semantic(
NotFoundItemType::Macro,
ResolutionContext::Statement(&mut ctx.environment),
);
let inference_id = ctx.resolver.inference().inference_id;
let prev_macro_resolver_data = ctx.resolver.macro_call_data.clone();
let callsite_resolver = ctx.resolver.data.clone_with_inference_id(ctx.db, inference_id);
let (content, name, mappings, is_macro_rule) =
if let Ok(ResolvedGenericItem::Macro(macro_declaration_id)) = user_defined_macro {
let macro_rules = ctx.db.macro_declaration_rules(macro_declaration_id)?;
Expand All @@ -523,9 +525,18 @@ fn compute_expr_inline_macro_semantic(
let mut matcher_ctx =
MatcherContext { captures, placeholder_to_rep_id, ..Default::default() };
let expanded_code = expand_macro_rule(ctx.db, rule, &mut matcher_ctx)?;
let macro_resolver_data =

let macro_defsite_resolver_data =
ctx.db.macro_declaration_resolver_data(macro_declaration_id)?;
ctx.resolver.macro_defsite_data = Some(macro_resolver_data);
let parent_macro_call_data = ctx.resolver.macro_call_data.clone();
ctx.resolver.macro_call_data = Some(ResolverMacroData {
defsite_data: macro_defsite_resolver_data,
callsite_data: callsite_resolver
.clone_with_inference_id(ctx.db, inference_id)
.into(),
expansion_result: expanded_code.clone().into(),
parent_macro_call_data: parent_macro_call_data.map(|data| data.into()),
});
(expanded_code.text, macro_name.into(), expanded_code.code_mappings, true)
} else if let Some(macro_plugin_id) =
ctx.db.crate_inline_macro_plugins(crate_id).get(&macro_name).cloned()
Expand Down Expand Up @@ -589,7 +600,7 @@ fn compute_expr_inline_macro_semantic(
} else {
compute_expr_semantic(ctx, &expr_syntax)
};
ctx.resolver.macro_defsite_data = prev_macro_resolver_data;
ctx.resolver.macro_call_data = prev_macro_resolver_data;
Ok(expr.expr)
}

Expand Down
54 changes: 49 additions & 5 deletions crates/cairo-lang-semantic/src/expr/test_data/inline_macros
Original file line number Diff line number Diff line change
Expand Up @@ -1015,11 +1015,15 @@ foo
macro assert_eq {
($x:ident, $y:ident) => {
if $x != $y {
panic!("Panic!");
$defsite::panic();
}
};
}

fn panic() {
panic!("Panic!");
}

//! > expected_diagnostics

//! > ==========================================================================
Expand Down Expand Up @@ -1161,6 +1165,11 @@ macro bas_use_z_from_callsite {
fn consume_z(_z: felt252) {}

//! > expected_diagnostics
warning: Path in a macro without a resolver modifier ($callsite or $defsite) - currently resolving as $callsite but this will not be supported in future versions.
--> lib.cairo[bas_use_z_from_callsite]:2:9
z
^

error[E0006]: Identifier not found.
--> lib.cairo[bas_use_z_from_callsite]:2:9
z
Expand Down Expand Up @@ -1200,10 +1209,40 @@ macro wrap_bas_use_z_from_callsite {
}

//! > expected_diagnostics
error: `$callsite` is not supported.
--> lib.cairo[wrap_bas_use_z_from_callsite][bas_use_z_from_callsite]:2:10
error[E0006]: Identifier not found.
--> lib.cairo[wrap_bas_use_z_from_callsite][bas_use_z_from_callsite]:2:20
$callsite::z
^^^^^^^^
^

//! > ==========================================================================

//! > Test usage of a callsite function with no callsite.

//! > test_runner_name
test_function_diagnostics(expect_diagnostics: warnings_only)

//! > function
fn foo() {
call_bar!();
}

//! > function_name
foo

//! > module_code
macro call_bar {
() => {
bar()
};
}

fn bar() {}

//! > expected_diagnostics
warning: Path in a macro without a resolver modifier ($callsite or $defsite) - currently resolving as $callsite but this will not be supported in future versions.
--> lib.cairo[call_bar]:2:9
bar()
^^^

//! > ==========================================================================

Expand All @@ -1216,7 +1255,7 @@ test_function_diagnostics(expect_diagnostics: true)
fn foo() {
test_macro!();
}

//! > function_name
foo

Expand All @@ -1228,6 +1267,11 @@ macro test_macro {
}

//! > expected_diagnostics
error: Missing token '}'.
--> lib.cairo:7:19
test_macro!();
^

error: No matching rule found in inline macro `test_macro`.
--> lib.cairo:7:5
test_macro!();
Expand Down
Loading