Skip to content
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

Change ParseOutput to return a NonTerminal instead of a Node #1187

Open
wants to merge 17 commits into
base: main
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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
use crate::cst::{Cursor, Node, TextIndex};
use std::rc::Rc;

use crate::cst::{Cursor, NonterminalNode, TextIndex};
use crate::parser::ParseError;

#[derive(Debug, PartialEq)]
pub struct ParseOutput {
pub(crate) parse_tree: Node,
pub(crate) parse_tree: Rc<NonterminalNode>,
pub(crate) errors: Vec<ParseError>,
}

impl ParseOutput {
pub fn tree(&self) -> Node {
self.parse_tree.clone()
pub fn tree(&self) -> &Rc<NonterminalNode> {
&self.parse_tree
}

pub fn errors(&self) -> &Vec<ParseError> {
Expand All @@ -22,6 +24,6 @@ impl ParseOutput {

/// Creates a cursor that starts at the root of the parse tree.
pub fn create_tree_cursor(&self) -> Cursor {
self.parse_tree.clone().cursor_with_offset(TextIndex::ZERO)
Rc::clone(&self.parse_tree).cursor_with_offset(TextIndex::ZERO)
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::rc::Rc;

use crate::cst::{Edge, Node, TerminalKind, TerminalKindExtensions, TextIndex};
use crate::cst::{Edge, Node, NonterminalNode, TerminalKind, TerminalKindExtensions, TextIndex};
use crate::parser::lexer::Lexer;
use crate::parser::parser_support::context::ParserContext;
use crate::parser::parser_support::parser_result::{
Expand Down Expand Up @@ -85,14 +85,9 @@ where
TerminalKind::UNRECOGNIZED
};
let node = Node::terminal(kind, input.to_string());
let tree = if no_match.kind.is_none() || start.utf8 == 0 {
node
} else {
trivia_nodes.push(Edge::anonymous(node));
Node::nonterminal(no_match.kind.unwrap(), trivia_nodes)
};
trivia_nodes.push(Edge::anonymous(node));
ParseOutput {
parse_tree: tree,
parse_tree: Rc::new(NonterminalNode::new(no_match.kind.unwrap(), trivia_nodes)),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if we are always unwrapping no_match.kind, should it still be an Option<>?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NoMatch is being used in the default() function with None

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here is an example of how it's used today:

// If the result won't match exactly, we return a dummy `ParserResult::no_match`, since

Copy link
Contributor

@OmarTawfik OmarTawfik Dec 23, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IIUC, in the case you mentioned, the kind is already known (nonterminal_name). Right? Is it possible to initialize it with that expected kind, to prevent another code path from accidentally leaving a None here?

errors: vec![ParseError::new(
start..start + input.into(),
no_match.expected_terminals,
Expand Down Expand Up @@ -156,18 +151,17 @@ where
));

ParseOutput {
parse_tree: Node::nonterminal(topmost_node.kind, new_children),
parse_tree: Rc::new(NonterminalNode::new(topmost_node.kind, new_children)),
errors,
}
} else {
let parse_tree = Node::Nonterminal(topmost_node);
let parse_tree = topmost_node;
let errors = stream.into_errors();

// Sanity check: Make sure that succesful parse is equivalent to not having any invalid nodes
debug_assert_eq!(
errors.is_empty(),
parse_tree
.clone()
Rc::clone(&parse_tree)
.cursor_with_offset(TextIndex::ZERO)
.remaining_nodes()
.all(|edge| edge
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
interface parser {
use cst.{cursor, node, nonterminal-kind, text-range};
use cst.{cursor, nonterminal-node, nonterminal-kind, text-range};

/// A parser instance that can parse source code into syntax trees.
/// Each parser is configured for a specific language version and grammar.
Expand Down Expand Up @@ -36,7 +36,7 @@ interface parser {
resource parse-output {
/// Returns the root node of the parsed syntax tree.
/// Even if there are parsing errors, a partial tree will still be available.
tree: func() -> node;
tree: func() -> nonterminal-node;

/// Returns a list of all parsing errors encountered.
/// An empty list indicates successful parsing with no errors.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
use std::rc::Rc;

use crate::wasm_crate::utils::{define_wrapper, FromFFI, IntoFFI};

mod ffi {
pub use crate::wasm_crate::bindings::exports::nomic_foundation::slang::cst::{
Cursor, Node, TextRange,
Cursor, NonterminalNode, TextRange,
};
pub use crate::wasm_crate::bindings::exports::nomic_foundation::slang::parser::{
Guest, GuestParseError, GuestParseOutput, GuestParser, NonterminalKind, ParseError,
Expand Down Expand Up @@ -77,8 +79,8 @@ define_wrapper! { ParseError {
//================================================

define_wrapper! { ParseOutput {
fn tree(&self) -> ffi::Node {
self._borrow_ffi().tree()._into_ffi()
fn tree(&self) -> ffi::NonterminalNode {
Rc::clone(self._borrow_ffi().tree())._into_ffi()
}

fn errors(&self) -> Vec<ffi::ParseError> {
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions crates/metaslang/cst/generated/public_api.txt

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 13 additions & 7 deletions crates/metaslang/cst/src/nodes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,18 @@ pub struct Edge<T: KindTypes> {
pub node: Node<T>,
}

impl<T: KindTypes> NonterminalNode<T> {
pub fn new(kind: T::NonterminalKind, children: Vec<Edge<T>>) -> Self {
let text_len = children.iter().map(|edge| edge.text_len()).sum();

NonterminalNode {
kind,
text_len,
children,
}
}
}

impl<T: KindTypes> Edge<T> {
/// Creates an anonymous node (without a label).
pub fn anonymous(node: Node<T>) -> Self {
Expand All @@ -81,13 +93,7 @@ impl<T: KindTypes> std::ops::Deref for Edge<T> {

impl<T: KindTypes> Node<T> {
pub fn nonterminal(kind: T::NonterminalKind, children: Vec<Edge<T>>) -> Self {
let text_len = children.iter().map(|edge| edge.text_len()).sum();

Self::Nonterminal(Rc::new(NonterminalNode {
kind,
text_len,
children,
}))
Self::Nonterminal(Rc::new(NonterminalNode::new(kind, children)))
}

pub fn terminal(kind: T::TerminalKind, text: String) -> Self {
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 5 additions & 3 deletions crates/solidity/outputs/cargo/tests/src/bindings.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use std::rc::Rc;
use std::sync::Arc;

use anyhow::Result;
use semver::Version;
use slang_solidity::bindings::{self, Bindings};
use slang_solidity::cst::TextIndex;
use slang_solidity::cst::{Node, TextIndex};
use slang_solidity::parser::Parser;
use slang_solidity::transform_built_ins_node;

Expand All @@ -20,8 +21,9 @@ pub fn create_bindings(version: &Version) -> Result<Bindings> {
"built-ins parse without errors"
);

let built_ins_cursor = transform_built_ins_node(&built_ins_parse_output.tree())
.cursor_with_offset(TextIndex::ZERO);
let built_ins_cursor =
transform_built_ins_node(&Node::Nonterminal(Rc::clone(built_ins_parse_output.tree())))
.cursor_with_offset(TextIndex::ZERO);

bindings.add_system_file("built_ins.sol", built_ins_cursor);
Ok(bindings)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::path::Path;
use std::rc::Rc;

use anyhow::Result;
use infra_utils::paths::PathExtensions;
Expand Down Expand Up @@ -89,8 +90,7 @@ fn using_the_cursor() -> Result<()> {
{
// --8<-- [start:using-iterator-api]

let identifiers: Vec<_> = parse_output
.tree()
let identifiers: Vec<_> = Rc::clone(parse_output.tree())
.descendants()
.filter(|edge| edge.is_terminal_with_kind(TerminalKind::Identifier))
.map(|identifier| identifier.unparse())
Expand All @@ -103,8 +103,7 @@ fn using_the_cursor() -> Result<()> {
{
// --8<-- [start:using-cursors-with-labels]

let identifiers: Vec<_> = parse_output
.tree()
let identifiers: Vec<_> = Rc::clone(parse_output.tree())
.descendants()
.filter(|edge| edge.label == Some(EdgeLabel::Name))
.filter(|edge| edge.is_terminal_with_kind(TerminalKind::Identifier))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,8 @@ fn using_the_parser() -> Result<()> {
// --8<-- [end:assert-is-valid]

// --8<-- [start:inspect-tree]
let parse_tree = parse_output.tree();
let contract = parse_output.tree();

let contract = parse_tree.as_nonterminal().unwrap();
assert_eq!(contract.kind, NonterminalKind::ContractDefinition);
assert_eq!(contract.children.len(), 7);

Expand Down
5 changes: 3 additions & 2 deletions crates/solidity/outputs/cargo/tests/src/trivia.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::rc::Rc;

use anyhow::Result;
use semver::Version;
use slang_solidity::cst::{NonterminalKind, TerminalKind};
Expand Down Expand Up @@ -27,8 +29,7 @@ fn compare_end_of_lines(input: &str, expected: &[&str]) -> Result<()> {
let output = parser.parse(NonterminalKind::SourceUnit, input);
assert!(output.is_valid());

let actual = output
.tree()
let actual = Rc::clone(output.tree())
.descendants()
.filter(|edge| edge.is_terminal_with_kind(TerminalKind::EndOfLine))
.map(|eol| eol.unparse())
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading