Skip to content

Commit

Permalink
refactored code
Browse files Browse the repository at this point in the history
  • Loading branch information
harshdoesdev authored and amitu committed Mar 8, 2024
1 parent 6177965 commit fdf29a6
Show file tree
Hide file tree
Showing 8 changed files with 143 additions and 90 deletions.
11 changes: 11 additions & 0 deletions ftd/src/ast/component.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ impl ComponentDefinition {

#[derive(Debug, Clone, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct Component {
pub id: Option<String>,
pub name: String,
pub properties: Vec<Property>,
pub iteration: Option<Loop>,
Expand All @@ -90,7 +91,9 @@ pub struct Component {
}

impl Component {
#[allow(clippy::too_many_arguments)]
fn new(
id: Option<String>,
name: &str,
properties: Vec<Property>,
iteration: Option<Loop>,
Expand All @@ -100,6 +103,7 @@ impl Component {
line_number: usize,
) -> Component {
Component {
id,
name: name.to_string(),
properties,
iteration,
Expand Down Expand Up @@ -178,8 +182,10 @@ impl Component {
let iteration = Loop::from_headers(&section.headers, doc_id)?;
let events = Event::from_headers(&section.headers, doc_id)?;
let condition = ftd::ast::Condition::from_headers(&section.headers, doc_id)?;
let id = ftd::ast::utils::get_component_id(&section.headers, doc_id)?;

Ok(Component::new(
id,
section.name.as_str(),
properties,
iteration,
Expand All @@ -200,6 +206,7 @@ impl Component {
Component::from_variable_value(key, value.unwrap(), doc_id)
}
ftd::ast::VariableValue::Optional { line_number, .. } => Ok(ftd::ast::Component {
id: None,
name: key.to_string(),
properties: vec![],
iteration: None,
Expand All @@ -209,6 +216,7 @@ impl Component {
line_number,
}),
ftd::ast::VariableValue::Constant { line_number, .. } => Ok(ftd::ast::Component {
id: None,
name: key.to_string(),
properties: vec![],
iteration: None,
Expand All @@ -231,6 +239,7 @@ impl Component {
)?);
}
Ok(ftd::ast::Component {
id: None,
name: key.to_string(),
properties: vec![],
iteration: None,
Expand Down Expand Up @@ -298,6 +307,7 @@ impl Component {
}

Ok(ftd::ast::Component {
id: None,
name,
properties,
iteration,
Expand All @@ -313,6 +323,7 @@ impl Component {
source: value_source,
condition,
} => Ok(ftd::ast::Component {
id: None,
name: key.to_string(),
properties: vec![Property::from_value(
Some(value),
Expand Down
10 changes: 10 additions & 0 deletions ftd/src/ast/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,16 @@ pub(crate) fn is_header_key(key: &str) -> bool {
key.starts_with(HEADER_KEY_START) && key.ends_with('$')
}

pub(crate) fn get_component_id(
headers: &ftd::p1::Headers,
doc_id: &str,
) -> ftd::p1::Result<Option<String>> {
match headers.0.iter().find(|header| header.get_key().eq("id")) {
Some(id) => id.get_value(doc_id),
None => Ok(None),
}
}

pub const REFERENCE: &str = "$";
pub const CLONE: &str = "*$";
pub const LOOP: &str = "$loop$";
Expand Down
14 changes: 14 additions & 0 deletions ftd/src/interpreter/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1096,6 +1096,20 @@ impl Document {
.collect_vec()
}

pub fn get_component_by_id(
&self,
component_name: &str,
component_id: &str,
) -> Option<&ftd::interpreter::Component> {
self.tree.iter().find(|v| {
if let Some(id) = &v.id {
return v.name.eq(component_name) && id.eq(component_id);
}

false
})
}

pub fn get_redirect(&self) -> ftd::interpreter::Result<Option<(String, i32)>> {
let components = self.get_instructions("ftd#redirect");

Expand Down
101 changes: 15 additions & 86 deletions ftd/src/interpreter/test.rs
Original file line number Diff line number Diff line change
@@ -1,78 +1,8 @@
use pretty_assertions::assert_eq; // macro

pub fn interpret_helper(
name: &str,
source: &str,
) -> ftd::interpreter::Result<ftd::interpreter::Document> {
let mut s = ftd::interpreter::interpret(name, source)?;
let document;
loop {
match s {
ftd::interpreter::Interpreter::Done { document: doc } => {
document = doc;
break;
}
ftd::interpreter::Interpreter::StuckOnImport {
module, state: st, ..
} => {
let source = "";
let mut foreign_variable = vec![];
let mut foreign_function = vec![];
if module.eq("test") {
foreign_variable.push("var".to_string());
foreign_function.push("fn".to_string());
}
let document = ftd::interpreter::ParsedDocument::parse(module.as_str(), source)?;
s = st.continue_after_import(
module.as_str(),
document,
foreign_variable,
foreign_function,
0,
)?;
}
ftd::interpreter::Interpreter::StuckOnProcessor {
state, ast, module, ..
} => {
let variable_definition = ast.clone().get_variable_definition(module.as_str())?;
let processor = variable_definition.processor.unwrap();
let value = ftd::interpreter::Value::String {
text: variable_definition
.value
.caption()
.unwrap_or(processor)
.to_uppercase()
.to_string(),
};
s = state.continue_after_processor(value, ast)?;
}
ftd::interpreter::Interpreter::StuckOnForeignVariable {
state,
module,
variable,
..
} => {
if module.eq("test") {
let value = ftd::interpreter::Value::String {
text: variable.to_uppercase().to_string(),
};
s = state.continue_after_variable(module.as_str(), variable.as_str(), value)?;
} else {
return ftd::interpreter::utils::e2(
format!("Unknown module {}", module),
module.as_str(),
0,
);
}
}
}
}
Ok(document)
}
use pretty_assertions::assert_eq;

#[track_caller]
fn p(s: &str, t: &str, fix: bool, file_location: &std::path::PathBuf) {
let mut i = interpret_helper("foo", s).unwrap_or_else(|e| panic!("{:?}", e));
let mut i = ftd::parse_doc("foo", s).unwrap_or_else(|e| panic!("{:?}", e));
for thing in ftd::interpreter::default::get_default_bag().keys() {
i.data.swap_remove(thing);
}
Expand Down Expand Up @@ -261,27 +191,26 @@ fn evalexpr_test() {

#[test]
fn test_extract_kwargs() {
let doc = interpret_helper(
let doc = ftd::parse_doc(
"foo",
r#"-- component foo:
kw-args data:
r#"
-- component fizz:
kw-args data:
-- ftd.text: Hello world
-- ftd.text: Hello world
-- end: foo
-- end: fizz
-- foo:
bar: Hello
baz: World
"#,
-- fizz:
id: test
bar: Hello
baz: World
"#,
)
.unwrap();

let tdoc = doc.tdoc();
let instructions = doc.get_instructions("foo#foo");
let instruction = instructions.first().unwrap();

let data = instruction.get_kwargs("data", &tdoc).unwrap();
let component = doc.get_component_by_id("foo#fizz", "test").unwrap();
let data = component.get_kwargs(&doc, "data").unwrap();

assert_eq!(data.get("bar"), Some(&String::from("Hello")));
assert_eq!(data.get("baz"), Some(&String::from("World")));
Expand Down
14 changes: 10 additions & 4 deletions ftd/src/interpreter/things/component.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ pub type Argument = ftd::interpreter::Field;

#[derive(Debug, Clone, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct Component {
pub id: Option<String>,
pub name: String,
pub properties: Vec<Property>,
pub iteration: Box<Option<Loop>>,
Expand All @@ -142,6 +143,7 @@ pub enum ComponentSource {
impl Component {
pub(crate) fn from_name(name: &str) -> Component {
Component {
id: None,
name: name.to_string(),
properties: vec![],
iteration: Box::new(None),
Expand Down Expand Up @@ -224,10 +226,10 @@ impl Component {

pub fn get_kwargs(
&self,
doc: &ftd::interpreter::Document,
kwargs_name: &str,
doc: &ftd::interpreter::TDoc,
) -> ftd::interpreter::Result<ftd::Map<String>> {
let property = match self.get_interpreter_value_of_argument(kwargs_name, doc)? {
let property = match self.get_interpreter_value_of_argument(kwargs_name, &doc.tdoc())? {
Some(property) => property,
None => {
return Err(ftd::interpreter::Error::OtherError(format!(
Expand All @@ -238,7 +240,7 @@ impl Component {
};

let kwargs = property
.kwargs(doc.name, self.line_number)?
.kwargs(doc.name.as_str(), self.line_number)?
.iter()
.map(|(name, value)| {
let value = match value.to_value().get_string_data() {
Expand All @@ -247,7 +249,7 @@ impl Component {
return Err(ftd::interpreter::Error::ParseError {
message: "Could not parse keyword argument value as string."
.to_string(),
doc_id: doc.name.to_string(),
doc_id: doc.name.clone(),
line_number: value.line_number(),
});
}
Expand Down Expand Up @@ -415,7 +417,10 @@ impl Component {
Self::assert_no_private_properties_while_invocation(&properties, &c.arguments)?;
}

let id = ast_component.id;

Ok(ftd::interpreter::StateWithThing::new_thing(Component {
id,
name,
properties,
iteration: Box::new(iteration),
Expand Down Expand Up @@ -549,6 +554,7 @@ impl Component {

return Ok(ftd::interpreter::StateWithThing::new_thing(Some(
Component {
id: None,
name,
properties,
iteration: Box::new(iteration.to_owned()),
Expand Down
15 changes: 15 additions & 0 deletions ftd/src/interpreter/things/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1579,6 +1579,21 @@ impl Value {
}
}

pub fn get_kwargs(
&self,
doc_id: &str,
line_number: usize,
) -> ftd::interpreter::Result<&ftd::Map<ftd::interpreter::PropertyValue>> {
match self {
Self::KwArgs { arguments } => Ok(arguments),
t => ftd::interpreter::utils::e2(
format!("Expected kw-args, found: `{:?}`", t),
doc_id,
line_number,
),
}
}

pub fn is_equal(&self, other: &Self) -> bool {
match (self.to_owned().inner(), other.to_owned().inner()) {
(Some(Value::String { text: ref a, .. }), Some(Value::String { text: ref b, .. })) => {
Expand Down
2 changes: 2 additions & 0 deletions ftd/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ pub mod interpreter;
pub mod js;
pub mod node;
pub mod p1;
mod parser;
pub use parser::parse_doc;
#[cfg(feature = "native-rendering")]
pub mod taffy;
#[cfg(feature = "terminal")]
Expand Down
Loading

0 comments on commit fdf29a6

Please sign in to comment.