Skip to content

Commit

Permalink
Made inline macros pluginable.
Browse files Browse the repository at this point in the history
commit-id:3784e194
  • Loading branch information
orizi committed Aug 14, 2023
1 parent 4398bf0 commit 19def5e
Show file tree
Hide file tree
Showing 11 changed files with 58 additions and 23 deletions.
21 changes: 18 additions & 3 deletions crates/cairo-lang-compiler/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::sync::Arc;

use anyhow::{anyhow, Result};
use cairo_lang_defs::db::{DefsDatabase, DefsGroup};
use cairo_lang_defs::plugin::MacroPlugin;
use cairo_lang_defs::plugin::{InlineMacroExprPlugin, MacroPlugin};
use cairo_lang_filesystem::cfg::CfgSet;
use cairo_lang_filesystem::db::{
init_dev_corelib, init_files_group, AsFilesGroupMut, FilesDatabase, FilesGroup, FilesGroupEx,
Expand All @@ -15,6 +15,7 @@ use cairo_lang_parser::db::ParserDatabase;
use cairo_lang_plugins::get_default_plugins;
use cairo_lang_project::ProjectConfig;
use cairo_lang_semantic::db::{SemanticDatabase, SemanticGroup};
use cairo_lang_semantic::inline_macros::get_default_inline_macro_plugins;
use cairo_lang_sierra_generator::db::SierraGenDatabase;
use cairo_lang_syntax::node::db::{SyntaxDatabase, SyntaxGroup};
use cairo_lang_utils::Upcast;
Expand All @@ -40,10 +41,14 @@ impl salsa::ParallelDatabase for RootDatabase {
}
}
impl RootDatabase {
fn new(plugins: Vec<Arc<dyn MacroPlugin>>) -> Self {
fn new(
plugins: Vec<Arc<dyn MacroPlugin>>,
inline_macro_plugins: Vec<Arc<dyn InlineMacroExprPlugin>>,
) -> Self {
let mut res = Self { storage: Default::default() };
init_files_group(&mut res);
res.set_macro_plugins(plugins);
res.set_inline_macro_plugins(inline_macro_plugins);
res
}

Expand All @@ -70,6 +75,7 @@ impl Default for RootDatabase {
#[derive(Clone, Debug)]
pub struct RootDatabaseBuilder {
plugins: Vec<Arc<dyn MacroPlugin>>,
inline_macro_plugins: Vec<Arc<dyn InlineMacroExprPlugin>>,
detect_corelib: bool,
project_config: Option<Box<ProjectConfig>>,
cfg_set: Option<CfgSet>,
Expand All @@ -79,6 +85,7 @@ impl RootDatabaseBuilder {
fn new() -> Self {
Self {
plugins: get_default_plugins(),
inline_macro_plugins: get_default_inline_macro_plugins(),
detect_corelib: false,
project_config: None,
cfg_set: None,
Expand All @@ -90,6 +97,14 @@ impl RootDatabaseBuilder {
self
}

pub fn with_inline_macro_plugin(
&mut self,
plugin: Arc<dyn InlineMacroExprPlugin>,
) -> &mut Self {
self.inline_macro_plugins.push(plugin);
self
}

pub fn clear_plugins(&mut self) -> &mut Self {
self.plugins.clear();
self
Expand All @@ -115,7 +130,7 @@ impl RootDatabaseBuilder {
// Errors if something is not OK are very subtle, mostly this results in missing
// identifier diagnostics, or panics regarding lack of corelib items.

let mut db = RootDatabase::new(self.plugins.clone());
let mut db = RootDatabase::new(self.plugins.clone(), self.inline_macro_plugins.clone());

if let Some(cfg_set) = &self.cfg_set {
db.use_cfg(cfg_set);
Expand Down
6 changes: 5 additions & 1 deletion crates/cairo-lang-defs/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ use cairo_lang_utils::Upcast;

use crate::ids::*;
use crate::patcher::Patches;
use crate::plugin::{DynGeneratedFileAuxData, MacroPlugin, PluginDiagnostic};
use crate::plugin::{
DynGeneratedFileAuxData, InlineMacroExprPlugin, MacroPlugin, PluginDiagnostic,
};

/// Salsa database interface.
/// See [`super::ids`] for further details.
Expand Down Expand Up @@ -65,6 +67,8 @@ pub trait DefsGroup:
// ========
#[salsa::input]
fn macro_plugins(&self) -> Vec<Arc<dyn MacroPlugin>>;
#[salsa::input]
fn inline_macro_plugins(&self) -> Vec<Arc<dyn InlineMacroExprPlugin>>;

// Module to syntax.
/// Gets the main file of the module.
Expand Down
5 changes: 4 additions & 1 deletion crates/cairo-lang-defs/src/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,10 @@ pub struct InlinePluginResult {
pub diagnostics: Vec<PluginDiagnostic>,
}

pub trait InlineMacroPlugin: std::fmt::Debug + Sync + Send {
pub trait InlineMacroExprPlugin: std::fmt::Debug + Sync + Send {
/// Returns the name of the inline macro.
fn name(&self) -> &str;

/// Generates code for an item. If no code should be generated returns None.
/// Otherwise, returns (virtual_module_name, module_content), and a virtual submodule
/// with that name and content should be created.
Expand Down
2 changes: 2 additions & 0 deletions crates/cairo-lang-lowering/src/test_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use cairo_lang_filesystem::detect::detect_corelib;
use cairo_lang_parser::db::ParserDatabase;
use cairo_lang_plugins::get_default_plugins;
use cairo_lang_semantic::db::{SemanticDatabase, SemanticGroup};
use cairo_lang_semantic::inline_macros::get_default_inline_macro_plugins;
use cairo_lang_syntax::node::db::{SyntaxDatabase, SyntaxGroup};
use cairo_lang_utils::Upcast;
use once_cell::sync::Lazy;
Expand Down Expand Up @@ -41,6 +42,7 @@ pub static SHARED_DB: Lazy<Mutex<LoweringDatabaseForTesting>> = Lazy::new(|| {
let mut res = LoweringDatabaseForTesting { storage: Default::default() };
init_files_group(&mut res);
res.set_macro_plugins(get_default_plugins());
res.set_inline_macro_plugins(get_default_inline_macro_plugins());
let corelib_path = detect_corelib().expect("Corelib not found in default location.");
init_dev_corelib(&mut res, corelib_path);
Mutex::new(res)
Expand Down
5 changes: 3 additions & 2 deletions crates/cairo-lang-semantic/src/expr/compute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ use crate::diagnostic::SemanticDiagnosticKind::{self, *};
use crate::diagnostic::{
ElementKind, NotFoundItemType, SemanticDiagnostics, UnsupportedOutsideOfFunctionFeatureName,
};
use crate::inline_macros::get_inline_macro_plugin;
use crate::items::enm::SemanticEnumEx;
use crate::items::imp::{filter_candidate_traits, infer_impl_by_self};
use crate::items::modifiers::compute_mutability;
Expand Down Expand Up @@ -284,7 +283,9 @@ fn compute_expr_inline_macro_semantic(
let syntax_db = ctx.db.upcast();

let macro_name = syntax.path(syntax_db).as_syntax_node().get_text(syntax_db).trim().to_string();
let Some(macro_plugin) = get_inline_macro_plugin(&macro_name) else {
let Some(macro_plugin) =
ctx.db.inline_macro_plugins().into_iter().find(|plugin| plugin.name() == macro_name)
else {
return Err(ctx
.diagnostics
.report(syntax, InlineMacroNotFound { macro_name: macro_name.into() }));
Expand Down
8 changes: 6 additions & 2 deletions crates/cairo-lang-semantic/src/inline_macros/array.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
use cairo_lang_defs::plugin::{InlineMacroPlugin, InlinePluginResult};
use cairo_lang_defs::plugin::{InlineMacroExprPlugin, InlinePluginResult};
use cairo_lang_syntax::node::db::SyntaxGroup;
use cairo_lang_syntax::node::{ast, TypedSyntaxNode};

use super::unsupported_bracket_diagnostic;

#[derive(Debug)]
pub struct ArrayMacro;
impl InlineMacroPlugin for ArrayMacro {
impl InlineMacroExprPlugin for ArrayMacro {
fn name(&self) -> &str {
"array"
}

fn generate_code(
&self,
db: &dyn SyntaxGroup,
Expand Down
8 changes: 6 additions & 2 deletions crates/cairo-lang-semantic/src/inline_macros/consteval_int.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use cairo_lang_defs::plugin::{InlineMacroPlugin, InlinePluginResult, PluginDiagnostic};
use cairo_lang_defs::plugin::{InlineMacroExprPlugin, InlinePluginResult, PluginDiagnostic};
use cairo_lang_syntax::node::db::SyntaxGroup;
use cairo_lang_syntax::node::{ast, TypedSyntaxNode};
use num_bigint::BigInt;
Expand All @@ -8,7 +8,11 @@ use super::unsupported_bracket_diagnostic;
#[derive(Debug)]
pub struct ConstevalIntMacro;

impl InlineMacroPlugin for ConstevalIntMacro {
impl InlineMacroExprPlugin for ConstevalIntMacro {
fn name(&self) -> &str {
"consteval_int"
}

fn generate_code(
&self,
db: &dyn SyntaxGroup,
Expand Down
20 changes: 9 additions & 11 deletions crates/cairo-lang-semantic/src/inline_macros/mod.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,22 @@
pub mod array;
pub mod consteval_int;
mod array;
mod consteval_int;

use cairo_lang_defs::plugin::{InlineMacroPlugin, InlinePluginResult, PluginDiagnostic};
use std::sync::Arc;

use cairo_lang_defs::plugin::{InlineMacroExprPlugin, InlinePluginResult, PluginDiagnostic};
use cairo_lang_syntax::node::ast::{self};
use cairo_lang_syntax::node::db::SyntaxGroup;
use cairo_lang_syntax::node::TypedSyntaxNode;

use super::inline_macros::array::ArrayMacro;
use super::inline_macros::consteval_int::ConstevalIntMacro;

/// Returns the inline macro plugin for the given macro name, or None if no such plugin exists.
pub fn get_inline_macro_plugin(macro_name: &str) -> Option<Box<dyn InlineMacroPlugin>> {
match macro_name {
"array" => Some(Box::new(ArrayMacro)),
"consteval_int" => Some(Box::new(ConstevalIntMacro)),
_ => None,
}
/// Gets the list of default plugins to load into the Cairo compiler.
pub fn get_default_inline_macro_plugins() -> Vec<Arc<dyn InlineMacroExprPlugin>> {
vec![Arc::new(ArrayMacro), Arc::new(ConstevalIntMacro)]
}

pub fn unsupported_bracket_diagnostic(
fn unsupported_bracket_diagnostic(
db: &dyn SyntaxGroup,
macro_ast: &ast::ExprInlineMacro,
) -> InlinePluginResult {
Expand Down
2 changes: 1 addition & 1 deletion crates/cairo-lang-semantic/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ pub mod corelib;
pub mod db;
pub mod diagnostic;
pub mod expr;
mod inline_macros;
pub mod inline_macros;
pub mod items;
pub mod literals;
pub mod lookup_item;
Expand Down
2 changes: 2 additions & 0 deletions crates/cairo-lang-semantic/src/test_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use cairo_lang_utils::{extract_matches, OptionFrom, Upcast};
use once_cell::sync::Lazy;

use crate::db::{SemanticDatabase, SemanticGroup};
use crate::inline_macros::get_default_inline_macro_plugins;
use crate::items::functions::GenericFunctionId;
use crate::{semantic, ConcreteFunctionWithBodyId, SemanticDiagnostic};

Expand All @@ -37,6 +38,7 @@ impl SemanticDatabaseForTesting {
let mut res = SemanticDatabaseForTesting { storage: Default::default() };
init_files_group(&mut res);
res.set_macro_plugins(get_default_plugins());
res.set_inline_macro_plugins(get_default_inline_macro_plugins());
let corelib_path = detect_corelib().expect("Corelib not found in default location.");
init_dev_corelib(&mut res, corelib_path);
res
Expand Down
2 changes: 2 additions & 0 deletions crates/cairo-lang-sierra-generator/src/test_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ use cairo_lang_utils::{Upcast, UpcastMut};
use defs::ids::FreeFunctionId;
use lowering::ids::ConcreteFunctionWithBodyLongId;
use once_cell::sync::Lazy;
use semantic::inline_macros::get_default_inline_macro_plugins;
use {cairo_lang_defs as defs, cairo_lang_lowering as lowering, cairo_lang_semantic as semantic};

use crate::db::{SierraGenDatabase, SierraGenGroup};
Expand Down Expand Up @@ -59,6 +60,7 @@ impl SierraGenDatabaseForTesting {
let mut res = SierraGenDatabaseForTesting { storage: Default::default() };
init_files_group(&mut res);
res.set_macro_plugins(get_default_plugins());
res.set_inline_macro_plugins(get_default_inline_macro_plugins());
let corelib_path = detect_corelib().expect("Corelib not found in default location.");
init_dev_corelib(&mut res, corelib_path);
res
Expand Down

0 comments on commit 19def5e

Please sign in to comment.