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

Delete some clones and make some of the code leaner #56

Merged
merged 5 commits into from
Oct 22, 2023
Merged
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
8 changes: 4 additions & 4 deletions pax-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,7 @@ fn main() -> Result<(), ()> {
.hidden(true); //hidden because this is of negative value to end-users; things are expected to break when invoked outside of the pax monorepo

#[allow(non_snake_case)]
let ARG_LSP = App::new("lsp")
.about("Start the Pax LSP server");

let ARG_LSP = App::new("lsp").about("Start the Pax LSP server");

let matches = App::new("pax")
.name("pax")
Expand Down Expand Up @@ -249,7 +247,9 @@ fn perform_nominal_action(
}
}
("lsp", Some(_)) => {
tokio::runtime::Runtime::new().unwrap().block_on(pax_language_server::start_server());
tokio::runtime::Runtime::new()
.unwrap()
.block_on(pax_language_server::start_server());
Ok(())
}
_ => unreachable!(), // If all subcommands are defined above, anything else is unreachable
Expand Down
95 changes: 42 additions & 53 deletions pax-compiler/src/expressions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,21 @@ use crate::parsing::escape_identifier;
use itertools::Itertools;
use lazy_static::lazy_static;

const BUILTIN_TYPES: &'static [(&str, &str); 12] = &[
("transform", "Transform2D"),
("width", "Size"),
("height", "Size"),
("x", "Size"),
("y", "Size"),
("anchor_x", "Size"),
("anchor_y", "Size"),
("skew_x", "Numeric"),
("skew_y", "Numeric"),
("scale_x", "Size"),
("scale_y", "Size"),
("rotate", "Rotation"),
];

