Skip to content

Commit

Permalink
Improved const item type acquisition logic
Browse files Browse the repository at this point in the history
  • Loading branch information
integraledelebesgue committed Oct 28, 2024
1 parent cd2ec14 commit d6b9dc6
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
17 changes: 11 additions & 6 deletions crates/cairo-lang-language-server/src/ide/hover/render/literal.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use cairo_lang_defs::ids::FunctionWithBodyId;
use cairo_lang_defs::ids::{ConstantLongId, FunctionWithBodyId};
use cairo_lang_filesystem::ids::FileId;
use cairo_lang_semantic::db::SemanticGroup;
use cairo_lang_semantic::items::function_with_body::SemanticExprLookup;
Expand All @@ -8,7 +8,7 @@ use cairo_lang_syntax::node::ast::{
};
use cairo_lang_syntax::node::kind::SyntaxKind;
use cairo_lang_syntax::node::{SyntaxNode, TypedSyntaxNode};
use cairo_lang_utils::Upcast;
use cairo_lang_utils::{Intern, Upcast};
use indoc::formatdoc;
use lsp_types::Hover;

Expand Down Expand Up @@ -46,7 +46,9 @@ pub fn literal(db: &AnalysisDatabase, node: &SyntaxNode, file_id: FileId) -> Opt

/// Gets the type of an expression associated with [`SyntaxNode`].
fn find_type(db: &AnalysisDatabase, node: SyntaxNode) -> Option<String> {
if let Some(function_id) = db.find_lookup_item(&node)?.function_with_body() {
let lookup_item = db.find_lookup_item(&node)?;

if let Some(function_id) = lookup_item.function_with_body() {
find_type_in_function_context(db, node.clone(), function_id)
} else {
find_type_in_const_declaration(db, node)
Expand All @@ -65,17 +67,20 @@ fn find_type_in_function_context(
Some(db.expr_semantic(function_id, expr_id).ty().format(db))
}

// TODO: think about something better
/// Gets the type of an expression associated with [`SyntaxNode`] assuming it's a const item.
fn find_type_in_const_declaration(db: &AnalysisDatabase, node: SyntaxNode) -> Option<String> {
let module_file_id = db.find_module_file_containing_node(&node)?;

let mut node = node;

while node.kind(db) != SyntaxKind::ItemConstant {
node = node.parent()?;
}

let declaration = ItemConstant::from_syntax_node(db, node);
Some(declaration.type_clause(db).ty(db).as_syntax_node().get_text(db))
let const_item = ItemConstant::from_syntax_node(db, node);
let item_id = ConstantLongId(module_file_id, const_item.stable_ptr()).intern(db);

Some(db.constant_const_type(item_id).ok()?.format(db))
}

/// Formats the number literal writing its decimal, hexadecimal and binary value and type.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ const SOME_CONST: felt252 = 0x<caret>123;
const SOME_CONST: felt252 = <sel>0x123</sel>;
// = popover
```cairo
felt252
core::felt252
```
---
value of literal: `291 (0x123 | 0b100100011)`
Expand Down

0 comments on commit d6b9dc6

Please sign in to comment.