ink-analyzer-ir 0.16.1

Intermediate representations (IRs) and abstractions of ink! smart contract code for ink! analyzer.
Documentation
//! Test utilities for IR types and abstractions.

#![cfg(test)]

use ra_ap_syntax::{ast, Edition, NodeOrToken, SyntaxKind, SyntaxNode};
use ra_ap_syntax::{AstNode, SourceFile, SyntaxToken};

use crate::{InkAttribute, InkEntity};

/// Returns the first syntax token in the code snippet.
pub fn parse_first_syntax_token(code: &str) -> SyntaxToken {
    parse_source(code)
        .syntax()
        .descendants_with_tokens()
        .find_map(NodeOrToken::into_token)
        .unwrap()
}

/// Returns the first syntax node in the code snippet.
pub fn parse_first_syntax_node(code: &str) -> SyntaxNode {
    parse_source(code)
        .syntax()
        .descendants()
        .find(|node| node.kind() != SyntaxKind::SOURCE_FILE)
        .unwrap()
}

/// Returns the first AST node of the generic type in the code snippet.
pub fn parse_first_ast_node_of_type<T>(code: &str) -> T
where
    T: AstNode,
{
    parse_source(code)
        .syntax()
        .descendants()
        .find_map(T::cast)
        .unwrap()
}

/// Returns the first attribute in the code snippet.
pub fn parse_first_attribute(code: &str) -> ast::Attr {
    parse_first_ast_node_of_type(code)
}

/// Returns the first ink! attribute in the code snippet.
pub fn parse_first_ink_attribute(code: &str) -> InkAttribute {
    parse_source(code)
        .syntax()
        .descendants()
        .find_map(|node| InkAttribute::cast(ast::Attr::cast(node)?))
        .unwrap()
}

/// Returns the first ink! entity of the generic type in the code snippet.
pub fn first_ink_entity_of_type<T>(code: &str) -> T
where
    T: InkEntity,
{
    parse_source(code)
        .syntax()
        .descendants()
        .find_map(T::cast)
        .unwrap()
}

/// Returns the `SourceFile` for the code snippet.
pub fn parse_source(code: &str) -> SourceFile {
    // TODO: Do we need an edition args?
    SourceFile::parse(code, Edition::Edition2021).tree()
}