pub fn compile_all_expressions<'a>(manifest: &'a mut PaxManifest) {
let mut swap_expression_specs: HashMap<usize, ExpressionSpec> = HashMap::new();
let mut all_expression_specs: HashMap<usize, ExpressionSpec> = HashMap::new();
Expand Down Expand Up @@ -76,22 +91,14 @@ fn pull_settings_with_selector(
settings: &Option<Vec<SettingsSelectorBlockDefinition>>,
selector: String,
) -> Option<Vec<(String, ValueDefinition)>> {
if let Some(val) = settings {
settings.as_ref().and_then(|val| {
let merged_settings: Vec<(String, ValueDefinition)> = val
.iter()
.filter(|block| block.selector == selector)
.map(|block| block.value_block.settings_key_value_pairs.clone())
.flatten()
.clone()
.flat_map(|block| block.value_block.settings_key_value_pairs.clone())
.collect();
if merged_settings.len() > 0 {
Some(merged_settings)
} else {
None
}
} else {
None
}
(!merged_settings.is_empty()).then(|| merged_settings)
})
}

fn merge_inline_settings_with_settings_block(
Expand Down Expand Up @@ -155,12 +162,9 @@ fn recurse_compile_literal_block<'a>(
) {
settings_pairs.for_each(|pair| {
match &mut pair.1 {
ValueDefinition::LiteralValue(_) => {
//no need to compile literal values
}
ValueDefinition::EventBindingTarget(_) => {
//event bindings are handled on a separate compiler pass; no-op here
}
// LiteralValue: no need to compile literal values
// EventBindingTarget: event bindings are handled on a separate compiler pass; no-op here
ValueDefinition::LiteralValue(_) | ValueDefinition::EventBindingTarget(_) => {}
ValueDefinition::Block(block) => {
let type_def = (current_property_definitions
.iter()
Expand All @@ -183,22 +187,10 @@ fn recurse_compile_literal_block<'a>(

let (output_statement, invocations) = compile_paxel_to_ril(&input, &ctx);

let builtin_types = HashMap::from([
("transform", "Transform2D".to_string()),
("width", "Size".to_string()),
("height", "Size".to_string()),
("x", "Size".to_string()),
("y", "Size".to_string()),
("anchor_x", "Size".to_string()),
("anchor_y", "Size".to_string()),
("skew_x", "Numeric".to_string()),
("skew_y", "Numeric".to_string()),
("scale_x", "Size".to_string()),
("scale_y", "Size".to_string()),
("rotate", "Rotation".to_string()),
]);

let pascalized_return_type = if let Some(type_string) = builtin_types.get(&*pair.0)
let pascalized_return_type = if let Some(type_string) = BUILTIN_TYPES
.iter()
.find(|type_str| type_str.0 == &*pair.0)
.map(|type_str| type_str.1)
{
type_string.to_string()
} else {
Expand Down Expand Up @@ -776,26 +768,23 @@ impl<'a> ExpressionCompilationContext<'a> {
};

// handle nested symbols like `foo.bar`.
match root_symbol_pd {
Some(root_symbol_pd) => {
let mut ret = vec![root_symbol_pd];
root_symbol_pd.map(|root_symbol_pd| {
let mut ret = vec![root_symbol_pd];
for atomic_symbol in split_symbols {
let td = ret.last().unwrap().get_type_definition(self.type_table);
//return terminal nested symbol's PropertyDefinition, or root's if there are no nested symbols
while let Some(atomic_symbol) = split_symbols.next() {
let td = ret.last().unwrap().get_type_definition(self.type_table);
ret.push(
td.property_definitions
.iter()
.find(|pd| pd.name == *atomic_symbol)
.expect(&format!(
"Unable to resolve nested symbol `{}` while evaluating `{}`.",
atomic_symbol, symbol
))
.clone(),
);
}
Some(ret)
let next_pd = td
.property_definitions
.iter()
.find(|pd| pd.name == *atomic_symbol)
.expect(&format!(
"Unable to resolve nested symbol `{}` while evaluating `{}`.",
atomic_symbol, symbol
))
.clone();
ret.push(next_pd);
}
None => None,
}
ret
})
}
}
29 changes: 12 additions & 17 deletions pax-compiler/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -728,22 +728,18 @@ fn recurse_generate_render_nodes_literal(
Some(format!("PropertyLiteral::new({})", lv))
}
ValueDefinition::Expression(_, id)
| ValueDefinition::Identifier(_, id) => {
Some(format!(
"PropertyExpression::new({})",
id.expect("Tried to use expression but it wasn't compiled")
))
}
ValueDefinition::Block(block) => {
Some(format!(
"PropertyLiteral::new({})",
recurse_literal_block(
block.clone(),
pd.get_type_definition(&rngc.type_table),
host_crate_info
)
))
}
| ValueDefinition::Identifier(_, id) => Some(format!(
"PropertyExpression::new({})",
id.expect("Tried to use expression but it wasn't compiled")
)),
ValueDefinition::Block(block) => Some(format!(
"PropertyLiteral::new({})",
recurse_literal_block(
block.clone(),
pd.get_type_definition(&rngc.type_table),
host_crate_info
)
)),
_ => {
panic!("Incorrect value bound to inline setting")
}
Expand All @@ -757,7 +753,6 @@ fn recurse_generate_render_nodes_literal(
}
};


if let Some(ril_literal_string) = ril_literal_string {
Some((pd.name.clone(), ril_literal_string))
} else {
Expand Down
59 changes: 29 additions & 30 deletions pax-compiler/src/parsing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,7 @@ fn recurse_visit_tag_pairs_for_template(

//add self to parent's children_id_list
let mut parents_children_id_list = ctx.child_id_tracking_stack.pop().unwrap();
parents_children_id_list.push(new_id.clone());
parents_children_id_list.push(new_id);
ctx.child_id_tracking_stack.push(parents_children_id_list);

match any_tag_pair.as_rule() {
Expand Down Expand Up @@ -459,7 +459,7 @@ fn recurse_visit_tag_pairs_for_template(

//`if` TemplateNodeDefinition
TemplateNodeDefinition {
id: new_id.clone(),
id: new_id,
control_flow_settings: Some(ControlFlowSettingsDefinition {
condition_expression_paxel: Some(expression_body),
condition_expression_vtable_id: None, //This will be written back to this data structure later, during expression compilation
Expand Down Expand Up @@ -529,7 +529,7 @@ fn recurse_visit_tag_pairs_for_template(

//`for` TemplateNodeDefinition
TemplateNodeDefinition {
id: new_id.clone(),
id: new_id,
type_id: TYPE_ID_REPEAT.to_string(),
control_flow_settings: Some(cfavd),
settings: None,
Expand All @@ -549,7 +549,7 @@ fn recurse_visit_tag_pairs_for_template(
}

TemplateNodeDefinition {
id: *&new_id.clone(),
id: *&new_id,
control_flow_settings: Some(ControlFlowSettingsDefinition {
condition_expression_paxel: None,
condition_expression_vtable_id: None,
Expand Down Expand Up @@ -845,14 +845,13 @@ impl Default for ParsingContext {
}
}


#[derive(Debug)]
pub struct ParsingError {
pub error_name: String,
pub error_message: String,
pub matched_string: String,
pub start: (usize, usize),
pub end: (usize, usize),
pub end: (usize, usize),
}

/// Extract all errors from a Pax parse result
Expand Down Expand Up @@ -889,15 +888,16 @@ pub fn extract_errors(pairs: pest::iterators::Pairs<Rule>) -> Vec<ParsingError>
format!("{:?}", pair.as_rule()),
"Open tag is malformed".to_string(),
)),
Rule::tag_error => Some((
Rule::tag_error => Some((
format!("{:?}", pair.as_rule()),
"Tag structure is unexpected.".to_string(),
)),
_ => None,
};
if let Some((error_name, error_message)) = error {
let span = pair.as_span();
let ((line_start, start_col), (line_end, end_col)) = (pair.line_col(),span.end_pos().line_col());
let ((line_start, start_col), (line_end, end_col)) =
(pair.line_col(), span.end_pos().line_col());
let error = ParsingError {
error_name,
error_message,
Expand All @@ -907,7 +907,7 @@ pub fn extract_errors(pairs: pest::iterators::Pairs<Rule>) -> Vec<ParsingError>
};
errors.push(error);
}
errors.extend(extract_errors(pair.into_inner()));
errors.extend(extract_errors(pair.into_inner()));
}

errors
Expand All @@ -927,27 +927,27 @@ pub fn assemble_component_definition(
.expect(&format!("unsuccessful parse from {}", &pax)) // unwrap the parse result
.next()
.unwrap(); // get and unwrap the `pax_component_definition` rule

let errors = extract_errors(_ast.clone().into_inner());
if !errors.is_empty() {
let mut error_messages = String::new();

for error in &errors {
let msg = format!(
"error: {}\n --> {}:{}\n |\n{} | {}\n |{}\n\n",
error.error_message,
error.start.0,
error.start.1,
error.start.0,
error.matched_string,
"^".repeat(error.matched_string.len())
);
error_messages.push_str(&msg);
}

panic!("{}", error_messages);

let errors = extract_errors(_ast.clone().into_inner());
if !errors.is_empty() {
let mut error_messages = String::new();

for error in &errors {
let msg = format!(
"error: {}\n --> {}:{}\n |\n{} | {}\n |{}\n\n",
error.error_message,
error.start.0,
error.start.1,
error.start.0,
error.matched_string,
"^".repeat(error.matched_string.len())
);
error_messages.push_str(&msg);
}


panic!("{}", error_messages);
}

if is_main_component {
ctx.main_component_type_id = self_type_id.to_string();
}
Expand Down Expand Up @@ -1277,7 +1277,6 @@ impl Reflectable for pax_runtime_api::Numeric {
}
}


impl Reflectable for pax_runtime_api::SizePixels {
fn get_import_path() -> String {
"pax_lang::api::SizePixels".to_string()
Expand Down
9 changes: 4 additions & 5 deletions pax-compiler/src/templating.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ use serde_derive::{Deserialize, Serialize};
#[allow(unused_imports)]
use serde_json;
use std::collections::HashMap;
use tera::{Tera, Context};

use tera::{Context, Tera};

use crate::manifest::{ExpressionSpec, PropertyDefinition};

Expand Down Expand Up @@ -137,12 +136,12 @@ pub fn press_template_codegen_cartridge_render_node_literal(
.unwrap();

let mut tera = Tera::default();
tera.add_raw_template("cartridge-render-node-literal", template).unwrap();
tera.add_raw_template("cartridge-render-node-literal", template)
.unwrap();

tera.render(
"cartridge-render-node-literal",
&Context::from_serialize(args).unwrap(),
)
.unwrap()
.unwrap()
}

8 changes: 0 additions & 8 deletions pax-core/src/expressions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,6 @@ impl<T: Default + Clone> PropertyInstance<T> for PropertyExpression<T> {
unreachable!()
}

// fn is_fresh(&self) -> bool {
// self.is_fresh
// }
//
// fn _mark_not_fresh(&mut self) {
// self.is_fresh = false;
// }

fn _get_vtable_id(&self) -> Option<usize> {
Some(self.id)
}
Expand Down
Loading