Skip to content
Closed
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
2 changes: 1 addition & 1 deletion .noir-sync-commit
Original file line number Diff line number Diff line change
@@ -1 +1 @@
f0c268606a71381ab4504396695a0adb9b3258b6
2f0d4e017b701b46b5c675e3b34af15ad6f28823
8 changes: 8 additions & 0 deletions noir/noir-repo/compiler/noirc_errors/src/reporter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ pub struct CustomDiagnostic {
pub secondaries: Vec<CustomLabel>,
notes: Vec<String>,
pub kind: DiagnosticKind,
pub deprecated: bool,
pub unnecessary: bool,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
Expand All @@ -35,6 +37,8 @@ impl CustomDiagnostic {
secondaries: Vec::new(),
notes: Vec::new(),
kind: DiagnosticKind::Error,
deprecated: false,
unnecessary: false,
}
}

Expand All @@ -49,6 +53,8 @@ impl CustomDiagnostic {
secondaries: vec![CustomLabel::new(secondary_message, secondary_span, None)],
notes: Vec::new(),
kind,
deprecated: false,
unnecessary: false,
}
}

Expand Down Expand Up @@ -101,6 +107,8 @@ impl CustomDiagnostic {
secondaries: vec![CustomLabel::new(secondary_message, secondary_span, None)],
notes: Vec::new(),
kind: DiagnosticKind::Bug,
deprecated: false,
unnecessary: false,
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,20 +150,24 @@ impl<'a> From<&'a ResolverError> for Diagnostic {
ResolverError::UnusedVariable { ident } => {
let name = &ident.0.contents;

Diagnostic::simple_warning(
let mut diagnostic = Diagnostic::simple_warning(
format!("unused variable {name}"),
"unused variable ".to_string(),
ident.span(),
)
);
diagnostic.unnecessary = true;
diagnostic
}
ResolverError::UnusedImport { ident } => {
let name = &ident.0.contents;

Diagnostic::simple_warning(
let mut diagnostic = Diagnostic::simple_warning(
format!("unused import {name}"),
"unused import ".to_string(),
ident.span(),
)
);
diagnostic.unnecessary = true;
diagnostic
}
ResolverError::VariableNotDeclared { name, span } => Diagnostic::simple_error(
format!("cannot find `{name}` in this scope "),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,9 @@ impl<'a> From<&'a TypeCheckError> for Diagnostic {
let primary_message = error.to_string();
let secondary_message = note.clone().unwrap_or_default();

Diagnostic::simple_warning(primary_message, secondary_message, *span)
let mut diagnostic = Diagnostic::simple_warning(primary_message, secondary_message, *span);
diagnostic.deprecated = true;
diagnostic
}
TypeCheckError::UnusedResultError { expr_type, expr_span } => {
let msg = format!("Unused expression result of type {expr_type}");
Expand Down
65 changes: 37 additions & 28 deletions noir/noir-repo/compiler/noirc_frontend/src/parser/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,42 +165,51 @@ impl std::fmt::Display for ParserError {
impl<'a> From<&'a ParserError> for Diagnostic {
fn from(error: &'a ParserError) -> Diagnostic {
match &error.reason {
Some(reason) => {
match reason {
ParserErrorReason::ConstrainDeprecated => Diagnostic::simple_error(
Some(reason) => match reason {
ParserErrorReason::ConstrainDeprecated => {
let mut diagnostic = Diagnostic::simple_error(
"Use of deprecated keyword 'constrain'".into(),
"The 'constrain' keyword is deprecated. Please use the 'assert' function instead.".into(),
error.span,
),
ParserErrorReason::ComptimeDeprecated => Diagnostic::simple_warning(
);
diagnostic.deprecated = true;
diagnostic
}
ParserErrorReason::ComptimeDeprecated => {
let mut diagnostic = Diagnostic::simple_warning(
"Use of deprecated keyword 'comptime'".into(),
"The 'comptime' keyword has been deprecated. It can be removed without affecting your program".into(),
error.span,
) ;
diagnostic.deprecated = true;
diagnostic
}
ParserErrorReason::InvalidBitSize(bit_size) => Diagnostic::simple_error(
format!("Use of invalid bit size {}", bit_size),
format!(
"Allowed bit sizes for integers are {}",
IntegerBitSize::allowed_sizes()
.iter()
.map(|n| n.to_string())
.collect::<Vec<_>>()
.join(", ")
),
ParserErrorReason::InvalidBitSize(bit_size) => Diagnostic::simple_error(
format!("Use of invalid bit size {}", bit_size),
format!("Allowed bit sizes for integers are {}", IntegerBitSize::allowed_sizes().iter().map(|n| n.to_string()).collect::<Vec<_>>().join(", ")),
error.span,
),
ParserErrorReason::ExperimentalFeature(_) => Diagnostic::simple_warning(
reason.to_string(),
"".into(),
error.span,
),
ParserErrorReason::TraitImplFunctionModifiers => Diagnostic::simple_warning(
reason.to_string(),
"".into(),
error.span,
),
ParserErrorReason::ExpectedPatternButFoundType(ty) => {
Diagnostic::simple_error("Expected a ; separating these two statements".into(), format!("{ty} is a type and cannot be used as a variable name"), error.span)
}
ParserErrorReason::Lexer(error) => error.into(),
other => {
Diagnostic::simple_error(format!("{other}"), String::new(), error.span)
}
error.span,
),
ParserErrorReason::ExperimentalFeature(_) => {
Diagnostic::simple_warning(reason.to_string(), "".into(), error.span)
}
}
ParserErrorReason::TraitImplFunctionModifiers => {
Diagnostic::simple_warning(reason.to_string(), "".into(), error.span)
}
ParserErrorReason::ExpectedPatternButFoundType(ty) => Diagnostic::simple_error(
"Expected a ; separating these two statements".into(),
format!("{ty} is a type and cannot be used as a variable name"),
error.span,
),
ParserErrorReason::Lexer(error) => error.into(),
other => Diagnostic::simple_error(format!("{other}"), String::new(), error.span),
},
None => {
let primary = error.to_string();
Diagnostic::simple_error(primary, String::new(), error.span)
Expand Down
20 changes: 12 additions & 8 deletions noir/noir-repo/compiler/noirc_frontend/src/resolve_locations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use noirc_errors::Location;
use crate::hir_def::expr::HirExpression;
use crate::hir_def::types::Type;

use crate::node_interner::{DefinitionKind, Node, NodeInterner};
use crate::node_interner::{DefinitionId, DefinitionKind, Node, NodeInterner};

impl NodeInterner {
/// Scans the interner for the item which is located at that [Location]
Expand Down Expand Up @@ -108,14 +108,18 @@ impl NodeInterner {
) -> Option<Location> {
match expression {
HirExpression::Ident(ident, _) => {
let definition_info = self.definition(ident.id);
match definition_info.kind {
DefinitionKind::Function(func_id) => {
Some(self.function_meta(&func_id).location)
if ident.id != DefinitionId::dummy_id() {
let definition_info = self.definition(ident.id);
match definition_info.kind {
DefinitionKind::Function(func_id) => {
Some(self.function_meta(&func_id).location)
}
DefinitionKind::Local(_local_id) => Some(definition_info.location),
DefinitionKind::Global(_global_id) => Some(definition_info.location),
_ => None,
}
DefinitionKind::Local(_local_id) => Some(definition_info.location),
DefinitionKind::Global(_global_id) => Some(definition_info.location),
_ => None,
} else {
None
}
}
HirExpression::Constructor(expr) => {
Expand Down
18 changes: 11 additions & 7 deletions noir/noir-repo/tooling/lsp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ use fm::{codespan_files as files, FileManager};
use fxhash::FxHashSet;
use lsp_types::{
request::{
Completion, DocumentSymbolRequest, HoverRequest, InlayHintRequest, PrepareRenameRequest,
References, Rename, SignatureHelpRequest,
CodeActionRequest, Completion, DocumentSymbolRequest, HoverRequest, InlayHintRequest,
PrepareRenameRequest, References, Rename, SignatureHelpRequest,
},
CodeLens,
};
Expand Down Expand Up @@ -51,21 +51,24 @@ use notifications::{
on_did_open_text_document, on_did_save_text_document, on_exit, on_initialized,
};
use requests::{
on_code_lens_request, on_completion_request, on_document_symbol_request, on_formatting,
on_goto_declaration_request, on_goto_definition_request, on_goto_type_definition_request,
on_hover_request, on_initialize, on_inlay_hint_request, on_prepare_rename_request,
on_profile_run_request, on_references_request, on_rename_request, on_shutdown,
on_signature_help_request, on_test_run_request, on_tests_request, LspInitializationOptions,
on_code_action_request, on_code_lens_request, on_completion_request,
on_document_symbol_request, on_formatting, on_goto_declaration_request,
on_goto_definition_request, on_goto_type_definition_request, on_hover_request, on_initialize,
on_inlay_hint_request, on_prepare_rename_request, on_profile_run_request,
on_references_request, on_rename_request, on_shutdown, on_signature_help_request,
on_test_run_request, on_tests_request, LspInitializationOptions,
};
use serde_json::Value as JsonValue;
use thiserror::Error;
use tower::Service;

mod modules;
mod notifications;
mod requests;
mod solver;
mod types;
mod utils;
mod visibility;

#[cfg(test)]
mod test_utils;
Expand Down Expand Up @@ -144,6 +147,7 @@ impl NargoLspService {
.request::<InlayHintRequest, _>(on_inlay_hint_request)
.request::<Completion, _>(on_completion_request)
.request::<SignatureHelpRequest, _>(on_signature_help_request)
.request::<CodeActionRequest, _>(on_code_action_request)
.notification::<notification::Initialized>(on_initialized)
.notification::<notification::DidChangeConfiguration>(on_did_change_configuration)
.notification::<notification::DidOpenTextDocument>(on_did_open_text_document)
Expand Down
131 changes: 131 additions & 0 deletions noir/noir-repo/tooling/lsp/src/modules.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
use std::collections::BTreeMap;

use noirc_frontend::{
ast::ItemVisibility,
graph::CrateId,
hir::def_map::{CrateDefMap, ModuleId},
macros_api::{ModuleDefId, NodeInterner},
node_interner::ReferenceId,
};

use crate::visibility::is_visible;

pub(crate) fn get_parent_module(
interner: &NodeInterner,
module_def_id: ModuleDefId,
) -> Option<ModuleId> {
let reference_id = module_def_id_to_reference_id(module_def_id);
interner.reference_module(reference_id).copied()
}

pub(crate) fn get_parent_module_id(
def_maps: &BTreeMap<CrateId, CrateDefMap>,
module_id: ModuleId,
) -> Option<ModuleId> {
let crate_def_map = &def_maps[&module_id.krate];
let module_data = &crate_def_map.modules()[module_id.local_id.0];
module_data.parent.map(|parent| ModuleId { krate: module_id.krate, local_id: parent })
}

pub(crate) fn module_def_id_to_reference_id(module_def_id: ModuleDefId) -> ReferenceId {
match module_def_id {
ModuleDefId::ModuleId(id) => ReferenceId::Module(id),
ModuleDefId::FunctionId(id) => ReferenceId::Function(id),
ModuleDefId::TypeId(id) => ReferenceId::Struct(id),
ModuleDefId::TypeAliasId(id) => ReferenceId::Alias(id),
ModuleDefId::TraitId(id) => ReferenceId::Trait(id),
ModuleDefId::GlobalId(id) => ReferenceId::Global(id),
}
}

/// Returns the fully-qualified path of the given `ModuleDefId` relative to `current_module_id`:
/// - If `ModuleDefId` is a module, that module's path is returned
/// - Otherwise, that item's parent module's path is returned
pub(crate) fn module_full_path(
module_def_id: ModuleDefId,
visibility: ItemVisibility,
current_module_id: ModuleId,
current_module_parent_id: Option<ModuleId>,
interner: &NodeInterner,
) -> Option<String> {
let full_path;
if let ModuleDefId::ModuleId(module_id) = module_def_id {
if !is_visible(visibility, current_module_id, module_id) {
return None;
}

full_path =
module_id_path(module_id, &current_module_id, current_module_parent_id, interner);
} else {
let Some(parent_module) = get_parent_module(interner, module_def_id) else {
return None;
};

if !is_visible(visibility, current_module_id, parent_module) {
return None;
}

full_path =
module_id_path(parent_module, &current_module_id, current_module_parent_id, interner);
}
Some(full_path)
}

/// Returns the path to reach an item inside `target_module_id` from inside `current_module_id`.
/// Returns a relative path if possible.
pub(crate) fn module_id_path(
target_module_id: ModuleId,
current_module_id: &ModuleId,
current_module_parent_id: Option<ModuleId>,
interner: &NodeInterner,
) -> String {
if Some(target_module_id) == current_module_parent_id {
return "super".to_string();
}

let mut segments: Vec<&str> = Vec::new();
let mut is_relative = false;

if let Some(module_attributes) = interner.try_module_attributes(&target_module_id) {
segments.push(&module_attributes.name);

let mut current_attributes = module_attributes;
loop {
let Some(parent_local_id) = current_attributes.parent else {
break;
};

let parent_module_id =
&ModuleId { krate: target_module_id.krate, local_id: parent_local_id };

if current_module_id == parent_module_id {
is_relative = true;
break;
}

if current_module_parent_id == Some(*parent_module_id) {
segments.push("super");
is_relative = true;
break;
}

let Some(parent_attributes) = interner.try_module_attributes(parent_module_id) else {
break;
};

segments.push(&parent_attributes.name);
current_attributes = parent_attributes;
}
}

if !is_relative {
// We don't record module attributes for the root module,
// so we handle that case separately
if let CrateId::Root(_) = target_module_id.krate {
segments.push("crate");
}
}

segments.reverse();
segments.join("::")
}
Loading