file_path
stringlengths
3
280
file_language
stringclasses
66 values
content
stringlengths
1
1.04M
repo_name
stringlengths
5
92
repo_stars
int64
0
154k
repo_description
stringlengths
0
402
repo_primary_language
stringclasses
108 values
developer_username
stringlengths
1
25
developer_name
stringlengths
0
30
developer_company
stringlengths
0
82
examples/variouslayouts.cpp
C++
#include "variouslayouts.h" #include "ui_variouslayouts.h" #include "uisupport_variouslayouts.h" VariousLayouts::VariousLayouts(QWidget *parent) : QWidget(parent), ui_(std::make_unique<Ui::VariousLayouts>()), uiSupport_(std::make_unique<UiSupport::VariousLayouts>(this, ui_.get())) { ui_->setupUi(this); uiSupport_->setup(); } VariousLayouts::~VariousLayouts() = default;
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
examples/variouslayouts.h
C/C++ Header
#pragma once #include <QWidget> #include <memory> namespace Ui { class VariousLayouts; } namespace UiSupport { class VariousLayouts; } class VariousLayouts : public QWidget { Q_OBJECT public: explicit VariousLayouts(QWidget *parent = nullptr); ~VariousLayouts() override; private: std::unique_ptr<Ui::VariousLayouts> ui_; std::unique_ptr<UiSupport::VariousLayouts> uiSupport_; };
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/color.rs
Rust
//! Qt color type and parser. use once_cell::sync::Lazy; use std::collections::HashMap; use std::str::FromStr; use thiserror::Error; #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum Color { Rgb8(ColorRgb8), Rgba8(ColorRgba8), } #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct ColorRgb8 { pub red: u8, pub green: u8, pub blue: u8, } #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct ColorRgba8 { pub red: u8, pub green: u8, pub blue: u8, pub alpha: u8, } impl Color { pub fn rgb8(red: u8, green: u8, blue: u8) -> Self { Color::Rgb8(ColorRgb8::new(red, green, blue)) } pub fn rgba8(red: u8, green: u8, blue: u8, alpha: u8) -> Self { Color::Rgba8(ColorRgba8::new(red, green, blue, alpha)) } } impl FromStr for Color { type Err = ParseColorError; fn from_str(src: &str) -> Result<Self, Self::Err> { if let Some(hex) = src.strip_prefix('#') { parse_hex_color(hex).ok_or(ParseColorError::InvalidHex) } else if src.eq_ignore_ascii_case("transparent") { Ok(Color::rgba8(0, 0, 0, 0)) } else if let Some(&c) = SVG_NAMED_COLORS.get(src) { Ok(Color::Rgb8(c)) } else if let Some(&c) = SVG_NAMED_COLORS.get(src.to_ascii_lowercase().as_str()) { Ok(Color::Rgb8(c)) } else { Err(ParseColorError::UnknownName) } } } impl ColorRgb8 { pub fn new(red: u8, green: u8, blue: u8) -> Self { ColorRgb8 { red, green, blue } } } impl ColorRgba8 { pub fn new(red: u8, green: u8, blue: u8, alpha: u8) -> Self { ColorRgba8 { red, green, blue, alpha, } } } #[derive(Debug, Error)] pub enum ParseColorError { #[error("invalid hex color")] InvalidHex, #[error("unknown named color")] UnknownName, } fn parse_hex_color(hex: &str) -> Option<Color> { if hex.contains(|c: char| !c.is_ascii_hexdigit()) { return None; } // unlike CSS, QML color is #argb, not #rgba let argb = u32::from_str_radix(hex, 16).ok()?; match hex.len() { 3 => Some(Color::rgb8( ((argb >> 8) & 0xf) as u8 * 0x11, ((argb >> 4) & 0xf) as u8 * 0x11, (argb & 0xf) as u8 * 0x11, )), 4 => Some(Color::rgba8( ((argb >> 8) & 0xf) as u8 * 0x11, ((argb >> 4) & 0xf) as u8 * 0x11, (argb & 0xf) as u8 * 0x11, ((argb >> 12) & 0xf) as u8 * 0x11, )), 6 => Some(Color::rgb8( ((argb >> 16) & 0xff) as u8, ((argb >> 8) & 0xff) as u8, (argb & 0xff) as u8, )), 8 => Some(Color::rgba8( ((argb >> 16) & 0xff) as u8, ((argb >> 8) & 0xff) as u8, (argb & 0xff) as u8, ((argb >> 24) & 0xff) as u8, )), _ => None, } } // https://www.w3.org/Graphics/SVG/1.1/types.html#ColorKeywords static SVG_NAMED_COLORS: Lazy<HashMap<&'static str, ColorRgb8>> = Lazy::new(|| { HashMap::from([ ("aliceblue", ColorRgb8::new(240, 248, 255)), ("antiquewhite", ColorRgb8::new(250, 235, 215)), ("aqua", ColorRgb8::new(0, 255, 255)), ("aquamarine", ColorRgb8::new(127, 255, 212)), ("azure", ColorRgb8::new(240, 255, 255)), ("beige", ColorRgb8::new(245, 245, 220)), ("bisque", ColorRgb8::new(255, 228, 196)), ("black", ColorRgb8::new(0, 0, 0)), ("blanchedalmond", ColorRgb8::new(255, 235, 205)), ("blue", ColorRgb8::new(0, 0, 255)), ("blueviolet", ColorRgb8::new(138, 43, 226)), ("brown", ColorRgb8::new(165, 42, 42)), ("burlywood", ColorRgb8::new(222, 184, 135)), ("cadetblue", ColorRgb8::new(95, 158, 160)), ("chartreuse", ColorRgb8::new(127, 255, 0)), ("chocolate", ColorRgb8::new(210, 105, 30)), ("coral", ColorRgb8::new(255, 127, 80)), ("cornflowerblue", ColorRgb8::new(100, 149, 237)), ("cornsilk", ColorRgb8::new(255, 248, 220)), ("crimson", ColorRgb8::new(220, 20, 60)), ("cyan", ColorRgb8::new(0, 255, 255)), ("darkblue", ColorRgb8::new(0, 0, 139)), ("darkcyan", ColorRgb8::new(0, 139, 139)), ("darkgoldenrod", ColorRgb8::new(184, 134, 11)), ("darkgray", ColorRgb8::new(169, 169, 169)), ("darkgreen", ColorRgb8::new(0, 100, 0)), ("darkgrey", ColorRgb8::new(169, 169, 169)), ("darkkhaki", ColorRgb8::new(189, 183, 107)), ("darkmagenta", ColorRgb8::new(139, 0, 139)), ("darkolivegreen", ColorRgb8::new(85, 107, 47)), ("darkorange", ColorRgb8::new(255, 140, 0)), ("darkorchid", ColorRgb8::new(153, 50, 204)), ("darkred", ColorRgb8::new(139, 0, 0)), ("darksalmon", ColorRgb8::new(233, 150, 122)), ("darkseagreen", ColorRgb8::new(143, 188, 143)), ("darkslateblue", ColorRgb8::new(72, 61, 139)), ("darkslategray", ColorRgb8::new(47, 79, 79)), ("darkslategrey", ColorRgb8::new(47, 79, 79)), ("darkturquoise", ColorRgb8::new(0, 206, 209)), ("darkviolet", ColorRgb8::new(148, 0, 211)), ("deeppink", ColorRgb8::new(255, 20, 147)), ("deepskyblue", ColorRgb8::new(0, 191, 255)), ("dimgray", ColorRgb8::new(105, 105, 105)), ("dimgrey", ColorRgb8::new(105, 105, 105)), ("dodgerblue", ColorRgb8::new(30, 144, 255)), ("firebrick", ColorRgb8::new(178, 34, 34)), ("floralwhite", ColorRgb8::new(255, 250, 240)), ("forestgreen", ColorRgb8::new(34, 139, 34)), ("fuchsia", ColorRgb8::new(255, 0, 255)), ("gainsboro", ColorRgb8::new(220, 220, 220)), ("ghostwhite", ColorRgb8::new(248, 248, 255)), ("gold", ColorRgb8::new(255, 215, 0)), ("goldenrod", ColorRgb8::new(218, 165, 32)), ("gray", ColorRgb8::new(128, 128, 128)), ("green", ColorRgb8::new(0, 128, 0)), ("greenyellow", ColorRgb8::new(173, 255, 47)), ("grey", ColorRgb8::new(128, 128, 128)), ("honeydew", ColorRgb8::new(240, 255, 240)), ("hotpink", ColorRgb8::new(255, 105, 180)), ("indianred", ColorRgb8::new(205, 92, 92)), ("indigo", ColorRgb8::new(75, 0, 130)), ("ivory", ColorRgb8::new(255, 255, 240)), ("khaki", ColorRgb8::new(240, 230, 140)), ("lavender", ColorRgb8::new(230, 230, 250)), ("lavenderblush", ColorRgb8::new(255, 240, 245)), ("lawngreen", ColorRgb8::new(124, 252, 0)), ("lemonchiffon", ColorRgb8::new(255, 250, 205)), ("lightblue", ColorRgb8::new(173, 216, 230)), ("lightcoral", ColorRgb8::new(240, 128, 128)), ("lightcyan", ColorRgb8::new(224, 255, 255)), ("lightgoldenrodyellow", ColorRgb8::new(250, 250, 210)), ("lightgray", ColorRgb8::new(211, 211, 211)), ("lightgreen", ColorRgb8::new(144, 238, 144)), ("lightgrey", ColorRgb8::new(211, 211, 211)), ("lightpink", ColorRgb8::new(255, 182, 193)), ("lightsalmon", ColorRgb8::new(255, 160, 122)), ("lightseagreen", ColorRgb8::new(32, 178, 170)), ("lightskyblue", ColorRgb8::new(135, 206, 250)), ("lightslategray", ColorRgb8::new(119, 136, 153)), ("lightslategrey", ColorRgb8::new(119, 136, 153)), ("lightsteelblue", ColorRgb8::new(176, 196, 222)), ("lightyellow", ColorRgb8::new(255, 255, 224)), ("lime", ColorRgb8::new(0, 255, 0)), ("limegreen", ColorRgb8::new(50, 205, 50)), ("linen", ColorRgb8::new(250, 240, 230)), ("magenta", ColorRgb8::new(255, 0, 255)), ("maroon", ColorRgb8::new(128, 0, 0)), ("mediumaquamarine", ColorRgb8::new(102, 205, 170)), ("mediumblue", ColorRgb8::new(0, 0, 205)), ("mediumorchid", ColorRgb8::new(186, 85, 211)), ("mediumpurple", ColorRgb8::new(147, 112, 219)), ("mediumseagreen", ColorRgb8::new(60, 179, 113)), ("mediumslateblue", ColorRgb8::new(123, 104, 238)), ("mediumspringgreen", ColorRgb8::new(0, 250, 154)), ("mediumturquoise", ColorRgb8::new(72, 209, 204)), ("mediumvioletred", ColorRgb8::new(199, 21, 133)), ("midnightblue", ColorRgb8::new(25, 25, 112)), ("mintcream", ColorRgb8::new(245, 255, 250)), ("mistyrose", ColorRgb8::new(255, 228, 225)), ("moccasin", ColorRgb8::new(255, 228, 181)), ("navajowhite", ColorRgb8::new(255, 222, 173)), ("navy", ColorRgb8::new(0, 0, 128)), ("oldlace", ColorRgb8::new(253, 245, 230)), ("olive", ColorRgb8::new(128, 128, 0)), ("olivedrab", ColorRgb8::new(107, 142, 35)), ("orange", ColorRgb8::new(255, 165, 0)), ("orangered", ColorRgb8::new(255, 69, 0)), ("orchid", ColorRgb8::new(218, 112, 214)), ("palegoldenrod", ColorRgb8::new(238, 232, 170)), ("palegreen", ColorRgb8::new(152, 251, 152)), ("paleturquoise", ColorRgb8::new(175, 238, 238)), ("palevioletred", ColorRgb8::new(219, 112, 147)), ("papayawhip", ColorRgb8::new(255, 239, 213)), ("peachpuff", ColorRgb8::new(255, 218, 185)), ("peru", ColorRgb8::new(205, 133, 63)), ("pink", ColorRgb8::new(255, 192, 203)), ("plum", ColorRgb8::new(221, 160, 221)), ("powderblue", ColorRgb8::new(176, 224, 230)), ("purple", ColorRgb8::new(128, 0, 128)), ("red", ColorRgb8::new(255, 0, 0)), ("rosybrown", ColorRgb8::new(188, 143, 143)), ("royalblue", ColorRgb8::new(65, 105, 225)), ("saddlebrown", ColorRgb8::new(139, 69, 19)), ("salmon", ColorRgb8::new(250, 128, 114)), ("sandybrown", ColorRgb8::new(244, 164, 96)), ("seagreen", ColorRgb8::new(46, 139, 87)), ("seashell", ColorRgb8::new(255, 245, 238)), ("sienna", ColorRgb8::new(160, 82, 45)), ("silver", ColorRgb8::new(192, 192, 192)), ("skyblue", ColorRgb8::new(135, 206, 235)), ("slateblue", ColorRgb8::new(106, 90, 205)), ("slategray", ColorRgb8::new(112, 128, 144)), ("slategrey", ColorRgb8::new(112, 128, 144)), ("snow", ColorRgb8::new(255, 250, 250)), ("springgreen", ColorRgb8::new(0, 255, 127)), ("steelblue", ColorRgb8::new(70, 130, 180)), ("tan", ColorRgb8::new(210, 180, 140)), ("teal", ColorRgb8::new(0, 128, 128)), ("thistle", ColorRgb8::new(216, 191, 216)), ("tomato", ColorRgb8::new(255, 99, 71)), ("turquoise", ColorRgb8::new(64, 224, 208)), ("violet", ColorRgb8::new(238, 130, 238)), ("wheat", ColorRgb8::new(245, 222, 179)), ("white", ColorRgb8::new(255, 255, 255)), ("whitesmoke", ColorRgb8::new(245, 245, 245)), ("yellow", ColorRgb8::new(255, 255, 0)), ("yellowgreen", ColorRgb8::new(154, 205, 50)), ]) }); #[cfg(test)] mod tests { use super::*; #[test] fn parse_hex() { assert_eq!( "#48c".parse::<Color>().unwrap(), Color::rgb8(0x44, 0x88, 0xcc) ); assert_eq!( "#F48c".parse::<Color>().unwrap(), Color::rgba8(0x44, 0x88, 0xcc, 0xff) ); assert_eq!( "#012abc".parse::<Color>().unwrap(), Color::rgb8(0x01, 0x2a, 0xbc) ); assert_eq!( "#DeadBeef".parse::<Color>().unwrap(), Color::rgba8(0xad, 0xbe, 0xef, 0xde) ); assert_eq!( "#00000000".parse::<Color>().unwrap(), Color::rgba8(0x00, 0x00, 0x00, 0x00) ); assert_eq!( "#ffffffff".parse::<Color>().unwrap(), Color::rgba8(0xff, 0xff, 0xff, 0xff) ); assert!("#+48c".parse::<Color>().is_err()); assert!("#4_8_c".parse::<Color>().is_err()); assert!("#".parse::<Color>().is_err()); assert!("#000000001".parse::<Color>().is_err()); } #[test] fn parse_named() { assert_eq!( "red".parse::<Color>().unwrap(), Color::rgb8(0xff, 0x00, 0x00) ); assert_eq!( "Blue".parse::<Color>().unwrap(), Color::rgb8(0x00, 0x00, 0xff) ); assert_eq!( "transparent".parse::<Color>().unwrap(), Color::rgba8(0, 0, 0, 0) ); assert_eq!( "Transparent".parse::<Color>().unwrap(), Color::rgba8(0, 0, 0, 0) ); } }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/diagnostic.rs
Rust
//! Utility for error reporting. use crate::qmlast::ParseError; use camino::{Utf8Path, Utf8PathBuf}; use std::ops::Range; use std::slice; /// Type (or level) of diagnostic message. #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub enum DiagnosticKind { Error, Warning, } /// Diagnostic message. #[derive(Clone, Debug)] pub struct Diagnostic { kind: DiagnosticKind, byte_range: Range<usize>, message: String, labels: Vec<(Range<usize>, String)>, notes: Vec<String>, } impl Diagnostic { /// Creates new diagnostic message of the given `kind`. pub fn new<S>(kind: DiagnosticKind, byte_range: Range<usize>, message: S) -> Self where S: Into<String>, { Diagnostic { kind, byte_range, message: message.into(), labels: Vec::new(), notes: Vec::new(), } } /// Creates new error message. pub fn error<S>(byte_range: Range<usize>, message: S) -> Self where S: Into<String>, { Self::new(DiagnosticKind::Error, byte_range, message) } /// Creates new warning message. pub fn warning<S>(byte_range: Range<usize>, message: S) -> Self where S: Into<String>, { Self::new(DiagnosticKind::Warning, byte_range, message) } /// Builds diagnostic with the given label attached. pub fn with_label<S>(mut self, byte_range: Range<usize>, message: S) -> Self where S: Into<String>, { self.push_label(byte_range, message); self } /// Builds diagnostic with the given labels attached. pub fn with_labels<I, S>(mut self, labels: I) -> Self where I: IntoIterator<Item = (Range<usize>, S)>, S: Into<String>, { self.extend_labels(labels); self } /// Builds diagnostic with the given note attached. pub fn with_note<S>(mut self, message: S) -> Self where S: Into<String>, { self.push_note(message); self } /// Builds diagnostic with the given notes attached. pub fn with_notes<I>(mut self, notes: I) -> Self where I: IntoIterator, I::Item: Into<String>, { self.extend_notes(notes); self } pub fn kind(&self) -> DiagnosticKind { self.kind } pub fn start_byte(&self) -> usize { self.byte_range.start } pub fn end_byte(&self) -> usize { self.byte_range.end } pub fn byte_range(&self) -> Range<usize> { Range { start: self.byte_range.start, end: self.byte_range.end, } } pub fn message(&self) -> &str { &self.message } pub fn labels(&self) -> &[(Range<usize>, String)] { &self.labels } /// Add a label to this diagnostic. pub fn push_label<S>(&mut self, byte_range: Range<usize>, message: S) where S: Into<String>, { self.labels.push((byte_range, message.into())); } /// Add labels to this diagnostic. pub fn extend_labels<I, S>(&mut self, labels: I) where I: IntoIterator<Item = (Range<usize>, S)>, S: Into<String>, { self.labels .extend(labels.into_iter().map(|(r, s)| (r, s.into()))); } pub fn notes(&self) -> &[String] { &self.notes } /// Add a note to this diagnostic. pub fn push_note<S>(&mut self, message: S) where S: Into<String>, { self.notes.push(message.into()); } /// Add notes to this diagnostic. pub fn extend_notes<I>(&mut self, notes: I) where I: IntoIterator, I::Item: Into<String>, { self.notes.extend(notes.into_iter().map(Into::into)); } } impl From<&ParseError<'_>> for Diagnostic { fn from(error: &ParseError) -> Self { Self::error(error.byte_range(), error.to_string()) } } impl From<ParseError<'_>> for Diagnostic { fn from(error: ParseError) -> Self { Self::from(&error) } } /// Manages diagnostic messages. #[derive(Clone, Debug, Default)] pub struct Diagnostics { diagnostics: Vec<Diagnostic>, } impl Diagnostics { pub fn new() -> Self { Diagnostics::default() } pub fn is_empty(&self) -> bool { self.diagnostics.is_empty() } pub fn has_error(&self) -> bool { self.diagnostics .iter() .any(|d| d.kind() == DiagnosticKind::Error) } pub fn len(&self) -> usize { self.diagnostics.len() } pub fn iter(&self) -> slice::Iter<'_, Diagnostic> { self.diagnostics.iter() } pub fn push<T>(&mut self, diag: T) where T: Into<Diagnostic>, { self.diagnostics.push(diag.into()) } /// Extracts error from the given `result` and pushes it. Returns the success value if any. pub fn consume_err<T, E>(&mut self, result: Result<T, E>) -> Option<T> where E: Into<Diagnostic>, { match result { Ok(x) => Some(x), Err(e) => { self.push(e); None } } } } impl<'a> IntoIterator for &'a Diagnostics { type Item = &'a Diagnostic; type IntoIter = slice::Iter<'a, Diagnostic>; fn into_iter(self) -> Self::IntoIter { self.iter() } } impl<T> Extend<T> for Diagnostics where T: Into<Diagnostic>, { fn extend<I>(&mut self, iter: I) where I: IntoIterator<Item = T>, { self.diagnostics.extend(iter.into_iter().map(|d| d.into())) } } /// Manages per-file store of diagnostic messages. #[derive(Clone, Debug, Default)] pub struct ProjectDiagnostics { file_diagnostics: Vec<(Utf8PathBuf, Diagnostics)>, // in insertion order } impl ProjectDiagnostics { pub fn new() -> Self { ProjectDiagnostics::default() } pub fn is_empty(&self) -> bool { // push() guarantees that each file store is not empty self.file_diagnostics.is_empty() } pub fn has_error(&self) -> bool { self.file_diagnostics.iter().any(|(_, ds)| ds.has_error()) } pub fn iter(&self) -> slice::Iter<'_, (Utf8PathBuf, Diagnostics)> { self.file_diagnostics.iter() } pub fn diagnostics(&self) -> impl Iterator<Item = (&Utf8Path, &Diagnostic)> { self.file_diagnostics .iter() .flat_map(|(p, ds)| ds.iter().map(|d| (p.as_ref(), d))) } pub fn push<P>(&mut self, path: P, diagnostics: Diagnostics) where P: AsRef<Utf8Path>, { if !diagnostics.is_empty() { self.file_diagnostics .push((path.as_ref().to_owned(), diagnostics)); } } }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/lib.rs
Rust
#![forbid(unsafe_code)] pub mod color; pub mod diagnostic; pub mod metatype; pub mod metatype_tweak; pub mod objtree; pub mod opcode; pub mod qmlast; pub mod qmldir; pub mod qmldoc; pub mod qtname; pub mod tir; pub mod typedexpr; pub mod typemap; pub mod typeutil; pub mod uigen;
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/metatype.rs
Rust
//! Qt metatypes.json data types. use serde::{Deserialize, Serialize}; // TODO: Symbols are stored as owned strings, but we'll eventually want to intern them, // where we can probably remove these temporary owned strings at all. /// C++ access specifier. #[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub enum AccessSpecifier { Private, Protected, Public, } /// Revision number of method or property. #[derive( Clone, Copy, Debug, Default, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, )] #[repr(transparent)] #[serde(transparent)] pub struct Revision(pub u32); impl Revision { pub fn is_zero(&self) -> bool { self.0 == 0 } } /// Class metadata. #[derive(Clone, Debug, Default, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct Class { pub class_name: String, pub qualified_class_name: String, #[serde(default)] pub super_classes: Vec<SuperClassSpecifier>, #[serde(default)] pub class_infos: Vec<ClassInfo>, #[serde(default)] pub interfaces: Vec<Vec<Interface>>, // no idea why this is nested array #[serde(default)] pub object: bool, #[serde(default)] pub gadget: bool, #[serde(default)] pub namespace: bool, #[serde(default)] pub enums: Vec<Enum>, #[serde(default)] pub properties: Vec<Property>, #[serde(default)] pub constructors: Vec<Method>, // only QObject appears to define this #[serde(default)] pub signals: Vec<Method>, #[serde(default)] pub slots: Vec<Method>, #[serde(default)] pub methods: Vec<Method>, } impl Class { /// Creates class metadata of object type. pub fn new<S>(name: S) -> Self where S: Into<String>, { let name: String = name.into(); Class { class_name: unqualify_name(&name).to_owned(), qualified_class_name: name, object: true, ..Default::default() } } /// Creates class metadata of gadget type. pub fn new_gadget<S>(name: S) -> Self where S: Into<String>, { let name: String = name.into(); Class { class_name: unqualify_name(&name).to_owned(), qualified_class_name: name, gadget: true, ..Default::default() } } /// Creates class metadata of object type with public super classes. pub fn with_supers<S, I>(name: S, supers: I) -> Self where S: Into<String>, I: IntoIterator, I::Item: Into<String>, { let name: String = name.into(); let super_classes = supers .into_iter() .map(SuperClassSpecifier::public) .collect(); Class { class_name: unqualify_name(&name).to_owned(), qualified_class_name: name, object: true, super_classes, ..Default::default() } } } fn unqualify_name(name: &str) -> &str { name.rsplit_once("::").map(|(_, n)| n).unwrap_or(name) } /// Super class reference with the access specifier. #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct SuperClassSpecifier { pub name: String, pub access: AccessSpecifier, } impl SuperClassSpecifier { /// Creates public super class specifier. pub fn public<S>(name: S) -> Self where S: Into<String>, { SuperClassSpecifier { name: name.into(), access: AccessSpecifier::Public, } } } /// Extra class metadata. (e.g. `""QML.Element"`" name) #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct ClassInfo { pub name: String, pub value: String, } impl ClassInfo { /// Creates class info pair. pub fn new<S, T>(name: S, value: T) -> Self where S: Into<String>, T: Into<String>, { ClassInfo { name: name.into(), value: value.into(), } } } /// Qt plugin interface identifier. (see `Q_DECLARE_INTERFACE()`) #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct Interface { pub class_name: String, pub id: String, } /// Enum (and flag) metadata. #[derive(Clone, Debug, Default, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct Enum { pub name: String, #[serde(skip_serializing_if = "Option::is_none")] pub alias: Option<String>, pub is_class: bool, pub is_flag: bool, pub values: Vec<String>, } impl Enum { /// Creates enum metadata. pub fn new<S>(name: S) -> Self where S: Into<String>, { Enum { name: name.into(), ..Default::default() } } /// Creates flag metadata. pub fn new_flag<S, T>(name: S, alias: T) -> Self where S: Into<String>, T: Into<String>, { Enum { name: name.into(), alias: Some(alias.into()), is_flag: true, ..Default::default() } } /// Creates enum metadata with values. pub fn with_values<S, I>(name: S, values: I) -> Self where S: Into<String>, I: IntoIterator, I::Item: Into<String>, { Enum { name: name.into(), values: values.into_iter().map(|n| n.into()).collect(), ..Default::default() } } } /// Property metadata. #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct Property { pub name: String, pub r#type: String, /// See `Q_PRIVATE_PROPERTY()`. #[serde(skip_serializing_if = "Option::is_none")] pub private_class: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub member: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub read: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub write: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub reset: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub notify: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub bindable: Option<String>, #[serde(default, skip_serializing_if = "Revision::is_zero")] pub revision: Revision, pub designable: bool, pub scriptable: bool, pub stored: bool, pub user: bool, pub constant: bool, pub r#final: bool, pub required: bool, /// Property index in the current meta object. (new in Qt 6) pub index: Option<i32>, } impl Property { /// Creates property metadata. pub fn new<S, T>(name: S, type_name: T) -> Self where S: Into<String>, T: Into<String>, { Property { name: name.into(), r#type: type_name.into(), ..Default::default() } } /// Creates property metadata of final. pub fn new_final<S, T>(name: S, type_name: T) -> Self where S: Into<String>, T: Into<String>, { Property { name: name.into(), r#type: type_name.into(), r#final: true, ..Default::default() } } } impl Default for Property { fn default() -> Self { Self { name: String::new(), r#type: String::new(), private_class: None, member: None, read: None, write: None, reset: None, notify: None, bindable: None, revision: Revision(0), designable: true, scriptable: true, stored: true, user: false, constant: false, r#final: false, required: false, index: None, } } } /// Signal, slot, or callable function metadata. #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct Method { pub name: String, pub access: AccessSpecifier, pub return_type: String, #[serde(default)] pub arguments: Vec<Argument>, #[serde(default, skip_serializing_if = "Revision::is_zero")] pub revision: Revision, } impl Method { /// Creates method metadata without arguments. pub fn nullary<S, T>(name: S, return_type: T) -> Self where S: Into<String>, T: Into<String>, { Method { name: name.into(), return_type: return_type.into(), ..Default::default() } } /// Creates method metadata with argument types. pub fn with_argument_types<S, T, I>(name: S, return_type: T, argument_types: I) -> Self where S: Into<String>, T: Into<String>, I: IntoIterator, I::Item: Into<String>, { Method { name: name.into(), return_type: return_type.into(), arguments: argument_types.into_iter().map(Argument::unnamed).collect(), ..Default::default() } } } impl Default for Method { fn default() -> Self { Self { name: String::new(), access: AccessSpecifier::Public, return_type: String::new(), arguments: vec![], revision: Revision(0), } } } /// Signal, slot, or callable function argument. #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct Argument { #[serde(skip_serializing_if = "Option::is_none")] pub name: Option<String>, pub r#type: String, } impl Argument { /// Creates argument metadata without name. pub fn unnamed<T>(type_name: T) -> Self where T: Into<String>, { Argument { name: None, r#type: type_name.into(), } } } #[derive(Clone, Debug, Default, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct CompilationUnit { #[serde(default)] pub classes: Vec<Class>, #[serde(skip_serializing_if = "Option::is_none")] pub input_file: Option<String>, #[serde(default)] pub output_revision: i32, } /// Collects all classes from metatypes.json document. /// /// The JSON document should consist of either a compilation unit object `{"classes": ...}` /// or an array of such objects `[{"classes": ...}, ...]`. pub fn extract_classes_from_str(json_data: &str) -> serde_json::Result<Vec<Class>> { // Don't use untagged enum to dispatch [{...}] and {...}. Doing that would move any // parsing error to the document level and line/column information would be lost. if json_data.trim_start().starts_with('{') { let unit: CompilationUnit = serde_json::from_str(json_data)?; Ok(unit.classes) } else { let units: Vec<CompilationUnit> = serde_json::from_str(json_data)?; Ok(units.into_iter().flat_map(|u| u.classes).collect()) } } #[cfg(test)] mod tests { use super::*; #[test] fn deserialize_class_decl() { let data = r###"{ "className": "QAction", "enums": [ { "isClass": false, "isFlag": false, "name": "Priority", "values": [ "LowPriority", "NormalPriority", "HighPriority" ] } ], "object": true, "properties": [ { "constant": false, "designable": true, "final": false, "name": "checkable", "notify": "changed", "read": "isCheckable", "required": false, "scriptable": true, "stored": true, "type": "bool", "user": false, "write": "setCheckable" } ], "qualifiedClassName": "QAction", "signals": [ { "access": "public", "name": "changed", "returnType": "void" }, { "access": "public", "arguments": [ { "name": "checked", "type": "bool" } ], "name": "triggered", "returnType": "void" } ], "slots": [ { "access": "public", "name": "trigger", "returnType": "void" }, { "access": "public", "name": "hover", "returnType": "void" }, { "access": "public", "arguments": [ { "type": "bool" } ], "name": "setChecked", "returnType": "void" } ], "superClasses": [ { "access": "public", "name": "QObject" } ] }"###; let _meta: Class = serde_json::from_str(data).unwrap(); } #[test] fn extract_classes_unit() { let data = r###"{ "classes": [ {"className": "Foo", "qualifiedClassName": "Foo", "object": true}, {"className": "Bar", "qualifiedClassName": "Bar", "object": true} ] }"###; let classes = extract_classes_from_str(data).unwrap(); assert_eq!(classes.len(), 2); } #[test] fn extract_classes_nested() { let data = r###"[ {"classes": [{"className": "Foo", "qualifiedClassName": "Foo", "object": true}]}, {"classes": [{"className": "Bar", "qualifiedClassName": "Bar", "object": true}]} ]"###; let classes = extract_classes_from_str(data).unwrap(); assert_eq!(classes.len(), 2); } }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/metatype_tweak.rs
Rust
//! Modifications on Qt metatypes data. use crate::metatype::{Class, ClassInfo, Enum, Method, Property, SuperClassSpecifier}; /// Applies all modifications on the given `classes` data. pub fn apply_all(classes: &mut Vec<Class>) { fix_classes(classes); classes.extend(internal_core_classes()); classes.extend(internal_gui_classes()); classes.extend(internal_widgets_classes()); } /// Updates existing class meta data. pub fn fix_classes(classes: &mut [Class]) { for cls in classes.iter_mut() { match cls.qualified_class_name.as_ref() { "QAbstractItemView" => fix_abstract_item_view(cls), "QAction" => fix_action(cls), "QComboBox" => fix_combo_box(cls), "QFont" => fix_font(cls), "QGridLayout" => fix_grid_layout(cls), "QLabel" => fix_label(cls), "QLayout" => fix_layout(cls), "QMenu" => fix_menu(cls), "QPushButton" => fix_push_button(cls), "QSizePolicy" => fix_size_policy(cls), "QTabWidget" => fix_tab_widget(cls), "QTableView" => fix_table_view(cls), "QTreeView" => fix_tree_view(cls), "QWidget" => fix_widget(cls), _ => {} } } } fn fix_abstract_item_view(cls: &mut Class) { cls.properties.extend([ // handled by uigen Property::new("model", "QAbstractItemModel*"), ]) } fn fix_action(cls: &mut Class) { cls.properties.push(Property { name: "separator".to_owned(), r#type: "bool".to_owned(), read: Some("isSeparator".to_owned()), write: Some("setSeparator".to_owned()), ..Default::default() }); } fn fix_combo_box(cls: &mut Class) { cls.properties.extend([ // handled by uigen Property::new("model", "QAbstractItemModel*"), ]) } fn fix_font(cls: &mut Class) { cls.properties.extend([ Property { name: "family".to_owned(), r#type: "QString".to_owned(), read: Some("family".to_owned()), write: Some("setFamily".to_owned()), ..Default::default() }, Property { name: "pointSize".to_owned(), r#type: "int".to_owned(), read: Some("pointSize".to_owned()), write: Some("setPointSize".to_owned()), ..Default::default() }, Property { name: "weight".to_owned(), r#type: "int".to_owned(), // TODO: enum QFont::Weight on Qt 6 read: Some("weight".to_owned()), write: Some("setWeight".to_owned()), ..Default::default() }, Property { name: "italic".to_owned(), r#type: "bool".to_owned(), read: Some("italic".to_owned()), write: Some("setItalic".to_owned()), ..Default::default() }, Property { name: "bold".to_owned(), r#type: "bool".to_owned(), read: Some("bold".to_owned()), write: Some("setBold".to_owned()), ..Default::default() }, Property { name: "underline".to_owned(), r#type: "bool".to_owned(), read: Some("underline".to_owned()), write: Some("setUnderline".to_owned()), ..Default::default() }, Property { name: "strikeout".to_owned(), // follows QML name r#type: "bool".to_owned(), read: Some("strikeOut".to_owned()), write: Some("setStrikeOut".to_owned()), ..Default::default() }, Property { name: "styleStrategy".to_owned(), r#type: "QFont::StyleStrategy".to_owned(), read: Some("styleStrategy".to_owned()), write: Some("setStyleStrategy".to_owned()), ..Default::default() }, Property { name: "kerning".to_owned(), r#type: "bool".to_owned(), read: Some("kerning".to_owned()), write: Some("setKerning".to_owned()), ..Default::default() }, ]); } fn fix_grid_layout(cls: &mut Class) { cls.enums.extend([ Enum::with_values("Flow", ["LeftToRight", "TopToBottom"]), // handled by uigen ]); cls.properties.extend([ // declared as QDOC_PROPERTY() Property { name: "horizontalSpacing".to_owned(), r#type: "int".to_owned(), read: Some("horizontalSpacing".to_owned()), write: Some("setHorizontalSpacing".to_owned()), ..Default::default() }, Property { name: "verticalSpacing".to_owned(), r#type: "int".to_owned(), read: Some("verticalSpacing".to_owned()), write: Some("setVerticalSpacing".to_owned()), ..Default::default() }, // handled by uigen Property::new("columns", "int"), Property::new("rows", "int"), Property::new("flow", "QGridLayout::Flow"), ]); } fn fix_label(cls: &mut Class) { cls.properties.push(Property { name: "buddy".to_owned(), r#type: "QWidget*".to_owned(), read: Some("buddy".to_owned()), write: Some("setBuddy".to_owned()), ..Default::default() }); } fn fix_layout(cls: &mut Class) { cls.class_infos .push(ClassInfo::new("QML.Attached", "QLayoutAttached")); if !cls.properties.iter().any(|p| p.name == "contentsMargins") { // Qt 5 cls.properties.push(Property { name: "contentsMargins".to_owned(), r#type: "QMargins".to_owned(), read: Some("contentsMargins".to_owned()), write: Some("setContentsMargins".to_owned()), ..Default::default() }); } } fn fix_menu(cls: &mut Class) { // for static evaluation pass to obtain QAction from menu object id cls.methods.push(Method { name: "menuAction".to_owned(), return_type: "QAction*".to_owned(), ..Default::default() }); } fn fix_push_button(cls: &mut Class) { if let Some(p) = cls.properties.iter_mut().find(|p| p.name == "default") { p.name += "_"; // reserved world } } fn fix_size_policy(cls: &mut Class) { cls.properties.extend([ Property { name: "horizontalPolicy".to_owned(), r#type: "QSizePolicy::Policy".to_owned(), read: Some("horizontalPolicy".to_owned()), write: Some("setHorizontalPolicy".to_owned()), ..Default::default() }, Property { name: "horizontalStretch".to_owned(), r#type: "int".to_owned(), read: Some("horizontalStretch".to_owned()), write: Some("setHorizontalStretch".to_owned()), ..Default::default() }, Property { name: "verticalPolicy".to_owned(), r#type: "QSizePolicy::Policy".to_owned(), read: Some("verticalPolicy".to_owned()), write: Some("setVerticalPolicy".to_owned()), ..Default::default() }, Property { name: "verticalStretch".to_owned(), r#type: "int".to_owned(), read: Some("verticalStretch".to_owned()), write: Some("setVerticalStretch".to_owned()), ..Default::default() }, ]); } fn fix_tab_widget(cls: &mut Class) { cls.class_infos .push(ClassInfo::new("QML.Attached", "QTabWidgetAttached")); } fn fix_table_view(cls: &mut Class) { cls.properties.extend([ Property::new("horizontalHeader", "QHeaderView*"), // handled by uigen Property::new("verticalHeader", "QHeaderView*"), // handled by uigen ]); } fn fix_tree_view(cls: &mut Class) { cls.properties.extend([ Property::new("header", "QHeaderView*"), // handled by uigen ]); } fn fix_widget(cls: &mut Class) { cls.properties.extend([ Property::new("actions", "QList<QAction*>"), // handled by uigen ]); } /// Creates meta data for QtCore classes which are internally required, but not defined /// in the Qt metatypes.json. pub fn internal_core_classes() -> impl IntoIterator<Item = Class> { [ Class { class_name: "QMargins".to_owned(), qualified_class_name: "QMargins".to_owned(), properties: vec![ Property::new_final("left", "int"), Property::new_final("top", "int"), Property::new_final("right", "int"), Property::new_final("bottom", "int"), ], ..Default::default() }, Class { class_name: "QRect".to_owned(), qualified_class_name: "QRect".to_owned(), properties: vec![ Property::new_final("x", "int"), Property::new_final("y", "int"), Property::new_final("width", "int"), Property::new_final("height", "int"), ], ..Default::default() }, Class { class_name: "QSize".to_owned(), qualified_class_name: "QSize".to_owned(), properties: vec![ Property::new_final("width", "int"), Property::new_final("height", "int"), ], ..Default::default() }, ] } /// Creates meta data for QtGui classes which are internally required, but not defined /// in the Qt metatypes.json. pub fn internal_gui_classes() -> impl IntoIterator<Item = Class> { [ Class { class_name: "QBrush".to_owned(), qualified_class_name: "QBrush".to_owned(), class_infos: vec![ClassInfo::new("QML.Element", "auto")], gadget: true, // mark as "uncreatable" object in .qmltypes properties: vec![ Property::new("color", "QColor"), Property::new("style", "Qt::BrushStyle"), ], ..Default::default() }, Class { class_name: "QColor".to_owned(), qualified_class_name: "QColor".to_owned(), class_infos: vec![ClassInfo::new("QML.Element", "auto")], gadget: true, // mark as "uncreatable" object in .qmltypes properties: vec![ // TODO: r, g, b: qreal vs int ], ..Default::default() }, Class { class_name: "QCursor".to_owned(), qualified_class_name: "QCursor".to_owned(), ..Default::default() }, Class { class_name: "QIcon".to_owned(), qualified_class_name: "QIcon".to_owned(), class_infos: vec![ClassInfo::new("QML.Element", "auto")], gadget: true, // mark as "uncreatable" object in .qmltypes properties: vec![ // follows QtQuick.Controls naming: Property::new("name", "QString"), // follows uic naming: Property::new("normalOff", "QPixmap"), Property::new("normalOn", "QPixmap"), Property::new("disabledOff", "QPixmap"), Property::new("disabledOn", "QPixmap"), Property::new("activeOff", "QPixmap"), Property::new("activeOn", "QPixmap"), Property::new("selectedOff", "QPixmap"), Property::new("selectedOn", "QPixmap"), ], ..Default::default() }, Class::new("QPaintDevice"), // super class of QWidget Class { class_name: "QPalette".to_owned(), qualified_class_name: "QPalette".to_owned(), super_classes: vec![SuperClassSpecifier::public("QPaletteColorGroup")], class_infos: vec![ClassInfo::new("QML.Element", "auto")], gadget: true, // mark as "uncreatable" object in .qmltypes properties: vec![ // modeled after QQuickPalette Property::new("active", "QPaletteColorGroup"), Property::new("disabled", "QPaletteColorGroup"), Property::new("inactive", "QPaletteColorGroup"), ], ..Default::default() }, Class { class_name: "QPaletteColorGroup".to_owned(), qualified_class_name: "QPaletteColorGroup".to_owned(), class_infos: vec![ClassInfo::new("QML.Element", "auto")], gadget: true, // mark as "uncreatable" object in .qmltypes properties: vec![ // modeled after QQuickColorGroup Property::new("active", "QBrush"), Property::new("alternateBase", "QBrush"), Property::new("base", "QBrush"), Property::new("brightText", "QBrush"), Property::new("button", "QBrush"), Property::new("buttonText", "QBrush"), Property::new("dark", "QBrush"), Property::new("highlight", "QBrush"), Property::new("highlightedText", "QBrush"), Property::new("light", "QBrush"), Property::new("link", "QBrush"), Property::new("linkVisited", "QBrush"), Property::new("mid", "QBrush"), Property::new("midlight", "QBrush"), Property::new("placeholderText", "QBrush"), Property::new("shadow", "QBrush"), Property::new("text", "QBrush"), Property::new("toolTipBase", "QBrush"), Property::new("toolTipText", "QBrush"), Property::new("window", "QBrush"), Property::new("windowText", "QBrush"), ], ..Default::default() }, Class { class_name: "QPixmap".to_owned(), qualified_class_name: "QPixmap".to_owned(), ..Default::default() }, ] } /// Creates meta data for QtWidgets classes which are internally required, but not defined /// in the Qt metatypes.json. pub fn internal_widgets_classes() -> impl IntoIterator<Item = Class> { [ Class { class_name: "QLayoutAttached".to_owned(), qualified_class_name: "QLayoutAttached".to_owned(), object: true, properties: vec![ Property::new("alignment", "Qt::Alignment"), Property::new("column", "int"), Property::new("columnMinimumWidth", "int"), Property::new("columnSpan", "int"), Property::new("columnStretch", "int"), Property::new("row", "int"), Property::new("rowMinimumHeight", "int"), Property::new("rowSpan", "int"), Property::new("rowStretch", "int"), ], ..Default::default() }, Class::new("QLayoutItem"), // super class of QLayout, QSpacerItem, and QWidgetItem Class { class_name: "QSpacerItem".to_owned(), qualified_class_name: "QSpacerItem".to_owned(), class_infos: vec![ClassInfo::new("QML.Element", "auto")], object: true, // mark as "creatable" object in .qmltypes properties: vec![ // follows uic names Property::new("orientation", "Qt::Orientation"), Property::new("sizeHint", "QSize"), Property::new("sizeType", "QSizePolicy"), ], ..Default::default() }, Class { class_name: "QTabWidgetAttached".to_owned(), qualified_class_name: "QTabWidgetAttached".to_owned(), object: true, properties: vec![ Property::new("icon", "QIcon"), Property::new("title", "QString"), Property::new("toolTip", "QString"), Property::new("whatsThis", "QString"), ], ..Default::default() }, ] }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/objtree.rs
Rust
//! Tree of QML objects. use crate::diagnostic::{Diagnostic, Diagnostics}; use crate::qmlast::{Node, UiObjectDefinition}; use crate::qtname::{self, UniqueNameGenerator}; use crate::typemap::{Class, NamedType, TypeSpace}; use std::collections::HashMap; use std::mem; /// Tree of object definitions and the corresponding types. /// /// This provides a global view of the QML document. #[derive(Clone, Debug)] pub struct ObjectTree<'a, 't> { nodes: Vec<ObjectNodeData<'a, 't>>, id_map: HashMap<String, usize>, } impl<'a, 't> ObjectTree<'a, 't> { /// Builds object tree from the given `root_node`. /// /// Returns None if the root node couldn't be parsed properly. Otherwise returns the tree /// even if some intermediate nodes couldn't be parsed. pub fn build( root_node: Node<'t>, source: &str, type_space: &impl TypeSpace<'a>, diagnostics: &mut Diagnostics, ) -> Option<Self> { let mut tree = ObjectTree { nodes: Vec::new(), id_map: HashMap::new(), }; if let Some(index) = tree.populate_node_rec(root_node, source, type_space, diagnostics) { assert!(index + 1 == tree.nodes.len()); tree.update_id_map(source, diagnostics); tree.ensure_object_names(); Some(tree) } else { None } } fn populate_node_rec( &mut self, node: Node<'t>, source: &str, type_space: &impl TypeSpace<'a>, diagnostics: &mut Diagnostics, ) -> Option<usize> { let obj = diagnostics.consume_err(UiObjectDefinition::from_node(node, source))?; let type_name = obj.type_name().to_string(source); // TODO: look up qualified name with '.' separator let ty = match type_space.get_type(&type_name) { Some(Ok(ty)) => ty, Some(Err(e)) => { diagnostics.push(Diagnostic::error( obj.type_name().node().byte_range(), format!("object type resolution failed: {e}"), )); return None; } None => { diagnostics.push(Diagnostic::error( obj.type_name().node().byte_range(), format!("unknown object type: {type_name}"), )); return None; } }; let is_custom_type = matches!(&ty, NamedType::QmlComponent(_)); let class = if let Some(class) = ty.into_class() { class } else { diagnostics.push(Diagnostic::error( obj.type_name().node().byte_range(), format!("invalid object type: {type_name}"), )); return None; }; let name = obj.object_id().map(|id| id.to_str(source).to_owned()); let child_indices = obj .child_object_nodes() .iter() .filter_map(|&n| self.populate_node_rec(n, source, type_space, diagnostics)) .collect(); let index = self.nodes.len(); self.nodes.push(ObjectNodeData { class, is_custom_type, obj, name, child_indices, }); Some(index) } fn update_id_map(&mut self, source: &str, diagnostics: &mut Diagnostics) { for (index, data) in self.nodes.iter().enumerate() { if let Some(id) = data.obj.object_id() { use std::collections::hash_map::Entry; match self.id_map.entry(id.to_str(source).to_owned()) { Entry::Vacant(e) => { e.insert(index); } Entry::Occupied(e) => { let old_id = self.nodes[*e.get()] .obj .object_id() .expect("indexed object must have id"); diagnostics.push( Diagnostic::error( id.node().byte_range(), format!("duplicated object id: {}", e.key()), ) .with_labels([ (old_id.node().byte_range(), "id is first defined here"), (id.node().byte_range(), "duplicated id is defined here"), ]), ); } } } } } fn ensure_object_names(&mut self) { let mut gen = UniqueNameGenerator::new(); for data in self.nodes.iter_mut().filter(|d| d.name.is_none()) { let prefix = qtname::variable_name_for_type(data.class.name()); data.name = Some(gen.generate_with_reserved_map(prefix, &self.id_map)); } } /// Reference to the root object. pub fn root<'b>(&'b self) -> ObjectNode<'a, 't, 'b> { ObjectNode::new(self.nodes.last().expect("root node must exist"), self) } /// Iterates over the all objects in the tree. pub fn flat_iter<'b>(&'b self) -> impl Iterator<Item = ObjectNode<'a, 't, 'b>> { self.nodes.iter().map(|d| ObjectNode::new(d, self)) } /// Number of the objects in the tree. pub fn flat_len(&self) -> usize { self.nodes.len() } /// Check whether or not the specified object id exists. pub fn contains_id<S>(&self, object_id: S) -> bool where S: AsRef<str>, { self.id_map.contains_key(object_id.as_ref()) } /// Reference to the object specified by id. /// /// The object is NOT looked up by any generated object name since any reference /// expression pointing to the generated name should be invalid. pub fn get_by_id<'b, S>(&'b self, object_id: S) -> Option<ObjectNode<'a, 't, 'b>> where S: AsRef<str>, { self.id_map .get(object_id.as_ref()) .map(|&i| ObjectNode::new(&self.nodes[i], self)) } } /// Reference to object definition with the type information. #[derive(Clone, Copy, Debug)] pub struct ObjectNode<'a, 't, 'b> { data: &'b ObjectNodeData<'a, 't>, tree: &'b ObjectTree<'a, 't>, } #[derive(Clone, Debug)] struct ObjectNodeData<'a, 't> { class: Class<'a>, is_custom_type: bool, obj: UiObjectDefinition<'t>, name: Option<String>, child_indices: Vec<usize>, } impl<'a, 't, 'b> ObjectNode<'a, 't, 'b> { fn new(data: &'b ObjectNodeData<'a, 't>, tree: &'b ObjectTree<'a, 't>) -> Self { ObjectNode { data, tree } } pub fn class(&self) -> &Class<'a> { &self.data.class } pub fn is_custom_type(&self) -> bool { self.data.is_custom_type } pub fn obj(&self) -> &UiObjectDefinition<'t> { &self.data.obj } /// Object id if given, or generated name which uniquely identifies this object. pub fn name(&self) -> &str { self.data .name .as_ref() .expect("unique name should have been generated") } /// Index of this object node in the flat vec. /// /// Typical use case is to build and store per-object data in separate vec. pub fn flat_index(&self) -> usize { let p: *const ObjectNodeData = self.data; let q: *const ObjectNodeData = self.tree.nodes.as_ptr(); assert!(p >= q); (p as usize - q as usize) / mem::size_of_val(self.data) } /// Iterates over the direct child objects. pub fn children(&self) -> impl Iterator<Item = ObjectNode<'a, 't, 'b>> { self.data .child_indices .iter() .map(|&i| ObjectNode::new(&self.tree.nodes[i], self.tree)) } } #[cfg(test)] mod tests { use super::*; use crate::diagnostic::Diagnostics; use crate::metatype; use crate::qmlast::UiProgram; use crate::qmldoc::UiDocument; use crate::typemap::{ModuleData, ModuleIdBuf, TypeMap}; use std::ptr; struct Env { doc: UiDocument, type_map: TypeMap, module_id: ModuleIdBuf, } impl Env { fn new(source: &str) -> Self { let mut type_map = TypeMap::with_primitive_types(); let module_id = ModuleIdBuf::Named("foo".to_owned()); let mut module_data = ModuleData::with_builtins(); module_data.extend([metatype::Class::new("Foo")]); type_map.insert_module(module_id.clone(), module_data); Env { doc: UiDocument::parse(source, "MyType", None), type_map, module_id, } } fn try_build_tree(&self) -> Result<ObjectTree, Diagnostics> { let mut diagnostics = Diagnostics::new(); let program = UiProgram::from_node(self.doc.root_node(), self.doc.source()).unwrap(); let tree = ObjectTree::build( program.root_object_node(), self.doc.source(), &self.type_map.get_module(self.module_id.as_ref()).unwrap(), &mut diagnostics, ); if diagnostics.has_error() { Err(diagnostics) } else { Ok(tree.unwrap()) } } } #[test] fn lookup_by_object_id() { let env = Env::new( r###" Foo { id: root Foo { id: child0 } Foo {} } "###, ); let tree = env.try_build_tree().unwrap(); assert!(ptr::eq( tree.get_by_id("root").unwrap().obj(), tree.root().obj() )); assert!(ptr::eq( tree.get_by_id("child0").unwrap().obj(), tree.root().children().next().unwrap().obj() )); assert!(!tree.contains_id("unknown")); assert!(tree.get_by_id("unknown").is_none()); } #[test] fn duplicated_object_id() { let env = Env::new( r###" Foo { id: root Foo { id: dup } Foo { id: dup } } "###, ); assert!(env.try_build_tree().is_err()); } #[test] fn generated_object_names() { let env = Env::new( r###" Foo { id: root Foo {} Foo {} } "###, ); let tree = env.try_build_tree().unwrap(); let children: Vec<_> = tree.root().children().collect(); assert_eq!(children[0].name(), "foo"); assert_eq!(children[1].name(), "foo1"); assert!(tree.get_by_id("foo").is_none()); assert!(tree.get_by_id("foo1").is_none()); } #[test] fn object_id_conflicts_with_generated_name() { let env = Env::new( r###" Foo { id: foo Foo {} } "###, ); let tree = env.try_build_tree().unwrap(); let child = tree.root().children().next().unwrap(); assert_eq!(child.name(), "foo1"); assert!(tree.get_by_id("foo").is_some()); assert!(tree.get_by_id("foo1").is_none()); } #[test] fn flat_index() { let env = Env::new( r###" Foo { Foo {} Foo {} } "###, ); let tree = env.try_build_tree().unwrap(); let nodes: Vec<_> = tree.flat_iter().collect(); assert_eq!(nodes[0].flat_index(), 0); assert_eq!(nodes[1].flat_index(), 1); assert_eq!(nodes[2].flat_index(), 2); } }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/opcode.rs
Rust
//! Function and operator constants. use crate::qmlast::{BinaryOperator, UnaryOperator}; use std::fmt; /// Builtin functions. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum BuiltinFunctionKind { /// `console.log()`, `.debug()`, `.info()`, `.warn()`, `.error()` ConsoleLog(ConsoleLogLevel), /// `Math.max()` Max, /// `Math.min()` Min, /// `qsTr()` Tr, } /// Builtin (pseudo) namespace or object hosting static functions. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum BuiltinNamespaceKind { Console, Math, } /// Log level of `console.log()`-family functions. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum ConsoleLogLevel { Log, Debug, Info, Warn, Error, } /// Unary operator. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum UnaryOp { Arith(UnaryArithOp), Bitwise(UnaryBitwiseOp), Logical(UnaryLogicalOp), } impl TryFrom<UnaryOperator> for UnaryOp { type Error = (); fn try_from(operator: UnaryOperator) -> Result<Self, Self::Error> { use UnaryOperator::*; match operator { LogicalNot => Ok(UnaryOp::Logical(UnaryLogicalOp::Not)), BitwiseNot => Ok(UnaryOp::Bitwise(UnaryBitwiseOp::Not)), Minus => Ok(UnaryOp::Arith(UnaryArithOp::Minus)), Plus => Ok(UnaryOp::Arith(UnaryArithOp::Plus)), Typeof | Void | Delete => Err(()), } } } impl fmt::Display for UnaryOp { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { UnaryOp::Arith(op) => op.fmt(f), UnaryOp::Bitwise(op) => op.fmt(f), UnaryOp::Logical(op) => op.fmt(f), } } } /// Unary arithmetic operator. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum UnaryArithOp { /// `-` Minus, /// `+` Plus, } impl fmt::Display for UnaryArithOp { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let s = match self { UnaryArithOp::Minus => "-", UnaryArithOp::Plus => "+", }; write!(f, "{}", s) } } /// Unary bitwise operator. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum UnaryBitwiseOp { /// `~` Not, } impl fmt::Display for UnaryBitwiseOp { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let s = match self { UnaryBitwiseOp::Not => "~", }; write!(f, "{}", s) } } /// Unary logical operator. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum UnaryLogicalOp { /// `!` Not, } impl fmt::Display for UnaryLogicalOp { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let s = match self { UnaryLogicalOp::Not => "!", }; write!(f, "{}", s) } } /// Binary operator. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum BinaryOp { Arith(BinaryArithOp), Bitwise(BinaryBitwiseOp), Shift(ShiftOp), Logical(BinaryLogicalOp), Comparison(ComparisonOp), } impl TryFrom<BinaryOperator> for BinaryOp { type Error = (); fn try_from(operator: BinaryOperator) -> Result<Self, Self::Error> { use BinaryOperator::*; match operator { LogicalAnd => Ok(BinaryOp::Logical(BinaryLogicalOp::And)), LogicalOr => Ok(BinaryOp::Logical(BinaryLogicalOp::Or)), RightShift => Ok(BinaryOp::Shift(ShiftOp::RightShift)), UnsignedRightShift => Err(()), LeftShift => Ok(BinaryOp::Shift(ShiftOp::LeftShift)), BitwiseAnd => Ok(BinaryOp::Bitwise(BinaryBitwiseOp::And)), BitwiseXor => Ok(BinaryOp::Bitwise(BinaryBitwiseOp::Xor)), BitwiseOr => Ok(BinaryOp::Bitwise(BinaryBitwiseOp::Or)), Add => Ok(BinaryOp::Arith(BinaryArithOp::Add)), Sub => Ok(BinaryOp::Arith(BinaryArithOp::Sub)), Mul => Ok(BinaryOp::Arith(BinaryArithOp::Mul)), Div => Ok(BinaryOp::Arith(BinaryArithOp::Div)), Rem => Ok(BinaryOp::Arith(BinaryArithOp::Rem)), Exp => Err(()), Equal | StrictEqual => Ok(BinaryOp::Comparison(ComparisonOp::Equal)), NotEqual | StrictNotEqual => Ok(BinaryOp::Comparison(ComparisonOp::NotEqual)), LessThan => Ok(BinaryOp::Comparison(ComparisonOp::LessThan)), LessThanEqual => Ok(BinaryOp::Comparison(ComparisonOp::LessThanEqual)), GreaterThan => Ok(BinaryOp::Comparison(ComparisonOp::GreaterThan)), GreaterThanEqual => Ok(BinaryOp::Comparison(ComparisonOp::GreaterThanEqual)), NullishCoalesce | Instanceof | In => Err(()), } } } impl fmt::Display for BinaryOp { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { BinaryOp::Arith(op) => op.fmt(f), BinaryOp::Bitwise(op) => op.fmt(f), BinaryOp::Shift(op) => op.fmt(f), BinaryOp::Logical(op) => op.fmt(f), BinaryOp::Comparison(op) => op.fmt(f), } } } /// Binary arithmetic operator. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum BinaryArithOp { /// `+` Add, /// `-` Sub, /// `*` Mul, /// `/` Div, /// `%` Rem, } impl fmt::Display for BinaryArithOp { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let s = match self { BinaryArithOp::Add => "+", BinaryArithOp::Sub => "-", BinaryArithOp::Mul => "*", BinaryArithOp::Div => "/", BinaryArithOp::Rem => "%", }; write!(f, "{}", s) } } /// Binary bitwise operator. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum BinaryBitwiseOp { /// `&` And, /// `^` Xor, /// `|` Or, } impl fmt::Display for BinaryBitwiseOp { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let s = match self { BinaryBitwiseOp::And => "&", BinaryBitwiseOp::Xor => "^", BinaryBitwiseOp::Or => "|", }; write!(f, "{}", s) } } /// Shift operator. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum ShiftOp { /// `>>` RightShift, /// `<<` LeftShift, } impl fmt::Display for ShiftOp { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let s = match self { ShiftOp::RightShift => ">>", ShiftOp::LeftShift => "<<", }; write!(f, "{}", s) } } /// Binary logical operator. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum BinaryLogicalOp { /// `&&` And, /// `||` Or, } impl fmt::Display for BinaryLogicalOp { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let s = match self { BinaryLogicalOp::And => "&&", BinaryLogicalOp::Or => "||", }; write!(f, "{}", s) } } /// Comparison operator. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum ComparisonOp { /// `==` Equal, /// `!=` NotEqual, /// `<` LessThan, /// `<=` LessThanEqual, /// `>` GreaterThan, /// `>=` GreaterThanEqual, } impl fmt::Display for ComparisonOp { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let s = match self { ComparisonOp::Equal => "==", ComparisonOp::NotEqual => "!=", ComparisonOp::LessThan => "<", ComparisonOp::LessThanEqual => "<=", ComparisonOp::GreaterThan => ">", ComparisonOp::GreaterThanEqual => ">=", }; write!(f, "{}", s) } }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/qmlast/astutil.rs
Rust
//! Utility for AST parsing and building. use super::{ParseError, ParseErrorKind}; use tree_sitter::{Node, TreeCursor}; pub(super) fn get_child_by_field_name<'tree>( node: Node<'tree>, name: &'static str, ) -> Result<Node<'tree>, ParseError<'tree>> { node.child_by_field_name(name) .ok_or_else(|| ParseError::new(node, ParseErrorKind::MissingField(name))) } /// Like `Node::children()`, but emits node with its optional field name. pub(super) fn children_with_field_name<'s, 'tree>( node: Node<'tree>, cursor: &'s mut TreeCursor<'tree>, ) -> impl ExactSizeIterator<Item = (Node<'tree>, Option<&'static str>)> + 's { cursor.reset(node); cursor.goto_first_child(); // would fail if node.child_count() == 0 (0..node.child_count()).map(|_| { let item = (cursor.node(), cursor.field_name()); cursor.goto_next_sibling(); item }) } pub(super) fn children_between_field_names<'s, 'tree>( node: Node<'tree>, cursor: &'s mut TreeCursor<'tree>, left_field_name: &'s str, right_field_name: &'s str, ) -> impl Iterator<Item = (Node<'tree>, Option<&'static str>)> + 's { children_with_field_name(node, cursor) .skip_while(move |(_, f)| !f.map(|s| s == left_field_name).unwrap_or(false)) .skip(1) // skip node pointed by left_field_name .take_while(move |(_, f)| !f.map(|s| s == right_field_name).unwrap_or(false)) } pub(super) fn node_text<'source>(node: Node<'_>, source: &'source str) -> &'source str { node.utf8_text(source.as_bytes()) .expect("source range must be valid utf-8 string") } pub(super) fn goto_first_named_child<'tree>( cursor: &mut TreeCursor<'tree>, ) -> Result<(), ParseError<'tree>> { if !cursor.goto_first_child() { return Err(ParseError::new( cursor.node(), ParseErrorKind::InvalidSyntax, )); } skip_until_named(cursor) } pub(super) fn skip_until_named<'tree>( cursor: &mut TreeCursor<'tree>, ) -> Result<(), ParseError<'tree>> { while cursor.node().is_extra() || !cursor.node().is_named() { let node = cursor.node(); if !cursor.goto_next_sibling() { return Err(ParseError::new(node, ParseErrorKind::InvalidSyntax)); } } Ok(()) } pub(super) fn handle_uninteresting_node(node: Node) -> Result<(), ParseError> { if node.is_extra() || !node.is_named() { Ok(()) } else { Err(ParseError::new(node, ParseErrorKind::UnexpectedNodeKind)) } } #[derive(Clone, Copy, Debug, PartialEq)] pub(super) enum Number { Integer(u64), Float(f64), } pub(super) fn parse_number<'tree>( node: Node<'tree>, source: &str, ) -> Result<Number, ParseError<'tree>> { if node.kind() != "number" { return Err(ParseError::new(node, ParseErrorKind::UnexpectedNodeKind)); } parse_number_str(node_text(node, source)) .ok_or_else(|| ParseError::new(node, ParseErrorKind::InvalidSyntax)) } fn parse_number_str(s: &str) -> Option<Number> { // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#numeric_literals // TODO: maybe incomplete if let Some((radix, t)) = strip_radix_prefix(s) { parse_integer_str_radix(t, radix) } else if s.contains(['e', '.']) { s.parse().ok().map(Number::Float) } else { parse_integer_str_radix(s, 10) } } fn parse_integer_str_radix(s: &str, radix: u32) -> Option<Number> { u64::from_str_radix(s, radix) .or_else(|_| { let cleaned: String = s.chars().filter(|&c| c != '_').collect(); u64::from_str_radix(&cleaned, radix) }) .ok() .map(Number::Integer) } fn strip_radix_prefix(s: &str) -> Option<(u32, &str)> { if s.starts_with("0b") || s.starts_with("0B") { Some((2, &s[2..])) } else if s.starts_with("0o") || s.starts_with("0O") { Some((8, &s[2..])) } else if s.starts_with("0x") || s.starts_with("0X") { Some((16, &s[2..])) } else if s.starts_with('0') && s.len() > 1 && s.chars().all(|c| ('0'..='7').contains(&c)) { Some((8, &s[1..])) } else { None } } pub(super) fn parse_string<'tree>( node: Node<'tree>, source: &str, ) -> Result<String, ParseError<'tree>> { if node.kind() != "string" { return Err(ParseError::new(node, ParseErrorKind::UnexpectedNodeKind)); } let mut decoded = String::with_capacity(node.byte_range().len()); for n in node.named_children(&mut node.walk()) { let s = node_text(n, source); match n.kind() { "string_fragment" => decoded.push_str(s), "escape_sequence" => { let c = unescape_char(s) .ok_or_else(|| ParseError::new(n, ParseErrorKind::InvalidSyntax))?; decoded.push(c); } _ => return Err(ParseError::new(n, ParseErrorKind::UnexpectedNodeKind)), } } Ok(decoded) } fn unescape_char(escaped: &str) -> Option<char> { if !escaped.starts_with('\\') { return None; } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#escape_sequences let tail = &escaped[1..]; if tail.len() == 1 { match tail.chars().next().unwrap() { '0' => Some('\0'), '\'' => Some('\''), '\"' => Some('\"'), '\\' => Some('\\'), 'n' => Some('\n'), 'r' => Some('\r'), 'v' => Some('\x0b'), 't' => Some('\t'), 'b' => Some('\x08'), 'f' => Some('\x0c'), _ => None, } } else if tail.starts_with("u{") && tail.ends_with('}') { char_from_str_radix(&tail[2..tail.len() - 1], 16) } else if (tail.starts_with('u') && tail.len() == 5) || (tail.starts_with('x') && tail.len() == 3) { char_from_str_radix(&tail[1..], 16) } else { None } } fn char_from_str_radix(src: &str, radix: u32) -> Option<char> { u32::from_str_radix(src, radix) .ok() .and_then(char::from_u32) } #[cfg(test)] mod tests { use super::*; #[test] fn number_literal() { assert_eq!(parse_number_str("0"), Some(Number::Integer(0))); assert_eq!(parse_number_str("123"), Some(Number::Integer(123))); assert_eq!( parse_number_str("01234567"), Some(Number::Integer(0o1234567)) ); assert_eq!(parse_number_str("0o123"), Some(Number::Integer(0o123))); assert_eq!(parse_number_str("0Xdead"), Some(Number::Integer(0xdead))); assert_eq!(parse_number_str("0e-1"), Some(Number::Float(0.))); assert_eq!(parse_number_str("0.8"), Some(Number::Float(0.8))); assert_eq!( parse_number_str("0b0101_1010"), Some(Number::Integer(0b0101_1010)) ); } #[test] fn escape_sequence() { assert_eq!(unescape_char(r"\n"), Some('\n')); assert_eq!(unescape_char(r"\\"), Some('\\')); assert_eq!(unescape_char(r"\0"), Some('\0')); assert_eq!(unescape_char(r"\x7f"), Some('\x7f')); assert_eq!(unescape_char(r"\u300f"), Some('\u{300f}')); assert_eq!(unescape_char(r"\u{12f}"), Some('\u{12f}')); } }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/qmlast/expr.rs
Rust
use super::astutil::{self, Number}; use super::node::{ExpressionNode, StatementNode}; use super::term::{self, Identifier, NestedIdentifier}; use super::{ParseError, ParseErrorKind}; use std::fmt; use tree_sitter::{Node, TreeCursor}; /// Tagged union that wraps an expression. #[derive(Clone, Debug)] pub enum Expression<'tree> { Identifier(Identifier<'tree>), This, Integer(u64), Float(f64), String(String), Bool(bool), Null, Array(Vec<ExpressionNode<'tree>>), Function(Function<'tree>), ArrowFunction(Function<'tree>), Member(MemberExpression<'tree>), Subscript(SubscriptExpression<'tree>), Call(CallExpression<'tree>), Assignment(AssignmentExpression<'tree>), Unary(UnaryExpression<'tree>), Binary(BinaryExpression<'tree>), As(AsExpression<'tree>), Ternary(TernaryExpression<'tree>), // TODO: ... } impl<'tree> Expression<'tree> { pub fn from_node(node: ExpressionNode<'tree>, source: &str) -> Result<Self, ParseError<'tree>> { Self::with_cursor(&mut node.walk(), source) } pub(super) fn with_cursor( cursor: &mut TreeCursor<'tree>, source: &str, ) -> Result<Self, ParseError<'tree>> { while cursor.node().kind() == "parenthesized_expression" { astutil::goto_first_named_child(cursor)?; } let node = cursor.node(); let expr = match node.kind() { "identifier" => Expression::Identifier(Identifier::from_node(node)?), "this" => Expression::This, "number" => { // A number is floating point in JavaScript, but we want to discriminate // integer/float to process numeric operations in more C/Rust-like way. // It will help avoid unexpected integer->float conversion by division. match astutil::parse_number(node, source)? { Number::Integer(n) => Expression::Integer(n), Number::Float(n) => Expression::Float(n), } } "string" => Expression::String(astutil::parse_string(node, source)?), "true" => Expression::Bool(true), "false" => Expression::Bool(false), "null" => Expression::Null, "array" => { let items = node .named_children(cursor) .filter(|n| !n.is_extra()) .map(ExpressionNode) .collect(); Expression::Array(items) } "function_expression" => Function::with_cursor(cursor).map(Expression::Function)?, "arrow_function" => Function::with_cursor(cursor).map(Expression::ArrowFunction)?, "member_expression" => { let object = astutil::get_child_by_field_name(node, "object").map(ExpressionNode)?; let property = Identifier::from_node(astutil::get_child_by_field_name(node, "property")?)?; // reject optional chaining: <object>?.<property> if let Some((n, _)) = astutil::children_between_field_names(node, cursor, "object", "property") .find(|(n, _)| !n.is_extra() && n.kind() != ".") { return Err(ParseError::new(n, ParseErrorKind::UnexpectedNodeKind)); } Expression::Member(MemberExpression { object, property }) } "subscript_expression" => { let object = astutil::get_child_by_field_name(node, "object").map(ExpressionNode)?; let index = astutil::get_child_by_field_name(node, "index").map(ExpressionNode)?; // reject optional chaining: <object>?.[<index>] if let Some((n, _)) = astutil::children_between_field_names(node, cursor, "object", "index") .find(|(n, _)| !n.is_extra() && n.kind() != "[") { return Err(ParseError::new(n, ParseErrorKind::UnexpectedNodeKind)); } Expression::Subscript(SubscriptExpression { object, index }) } "call_expression" => { let function = astutil::get_child_by_field_name(node, "function").map(ExpressionNode)?; let arguments = astutil::get_child_by_field_name(node, "arguments")? .named_children(cursor) .filter(|n| !n.is_extra()) .map(ExpressionNode) .collect(); // reject optional chaining: <function>?.(<arguments>) if let Some((n, _)) = astutil::children_between_field_names(node, cursor, "function", "arguments") .find(|(n, _)| !n.is_extra()) { return Err(ParseError::new(n, ParseErrorKind::UnexpectedNodeKind)); } Expression::Call(CallExpression { function, arguments, }) } "assignment_expression" => { let left = astutil::get_child_by_field_name(node, "left").map(ExpressionNode)?; let right = astutil::get_child_by_field_name(node, "right").map(ExpressionNode)?; Expression::Assignment(AssignmentExpression { left, right }) } "unary_expression" => { let operator = UnaryOperator::from_node(astutil::get_child_by_field_name(node, "operator")?)?; let argument = astutil::get_child_by_field_name(node, "argument").map(ExpressionNode)?; Expression::Unary(UnaryExpression { operator, argument }) } "binary_expression" => { let operator = BinaryOperator::from_node(astutil::get_child_by_field_name(node, "operator")?)?; let left = astutil::get_child_by_field_name(node, "left").map(ExpressionNode)?; let right = astutil::get_child_by_field_name(node, "right").map(ExpressionNode)?; Expression::Binary(BinaryExpression { operator, left, right, }) } "as_expression" => { let invalid_syntax = || ParseError::new(node, ParseErrorKind::InvalidSyntax); let mut children = node.children(cursor).filter(|n| !n.is_extra()); let value = children .next() .ok_or_else(invalid_syntax) .map(ExpressionNode)?; let as_node = children.next().ok_or_else(invalid_syntax)?; let ty_node = children.next().ok_or_else(invalid_syntax)?; if let Some(n) = children.next() { return Err(ParseError::new(n, ParseErrorKind::UnexpectedNodeKind)); } if as_node.kind() != "as" { return Err(ParseError::new(as_node, ParseErrorKind::UnexpectedNodeKind)); } Expression::As(AsExpression { value, ty: NestedIdentifier::from_node(ty_node)?, }) } "ternary_expression" => { let condition = astutil::get_child_by_field_name(node, "condition").map(ExpressionNode)?; let consequence = astutil::get_child_by_field_name(node, "consequence").map(ExpressionNode)?; let alternative = astutil::get_child_by_field_name(node, "alternative").map(ExpressionNode)?; Expression::Ternary(TernaryExpression { condition, consequence, alternative, }) } // TODO: ... _ => { return Err(ParseError::new(node, ParseErrorKind::UnexpectedNodeKind)); } }; Ok(expr) } } /// Represents a function or arrow function expression. #[derive(Clone, Debug)] pub struct Function<'tree> { pub name: Option<Identifier<'tree>>, pub parameters: Vec<FormalParameter<'tree>>, pub return_ty: Option<NestedIdentifier<'tree>>, pub body: FunctionBody<'tree>, } impl<'tree> Function<'tree> { pub fn from_node(node: ExpressionNode<'tree>) -> Result<Self, ParseError<'tree>> { Self::with_cursor(&mut node.walk()) } fn with_cursor(cursor: &mut TreeCursor<'tree>) -> Result<Self, ParseError<'tree>> { let node = cursor.node(); match node.kind() { "function_expression" => { // reject unsupported keywords like 'async' if let Some(n) = node.children(cursor).find(|n| !n.is_extra()) { if n.kind() != "function" { return Err(ParseError::new(n, ParseErrorKind::UnexpectedNodeKind)); } } let name = node .child_by_field_name("name") .map(Identifier::from_node) .transpose()?; let parameters = astutil::get_child_by_field_name(node, "parameters")? .named_children(cursor) .filter(|n| !n.is_extra()) .map(FormalParameter::from_node) .collect::<Result<Vec<_>, _>>()?; let return_ty = node .child_by_field_name("return_type") .map(term::extract_type_annotation) .transpose()?; let body_node = astutil::get_child_by_field_name(node, "body")?; Ok(Function { name, parameters, return_ty, body: FunctionBody::Statement(StatementNode(body_node)), }) } "arrow_function" => { // reject unsupported keywords like 'async' if let Some((n, _)) = astutil::children_with_field_name(node, cursor) .take_while(|(_, f)| !matches!(f, Some("parameter" | "parameters"))) .find(|(n, _)| !n.is_extra()) { return Err(ParseError::new(n, ParseErrorKind::UnexpectedNodeKind)); } let parameters = if let Some(n) = node.child_by_field_name("parameter") { vec![FormalParameter { name: Identifier::from_node(n)?, ty: None, }] } else { astutil::get_child_by_field_name(node, "parameters")? .named_children(cursor) .filter(|n| !n.is_extra()) .map(FormalParameter::from_node) .collect::<Result<Vec<_>, _>>()? }; let return_ty = node .child_by_field_name("return_type") .map(term::extract_type_annotation) .transpose()?; let body_node = astutil::get_child_by_field_name(node, "body")?; let body = if body_node.kind() == "statement_block" { FunctionBody::Statement(StatementNode(body_node)) } else { FunctionBody::Expression(ExpressionNode(body_node)) }; Ok(Function { name: None, parameters, return_ty, body, }) } _ => Err(ParseError::new(node, ParseErrorKind::UnexpectedNodeKind)), } } } /// Variant for function body. /// /// If the function isn't an arrow function, the body should be `Statement` kind. #[derive(Clone, Copy, Debug)] pub enum FunctionBody<'tree> { Expression(ExpressionNode<'tree>), Statement(StatementNode<'tree>), } /// Represents a function parameter. /// /// This does not support destructuring pattern, default initializer, etc. #[derive(Clone, Debug)] pub struct FormalParameter<'tree> { pub name: Identifier<'tree>, pub ty: Option<NestedIdentifier<'tree>>, } impl<'tree> FormalParameter<'tree> { fn from_node(node: Node<'tree>) -> Result<Self, ParseError<'tree>> { if node.kind() != "required_parameter" { return Err(ParseError::new(node, ParseErrorKind::UnexpectedNodeKind)); } let name = astutil::get_child_by_field_name(node, "pattern").and_then(Identifier::from_node)?; let ty = node .child_by_field_name("type") .map(term::extract_type_annotation) .transpose()?; Ok(FormalParameter { name, ty }) } pub fn node(&self) -> Node<'tree> { self.name .node() .parent() .expect("formal parameter name node should have parent") } } /// Represents a member expression. #[derive(Clone, Debug)] pub struct MemberExpression<'tree> { pub object: ExpressionNode<'tree>, pub property: Identifier<'tree>, } /// Represents a subscript expression. #[derive(Clone, Debug)] pub struct SubscriptExpression<'tree> { pub object: ExpressionNode<'tree>, pub index: ExpressionNode<'tree>, } /// Represents a call expression. #[derive(Clone, Debug)] pub struct CallExpression<'tree> { pub function: ExpressionNode<'tree>, pub arguments: Vec<ExpressionNode<'tree>>, } /// Represents an assignment expression. #[derive(Clone, Debug)] pub struct AssignmentExpression<'tree> { pub left: ExpressionNode<'tree>, pub right: ExpressionNode<'tree>, } /// Represents a unary expression. #[derive(Clone, Debug)] pub struct UnaryExpression<'tree> { pub operator: UnaryOperator, pub argument: ExpressionNode<'tree>, } /// Unary operation type. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum UnaryOperator { /// `!` LogicalNot, /// `~` BitwiseNot, /// `-` Minus, /// `+` Plus, /// `typeof` Typeof, /// `void` Void, /// `delete` Delete, } impl UnaryOperator { pub fn from_node(node: Node) -> Result<Self, ParseError> { use UnaryOperator::*; if node.is_named() { return Err(ParseError::new(node, ParseErrorKind::UnexpectedNodeKind)); } let op = match node.kind() { "!" => LogicalNot, "~" => BitwiseNot, "-" => Minus, "+" => Plus, "typeof" => Typeof, "void" => Void, "delete" => Delete, _ => return Err(ParseError::new(node, ParseErrorKind::UnexpectedNodeKind)), }; Ok(op) } } impl fmt::Display for UnaryOperator { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use UnaryOperator::*; let s = match self { LogicalNot => "!", BitwiseNot => "~", Minus => "-", Plus => "+", Typeof => "typeof", Void => "void", Delete => "delete", }; write!(f, "{}", s) } } /// Represents a binary expression. #[derive(Clone, Debug)] pub struct BinaryExpression<'tree> { pub operator: BinaryOperator, pub left: ExpressionNode<'tree>, pub right: ExpressionNode<'tree>, } /// Binary operation type. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum BinaryOperator { /// `&&` LogicalAnd, /// `||` LogicalOr, /// `>>` RightShift, /// `>>>` UnsignedRightShift, /// `<<` LeftShift, /// `&` BitwiseAnd, /// `^` BitwiseXor, /// `|` BitwiseOr, /// `+` Add, /// `-` Sub, /// `*` Mul, /// `/` Div, /// `%` Rem, /// `**` Exp, /// `==` Equal, /// `===` StrictEqual, /// `!=` NotEqual, /// `!==` StrictNotEqual, /// `<` LessThan, /// `<=` LessThanEqual, /// `>` GreaterThan, /// `>=` GreaterThanEqual, /// `??` NullishCoalesce, /// `instanceof` Instanceof, /// `in` In, } impl BinaryOperator { pub fn from_node(node: Node) -> Result<Self, ParseError> { use BinaryOperator::*; if node.is_named() { return Err(ParseError::new(node, ParseErrorKind::UnexpectedNodeKind)); } let op = match node.kind() { "&&" => LogicalAnd, "||" => LogicalOr, ">>" => RightShift, ">>>" => UnsignedRightShift, "<<" => LeftShift, "&" => BitwiseAnd, "^" => BitwiseXor, "|" => BitwiseOr, "+" => Add, "-" => Sub, "*" => Mul, "/" => Div, "%" => Rem, "**" => Exp, "==" => Equal, "===" => StrictEqual, "!=" => NotEqual, "!==" => StrictNotEqual, "<" => LessThan, "<=" => LessThanEqual, ">" => GreaterThan, ">=" => GreaterThanEqual, "??" => NullishCoalesce, "instanceof" => Instanceof, "in" => In, _ => return Err(ParseError::new(node, ParseErrorKind::UnexpectedNodeKind)), }; Ok(op) } } impl fmt::Display for BinaryOperator { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use BinaryOperator::*; let s = match self { LogicalAnd => "&&", LogicalOr => "||", RightShift => ">>", UnsignedRightShift => ">>>", LeftShift => "<<", BitwiseAnd => "&", BitwiseXor => "^", BitwiseOr => "|", Add => "+", Sub => "-", Mul => "*", Div => "/", Rem => "%", Exp => "**", Equal => "==", StrictEqual => "===", NotEqual => "!=", StrictNotEqual => "!==", LessThan => "<", LessThanEqual => "<=", GreaterThan => ">", GreaterThanEqual => ">=", NullishCoalesce => "??", Instanceof => "instanceof", In => "in", }; write!(f, "{}", s) } } /// Represents an `as` (or type cast) expression. #[derive(Clone, Debug)] pub struct AsExpression<'tree> { pub value: ExpressionNode<'tree>, pub ty: NestedIdentifier<'tree>, } /// Represents a ternary (or conditional) expression. #[derive(Clone, Debug)] pub struct TernaryExpression<'tree> { pub condition: ExpressionNode<'tree>, pub consequence: ExpressionNode<'tree>, pub alternative: ExpressionNode<'tree>, } #[cfg(test)] mod tests { use super::super::stmt::Statement; use super::*; use crate::qmlast::{UiObjectDefinition, UiProgram}; use crate::qmldoc::UiDocument; macro_rules! impl_unwrap_fn { ($name:ident, $pat:path, $ty:ty) => { fn $name(self) -> $ty { match self { $pat(x) => x, _ => panic!("unexpected expression: {self:?}"), } } }; } impl<'tree> Expression<'tree> { impl_unwrap_fn!(unwrap_identifier, Expression::Identifier, Identifier<'tree>); impl_unwrap_fn!(unwrap_integer, Expression::Integer, u64); impl_unwrap_fn!(unwrap_float, Expression::Float, f64); impl_unwrap_fn!(unwrap_string, Expression::String, String); impl_unwrap_fn!(unwrap_bool, Expression::Bool, bool); impl_unwrap_fn!(unwrap_array, Expression::Array, Vec<ExpressionNode<'tree>>); impl_unwrap_fn!(unwrap_function, Expression::Function, Function<'tree>); impl_unwrap_fn!( unwrap_arrow_function, Expression::ArrowFunction, Function<'tree> ); impl_unwrap_fn!(unwrap_member, Expression::Member, MemberExpression<'tree>); impl_unwrap_fn!( unwrap_subscript, Expression::Subscript, SubscriptExpression<'tree> ); impl_unwrap_fn!(unwrap_call, Expression::Call, CallExpression<'tree>); impl_unwrap_fn!( unwrap_assignment, Expression::Assignment, AssignmentExpression<'tree> ); impl_unwrap_fn!(unwrap_unary, Expression::Unary, UnaryExpression<'tree>); impl_unwrap_fn!(unwrap_binary, Expression::Binary, BinaryExpression<'tree>); impl_unwrap_fn!(unwrap_as, Expression::As, AsExpression<'tree>); impl_unwrap_fn!( unwrap_ternary, Expression::Ternary, TernaryExpression<'tree> ); } fn parse(source: &str) -> UiDocument { UiDocument::parse(source, "MyType", None) } fn extract_expr<'a>(doc: &'a UiDocument, name: &str) -> Result<Expression<'a>, ParseError<'a>> { let program = UiProgram::from_node(doc.root_node(), doc.source()).unwrap(); let obj = UiObjectDefinition::from_node(program.root_object_node(), doc.source()).unwrap(); let map = obj.build_binding_map(doc.source()).unwrap(); let node = map.get(name).unwrap().get_node().unwrap(); match Statement::from_node(node).unwrap() { Statement::Expression(n) => n.parse(doc.source()), stmt => panic!("expression statement node must be specified, but got {stmt:?}"), } } fn unwrap_expr<'a>(doc: &'a UiDocument, name: &str) -> Expression<'a> { extract_expr(doc, name).unwrap() } #[test] #[allow(clippy::bool_assert_comparison)] fn trivial_expressions() { let doc = parse( r###" Foo { identifier: foo this_: this integer: 123 float: 123. string_: "whatever" escaped_string: "foo\nbar" true_: true false_: false null_: null array: [0, 1, /*garbage*/ 2] paren1: (foo) paren2: ((foo)) paren_comment: (/*garbage*/ foo) } "###, ); assert_eq!( unwrap_expr(&doc, "identifier") .unwrap_identifier() .to_str(doc.source()), "foo" ); assert!(matches!(unwrap_expr(&doc, "this_"), Expression::This)); assert_eq!(unwrap_expr(&doc, "integer").unwrap_integer(), 123); assert_eq!(unwrap_expr(&doc, "float").unwrap_float(), 123.); assert_eq!(unwrap_expr(&doc, "string_").unwrap_string(), "whatever"); assert_eq!( unwrap_expr(&doc, "escaped_string").unwrap_string(), "foo\nbar" ); assert_eq!(unwrap_expr(&doc, "true_").unwrap_bool(), true); assert_eq!(unwrap_expr(&doc, "false_").unwrap_bool(), false); assert!(matches!(unwrap_expr(&doc, "null_"), Expression::Null)); assert_eq!( unwrap_expr(&doc, "array") .unwrap_array() .iter() .map(|&n| n.parse(doc.source()).unwrap().unwrap_integer()) .collect::<Vec<_>>(), [0, 1, 2] ); assert!(extract_expr(&doc, "paren1").is_ok()); assert!(extract_expr(&doc, "paren2").is_ok()); assert!(extract_expr(&doc, "paren_comment").is_ok()); } #[test] fn function() { let doc = parse( r###" Foo { unnamed_no_arg: /*garbage*/ function /*garbage*/ (/*garbage*/) { 0 } unnamed_one_arg: function (/*garbage*/ a) {} named_no_arg: function foo() {} named_arg_typed: function foo(a: int, /*garbage*/ b: bar.bool): string {} async_fn: async function foo() {} } "###, ); let x = unwrap_expr(&doc, "unnamed_no_arg").unwrap_function(); assert!(x.name.is_none()); assert!(x.parameters.is_empty()); assert!(x.return_ty.is_none()); assert!(matches!(x.body, FunctionBody::Statement(_))); let x = unwrap_expr(&doc, "unnamed_one_arg").unwrap_function(); assert!(x.name.is_none()); assert_eq!(x.parameters.len(), 1); assert_eq!(x.parameters[0].name.to_str(doc.source()), "a"); assert!(x.parameters[0].ty.is_none()); assert!(x.return_ty.is_none()); let x = unwrap_expr(&doc, "named_no_arg").unwrap_function(); assert_eq!(x.name.unwrap().to_str(doc.source()), "foo"); assert!(x.parameters.is_empty()); assert!(x.return_ty.is_none()); let x = unwrap_expr(&doc, "named_arg_typed").unwrap_function(); assert_eq!(x.name.unwrap().to_str(doc.source()), "foo"); assert_eq!(x.parameters.len(), 2); assert_eq!(x.parameters[0].name.to_str(doc.source()), "a"); assert_eq!( x.parameters[0].ty.as_ref().unwrap().to_string(doc.source()), "int" ); assert_eq!(x.parameters[1].name.to_str(doc.source()), "b"); assert_eq!( x.parameters[1].ty.as_ref().unwrap().to_string(doc.source()), "bar.bool" ); assert_eq!( x.return_ty.as_ref().unwrap().to_string(doc.source()), "string" ); assert!(extract_expr(&doc, "async_fn").is_err()); } #[test] fn arrow_function() { let doc = parse( r###" Foo { no_arg_expr: /*garbage*/ (/*garbage*/) => /*garbage*/ 0 no_arg_stmt: /*garbage*/ (/*garbage*/) => { 0 } bare_arg: /*garbage*/ a => a one_arg: (/*garbage*/ a) => {} arg_typed: (a: int, /*garbage*/ b: bool): string => {} async_bare: async a => a async_paren: async () => {} } "###, ); let x = unwrap_expr(&doc, "no_arg_expr").unwrap_arrow_function(); assert!(x.name.is_none()); assert!(x.parameters.is_empty()); assert!(x.return_ty.is_none()); assert!(matches!(x.body, FunctionBody::Expression(_))); let x = unwrap_expr(&doc, "no_arg_stmt").unwrap_arrow_function(); assert!(x.name.is_none()); assert!(x.parameters.is_empty()); assert!(x.return_ty.is_none()); assert!(matches!(x.body, FunctionBody::Statement(_))); let x = unwrap_expr(&doc, "bare_arg").unwrap_arrow_function(); assert_eq!(x.parameters.len(), 1); assert_eq!(x.parameters[0].name.to_str(doc.source()), "a"); assert!(x.parameters[0].ty.is_none()); assert!(x.return_ty.is_none()); let x = unwrap_expr(&doc, "one_arg").unwrap_arrow_function(); assert_eq!(x.parameters.len(), 1); assert_eq!(x.parameters[0].name.to_str(doc.source()), "a"); assert!(x.parameters[0].ty.is_none()); assert!(x.return_ty.is_none()); let x = unwrap_expr(&doc, "arg_typed").unwrap_arrow_function(); assert_eq!(x.parameters.len(), 2); assert_eq!(x.parameters[0].name.to_str(doc.source()), "a"); assert_eq!( x.parameters[0].ty.as_ref().unwrap().to_string(doc.source()), "int" ); assert_eq!(x.parameters[1].name.to_str(doc.source()), "b"); assert_eq!( x.parameters[1].ty.as_ref().unwrap().to_string(doc.source()), "bool" ); assert_eq!( x.return_ty.as_ref().unwrap().to_string(doc.source()), "string" ); assert!(extract_expr(&doc, "async_bare").is_err()); assert!(extract_expr(&doc, "async_paren").is_err()); } #[test] fn member_expression() { let doc = parse( r###" Foo { member: foo /*garbage*/ . /*garbage*/ bar member_opt: foo?.bar } "###, ); let x = unwrap_expr(&doc, "member").unwrap_member(); assert_eq!( x.object .parse(doc.source()) .unwrap() .unwrap_identifier() .to_str(doc.source()), "foo" ); assert_eq!(x.property.to_str(doc.source()), "bar"); assert!(extract_expr(&doc, "member_opt").is_err()); } #[test] fn subscript_expression() { let doc = parse( r###" Foo { subscript: foo /*garbage*/ [ /*garbage*/ bar ] subscript_opt: foo?.[bar] } "###, ); let x = unwrap_expr(&doc, "subscript").unwrap_subscript(); assert_eq!( x.object .parse(doc.source()) .unwrap() .unwrap_identifier() .to_str(doc.source()), "foo" ); assert_eq!( x.index .parse(doc.source()) .unwrap() .unwrap_identifier() .to_str(doc.source()), "bar" ); assert!(extract_expr(&doc, "subscript_opt").is_err()); } #[test] fn call_expression() { let doc = parse( r###" Foo { call: foo /*garbage*/ (1, /*garbage*/ 2) call_opt: foo.bar?.() } "###, ); let x = unwrap_expr(&doc, "call").unwrap_call(); assert_eq!( x.function .parse(doc.source()) .unwrap() .unwrap_identifier() .to_str(doc.source()), "foo" ); assert_eq!(x.arguments.len(), 2); assert!(extract_expr(&doc, "call_opt").is_err()); } #[test] fn assignment_expression() { let doc = parse( r###" Foo { assign: foo = 1 } "###, ); let x = unwrap_expr(&doc, "assign").unwrap_assignment(); assert_eq!( x.left .parse(doc.source()) .unwrap() .unwrap_identifier() .to_str(doc.source()), "foo" ); assert_ne!(x.left, x.right); } #[test] fn unary_expression() { let doc = parse( r###" Foo { logical_not: !whatever } "###, ); let x = unwrap_expr(&doc, "logical_not").unwrap_unary(); assert_eq!(x.operator, UnaryOperator::LogicalNot); } #[test] fn binary_expression() { let doc = parse( r###" Foo { add: 1 + 2 } "###, ); let x = unwrap_expr(&doc, "add").unwrap_binary(); assert_eq!(x.operator, BinaryOperator::Add); assert_ne!(x.left, x.right); } #[test] fn as_expression() { let doc = parse( r###" Foo { as_: /*garbage*/ 1.0 /*garbage*/ as /*garbage*/ int /*garbage*/ } "###, ); let x = unwrap_expr(&doc, "as_").unwrap_as(); assert_ne!(x.value.inner_node(), x.ty.node()); assert_eq!(x.ty.to_string(doc.source()), "int"); } #[test] fn ternary_expression() { let doc = parse( r###" Foo { ternary: true ? "true" : "false" } "###, ); let x = unwrap_expr(&doc, "ternary").unwrap_ternary(); assert_ne!(x.condition, x.consequence); assert_ne!(x.consequence, x.alternative); } }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/qmlast/mod.rs
Rust
//! QML parser interface and document model. use std::error::Error; use std::fmt; use std::ops::Range; mod astutil; mod expr; mod node; mod object; mod stmt; mod term; pub use self::expr::*; // re-export pub use self::node::*; // re-export pub use self::object::*; // re-export pub use self::stmt::*; // re-export pub use self::term::*; // re-export pub use tree_sitter::Node; // re-export /// Semantic or syntax error occurred while parsing QML source. #[derive(Clone, Debug)] pub struct ParseError<'tree> { node: Node<'tree>, kind: ParseErrorKind, } /// Details of QML parse error. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum ParseErrorKind { InvalidSyntax, UnexpectedNodeKind, MissingField(&'static str), DuplicatedBinding, MultipleDefaultLabels, } impl<'tree> ParseError<'tree> { pub fn new(node: Node<'tree>, kind: ParseErrorKind) -> Self { ParseError { node, kind } } pub fn node(&self) -> Node<'tree> { self.node } pub fn kind(&self) -> ParseErrorKind { self.kind } pub fn start_byte(&self) -> usize { self.node.start_byte() } pub fn end_byte(&self) -> usize { self.node.end_byte() } pub fn byte_range(&self) -> Range<usize> { self.node.byte_range() } } impl fmt::Display for ParseError<'_> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use ParseErrorKind::*; match self.kind { InvalidSyntax => write!(f, "syntax error"), UnexpectedNodeKind => write!(f, "unexpected node kind: {}", self.node.kind()), MissingField(name) => write!(f, "missing field: {}", name), DuplicatedBinding => write!(f, "duplicated binding"), MultipleDefaultLabels => write!(f, "multiple default labels"), } } } impl Error for ParseError<'_> {}
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/qmlast/node.rs
Rust
//! Newtype for Node. use super::expr::Expression; use super::stmt::Statement; use super::ParseError; use std::ops::Range; use tree_sitter::{Node, TreeCursor}; /// CST node that represents an [`Expression`](Expression). #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct ExpressionNode<'tree>(pub(super) Node<'tree>); impl<'tree> ExpressionNode<'tree> { pub fn parse(&self, source: &str) -> Result<Expression<'tree>, ParseError<'tree>> { Expression::from_node(*self, source) } /// Returns true if this is a function or arrow function node without parentheses. pub fn is_bare_function(&self) -> bool { self.0.kind() == "function_expression" || self.0.kind() == "arrow_function" } pub(super) fn inner_node(&self) -> Node<'tree> { self.0 } pub fn byte_range(&self) -> Range<usize> { self.0.byte_range() } pub(super) fn walk(&self) -> TreeCursor<'tree> { self.0.walk() } } /// CST node that represents a [`Statement`](Statement). #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct StatementNode<'tree>(pub(super) Node<'tree>); impl<'tree> StatementNode<'tree> { pub fn parse(&self) -> Result<Statement<'tree>, ParseError<'tree>> { Statement::from_node(*self) } pub(super) fn inner_node(&self) -> Node<'tree> { self.0 } pub fn byte_range(&self) -> Range<usize> { self.0.byte_range() } pub(super) fn walk(&self) -> TreeCursor<'tree> { self.0.walk() } }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/qmlast/object.rs
Rust
use super::astutil; use super::node::StatementNode; use super::stmt::Statement; use super::term::{Identifier, NestedIdentifier}; use super::{ParseError, ParseErrorKind}; use std::collections::HashMap; use tree_sitter::{Node, TreeCursor}; /// Represents a top-level QML program. #[derive(Clone, Debug)] pub struct UiProgram<'tree> { imports: Vec<UiImport<'tree>>, root_object_node: Node<'tree>, } impl<'tree> UiProgram<'tree> { pub fn from_node(node: Node<'tree>, source: &str) -> Result<Self, ParseError<'tree>> { Self::with_cursor(&mut node.walk(), source) } fn with_cursor( cursor: &mut TreeCursor<'tree>, source: &str, ) -> Result<Self, ParseError<'tree>> { let node = cursor.node(); if node.kind() != "program" { return Err(ParseError::new(node, ParseErrorKind::UnexpectedNodeKind)); } let mut imports = Vec::new(); for n in node.named_children(cursor) { match n.kind() { "ui_import" => imports.push(UiImport::from_node(n, source)?), // TODO: ui_pragma "ui_object_definition" | "ui_annotated_object" => {} // root _ => astutil::handle_uninteresting_node(n)?, } } let root_object_node = astutil::get_child_by_field_name(node, "root")?; Ok(UiProgram { imports, root_object_node, }) } /// Import statements. pub fn imports(&self) -> &[UiImport<'tree>] { &self.imports } /// Node for the top-level object (or component.) pub fn root_object_node(&self) -> Node<'tree> { self.root_object_node } } /// Represents an import statement. #[derive(Clone, Debug)] pub struct UiImport<'tree> { node: Node<'tree>, source: UiImportSource<'tree>, version: Option<(u8, Option<u8>)>, alias: Option<Identifier<'tree>>, } /// Variant for the import source. #[derive(Clone, Debug)] pub enum UiImportSource<'tree> { /// (Dotted) identifier for a named module. Identifier(NestedIdentifier<'tree>), /// String which is typically a directory path. String(String), } impl<'tree> UiImport<'tree> { pub fn from_node(node: Node<'tree>, source: &str) -> Result<Self, ParseError<'tree>> { if node.kind() != "ui_import" { return Err(ParseError::new(node, ParseErrorKind::UnexpectedNodeKind)); } let source_node = astutil::get_child_by_field_name(node, "source")?; let source_mod = match source_node.kind() { "identifier" | "nested_identifier" => { UiImportSource::Identifier(NestedIdentifier::from_node(source_node)?) } "string" => UiImportSource::String(astutil::parse_string(source_node, source)?), _ => { return Err(ParseError::new( source_node, ParseErrorKind::UnexpectedNodeKind, )) } }; let version = if let Some(version_node) = node.child_by_field_name("version") { let parse = |n| -> Result<u8, ParseError<'tree>> { astutil::node_text(n, source) .parse() .map_err(|_| ParseError::new(n, ParseErrorKind::InvalidSyntax)) }; Some(( parse(astutil::get_child_by_field_name(version_node, "major")?)?, version_node .child_by_field_name("minor") .map(parse) .transpose()?, )) } else { None }; let alias = node .child_by_field_name("alias") .map(Identifier::from_node) .transpose()?; Ok(UiImport { node, source: source_mod, version, alias, }) } pub fn node(&self) -> Node<'tree> { self.node } pub fn source(&self) -> &UiImportSource<'tree> { &self.source } pub fn version(&self) -> Option<(u8, Option<u8>)> { self.version } pub fn alias(&self) -> Option<Identifier<'tree>> { self.alias } } fn extract_object_id(node: StatementNode) -> Result<Identifier, ParseError> { if let Statement::Expression(n) = node.parse()? { Identifier::from_node(n.inner_node()) } else { Err(ParseError::new( node.inner_node(), ParseErrorKind::UnexpectedNodeKind, )) } } /// Represents a QML object or top-level component. #[derive(Clone, Debug)] pub struct UiObjectDefinition<'tree> { node: Node<'tree>, type_name: NestedIdentifier<'tree>, body: UiObjectBody<'tree>, } impl<'tree> UiObjectDefinition<'tree> { pub fn from_node(node: Node<'tree>, source: &str) -> Result<Self, ParseError<'tree>> { // TODO: ui_annotated_object if node.kind() != "ui_object_definition" { return Err(ParseError::new(node, ParseErrorKind::UnexpectedNodeKind)); } let mut cursor = node.walk(); cursor.reset(astutil::get_child_by_field_name(node, "type_name")?); let type_name = NestedIdentifier::with_cursor(&mut cursor)?; cursor.reset(astutil::get_child_by_field_name(node, "initializer")?); let body = UiObjectBody::with_cursor(&mut cursor, source)?; Ok(UiObjectDefinition { node, type_name, body, }) } pub fn node(&self) -> Node<'tree> { self.node } pub fn type_name(&self) -> &NestedIdentifier<'tree> { &self.type_name } /// Object id which should be unique within the QML program. pub fn object_id(&self) -> Option<Identifier<'tree>> { self.body.object_id } /// Nodes for the direct child objects. /// /// This does not include objects bound to the properties. pub fn child_object_nodes(&self) -> &[Node<'tree>] { &self.body.child_object_nodes } /// Nodes for the attached type property bindings. pub fn attached_type_bindings(&self) -> &[UiBinding<'tree>] { &self.body.attached_type_bindings } /// Creates map of attached type property bindings. pub fn build_attached_type_map<'s>( &self, source: &'s str, ) -> Result<UiAttachedTypeBindingMap<'tree, 's>, ParseError<'tree>> { let mut type_map = UiAttachedTypeBindingMap::new(); for UiBinding { name, notation } in self.attached_type_bindings() { let (type_name, prop_name) = name .split_type_name_prefix(source) .expect("attached binding name should have type prefix"); let (_, map) = type_map .entry( type_name .components() .iter() .map(|p| p.to_str(source)) .collect(), ) .or_insert_with(|| (type_name, HashMap::new())); match *notation { UiBindingNotation::Scalar(n) => { try_insert_ui_binding_node(map, &prop_name, n, source)? } UiBindingNotation::Grouped(_) => unreachable!("attached binding can't be grouped"), } } Ok(type_map) } /// Nodes for the property bindings. pub fn bindings(&self) -> &[UiBinding<'tree>] { &self.body.bindings } /// Creates map of property bindings. pub fn build_binding_map<'s>( &self, source: &'s str, ) -> Result<UiBindingMap<'tree, 's>, ParseError<'tree>> { let mut map = HashMap::new(); for UiBinding { name, notation } in self.bindings() { match *notation { UiBindingNotation::Scalar(n) => { try_insert_ui_binding_node(&mut map, name, n, source)?; } UiBindingNotation::Grouped(n) => { try_insert_ui_grouped_binding_node(&mut map, name, n, source)?; } } } Ok(map) } } #[derive(Clone, Debug)] struct UiObjectBody<'tree> { object_id: Option<Identifier<'tree>>, child_object_nodes: Vec<Node<'tree>>, attached_type_bindings: Vec<UiBinding<'tree>>, bindings: Vec<UiBinding<'tree>>, // TODO: ... } impl<'tree> UiObjectBody<'tree> { fn with_cursor( cursor: &mut TreeCursor<'tree>, source: &str, ) -> Result<Self, ParseError<'tree>> { let container_node = cursor.node(); if container_node.kind() != "ui_object_initializer" { return Err(ParseError::new( container_node, ParseErrorKind::UnexpectedNodeKind, )); } let mut object_id = None; let mut child_object_nodes = Vec::new(); let mut attached_type_bindings = Vec::new(); let mut bindings = Vec::new(); for node in container_node.named_children(cursor) { // TODO: ui_annotated_object_member match node.kind() { "ui_object_definition" => { let name_node = astutil::get_child_by_field_name(node, "type_name")?; let name = NestedIdentifier::from_node(name_node)?; if name.maybe_starts_with_type_name(source) { child_object_nodes.push(node); } else { // grouped binding notation: base { prop: ...; ... } let value_node = astutil::get_child_by_field_name(node, "initializer")?; bindings.push(UiBinding { name, notation: UiBindingNotation::Grouped(value_node), }); } } "ui_binding" => { let name_node = astutil::get_child_by_field_name(node, "name")?; let name = NestedIdentifier::from_node(name_node)?; let value_node = astutil::get_child_by_field_name(node, "value").map(StatementNode)?; if name.to_string(source) == "id" { if object_id.is_some() { return Err(ParseError::new( name_node, ParseErrorKind::DuplicatedBinding, )); } object_id = Some(extract_object_id(value_node)?); } else if name.split_type_name_prefix(source).is_some() { attached_type_bindings.push(UiBinding { name, notation: UiBindingNotation::Scalar(value_node), }); } else { bindings.push(UiBinding { name, notation: UiBindingNotation::Scalar(value_node), }); } } // TODO: ... _ => astutil::handle_uninteresting_node(node)?, } } Ok(UiObjectBody { object_id, child_object_nodes, attached_type_bindings, bindings, }) } } /// Represents a property binding. #[derive(Clone, Debug)] pub struct UiBinding<'tree> { name: NestedIdentifier<'tree>, notation: UiBindingNotation<'tree>, } // TODO: public interface to UiBinding /// Variant for the property binding notation. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum UiBindingNotation<'tree> { Scalar(StatementNode<'tree>), Grouped(Node<'tree>), } /// Map of type name to attached property binding map. pub type UiAttachedTypeBindingMap<'tree, 'source> = HashMap<Vec<&'source str>, (NestedIdentifier<'tree>, UiBindingMap<'tree, 'source>)>; /// Map of property binding name to value (or nested binding map.) pub type UiBindingMap<'tree, 'source> = HashMap<&'source str, UiBindingValue<'tree, 'source>>; /// Variant for the property binding map. #[derive(Clone, Debug)] pub enum UiBindingValue<'tree, 'source> { // TODO: rename Node and get_node() which are ambiguous Node(StatementNode<'tree>), Map(Node<'tree>, UiBindingMap<'tree, 'source>), } impl<'tree, 'source> UiBindingValue<'tree, 'source> { /// Node representing this expression or group. pub fn node(&self) -> Node<'tree> { match self { UiBindingValue::Node(n) => n.inner_node(), UiBindingValue::Map(n, _) => *n, } } /// Node representing the binding notation of this value. /// /// If this is an intermediate map, the parent (nested) identifier node will be /// returned. That wouldn't be ideal, but should be okay for error reporting. pub fn binding_node(&self) -> Node<'tree> { self.node() .parent() .expect("binding value node should have parent") } /// Returns whether this is a (nested) map or not. pub fn is_map(&self) -> bool { self.get_map().is_some() } /// Returns the node if this isn't a (nested) map. pub fn get_node(&self) -> Option<StatementNode<'tree>> { match self { UiBindingValue::Node(n) => Some(*n), UiBindingValue::Map(..) => None, } } /// Returns a reference to the map if this is a (nested) map. pub fn get_map(&self) -> Option<&UiBindingMap<'tree, 'source>> { match self { UiBindingValue::Node(_) => None, UiBindingValue::Map(_, m) => Some(m), } } /// Returns a reference to the value corresponding to the key. /// /// If this isn't a (nested) map, returns None. pub fn get_map_value(&self, k: &str) -> Option<&UiBindingValue<'tree, 'source>> { self.get_map().and_then(|m| m.get(k)) } } fn ensure_ui_binding_map_bases<'tree, 'source, 'map>( mut map: &'map mut UiBindingMap<'tree, 'source>, full_name: &NestedIdentifier<'tree>, source: &'source str, ) -> Result<(&'map mut UiBindingMap<'tree, 'source>, Identifier<'tree>), ParseError<'tree>> { let mut name_iter = full_name.components().iter().copied(); let mut cur = name_iter .next() .expect("identifier should have at least one name"); for next in name_iter { // new map of name 'cur' is created for the 'next' node. match map .entry(cur.to_str(source)) .or_insert_with(|| UiBindingValue::Map(next.node(), HashMap::new())) { UiBindingValue::Node(_) => { return Err(ParseError::new( cur.node(), ParseErrorKind::DuplicatedBinding, )); } UiBindingValue::Map(_, m) => { map = m; } } cur = next; } Ok((map, cur)) } fn try_insert_ui_binding_node<'tree, 'source>( map: &mut UiBindingMap<'tree, 'source>, name: &NestedIdentifier<'tree>, value_node: StatementNode<'tree>, source: &'source str, ) -> Result<(), ParseError<'tree>> { use std::collections::hash_map::Entry; let (map, last) = ensure_ui_binding_map_bases(map, name, source)?; if let Entry::Vacant(e) = map.entry(last.to_str(source)) { e.insert(UiBindingValue::Node(value_node)); } else { return Err(ParseError::new( last.node(), ParseErrorKind::DuplicatedBinding, )); } Ok(()) } fn try_insert_ui_grouped_binding_node<'tree, 'source>( map: &mut UiBindingMap<'tree, 'source>, group_name: &NestedIdentifier<'tree>, container_node: Node<'tree>, source: &'source str, ) -> Result<(), ParseError<'tree>> { if container_node.kind() != "ui_object_initializer" { return Err(ParseError::new( container_node, ParseErrorKind::UnexpectedNodeKind, )); } // Intermediate maps are created by the group_name node, but the bottom map should be // attached to the container node if it's newly created. let map = { let (m, last) = ensure_ui_binding_map_bases(map, group_name, source)?; let v = m .entry(last.to_str(source)) .or_insert_with(|| UiBindingValue::Map(container_node, HashMap::new())); match v { UiBindingValue::Node(_) => { return Err(ParseError::new( last.node(), ParseErrorKind::DuplicatedBinding, )); } UiBindingValue::Map(_, m) => m, } }; for node in container_node.named_children(&mut container_node.walk()) { // TODO: ui_annotated_object_member match node.kind() { "ui_object_definition" => { let name_node = astutil::get_child_by_field_name(node, "type_name")?; let name = NestedIdentifier::from_node(name_node)?; try_insert_ui_grouped_binding_node( map, &name, astutil::get_child_by_field_name(node, "initializer")?, source, )?; } "ui_binding" => { let name_node = astutil::get_child_by_field_name(node, "name")?; let name = NestedIdentifier::from_node(name_node)?; let value_node = astutil::get_child_by_field_name(node, "value").map(StatementNode)?; try_insert_ui_binding_node(map, &name, value_node, source)?; } _ => astutil::handle_uninteresting_node(node)?, } } Ok(()) } #[cfg(test)] mod tests { use super::*; use crate::qmldoc::UiDocument; fn parse(source: &str) -> UiDocument { UiDocument::parse(source, "MyType", None) } fn extract_root_object(doc: &UiDocument) -> Result<UiObjectDefinition, ParseError> { let program = UiProgram::from_node(doc.root_node(), doc.source()).unwrap(); UiObjectDefinition::from_node(program.root_object_node(), doc.source()) } impl<'tree> UiImportSource<'tree> { fn unwrap_identifier(&self) -> &NestedIdentifier<'tree> { match self { UiImportSource::Identifier(x) => x, _ => panic!("not an identifier"), } } fn unwrap_string(&self) -> &str { match self { UiImportSource::String(x) => x, _ => panic!("not a string"), } } } #[test] fn import_statements() { let doc = parse( r###" import Foo.Bar import Baz 2 import Blah.Blah 2.1 as A import "Dir" as B Foo {} "###, ); let program = UiProgram::from_node(doc.root_node(), doc.source()).unwrap(); let imports = program.imports(); assert_eq!(imports.len(), 4); assert_eq!( imports[0] .source() .unwrap_identifier() .to_string(doc.source()), "Foo.Bar" ); assert_eq!(imports[0].version(), None); assert!(imports[0].alias().is_none()); assert_eq!( imports[1] .source() .unwrap_identifier() .to_string(doc.source()), "Baz" ); assert_eq!(imports[1].version(), Some((2, None))); assert!(imports[1].alias().is_none()); assert_eq!( imports[2] .source() .unwrap_identifier() .to_string(doc.source()), "Blah.Blah" ); assert_eq!(imports[2].version(), Some((2, Some(1)))); assert_eq!(imports[2].alias().unwrap().to_str(doc.source()), "A"); assert_eq!(imports[3].source().unwrap_string(), "Dir"); assert_eq!(imports[3].version(), None); assert_eq!(imports[3].alias().unwrap().to_str(doc.source()), "B"); } #[test] fn non_trivial_object_id_expression() { let doc = parse(r"Foo { id: (expr) }"); assert!(extract_root_object(&doc).is_err()); } #[test] fn trivial_object() { let doc = parse(r"Foo.Bar {}"); let root_obj = extract_root_object(&doc).unwrap(); assert_eq!(root_obj.type_name().to_string(doc.source()), "Foo.Bar"); assert!(root_obj.child_object_nodes().is_empty()); } #[test] fn nested_object() { let doc = parse( r###" Foo { // comment Bar.Bar {} Baz {} } "###, ); let root_obj = extract_root_object(&doc).unwrap(); assert_eq!(root_obj.type_name().to_string(doc.source()), "Foo"); assert_eq!(root_obj.child_object_nodes().len(), 2); let child_objs: Vec<_> = root_obj .child_object_nodes() .iter() .map(|&n| UiObjectDefinition::from_node(n, doc.source()).unwrap()) .collect(); assert_eq!(child_objs[0].type_name().to_string(doc.source()), "Bar.Bar"); assert_eq!(child_objs[1].type_name().to_string(doc.source()), "Baz"); } #[test] fn property_bindings() { let doc = parse( r###" Foo { id: whatever bar: 0 nested.a: 1 nested.b: 2 nested.c: 3 } "###, ); let root_obj = extract_root_object(&doc).unwrap(); assert_eq!( root_obj.object_id().unwrap().to_str(doc.source()), "whatever" ); let map = root_obj.build_binding_map(doc.source()).unwrap(); assert_eq!(map.len(), 2); assert!(!map.get("bar").unwrap().is_map()); let nested = map.get("nested").unwrap(); assert!(nested.is_map()); assert_eq!(nested.get_map().unwrap().len(), 3); assert!(!nested.get_map_value("a").unwrap().is_map()); assert!(!nested.get_map_value("b").unwrap().is_map()); assert!(!nested.get_map_value("c").unwrap().is_map()); } #[test] fn duplicated_property_bindings() { let doc = parse( r###" Foo { bar: 0 bar: 1 } "###, ); let root_obj = extract_root_object(&doc).unwrap(); assert!(root_obj.build_binding_map(doc.source()).is_err()); } #[test] fn duplicated_property_bindings_map_to_node() { let doc = parse( r###" Foo { bar.baz: 0 bar: 1 } "###, ); let root_obj = extract_root_object(&doc).unwrap(); assert!(root_obj.build_binding_map(doc.source()).is_err()); } #[test] fn duplicated_property_bindings_node_to_map() { let doc = parse( r###" Foo { bar: 0 bar.baz: 1 } "###, ); let root_obj = extract_root_object(&doc).unwrap(); assert!(root_obj.build_binding_map(doc.source()).is_err()); } #[test] fn duplicated_object_id_bindings() { let doc = parse( r###" Foo { id: foo id: bar } "###, ); assert!(extract_root_object(&doc).is_err()); } #[test] fn object_id_binding_with_comment() { let doc = parse(r"Foo { id: /*what*/ ever /*never*/ }"); let root_obj = extract_root_object(&doc).unwrap(); assert_eq!(root_obj.object_id().unwrap().to_str(doc.source()), "ever"); } #[test] fn grouped_property_bindings() { let doc = parse( r###" Foo { nested.a: 1 nested { b: 2; /* comment */ c: 3 } } "###, ); let root_obj = extract_root_object(&doc).unwrap(); let map = root_obj.build_binding_map(doc.source()).unwrap(); assert_eq!(map.len(), 1); let nested = map.get("nested").unwrap(); assert!(nested.is_map()); assert_eq!(nested.get_map().unwrap().len(), 3); assert!(!nested.get_map_value("a").unwrap().is_map()); assert!(!nested.get_map_value("b").unwrap().is_map()); assert!(!nested.get_map_value("c").unwrap().is_map()); } #[test] fn nested_grouped_property_bindings() { let doc = parse( r###" Foo { a { b { c: 1 } } } "###, ); let root_obj = extract_root_object(&doc).unwrap(); let map = root_obj.build_binding_map(doc.source()).unwrap(); assert!(!map .get("a") .unwrap() .get_map_value("b") .unwrap() .get_map_value("c") .unwrap() .is_map()); } #[test] fn attached_property_bindings() { let doc = parse( r###" Foo { Bar.baz: 0 A.B.c.d: 1 Bar.bar: 2 } "###, ); let root_obj = extract_root_object(&doc).unwrap(); let type_map = root_obj.build_attached_type_map(doc.source()).unwrap(); assert_eq!(type_map.len(), 2); let (_, bar_map) = type_map.get(["Bar"].as_ref()).unwrap(); assert_eq!(bar_map.len(), 2); assert!(!bar_map.get("bar").unwrap().is_map()); assert!(!bar_map.get("baz").unwrap().is_map()); let (_, ab_map) = type_map.get(["A", "B"].as_ref()).unwrap(); assert_eq!(ab_map.len(), 1); assert!(ab_map.get("c").unwrap().is_map()); assert!(!ab_map .get("c") .unwrap() .get_map_value("d") .unwrap() .is_map()); } }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/qmlast/stmt.rs
Rust
use super::astutil; use super::node::{ExpressionNode, StatementNode}; use super::term::{self, Identifier, NestedIdentifier}; use super::{ParseError, ParseErrorKind}; use tree_sitter::{Node, TreeCursor}; /// Variant for statements. #[derive(Clone, Debug)] pub enum Statement<'tree> { /// Expression node. Expression(ExpressionNode<'tree>), /// Block of statement nodes, or an empty statement without block. Block(Vec<StatementNode<'tree>>), LexicalDeclaration(LexicalDeclaration<'tree>), If(IfStatement<'tree>), Switch(SwitchStatement<'tree>), /// Break with optional label. Break(Option<Identifier<'tree>>), /// Return with optionally expression node. Return(Option<ExpressionNode<'tree>>), } impl<'tree> Statement<'tree> { pub fn from_node(node: StatementNode<'tree>) -> Result<Self, ParseError<'tree>> { Self::with_cursor(&mut node.walk()) } pub(super) fn with_cursor(cursor: &mut TreeCursor<'tree>) -> Result<Self, ParseError<'tree>> { let node = cursor.node(); let stmt = match node.kind() { "expression_statement" => { astutil::goto_first_named_child(cursor)?; Statement::Expression(ExpressionNode(cursor.node())) } "statement_block" => { let stmts = node .named_children(cursor) .filter(|n| !n.is_extra()) .map(StatementNode) .collect(); Statement::Block(stmts) } "empty_statement" => Statement::Block(vec![]), "lexical_declaration" => { LexicalDeclaration::with_cursor(cursor).map(Statement::LexicalDeclaration)? } "if_statement" => { let condition = astutil::get_child_by_field_name(node, "condition").map(ExpressionNode)?; let consequence = astutil::get_child_by_field_name(node, "consequence").map(StatementNode)?; let alternative = node .child_by_field_name("alternative") .map(|n| { cursor.reset(n); astutil::goto_first_named_child(cursor)?; Ok(StatementNode(cursor.node())) }) .transpose()?; Statement::If(IfStatement { condition, consequence, alternative, }) } "switch_statement" => SwitchStatement::with_cursor(cursor).map(Statement::Switch)?, "break_statement" => { let label = node .child_by_field_name("label") .map(Identifier::from_node) .transpose()?; Statement::Break(label) } "return_statement" => { let expr = node .named_children(cursor) .find(|n| !n.is_extra()) .map(ExpressionNode); Statement::Return(expr) } _ => { return Err(ParseError::new(node, ParseErrorKind::UnexpectedNodeKind)); } }; Ok(stmt) } } /// Represents a "let"/"const" declaration. #[derive(Clone, Debug)] pub struct LexicalDeclaration<'tree> { pub kind: LexicalDeclarationKind, pub variables: Vec<VariableDeclarator<'tree>>, } impl<'tree> LexicalDeclaration<'tree> { fn with_cursor(cursor: &mut TreeCursor<'tree>) -> Result<Self, ParseError<'tree>> { let node = cursor.node(); let kind_node = astutil::get_child_by_field_name(node, "kind")?; let kind = LexicalDeclarationKind::from_node(kind_node)?; let variables = node .named_children(cursor) .filter(|&n| !n.is_extra() && n != kind_node) .map(VariableDeclarator::from_node) .collect::<Result<Vec<_>, _>>()?; Ok(LexicalDeclaration { kind, variables }) } } /// Type of lexical declaration. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum LexicalDeclarationKind { Let, Const, } impl LexicalDeclarationKind { fn from_node(node: Node) -> Result<Self, ParseError> { if node.is_named() { return Err(ParseError::new(node, ParseErrorKind::UnexpectedNodeKind)); } match node.kind() { "let" => Ok(LexicalDeclarationKind::Let), "const" => Ok(LexicalDeclarationKind::Const), _ => Err(ParseError::new(node, ParseErrorKind::UnexpectedNodeKind)), } } } /// Pair of variable name and initializer expression. /// /// This does not support array/object destructuring pattern. #[derive(Clone, Debug)] pub struct VariableDeclarator<'tree> { pub name: Identifier<'tree>, pub ty: Option<NestedIdentifier<'tree>>, pub value: Option<ExpressionNode<'tree>>, } impl<'tree> VariableDeclarator<'tree> { fn from_node(node: Node<'tree>) -> Result<Self, ParseError<'tree>> { if node.kind() != "variable_declarator" { return Err(ParseError::new(node, ParseErrorKind::UnexpectedNodeKind)); } let name = astutil::get_child_by_field_name(node, "name").and_then(Identifier::from_node)?; let ty = node .child_by_field_name("type") .map(term::extract_type_annotation) .transpose()?; let value = node.child_by_field_name("value").map(ExpressionNode); Ok(VariableDeclarator { name, ty, value }) } pub fn node(&self) -> Node<'tree> { self.name .node() .parent() .expect("variable declarator name node should have parent") } } /// Represents an "if" statement. #[derive(Clone, Debug)] pub struct IfStatement<'tree> { pub condition: ExpressionNode<'tree>, pub consequence: StatementNode<'tree>, pub alternative: Option<StatementNode<'tree>>, } /// Represents a "switch" statement. #[derive(Clone, Debug)] pub struct SwitchStatement<'tree> { /// Expression to be matched against each case clause. pub value: ExpressionNode<'tree>, /// Case clauses. pub cases: Vec<SwitchCase<'tree>>, /// Default clause. pub default: Option<SwitchDefault<'tree>>, } /// Represents a "case" clause. #[derive(Clone, Debug)] pub struct SwitchCase<'tree> { /// Expression to be matched. pub value: ExpressionNode<'tree>, /// Statements to be executed. pub body: Vec<StatementNode<'tree>>, } /// Represents a "default" clause. #[derive(Clone, Debug)] pub struct SwitchDefault<'tree> { /// Index in the fall-through list, which is usually `cases.len()`. pub position: usize, /// Statements to be executed. pub body: Vec<StatementNode<'tree>>, } impl<'tree> SwitchStatement<'tree> { fn with_cursor(cursor: &mut TreeCursor<'tree>) -> Result<Self, ParseError<'tree>> { let switch_node = cursor.node(); let switch_value = astutil::get_child_by_field_name(switch_node, "value").map(ExpressionNode)?; let switch_body_node = astutil::get_child_by_field_name(switch_node, "body")?; let mut cases = Vec::new(); let mut default = None; for (i, node) in switch_body_node.named_children(cursor).enumerate() { match node.kind() { "switch_case" => { let value = astutil::get_child_by_field_name(node, "value").map(ExpressionNode)?; let body = node .children_by_field_name("body", &mut node.walk()) .map(StatementNode) .collect(); cases.push(SwitchCase { value, body }); } "switch_default" if default.is_some() => { return Err(ParseError::new(node, ParseErrorKind::MultipleDefaultLabels)); } "switch_default" => { let body = node .children_by_field_name("body", &mut node.walk()) .map(StatementNode) .collect(); default = Some(SwitchDefault { position: i, body }); } _ => { return Err(ParseError::new(node, ParseErrorKind::UnexpectedNodeKind)); } } } Ok(SwitchStatement { value: switch_value, cases, default, }) } } #[cfg(test)] mod tests { use super::super::expr::Expression; use super::*; use crate::qmlast::{UiObjectDefinition, UiProgram}; use crate::qmldoc::UiDocument; macro_rules! impl_unwrap_fn { ($name:ident, $pat:path, $ty:ty) => { fn $name(self) -> $ty { match self { $pat(x) => x, _ => panic!("unexpected statement: {self:?}"), } } }; } impl<'tree> Statement<'tree> { impl_unwrap_fn!( unwrap_expression, Statement::Expression, ExpressionNode<'tree> ); impl_unwrap_fn!(unwrap_block, Statement::Block, Vec<StatementNode<'tree>>); impl_unwrap_fn!( unwrap_lexical_declaration, Statement::LexicalDeclaration, LexicalDeclaration<'tree> ); impl_unwrap_fn!(unwrap_if, Statement::If, IfStatement<'tree>); impl_unwrap_fn!(unwrap_switch, Statement::Switch, SwitchStatement<'tree>); impl_unwrap_fn!(unwrap_break, Statement::Break, Option<Identifier<'tree>>); impl_unwrap_fn!( unwrap_return, Statement::Return, Option<ExpressionNode<'tree>> ); } fn parse(source: &str) -> UiDocument { UiDocument::parse(source, "MyType", None) } fn extract_stmt<'t>(doc: &'t UiDocument, name: &str) -> Result<Statement<'t>, ParseError<'t>> { let program = UiProgram::from_node(doc.root_node(), doc.source()).unwrap(); let obj = UiObjectDefinition::from_node(program.root_object_node(), doc.source()).unwrap(); let map = obj.build_binding_map(doc.source()).unwrap(); let node = map.get(name).unwrap().get_node().unwrap(); node.parse() } fn unwrap_stmt<'t>(doc: &'t UiDocument, name: &str) -> Statement<'t> { extract_stmt(doc, name).unwrap() } fn unwrap_block_stmt<'t>(doc: &'t UiDocument, name: &str) -> Statement<'t> { let ns = unwrap_stmt(doc, name).unwrap_block(); assert!(ns.len() == 1); ns[0].parse().unwrap() } #[test] fn trivial_statements() { let doc = parse( r###" Foo { identifier_expr: foo block: { /*garbage*/ 0; { nested; } 2 /*garbage*/ } empty_block: {} empty_no_block: ; } "###, ); let n = unwrap_stmt(&doc, "identifier_expr").unwrap_expression(); assert!(Expression::from_node(n, doc.source()).is_ok()); let ns = unwrap_stmt(&doc, "block").unwrap_block(); assert_eq!(ns.len(), 3); assert!( Expression::from_node(ns[0].parse().unwrap().unwrap_expression(), doc.source()).is_ok() ); assert!(matches!(ns[1].parse().unwrap(), Statement::Block(_))); assert!( Expression::from_node(ns[2].parse().unwrap().unwrap_expression(), doc.source()).is_ok() ); let ns = unwrap_stmt(&doc, "empty_block").unwrap_block(); assert!(ns.is_empty()); let ns = unwrap_stmt(&doc, "empty_no_block").unwrap_block(); assert!(ns.is_empty()); } #[test] fn lexical_declaration() { let doc = parse( r###" Foo { let_one: { let x = 1 } let_uninit: { let x } let_typed: { let x: int } const_two: { const x = 1, y = 2 } } "###, ); let x = unwrap_block_stmt(&doc, "let_one").unwrap_lexical_declaration(); assert_eq!(x.kind, LexicalDeclarationKind::Let); assert_eq!(x.variables.len(), 1); assert_eq!(x.variables[0].name.to_str(doc.source()), "x"); assert!(x.variables[0].ty.is_none()); assert!(Expression::from_node(x.variables[0].value.unwrap(), doc.source()).is_ok()); let x = unwrap_block_stmt(&doc, "let_uninit").unwrap_lexical_declaration(); assert_eq!(x.kind, LexicalDeclarationKind::Let); assert_eq!(x.variables.len(), 1); assert_eq!(x.variables[0].name.to_str(doc.source()), "x"); assert!(x.variables[0].ty.is_none()); assert!(x.variables[0].value.is_none()); let x = unwrap_block_stmt(&doc, "let_typed").unwrap_lexical_declaration(); assert_eq!(x.kind, LexicalDeclarationKind::Let); assert_eq!(x.variables.len(), 1); assert_eq!(x.variables[0].name.to_str(doc.source()), "x"); assert_eq!( x.variables[0].ty.as_ref().unwrap().to_string(doc.source()), "int" ); assert!(x.variables[0].value.is_none()); let x = unwrap_block_stmt(&doc, "const_two").unwrap_lexical_declaration(); assert_eq!(x.kind, LexicalDeclarationKind::Const); assert_eq!(x.variables.len(), 2); assert_eq!(x.variables[0].name.to_str(doc.source()), "x"); assert!(x.variables[0].ty.is_none()); assert!(Expression::from_node(x.variables[0].value.unwrap(), doc.source()).is_ok()); assert_eq!(x.variables[1].name.to_str(doc.source()), "y"); assert!(x.variables[1].ty.is_none()); assert!(Expression::from_node(x.variables[1].value.unwrap(), doc.source()).is_ok()); } #[test] fn if_statement() { let doc = parse( r###" Foo { if_: if (0) /*garbage*/ { 1 } if_else: if (0) { 1 } else /*garbage*/ { 2 } } "###, ); let x = unwrap_stmt(&doc, "if_").unwrap_if(); assert!(Expression::from_node(x.condition, doc.source()).is_ok()); assert!(x.consequence.parse().is_ok()); assert!(x.alternative.is_none()); let x = unwrap_stmt(&doc, "if_else").unwrap_if(); assert!(Expression::from_node(x.condition, doc.source()).is_ok()); assert!(x.consequence.parse().is_ok()); assert!(x.alternative.unwrap().parse().is_ok()); assert_ne!(x.consequence, x.alternative.unwrap()); } #[test] fn switch_statement() { let doc = parse( r###" Foo { switch_no_default: switch (foo) { case /*garbage*/ 0: "case 0" /*garbage*/; break; case 1 /*garbage*/: case 2: break a; } switch_with_default: switch (foo) { case 0: default: "default"; } switch_multiple_defaults: switch (foo) { case 0: default: "default"; default: "default"; } } "###, ); let x = unwrap_stmt(&doc, "switch_no_default").unwrap_switch(); assert!(Expression::from_node(x.value, doc.source()).is_ok()); assert_eq!(x.cases.len(), 3); assert!(Expression::from_node(x.cases[0].value, doc.source()).is_ok()); assert_eq!(x.cases[0].body.len(), 2); assert!(x.cases[0].body[1].parse().unwrap().unwrap_break().is_none()); assert_eq!(x.cases[1].body.len(), 0); assert_eq!(x.cases[2].body.len(), 1); assert!(x.cases[2].body[0].parse().unwrap().unwrap_break().is_some()); assert!(x.default.is_none()); let x = unwrap_stmt(&doc, "switch_with_default").unwrap_switch(); assert_eq!(x.cases.len(), 1); assert_eq!(x.cases[0].body.len(), 0); assert_eq!(x.default.as_ref().unwrap().position, 1); assert_eq!(x.default.as_ref().unwrap().body.len(), 1); assert!(extract_stmt(&doc, "switch_multiple_defaults").is_err()); } #[test] fn return_statement() { let doc = parse( r###" Foo { return_none: { return; } return_garbage: { return /*garbage*/; } return_value: { return /*garbage*/ 1; } } "###, ); let x = unwrap_block_stmt(&doc, "return_none").unwrap_return(); assert!(x.is_none()); let x = unwrap_block_stmt(&doc, "return_garbage").unwrap_return(); assert!(x.is_none()); let x = unwrap_block_stmt(&doc, "return_value").unwrap_return(); assert!(Expression::from_node(x.unwrap(), doc.source()).is_ok()); } }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/qmlast/term.rs
Rust
use super::astutil; use super::{ParseError, ParseErrorKind}; use std::borrow::Cow; use tree_sitter::{Node, TreeCursor}; /// Represents a primitive identifier. #[derive(Clone, Copy, Debug)] pub struct Identifier<'tree>(Node<'tree>); impl<'tree> Identifier<'tree> { pub fn from_node(node: Node<'tree>) -> Result<Self, ParseError<'tree>> { match node.kind() { "identifier" | "predefined_type" | "property_identifier" | "statement_identifier" | "type_identifier" => Ok(Identifier(node)), _ => Err(ParseError::new(node, ParseErrorKind::UnexpectedNodeKind)), } } pub fn node(&self) -> Node<'tree> { self.0 } /// Checks if this identifier looks like a type name. pub fn maybe_type_name(&self, source: &str) -> bool { self.to_str(source).starts_with(char::is_uppercase) } pub fn to_str<'s>(&self, source: &'s str) -> &'s str { astutil::node_text(self.0, source) } } /// Represents a (possibly nested) identifier. #[derive(Clone, Debug)] pub struct NestedIdentifier<'tree> { // TODO: optimize with smallvec or store the nested_identifier node? components: Vec<Identifier<'tree>>, } impl<'tree> NestedIdentifier<'tree> { pub fn from_node(node: Node<'tree>) -> Result<Self, ParseError<'tree>> { Self::with_cursor(&mut node.walk()) } pub(super) fn with_cursor(cursor: &mut TreeCursor<'tree>) -> Result<Self, ParseError<'tree>> { let mut depth: usize = 0; while matches!( cursor.node().kind(), "nested_identifier" | "nested_type_identifier" ) { astutil::goto_first_named_child(cursor)?; depth += 1; } let components = if depth == 0 { // (identifier) vec![Identifier::from_node(cursor.node())?] } else { // (nested_identifier (nested_identifier (identifier) (identifier)) (identifier)) let mut components = Vec::with_capacity(depth + 1); 'pop: loop { let node = cursor.node(); match node.kind() { "identifier" | "type_identifier" => { components.push(Identifier(node)); } _ => astutil::handle_uninteresting_node(node)?, } while !cursor.goto_next_sibling() { if !cursor.goto_parent() { break 'pop; } } } components }; Ok(NestedIdentifier { components }) } /// Node representing the (possibly nested) identifier. /// /// If this has been split previously, the returned node may point to a wider /// identifier range. pub fn node(&self) -> Node<'tree> { if self.components.len() == 1 { // (identifier) self.components[0].node() } else { // (nested_identifier (nested_identifier (identifier) (identifier)) (identifier)) self.components .last() .expect("nested identifier shouldn't be empty") .node() .parent() .expect("nested identifier node should have parent") } } pub fn components(&self) -> &[Identifier<'tree>] { &self.components } /// Checks if this looks like an identifier prefixed with a type name. pub fn maybe_starts_with_type_name(&self, source: &str) -> bool { self.components .first() .map(|p| p.maybe_type_name(source)) .unwrap_or(false) } /// Splits this to type-name-a-like and the remainder parts. /// /// If either part is empty, returns None. pub fn split_type_name_prefix(&self, source: &str) -> Option<(Self, Self)> { match self .components .iter() .position(|p| !p.maybe_type_name(source)) { Some(n) if n > 0 => { let (type_parts, rem_parts) = self.components.split_at(n); debug_assert!(!type_parts.is_empty()); debug_assert!(!rem_parts.is_empty()); Some(( NestedIdentifier { components: type_parts.to_owned(), }, NestedIdentifier { components: rem_parts.to_owned(), }, )) } _ => None, } } pub fn to_string<'s>(&self, source: &'s str) -> Cow<'s, str> { if self.components.len() == 1 { Cow::Borrowed(self.components[0].to_str(source)) } else { let dotted_path = self .components .iter() .map(|p| p.to_str(source)) .collect::<Vec<_>>() .join("."); Cow::Owned(dotted_path) } } } // TODO: maybe introduce an AST type dedicated for type expression? pub(super) fn extract_type_annotation(node: Node) -> Result<NestedIdentifier, ParseError> { let mut cursor = node.walk(); astutil::goto_first_named_child(&mut cursor)?; NestedIdentifier::with_cursor(&mut cursor) } #[cfg(test)] mod tests { use super::*; use crate::qmldoc::UiDocument; fn parse(source: &str) -> UiDocument { UiDocument::parse(source, "MyType", None) } fn extract_type_id(doc: &UiDocument) -> Result<NestedIdentifier, ParseError> { let node = doc .root_node() .child_by_field_name("root") .unwrap() .child_by_field_name("type_name") .unwrap(); NestedIdentifier::with_cursor(&mut node.walk()) } #[test] fn trivial_identifier() { let doc = parse(r"Foo {}"); let id = extract_type_id(&doc).unwrap(); assert_eq!(id.components().len(), 1); assert_eq!(id.to_string(doc.source()), "Foo"); } #[test] fn nested_identifier() { let doc = parse(r"Foo.Bar.Baz {}"); let id = extract_type_id(&doc).unwrap(); assert_eq!(id.components().len(), 3); assert_eq!(id.to_string(doc.source()), "Foo.Bar.Baz"); } #[test] fn nested_identifier_with_comments() { let doc = parse(r"Foo. /*Bar.*/ Baz {}"); let id = extract_type_id(&doc).unwrap(); assert_eq!(id.components().len(), 2); assert_eq!(id.to_string(doc.source()), "Foo.Baz"); } #[test] fn doubled_dots_in_identifier() { // this is syntax error, but recovered as Foo./* something bad */Bar. let doc = parse(r"Foo..Bar {}"); let id = extract_type_id(&doc).unwrap(); assert_eq!(id.to_string(doc.source()), "Foo.Bar"); } }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/qmldir.rs
Rust
//! QML module/directory handling. use crate::diagnostic::{Diagnostic, Diagnostics, ProjectDiagnostics}; use crate::qmlast::{UiImportSource, UiObjectDefinition, UiProgram}; use crate::qmldoc::{UiDocument, UiDocumentsCache}; use crate::typemap::{ModuleData, ModuleId, ModuleIdBuf, QmlComponentData, TypeMap}; use camino::{Utf8Path, Utf8PathBuf}; use std::io; use thiserror::Error; /// Populates directory modules reachable from the given `src_paths`. /// /// The `src_paths` element may point to either a QML file or a directory containing QML files. pub fn populate_directories<I>( type_map: &mut TypeMap, docs_cache: &mut UiDocumentsCache, src_paths: I, project_diagnostics: &mut ProjectDiagnostics, ) -> Result<(), PopulateError> where I: IntoIterator, I::Item: AsRef<Utf8Path>, { let mut pending_dirs: Vec<_> = src_paths .into_iter() .map(|p| { let p = p.as_ref(); if p.is_file() { normalize_path(p.parent().expect("file path should have parent")) } else { normalize_path(p) } }) .collect(); log::debug!("populating directories from {pending_dirs:?}"); while let Some(base_dir) = pending_dirs.pop() { if type_map.contains_module(ModuleId::Directory(base_dir.as_ref())) { continue; // already visited } log::trace!("processing directory {base_dir:?}"); let mut base_module_data = ModuleData::default(); for entry in base_dir .read_dir_utf8() .map_err(|e| PopulateError::ReadDir(base_dir.clone(), e))? { let entry = entry.map_err(|e| PopulateError::ReadDir(base_dir.clone(), e))?; if !is_qml_file(entry.path()) { continue; } log::trace!("processing file {:?}", entry.path()); let doc = docs_cache .read(entry.path()) .map_err(|e| PopulateError::ReadUiDocument(entry.path().to_owned(), e))?; let mut diagnostics = Diagnostics::new(); if let Some(data) = make_doc_component_data(doc, &base_dir, &mut diagnostics) { for id in data.imports() { match id { ModuleId::Builtins | ModuleId::Named(_) => {} ModuleId::Directory(dir) if !type_map.contains_module(id) => { pending_dirs.push(dir.to_owned()); } ModuleId::Directory(_) => {} // already visited } } base_module_data.push_qml_component(data); } project_diagnostics.push(entry.path(), diagnostics); } type_map.insert_module( ModuleIdBuf::Directory(base_dir.to_owned()), base_module_data, ); } Ok(()) } fn make_doc_component_data( doc: &UiDocument, doc_base_dir: &Utf8Path, diagnostics: &mut Diagnostics, ) -> Option<QmlComponentData> { let program = diagnostics.consume_err(UiProgram::from_node(doc.root_node(), doc.source()))?; let obj = diagnostics.consume_err(UiObjectDefinition::from_node( program.root_object_node(), doc.source(), ))?; let mut data = QmlComponentData::with_super(doc.type_name(), obj.type_name().to_string(doc.source())); // QML files in the base directory should be available by default data.import_module(ModuleIdBuf::Directory(doc_base_dir.to_owned())); for imp in program.imports() { if imp.alias().is_some() { diagnostics.push(Diagnostic::error( imp.node().byte_range(), "aliased import is not supported", )); continue; } if imp.version().is_some() { diagnostics.push(Diagnostic::warning( imp.node().byte_range(), "import version is ignored", )); } match imp.source() { UiImportSource::Identifier(x) => { let s = x.to_string(doc.source()); data.import_module(ModuleIdBuf::Named(s.into())); } UiImportSource::String(x) => { let dir = doc_base_dir.join(x); if dir.is_dir() { data.import_module(ModuleIdBuf::Directory(normalize_path(dir).to_owned())); } else { // confine error so the population loop wouldn't fail with e.g. ENOENT diagnostics.push(Diagnostic::error( imp.node().byte_range(), // TODO: on imp.source() node format!("source path is not a directory: {dir}"), )); } } } } // TODO: properties, functions, etc. if we add support for those Some(data) } fn is_qml_file(path: &Utf8Path) -> bool { path.is_file() && path .extension() .map(|s| s.eq_ignore_ascii_case("qml")) .unwrap_or(false) } pub fn normalize_path<P>(path: P) -> Utf8PathBuf where P: AsRef<Utf8Path>, { // TODO: normalize per BuildContext rule?, which wouldn't fail let path = path.as_ref(); if path.as_str().is_empty() { // Path("foo").parent() returns "", not "." // https://github.com/rust-lang/rust/issues/36861 Utf8Path::new(".").canonicalize_utf8() } else { path.canonicalize_utf8() } .unwrap_or_else(|_| path.to_owned()) } /// Error occurred while populating directory modules. #[derive(Debug, Error)] pub enum PopulateError { #[error("failed to read module directory '{0}': {1}")] ReadDir(Utf8PathBuf, #[source] io::Error), #[error("failed to read QML document '{0}': {1}")] ReadUiDocument(Utf8PathBuf, #[source] io::Error), }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/qmldoc.rs
Rust
//! QML source document management. use camino::{Utf8Path, Utf8PathBuf}; use std::collections::{HashMap, VecDeque}; use std::error::Error; use std::fmt; use std::fs; use std::io; use std::ops::Range; use tree_sitter::{Language, Node, Parser, Tree}; /// Object holding QML source text and parsed tree. #[derive(Clone, Debug)] pub struct UiDocument { source: String, tree: Tree, type_name: String, path: Option<Utf8PathBuf>, } impl UiDocument { /// Creates parsed tree for the given QML source. /// /// The parsing doesn't fail even if the QML source has a syntax error. Instead, a node /// representing the error is inserted. pub fn parse<S, T>(source: S, type_name: T, path: Option<Utf8PathBuf>) -> Self where S: Into<String>, T: Into<String>, { let source = source.into(); let mut parser = new_parser(); let tree = parser .parse(source.as_bytes(), None) .expect("no timeout nor cancellation should have been made"); let type_name = type_name.into(); UiDocument { source, tree, type_name, path, } } /// Creates parsed tree from the given QML file. /// /// The parsing doesn't fail even if the QML source has a syntax error. Instead, a node /// representing the error is inserted. pub fn read<P>(path: P) -> io::Result<Self> where P: AsRef<Utf8Path>, // TODO: or Into<Utf8PathBuf>, but read(&path) makes more sense? { let path = path.as_ref(); let type_name = path .file_stem() .ok_or_else(|| io::Error::other("no type name part in file name"))?; log::debug!("reading file {path:?}"); let source = fs::read_to_string(path)?; Ok(Self::parse(source, type_name, Some(path.to_owned()))) } /// File path to this QML document. pub fn path(&self) -> Option<&Utf8Path> { self.path.as_deref() } /// Type (or component) name of this QML document. /// /// It's typically the file name without ".qml" suffix. pub fn type_name(&self) -> &str { &self.type_name } pub fn has_syntax_error(&self) -> bool { self.tree.root_node().has_error() } /// Collects syntax errors from the parsed tree. pub fn collect_syntax_errors(&self) -> Vec<SyntaxError<'_>> { if !self.tree.root_node().has_error() { return Vec::new(); } // walk tree since (MISSING) nodes can't be queried: // https://github.com/tree-sitter/tree-sitter/issues/650 let mut cursor = self.tree.walk(); let mut pending_nodes = VecDeque::from([self.tree.root_node()]); let mut errors = Vec::new(); while let Some(node) = pending_nodes.pop_front() { assert!(node.has_error()); if node.is_error() { errors.push(SyntaxError::new(node, SyntaxErrorKind::Error)); } else if node.is_missing() { errors.push(SyntaxError::new(node, SyntaxErrorKind::Missing)); } else { for n in node.children(&mut cursor) { if n.has_error() { pending_nodes.push_back(n); } } } } errors } pub fn source(&self) -> &str { &self.source } /// Root node of the parsed tree. pub fn root_node(&self) -> Node<'_> { self.tree.root_node() } } /// Cache of [`UiDocument`]s loaded from file. #[derive(Clone, Debug, Default)] pub struct UiDocumentsCache { docs: HashMap<Utf8PathBuf, UiDocument>, } impl UiDocumentsCache { pub fn new() -> Self { UiDocumentsCache::default() } /// Reads the specified QML file if unavailable in cache, returns the cached document. pub fn read<P>(&mut self, path: P) -> io::Result<&mut UiDocument> where P: AsRef<Utf8Path>, { use std::collections::hash_map::Entry; let path = path.as_ref(); // user specified path to be kept in UiDocument object let doc = match self.docs.entry(path.canonicalize_utf8()?) { Entry::Occupied(e) => e.into_mut(), Entry::Vacant(e) => e.insert(UiDocument::read(path)?), }; Ok(doc) } /// Returns the cached document for the specified path. pub fn get<P>(&self, path: P) -> Option<&UiDocument> where P: AsRef<Utf8Path>, { path.as_ref() .canonicalize_utf8() .ok() .and_then(|p| self.docs.get(&p)) } /// Checks if the specified document is cached. pub fn contains<P>(&self, path: P) -> bool where P: AsRef<Utf8Path>, { self.get(path).is_some() } /// Evicts the specified document from the cache. pub fn remove<P>(&mut self, path: P) -> Option<UiDocument> where P: AsRef<Utf8Path>, { path.as_ref() .canonicalize_utf8() .ok() .and_then(|p| self.docs.remove(&p)) } } fn new_parser() -> Parser { let language = Language::new(tree_sitter_qmljs::LANGUAGE); let mut parser = Parser::new(); parser .set_language(&language) .expect("QML grammar should be compatible with parser"); parser } /// Syntax error found in QML parse tree. #[derive(Clone, Debug)] pub struct SyntaxError<'t> { node: Node<'t>, kind: SyntaxErrorKind, } /// Details of QML syntax error. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum SyntaxErrorKind { Error, Missing, } impl<'t> SyntaxError<'t> { pub fn new(node: Node<'t>, kind: SyntaxErrorKind) -> Self { SyntaxError { node, kind } } pub fn node(&self) -> Node<'t> { self.node } pub fn kind(&self) -> SyntaxErrorKind { self.kind } pub fn start_byte(&self) -> usize { self.node.start_byte() } pub fn end_byte(&self) -> usize { self.node.end_byte() } pub fn byte_range(&self) -> Range<usize> { self.node.byte_range() } } impl fmt::Display for SyntaxError<'_> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.kind { SyntaxErrorKind::Error => write!(f, "syntax error"), SyntaxErrorKind::Missing => write!(f, "missing {}", self.node.kind()), } } } impl Error for SyntaxError<'_> {} #[cfg(test)] mod tests { use super::*; fn parse(source: &str) -> UiDocument { UiDocument::parse(source, "MyType", None) } #[test] fn syntax_error() { let doc = parse( r###" import "###, ); assert!(doc.has_syntax_error()); let errors = doc.collect_syntax_errors(); assert_eq!(errors.len(), 1); } #[test] fn syntax_error_missing() { let doc = parse( r###" Foo { "###, ); assert!(doc.has_syntax_error()); let errors = doc.collect_syntax_errors(); assert_eq!(errors.len(), 1); } #[test] fn syntax_error_deep() { let doc = parse( r###" Foo { Ok { bar: 0 } Missing { baz: ( } } "###, ); assert!(doc.has_syntax_error()); let errors = doc.collect_syntax_errors(); assert_eq!(errors.len(), 1); } }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/qtname.rs
Rust
//! Utility for Qt naming convention. use std::collections::HashMap; /// File naming rules. #[derive(Clone, Debug, Eq, PartialEq)] pub struct FileNameRules { pub cxx_header_suffix: String, pub lowercase: bool, } impl FileNameRules { pub fn type_name_to_cxx_header_name<S>(&self, type_name: S) -> String where S: AsRef<str>, { self.apply_case_change(format!( "{}.{}", type_name.as_ref(), &self.cxx_header_suffix )) } pub fn type_name_to_ui_name<S>(&self, type_name: S) -> String where S: AsRef<str>, { self.apply_case_change(format!("{}.ui", type_name.as_ref())) } pub fn type_name_to_ui_cxx_header_name<S>(&self, type_name: S) -> String where S: AsRef<str>, { self.apply_case_change(format!( "ui_{}.{}", type_name.as_ref(), &self.cxx_header_suffix )) } pub fn type_name_to_ui_support_cxx_header_name<S>(&self, type_name: S) -> String where S: AsRef<str>, { self.apply_case_change(format!( "uisupport_{}.{}", type_name.as_ref(), &self.cxx_header_suffix )) } fn apply_case_change(&self, mut file_name: String) -> String { if self.lowercase { file_name.make_ascii_lowercase(); } file_name } } impl Default for FileNameRules { fn default() -> Self { Self { cxx_header_suffix: "h".to_owned(), lowercase: true, } } } /// Generates unique name with string prefixes. /// /// The naming rule follows `Driver::unique()` defined in `qtbase/src/tools/uic/driver.cpp`. #[derive(Clone, Debug, Default)] pub struct UniqueNameGenerator { used_prefixes: HashMap<String, usize>, // prefix: next count } impl UniqueNameGenerator { pub fn new() -> Self { UniqueNameGenerator::default() } /// Generates unique name starting with the given `prefix`. pub fn generate<S>(&mut self, prefix: S) -> String where S: AsRef<str>, { let prefix = prefix.as_ref(); let count = self.used_prefixes.entry(prefix.to_owned()).or_insert(0); let id = concat_number_suffix(prefix, *count); *count += 1; id } /// Generates unique name starting with the given `prefix`, and not listed in /// the reserved map. pub fn generate_with_reserved_map<S, V>( &mut self, prefix: S, reserved_map: &HashMap<String, V>, ) -> String where S: AsRef<str>, { let prefix = prefix.as_ref(); let count = self.used_prefixes.entry(prefix.to_owned()).or_insert(0); let (n, id) = (*count..=*count + reserved_map.len()) .find_map(|n| { let id = concat_number_suffix(prefix, n); if reserved_map.contains_key(&id) { None } else { Some((n, id)) } }) .expect("unused id must be found within N+1 tries"); *count = n + 1; id } } fn concat_number_suffix(prefix: &str, n: usize) -> String { if n == 0 { prefix.to_owned() } else { format!("{prefix}{n}") } } /// Creates a copy of the given string which the first character is turned into ASCII upper case. pub fn to_ascii_capitalized(name: &str) -> String { if name.starts_with(|c: char| c.is_ascii_lowercase()) { let src_bytes = name.as_bytes(); let mut capitalized = Vec::with_capacity(src_bytes.len()); capitalized.push(src_bytes[0].to_ascii_uppercase()); capitalized.extend_from_slice(&src_bytes[1..]); String::from_utf8(capitalized).expect("changing ASCII letter should not invalidate UTF-8") } else { name.to_owned() } } /// Creates a copy of the given string which the first character is turned into ASCII lower case. pub fn to_ascii_uncapitalized(name: &str) -> String { if name.starts_with(|c: char| c.is_ascii_uppercase()) { let src_bytes = name.as_bytes(); let mut uncapitalized = Vec::with_capacity(src_bytes.len()); uncapitalized.push(src_bytes[0].to_ascii_lowercase()); uncapitalized.extend_from_slice(&src_bytes[1..]); String::from_utf8(uncapitalized).expect("changing ASCII letter should not invalidate UTF-8") } else { name.to_owned() } } /// Extracts signal name from the given `on` callback name. /// /// ``` /// # use qmluic::qtname::*; /// assert_eq!(callback_to_signal_name("onClicked"), Some("clicked".to_owned())); /// assert!(callback_to_signal_name("click").is_none()); /// assert!(callback_to_signal_name("on").is_none()); /// assert!(callback_to_signal_name("onclick").is_none()); /// ``` pub fn callback_to_signal_name(name: &str) -> Option<String> { if name.starts_with("on") && name[2..].starts_with(|c: char| c.is_ascii_uppercase()) { Some(to_ascii_uncapitalized(&name[2..])) } else { None } } /// Checks if the property name follows the standard setter function naming convention. /// /// See `PropertyDef::stdCppSet()` in `qtbase/src/tools/moc/moc.h` for details. pub fn is_std_set_property(name: &str, write_func_name: Option<&str>) -> bool { if let (Some(f), Some(h)) = (write_func_name, name.chars().next()) { // f == set<Name> f.starts_with("set") && f[3..].starts_with(h.to_ascii_uppercase()) && f[(3 + h.len_utf8())..] == name[h.len_utf8()..] } else { false } } /// Generates variable name candidate for the given type. /// /// The `type_name` should be a valid identifier. `Scoped::Name` is invalid for example. /// /// This follows the convention of `Driver::qtify()` defined in /// `qtbase/src/tools/uic/driver.cpp`, but does not return an empty string unless the given /// `type_name` is empty. pub fn variable_name_for_type<S>(type_name: S) -> String where S: AsRef<str>, { let type_name = type_name.as_ref(); let mut var_name = String::with_capacity(type_name.len()); let mut chars = type_name.chars().fuse(); if type_name.starts_with(['Q', 'K']) && type_name[1..].starts_with(|c: char| c.is_ascii_alphabetic()) { chars.next(); } for c in chars.by_ref() { var_name.push(c.to_ascii_lowercase()); if !c.is_ascii_uppercase() { break; } } var_name.extend(chars); var_name } #[cfg(test)] mod tests { use super::*; #[test] fn std_set_property_name() { assert!(is_std_set_property("std", Some("setStd"))); assert!(!is_std_set_property("std", Some("updateStd"))); assert!(!is_std_set_property("std", None)); assert!(!is_std_set_property("", Some("set"))); } #[test] fn qtified_variable_name() { assert_eq!(variable_name_for_type("QMainWindow"), "mainWindow"); assert_eq!(variable_name_for_type("QVBoxLayout"), "vboxLayout"); assert_eq!(variable_name_for_type("Q"), "q"); assert_eq!(variable_name_for_type("Q3D"), "q3D"); } }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/tir/builder.rs
Rust
use super::ceval; use super::core::{ BasicBlock, BasicBlockRef, CodeBody, Constant, ConstantValue, EnumVariant, Local, LocalRef, NamedObject, Operand, Rvalue, Statement, Terminator, Void, }; use crate::diagnostic::Diagnostics; use crate::opcode::{BinaryArithOp, BinaryLogicalOp, BinaryOp, BuiltinFunctionKind, UnaryOp}; use crate::qmlast::StatementNode; use crate::typedexpr::{ self, DescribeType, ExpressionError, ExpressionVisitor, RefSpace, TypeAnnotationSpace, TypeDesc, }; use crate::typemap::{Class, Enum, MethodMatches, NamedType, Property, TypeKind, TypeMapError}; use crate::typeutil::{self, TypeCastKind, TypeError}; use itertools::Itertools as _; use std::ops::Range; /// Translates AST to type-checked IR. #[derive(Clone, Debug)] struct CodeBuilder<'a> { code: CodeBody<'a>, } impl<'a> CodeBuilder<'a> { fn new() -> Self { CodeBuilder { code: CodeBody::empty(), } } fn alloca(&mut self, ty: TypeKind<'a>, byte_range: Range<usize>) -> Result<Local<'a>, Void> { if ty != TypeKind::VOID { let a = Local::new(self.code.locals.len(), ty, byte_range); self.code.locals.push(a.clone()); Ok(a) } else { Err(Void::new(byte_range)) } } fn current_basic_block_ref(&self) -> BasicBlockRef { assert!(!self.code.basic_blocks.is_empty()); BasicBlockRef(self.code.basic_blocks.len() - 1) } fn current_basic_block_mut(&mut self) -> &mut BasicBlock<'a> { self.code .basic_blocks .last_mut() .expect("at least one basic block must exist") } fn get_basic_block_mut(&mut self, r: BasicBlockRef) -> &mut BasicBlock<'a> { &mut self.code.basic_blocks[r.0] } fn set_completion_value(&mut self, value: Operand<'a>) { self.current_basic_block_mut().set_completion_value(value) } fn push_statement(&mut self, stmt: Statement<'a>) { self.current_basic_block_mut().push_statement(stmt); } fn emit_result( &mut self, ty: TypeKind<'a>, rv: Rvalue<'a>, byte_range: Range<usize>, ) -> Operand<'a> { match self.alloca(ty, byte_range) { Ok(a) => { self.push_statement(Statement::Assign(a.name, rv)); Operand::Local(a) } Err(v) => { self.push_statement(Statement::Exec(rv)); Operand::Void(v) } } } } impl<'a> ExpressionVisitor<'a> for CodeBuilder<'a> { type Item = Operand<'a>; type Local = LocalRef; type Label = BasicBlockRef; fn make_void(&self, byte_range: Range<usize>) -> Self::Item { Operand::Void(Void::new(byte_range)) } fn visit_integer( &mut self, value: u64, byte_range: Range<usize>, ) -> Result<Self::Item, ExpressionError<'a>> { let v = ConstantValue::Integer(value.try_into()?); Ok(Operand::Constant(Constant::new(v, byte_range))) } fn visit_float( &mut self, value: f64, byte_range: Range<usize>, ) -> Result<Self::Item, ExpressionError<'a>> { let v = ConstantValue::Float(value); Ok(Operand::Constant(Constant::new(v, byte_range))) } fn visit_string( &mut self, value: String, byte_range: Range<usize>, ) -> Result<Self::Item, ExpressionError<'a>> { let v = ConstantValue::CString(value); Ok(Operand::Constant(Constant::new(v, byte_range))) } fn visit_bool( &mut self, value: bool, byte_range: Range<usize>, ) -> Result<Self::Item, ExpressionError<'a>> { let v = ConstantValue::Bool(value); Ok(Operand::Constant(Constant::new(v, byte_range))) } fn visit_null(&mut self, byte_range: Range<usize>) -> Result<Self::Item, ExpressionError<'a>> { let v = ConstantValue::NullPointer; Ok(Operand::Constant(Constant::new(v, byte_range))) } fn visit_enum( &mut self, enum_ty: Enum<'a>, variant: &str, byte_range: Range<usize>, ) -> Result<Self::Item, ExpressionError<'a>> { Ok(Operand::EnumVariant(EnumVariant::new( enum_ty, variant, byte_range, ))) } fn visit_array( &mut self, elements: Vec<Self::Item>, byte_range: Range<usize>, ) -> Result<Self::Item, ExpressionError<'a>> { let operands: Vec<_> = elements.into_iter().map(ensure_concrete_string).collect(); if let Some(mut elem_t) = operands.first().map(|a| a.type_desc()) { for (i, a) in operands.iter().enumerate().skip(1) { elem_t = typeutil::deduce_type(elem_t, a.type_desc()).map_err(|e| match e { TypeError::IncompatibleTypes(l, r) => { ExpressionError::IncompatibleArrayElementType(i, l, r) } e => to_operation_type_error("array", e), })?; } let ty = TypeKind::List(Box::new(to_concrete_type("array", elem_t)?)); Ok(self.emit_result(ty.clone(), Rvalue::MakeList(ty, operands), byte_range)) } else { Ok(Operand::Constant(Constant::new( ConstantValue::EmptyList, byte_range, ))) } } fn visit_local_ref(&mut self, name: Self::Local) -> Result<Self::Item, ExpressionError<'a>> { let a = self.code.locals[name.0].clone(); // name must be valid Ok(Operand::Local(a)) } fn visit_local_declaration( &mut self, ty: TypeKind<'a>, byte_range: Range<usize>, ) -> Result<Self::Local, ExpressionError<'a>> { let a = self.alloca(ty, byte_range).map_err(|_| { ExpressionError::OperationOnUnsupportedType( "local declaration".to_owned(), TypeDesc::VOID, ) })?; Ok(a.name) } fn visit_local_assignment( &mut self, name: Self::Local, right: Self::Item, byte_range: Range<usize>, ) -> Result<Self::Item, ExpressionError<'a>> { let ty = &self.code.locals[name.0].ty; // name must be valid let right = ensure_concrete_string(right); if !typeutil::is_assignable(ty, &right.type_desc())? { return Err(ExpressionError::OperationOnIncompatibleTypes( "=".to_owned(), TypeDesc::Concrete(ty.clone()), right.type_desc(), )); } self.push_statement(Statement::Assign(name, Rvalue::Copy(right))); // TODO: or return rvalue?, but property assignment doesn't because it would have // to re-read property Ok(Operand::Void(Void::new(byte_range))) } fn visit_function_parameter( &mut self, ty: TypeKind<'a>, byte_range: Range<usize>, ) -> Result<Self::Local, ExpressionError<'a>> { assert_eq!( self.code.locals.len(), self.code.parameter_count, "function parameters must be declared prior to any local declarations" ); let a = self.alloca(ty, byte_range).map_err(|_| { ExpressionError::OperationOnUnsupportedType( "function parameter".to_owned(), TypeDesc::VOID, ) })?; self.code.parameter_count = self.code.locals.len(); Ok(a.name) } fn visit_object_ref( &mut self, cls: Class<'a>, name: &str, byte_range: Range<usize>, ) -> Result<Self::Item, ExpressionError<'a>> { Ok(Operand::NamedObject(NamedObject::new( name, cls, byte_range, ))) } fn visit_object_property( &mut self, object: Self::Item, property: Property<'a>, byte_range: Range<usize>, ) -> Result<Self::Item, ExpressionError<'a>> { if !property.is_readable() { return Err(ExpressionError::UnreadableProperty); } let object = ensure_concrete_string(object); Ok(self.emit_result( property.value_type().clone(), Rvalue::ReadProperty(object, property), byte_range, )) } fn visit_object_property_assignment( &mut self, object: Self::Item, property: Property<'a>, right: Self::Item, byte_range: Range<usize>, ) -> Result<Self::Item, ExpressionError<'a>> { if !property.is_writable() { return Err(ExpressionError::UnwritableProperty); } let ty = property.value_type(); let object = ensure_concrete_string(object); let right = ensure_concrete_string(right); if !typeutil::is_assignable(ty, &right.type_desc())? { return Err(ExpressionError::OperationOnIncompatibleTypes( "=".to_owned(), TypeDesc::Concrete(ty.clone()), right.type_desc(), )); } // TODO: should we allow chained assignment? // TODO: do we want to break binding? maybe no, but document the behavior difference Ok(self.emit_result( TypeKind::VOID, Rvalue::WriteProperty(object, property, right), byte_range, )) } fn visit_object_subscript( &mut self, object: Self::Item, index: Self::Item, byte_range: Range<usize>, ) -> Result<Self::Item, ExpressionError<'a>> { let elem_ty = check_object_subscript_type(&object, &index)?; Ok(self.emit_result(elem_ty, Rvalue::ReadSubscript(object, index), byte_range)) } fn visit_object_subscript_assignment( &mut self, object: Self::Item, index: Self::Item, right: Self::Item, byte_range: Range<usize>, ) -> Result<Self::Item, ExpressionError<'a>> { let elem_ty = check_object_subscript_type(&object, &index)?; if !typeutil::is_assignable(&elem_ty, &right.type_desc())? { return Err(ExpressionError::OperationOnIncompatibleTypes( "=".to_owned(), TypeDesc::Concrete(elem_ty), right.type_desc(), )); } // TODO: or return rvalue?, but property assignment doesn't because it would have // to re-read property self.push_statement(Statement::Exec(Rvalue::WriteSubscript( object, index, right, ))); Ok(Operand::Void(Void::new(byte_range))) } fn visit_object_method_call( &mut self, object: Self::Item, methods: MethodMatches<'a>, arguments: Vec<Self::Item>, byte_range: Range<usize>, ) -> Result<Self::Item, ExpressionError<'a>> { let object = ensure_concrete_string(object); let arguments: Vec<_> = arguments.into_iter().map(ensure_concrete_string).collect(); let mut matched_index: Option<usize> = None; for (i, m) in methods.iter().enumerate() { if m.arguments_len() == arguments.len() { let compatible: Result<bool, TypeMapError> = m .argument_types() .iter() .zip(&arguments) .try_fold(true, |acc, (ty, v)| { Ok(acc && typeutil::is_assignable(ty, &v.type_desc()).unwrap_or(false)) }); if compatible? { matched_index = Some(i); break; } } } if let Some(i) = matched_index { let m = methods.into_vec().swap_remove(i); Ok(self.emit_result( m.return_type().clone(), Rvalue::CallMethod(object, m, arguments), byte_range, )) } else { let expects = methods .iter() .map(|m| { m.argument_types() .iter() .map(|t| t.qualified_cxx_name().into_owned()) .join(", ") }) .join(") | ("); let actual = arguments .iter() .map(|v| v.type_desc().qualified_name().into_owned()) .join(", "); Err(ExpressionError::InvalidArgument(format!( "expects ({expects}), but got ({actual})" ))) } } fn visit_builtin_call( &mut self, function: BuiltinFunctionKind, arguments: Vec<Self::Item>, byte_range: Range<usize>, ) -> Result<Self::Item, ExpressionError<'a>> { let (ty, arguments) = match function { BuiltinFunctionKind::ConsoleLog(_) => { // Not all types can be sent to QDebug stream, but it's unlikely we would // use such type in QML. Ok((TypeKind::VOID, arguments)) } BuiltinFunctionKind::Max | BuiltinFunctionKind::Min => { if arguments.len() == 2 { let op = if function == BuiltinFunctionKind::Max { "max" } else { "min" }; let arguments: Vec<_> = arguments.into_iter().map(ensure_concrete_string).collect(); let ty = deduce_concrete_type( op, arguments[0].type_desc(), arguments[1].type_desc(), )?; match ty { TypeKind::BOOL | TypeKind::DOUBLE | TypeKind::INT | TypeKind::UINT | TypeKind::STRING => Ok((ty, arguments)), _ => Err(ExpressionError::OperationOnUnsupportedType( op.to_owned(), TypeDesc::Concrete(ty), )), } } else { Err(ExpressionError::InvalidArgument(format!( "expects 2 arguments, but got {}", arguments.len() ))) } } BuiltinFunctionKind::Tr => { if arguments.len() == 1 { match arguments[0].type_desc() { TypeDesc::ConstString => Ok((TypeKind::STRING, arguments)), t => Err(ExpressionError::InvalidArgument(t.qualified_name().into())), } } else { Err(ExpressionError::InvalidArgument(format!( "expects 1 argument, but got {}", arguments.len() ))) } } }?; Ok(self.emit_result( ty, Rvalue::CallBuiltinFunction(function, arguments), byte_range, )) } fn visit_unary_expression( &mut self, unary: UnaryOp, argument: Self::Item, byte_range: Range<usize>, ) -> Result<Self::Item, ExpressionError<'a>> { match argument { Operand::Constant(a) => match unary { UnaryOp::Arith(op) => ceval::eval_unary_arith_expression(op, a.value), UnaryOp::Bitwise(op) => ceval::eval_unary_bitwise_expression(op, a.value), UnaryOp::Logical(op) => ceval::eval_unary_logical_expression(op, a.value), } .map(|v| Operand::Constant(Constant::new(v, byte_range))), argument => self.emit_unary_expression(unary, argument, byte_range), } } fn visit_binary_expression( &mut self, binary: BinaryOp, left: Self::Item, right: Self::Item, byte_range: Range<usize>, ) -> Result<Self::Item, ExpressionError<'a>> { match (left, right) { (Operand::Constant(l), Operand::Constant(r)) => match binary { BinaryOp::Arith(op) => ceval::eval_binary_arith_expression(op, l.value, r.value), BinaryOp::Bitwise(op) => { ceval::eval_binary_bitwise_expression(op, l.value, r.value) } BinaryOp::Shift(op) => ceval::eval_shift_expression(op, l.value, r.value), BinaryOp::Logical(_) => { panic!("visit_binary_logical_expression() should be called") } BinaryOp::Comparison(op) => ceval::eval_comparison_expression(op, l.value, r.value), } .map(|v| Operand::Constant(Constant::new(v, byte_range))), (left, right) => self.emit_binary_expression(binary, left, right, byte_range), } } fn visit_binary_logical_expression( &mut self, op: BinaryLogicalOp, (left, left_ref): (Self::Item, Self::Label), (right, right_ref): (Self::Item, Self::Label), byte_range: Range<usize>, ) -> Self::Item { // no constant evaluation path needed as we know the concrete type of the operands assert_eq!(left.type_desc(), TypeDesc::BOOL); assert_eq!(right.type_desc(), TypeDesc::BOOL); // short circult if left == init_value let (init_value, true_ref, false_ref) = match op { BinaryLogicalOp::And => (false, left_ref.next(), right_ref.next()), // right start, end BinaryLogicalOp::Or => (true, right_ref.next(), left_ref.next()), // end, right start }; let sink = self.alloca(TypeKind::BOOL, byte_range).unwrap(); let block = self.get_basic_block_mut(left_ref); block.push_statement(Statement::Assign( sink.name, Rvalue::Copy(Operand::Constant(Constant::new( ConstantValue::Bool(init_value), left.byte_range(), ))), )); block.finalize(Terminator::BrCond(left, true_ref, false_ref)); let block = self.get_basic_block_mut(right_ref); block.push_statement(Statement::Assign(sink.name, Rvalue::Copy(right))); block.finalize(Terminator::Br(right_ref.next())); // end Operand::Local(sink) } fn visit_as_expression( &mut self, value: Self::Item, ty: TypeKind<'a>, byte_range: Range<usize>, ) -> Result<Self::Item, ExpressionError<'a>> { let value = ensure_concrete_string(value); match typeutil::pick_type_cast(&ty, &value.type_desc())? { TypeCastKind::Noop => Ok(value), TypeCastKind::Implicit => Ok(self.emit_result(ty, Rvalue::Copy(value), byte_range)), TypeCastKind::Static => { Ok(self.emit_result(ty.clone(), Rvalue::StaticCast(ty, value), byte_range)) } TypeCastKind::Variant => { Ok(self.emit_result(ty.clone(), Rvalue::VariantCast(ty, value), byte_range)) } TypeCastKind::Invalid => Err(ExpressionError::OperationOnIncompatibleTypes( "as".to_owned(), value.type_desc(), TypeDesc::Concrete(ty), )), } } fn visit_ternary_expression( &mut self, (condition, condition_ref): (Self::Item, Self::Label), (consequence, consequence_ref): (Self::Item, Self::Label), (alternative, alternative_ref): (Self::Item, Self::Label), byte_range: Range<usize>, ) -> Result<Self::Item, ExpressionError<'a>> { let consequence = ensure_concrete_string(consequence); let alternative = ensure_concrete_string(alternative); let ty = deduce_concrete_type("ternary", consequence.type_desc(), alternative.type_desc())?; let sink = self.alloca(ty, byte_range); self.get_basic_block_mut(condition_ref) .finalize(Terminator::BrCond( condition, condition_ref.next(), // consequence start consequence_ref.next(), // alternative start )); for (src, src_ref) in [ (consequence, consequence_ref), (alternative, alternative_ref), ] { let block = self.get_basic_block_mut(src_ref); if let Ok(a) = &sink { block.push_statement(Statement::Assign(a.name, Rvalue::Copy(src))); } block.finalize(Terminator::Br(alternative_ref.next())); // end } Ok(sink.map(Operand::Local).unwrap_or_else(Operand::Void)) } fn visit_expression_statement(&mut self, value: Self::Item) { self.set_completion_value(ensure_concrete_string(value)); } fn visit_if_statement( &mut self, (condition, condition_ref): (Self::Item, Self::Label), consequence_ref: Self::Label, alternative_ref: Option<Self::Label>, ) { self.get_basic_block_mut(condition_ref) .finalize(Terminator::BrCond( condition, condition_ref.next(), // consequence start consequence_ref.next(), // alternative start or end )); let end_ref = alternative_ref.unwrap_or(consequence_ref).next(); self.get_basic_block_mut(consequence_ref) .finalize(Terminator::Br(end_ref)); if let Some(l) = alternative_ref { self.get_basic_block_mut(l) .finalize(Terminator::Br(end_ref)); } } fn visit_switch_statement( &mut self, case_conditions: Vec<(Self::Item, Self::Label)>, bodies: Vec<Self::Label>, default_pos: Option<usize>, head_ref: Self::Label, exit_ref: Self::Label, ) { // order of blocks: ...|case0|case1|...|exit|body0|body1|...| // ^ default_pos let last_body_ref = bodies.last().copied().unwrap_or(exit_ref); let mut case_body_start_refs = Vec::with_capacity(bodies.len()); case_body_start_refs.push(exit_ref.next()); if let Some((_, heads)) = bodies.split_last() { case_body_start_refs.extend(heads.iter().map(|r| r.next())); } let default_body_start_ref = default_pos.map(|p| case_body_start_refs.remove(p)); // connect case branches assert_eq!(case_conditions.len(), case_body_start_refs.len()); for (i, ((condition, condition_ref), &body_start_ref)) in case_conditions .into_iter() .zip(&case_body_start_refs) .enumerate() { let next_ref = if i + 1 < case_body_start_refs.len() { condition_ref.next() // next condition start } else { default_body_start_ref.unwrap_or_else(|| last_body_ref.next()) // default or end }; self.get_basic_block_mut(condition_ref) .finalize(Terminator::BrCond(condition, body_start_ref, next_ref)); } // connect fall-through paths for &body_ref in &bodies { self.get_basic_block_mut(body_ref) .finalize(Terminator::Br(body_ref.next())); // next body start or end } // connect enter/exit paths self.get_basic_block_mut(head_ref) .finalize(Terminator::Br(exit_ref.next())); // jump over "break" slot self.get_basic_block_mut(exit_ref) .finalize(Terminator::Br(last_body_ref.next())); // end } fn visit_break_statement(&mut self, exit_ref: Self::Label) { self.current_basic_block_mut() .finalize(Terminator::Br(exit_ref)); self.code.basic_blocks.push(BasicBlock::empty()); // unreachable code may be inserted here } fn visit_return_statement(&mut self, value: Self::Item) { let value = ensure_concrete_string(value); self.current_basic_block_mut() .finalize(Terminator::Return(value)); self.code.basic_blocks.push(BasicBlock::empty()); // unreachable code may be inserted here } /// Inserts new basic block for the statements after the branch, returns the reference /// to the old (pre-branch) basic block. /// /// The returned basic block should be finalized by the subsequent `visit_*()` call. fn mark_branch_point(&mut self) -> Self::Label { let old_ref = self.current_basic_block_ref(); self.code.basic_blocks.push(BasicBlock::empty()); old_ref } } impl<'a> CodeBuilder<'a> { fn emit_unary_expression( &mut self, unary: UnaryOp, argument: Operand<'a>, byte_range: Range<usize>, ) -> Result<Operand<'a>, ExpressionError<'a>> { let unsupported = |t| ExpressionError::OperationOnUnsupportedType(unary.to_string(), t); let argument = ensure_concrete_string(argument); match unary { UnaryOp::Arith(_) => { let ty = to_concrete_type(unary, argument.type_desc())?; match &ty { &TypeKind::INT | &TypeKind::UINT | &TypeKind::DOUBLE => Ok(ty), _ => Err(unsupported(TypeDesc::Concrete(ty))), } } UnaryOp::Bitwise(_) => { let ty = to_concrete_type(unary, argument.type_desc())?; match &ty { &TypeKind::INT | &TypeKind::UINT | TypeKind::Just(NamedType::Enum(_)) => Ok(ty), _ => Err(unsupported(TypeDesc::Concrete(ty))), } } UnaryOp::Logical(_) => match argument.type_desc() { TypeDesc::BOOL => Ok(TypeKind::BOOL), t => Err(unsupported(t)), }, } .map(|ty| self.emit_result(ty, Rvalue::UnaryOp(unary, argument), byte_range)) } fn emit_binary_expression( &mut self, binary: BinaryOp, left: Operand<'a>, right: Operand<'a>, byte_range: Range<usize>, ) -> Result<Operand<'a>, ExpressionError<'a>> { let unsupported = |t| ExpressionError::OperationOnUnsupportedType(binary.to_string(), t); let left = ensure_concrete_string(left); let right = ensure_concrete_string(right); match binary { BinaryOp::Arith(op) => { use BinaryArithOp::*; let ty = deduce_concrete_type(op, left.type_desc(), right.type_desc())?; match &ty { &TypeKind::INT | &TypeKind::UINT | &TypeKind::DOUBLE => Ok(ty), &TypeKind::STRING => match op { Add => Ok(ty), Sub | Mul | Div | Rem => Err(unsupported(TypeDesc::Concrete(ty))), }, _ => Err(unsupported(TypeDesc::Concrete(ty))), } } BinaryOp::Bitwise(op) => { let ty = deduce_concrete_type(op, left.type_desc(), right.type_desc())?; match &ty { &TypeKind::BOOL | &TypeKind::INT | &TypeKind::UINT | TypeKind::Just(NamedType::Enum(_)) => Ok(ty), _ => Err(unsupported(TypeDesc::Concrete(ty))), } } BinaryOp::Shift(op) => { let lty = to_concrete_type(op, left.type_desc())?; let rt = right.type_desc(); match (&lty, &rt) { ( &TypeKind::INT | &TypeKind::UINT, TypeDesc::ConstInteger | &TypeDesc::INT | &TypeDesc::UINT, ) => Ok(lty), _ => Err(ExpressionError::OperationOnUnsupportedTypes( op.to_string(), TypeDesc::Concrete(lty), rt, )), } } BinaryOp::Logical(_) => { panic!("visit_binary_logical_expression() should be called") } BinaryOp::Comparison(op) => { let ty = deduce_concrete_type(op, left.type_desc(), right.type_desc())?; match &ty { &TypeKind::BOOL | &TypeKind::INT | &TypeKind::UINT | &TypeKind::DOUBLE | &TypeKind::STRING | TypeKind::Just(NamedType::Enum(_)) | TypeKind::Pointer(_) => Ok(TypeKind::BOOL), _ => Err(unsupported(TypeDesc::Concrete(ty))), } } } .map(|ty| self.emit_result(ty, Rvalue::BinaryOp(binary, left, right), byte_range)) } } fn to_operation_type_error(op_desc: impl ToString, err: TypeError) -> ExpressionError { match err { TypeError::TypeResolution(e) => ExpressionError::TypeResolution(e), TypeError::IncompatibleTypes(l, r) => { ExpressionError::OperationOnIncompatibleTypes(op_desc.to_string(), l, r) } TypeError::UndeterminedType(t) => { ExpressionError::OperationOnUndeterminedType(op_desc.to_string(), t) } } } fn deduce_concrete_type<'a>( op_desc: impl ToString, left: TypeDesc<'a>, right: TypeDesc<'a>, ) -> Result<TypeKind<'a>, ExpressionError<'a>> { typeutil::deduce_concrete_type(left, right).map_err(|e| to_operation_type_error(op_desc, e)) } fn to_concrete_type(op_desc: impl ToString, t: TypeDesc) -> Result<TypeKind, ExpressionError> { typeutil::to_concrete_type(t).map_err(|e| to_operation_type_error(op_desc, e)) } fn ensure_concrete_string(x: Operand) -> Operand { match x { Operand::Constant(Constant { value: ConstantValue::CString(s), byte_range, }) => Operand::Constant(Constant { value: ConstantValue::QString(s), byte_range, }), x => x, } } fn check_object_subscript_type<'a>( object: &Operand<'a>, index: &Operand<'a>, ) -> Result<TypeKind<'a>, ExpressionError<'a>> { let elem_ty = match to_concrete_type("subscript", object.type_desc())? { ty @ (TypeKind::Just(_) | TypeKind::Pointer(_)) => { return Err(ExpressionError::OperationOnUnsupportedType( "subscript".to_owned(), TypeDesc::Concrete(ty), )) } TypeKind::List(ty) => *ty, }; match index.type_desc() { TypeDesc::ConstInteger | TypeDesc::INT | TypeDesc::UINT => {} t => return Err(ExpressionError::IncompatibleIndexType(t)), }; Ok(elem_ty) } /// Translates expression AST nodes into type-checked IR. pub fn build<'a, C>( ctx: &C, node: StatementNode, source: &str, diagnostics: &mut Diagnostics, ) -> Option<CodeBody<'a>> where C: RefSpace<'a> + TypeAnnotationSpace<'a>, { let mut builder = CodeBuilder::new(); typedexpr::walk(ctx, node, source, &mut builder, diagnostics)?; let current_ref = builder.current_basic_block_ref(); builder .code .finalize_completion_values(current_ref, node.byte_range()); Some(builder.code) } /// Translates callback AST nodes into type-checked IR. /// /// If the top-level node is a function, a callback body having the specified function /// parameters will be built. Otherwise this function is identical to `build()`. pub fn build_callback<'a, C>( ctx: &C, node: StatementNode, source: &str, diagnostics: &mut Diagnostics, ) -> Option<CodeBody<'a>> where C: RefSpace<'a> + TypeAnnotationSpace<'a>, { let mut builder = CodeBuilder::new(); typedexpr::walk_callback(ctx, node, source, &mut builder, diagnostics)?; let current_ref = builder.current_basic_block_ref(); builder .code .finalize_completion_values(current_ref, node.byte_range()); Some(builder.code) }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/tir/ceval.rs
Rust
//! Utility to evaluate constant expression. //! //! This is not for optimization. We don't want to allocate local variable without //! concrete integer/string type. And we do want to concatenate string literals to //! support translation. use super::core::ConstantValue; use crate::opcode::{ BinaryArithOp, BinaryBitwiseOp, ComparisonOp, ShiftOp, UnaryArithOp, UnaryBitwiseOp, UnaryLogicalOp, }; use crate::typedexpr::{DescribeType, ExpressionError}; pub(super) fn eval_unary_arith_expression( op: UnaryArithOp, argument: ConstantValue, ) -> Result<ConstantValue, ExpressionError<'static>> { use UnaryArithOp::*; match argument { ConstantValue::Integer(v) => { let a = match op { Plus => Some(v), Minus => v.checked_neg(), }; a.map(ConstantValue::Integer) .ok_or(ExpressionError::IntegerOverflow) } ConstantValue::Float(v) => { let a = match op { Plus => v, Minus => -v, }; Ok(ConstantValue::Float(a)) } ConstantValue::Bool(_) | ConstantValue::CString(_) | ConstantValue::QString(_) | ConstantValue::NullPointer | ConstantValue::EmptyList => Err(ExpressionError::OperationOnUnsupportedType( op.to_string(), argument.type_desc(), )), } } pub(super) fn eval_unary_bitwise_expression( op: UnaryBitwiseOp, argument: ConstantValue, ) -> Result<ConstantValue, ExpressionError<'static>> { use UnaryBitwiseOp::*; match argument { ConstantValue::Integer(v) => { let a = match op { Not => !v, }; Ok(ConstantValue::Integer(a)) } ConstantValue::Bool(_) | ConstantValue::Float(_) | ConstantValue::CString(_) | ConstantValue::QString(_) | ConstantValue::NullPointer | ConstantValue::EmptyList => Err(ExpressionError::OperationOnUnsupportedType( op.to_string(), argument.type_desc(), )), } } pub(super) fn eval_unary_logical_expression( op: UnaryLogicalOp, argument: ConstantValue, ) -> Result<ConstantValue, ExpressionError<'static>> { use UnaryLogicalOp::*; match argument { ConstantValue::Bool(v) => { let a = match op { Not => !v, }; Ok(ConstantValue::Bool(a)) } ConstantValue::Integer(_) | ConstantValue::Float(_) | ConstantValue::CString(_) | ConstantValue::QString(_) | ConstantValue::NullPointer | ConstantValue::EmptyList => Err(ExpressionError::OperationOnUnsupportedType( op.to_string(), argument.type_desc(), )), } } pub(super) fn eval_binary_arith_expression( op: BinaryArithOp, left: ConstantValue, right: ConstantValue, ) -> Result<ConstantValue, ExpressionError<'static>> { use BinaryArithOp::*; match (left, right) { (left @ ConstantValue::Bool(_), ConstantValue::Bool(_)) => Err( ExpressionError::OperationOnUnsupportedType(op.to_string(), left.type_desc()), ), (ConstantValue::Integer(l), ConstantValue::Integer(r)) => { let a = match op { Add => i64::checked_add(l, r), Sub => i64::checked_sub(l, r), Mul => i64::checked_mul(l, r), Div => i64::checked_div(l, r), Rem => i64::checked_rem(l, r), }; a.map(ConstantValue::Integer) .ok_or(ExpressionError::IntegerOverflow) } (ConstantValue::Float(l), ConstantValue::Float(r)) => { let a = match op { Add => l + r, Sub => l - r, Mul => l * r, Div => l / r, Rem => l % r, }; Ok(ConstantValue::Float(a)) } (ConstantValue::CString(l), ConstantValue::CString(r)) => match op { Add => Ok(ConstantValue::CString(l + &r)), Sub | Mul | Div | Rem => Err(ExpressionError::OperationOnUnsupportedType( op.to_string(), ConstantValue::CString(l).type_desc(), )), }, (left @ ConstantValue::QString(_), ConstantValue::QString(_)) => Err( ExpressionError::OperationOnUnsupportedType(op.to_string(), left.type_desc()), ), (left, right) => Err(ExpressionError::OperationOnIncompatibleTypes( op.to_string(), left.type_desc(), right.type_desc(), )), } } pub(super) fn eval_binary_bitwise_expression( op: BinaryBitwiseOp, left: ConstantValue, right: ConstantValue, ) -> Result<ConstantValue, ExpressionError<'static>> { use BinaryBitwiseOp::*; match (left, right) { (ConstantValue::Bool(l), ConstantValue::Bool(r)) => { let a = match op { And => l & r, Xor => l ^ r, Or => l | r, }; Ok(ConstantValue::Bool(a)) } (ConstantValue::Integer(l), ConstantValue::Integer(r)) => { let a = match op { And => l & r, Xor => l ^ r, Or => l | r, }; Ok(ConstantValue::Integer(a)) } (left @ ConstantValue::Float(_), ConstantValue::Float(_)) | (left @ ConstantValue::CString(_), ConstantValue::CString(_)) | (left @ ConstantValue::QString(_), ConstantValue::QString(_)) => Err( ExpressionError::OperationOnUnsupportedType(op.to_string(), left.type_desc()), ), (left, right) => Err(ExpressionError::OperationOnIncompatibleTypes( op.to_string(), left.type_desc(), right.type_desc(), )), } } pub(super) fn eval_shift_expression( op: ShiftOp, left: ConstantValue, right: ConstantValue, ) -> Result<ConstantValue, ExpressionError<'static>> { use ShiftOp::*; match (left, right) { (ConstantValue::Integer(l), ConstantValue::Integer(r)) => { let a = match op { RightShift => l.checked_shr(r.try_into()?), LeftShift => l.checked_shl(r.try_into()?), }; a.map(ConstantValue::Integer) .ok_or(ExpressionError::IntegerOverflow) } (left, right) => Err(ExpressionError::OperationOnUnsupportedTypes( op.to_string(), left.type_desc(), right.type_desc(), )), } } pub(super) fn eval_comparison_expression( op: ComparisonOp, left: ConstantValue, right: ConstantValue, ) -> Result<ConstantValue, ExpressionError<'static>> { macro_rules! compare { ($left:expr, $right:expr) => {{ let a = match op { ComparisonOp::Equal => $left == $right, ComparisonOp::NotEqual => $left != $right, ComparisonOp::LessThan => $left < $right, ComparisonOp::LessThanEqual => $left <= $right, ComparisonOp::GreaterThan => $left > $right, ComparisonOp::GreaterThanEqual => $left >= $right, }; Ok(ConstantValue::Bool(a)) }}; } match (left, right) { (ConstantValue::Bool(l), ConstantValue::Bool(r)) => compare!(l, r), (ConstantValue::Integer(l), ConstantValue::Integer(r)) => compare!(l, r), (ConstantValue::Float(l), ConstantValue::Float(r)) => compare!(l, r), (ConstantValue::CString(l), ConstantValue::CString(r)) | (ConstantValue::QString(l), ConstantValue::QString(r)) => compare!(l, r), (ConstantValue::NullPointer, ConstantValue::NullPointer) => compare!((), ()), (left, right) => Err(ExpressionError::OperationOnIncompatibleTypes( op.to_string(), left.type_desc(), right.type_desc(), )), } }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/tir/core.rs
Rust
//! Type-checked intermediate representation of expressions. use crate::diagnostic::{Diagnostic, Diagnostics}; use crate::opcode::{BinaryOp, BuiltinFunctionKind, UnaryOp}; use crate::typedexpr::{DescribeType, TypeDesc}; use crate::typemap::{Class, Enum, Method, NamedType, Property, TypeKind}; use crate::typeutil::{self, TypeError}; use std::mem; use std::ops::Range; /// Container of type-checked IR code. #[derive(Clone, Debug)] pub struct CodeBody<'a> { pub basic_blocks: Vec<BasicBlock<'a>>, pub locals: Vec<Local<'a>>, /// Number of local variables which should be provided as arguments by caller. pub parameter_count: usize, /// List of static object/property dependencies, which will be collected by /// `analyze_code_property_dependency()`. pub static_property_deps: Vec<(NamedObjectRef, Method<'a>)>, pub property_observer_count: usize, } impl<'a> CodeBody<'a> { pub(super) fn empty() -> Self { CodeBody { basic_blocks: vec![BasicBlock::empty()], locals: vec![], parameter_count: 0, static_property_deps: vec![], property_observer_count: 0, } } /// Resolves return type of this code. pub fn resolve_return_type(&self, diagnostics: &mut Diagnostics) -> Option<TypeDesc<'a>> { let operands: Vec<_> = self .basic_blocks .iter() .filter_map(|b| { if let Terminator::Return(a) = b.terminator() { Some(a) } else { None } }) .collect(); if let Some(first) = operands.first() { let mut known = first.type_desc(); for a in operands.iter().skip(1) { known = match typeutil::deduce_type(known, a.type_desc()) { Ok(t) => t, Err(TypeError::IncompatibleTypes(l, r)) => { let mut diag = Diagnostic::error( a.byte_range(), format!( "cannot deduce return type from '{}' and '{}'", l.qualified_name(), r.qualified_name() ), ); typeutil::diagnose_incompatible_types( &mut diag, first.byte_range(), &l, a.byte_range(), &r, ); diagnostics.push(diag); return None; } Err(e) => { diagnostics.push(Diagnostic::error(a.byte_range(), e.to_string())); return None; } }; } Some(known) } else { // If there were no return terminator, the code would never return (e.g. infinite // loop if we'd supported loop statement.) Let's pick void in that case since we // have no "never" type. Some(TypeDesc::VOID) } } /// Patches up terminators from the specified block so that the completion values /// will be returned. pub(super) fn finalize_completion_values( &mut self, start_ref: BasicBlockRef, byte_range: Range<usize>, ) { let start_block = &mut self.basic_blocks[start_ref.0]; assert!(start_block.terminator.is_none()); if let Some(a) = start_block.completion_value.take() { // common fast path: no need to build reverse "br" map start_block.terminator = Some(Terminator::Return(a)); return; } // build reverse "br" map: conditional branches aren't collected since they // cannot be turned into "return", and a condition value isn't considered // a completion value. let mut incoming_map = vec![vec![]; self.basic_blocks.len()]; let mut reachable = vec![false; self.basic_blocks.len()]; reachable[0] = true; for (i, b) in self.basic_blocks.iter().enumerate() { match &b.terminator { Some(Terminator::Br(l)) => incoming_map[l.0].push(i), Some(Terminator::BrCond(_, a, b)) => { reachable[a.0] = true; reachable[b.0] = true; } Some(Terminator::Return(_) | Terminator::Unreachable) | None => {} } } // turn "br" into "return" while distance from the start_ref block is 0, where // distance = completion_value + statements.len() let mut to_visit = vec![start_ref.0]; while let Some(i) = to_visit.pop() { let b = &mut self.basic_blocks[i]; assert!(matches!(b.terminator, Some(Terminator::Br(_)) | None)); if let Some(a) = b.completion_value.take() { b.terminator = Some(Terminator::Return(a)); } else { b.terminator = if reachable[i] { let end = byte_range.end; // implicit return should be at end Some(Terminator::Return(Operand::Void(Void::new(end..end)))) } else { Some(Terminator::Unreachable) }; if b.statements.is_empty() { to_visit.extend(mem::take(&mut incoming_map[i])); } } } } pub(super) fn alloc_property_observer(&mut self) -> PropertyObserverRef { let n = self.property_observer_count; self.property_observer_count += 1; PropertyObserverRef(n) } } /// List of statements to be run sequentially. #[derive(Clone, Debug, PartialEq)] pub struct BasicBlock<'a> { pub statements: Vec<Statement<'a>>, completion_value: Option<Operand<'a>>, terminator: Option<Terminator<'a>>, } impl<'a> BasicBlock<'a> { pub(super) fn empty() -> Self { BasicBlock { statements: Vec::new(), completion_value: None, terminator: None, } } pub fn terminator(&self) -> &Terminator<'a> { self.terminator .as_ref() .expect("terminator must have been set by builder") } pub(super) fn set_completion_value(&mut self, value: Operand<'a>) { assert!(self.terminator.is_none()); self.completion_value = Some(value); } pub(super) fn push_statement(&mut self, stmt: Statement<'a>) { assert!(self.terminator.is_none()); self.statements.push(stmt); } pub(super) fn finalize(&mut self, term: Terminator<'a>) { assert!(self.terminator.is_none()); self.terminator = Some(term); } } /// Basic block index. #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct BasicBlockRef(pub usize); impl BasicBlockRef { pub(super) fn next(&self) -> Self { BasicBlockRef(self.0 + 1) } } /// Variant for statements. #[derive(Clone, Debug, PartialEq)] pub enum Statement<'a> { /// `<local> = <rvalue>` Assign(LocalRef, Rvalue<'a>), /// `<rvalue>` Exec(Rvalue<'a>), /// `disconnect(<observer>); <observer> = connect(<local>, <signal>...)` ObserveProperty(PropertyObserverRef, LocalRef, Method<'a>), } /// Last instruction to exit from `BasicBlock`. #[derive(Clone, Debug, PartialEq)] pub enum Terminator<'a> { /// `goto <block>` Br(BasicBlockRef), /// `goto (<cond> ? <block1> : <block2>)` BrCond(Operand<'a>, BasicBlockRef, BasicBlockRef), /// `return <operand>` Return(Operand<'a>), /// `unreachable()` Unreachable, } /// Variable or constant value. #[derive(Clone, Debug, PartialEq)] pub enum Operand<'a> { Constant(Constant), EnumVariant(EnumVariant<'a>), Local(Local<'a>), NamedObject(NamedObject<'a>), Void(Void), } impl Operand<'_> { /// Source code location of the expression that this operand represents. pub fn byte_range(&self) -> Range<usize> { match self { Operand::Constant(x) => x.byte_range.clone(), Operand::EnumVariant(x) => x.byte_range.clone(), Operand::Local(x) => x.byte_range.clone(), Operand::NamedObject(x) => x.byte_range.clone(), Operand::Void(x) => x.byte_range.clone(), } } } impl<'a> DescribeType<'a> for Operand<'a> { fn type_desc(&self) -> TypeDesc<'a> { match self { Operand::Constant(x) => x.value.type_desc(), Operand::EnumVariant(x) => { TypeDesc::Concrete(TypeKind::Just(NamedType::Enum(x.ty.clone()))) } Operand::Local(x) => TypeDesc::Concrete(x.ty.clone()), Operand::NamedObject(x) => { TypeDesc::Concrete(TypeKind::Pointer(NamedType::Class(x.cls.clone()))) } Operand::Void(_) => TypeDesc::VOID, } } } /// Constant value which concrete type might not be determined yet. #[derive(Clone, Debug, PartialEq)] pub struct Constant { pub value: ConstantValue, pub byte_range: Range<usize>, } impl Constant { pub(super) fn new(value: ConstantValue, byte_range: Range<usize>) -> Self { Constant { value, byte_range } } } /// Variant for constant values. #[derive(Clone, Debug, PartialEq)] pub enum ConstantValue { Bool(bool), Integer(i64), Float(f64), /// Default string literal. CString(String), /// `QStringLiteral("")` QString(String), /// `nullptr` NullPointer, /// Empty list which element type is unknown. EmptyList, } impl DescribeType<'static> for ConstantValue { fn type_desc(&self) -> TypeDesc<'static> { match self { ConstantValue::Bool(_) => TypeDesc::BOOL, ConstantValue::Integer(_) => TypeDesc::ConstInteger, ConstantValue::Float(_) => TypeDesc::DOUBLE, ConstantValue::CString(_) => TypeDesc::ConstString, ConstantValue::QString(_) => TypeDesc::STRING, ConstantValue::NullPointer => TypeDesc::NullPointer, ConstantValue::EmptyList => TypeDesc::EmptyList, } } } /// Enum variant. /// /// An enum variant is a constant, but the exact value is unknown. #[derive(Clone, Debug, Eq, PartialEq)] pub struct EnumVariant<'a> { pub ty: Enum<'a>, pub variant: String, pub byte_range: Range<usize>, } impl<'a> EnumVariant<'a> { pub(super) fn new(ty: Enum<'a>, variant: impl Into<String>, byte_range: Range<usize>) -> Self { EnumVariant { ty, variant: variant.into(), byte_range, } } pub fn cxx_expression(&self) -> String { self.ty.qualify_cxx_variant_name(&self.variant) } } /// Local (auto) variable with type information. #[derive(Clone, Debug, Eq, PartialEq)] pub struct Local<'a> { pub name: LocalRef, pub ty: TypeKind<'a>, /// Source code location of the value expression that this variable holds. pub byte_range: Range<usize>, } impl<'a> Local<'a> { pub(super) fn new(name: usize, ty: TypeKind<'a>, byte_range: Range<usize>) -> Self { assert!(ty != TypeKind::VOID); Local { name: LocalRef(name), ty, byte_range, } } } /// Local (auto) variable index. #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct LocalRef(pub usize); /// Member object with type information. #[derive(Clone, Debug, Eq, PartialEq)] pub struct NamedObject<'a> { pub name: NamedObjectRef, pub cls: Class<'a>, pub byte_range: Range<usize>, } impl<'a> NamedObject<'a> { pub(super) fn new(name: impl Into<String>, cls: Class<'a>, byte_range: Range<usize>) -> Self { NamedObject { name: NamedObjectRef(name.into()), cls, byte_range, } } } /// Member object name. #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct NamedObjectRef(pub String); /// Placeholder representing void expression. /// /// Since void expression cannot be assigned to lvalue, the type of [`Local`](Local) /// shouldn't be [`void`](TypeKind::VOID). Use `Void` instead. #[derive(Clone, Debug, Eq, PartialEq)] pub struct Void { /// Source code location of the holding void expression. pub byte_range: Range<usize>, } impl Void { pub(super) fn new(byte_range: Range<usize>) -> Self { Void { byte_range } } } /// Index of dynamic object property observer. #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct PropertyObserverRef(pub usize); /// Variant for rvalue expressions. #[derive(Clone, Debug, PartialEq)] pub enum Rvalue<'a> { Copy(Operand<'a>), /// `<op> <arg>` UnaryOp(UnaryOp, Operand<'a>), /// `<left> <op> <right>` BinaryOp(BinaryOp, Operand<'a>, Operand<'a>), /// `static_cast<ty>(<arg>)` StaticCast(TypeKind<'a>, Operand<'a>), /// `<arg>.value<T>()` VariantCast(TypeKind<'a>, Operand<'a>), /// `<function>(<args>)` CallBuiltinFunction(BuiltinFunctionKind, Vec<Operand<'a>>), /// `<obj> -> <method>(<args>)` CallMethod(Operand<'a>, Method<'a>, Vec<Operand<'a>>), /// `<obj> -> <read_property>()` ReadProperty(Operand<'a>, Property<'a>), /// `<obj> -> <write_property>(<right>)` WriteProperty(Operand<'a>, Property<'a>, Operand<'a>), /// `<obj>[<index>]` ReadSubscript(Operand<'a>, Operand<'a>), /// `<obj>[<index>] = <right>` WriteSubscript(Operand<'a>, Operand<'a>, Operand<'a>), /// `<ty>{<0>, <1>, ...}` MakeList(TypeKind<'a>, Vec<Operand<'a>>), }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/tir/dump.rs
Rust
use super::core::{ BasicBlock, CodeBody, ConstantValue, Local, NamedObjectRef, Operand, Rvalue, Statement, Terminator, }; use crate::typedexpr::DescribeType; use crate::typemap::Method; use itertools::Itertools as _; use std::io; /// Prints `CodeBody` in human-readable format. pub fn dump_code_body<W: io::Write>(w: &mut W, code: &CodeBody) -> io::Result<()> { dump_locals(w, &code.locals)?; for (i, b) in code.basic_blocks.iter().enumerate() { writeln!(w, ".{}:", i)?; dump_basic_block(w, b)?; } if !code.static_property_deps.is_empty() { writeln!(w, "static_property_deps:")?; dump_static_property_deps(w, &code.static_property_deps)?; } Ok(()) } fn dump_locals<W: io::Write>(w: &mut W, locals: &[Local]) -> io::Result<()> { for a in locals { writeln!(w, " %{}: {}", a.name.0, a.ty.qualified_cxx_name())?; } Ok(()) } fn dump_static_property_deps<W: io::Write>( w: &mut W, deps: &[(NamedObjectRef, Method)], ) -> io::Result<()> { for (n, signal) in deps { writeln!(w, " [{}], {:?}", n.0, signal.name())?; } Ok(()) } fn dump_basic_block<W: io::Write>(w: &mut W, block: &BasicBlock) -> io::Result<()> { for s in &block.statements { dump_statement(w, s)?; } match block.terminator() { Terminator::Br(x) => writeln!(w, " br .{}", x.0), Terminator::BrCond(x, y, z) => { writeln!(w, " br_cond {}, .{}, .{}", format_operand(x), y.0, z.0) } Terminator::Return(x) => writeln!(w, " return {}", format_operand(x)), Terminator::Unreachable => writeln!(w, " unreachable"), } } fn dump_statement<W: io::Write>(w: &mut W, stmt: &Statement) -> io::Result<()> { match stmt { Statement::Assign(l, r) => writeln!(w, " %{} = {}", l.0, format_rvalue(r)), Statement::Exec(r) => writeln!(w, " {}", format_rvalue(r)), Statement::ObserveProperty(h, l, signal) => writeln!( w, " ^{} = observe_property %{}, {:?}", h.0, l.0, signal.name() ), } } fn format_rvalue(rv: &Rvalue) -> String { match rv { Rvalue::Copy(a) => format!("copy {}", format_operand(a)), Rvalue::UnaryOp(op, a) => format!("unary_op '{}', {}", op, format_operand(a)), Rvalue::BinaryOp(op, l, r) => format!( "binary_op '{}', {}, {}", op, format_operand(l), format_operand(r) ), Rvalue::StaticCast(ty, a) => format!( "static_cast '{}', {}", ty.qualified_cxx_name(), format_operand(a) ), Rvalue::VariantCast(ty, a) => format!( "variant_cast '{}', {}", ty.qualified_cxx_name(), format_operand(a) ), Rvalue::CallBuiltinFunction(f, args) => { format!( "call_builtin_function {:?}, {{{}}}", f, args.iter().map(format_operand).join(", ") ) } Rvalue::CallMethod(obj, meth, args) => { format!( "call_method {}, {:?}, {{{}}}", format_operand(obj), meth.name(), args.iter().map(format_operand).join(", ") ) } Rvalue::ReadProperty(obj, prop) => { format!("read_property {}, {:?}", format_operand(obj), prop.name()) } Rvalue::WriteProperty(obj, prop, r) => { format!( "write_property {}, {:?}, {}", format_operand(obj), prop.name(), format_operand(r) ) } Rvalue::ReadSubscript(obj, index) => { format!( "read_subscript {}, {}", format_operand(obj), format_operand(index), ) } Rvalue::WriteSubscript(obj, index, r) => { format!( "write_subscript {}, {}, {}", format_operand(obj), format_operand(index), format_operand(r), ) } Rvalue::MakeList(ty, xs) => { format!( "make_list '{}', {{{}}}", ty.qualified_cxx_name(), xs.iter().map(format_operand).join(", "), ) } } } fn format_operand(a: &Operand) -> String { match a { Operand::Constant(x) => match &x.value { ConstantValue::Bool(v) => format!("{:?}: {}", v, a.type_desc().qualified_name()), ConstantValue::Integer(v) => format!("{:?}: {}", v, a.type_desc().qualified_name()), ConstantValue::Float(v) => format!("{:?}: {}", v, a.type_desc().qualified_name()), ConstantValue::CString(v) => format!("{:?}: {}", v, a.type_desc().qualified_name()), ConstantValue::QString(v) => format!("{:?}: {}", v, a.type_desc().qualified_name()), ConstantValue::NullPointer => format!("nullptr: {}", a.type_desc().qualified_name()), ConstantValue::EmptyList => format!("{{}}: {}", a.type_desc().qualified_name()), }, Operand::EnumVariant(x) => format!( "'{}': {}", x.cxx_expression(), a.type_desc().qualified_name() ), Operand::Local(x) => format!("%{}: {}", x.name.0, a.type_desc().qualified_name()), Operand::NamedObject(x) => format!("[{}]: {}", x.name.0, a.type_desc().qualified_name()), Operand::Void(_) => format!("_: {}", a.type_desc().qualified_name()), } }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/tir/interpret.rs
Rust
//! Minimal TIR interpreter designed for .ui generation pass. use super::{BasicBlockRef, CodeBody, ConstantValue, Operand, Rvalue, Statement, Terminator}; use crate::opcode::{BinaryBitwiseOp, BinaryOp, BuiltinFunctionKind}; use crate::typemap::TypeSpace; #[derive(Clone, Debug, PartialEq)] pub enum EvaluatedValue { Bool(bool), Integer(i64), Float(f64), String(String, StringKind), StringList(Vec<(String, StringKind)>), EnumSet(Vec<String>), ObjectRef(String), ObjectRefList(Vec<String>), EmptyList, } /// Marker of bare or translatable string. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum StringKind { /// Bare string. NoTr, /// String wrapped with `qsTr()`. Tr, } impl EvaluatedValue { pub fn unwrap_integer(self) -> i64 { match self { EvaluatedValue::Integer(d) => d, _ => panic!("evaluated value must be integer"), } } pub fn unwrap_string(self) -> (String, StringKind) { match self { EvaluatedValue::String(s, k) => (s, k), _ => panic!("evaluated value must be string"), } } pub fn unwrap_string_list(self) -> Vec<(String, StringKind)> { match self { EvaluatedValue::StringList(xs) => xs, EvaluatedValue::EmptyList => vec![], _ => panic!("evaluated value must be string list"), } } pub fn unwrap_enum_set(self) -> Vec<String> { match self { EvaluatedValue::EnumSet(es) => es, _ => panic!("evaluated value must be enum set"), } } pub fn unwrap_object_ref(self) -> String { match self { EvaluatedValue::ObjectRef(s) => s, _ => panic!("evaluated value must be object ref"), } } pub fn into_object_ref_list(self) -> Option<Vec<String>> { match self { EvaluatedValue::ObjectRefList(ss) => Some(ss), EvaluatedValue::EmptyList => Some(vec![]), _ => None, } } } /// Evaluates TIR code to constant value. pub fn evaluate_code(code: &CodeBody) -> Option<EvaluatedValue> { // fast path for simple constant expression if let Terminator::Return(a @ Operand::Constant(_)) = code.basic_blocks[0].terminator() { return to_evaluated_value(&[], a, StringKind::NoTr); } let mut visited_blocks = vec![false; code.basic_blocks.len()]; let mut visit_block = |r: BasicBlockRef| { if visited_blocks[r.0] { None // prevent infinite loop } else { visited_blocks[r.0] = true; Some(&code.basic_blocks[r.0]) } }; let mut block = visit_block(BasicBlockRef(0))?; let mut locals: Vec<Option<EvaluatedValue>> = vec![None; code.locals.len()]; loop { for stmt in &block.statements { match stmt { Statement::Assign(l, r) => { locals[l.0] = match r { Rvalue::Copy(a) => to_evaluated_value(&locals, a, StringKind::NoTr), Rvalue::BinaryOp(BinaryOp::Bitwise(BinaryBitwiseOp::Or), l, r) => { to_evaluated_enum_set(&locals, l, r) } Rvalue::CallBuiltinFunction(BuiltinFunctionKind::Tr, args) => { to_evaluated_value(&locals, &args[0], StringKind::Tr) } Rvalue::CallMethod(Operand::NamedObject(x), meth, _) if meth.object_class().name() == "QMenu" && meth.name() == "menuAction" && meth.arguments_len() == 0 && meth.return_type_name() == "QAction*" => { // TODO: better check for applicability of static evaluation // translate menu.menuAction() to <addaction name="menu"/> Some(EvaluatedValue::ObjectRef(x.name.0.clone())) } Rvalue::MakeList(_, args) => to_evaluated_list(&locals, args), // No need to support other operations since constants are evaluated // by TIR builder. _ => return None, } } Statement::Exec(_) => {} // uninteresting as a constant expression Statement::ObserveProperty(..) => {} } } match block.terminator() { Terminator::Br(r) => block = visit_block(*r)?, Terminator::BrCond(..) => return None, // unsupported Terminator::Return(a) => return to_evaluated_value(&locals, a, StringKind::NoTr), Terminator::Unreachable => unreachable!(), } } } fn to_evaluated_value( locals: &[Option<EvaluatedValue>], a: &Operand, k: StringKind, ) -> Option<EvaluatedValue> { match a { Operand::Constant(x) => match &x.value { ConstantValue::Bool(v) => Some(EvaluatedValue::Bool(*v)), ConstantValue::Integer(v) => Some(EvaluatedValue::Integer(*v)), ConstantValue::Float(v) => Some(EvaluatedValue::Float(*v)), ConstantValue::CString(v) => Some(EvaluatedValue::String(v.clone(), k)), ConstantValue::QString(v) => Some(EvaluatedValue::String(v.clone(), k)), ConstantValue::NullPointer => None, ConstantValue::EmptyList => Some(EvaluatedValue::EmptyList), }, Operand::EnumVariant(x) => Some(EvaluatedValue::EnumSet(vec![x.cxx_expression()])), Operand::Local(x) => locals[x.name.0].clone(), Operand::NamedObject(x) => Some(EvaluatedValue::ObjectRef(x.name.0.clone())), Operand::Void(_) => None, } } fn to_evaluated_list( locals: &[Option<EvaluatedValue>], args: &[Operand], ) -> Option<EvaluatedValue> { let mut item_iter = args .iter() .map(|a| to_evaluated_value(locals, a, StringKind::NoTr)) .peekable(); match item_iter.peek() { Some(Some(EvaluatedValue::String(..))) => { let ss = item_iter .map(|v| { if let Some(EvaluatedValue::String(s, k)) = v { Some((s, k)) } else { None } }) .collect::<Option<Vec<_>>>()?; Some(EvaluatedValue::StringList(ss)) } Some(Some(EvaluatedValue::ObjectRef(..))) => { let ss = item_iter .map(|v| { if let Some(EvaluatedValue::ObjectRef(s)) = v { Some(s) } else { None } }) .collect::<Option<Vec<_>>>()?; Some(EvaluatedValue::ObjectRefList(ss)) } _ => None, } } fn to_evaluated_enum_set( locals: &[Option<EvaluatedValue>], left: &Operand, right: &Operand, ) -> Option<EvaluatedValue> { match ( to_evaluated_value(locals, left, StringKind::NoTr)?, to_evaluated_value(locals, right, StringKind::NoTr)?, ) { (EvaluatedValue::EnumSet(mut ls), EvaluatedValue::EnumSet(rs)) => { ls.extend(rs); Some(EvaluatedValue::EnumSet(ls)) } _ => None, } }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/tir/mod.rs
Rust
//! Type-checked intermediate representation of expressions. // FIXME: Result<_, ExpressionError>: the `Err`-variant returned from this // function is very large #![allow(clippy::result_large_err)] mod builder; mod ceval; mod core; mod dump; pub mod interpret; mod propdep; pub use self::builder::{build, build_callback}; // re-export pub use self::core::*; // re-export pub use self::dump::dump_code_body; // re-export pub use self::interpret::evaluate_code; // re-export pub use self::propdep::analyze_code_property_dependency; // re-export
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/tir/propdep.rs
Rust
use super::core::{CodeBody, NamedObjectRef, Operand, Rvalue, Statement}; use crate::diagnostic::{Diagnostic, Diagnostics}; use crate::typedexpr::DescribeType as _; /// Analyzes TIR code to collect object/property dependencies and insert observe statements. pub fn analyze_code_property_dependency(code: &mut CodeBody<'_>, diagnostics: &mut Diagnostics) { for i in 0..code.basic_blocks.len() { analyze_block(code, i, diagnostics); } } fn analyze_block(code: &mut CodeBody<'_>, block_index: usize, diagnostics: &mut Diagnostics) { // if a variable comes in from another basic block, simply take it as dynamic let mut locals: Vec<Option<&NamedObjectRef>> = vec![None; code.locals.len()]; let block = &code.basic_blocks[block_index]; let mut to_observe = Vec::new(); for (line, stmt) in block.statements.iter().enumerate() { match stmt { Statement::Assign(_, r) | Statement::Exec(r) => match r { Rvalue::ReadProperty(a, prop) if a.type_desc().is_pointer() && !prop.is_constant() => { match prop.notify_signal().transpose() { Ok(Some(signal)) => match a { Operand::NamedObject(x) => { code.static_property_deps.push((x.name.clone(), signal)); } Operand::Local(x) => { if let Some(n) = locals[x.name.0] { code.static_property_deps.push((n.clone(), signal)); } else { // could be deduplicated by (local, generation, signal) if needed to_observe.push((line, x.name, signal)); } } Operand::Constant(_) | Operand::EnumVariant(_) | Operand::Void(_) => { panic!("invald read_property: {r:?}"); } }, Ok(None) => diagnostics.push(Diagnostic::error( a.byte_range(), format!("unobservable property: {}", prop.name()), )), Err(e) => diagnostics.push(Diagnostic::error( a.byte_range(), format!("type resolution failed: {e}"), )), } } _ => {} }, Statement::ObserveProperty(..) => {} } // update locals *after* inspecting rvalue match stmt { Statement::Assign(l, r) => { locals[l.0] = match r { // track object reference Rvalue::Copy(a) => match a { Operand::Local(x) => locals[x.name.0], Operand::NamedObject(x) => Some(&x.name), Operand::Constant(_) | Operand::EnumVariant(_) | Operand::Void(_) => None, }, // otherwise reset to unknown state _ => None, }; } Statement::Exec(_) | Statement::ObserveProperty(..) => {} } } // allocate observers in order (just for code readability) let mut observers = Vec::new(); observers.resize_with(to_observe.len(), || code.alloc_property_observer()); // we could teach caller about the observed properties without mutating the code body, // but having the statement makes it easy to test and debug. let block = &mut code.basic_blocks[block_index]; for ((line, obj, signal), h) in to_observe.into_iter().zip(observers).rev() { block .statements .insert(line, Statement::ObserveProperty(h, obj, signal)); } }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/typedexpr.rs
Rust
//! Expression tree visitor with type information. // FIXME: Result<_, ExpressionError>: the `Err`-variant returned from this // function is very large #![allow(clippy::result_large_err)] use crate::diagnostic::{Diagnostic, Diagnostics}; use crate::opcode::{ BinaryLogicalOp, BinaryOp, BuiltinFunctionKind, BuiltinNamespaceKind, ComparisonOp, ConsoleLogLevel, UnaryLogicalOp, UnaryOp, }; use crate::qmlast::{ Expression, ExpressionNode, Function, FunctionBody, Identifier, LexicalDeclarationKind, NestedIdentifier, Node, Statement, StatementNode, }; use crate::typemap::{ Class, Enum, MethodMatches, NamedType, Property, TypeKind, TypeMapError, TypeSpace, }; use crate::typeutil; use itertools::Itertools as _; use std::borrow::Cow; use std::collections::HashMap; use std::fmt::Debug; use std::num::TryFromIntError; use std::ops::Range; use thiserror::Error; /// Expression type. #[derive(Clone, Debug, Eq, PartialEq)] pub enum TypeDesc<'a> { /// Integer literal or constant expression without concrete type. ConstInteger, /// String literal or constant expression without concrete type. ConstString, /// Null pointer literal without concrete type. NullPointer, /// Empty array literal or constant expression without concrete type. EmptyList, /// Type that has been determined. Concrete(TypeKind<'a>), } impl TypeDesc<'_> { pub const BOOL: Self = TypeDesc::Concrete(TypeKind::BOOL); pub const DOUBLE: Self = TypeDesc::Concrete(TypeKind::DOUBLE); pub const INT: Self = TypeDesc::Concrete(TypeKind::INT); pub const UINT: Self = TypeDesc::Concrete(TypeKind::UINT); pub const STRING: Self = TypeDesc::Concrete(TypeKind::STRING); pub const VARIANT: Self = TypeDesc::Concrete(TypeKind::VARIANT); pub const VOID: Self = TypeDesc::Concrete(TypeKind::VOID); pub fn qualified_name(&self) -> Cow<'_, str> { match self { TypeDesc::ConstInteger => "integer".into(), TypeDesc::ConstString => "string".into(), TypeDesc::NullPointer => "nullptr_t".into(), TypeDesc::EmptyList => "list".into(), TypeDesc::Concrete(k) => k.qualified_cxx_name(), } } pub fn is_pointer(&self) -> bool { match self { TypeDesc::ConstInteger | TypeDesc::ConstString | TypeDesc::EmptyList => false, TypeDesc::NullPointer => true, TypeDesc::Concrete(k) => k.is_pointer(), } } } /// Provides type of the translated item. pub trait DescribeType<'a> { fn type_desc(&self) -> TypeDesc<'a>; } /// Resolved type/object reference. #[derive(Clone, Debug, Eq, PartialEq)] pub enum RefKind<'a> { /// Type reference. Type(NamedType<'a>), /// Enum variant of the type. EnumVariant(Enum<'a>), /// Object reference of the type. Object(Class<'a>), /// Property of implicit this object reference. ObjectProperty(Class<'a>, String, Property<'a>), /// Method of implicit this object reference. ObjectMethod(Class<'a>, String, MethodMatches<'a>), } /// Top-level context or object which supports name lookup. pub trait RefSpace<'a> { /// Looks up reference by name. fn get_ref(&self, name: &str) -> Option<Result<RefKind<'a>, TypeMapError>>; /// Looks up "this" object type and name. fn this_object(&self) -> Option<(Class<'a>, String)>; } /// Context which supports type annotation lookup. pub trait TypeAnnotationSpace<'a> { /// Looks up type by scoped name and wraps it with the appropriate `TypeKind`. fn get_annotated_type_scoped( &self, scoped_name: &str, ) -> Option<Result<TypeKind<'a>, TypeMapError>>; } impl<'a, T: TypeSpace<'a>> RefSpace<'a> for T { fn get_ref(&self, name: &str) -> Option<Result<RefKind<'a>, TypeMapError>> { #[allow(clippy::manual_map)] if let Some(r) = self.get_type(name) { Some(r.map(RefKind::Type)) } else if let Some(r) = self.get_enum_by_variant(name) { Some(r.map(RefKind::EnumVariant)) } else { None } } fn this_object(&self) -> Option<(Class<'a>, String)> { None } } /// Translates each expression node to [`Self::Item`]. pub trait ExpressionVisitor<'a> { type Item: DescribeType<'a> + Clone; type Local: Copy; type Label: Copy; /// Creates an item that represents a valid, but not meaningful value. `return;` statement /// will generate this value. fn make_void(&self, byte_range: Range<usize>) -> Self::Item; fn visit_integer( &mut self, value: u64, byte_range: Range<usize>, ) -> Result<Self::Item, ExpressionError<'a>>; fn visit_float( &mut self, value: f64, byte_range: Range<usize>, ) -> Result<Self::Item, ExpressionError<'a>>; fn visit_string( &mut self, value: String, byte_range: Range<usize>, ) -> Result<Self::Item, ExpressionError<'a>>; fn visit_bool( &mut self, value: bool, byte_range: Range<usize>, ) -> Result<Self::Item, ExpressionError<'a>>; fn visit_null(&mut self, byte_range: Range<usize>) -> Result<Self::Item, ExpressionError<'a>>; fn visit_enum( &mut self, enum_ty: Enum<'a>, variant: &str, byte_range: Range<usize>, ) -> Result<Self::Item, ExpressionError<'a>>; fn visit_array( &mut self, elements: Vec<Self::Item>, byte_range: Range<usize>, ) -> Result<Self::Item, ExpressionError<'a>>; fn visit_local_ref(&mut self, name: Self::Local) -> Result<Self::Item, ExpressionError<'a>>; fn visit_local_declaration( &mut self, ty: TypeKind<'a>, byte_range: Range<usize>, ) -> Result<Self::Local, ExpressionError<'a>>; fn visit_local_assignment( &mut self, name: Self::Local, right: Self::Item, byte_range: Range<usize>, ) -> Result<Self::Item, ExpressionError<'a>>; fn visit_function_parameter( &mut self, ty: TypeKind<'a>, byte_range: Range<usize>, ) -> Result<Self::Local, ExpressionError<'a>>; fn visit_object_ref( &mut self, cls: Class<'a>, name: &str, byte_range: Range<usize>, ) -> Result<Self::Item, ExpressionError<'a>>; fn visit_object_property( &mut self, object: Self::Item, property: Property<'a>, byte_range: Range<usize>, ) -> Result<Self::Item, ExpressionError<'a>>; fn visit_object_property_assignment( &mut self, object: Self::Item, property: Property<'a>, right: Self::Item, byte_range: Range<usize>, ) -> Result<Self::Item, ExpressionError<'a>>; fn visit_object_subscript( &mut self, object: Self::Item, index: Self::Item, byte_range: Range<usize>, ) -> Result<Self::Item, ExpressionError<'a>>; fn visit_object_subscript_assignment( &mut self, object: Self::Item, index: Self::Item, right: Self::Item, byte_range: Range<usize>, ) -> Result<Self::Item, ExpressionError<'a>>; fn visit_object_method_call( &mut self, object: Self::Item, methods: MethodMatches<'a>, arguments: Vec<Self::Item>, byte_range: Range<usize>, ) -> Result<Self::Item, ExpressionError<'a>>; fn visit_builtin_call( &mut self, function: BuiltinFunctionKind, arguments: Vec<Self::Item>, byte_range: Range<usize>, ) -> Result<Self::Item, ExpressionError<'a>>; fn visit_unary_expression( &mut self, unary: UnaryOp, argument: Self::Item, byte_range: Range<usize>, ) -> Result<Self::Item, ExpressionError<'a>>; fn visit_binary_expression( &mut self, binary: BinaryOp, left: Self::Item, right: Self::Item, byte_range: Range<usize>, ) -> Result<Self::Item, ExpressionError<'a>>; fn visit_binary_logical_expression( &mut self, op: BinaryLogicalOp, left: (Self::Item, Self::Label), right: (Self::Item, Self::Label), byte_range: Range<usize>, ) -> Self::Item; fn visit_as_expression( &mut self, value: Self::Item, ty: TypeKind<'a>, byte_range: Range<usize>, ) -> Result<Self::Item, ExpressionError<'a>>; fn visit_ternary_expression( &mut self, condition: (Self::Item, Self::Label), consequence: (Self::Item, Self::Label), alternative: (Self::Item, Self::Label), byte_range: Range<usize>, ) -> Result<Self::Item, ExpressionError<'a>>; fn visit_expression_statement(&mut self, value: Self::Item); fn visit_if_statement( &mut self, condition: (Self::Item, Self::Label), consequence_ref: Self::Label, alternative_ref: Option<Self::Label>, ); fn visit_switch_statement( &mut self, case_conditions: Vec<(Self::Item, Self::Label)>, bodies: Vec<Self::Label>, default_pos: Option<usize>, head_ref: Self::Label, exit_ref: Self::Label, ); fn visit_break_statement(&mut self, exit_ref: Self::Label); fn visit_return_statement(&mut self, value: Self::Item); fn mark_branch_point(&mut self) -> Self::Label; } #[derive(Clone, Debug, Error)] pub enum ExpressionError<'a> { #[error("integer conversion failed: {0}")] IntegerConversion(#[from] TryFromIntError), #[error("integer overflow")] IntegerOverflow, #[error("type resolution failed: {0}")] TypeResolution(#[from] TypeMapError), #[error( "incompatible array element types at index {0}: {ty1} and {ty2}", ty1 = .1.qualified_name(), ty2 = .2.qualified_name(), )] IncompatibleArrayElementType(usize, TypeDesc<'a>, TypeDesc<'a>), #[error("index must be of integer type, but got: {ty}", ty = .0.qualified_name())] IncompatibleIndexType(TypeDesc<'a>), #[error("invalid argument: {0}")] InvalidArgument(String), #[error( "operation '{0}' on incompatible types: {ty1} and {ty2}", ty1 = .1.qualified_name(), ty2 = .2.qualified_name(), )] OperationOnIncompatibleTypes(String, TypeDesc<'a>, TypeDesc<'a>), #[error("operation '{0}' on undetermined type: {ty}", ty = .1.qualified_name())] OperationOnUndeterminedType(String, TypeDesc<'a>), #[error("operation '{0}' on unsupported type: {ty}", ty = .1.qualified_name())] OperationOnUnsupportedType(String, TypeDesc<'a>), #[error( "operation '{0}' on unsupported types: {ty1} and {ty2}", ty1 = .1.qualified_name(), ty2 = .2.qualified_name(), )] OperationOnUnsupportedTypes(String, TypeDesc<'a>, TypeDesc<'a>), #[error("not a readable property")] UnreadableProperty, #[error("not a writable property")] UnwritableProperty, } #[derive(Debug)] enum Intermediate<'a, T, L> { Item(T), Local(L, LexicalDeclarationKind), BoundProperty(T, Property<'a>, ReceiverKind), BoundSubscript(T, T, ExprKind), BoundMethod(T, MethodMatches<'a>), BuiltinFunction(BuiltinFunctionKind), BuiltinNamespace(BuiltinNamespaceKind), Type(NamedType<'a>), } /// Category of expression. #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum ExprKind { Lvalue, Rvalue, } /// Receiver category of bound property. /// /// Object (or pointer) property is always assignable, but rvalue gadget property isn't. #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum ReceiverKind { Object, Gadget(ExprKind), } /// Walks statement nodes recursively from the specified `node`. /// /// `ctx` is the space where an identifier expression is resolved. pub fn walk<'a, C, V>( ctx: &C, node: StatementNode, source: &str, visitor: &mut V, diagnostics: &mut Diagnostics, ) -> Option<()> where C: RefSpace<'a> + TypeAnnotationSpace<'a>, V: ExpressionVisitor<'a>, { let mut locals = HashMap::new(); walk_stmt(ctx, &mut locals, None, node, source, visitor, diagnostics) } /// Walks statement nodes recursively. fn walk_stmt<'a, C, V>( ctx: &C, locals: &mut HashMap<String, (V::Local, LexicalDeclarationKind)>, break_label: Option<V::Label>, node: StatementNode, source: &str, visitor: &mut V, diagnostics: &mut Diagnostics, ) -> Option<()> where C: RefSpace<'a> + TypeAnnotationSpace<'a>, V: ExpressionVisitor<'a>, { match diagnostics.consume_err(node.parse())? { Statement::Expression(n) => { let value = walk_rvalue(ctx, locals, n, source, visitor, diagnostics)?; visitor.visit_expression_statement(value); Some(()) } Statement::Block(ns) => { let mut locals = locals.clone(); // inner scope inheriting outer walk_stmt_nodes( ctx, &mut locals, break_label, &ns, source, visitor, diagnostics, ) } Statement::LexicalDeclaration(x) => { for decl in &x.variables { let rvalue_node = if let Some(n) = decl.value { let v = walk_rvalue(ctx, locals, n, source, visitor, diagnostics)?; Some((v, n)) } else if x.kind == LexicalDeclarationKind::Const { diagnostics.push(Diagnostic::error( decl.node().byte_range(), "const declaration must have initializer", )); return None; } else { None }; let ty = if let Some(n) = &decl.ty { process_type_annotation(ctx, n, source, diagnostics)? } else if let Some((v, n)) = &rvalue_node { diagnostics.consume_expr_err(*n, typeutil::to_concrete_type(v.type_desc()))? } else { diagnostics.push(Diagnostic::error( decl.node().byte_range(), "variable declaration must have type annotation or initializer", )); return None; }; let local = diagnostics.consume_node_err( decl.node(), visitor.visit_local_declaration(ty, decl.node().byte_range()), )?; locals.insert(decl.name.to_str(source).to_owned(), (local, x.kind)); if let Some((v, _)) = rvalue_node { diagnostics.consume_node_err( decl.node(), visitor.visit_local_assignment(local, v, decl.node().byte_range()), )?; } } Some(()) } Statement::If(x) => { let condition = walk_rvalue(ctx, locals, x.condition, source, visitor, diagnostics)?; let condition_label = visitor.mark_branch_point(); walk_stmt( ctx, locals, break_label, x.consequence, source, visitor, diagnostics, )?; let consequence_label = visitor.mark_branch_point(); let alternative_label = if let Some(n) = x.alternative { walk_stmt(ctx, locals, break_label, n, source, visitor, diagnostics)?; Some(visitor.mark_branch_point()) } else { None }; check_condition_type(&condition, x.condition, diagnostics)?; visitor.visit_if_statement( (condition, condition_label), consequence_label, alternative_label, ); Some(()) } Statement::Switch(x) => { // build separate set of condition blocks and body blocks so the compiler can // easily detect multiple branches let left = walk_rvalue(ctx, locals, x.value, source, visitor, diagnostics)?; let case_conditions: Vec<_> = x .cases .iter() .filter_map(|c| { let right = walk_rvalue(ctx, locals, c.value, source, visitor, diagnostics)?; let condition = diagnostics.consume_expr_err( c.value, visitor.visit_binary_expression( BinaryOp::Comparison(ComparisonOp::Equal), left.clone(), right, c.value.byte_range(), ), )?; let condition_label = visitor.mark_branch_point(); Some((condition, condition_label)) }) .collect(); let mut body_statements: Vec<_> = x.cases.iter().map(|c| &c.body).collect(); let default_pos = if let Some(d) = &x.default { body_statements.insert(d.position, &d.body); Some(d.position) } else { None }; // allocate empty block where "break" will be directed let head_ref = visitor.mark_branch_point(); let exit_ref = visitor.mark_branch_point(); let break_label = Some(exit_ref); let bodies: Vec<_> = body_statements .iter() .filter_map(|nodes| { walk_stmt_nodes( ctx, locals, break_label, nodes, source, visitor, diagnostics, )?; let body_label = visitor.mark_branch_point(); Some(body_label) }) .collect(); if x.cases.len() == case_conditions.len() && body_statements.len() == bodies.len() { visitor.visit_switch_statement( case_conditions, bodies, default_pos, head_ref, exit_ref, ); Some(()) } else { None } } Statement::Break(l) => { if let Some(n) = l { diagnostics.push(Diagnostic::error( n.node().byte_range(), "labeled break is not supported", )); None } else if let Some(l) = break_label { visitor.visit_break_statement(l); Some(()) } else { diagnostics.push(Diagnostic::error( node.byte_range(), "break not in loop or switch statement", )); None } } Statement::Return(x) => { let value = if let Some(n) = x { walk_rvalue(ctx, locals, n, source, visitor, diagnostics)? } else { visitor.make_void(node.byte_range()) }; visitor.visit_return_statement(value); Some(()) } } } fn walk_stmt_nodes<'a, C, V>( ctx: &C, locals: &mut HashMap<String, (V::Local, LexicalDeclarationKind)>, break_label: Option<V::Label>, nodes: &[StatementNode], source: &str, visitor: &mut V, diagnostics: &mut Diagnostics, ) -> Option<()> where C: RefSpace<'a> + TypeAnnotationSpace<'a>, V: ExpressionVisitor<'a>, { let mut res = Some(()); for &n in nodes { // visit all to report as many errors as possible let r = walk_stmt(ctx, locals, break_label, n, source, visitor, diagnostics); res = res.and(r); } res } /// Walks statement or unnamed function block from the specified `node`. /// /// `ctx` is the space where an identifier expression is resolved. pub fn walk_callback<'a, C, V>( ctx: &C, node: StatementNode, source: &str, visitor: &mut V, diagnostics: &mut Diagnostics, ) -> Option<()> where C: RefSpace<'a> + TypeAnnotationSpace<'a>, V: ExpressionVisitor<'a>, { match diagnostics.consume_err(node.parse())? { // explicitly test the node kind since any expression surrounded by parentheses // shouldn't be parsed as a top-level function block. Statement::Expression(n) if n.is_bare_function() => { walk_callback_function(ctx, n, source, visitor, diagnostics) } _ => walk(ctx, node, source, visitor, diagnostics), } } fn walk_callback_function<'a, C, V>( ctx: &C, node: ExpressionNode, source: &str, visitor: &mut V, diagnostics: &mut Diagnostics, ) -> Option<()> where C: RefSpace<'a> + TypeAnnotationSpace<'a>, V: ExpressionVisitor<'a>, { let func = diagnostics.consume_err(Function::from_node(node))?; if let Some(n) = func.name { diagnostics.push(Diagnostic::error( n.node().byte_range(), "named function isn't allowed", )); return None; } if let Some(n) = func.return_ty { diagnostics.push(Diagnostic::warning( n.node().byte_range(), "return type is ignored (which may be changed later)", )); } let mut locals = HashMap::new(); for param in &func.parameters { let name = param.name.to_str(source); if locals.contains_key(name) { diagnostics.push(Diagnostic::error( param.name.node().byte_range(), format!("redefinition of parameter: {name}"), )); } else if let Some(n) = &param.ty { let ty = process_type_annotation(ctx, n, source, diagnostics)?; let local = diagnostics.consume_node_err( param.node(), visitor.visit_function_parameter(ty, param.node().byte_range()), )?; locals.insert(name.to_owned(), (local, LexicalDeclarationKind::Let)); } else { diagnostics.push(Diagnostic::error( param.node().byte_range(), "function parameter must have type annotation", )); } } if locals.len() != func.parameters.len() { return None; } match func.body { FunctionBody::Expression(n) => { let value = walk_rvalue(ctx, &mut locals, n, source, visitor, diagnostics)?; visitor.visit_expression_statement(value); Some(()) } FunctionBody::Statement(n) => { walk_stmt(ctx, &mut locals, None, n, source, visitor, diagnostics) } } } /// Walks expression nodes recursively and returns item to be used as an rvalue. fn walk_rvalue<'a, C, V>( ctx: &C, locals: &mut HashMap<String, (V::Local, LexicalDeclarationKind)>, node: ExpressionNode, source: &str, visitor: &mut V, diagnostics: &mut Diagnostics, ) -> Option<V::Item> where C: RefSpace<'a> + TypeAnnotationSpace<'a>, V: ExpressionVisitor<'a>, { match walk_expr(ctx, locals, node, source, visitor, diagnostics)? { Intermediate::Item(x) => Some(x), Intermediate::Local(l, _) => diagnostics.consume_expr_err(node, visitor.visit_local_ref(l)), Intermediate::BoundProperty(it, p, _) => diagnostics.consume_expr_err( node, visitor.visit_object_property(it, p, node.byte_range()), ), Intermediate::BoundSubscript(it, i, _) => diagnostics.consume_expr_err( node, visitor.visit_object_subscript(it, i, node.byte_range()), ), Intermediate::BoundMethod(..) | Intermediate::BuiltinFunction(_) => { diagnostics.push(Diagnostic::error( node.byte_range(), "bare function reference", )); None } Intermediate::BuiltinNamespace(_) | Intermediate::Type(_) => { diagnostics.push(Diagnostic::error(node.byte_range(), "bare type reference")); None } } } /// Walks expression nodes recursively and returns intermediate result. fn walk_expr<'a, C, V>( ctx: &C, locals: &mut HashMap<String, (V::Local, LexicalDeclarationKind)>, node: ExpressionNode, source: &str, visitor: &mut V, diagnostics: &mut Diagnostics, ) -> Option<Intermediate<'a, V::Item, V::Local>> where C: RefSpace<'a> + TypeAnnotationSpace<'a>, V: ExpressionVisitor<'a>, { match diagnostics.consume_err(node.parse(source))? { Expression::Identifier(x) => { process_identifier(ctx, Some(locals), true, x, source, visitor, diagnostics) } Expression::This => { if let Some((cls, name)) = ctx.this_object() { diagnostics .consume_expr_err( node, visitor.visit_object_ref(cls, &name, node.byte_range()), ) .map(Intermediate::Item) } else { diagnostics.push(Diagnostic::error(node.byte_range(), "undefined reference")); None } } Expression::Integer(v) => diagnostics .consume_expr_err(node, visitor.visit_integer(v, node.byte_range())) .map(Intermediate::Item), Expression::Float(v) => diagnostics .consume_expr_err(node, visitor.visit_float(v, node.byte_range())) .map(Intermediate::Item), Expression::String(v) => diagnostics .consume_expr_err(node, visitor.visit_string(v, node.byte_range())) .map(Intermediate::Item), Expression::Bool(v) => diagnostics .consume_expr_err(node, visitor.visit_bool(v, node.byte_range())) .map(Intermediate::Item), Expression::Null => diagnostics .consume_expr_err(node, visitor.visit_null(node.byte_range())) .map(Intermediate::Item), Expression::Array(ns) => { let elements = ns .iter() .map(|&n| walk_rvalue(ctx, locals, n, source, visitor, diagnostics)) .collect::<Option<Vec<_>>>()?; match visitor.visit_array(elements, node.byte_range()) { Ok(it) => Some(Intermediate::Item(it)), Err(e) => { let mut diag = Diagnostic::error(node.byte_range(), e.to_string()); if let ExpressionError::IncompatibleArrayElementType(i, l, r) = &e { typeutil::diagnose_incompatible_types( &mut diag, ns[*i - 1].byte_range(), l, ns[*i].byte_range(), r, ); } diagnostics.push(diag); None } } } Expression::Function(_) | Expression::ArrowFunction(_) => { diagnostics.push(Diagnostic::error( node.byte_range(), "unsupported expression", )); None } Expression::Member(x) => { match walk_expr(ctx, locals, x.object, source, visitor, diagnostics)? { Intermediate::Item(it) => { process_item_property(it, x.property, ExprKind::Rvalue, source, diagnostics) } Intermediate::Local(l, _) => { let it = diagnostics.consume_expr_err(node, visitor.visit_local_ref(l))?; process_item_property(it, x.property, ExprKind::Lvalue, source, diagnostics) } Intermediate::BoundProperty(it, p, _) => { let obj = diagnostics.consume_expr_err( x.object, visitor.visit_object_property(it, p, x.object.byte_range()), )?; process_item_property(obj, x.property, ExprKind::Rvalue, source, diagnostics) } Intermediate::BoundSubscript(it, i, _) => { let obj = diagnostics.consume_expr_err( x.object, visitor.visit_object_subscript(it, i, x.object.byte_range()), )?; process_item_property(obj, x.property, ExprKind::Rvalue, source, diagnostics) } Intermediate::BoundMethod(..) | Intermediate::BuiltinFunction(_) => { diagnostics.push(Diagnostic::error( node.byte_range(), "function has no property/method", )); None } Intermediate::BuiltinNamespace(k) => { process_namespace_name(k, x.property, source, diagnostics) } Intermediate::Type(ty) => { process_identifier(&ty, None, false, x.property, source, visitor, diagnostics) } } } Expression::Subscript(x) => { let (obj, k) = match walk_expr(ctx, locals, x.object, source, visitor, diagnostics)? { Intermediate::Item(it) => (it, ExprKind::Rvalue), Intermediate::Local(l, _) => { let it = diagnostics.consume_expr_err(node, visitor.visit_local_ref(l))?; (it, ExprKind::Lvalue) } Intermediate::BoundProperty(it, p, _) => { let obj = diagnostics.consume_expr_err( x.object, visitor.visit_object_property(it, p, x.object.byte_range()), )?; (obj, ExprKind::Rvalue) } Intermediate::BoundSubscript(it, i, _) => { let obj = diagnostics.consume_expr_err( x.object, visitor.visit_object_subscript(it, i, x.object.byte_range()), )?; (obj, ExprKind::Rvalue) } Intermediate::BoundMethod(..) | Intermediate::BuiltinFunction(_) => { diagnostics.push(Diagnostic::error( x.object.byte_range(), "bare function reference", )); return None; } Intermediate::BuiltinNamespace(_) | Intermediate::Type(_) => { diagnostics.push(Diagnostic::error( x.object.byte_range(), "bare type reference", )); return None; } }; let index = walk_rvalue(ctx, locals, x.index, source, visitor, diagnostics)?; Some(Intermediate::BoundSubscript(obj, index, k)) } Expression::Call(x) => { let arguments = x .arguments .iter() .map(|&n| walk_rvalue(ctx, locals, n, source, visitor, diagnostics)) .collect::<Option<Vec<_>>>()?; match walk_expr(ctx, locals, x.function, source, visitor, diagnostics)? { Intermediate::BoundMethod(it, ms) => diagnostics .consume_expr_err( node, visitor.visit_object_method_call(it, ms, arguments, node.byte_range()), ) .map(Intermediate::Item), Intermediate::BuiltinFunction(f) => diagnostics .consume_expr_err( node, visitor.visit_builtin_call(f, arguments, node.byte_range()), ) .map(Intermediate::Item), Intermediate::Item(_) | Intermediate::Local(..) | Intermediate::BoundProperty(..) | Intermediate::BoundSubscript(..) | Intermediate::BuiltinNamespace(_) | Intermediate::Type(_) => { diagnostics.push(Diagnostic::error(x.function.byte_range(), "not callable")); None } } } Expression::Assignment(x) => { let right = walk_rvalue(ctx, locals, x.right, source, visitor, diagnostics)?; match walk_expr(ctx, locals, x.left, source, visitor, diagnostics)? { Intermediate::Local(l, k) => match k { LexicalDeclarationKind::Let => diagnostics .consume_expr_err( node, visitor.visit_local_assignment(l, right, node.byte_range()), ) .map(Intermediate::Item), LexicalDeclarationKind::Const => { diagnostics.push(Diagnostic::error( x.left.byte_range(), "cannot assign to const variable", )); None } }, Intermediate::BoundProperty( it, p, ReceiverKind::Object | ReceiverKind::Gadget(ExprKind::Lvalue), ) => diagnostics .consume_expr_err( node, visitor.visit_object_property_assignment(it, p, right, node.byte_range()), ) .map(Intermediate::Item), Intermediate::BoundProperty(_, _, ReceiverKind::Gadget(ExprKind::Rvalue)) => { diagnostics.push(Diagnostic::error( x.left.byte_range(), "rvalue gadget property is not assignable", )); None } Intermediate::BoundSubscript(it, i, ExprKind::Lvalue) => diagnostics .consume_expr_err( node, visitor.visit_object_subscript_assignment(it, i, right, node.byte_range()), ) .map(Intermediate::Item), Intermediate::BoundSubscript(_, _, ExprKind::Rvalue) => { diagnostics.push(Diagnostic::error( x.left.byte_range(), "rvalue subscript is not assignable", )); None } Intermediate::Item(_) | Intermediate::BoundMethod(..) | Intermediate::BuiltinFunction(_) | Intermediate::BuiltinNamespace(_) | Intermediate::Type(_) => { diagnostics.push(Diagnostic::error(x.left.byte_range(), "not assignable")); None } } } Expression::Unary(x) => { let argument = walk_rvalue(ctx, locals, x.argument, source, visitor, diagnostics)?; let argument_t = argument.type_desc(); let unary = UnaryOp::try_from(x.operator) .map_err(|()| { diagnostics.push(Diagnostic::error( node.byte_range(), format!("unsupported operation '{}'", x.operator), )) }) .ok()?; match visitor.visit_unary_expression(unary, argument, node.byte_range()) { Ok(it) => Some(Intermediate::Item(it)), Err(e) => { let mut diag = Diagnostic::error(node.byte_range(), e.to_string()); if unary == UnaryOp::Logical(UnaryLogicalOp::Not) && matches!(&e, ExpressionError::OperationOnUnsupportedType(..)) { typeutil::diagnose_bool_conversion( &mut diag, x.argument.byte_range(), &argument_t, false, // truthy ); } diagnostics.push(diag); None } } } Expression::Binary(x) => { let binary = BinaryOp::try_from(x.operator) .map_err(|()| { diagnostics.push(Diagnostic::error( node.byte_range(), format!("unsupported operation '{}'", x.operator), )) }) .ok()?; let diagnose = |e: &ExpressionError| { let mut diag = Diagnostic::error(node.byte_range(), e.to_string()); match e { ExpressionError::OperationOnIncompatibleTypes(_, l, r) => { typeutil::diagnose_incompatible_types( &mut diag, x.left.byte_range(), l, x.right.byte_range(), r, ); } ExpressionError::OperationOnUnsupportedType(_, t) => { typeutil::push_type_label(&mut diag, x.left.byte_range(), t); typeutil::push_type_label(&mut diag, x.right.byte_range(), t); } ExpressionError::OperationOnUnsupportedTypes(_, l, r) => { typeutil::push_type_label(&mut diag, x.left.byte_range(), l); typeutil::push_type_label(&mut diag, x.right.byte_range(), r); } _ => {} } diag }; match binary { BinaryOp::Arith(_) | BinaryOp::Bitwise(_) | BinaryOp::Shift(_) | BinaryOp::Comparison(_) => { let left = walk_rvalue(ctx, locals, x.left, source, visitor, diagnostics)?; let right = walk_rvalue(ctx, locals, x.right, source, visitor, diagnostics)?; match visitor.visit_binary_expression(binary, left, right, node.byte_range()) { Ok(it) => Some(Intermediate::Item(it)), Err(e) => { diagnostics.push(diagnose(&e)); None } } } BinaryOp::Logical(op) => { let left = walk_rvalue(ctx, locals, x.left, source, visitor, diagnostics)?; let left_label = visitor.mark_branch_point(); let right = walk_rvalue(ctx, locals, x.right, source, visitor, diagnostics)?; let right_label = visitor.mark_branch_point(); check_condition_type(&left, x.left, diagnostics)?; check_condition_type(&right, x.right, diagnostics)?; let it = visitor.visit_binary_logical_expression( op, (left, left_label), (right, right_label), node.byte_range(), ); Some(Intermediate::Item(it)) } } } Expression::As(x) => { let value = walk_rvalue(ctx, locals, x.value, source, visitor, diagnostics)?; let ty = process_type_annotation(ctx, &x.ty, source, diagnostics)?; diagnostics .consume_expr_err( node, visitor.visit_as_expression(value, ty, node.byte_range()), ) .map(Intermediate::Item) } Expression::Ternary(x) => { let condition = walk_rvalue(ctx, locals, x.condition, source, visitor, diagnostics)?; let condition_label = visitor.mark_branch_point(); let consequence = walk_rvalue(ctx, locals, x.consequence, source, visitor, diagnostics)?; let consequence_label = visitor.mark_branch_point(); let alternative = walk_rvalue(ctx, locals, x.alternative, source, visitor, diagnostics)?; let alternative_label = visitor.mark_branch_point(); check_condition_type(&condition, x.condition, diagnostics)?; match visitor.visit_ternary_expression( (condition, condition_label), (consequence, consequence_label), (alternative, alternative_label), node.byte_range(), ) { Ok(it) => Some(Intermediate::Item(it)), Err(e) => { let mut diag = Diagnostic::error(node.byte_range(), e.to_string()); if let ExpressionError::OperationOnIncompatibleTypes(_, l, r) = &e { typeutil::diagnose_incompatible_types( &mut diag, x.consequence.byte_range(), l, x.alternative.byte_range(), r, ); }; diagnostics.push(diag); None } } } } } fn process_identifier<'a, C, V>( ctx: &C, locals: Option<&HashMap<String, (V::Local, LexicalDeclarationKind)>>, use_globals: bool, id: Identifier, source: &str, visitor: &mut V, diagnostics: &mut Diagnostics, ) -> Option<Intermediate<'a, V::Item, V::Local>> where C: RefSpace<'a>, V: ExpressionVisitor<'a>, { let name = id.to_str(source); if let Some(&(l, k)) = locals.and_then(|m| m.get(name)) { Some(Intermediate::Local(l, k)) } else if let Some(r) = ctx.get_ref(name) { match r { Ok(RefKind::Type(ty)) => Some(Intermediate::Type(ty)), Ok(RefKind::EnumVariant(en)) => diagnostics .consume_node_err( id.node(), visitor.visit_enum(en, name, id.node().byte_range()), ) .map(Intermediate::Item), Ok(RefKind::Object(cls)) => diagnostics .consume_node_err( id.node(), visitor.visit_object_ref(cls, name, id.node().byte_range()), ) .map(Intermediate::Item), Ok(RefKind::ObjectProperty(obj_cls, obj_name, p)) => diagnostics .consume_node_err( id.node(), visitor.visit_object_ref(obj_cls, &obj_name, id.node().byte_range()), ) .map(|item| Intermediate::BoundProperty(item, p, ReceiverKind::Object)), Ok(RefKind::ObjectMethod(obj_cls, obj_name, m)) => diagnostics .consume_node_err( id.node(), visitor.visit_object_ref(obj_cls, &obj_name, id.node().byte_range()), ) .map(|item| Intermediate::BoundMethod(item, m)), Err(e) => { diagnostics.push(Diagnostic::error( id.node().byte_range(), format!("type resolution failed: {e}"), )); None } } } else if let Some(x) = use_globals.then(|| lookup_global_name(name)).flatten() { Some(x) } else { diagnostics.push(Diagnostic::error( id.node().byte_range(), "undefined reference", )); None } } fn lookup_global_name<T, L>(name: &str) -> Option<Intermediate<'static, T, L>> { match name { "Math" => Some(Intermediate::BuiltinNamespace(BuiltinNamespaceKind::Math)), "console" => Some(Intermediate::BuiltinNamespace( BuiltinNamespaceKind::Console, )), "qsTr" => Some(Intermediate::BuiltinFunction(BuiltinFunctionKind::Tr)), _ => None, } } fn process_namespace_name<'a, T, L>( kind: BuiltinNamespaceKind, id: Identifier, source: &str, diagnostics: &mut Diagnostics, ) -> Option<Intermediate<'a, T, L>> { let name = id.to_str(source); let not_found_in = |ns: &str| { Diagnostic::error( id.node().byte_range(), format!("property/method named '{name}' not found in '{ns}'"), ) }; match kind { BuiltinNamespaceKind::Console => { let log_fn = |lv| Intermediate::BuiltinFunction(BuiltinFunctionKind::ConsoleLog(lv)); match name { "debug" => Some(log_fn(ConsoleLogLevel::Debug)), "error" => Some(log_fn(ConsoleLogLevel::Error)), "info" => Some(log_fn(ConsoleLogLevel::Info)), "log" => Some(log_fn(ConsoleLogLevel::Log)), "warn" => Some(log_fn(ConsoleLogLevel::Warn)), _ => { diagnostics.push(not_found_in("console")); None } } } BuiltinNamespaceKind::Math => match name { "max" => Some(Intermediate::BuiltinFunction(BuiltinFunctionKind::Max)), "min" => Some(Intermediate::BuiltinFunction(BuiltinFunctionKind::Min)), _ => { diagnostics.push(not_found_in("Math")); None } }, } } fn process_item_property<'a, T, L>( item: T, id: Identifier, item_kind: ExprKind, source: &str, diagnostics: &mut Diagnostics, ) -> Option<Intermediate<'a, T, L>> where T: DescribeType<'a>, { let name = id.to_str(source); let not_found = || { Diagnostic::error( id.node().byte_range(), format!( "property/method named '{name}' not found in type '{type_name}'", type_name = item.type_desc().qualified_name(), ), ) }; let ty = match typeutil::to_concrete_type(item.type_desc()) { Ok(ty) => ty, Err(e) => { diagnostics.push(Diagnostic::error(id.node().byte_range(), e.to_string())); return None; } }; let is_pointer = ty.is_pointer(); if let Some(cls) = ty.into_class() { let k = if is_pointer { ReceiverKind::Object } else { ReceiverKind::Gadget(item_kind) }; if let Some(r) = cls.get_property(name) { match r { Ok(p) => Some(Intermediate::BoundProperty(item, p, k)), Err(e) => { diagnostics.push(Diagnostic::error( id.node().byte_range(), format!("property resolution failed: {e}"), )); None } } } else if let Some(r) = cls.get_public_method(name) { match r { Ok(m) => Some(Intermediate::BoundMethod(item, m)), Err(e) => { diagnostics.push(Diagnostic::error( id.node().byte_range(), format!("method resolution failed: {e}"), )); None } } } else { diagnostics.push(not_found()); None } } else { diagnostics.push(not_found()); None } } fn process_type_annotation<'a, C>( ctx: &C, id: &NestedIdentifier, source: &str, diagnostics: &mut Diagnostics, ) -> Option<TypeKind<'a>> where C: TypeAnnotationSpace<'a>, { // TODO: look up qualified name without joining let scoped_name = id.components().iter().map(|n| n.to_str(source)).join("::"); match ctx.get_annotated_type_scoped(&scoped_name) { Some(Ok(ty)) => Some(ty), Some(Err(e)) => { diagnostics.push(Diagnostic::error( id.node().byte_range(), format!("type resolution failed: {e}"), )); None } None => { diagnostics.push(Diagnostic::error(id.node().byte_range(), "undefined type")); None } } } fn check_condition_type<'a, T>( condition: &T, node: ExpressionNode, diagnostics: &mut Diagnostics, ) -> Option<()> where T: DescribeType<'a>, { match condition.type_desc() { TypeDesc::BOOL => Some(()), t => { let mut diag = Diagnostic::error( node.byte_range(), format!( "condition must be of bool type, but got: {}", t.qualified_name() ), ); typeutil::diagnose_bool_conversion( &mut diag, node.byte_range(), &t, true, // truthy ); diagnostics.push(diag); None } } } // TODO: maybe rewrite this extension methods with a plain function? impl Diagnostics { fn consume_expr_err<T, E>(&mut self, node: ExpressionNode, result: Result<T, E>) -> Option<T> where E: ToString, { self.consume_err(result.map_err(|e| Diagnostic::error(node.byte_range(), e.to_string()))) } fn consume_node_err<T, E>(&mut self, node: Node, result: Result<T, E>) -> Option<T> where E: ToString, { self.consume_err(result.map_err(|e| Diagnostic::error(node.byte_range(), e.to_string()))) } }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/typemap/class.rs
Rust
use super::core::{TypeMapError, TypeSpace}; use super::enum_::Enum; use super::function::{Method, MethodDataTable, MethodKind, MethodMatches}; use super::namespace::NamespaceData; use super::util::{self, TypeDataRef}; use super::{NamedType, ParentSpace, TypeKind}; use crate::metatype; use crate::qtname; use std::collections::{HashMap, HashSet, VecDeque}; use std::iter::FusedIterator; use std::slice; /// QObject (or gadget) class representation. #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub struct Class<'a> { data: TypeDataRef<'a, ClassData>, parent_space: Box<ParentSpace<'a>>, temporary_class_name: Option<String>, // generated name e.g. QList<T> } /// Stored class representation. #[derive(Clone, Debug)] pub(super) struct ClassData { class_name: String, public_super_class_names: Vec<String>, attached_class_name: Option<String>, inner_type_map: NamespaceData, property_map: HashMap<String, PropertyData>, public_methods: MethodDataTable, } impl<'a> Class<'a> { pub(super) fn new(data: TypeDataRef<'a, ClassData>, parent_space: ParentSpace<'a>) -> Self { Class { data, parent_space: Box::new(parent_space), temporary_class_name: None, } } pub(super) fn with_temporary_name( name: impl Into<String>, data: TypeDataRef<'a, ClassData>, parent_space: ParentSpace<'a>, ) -> Self { Class { data, parent_space: Box::new(parent_space), temporary_class_name: Some(name.into()), } } pub fn public_super_classes(&self) -> SuperClasses<'a> { SuperClasses::new( self.data.as_ref().public_super_class_names.iter(), *self.parent_space.clone(), ) } fn base_classes(&self) -> BaseClasses<'a> { BaseClasses::new(self.public_super_classes()) } fn find_map_self_and_base_classes<T>( &self, mut f: impl FnMut(&Class<'a>) -> Option<Result<T, TypeMapError>>, ) -> Option<Result<T, TypeMapError>> { if let Some(r) = f(self) { Some(r) } else { self.base_classes() .find_map(|r| r.and_then(|c| f(&c).transpose()).transpose()) } } pub fn is_derived_from(&self, base: &Class) -> bool { self.is_derived_from_pedantic(base) .and_then(|r| r.ok()) .is_some() } fn is_derived_from_pedantic(&self, base: &Class) -> Option<Result<(), TypeMapError>> { if self == base { Some(Ok(())) } else { self.base_classes() .find_map(|r| r.map(|c| (&c == base).then_some(())).transpose()) } } pub fn common_base_class(&self, other: &Class<'a>) -> Option<Result<Class<'a>, TypeMapError>> { // quadratic, but the inheritance chain should be short self.find_map_self_and_base_classes(|cls| { other .is_derived_from_pedantic(cls) .map(|r| r.map(|()| cls.clone())) }) } pub fn attached_class(&self) -> Option<Result<Class<'a>, TypeMapError>> { self.data .as_ref() .attached_class_name .as_ref() .map(|n| resolve_class_scoped(&self.parent_space, n)) } fn get_type_no_super(&self, name: &str) -> Option<Result<NamedType<'a>, TypeMapError>> { self.data .as_ref() .inner_type_map .get_type_with(name, None, || ParentSpace::Class(self.clone())) } fn get_enum_by_variant_no_super(&self, name: &str) -> Option<Result<Enum<'a>, TypeMapError>> { self.data .as_ref() .inner_type_map .get_enum_by_variant_with(name, || ParentSpace::Class(self.clone())) } /// Looks up property by name. pub fn get_property(&self, name: &str) -> Option<Result<Property<'a>, TypeMapError>> { self.find_map_self_and_base_classes(|cls| cls.get_property_no_super(name)) } fn get_property_no_super(&self, name: &str) -> Option<Result<Property<'a>, TypeMapError>> { self.data .as_ref() .property_map .get_key_value(name) .map(|(n, d)| Property::new(TypeDataRef(n), TypeDataRef(d), self.clone())) } /// Looks up signals, slots, and methods by name. /// /// Though signals are conceptually different from slots and methods, they live in /// the same name resolution space. Therefore, they are looked up together. Use /// [`kind()`](super::Method::kind()) to find the nature of the function. pub fn get_public_method(&self, name: &str) -> Option<Result<MethodMatches<'a>, TypeMapError>> { // TODO: does it follow the shadowing rule of Qt meta methods? self.find_map_self_and_base_classes(|cls| cls.get_public_method_no_super(name)) } fn get_public_method_no_super( &self, name: &str, ) -> Option<Result<MethodMatches<'a>, TypeMapError>> { self.data .as_ref() .public_methods .get_method_with(name, || self.clone()) } } impl<'a> TypeSpace<'a> for Class<'a> { fn name(&self) -> &str { self.temporary_class_name .as_ref() .unwrap_or(&self.data.as_ref().class_name) } fn get_type(&self, name: &str) -> Option<Result<NamedType<'a>, TypeMapError>> { self.find_map_self_and_base_classes(|cls| cls.get_type_no_super(name)) } fn lexical_parent(&self) -> Option<&ParentSpace<'a>> { Some(&self.parent_space) } fn get_enum_by_variant(&self, name: &str) -> Option<Result<Enum<'a>, TypeMapError>> { self.find_map_self_and_base_classes(|cls| cls.get_enum_by_variant_no_super(name)) } } impl ClassData { pub(super) fn with_supers<S, I>(name: S, super_names: I) -> Self where S: Into<String>, I: IntoIterator, I::Item: Into<String>, { ClassData { class_name: name.into(), public_super_class_names: super_names.into_iter().map(Into::into).collect(), attached_class_name: None, inner_type_map: NamespaceData::default(), property_map: HashMap::new(), public_methods: MethodDataTable::default(), } } pub(super) fn from_meta(meta: metatype::Class) -> Self { let public_super_class_names = meta .super_classes .into_iter() .filter_map(|s| { if s.access == metatype::AccessSpecifier::Public { Some(s.name) } else { None } }) .collect(); let attached_class_name = meta .class_infos .into_iter() .find_map(|x| (x.name == "QML.Attached").then_some(x.value)); let mut inner_type_map = NamespaceData::default(); inner_type_map.extend_enums(meta.enums); let property_map = meta .properties .into_iter() .map(PropertyData::pair_from_meta) .collect(); let public_methods = MethodDataTable::from_meta( [ (meta.signals, MethodKind::Signal), (meta.slots, MethodKind::Slot), (meta.methods, MethodKind::Method), ], metatype::AccessSpecifier::Public, ); ClassData { class_name: meta.class_name, public_super_class_names, attached_class_name, inner_type_map, property_map, public_methods, } } pub(super) fn class_name(&self) -> &str { &self.class_name } } /// Property representation. #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub struct Property<'a> { name: TypeDataRef<'a, String>, data: TypeDataRef<'a, PropertyData>, value_type: TypeKind<'a>, object_class: Class<'a>, } /// Stored property representation. #[derive(Clone, Debug)] struct PropertyData { type_name: String, read_func_name: Option<String>, write_func_name: Option<String>, notify_signal_name: Option<String>, constant: bool, } impl<'a> Property<'a> { fn new( name: TypeDataRef<'a, String>, data: TypeDataRef<'a, PropertyData>, object_class: Class<'a>, ) -> Result<Self, TypeMapError> { let value_type = util::decorated_type(&data.as_ref().type_name, |n| { object_class.resolve_type_scoped(n) })?; Ok(Property { name, data, value_type, object_class, }) } pub fn name(&self) -> &str { self.name.as_ref() } /// Type of the property value. pub fn value_type(&self) -> &TypeKind<'a> { &self.value_type } /// Type name of the property value. pub fn value_type_name(&self) -> &str { &self.data.as_ref().type_name } /// Whether or not this property can be get. pub fn is_readable(&self) -> bool { self.data.as_ref().read_func_name.is_some() } /// Whether or not this property can be set. pub fn is_writable(&self) -> bool { self.data.as_ref().write_func_name.is_some() } /// Whether or not changes on this property can be notified. pub fn is_notifiable(&self) -> bool { self.data.as_ref().notify_signal_name.is_some() } /// Whether or not this property never changes. pub fn is_constant(&self) -> bool { self.data.as_ref().constant } /// Whether or not this property provides the standard setter function. /// /// See `PropertyDef::stdCppSet()` in `qtbase/src/tools/moc/moc.h` for details. pub fn is_std_set(&self) -> bool { let d = self.data.as_ref(); qtname::is_std_set_property(self.name.as_ref(), d.write_func_name.as_deref()) } /// Function name to get this property. pub fn read_func_name(&self) -> Option<&str> { self.data.as_ref().read_func_name.as_deref() } /// Function name to set this property. pub fn write_func_name(&self) -> Option<&str> { self.data.as_ref().write_func_name.as_deref() } /// Signal function to notify changes on this property. pub fn notify_signal(&self) -> Option<Result<Method<'a>, TypeMapError>> { self.notify_signal_name() .map(|n| self.find_notify_signal(n)) } fn find_notify_signal(&self, name: &str) -> Result<Method<'a>, TypeMapError> { let matches = self .object_class .get_public_method(name) .unwrap_or_else(|| Err(TypeMapError::InvalidNotifySignal(name.to_owned())))?; let mut best: Option<Method<'a>> = None; for m in matches .into_iter() .filter(|m| m.kind() == MethodKind::Signal) { if best .as_ref() .map(|k| m.arguments_len() <= k.arguments_len()) .unwrap_or(false) { // Prefer function having more arguments. Default parameter is invisible // to metatype, but its existence is significant for overload resolution. continue; } if m.arguments_len() == 0 || m.argument_type(0) == self.value_type() { best = Some(m); } } best.ok_or_else(|| TypeMapError::InvalidNotifySignal(name.to_owned())) } /// Signal name to notify changes on this property. pub fn notify_signal_name(&self) -> Option<&str> { self.data.as_ref().notify_signal_name.as_deref() } /// Type of the object which this property is associated with. pub fn object_class(&self) -> &Class<'a> { &self.object_class } } impl PropertyData { fn pair_from_meta(meta: metatype::Property) -> (String, Self) { let data = PropertyData { type_name: meta.r#type, read_func_name: meta.read, write_func_name: meta.write, notify_signal_name: meta.notify, constant: meta.constant, }; (meta.name, data) } } /// Iterator over the direct super classes. #[derive(Clone, Debug)] pub struct SuperClasses<'a> { names_iter: slice::Iter<'a, String>, parent_space: ParentSpace<'a>, } impl<'a> SuperClasses<'a> { fn new(names_iter: slice::Iter<'a, String>, parent_space: ParentSpace<'a>) -> Self { SuperClasses { names_iter, parent_space, } } } impl<'a> Iterator for SuperClasses<'a> { type Item = Result<Class<'a>, TypeMapError>; fn next(&mut self) -> Option<Self::Item> { self.names_iter .next() .map(|n| resolve_class_scoped(&self.parent_space, n)) } fn size_hint(&self) -> (usize, Option<usize>) { self.names_iter.size_hint() } } impl<'a> FusedIterator for SuperClasses<'a> where slice::Iter<'a, String>: FusedIterator {} /// Iterator to walk up the super classes. /// /// This runs breadth-first search over super classes just because it's easier to implement /// than DFS. That shouldn't matter since the resolution would be ambiguous if two super classes /// in different chains had conflicting definitions. Don't rely on the behavior specific to /// BFS or DFS. #[derive(Clone, Debug)] struct BaseClasses<'a> { pending: VecDeque<SuperClasses<'a>>, visited: HashSet<Class<'a>>, } impl<'a> BaseClasses<'a> { fn new(supers: SuperClasses<'a>) -> Self { BaseClasses { pending: VecDeque::from([supers]), visited: HashSet::new(), } } } impl<'a> Iterator for BaseClasses<'a> { type Item = Result<Class<'a>, TypeMapError>; fn next(&mut self) -> Option<Self::Item> { while let Some(supers) = self.pending.front_mut() { for r in supers.by_ref() { return match r { Ok(c) if self.visited.insert(c.clone()) => { self.pending.push_back(c.public_super_classes()); Some(Ok(c)) } Ok(_) => continue, // already visited Err(_) => Some(r), }; } self.pending.pop_front(); } None } } impl FusedIterator for BaseClasses<'_> {} fn resolve_class_scoped<'a>( parent_space: &ParentSpace<'a>, scoped_name: &str, ) -> Result<Class<'a>, TypeMapError> { let ty = parent_space .resolve_type_scoped(scoped_name) .unwrap_or_else(|| Err(TypeMapError::InvalidTypeRef(scoped_name.to_owned())))?; ty.into_class() .ok_or_else(|| TypeMapError::InvalidSuperClassType(scoped_name.to_owned())) } #[cfg(test)] mod tests { use super::super::{ModuleData, ModuleId, TypeMap}; use super::*; use crate::metatype; fn unwrap_class(r: Option<Result<NamedType, TypeMapError>>) -> Class { match r { Some(Ok(NamedType::Class(x))) => x, _ => panic!("unexpected type: {r:?}"), } } #[test] fn base_classes_simple() { let mut type_map = TypeMap::empty(); let module_id = ModuleId::Named("foo"); let mut module_data = ModuleData::default(); module_data.extend([ metatype::Class::new("Root"), metatype::Class::with_supers("Sub1", ["Root"]), metatype::Class::with_supers("Sub2", ["Sub1"]), ]); type_map.insert_module(module_id, module_data); let module = type_map.get_module(module_id).unwrap(); let root_class = unwrap_class(module.get_type("Root")); let sub1_class = unwrap_class(module.get_type("Sub1")); let sub2_class = unwrap_class(module.get_type("Sub2")); assert_eq!( root_class .base_classes() .collect::<Result<Vec<_>, _>>() .unwrap(), [] ); assert_eq!( sub1_class .base_classes() .collect::<Result<Vec<_>, _>>() .unwrap(), [root_class.clone()] ); assert_eq!( sub2_class .base_classes() .collect::<Result<Vec<_>, _>>() .unwrap(), [sub1_class.clone(), root_class.clone()] ); } #[test] fn base_classes_multiple() { let mut type_map = TypeMap::empty(); let module_id = ModuleId::Named("foo"); let mut module_data = ModuleData::default(); module_data.extend([ metatype::Class::new("Root1"), metatype::Class::new("Root2"), metatype::Class::with_supers("Sub1", ["Root1"]), metatype::Class::with_supers("Sub2", ["Sub1", "Root2"]), ]); type_map.insert_module(module_id, module_data); let module = type_map.get_module(module_id).unwrap(); let root1_class = unwrap_class(module.get_type("Root1")); let root2_class = unwrap_class(module.get_type("Root2")); let sub1_class = unwrap_class(module.get_type("Sub1")); let sub2_class = unwrap_class(module.get_type("Sub2")); assert_eq!( sub2_class .base_classes() .collect::<Result<Vec<_>, _>>() .unwrap(), [sub1_class.clone(), root2_class.clone(), root1_class.clone()] ); } #[test] fn base_classes_diamond() { let mut type_map = TypeMap::empty(); let module_id = ModuleId::Named("foo"); let mut module_data = ModuleData::default(); module_data.extend([ metatype::Class::new("Root"), metatype::Class::with_supers("Mid1", ["Root"]), metatype::Class::with_supers("Mid2", ["Root"]), metatype::Class::with_supers("Leaf", ["Mid1", "Mid2"]), ]); type_map.insert_module(module_id, module_data); let module = type_map.get_module(module_id).unwrap(); let root_class = unwrap_class(module.get_type("Root")); let mid1_class = unwrap_class(module.get_type("Mid1")); let mid2_class = unwrap_class(module.get_type("Mid2")); let leaf_class = unwrap_class(module.get_type("Leaf")); assert_eq!( leaf_class .base_classes() .collect::<Result<Vec<_>, _>>() .unwrap(), [mid1_class.clone(), mid2_class.clone(), root_class.clone()] ); } #[test] fn common_base_class() { let mut type_map = TypeMap::empty(); let module_id = ModuleId::Named("foo"); let mut module_data = ModuleData::default(); module_data.extend([ metatype::Class::new("Root1"), metatype::Class::new("Root2"), metatype::Class::with_supers("Mid1", ["Root1"]), metatype::Class::with_supers("Mid2", ["Root2"]), metatype::Class::with_supers("Mid3", ["Root2"]), metatype::Class::with_supers("Leaf1", ["Mid1", "Mid2"]), metatype::Class::with_supers("Leaf2", ["Mid3"]), ]); type_map.insert_module(module_id, module_data); // Root1 <--- Mid1 <--- Leaf1 // / // Root2 <--- Mid2 <- // \ // - Mid3 <--- Leaf2 let module = type_map.get_module(module_id).unwrap(); let root1_class = unwrap_class(module.get_type("Root1")); let root2_class = unwrap_class(module.get_type("Root2")); let mid1_class = unwrap_class(module.get_type("Mid1")); let mid2_class = unwrap_class(module.get_type("Mid2")); let mid3_class = unwrap_class(module.get_type("Mid3")); let leaf1_class = unwrap_class(module.get_type("Leaf1")); let leaf2_class = unwrap_class(module.get_type("Leaf2")); assert!(Class::common_base_class(&root1_class, &root2_class).is_none()); assert!(Class::common_base_class(&mid1_class, &mid2_class).is_none()); assert_eq!( Class::common_base_class(&mid2_class, &mid3_class) .unwrap() .unwrap(), root2_class ); assert_eq!( Class::common_base_class(&mid3_class, &mid2_class) .unwrap() .unwrap(), root2_class ); assert_eq!( Class::common_base_class(&leaf1_class, &mid1_class) .unwrap() .unwrap(), mid1_class ); assert_eq!( Class::common_base_class(&mid1_class, &leaf1_class) .unwrap() .unwrap(), mid1_class ); assert_eq!( Class::common_base_class(&leaf1_class, &mid2_class) .unwrap() .unwrap(), mid2_class ); assert_eq!( Class::common_base_class(&mid2_class, &leaf1_class) .unwrap() .unwrap(), mid2_class ); assert_eq!( Class::common_base_class(&leaf1_class, &leaf2_class) .unwrap() .unwrap(), root2_class ); assert_eq!( Class::common_base_class(&leaf2_class, &leaf1_class) .unwrap() .unwrap(), root2_class ); } #[test] fn attached_class() { let mut type_map = TypeMap::empty(); let module_id = ModuleId::Named("foo"); let mut module_data = ModuleData::default(); module_data.extend([ metatype::Class::new("FooAttached"), metatype::Class { class_name: "Foo".to_owned(), qualified_class_name: "Foo".to_owned(), class_infos: vec![metatype::ClassInfo::new("QML.Attached", "FooAttached")], ..Default::default() }, ]); type_map.insert_module(module_id, module_data); let module = type_map.get_module(module_id).unwrap(); let foo_class = unwrap_class(module.get_type("Foo")); let foo_attached_class = unwrap_class(module.get_type("FooAttached")); assert_eq!( foo_class.attached_class().unwrap().unwrap(), foo_attached_class ); } #[test] fn property_std_set() { let mut type_map = TypeMap::with_primitive_types(); let module_id = ModuleId::Named("foo"); let mut module_data = ModuleData::with_builtins(); module_data.extend([ metatype::Class { class_name: "Root".to_owned(), qualified_class_name: "Foo".to_owned(), properties: vec![ metatype::Property { name: "rootStd".to_owned(), r#type: "int".to_owned(), write: Some("setRootStd".to_owned()), ..Default::default() }, metatype::Property { name: "rootNoStd".to_owned(), r#type: "int".to_owned(), write: Some("setRootNoStdWriteFunc".to_owned()), ..Default::default() }, ], ..Default::default() }, metatype::Class { class_name: "Sub".to_owned(), qualified_class_name: "Sub".to_owned(), super_classes: vec![metatype::SuperClassSpecifier::public("Root")], properties: vec![ metatype::Property { name: "subStd".to_owned(), r#type: "int".to_owned(), write: Some("setSubStd".to_owned()), ..Default::default() }, metatype::Property { name: "subNoWrite".to_owned(), r#type: "int".to_owned(), write: None, ..Default::default() }, ], ..Default::default() }, ]); type_map.insert_module(module_id, module_data); let module = type_map.get_module(module_id).unwrap(); let sub_class = unwrap_class(module.get_type("Sub")); assert!(sub_class .get_property("rootStd") .unwrap() .unwrap() .is_std_set()); assert!(!sub_class .get_property("rootNoStd") .unwrap() .unwrap() .is_std_set()); assert!(sub_class .get_property("subStd") .unwrap() .unwrap() .is_std_set()); assert!(!sub_class .get_property("subNoWrite") .unwrap() .unwrap() .is_std_set()); } #[test] fn property_method() { let mut type_map = TypeMap::with_primitive_types(); let module_id = ModuleId::Named("foo"); let mut module_data = ModuleData::with_builtins(); module_data.extend([metatype::Class { class_name: "Foo".to_owned(), qualified_class_name: "Foo".to_owned(), properties: vec![ metatype::Property { name: "prop1".to_owned(), r#type: "int".to_owned(), read: Some("prop1".to_owned()), write: Some("setProp1".to_owned()), notify: Some("prop1Changed".to_owned()), ..Default::default() }, metatype::Property { name: "prop2".to_owned(), r#type: "int".to_owned(), read: Some("prop2".to_owned()), write: Some("setProp2".to_owned()), notify: Some("prop2Changed".to_owned()), ..Default::default() }, ], signals: vec![ metatype::Method::nullary("prop1Changed", "void"), // prop2Changed(int = default_value), prop2Changed(QString, int) metatype::Method::with_argument_types("prop2Changed", "void", ["int"]), metatype::Method::nullary("prop2Changed", "void"), metatype::Method::with_argument_types("prop2Changed", "void", ["QString", "int"]), ], ..Default::default() }]); type_map.insert_module(module_id, module_data); let module = type_map.get_module(module_id).unwrap(); let foo_class = unwrap_class(module.get_type("Foo")); let prop1 = foo_class.get_property("prop1").unwrap().unwrap(); let prop1_notify = prop1.notify_signal().unwrap().unwrap(); assert_eq!(prop1_notify.name(), "prop1Changed"); assert_eq!(prop1_notify.arguments_len(), 0); let prop2 = foo_class.get_property("prop2").unwrap().unwrap(); let prop2_notify = prop2.notify_signal().unwrap().unwrap(); assert_eq!(prop2_notify.name(), "prop2Changed"); assert_eq!(prop2_notify.arguments_len(), 1); assert_eq!( prop2_notify.argument_type(0), &TypeKind::Just(module.resolve_type("int").unwrap().unwrap()) ); } }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/typemap/core.rs
Rust
use super::enum_::Enum; use super::module::ModuleIdBuf; use super::{NamedType, ParentSpace}; use itertools::Itertools as _; use std::borrow::Cow; use std::iter::FusedIterator; use thiserror::Error; /// Interface to look up type by name. pub trait TypeSpace<'a> { /// Name of this type. fn name(&self) -> &str; /// Scoped C++ name of this type from the root namespace. /// /// This is designed for diagnostics, but can be embedded in the generated .ui file. fn qualified_cxx_name(&self) -> Cow<'_, str> { make_qualified_name(self, "::") } /// Looks up type by name. /// /// If this type is a class, the returned type may be inherited from one of the super classes. fn get_type(&self, name: &str) -> Option<Result<NamedType<'a>, TypeMapError>>; /// Looks up type by scoped name. fn get_type_scoped(&self, scoped_name: &str) -> Option<Result<NamedType<'a>, TypeMapError>> { // no support for the ::<top-level> notation let mut parts = scoped_name.split("::"); let head = self.get_type(parts.next().expect("split should have at least one name")); parts.fold(head, |outer, name| match outer { Some(Ok(ty)) => ty.get_type(name), Some(Err(_)) | None => outer, }) } /// Parent space of this type. /// /// This is unrelated to the super type of the class inheritance. #[doc(hidden)] fn lexical_parent(&self) -> Option<&ParentSpace<'a>>; /// Looks up type by name from this towards the parent type space. fn resolve_type(&self, name: &str) -> Option<Result<NamedType<'a>, TypeMapError>> { self.get_type(name) .or_else(|| LexicalAncestorSpaces::new(self).find_map(|ty| ty.get_type(name))) } /// Looks up type by scoped name from this towards the parent type space. fn resolve_type_scoped( &self, scoped_name: &str, ) -> Option<Result<NamedType<'a>, TypeMapError>> { // no support for the ::<top-level> notation let mut parts = scoped_name.split("::"); let head = self.resolve_type(parts.next().expect("split should have at least one name")); // "resolve" only the first node. the remainder should be direct child. parts.fold(head, |outer, name| match outer { Some(Ok(ty)) => ty.get_type(name), Some(Err(_)) | None => outer, }) } /// Looks up enum type by variant name. /// /// The returned type is not an abstract [`NamedType`] since Qt metatype does not support /// an arbitrary static constant. fn get_enum_by_variant(&self, name: &str) -> Option<Result<Enum<'a>, TypeMapError>>; } /// Iterator to walk up the type tree. /// /// This is basically a [`std::iter::successors()`] iterator with slightly different lifetime /// requirement. #[derive(Clone, Debug)] struct LexicalAncestorSpaces<'a, 'b> { next_ty: Option<&'b ParentSpace<'a>>, } impl<'a, 'b> LexicalAncestorSpaces<'a, 'b> { fn new<T>(ty: &'b T) -> Self where T: TypeSpace<'a> + ?Sized, { LexicalAncestorSpaces { next_ty: ty.lexical_parent(), } } } impl<'a, 'b> Iterator for LexicalAncestorSpaces<'a, 'b> { type Item = &'b ParentSpace<'a>; fn next(&mut self) -> Option<Self::Item> { let ty = self.next_ty; self.next_ty = ty.and_then(|t| t.lexical_parent()); ty } fn size_hint(&self) -> (usize, Option<usize>) { if self.next_ty.is_some() { (1, None) } else { (0, Some(0)) } } } impl FusedIterator for LexicalAncestorSpaces<'_, '_> {} /// Error denoting inconsistency in the [`TypeMap`](super::TypeMap). #[derive(Clone, Debug, Error)] pub enum TypeMapError { #[error("invalid module reference '{0:?}'")] InvalidModuleRef(ModuleIdBuf), #[error("invalid type reference '{0}'")] InvalidTypeRef(String), #[error("invalid type '{0}' as a super class")] InvalidSuperClassType(String), #[error("invalid type '{0}' as an alias enum")] InvalidAliasEnumType(String), #[error("invalid notify signal '{0}'")] InvalidNotifySignal(String), #[error("invalid QML component '{0}' in non-module space '{1}'")] InvalidQmlComponentSpace(String, String), #[error("unsupported type decoration in '{0}'")] UnsupportedDecoration(String), } /// Builds a qualified type name by walking up the type tree. fn make_qualified_name<'a, 'b, T>(ty: &'b T, sep: &str) -> Cow<'b, str> where T: TypeSpace<'a> + ?Sized, { let mut names = collect_ancestor_names(LexicalAncestorSpaces::new(ty)); if names.is_empty() { Cow::Borrowed(ty.name()) } else { names.push(ty.name()); Cow::Owned(names.join(sep)) } } fn collect_ancestor_names<'b>(ancestors: LexicalAncestorSpaces<'_, 'b>) -> Vec<&'b str> { let mut names = Vec::new(); for (ty, p) in ancestors.tuple_windows() { match (ty, p) { (ParentSpace::Namespace(_), ParentSpace::ImportedModuleSpace(_)) => { break; // root namespace } _ => { names.push(ty.name()); } } } names.reverse(); names }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/typemap/enum_.rs
Rust
use super::core::{TypeMapError, TypeSpace}; use super::util::TypeDataRef; use super::{NamedType, ParentSpace}; use crate::metatype; use std::collections::HashSet; /// Enum representation. #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub struct Enum<'a> { data: TypeDataRef<'a, EnumData>, parent_space: ParentSpace<'a>, } /// Stored enum representation. #[derive(Clone, Debug)] pub(super) struct EnumData { name: String, alias: Option<String>, is_class: bool, is_flag: bool, variants: Vec<String>, variant_set: HashSet<String>, } impl<'a> Enum<'a> { pub(super) fn new(data: TypeDataRef<'a, EnumData>, parent_space: ParentSpace<'a>) -> Self { Enum { data, parent_space } } pub fn alias_enum(&self) -> Option<Result<Enum<'a>, TypeMapError>> { self.data .as_ref() .alias .as_ref() .map(|n| match self.parent_space.resolve_type_scoped(n) { Some(Ok(NamedType::Enum(x))) => Ok(x), Some(Ok(_)) => Err(TypeMapError::InvalidAliasEnumType(n.to_owned())), Some(Err(e)) => Err(e), None => Err(TypeMapError::InvalidTypeRef(n.to_owned())), }) } pub fn is_scoped(&self) -> bool { self.data.as_ref().is_class } pub fn is_flag(&self) -> bool { self.data.as_ref().is_flag } pub fn variants(&self) -> impl Iterator<Item = &str> { self.data.as_ref().variants.iter().map(String::as_str) } pub fn contains_variant(&self, name: &str) -> bool { self.data.as_ref().variant_set.contains(name) } pub fn qualify_cxx_variant_name(&self, name: &str) -> String { if self.is_scoped() { format!("{}::{}", self.qualified_cxx_name(), name) } else if let Some(p) = self.lexical_parent() { format!("{}::{}", p.qualified_cxx_name(), name) } else { // enum should have a parent space, but if there were none, returning the variant // name would make sense. name.to_owned() } } } impl<'a> TypeSpace<'a> for Enum<'a> { fn name(&self) -> &str { &self.data.as_ref().name } fn get_type(&self, _name: &str) -> Option<Result<NamedType<'a>, TypeMapError>> { None } fn lexical_parent(&self) -> Option<&ParentSpace<'a>> { Some(&self.parent_space) } fn get_enum_by_variant(&self, name: &str) -> Option<Result<Enum<'a>, TypeMapError>> { if self.is_scoped() && self.contains_variant(name) { Some(Ok(self.clone())) } else { None } } } impl EnumData { pub(super) fn from_meta(meta: metatype::Enum) -> Self { let variant_set = HashSet::from_iter(meta.values.iter().cloned()); EnumData { name: meta.name, alias: meta.alias, is_class: meta.is_class, is_flag: meta.is_flag, variants: meta.values, variant_set, } } pub(super) fn unscoped_variants(&self) -> Option<&[String]> { if self.is_class { None } else { Some(&self.variants) } } }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/typemap/function.rs
Rust
use super::class::Class; use super::core::{TypeMapError, TypeSpace as _}; use super::util::{self, TypeDataRef}; use super::TypeKind; use crate::metatype; use std::slice; use std::vec; /// Stored method table wrapper to help name-based lookup. #[derive(Clone, Debug, Default)] pub(super) struct MethodDataTable { methods: Vec<MethodData>, } impl MethodDataTable { pub(super) fn from_meta<I>(meta_iter: I, access: metatype::AccessSpecifier) -> Self where I: IntoIterator<Item = (Vec<metatype::Method>, MethodKind)>, { let mut methods: Vec<_> = meta_iter .into_iter() .flat_map(|(ms, k)| { ms.into_iter() .filter_map(move |m| (m.access == access).then(|| MethodData::from_meta(m, k))) }) .collect(); methods.sort_by(|a, b| a.name.cmp(&b.name)); // so we can do binary search MethodDataTable { methods } } pub(super) fn get_method_with<'a>( &'a self, name: &str, mut make_object_class: impl FnMut() -> Class<'a>, ) -> Option<Result<MethodMatches<'a>, TypeMapError>> { let start = self.methods.partition_point(|d| d.name.as_str() < name); assert!(start <= self.methods.len()); let count = self.methods[start..] .iter() .take_while(|d| d.name == name) .count(); match count { 0 => None, 1 => { let r = Method::new(TypeDataRef(&self.methods[start]), make_object_class()) .map(MethodMatches::Unique); Some(r) } _ => { let r = self.methods[start..start + count] .iter() .map(|d| Method::new(TypeDataRef(d), make_object_class())) .collect::<Result<Vec<_>, _>>() .map(MethodMatches::Overloaded); Some(r) } } } } /// Method representation. /// /// All type information is resolved when the `Method` object is created, so you don't /// have to deal with `TypeMapError` later. #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub struct Method<'a> { data: TypeDataRef<'a, MethodData>, return_type: TypeKind<'a>, argument_types: Vec<TypeKind<'a>>, object_class: Class<'a>, } /// Stored method representation. #[derive(Clone, Debug)] struct MethodData { name: String, kind: MethodKind, return_type_name: String, arguments: Vec<ArgumentData>, } /// Nature of the method. #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub enum MethodKind { Signal, Slot, Method, } #[derive(Clone, Debug)] struct ArgumentData { name: Option<String>, type_name: String, } impl<'a> Method<'a> { fn new( data: TypeDataRef<'a, MethodData>, object_class: Class<'a>, ) -> Result<Self, TypeMapError> { let make_type = |n| util::decorated_type(n, |n| object_class.resolve_type_scoped(n)); let return_type = make_type(&data.as_ref().return_type_name)?; let argument_types = data .as_ref() .arguments .iter() .map(|d| make_type(&d.type_name)) .collect::<Result<Vec<_>, _>>()?; Ok(Method { data, return_type, argument_types, object_class, }) } pub fn name(&self) -> &str { &self.data.as_ref().name } pub fn kind(&self) -> MethodKind { self.data.as_ref().kind } /// Type of the return value. pub fn return_type(&self) -> &TypeKind<'a> { &self.return_type } /// Type name of the return value. pub fn return_type_name(&self) -> &str { &self.data.as_ref().return_type_name } /// Number of the arguments. pub fn arguments_len(&self) -> usize { self.data.as_ref().arguments.len() } /// Name of the nth argument if available. pub fn argument_name(&self, index: usize) -> Option<&str> { self.data.as_ref().arguments[index].name.as_deref() } /// Type of the nth argument. pub fn argument_type(&self, index: usize) -> &TypeKind<'a> { &self.argument_types[index] } /// Type name of the nth argument. pub fn argument_type_name(&self, index: usize) -> &str { &self.data.as_ref().arguments[index].type_name } /// Type of arguments in order. pub fn argument_types(&self) -> &[TypeKind<'a>] { &self.argument_types } /// Type of the object which this method is associated with. pub fn object_class(&self) -> &Class<'a> { &self.object_class } } impl MethodData { fn from_meta(meta: metatype::Method, kind: MethodKind) -> Self { let arguments = meta .arguments .into_iter() .map(|m| ArgumentData { name: m.name, type_name: m.r#type, }) .collect(); MethodData { name: meta.name, kind, return_type_name: meta.return_type, arguments, } } } /// Methods found by name. #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub enum MethodMatches<'a> { Unique(Method<'a>), Overloaded(Vec<Method<'a>>), } impl<'a> MethodMatches<'a> { /// Returns true if this method isn't overloaded. pub fn is_unique(&self) -> bool { matches!(self, MethodMatches::Unique(_)) } pub fn as_unique(&self) -> Option<&Method<'a>> { match self { MethodMatches::Unique(m) => Some(m), MethodMatches::Overloaded(_) => None, } } pub fn into_unique(self) -> Option<Method<'a>> { match self { MethodMatches::Unique(m) => Some(m), MethodMatches::Overloaded(_) => None, } } #[allow(clippy::len_without_is_empty)] // should never be empty pub fn len(&self) -> usize { self.as_slice().len() } pub fn iter(&self) -> slice::Iter<'_, Method<'a>> { self.as_slice().iter() } pub fn as_slice(&self) -> &[Method<'a>] { match self { MethodMatches::Unique(m) => slice::from_ref(m), MethodMatches::Overloaded(ms) => ms, } } pub fn into_vec(self) -> Vec<Method<'a>> { match self { MethodMatches::Unique(m) => vec![m], MethodMatches::Overloaded(ms) => ms, } } } impl<'a> IntoIterator for MethodMatches<'a> { type Item = Method<'a>; type IntoIter = vec::IntoIter<Method<'a>>; fn into_iter(self) -> Self::IntoIter { self.into_vec().into_iter() } } #[cfg(test)] mod tests { use super::super::{ModuleData, ModuleId, NamedType, TypeMap}; use super::*; use crate::metatype; fn unwrap_class(r: Option<Result<NamedType, TypeMapError>>) -> Class { match r { Some(Ok(NamedType::Class(x))) => x, _ => panic!("unexpected type: {r:?}"), } } #[test] fn method_lookup() { let mut type_map = TypeMap::with_primitive_types(); let module_id = ModuleId::Named("foo"); let mut module_data = ModuleData::with_builtins(); module_data.extend([ metatype::Class { class_name: "Root".to_owned(), qualified_class_name: "Root".to_owned(), signals: vec![metatype::Method::nullary("signal0", "void")], slots: vec![metatype::Method::nullary("slot0", "void")], methods: vec![ metatype::Method::nullary("overloaded0", "void"), metatype::Method::with_argument_types("overloaded0", "void", ["int"]), ], ..Default::default() }, metatype::Class::with_supers("Sub", ["Root"]), ]); type_map.insert_module(module_id, module_data); let module = type_map.get_module(module_id).unwrap(); let root_class = unwrap_class(module.get_type("Root")); let sub_class = unwrap_class(module.get_type("Sub")); let m = root_class.get_public_method("signal0").unwrap().unwrap(); assert!(m.is_unique()); assert_eq!(m.as_unique().unwrap().name(), "signal0"); assert_eq!(m.as_unique().unwrap().kind(), MethodKind::Signal); let m = sub_class.get_public_method("slot0").unwrap().unwrap(); assert!(m.is_unique()); assert_eq!(m.as_unique().unwrap().name(), "slot0"); assert_eq!(m.as_unique().unwrap().kind(), MethodKind::Slot); let m = root_class .get_public_method("overloaded0") .unwrap() .unwrap(); assert!(!m.is_unique()); assert_eq!(m.len(), 2); assert!(m.iter().all(|m| m.name() == "overloaded0")); assert!(m.iter().all(|m| m.kind() == MethodKind::Method)); assert!(root_class.get_public_method("a").is_none()); assert!(root_class.get_public_method("z").is_none()); assert!(sub_class.get_public_method("a").is_none()); assert!(sub_class.get_public_method("z").is_none()); } }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/typemap/mod.rs
Rust
//! Manages types loaded from Qt metatypes.json. use camino::Utf8PathBuf; use std::borrow::Cow; use std::collections::HashMap; use std::fmt; use std::mem; mod class; mod core; mod enum_; mod function; mod module; mod namespace; mod primitive; mod qml_component; mod util; pub use self::class::*; // re-export pub use self::core::*; // re-export pub use self::enum_::*; // re-export pub use self::function::*; // re-export pub use self::module::*; // re-export pub use self::namespace::*; // re-export pub use self::primitive::*; // re-export pub use self::qml_component::*; // re-export use self::util::TypeMapRef; /// Storage to map type name to class or enum representation. #[derive(Debug)] pub struct TypeMap { builtins: ModuleData, named_module_map: HashMap<String, ModuleData>, directory_module_map: HashMap<Utf8PathBuf, ModuleData>, } impl TypeMap { /// Creates empty type map. pub fn empty() -> Self { TypeMap { builtins: ModuleData::default(), named_module_map: HashMap::default(), directory_module_map: HashMap::default(), } } /// Creates type map containing the primitive types. pub fn with_primitive_types() -> Self { let mut builtins = ModuleData::with_namespace(NamespaceData::with_primitive_types(&PrimitiveType::ALL)); builtins.push_alias("qreal", "double").unwrap(); TypeMap { builtins, named_module_map: HashMap::default(), directory_module_map: HashMap::default(), } } /// Checks if the specified module exists. pub fn contains_module(&self, id: ModuleId) -> bool { match id { ModuleId::Builtins => true, ModuleId::Named(name) => self.named_module_map.contains_key(name), ModuleId::Directory(path) => self.directory_module_map.contains_key(path), } } /// Looks up module by identifier. pub fn get_module<'a>(&'a self, id: ModuleId) -> Option<Namespace<'a>> { match id { ModuleId::Builtins => Some(self.builtins.to_namespace(TypeMapRef(self))), ModuleId::Named(name) => self .named_module_map .get(name) .map(|d| d.to_namespace(TypeMapRef(self))), ModuleId::Directory(path) => self .directory_module_map .get(path) .map(|d| d.to_namespace(TypeMapRef(self))), } } /// Looks up mutable module data by identifier. pub fn get_module_data<'a>(&'a self, id: ModuleId) -> Option<&'a ModuleData> { match id { ModuleId::Builtins => Some(&self.builtins), ModuleId::Named(name) => self.named_module_map.get(name), ModuleId::Directory(path) => self.directory_module_map.get(path), } } /// Looks up mutable module data by identifier. pub fn get_module_data_mut<'a>(&'a mut self, id: ModuleId) -> Option<&'a mut ModuleData> { match id { ModuleId::Builtins => Some(&mut self.builtins), ModuleId::Named(name) => self.named_module_map.get_mut(name), ModuleId::Directory(path) => self.directory_module_map.get_mut(path), } } /// Inserts new module. pub fn insert_module<S>(&mut self, id: S, data: ModuleData) -> Option<ModuleData> where S: Into<ModuleIdBuf>, { match id.into() { ModuleIdBuf::Builtins => Some(mem::replace(&mut self.builtins, data)), ModuleIdBuf::Named(name) => self.named_module_map.insert(name, data), ModuleIdBuf::Directory(path) => self.directory_module_map.insert(path, data), } } } /// Type variants returned by [`TypeMap`]. #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub enum NamedType<'a> { Class(Class<'a>), Enum(Enum<'a>), Namespace(Namespace<'a>), Primitive(PrimitiveType), QmlComponent(QmlComponent<'a>), } impl<'a> NamedType<'a> { /// Returns true if this type is supposed to be passed by `const T &`. fn is_const_ref_preferred(&self) -> bool { match self { NamedType::Class(_) => true, NamedType::Enum(_) => false, NamedType::Namespace(_) => false, // invalid NamedType::Primitive(pt) => pt.is_const_ref_preferred(), NamedType::QmlComponent(_) => true, } } /// Turns this into class representation if supported by the underlying type. pub fn into_class(self) -> Option<Class<'a>> { match self { NamedType::Class(cls) => Some(cls), NamedType::Enum(_) => None, NamedType::Namespace(_) => None, NamedType::Primitive(pt) => pt.to_class(), NamedType::QmlComponent(ns) => Some(ns.into_class()), } } } impl<'a> TypeSpace<'a> for NamedType<'a> { fn name(&self) -> &str { match self { NamedType::Class(cls) => cls.name(), NamedType::Enum(en) => en.name(), NamedType::Namespace(ns) => ns.name(), NamedType::Primitive(pt) => pt.name(), NamedType::QmlComponent(_) => "", } } fn get_type(&self, name: &str) -> Option<Result<NamedType<'a>, TypeMapError>> { match self { NamedType::Class(cls) => cls.get_type(name), NamedType::Enum(_) => None, NamedType::Namespace(ns) => ns.get_type(name), NamedType::Primitive(_) => None, NamedType::QmlComponent(_) => None, } } fn lexical_parent(&self) -> Option<&ParentSpace<'a>> { match self { NamedType::Class(cls) => cls.lexical_parent(), NamedType::Enum(en) => en.lexical_parent(), NamedType::Namespace(ns) => ns.lexical_parent(), NamedType::Primitive(_) => None, NamedType::QmlComponent(_) => None, } } fn get_enum_by_variant(&self, name: &str) -> Option<Result<Enum<'a>, TypeMapError>> { match self { NamedType::Class(cls) => cls.get_enum_by_variant(name), NamedType::Enum(en) => en.get_enum_by_variant(name), NamedType::Namespace(ns) => ns.get_enum_by_variant(name), NamedType::Primitive(_) => None, NamedType::QmlComponent(_) => None, } } } /// Type variants for parent space. #[derive(Clone, Eq, Hash, PartialEq)] #[doc(hidden)] // this is implementation detail, but exposed by TypeSpace trait pub enum ParentSpace<'a> { Class(Class<'a>), ImportedModuleSpace(ImportedModuleSpace<'a>), Namespace(Namespace<'a>), } impl<'a> TypeSpace<'a> for ParentSpace<'a> { fn name(&self) -> &str { match self { ParentSpace::Class(cls) => cls.name(), ParentSpace::ImportedModuleSpace(ns) => ns.name(), ParentSpace::Namespace(ns) => ns.name(), } } fn get_type(&self, name: &str) -> Option<Result<NamedType<'a>, TypeMapError>> { match self { ParentSpace::Class(cls) => cls.get_type(name), ParentSpace::ImportedModuleSpace(ns) => ns.get_type(name), ParentSpace::Namespace(ns) => ns.get_type(name), } } fn lexical_parent(&self) -> Option<&ParentSpace<'a>> { match self { ParentSpace::Class(cls) => cls.lexical_parent(), ParentSpace::ImportedModuleSpace(ns) => ns.lexical_parent(), ParentSpace::Namespace(ns) => ns.lexical_parent(), } } fn get_enum_by_variant(&self, name: &str) -> Option<Result<Enum<'a>, TypeMapError>> { match self { ParentSpace::Class(cls) => cls.get_enum_by_variant(name), ParentSpace::ImportedModuleSpace(ns) => ns.get_enum_by_variant(name), ParentSpace::Namespace(ns) => ns.get_enum_by_variant(name), } } } impl fmt::Debug for ParentSpace<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // don't print ancestor contents recursively, which would be quite noisy match self { Self::Class(cls) => f .debug_tuple("Class") .field(&format_args!("{:?}", cls.qualified_cxx_name())) .finish(), Self::ImportedModuleSpace(ns) => f .debug_tuple("ImportedModuleSpace") .field(&format_args!("{:?}", ns.qualified_cxx_name())) .finish(), Self::Namespace(ns) => f .debug_tuple("Namespace") .field(&format_args!("{:?}", ns.qualified_cxx_name())) .finish(), } } } /// Type of variables, properties, function arguments, etc. #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub enum TypeKind<'a> { /// Just a named (or value) type. /// /// The type should be a [`PrimitiveType`], [`Enum`], or gadget [`Class`]. Just(NamedType<'a>), /// Pointer to a named object type. /// /// The type should be an object [`Class`]. It's unlikely we'll support a pointer to /// a value type. Pointer(NamedType<'a>), /// List of the given (possibly nested) type. List(Box<TypeKind<'a>>), } impl<'a> TypeKind<'a> { pub const BOOL: Self = TypeKind::Just(NamedType::Primitive(PrimitiveType::Bool)); pub const DOUBLE: Self = TypeKind::Just(NamedType::Primitive(PrimitiveType::Double)); pub const INT: Self = TypeKind::Just(NamedType::Primitive(PrimitiveType::Int)); pub const UINT: Self = TypeKind::Just(NamedType::Primitive(PrimitiveType::Uint)); pub const STRING: Self = TypeKind::Just(NamedType::Primitive(PrimitiveType::QString)); pub const VARIANT: Self = TypeKind::Just(NamedType::Primitive(PrimitiveType::QVariant)); pub const VOID: Self = TypeKind::Just(NamedType::Primitive(PrimitiveType::Void)); /// Returns true if this type is supposed to be passed by `const T &`. pub fn is_const_ref_preferred(&self) -> bool { match self { TypeKind::Just(ty) => ty.is_const_ref_preferred(), TypeKind::Pointer(_) => false, TypeKind::List(_) => true, } } pub fn is_pointer(&self) -> bool { match self { TypeKind::Just(_) => false, TypeKind::Pointer(_) => true, TypeKind::List(_) => false, } } pub fn qualified_cxx_name(&self) -> Cow<'_, str> { match self { TypeKind::Just(ty) => ty.qualified_cxx_name(), TypeKind::Pointer(ty) => ty.qualified_cxx_name() + "*", TypeKind::List(ty) => match ty.as_ref() { // see also util::decorated_type() &TypeKind::STRING => "QStringList".into(), _ => format!("QList<{}>", ty.qualified_cxx_name()).into(), }, } } /// Turns this into class representation if supported by the underlying value/pointer type. /// /// Be aware that the returned class represents the inner type, not the pointer type if /// this is a pointer. pub fn into_class(self) -> Option<Class<'a>> { match self { TypeKind::Just(ty) => ty.into_class(), TypeKind::Pointer(ty) => ty.into_class(), TypeKind::List(_) => { // name should be unqualified<qualified>, but we know 'QList<>' has no scope Some(primitive::make_list_class(self.qualified_cxx_name())) } } } } #[cfg(test)] mod tests { use super::*; use crate::metatype; fn unwrap_class(r: Option<Result<NamedType, TypeMapError>>) -> Class { match r { Some(Ok(NamedType::Class(x))) => x, _ => panic!("unexpected type: {r:?}"), } } fn unwrap_enum(r: Option<Result<NamedType, TypeMapError>>) -> Enum { match r { Some(Ok(NamedType::Enum(x))) => x, _ => panic!("unexpected type: {r:?}"), } } #[test] fn type_eq() { let mut type_map = TypeMap::empty(); let module_id = ModuleId::Named("foo"); type_map.insert_module(module_id, ModuleData::with_builtins()); let module_data = type_map.get_module_data_mut(module_id).unwrap(); module_data.extend([metatype::Class::new("Foo"), metatype::Class::new("Bar")]); module_data.extend([metatype::Enum::new("Baz")]); let module = type_map.get_module(module_id).unwrap(); assert_eq!( module.get_type("Foo").unwrap().unwrap(), module.get_type("Foo").unwrap().unwrap() ); assert_ne!( module.get_type("Foo").unwrap().unwrap(), module.get_type("Bar").unwrap().unwrap() ); assert_ne!( module.get_type("Foo").unwrap().unwrap(), module.get_type("Baz").unwrap().unwrap() ); assert_eq!( module.get_type("Baz").unwrap().unwrap(), module.get_type("Baz").unwrap().unwrap() ); } #[test] fn named_module() { let mut type_map = TypeMap::with_primitive_types(); let module_id = ModuleId::Named("foo"); type_map.insert_module(module_id, ModuleData::with_builtins()); type_map .get_module_data_mut(module_id) .unwrap() .extend([metatype::Class::new("Foo")]); let module = type_map.get_module(module_id).unwrap(); assert!(module.get_type("Foo").is_some()); assert!( module.get_type("int").is_none(), "imported type not in namespace" ); } #[test] fn aliased_type() { let mut type_map = TypeMap::with_primitive_types(); let module_id = ModuleId::Named("foo"); let mut module_data = ModuleData::default(); module_data.extend([metatype::Class::new("Foo")]); module_data.push_alias("aliased_foo", "Foo").unwrap(); type_map.insert_module(module_id, module_data); let module = type_map.get_module(module_id).unwrap(); // generic type alias is purely an alias. no new type wouldn't be created. assert_eq!( module.get_type("aliased_foo").unwrap().unwrap(), module.get_type_scoped("Foo").unwrap().unwrap() ); } #[test] fn aliased_enum_eq() { let mut type_map = TypeMap::empty(); let module_id = ModuleId::Named("foo"); type_map.insert_module(module_id, ModuleData::with_builtins()); type_map.get_module_data_mut(module_id).unwrap().extend([ metatype::Enum::new("Foo"), metatype::Enum::new_flag("Foos", "Foo"), ]); let module = type_map.get_module(module_id).unwrap(); // unlike generic type alias, aliased enum (or flag) is a separate type. assert_eq!( unwrap_enum(module.get_type("Foos")) .alias_enum() .unwrap() .unwrap(), unwrap_enum(module.get_type("Foo")) ); } #[test] fn qualified_cxx_name() { let mut type_map = TypeMap::with_primitive_types(); let module_id = ModuleId::Named("foo"); type_map.insert_module(module_id, ModuleData::with_builtins()); let mut foo_meta = metatype::Class::new("Foo"); foo_meta.enums.push(metatype::Enum::new("Bar")); type_map .get_module_data_mut(module_id) .unwrap() .extend([foo_meta]); let module = type_map.get_module(module_id).unwrap(); assert_eq!( module .resolve_type("int") .unwrap() .unwrap() .qualified_cxx_name(), "int" ); let foo_type = module.get_type("Foo").unwrap().unwrap(); assert_eq!(foo_type.qualified_cxx_name(), "Foo"); assert_eq!( foo_type .get_type("Bar") .unwrap() .unwrap() .qualified_cxx_name(), "Foo::Bar" ); } #[test] fn get_type_of_root() { let mut type_map = TypeMap::with_primitive_types(); let module_id = ModuleId::Named("foo"); type_map.insert_module(module_id, ModuleData::with_builtins()); type_map .get_module_data_mut(module_id) .unwrap() .extend([metatype::Class::new("Foo")]); let module = type_map.get_module(module_id).unwrap(); assert_eq!( module.resolve_type("int").unwrap().unwrap(), NamedType::Primitive(PrimitiveType::Int) ); let foo_class = unwrap_class(module.get_type("Foo")); assert!(foo_class.get_type("int").is_none()); assert_eq!( foo_class.resolve_type("int").unwrap().unwrap(), NamedType::Primitive(PrimitiveType::Int) ); } #[test] fn get_type_of_root_scoped() { let mut type_map = TypeMap::with_primitive_types(); let module_id = ModuleId::Named("foo"); type_map.insert_module(module_id, ModuleData::with_builtins()); let mut foo_meta = metatype::Class::new("Foo"); foo_meta.enums.push(metatype::Enum::new("Bar")); type_map .get_module_data_mut(module_id) .unwrap() .extend([foo_meta]); let module = type_map.get_module(module_id).unwrap(); let foo_class = unwrap_class(module.get_type("Foo")); assert_eq!( module.get_type_scoped("Foo").unwrap().unwrap(), module.get_type("Foo").unwrap().unwrap() ); assert_eq!( module.get_type_scoped("Foo::Bar").unwrap().unwrap(), foo_class.get_type("Bar").unwrap().unwrap() ); assert!(foo_class.get_type_scoped("Foo::Bar").is_none()); assert_eq!( foo_class.resolve_type_scoped("Foo::Bar").unwrap().unwrap(), foo_class.get_type("Bar").unwrap().unwrap() ); } #[test] fn do_not_resolve_intermediate_type_scoped() { let mut type_map = TypeMap::with_primitive_types(); let module_id = ModuleId::Named("foo"); type_map.insert_module(module_id, ModuleData::with_builtins()); type_map .get_module_data_mut(module_id) .unwrap() .extend([metatype::Class::new("Foo")]); let module = type_map.get_module(module_id).unwrap(); let foo_class = unwrap_class(module.get_type("Foo")); assert!(foo_class.resolve_type_scoped("int").is_some()); assert_eq!( unwrap_class(foo_class.resolve_type_scoped("Foo")), foo_class ); assert!(foo_class.resolve_type_scoped("Foo::int").is_none()); } #[test] fn get_super_class_type() { let mut type_map = TypeMap::with_primitive_types(); let module_id = ModuleId::Named("foo"); type_map.insert_module(module_id, ModuleData::with_builtins()); let mut root_meta = metatype::Class::new("Root"); root_meta.enums.push(metatype::Enum::new("RootEnum")); type_map.get_module_data_mut(module_id).unwrap().extend([ root_meta, metatype::Class::with_supers("Sub1", ["Root"]), metatype::Class::with_supers("Sub2", ["Sub1"]), ]); let module = type_map.get_module(module_id).unwrap(); let root_class = unwrap_class(module.get_type("Root")); let sub2_class = unwrap_class(module.get_type("Sub2")); assert_eq!( sub2_class.get_type("RootEnum").unwrap().unwrap(), root_class.get_type("RootEnum").unwrap().unwrap() ); assert_eq!( module.get_type_scoped("Sub2::RootEnum").unwrap().unwrap(), root_class.get_type("RootEnum").unwrap().unwrap() ); } #[test] fn class_derived_from() { let mut type_map = TypeMap::with_primitive_types(); let module_id = ModuleId::Named("foo"); type_map.insert_module(module_id, ModuleData::with_builtins()); type_map.get_module_data_mut(module_id).unwrap().extend([ metatype::Class::new("Root"), metatype::Class::with_supers("Sub1", ["Root"]), metatype::Class::with_supers("Sub2", ["Sub1"]), metatype::Class::with_supers("Sub3", ["Root"]), ]); let module = type_map.get_module(module_id).unwrap(); let root_class = unwrap_class(module.get_type("Root")); let sub1_class = unwrap_class(module.get_type("Sub1")); let sub2_class = unwrap_class(module.get_type("Sub2")); let sub3_class = unwrap_class(module.get_type("Sub3")); assert!(root_class.is_derived_from(&root_class)); assert!(sub1_class.is_derived_from(&root_class)); assert!(sub2_class.is_derived_from(&root_class)); assert!(sub3_class.is_derived_from(&root_class)); assert!(!sub3_class.is_derived_from(&sub1_class)); assert!(!sub3_class.is_derived_from(&sub2_class)); assert!(!root_class.is_derived_from(&sub1_class)); } #[test] fn get_type_of_property() { let mut type_map = TypeMap::with_primitive_types(); let module_id = ModuleId::Named("foo"); type_map.insert_module(module_id, ModuleData::with_builtins()); let mut foo_meta = metatype::Class::new("Foo"); foo_meta .properties .push(metatype::Property::new("foo_prop", "int")); let mut bar_meta = metatype::Class::with_supers("Bar", ["Foo"]); bar_meta .properties .push(metatype::Property::new("bar_prop", "bool")); type_map .get_module_data_mut(module_id) .unwrap() .extend([foo_meta, bar_meta]); let module = type_map.get_module(module_id).unwrap(); let bar_class = unwrap_class(module.get_type("Bar")); assert_eq!( bar_class .get_property("bar_prop") .unwrap() .unwrap() .value_type(), &TypeKind::Just(module.resolve_type("bool").unwrap().unwrap()) ); assert_eq!( bar_class .get_property("foo_prop") .unwrap() .unwrap() .value_type(), &TypeKind::Just(module.resolve_type("int").unwrap().unwrap()) ); } #[test] fn get_type_of_property_decorated() { let mut type_map = TypeMap::empty(); let module_id = ModuleId::Named("foo"); let mut module_data = ModuleData::with_builtins(); let mut foo_meta = metatype::Class::new("Foo"); foo_meta.properties.extend([ metatype::Property::new("pointer", "Foo*"), metatype::Property::new("pointer_list", "QList<Foo*>"), metatype::Property::new("pointer_vector", "QVector<Foo*>"), ]); module_data.extend([foo_meta]); type_map.insert_module(module_id, module_data); let module = type_map.get_module(module_id).unwrap(); let foo_class = unwrap_class(module.get_type("Foo")); assert_eq!( foo_class .get_property("pointer") .unwrap() .unwrap() .value_type(), &TypeKind::Pointer(NamedType::Class(foo_class.clone())) ); assert_eq!( foo_class .get_property("pointer_list") .unwrap() .unwrap() .value_type(), &TypeKind::List(Box::new(TypeKind::Pointer(NamedType::Class( foo_class.clone() )))) ); assert_eq!( foo_class .get_property("pointer_vector") .unwrap() .unwrap() .value_type(), &TypeKind::List(Box::new(TypeKind::Pointer(NamedType::Class( foo_class.clone() )))) ); } #[test] fn get_enum_by_variant() { let mut type_map = TypeMap::empty(); let module_id = ModuleId::Named("foo"); type_map.insert_module(module_id, ModuleData::with_builtins()); let mut foo_meta = metatype::Class::new("Foo"); let unscoped_meta = metatype::Enum::with_values("Unscoped", ["X", "Y"]); let mut scoped_meta = metatype::Enum::with_values("Scoped", ["A", "Y"]); scoped_meta.is_class = true; foo_meta.enums.extend([unscoped_meta, scoped_meta]); type_map .get_module_data_mut(module_id) .unwrap() .extend([foo_meta]); let module = type_map.get_module(module_id).unwrap(); let foo_class = unwrap_class(module.get_type("Foo")); let unscoped_enum = unwrap_enum(foo_class.get_type("Unscoped")); assert_eq!( foo_class.get_enum_by_variant("X").unwrap().unwrap(), unscoped_enum ); assert_eq!( foo_class.get_enum_by_variant("Y").unwrap().unwrap(), unscoped_enum ); assert!(foo_class.get_enum_by_variant("A").is_none()); let scoped_enum = unwrap_enum(foo_class.get_type("Scoped")); assert!(unscoped_enum.get_enum_by_variant("X").is_none()); assert_eq!( scoped_enum.get_enum_by_variant("A").unwrap().unwrap(), scoped_enum ); } #[test] fn get_super_class_enum_by_variant() { let mut type_map = TypeMap::empty(); let module_id = ModuleId::Named("foo"); type_map.insert_module(module_id, ModuleData::with_builtins()); let mut foo_meta = metatype::Class::new("Foo"); let unscoped_meta = metatype::Enum::with_values("Unscoped", ["X", "Y"]); foo_meta.enums.extend([unscoped_meta]); let bar_meta = metatype::Class::with_supers("Bar", ["Foo"]); type_map .get_module_data_mut(module_id) .unwrap() .extend([foo_meta, bar_meta]); let module = type_map.get_module(module_id).unwrap(); let foo_class = unwrap_class(module.get_type("Bar")); let bar_class = unwrap_class(module.get_type("Bar")); let unscoped_enum = unwrap_enum(foo_class.get_type("Unscoped")); assert_eq!( bar_class.get_enum_by_variant("X").unwrap().unwrap(), unscoped_enum ); } }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/typemap/module.rs
Rust
use super::core::{TypeMapError, TypeSpace}; use super::enum_::Enum; use super::namespace::{Namespace, NamespaceData}; use super::util::{TypeDataRef, TypeMapRef}; use super::QmlComponentData; use super::{NamedType, ParentSpace, TypeMap}; use crate::metatype; use camino::{Utf8Path, Utf8PathBuf}; /// Top-level module identifier. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum ModuleId<'s> { /// Built-in types. Builtins, /// QML module which can be imported by (dotted) name. Named(&'s str), /// Directory containing QML files, which can be imported by string. /// /// The path must be normalized in a certain form. Typically it is an absolute path. Directory(&'s Utf8Path), } /// Owned `ModuleId`. #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub enum ModuleIdBuf { Builtins, Named(String), Directory(Utf8PathBuf), } impl ModuleIdBuf { pub fn as_ref(&self) -> ModuleId<'_> { match self { ModuleIdBuf::Builtins => ModuleId::Builtins, ModuleIdBuf::Named(name) => ModuleId::Named(name), ModuleIdBuf::Directory(path) => ModuleId::Directory(path), } } } impl From<ModuleId<'_>> for ModuleIdBuf { fn from(id: ModuleId<'_>) -> Self { match id { ModuleId::Builtins => ModuleIdBuf::Builtins, ModuleId::Named(name) => ModuleIdBuf::Named(name.to_owned()), ModuleId::Directory(path) => ModuleIdBuf::Directory(path.to_owned()), } } } /// Stored top-level namespace with imports list. #[derive(Clone, Debug, Default)] pub struct ModuleData { namespace: NamespaceData, imports: Vec<ModuleIdBuf>, } impl ModuleData { // TODO: redesign mutation API pub(super) fn with_namespace(namespace: NamespaceData) -> Self { ModuleData { namespace, imports: vec![], } } /// Creates new module storage with builtin imports. pub fn with_builtins() -> Self { ModuleData { namespace: NamespaceData::default(), imports: vec![ModuleIdBuf::Builtins], } } /// Adds the specified module to the import list from which type names will be resolved. pub fn import_module<S>(&mut self, id: S) where S: Into<ModuleIdBuf>, { self.imports.push(id.into()) } /// Makes type `old_name` in the same module be also found by the given `new_name`. pub fn push_alias<S, T>(&mut self, new_name: S, old_name: T) -> Result<(), TypeMapError> where S: Into<String>, T: AsRef<str>, { self.namespace.push_alias(new_name, old_name) } pub fn push_qml_component(&mut self, data: QmlComponentData) { self.namespace.push_qml_component(data); } pub(super) fn to_namespace<'a>( self: &'a ModuleData, type_map: TypeMapRef<'a>, ) -> Namespace<'a> { let imported_space = ImportedModuleSpace::from_modules(&self.imports, type_map); Namespace::with_type_map( TypeDataRef(&self.namespace), type_map, ParentSpace::ImportedModuleSpace(imported_space), ) } } impl Extend<metatype::Class> for ModuleData { fn extend<T>(&mut self, iter: T) where T: IntoIterator<Item = metatype::Class>, { self.namespace.extend_classes(iter) } } impl Extend<metatype::Enum> for ModuleData { fn extend<T>(&mut self, iter: T) where T: IntoIterator<Item = metatype::Enum>, { self.namespace.extend_enums(iter) } } /// Stack of modules which represents a type space containing imported modules. #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub struct ImportedModuleSpace<'a> { data_stack: Vec<Result<TypeDataRef<'a, ModuleData>, ModuleIdBuf>>, type_map: TypeMapRef<'a>, } impl<'a> ImportedModuleSpace<'a> { pub fn new(type_map: &'a TypeMap) -> Self { ImportedModuleSpace { data_stack: vec![], type_map: TypeMapRef(type_map), } } pub(super) fn from_modules(modules: &[ModuleIdBuf], type_map: TypeMapRef<'a>) -> Self { let data_stack = modules .iter() .map(|id| { type_map .as_ref() .get_module_data(id.as_ref()) .ok_or_else(|| id.clone()) .map(TypeDataRef) }) .collect(); ImportedModuleSpace { data_stack, type_map, } } /// Adds the specified module to the stack of the imported modules. #[must_use] pub fn import_module(&mut self, id: ModuleId) -> bool { if let Some(d) = self.type_map.as_ref().get_module_data(id) { self.data_stack.push(Ok(TypeDataRef(d))); true } else { false } } } // TODO: remove or refactor TypeSpace abstraction impl<'a> TypeSpace<'a> for ImportedModuleSpace<'a> { fn name(&self) -> &str { "" } fn get_type(&self, name: &str) -> Option<Result<NamedType<'a>, TypeMapError>> { self.data_stack.iter().rev().find_map(|r| match r { Ok(d) => d .as_ref() .namespace .get_type_with(name, Some(self.type_map), || { ParentSpace::Namespace(d.as_ref().to_namespace(self.type_map)) }), Err(id) => Some(Err(TypeMapError::InvalidModuleRef(id.clone()))), }) } fn lexical_parent(&self) -> Option<&ParentSpace<'a>> { None } fn get_enum_by_variant(&self, _name: &str) -> Option<Result<Enum<'a>, TypeMapError>> { None // enum variant shouldn't exist in the top-level imported namespace } }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/typemap/namespace.rs
Rust
use super::class::{Class, ClassData}; use super::core::{TypeMapError, TypeSpace}; use super::enum_::{Enum, EnumData}; use super::qml_component::{QmlComponent, QmlComponentData}; use super::util::{TypeDataRef, TypeMapRef}; use super::{NamedType, ParentSpace, PrimitiveType}; use crate::metatype; use std::collections::HashMap; /// Represents a type map in tree (or a namespace), which is created temporarily by borrowing /// type maps. #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub struct Namespace<'a> { data: TypeDataRef<'a, NamespaceData>, type_map_opt: Option<TypeMapRef<'a>>, parent_space: Option<Box<ParentSpace<'a>>>, } /// Stored type namespace. #[derive(Clone, Debug, Default)] pub struct NamespaceData { name_map: HashMap<String, TypeIndex>, classes: Vec<ClassData>, enums: Vec<EnumData>, enum_variant_map: HashMap<String, usize>, qml_components: Vec<QmlComponentData>, } /// Index to type variant stored in [`NamespaceData`]. #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum TypeIndex { Class(usize), Enum(usize), Primitive(PrimitiveType), QmlComponent(usize), } impl<'a> Namespace<'a> { // TODO: map C++ namespace to this type pub(super) fn root(data: TypeDataRef<'a, NamespaceData>) -> Self { Namespace { data, type_map_opt: None, parent_space: None, } } pub(super) fn with_type_map( data: TypeDataRef<'a, NamespaceData>, type_map: TypeMapRef<'a>, parent_space: ParentSpace<'a>, ) -> Self { Namespace { data, type_map_opt: Some(type_map), parent_space: Some(Box::new(parent_space)), } } } impl<'a> TypeSpace<'a> for Namespace<'a> { fn name(&self) -> &str { "" // TODO: return name if not root namespace } fn get_type(&self, name: &str) -> Option<Result<NamedType<'a>, TypeMapError>> { self.data .as_ref() .get_type_with(name, self.type_map_opt, || { ParentSpace::Namespace(self.clone()) }) } fn lexical_parent(&self) -> Option<&ParentSpace<'a>> { self.parent_space.as_deref() } fn get_enum_by_variant(&self, name: &str) -> Option<Result<Enum<'a>, TypeMapError>> { self.data .as_ref() .get_enum_by_variant_with(name, || ParentSpace::Namespace(self.clone())) } } impl NamespaceData { // TODO: redesign mutation API pub(super) fn with_primitive_types(types: &[PrimitiveType]) -> Self { let name_map = HashMap::from_iter( types .iter() .map(|&t| (t.name().to_owned(), TypeIndex::Primitive(t))), ); NamespaceData { name_map, ..Default::default() } } pub(super) fn extend_classes<T>(&mut self, iter: T) where T: IntoIterator<Item = metatype::Class>, { let start = self.classes.len(); for (i, meta) in iter.into_iter().enumerate() { // TODO: use qualified type name and insert namespace node accordingly let name = meta.class_name.clone(); self.classes.push(ClassData::from_meta(meta)); self.name_map.insert(name, TypeIndex::Class(i + start)); } } pub(super) fn extend_enums<T>(&mut self, iter: T) where T: IntoIterator<Item = metatype::Enum>, { let start = self.enums.len(); for (i, meta) in iter.into_iter().enumerate() { let name = meta.name.clone(); let data = EnumData::from_meta(meta); let index = i + start; self.name_map.insert(name, TypeIndex::Enum(index)); if let Some(variants) = data.unscoped_variants() { self.enum_variant_map .extend(variants.iter().map(|v| (v.to_owned(), index))); } self.enums.push(data); } } pub(super) fn push_alias<S, T>(&mut self, new_name: S, old_name: T) -> Result<(), TypeMapError> where S: Into<String>, T: AsRef<str>, { let old_name = old_name.as_ref(); let &index = self .name_map .get(old_name) .ok_or_else(|| TypeMapError::InvalidTypeRef(old_name.to_owned()))?; self.name_map.insert(new_name.into(), index); Ok(()) } pub(super) fn push_qml_component(&mut self, data: QmlComponentData) { let start = self.qml_components.len(); let name = data.class_name().to_owned(); self.qml_components.push(data); self.name_map.insert(name, TypeIndex::QmlComponent(start)); } pub(super) fn get_type_with<'a, F>( &'a self, name: &str, type_map_opt: Option<TypeMapRef<'a>>, make_parent_space: F, ) -> Option<Result<NamedType<'a>, TypeMapError>> where F: FnOnce() -> ParentSpace<'a>, { self.name_map.get(name).map(|&index| match index { TypeIndex::Class(i) => Ok(NamedType::Class(Class::new( TypeDataRef(&self.classes[i]), make_parent_space(), ))), TypeIndex::Enum(i) => Ok(NamedType::Enum(Enum::new( TypeDataRef(&self.enums[i]), make_parent_space(), ))), TypeIndex::Primitive(t) => Ok(NamedType::Primitive(t)), TypeIndex::QmlComponent(i) => { // The type_map ref should be provided by top-level or qmldir module space. // Otherwise it is an error to register QmlComponent to the namespace. if let Some(type_map) = type_map_opt { Ok(NamedType::QmlComponent(QmlComponent::new( TypeDataRef(&self.qml_components[i]), type_map, ))) } else { Err(TypeMapError::InvalidQmlComponentSpace( name.to_owned(), make_parent_space().name().to_owned(), )) } } }) } pub(super) fn get_enum_by_variant_with<'a, F>( &'a self, name: &str, make_parent_space: F, ) -> Option<Result<Enum<'a>, TypeMapError>> where F: FnOnce() -> ParentSpace<'a>, { self.enum_variant_map .get(name) .map(|&i| Ok(Enum::new(TypeDataRef(&self.enums[i]), make_parent_space()))) } }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/typemap/primitive.rs
Rust
use super::class::{Class, ClassData}; use super::namespace::{Namespace, NamespaceData}; use super::util::TypeDataRef; use super::ParentSpace; use crate::metatype; use once_cell::sync::Lazy; /// Value types provided by C++ language and Qt runtime. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum PrimitiveType { Bool, Double, Int, QString, QVariant, Uint, Void, } impl PrimitiveType { pub(super) const ALL: [Self; 7] = [ PrimitiveType::Bool, PrimitiveType::Double, PrimitiveType::Int, PrimitiveType::QString, PrimitiveType::QVariant, PrimitiveType::Uint, PrimitiveType::Void, ]; pub const fn name(&self) -> &'static str { match self { PrimitiveType::Bool => "bool", PrimitiveType::Double => "double", PrimitiveType::Int => "int", PrimitiveType::QString => "QString", PrimitiveType::QVariant => "QVariant", PrimitiveType::Uint => "uint", PrimitiveType::Void => "void", } } /// Returns true if this type is supposed to be passed by `const T &`. pub(super) const fn is_const_ref_preferred(&self) -> bool { match self { PrimitiveType::Bool => false, PrimitiveType::Double => false, PrimitiveType::Int => false, PrimitiveType::QString => true, PrimitiveType::QVariant => true, PrimitiveType::Uint => false, PrimitiveType::Void => false, // invalid } } /// Creates class representation if supported by the underlying type. pub fn to_class(&self) -> Option<Class<'static>> { match self { PrimitiveType::Bool => None, PrimitiveType::Double => None, PrimitiveType::Int => None, PrimitiveType::QString => Some(Class::new( TypeDataRef(&STRING_CLASS_DATA), make_primitive_space(), )), PrimitiveType::QVariant => None, PrimitiveType::Uint => None, PrimitiveType::Void => None, } } } /// Creates a static parent space where only primitive types can be resolved. /// /// In theory, any primitive type can have a parent module space which will be dynamically /// created, but the const-ness of PrimitiveType is pretty useful for pattern matching. /// Therefore, a class representation of primitive type is constrained to static space. fn make_primitive_space() -> ParentSpace<'static> { ParentSpace::Namespace(Namespace::root(TypeDataRef(&PRIMITIVE_SPACE_DATA))) } /// Creates a class representation for the specified list type. /// /// Note that this class representation cannot have any method that references the element /// type such as `T &at(index)`. pub(super) fn make_list_class(name: impl Into<String>) -> Class<'static> { Class::with_temporary_name(name, TypeDataRef(&LIST_CLASS_DATA), make_primitive_space()) } static PRIMITIVE_SPACE_DATA: Lazy<NamespaceData> = Lazy::new(|| NamespaceData::with_primitive_types(&PrimitiveType::ALL)); static STRING_CLASS_DATA: Lazy<ClassData> = Lazy::new(|| { use PrimitiveType::*; let meta = metatype::Class { class_name: QString.name().to_owned(), qualified_class_name: QString.name().to_owned(), methods: vec![ metatype::Method::with_argument_types("arg", QString.name(), [Double.name()]), metatype::Method::with_argument_types("arg", QString.name(), [Int.name()]), metatype::Method::with_argument_types("arg", QString.name(), [QString.name()]), metatype::Method::with_argument_types("arg", QString.name(), [Uint.name()]), metatype::Method::nullary("isEmpty", Bool.name()), ], ..Default::default() }; ClassData::from_meta(meta) }); static LIST_CLASS_DATA: Lazy<ClassData> = Lazy::new(|| { use PrimitiveType::*; let class_name = "QList"; // unused let meta = metatype::Class { class_name: class_name.to_owned(), qualified_class_name: class_name.to_owned(), methods: vec![metatype::Method::nullary("isEmpty", Bool.name())], ..Default::default() }; ClassData::from_meta(meta) });
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/typemap/qml_component.rs
Rust
use super::class::{Class, ClassData}; use super::module::{ImportedModuleSpace, ModuleId, ModuleIdBuf}; use super::util::{TypeDataRef, TypeMapRef}; use super::ParentSpace; /// QML component representation. /// /// A QML component is basically a class inside an anonymous namespace, and this type itself /// isn't a [`TypeSpace`](super::core::TypeSpace). Use [`QmlComponent::as_class`] or /// [`QmlComponent::into_class`] to get the class representation. #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub struct QmlComponent<'a> { class: Class<'a>, } /// Stored QML component representation. #[derive(Clone, Debug)] pub struct QmlComponentData { imports: Vec<ModuleIdBuf>, class: ClassData, } impl<'a> QmlComponent<'a> { pub(super) fn new(data: TypeDataRef<'a, QmlComponentData>, type_map: TypeMapRef<'a>) -> Self { // Inner enum will belong to the class since it is public and should be qualified with // the component name. OTOH, inline component will be added to the imported namespace. let imported_space = ImportedModuleSpace::from_modules(&data.as_ref().imports, type_map); let class = Class::new( TypeDataRef(&data.as_ref().class), ParentSpace::ImportedModuleSpace(imported_space), ); QmlComponent { class } } /// Returns reference to the class representation of this QML component. pub fn as_class(&self) -> &Class<'a> { &self.class } /// Turns this into the underlying class representation. pub fn into_class(self) -> Class<'a> { self.class } } impl QmlComponentData { // TODO: redesign constructor or builder API pub fn with_super<S, T>(name: S, super_name: T) -> Self where S: Into<String>, T: Into<String>, { QmlComponentData { imports: vec![ModuleIdBuf::Builtins], class: ClassData::with_supers(name, [super_name]), } } pub fn imports(&self) -> impl ExactSizeIterator<Item = ModuleId<'_>> { self.imports.iter().map(|id| id.as_ref()) } /// Adds the specified module to the import list from which type names will be resolved. pub fn import_module<S>(&mut self, id: S) where S: Into<ModuleIdBuf>, { self.imports.push(id.into()) } pub(super) fn class_name(&self) -> &str { self.class.class_name() } }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/typemap/util.rs
Rust
use super::core::TypeMapError; use super::{NamedType, TypeKind, TypeMap}; use std::fmt; use std::hash::{Hash, Hasher}; use std::ptr; /// Thin wrapper around reference to TypeMap data. /// /// Two type objects should be considered equal if both borrow the identical data. /// /// This does not implement Deref nor AsRef since the lifetime of the borrowed data /// must be propagated in many cases. #[derive(Clone, Copy)] pub(super) struct TypeDataRef<'a, T: ?Sized>(pub &'a T); impl<'a, T: ?Sized> TypeDataRef<'a, T> { pub fn as_ref(&self) -> &'a T { self.0 } } impl<T: ?Sized> PartialEq for TypeDataRef<'_, T> { fn eq(&self, other: &Self) -> bool { ptr::eq(self.0, other.0) } } impl<T: ?Sized> Eq for TypeDataRef<'_, T> {} impl<T: ?Sized> Hash for TypeDataRef<'_, T> { fn hash<H: Hasher>(&self, state: &mut H) { ptr::hash(self.0, state); } } impl<T: ?Sized + fmt::Debug> fmt::Debug for TypeDataRef<'_, T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_tuple("TypeDataRef") .field(&format_args!("@{:p} {:?}", self.0, self.0)) .finish() } } /// Thin wrapper around reference to TypeMap. /// /// This does not implement Deref nor AsRef since the lifetime of the borrowed data /// must be propagated in many cases. #[derive(Clone, Copy)] pub(super) struct TypeMapRef<'a>(pub &'a TypeMap); impl<'a> TypeMapRef<'a> { pub fn as_ref(&self) -> &'a TypeMap { self.0 } } impl PartialEq for TypeMapRef<'_> { fn eq(&self, other: &Self) -> bool { ptr::eq(self.0, other.0) } } impl Eq for TypeMapRef<'_> {} impl Hash for TypeMapRef<'_> { fn hash<H: Hasher>(&self, state: &mut H) { ptr::hash(self.0, state); } } impl fmt::Debug for TypeMapRef<'_> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // don't print the TypeMap content, which would be quite noisy f.debug_tuple("TypeMapRef") .field(&format_args!("@{:p}", self.0)) .finish() } } /// Strips type decoration from the `name`, looks up the type, and wraps it up. /// /// The given `name` should be normalized in Qt moc way. pub(super) fn decorated_type<'a>( name: &str, lookup: impl FnOnce(&str) -> Option<Result<NamedType<'a>, TypeMapError>>, ) -> Result<TypeKind<'a>, TypeMapError> { // TODO: type alias map at decorated type spec level? let name = match name { "QStringList" => "QList<QString>", n => n, }; if let Some(s) = name.strip_suffix('>') { if let Some(t) = s.strip_prefix("QList<") { Ok(TypeKind::List(Box::new(decorated_type(t, lookup)?))) } else if let Some(t) = s.strip_prefix("QVector<") { Ok(TypeKind::List(Box::new(decorated_type(t, lookup)?))) } else { Err(TypeMapError::UnsupportedDecoration(name.to_owned())) } } else if let Some(s) = name.strip_suffix('*') { lookup(s) .unwrap_or_else(|| Err(TypeMapError::InvalidTypeRef(s.to_owned()))) .map(TypeKind::Pointer) } else { lookup(name) .unwrap_or_else(|| Err(TypeMapError::InvalidTypeRef(name.to_owned()))) .map(TypeKind::Just) } }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/typeutil.rs
Rust
use crate::diagnostic::Diagnostic; use crate::typedexpr::TypeDesc; use crate::typemap::{Enum, NamedType, TypeKind, TypeMapError, TypeSpace as _}; use std::ops::Range; use thiserror::Error; #[derive(Clone, Debug, Error)] pub enum TypeError<'a> { #[error("type resolution failed: {0}")] TypeResolution(#[from] TypeMapError), #[error("incompatible types: {} and {}", .0.qualified_name(), .1.qualified_name())] IncompatibleTypes(TypeDesc<'a>, TypeDesc<'a>), #[error("undetermined type: {}", .0.qualified_name())] UndeterminedType(TypeDesc<'a>), } fn is_compatible_enum(left: &Enum, right: &Enum) -> Result<bool, TypeMapError> { Ok(left == right || left .alias_enum() .transpose()? .is_some_and(|en| &en == right) || right .alias_enum() .transpose()? .is_some_and(|en| &en == left)) } pub fn deduce_concrete_type<'a>( left: TypeDesc<'a>, right: TypeDesc<'a>, ) -> Result<TypeKind<'a>, TypeError<'a>> { deduce_type(left, right).and_then(to_concrete_type) } pub fn to_concrete_type(t: TypeDesc) -> Result<TypeKind, TypeError> { match t { TypeDesc::Concrete(ty) => Ok(ty), TypeDesc::ConstInteger => Ok(TypeKind::INT), // fallback to default TypeDesc::ConstString => Ok(TypeKind::STRING), t @ (TypeDesc::NullPointer | TypeDesc::EmptyList) => Err(TypeError::UndeterminedType(t)), } } /// Determines the compatible type from `left` and `right`. /// /// If either type is concrete, and if it is compatible with the other concrete type, /// the concrete type will be returned. Implicit upcast isn't allowed because it would /// be confusing if QObject were deduced from two different types. pub fn deduce_type<'a>( left: TypeDesc<'a>, right: TypeDesc<'a>, ) -> Result<TypeDesc<'a>, TypeError<'a>> { match (left, right) { (left, right) if left == right => Ok(left), (l @ (TypeDesc::INT | TypeDesc::UINT), TypeDesc::ConstInteger) => Ok(l), (TypeDesc::ConstInteger, r @ (TypeDesc::INT | TypeDesc::UINT)) => Ok(r), (l @ TypeDesc::STRING, TypeDesc::ConstString) => Ok(l), (TypeDesc::ConstString, r @ TypeDesc::STRING) => Ok(r), ( TypeDesc::Concrete(TypeKind::Just(NamedType::Enum(l))), TypeDesc::Concrete(TypeKind::Just(NamedType::Enum(r))), ) if is_compatible_enum(&l, &r)? => { Ok(TypeDesc::Concrete(TypeKind::Just(NamedType::Enum(l)))) } (l @ TypeDesc::Concrete(TypeKind::Pointer(_)), TypeDesc::NullPointer) => Ok(l), (TypeDesc::NullPointer, r @ TypeDesc::Concrete(TypeKind::Pointer(_))) => Ok(r), (l @ TypeDesc::Concrete(TypeKind::List(_)), TypeDesc::EmptyList) => Ok(l), (TypeDesc::EmptyList, r @ TypeDesc::Concrete(TypeKind::List(_))) => Ok(r), (left, right) => Err(TypeError::IncompatibleTypes(left, right)), } } /// Method of type conversion. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum TypeCastKind { /// Exactly the Same type. No type conversion needed. Noop, /// Not the same type, but compatible. No explicit type conversion needed. Implicit, /// Use `static_cast<T>()`. Static, /// Use `QVariant::value<T>()`. Variant, /// No valid type casting available. Invalid, } /// Determine the method to convert the `actual` to the variable of the `expected` type. pub fn pick_type_cast( expected: &TypeKind, actual: &TypeDesc, ) -> Result<TypeCastKind, TypeMapError> { match (expected, actual) { (expected, TypeDesc::Concrete(ty)) => pick_concrete_type_cast(expected, ty), (&TypeKind::INT | &TypeKind::UINT, TypeDesc::ConstInteger) => Ok(TypeCastKind::Implicit), (&TypeKind::DOUBLE, TypeDesc::ConstInteger) => Ok(TypeCastKind::Static), // TODO: should we allow bool <- integer cast? (&TypeKind::STRING, TypeDesc::ConstString) => Ok(TypeCastKind::Implicit), (TypeKind::Pointer(_), TypeDesc::NullPointer) => Ok(TypeCastKind::Implicit), (TypeKind::List(_), TypeDesc::EmptyList) => Ok(TypeCastKind::Implicit), (&TypeKind::VOID, _) => Ok(TypeCastKind::Static), _ => Ok(TypeCastKind::Invalid), } } /// Determine the method to convert the concrete `actual` to the variable of the `expected` type. pub fn pick_concrete_type_cast( expected: &TypeKind, actual: &TypeKind, ) -> Result<TypeCastKind, TypeMapError> { match (expected, actual) { (expected, actual) if expected == actual => Ok(TypeCastKind::Noop), (TypeKind::Just(NamedType::Enum(e)), TypeKind::Just(NamedType::Enum(a))) if is_compatible_enum(e, a)? => { Ok(TypeCastKind::Implicit) } (TypeKind::Pointer(NamedType::Class(e)), TypeKind::Pointer(NamedType::Class(a))) if a.is_derived_from(e) => { Ok(TypeCastKind::Implicit) } ( &TypeKind::DOUBLE | &TypeKind::INT | &TypeKind::UINT, &TypeKind::DOUBLE | &TypeKind::INT | &TypeKind::UINT, ) => Ok(TypeCastKind::Static), (&TypeKind::INT | &TypeKind::UINT, TypeKind::Just(NamedType::Enum(_))) => { Ok(TypeCastKind::Static) } (&TypeKind::INT | &TypeKind::UINT, &TypeKind::BOOL) => Ok(TypeCastKind::Static), // TODO: should we allow bool <- integer cast? (&TypeKind::VOID, _) => Ok(TypeCastKind::Static), (_, &TypeKind::VARIANT) => Ok(TypeCastKind::Variant), // TODO: check expected type _ => Ok(TypeCastKind::Invalid), } } /// Checks if the `actual` can be assigned to the variable of the `expected` type. pub fn is_assignable(expected: &TypeKind, actual: &TypeDesc) -> Result<bool, TypeMapError> { pick_type_cast(expected, actual) .map(|k| matches!(k, TypeCastKind::Noop | TypeCastKind::Implicit)) } /// Checks if the `actual` can be assigned to the variable of the `expected` type. pub fn is_concrete_assignable( expected: &TypeKind, actual: &TypeKind, ) -> Result<bool, TypeMapError> { pick_concrete_type_cast(expected, actual) .map(|k| matches!(k, TypeCastKind::Noop | TypeCastKind::Implicit)) } pub fn diagnose_bool_conversion( diag: &mut Diagnostic, byte_range: Range<usize>, t: &TypeDesc, truthy: bool, ) { push_type_label(diag, byte_range, t); let ne = if truthy { "!=" } else { "==" }; let neg = if truthy { "!" } else { "" }; match t { TypeDesc::ConstInteger | &TypeDesc::INT | &TypeDesc::UINT => { diag.push_note(format!("use (expr {ne} 0) to test zero")); } TypeDesc::ConstString | &TypeDesc::STRING => { diag.push_note(format!(r#"use ({neg}expr.isEmpty()) to test empty string"#)); } TypeDesc::Concrete(TypeKind::Just(NamedType::Enum(_))) => { diag.push_note(format!("use ((expr as int) {ne} 0) to test flag")); } TypeDesc::Concrete(TypeKind::Pointer(_)) => { diag.push_note(format!("use (expr {ne} null) to test null pointer")); } TypeDesc::Concrete(TypeKind::List(_)) => { diag.push_note(format!(r#"use ({neg}expr.isEmpty()) to test empty list"#)); } _ => {} } } /// Adds diagnostic information about type incompatibility. pub fn diagnose_incompatible_types( diag: &mut Diagnostic, left_byte_range: Range<usize>, left_t: &TypeDesc, right_byte_range: Range<usize>, right_t: &TypeDesc, ) { push_type_label(diag, left_byte_range, left_t); push_type_label(diag, right_byte_range, right_t); match (left_t, right_t) { ( &TypeDesc::DOUBLE | &TypeDesc::INT | &TypeDesc::UINT, &TypeDesc::DOUBLE | &TypeDesc::INT | &TypeDesc::UINT, ) => { diag.push_note(format!( "use (expr as {}) or (expr as {}) for numeric cast", right_t.qualified_name(), left_t.qualified_name(), )); } ( TypeDesc::Concrete(TypeKind::Pointer(NamedType::Class(l))), TypeDesc::Concrete(TypeKind::Pointer(NamedType::Class(r))), ) => { if matches!( (l.name(), r.name()), ("QAction", "QMenu") | ("QMenu", "QAction") ) { diag.push_note("call .menuAction() to obtain QAction* associated with menu"); } else if let Some(Ok(b)) = l.common_base_class(r) { diag.push_note(format!( "use (expr as {}) to upcast to base class", b.name(), )); } } _ => {} } } pub fn push_type_label(diag: &mut Diagnostic, byte_range: Range<usize>, t: &TypeDesc) { diag.push_label(byte_range, format!("type: {}", t.qualified_name())); }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/uigen/binding.rs
Rust
use super::expr; use super::objcode::{CallbackCode, ObjectCodeMap, PropertyCode, PropertyCodeKind}; use crate::diagnostic::{Diagnostic, Diagnostics}; use crate::objtree::{ObjectNode, ObjectTree}; use crate::opcode::{BuiltinFunctionKind, ConsoleLogLevel}; use crate::qtname::{self, FileNameRules, UniqueNameGenerator}; use crate::tir; use crate::typedexpr::DescribeType as _; use crate::typemap::{Class, Method, TypeKind, TypeSpace}; use itertools::Itertools as _; use std::collections::{HashMap, HashSet}; use std::io::{self, Write as _}; use std::iter; /// C++ code to set up dynamic property bindings. #[derive(Clone, Debug)] pub struct UiSupportCode { self_class: String, root_class: String, ui_class: String, system_includes: HashSet<&'static str>, quote_includes: Vec<String>, bindings: Vec<CxxBinding>, callbacks: Vec<CxxCallback>, } impl UiSupportCode { pub(super) fn build( type_name: &str, file_name_rules: &FileNameRules, object_tree: &ObjectTree, object_code_maps: &[ObjectCodeMap], diagnostics: &mut Diagnostics, ) -> Self { let system_includes = collect_system_includes(object_code_maps); let quote_includes = vec![file_name_rules.type_name_to_ui_cxx_header_name(type_name)]; let mut name_gen = UniqueNameGenerator::new(); let binding_code_translator = CxxCodeBodyTranslator::new( object_tree.root().name(), type_name, CxxCodeReturnKind::Value, ); let callback_code_translator = CxxCodeBodyTranslator::new( object_tree.root().name(), type_name, CxxCodeReturnKind::Void, ); let mut bindings = Vec::new(); let mut callbacks = Vec::new(); for (obj_node, code_map) in object_tree.flat_iter().zip(object_code_maps) { // TODO: exclude pseudo node like QSpacerItem explicitly? let receiver = binding_code_translator .format_named_object_ref(&tir::NamedObjectRef(obj_node.name().to_owned())); let dyn_props = code_map .properties() .iter() .filter(|(_, p)| !p.is_evaluated_constant()) .sorted_by_key(|&(k, _)| k); bindings.extend(dyn_props.filter_map(|(_, property_code)| { let prefix = qtname::to_ascii_capitalized(obj_node.name()) + &qtname::to_ascii_capitalized(property_code.desc().name()); let name = name_gen.generate(&prefix); let value_function = match property_code.kind() { PropertyCodeKind::Expr(ty, code) => { expr::verify_code_return_type(property_code.node(), code, ty, diagnostics)?; CxxBindingValueFunction::Expr(CxxEvalExprFunction::build( &binding_code_translator, &name, ty, code, )) } PropertyCodeKind::GadgetMap(cls, map) => { CxxBindingValueFunction::GadgetMap(CxxEvalGadgetMapFunction::build( &binding_code_translator, &mut name_gen, &name, cls, map, diagnostics, )) } PropertyCodeKind::ObjectMap(..) => { diagnostics.push(Diagnostic::error( property_code.node().byte_range(), "nested dynamic binding is not supported", )); return None; } }; let update = CxxUpdateBinding::build(property_code, value_function, diagnostics)?; Some(CxxBinding::new(name, &receiver, update)) })); callbacks.extend( code_map .callbacks() .iter() .sorted_by_key(|c| c.desc().name()) .map(|callback_code| { let prefix = qtname::to_ascii_capitalized(obj_node.name()) + &qtname::to_ascii_capitalized(callback_code.desc().name()); let name = name_gen.generate(&prefix); CxxCallback::build(&callback_code_translator, name, obj_node, callback_code) }), ); } UiSupportCode { self_class: type_name.to_owned(), root_class: object_tree.root().class().qualified_cxx_name().into(), ui_class: format!("Ui::{}", type_name), system_includes, quote_includes, bindings, callbacks, } } /// Writes C++ header content. pub fn write_header<W: io::Write>(&self, writer: &mut W) -> io::Result<()> { // TODO: code style options, factor out code generator? let mut w = CodeWriter::new(writer); writeln!(w, "#pragma once")?; for f in self.system_includes.iter().sorted() { writeln!(w, r###"#include <{f}>"###)?; } for f in &self.quote_includes { writeln!(w, r###"#include "{f}""###)?; } writeln!(w)?; writeln!(w, "namespace UiSupport {{")?; writeln!(w, "class {}", self.self_class)?; writeln!(w, "{{")?; writeln!(w, "public:")?; self.write_constructor(&mut w.indented())?; self.write_setup_function(&mut w.indented())?; writeln!(w, "private:")?; self.write_binding_index(&mut w.indented())?; self.write_binding_functions(&mut w.indented())?; self.write_callback_functions(&mut w.indented())?; self.write_fields(&mut w.indented())?; writeln!(w, "}};")?; writeln!(w, "}} // namespace UiSupport") } fn write_constructor<W: io::Write>(&self, w: &mut CodeWriter<W>) -> io::Result<()> { writeln!( w, "{}({} *root, {} *ui): root_(root), ui_(ui) {{}}", self.self_class, self.root_class, self.ui_class, )?; writeln!(w) } fn write_setup_function<W: io::Write>(&self, w: &mut CodeWriter<W>) -> io::Result<()> { writeln!(w, "void setup()")?; writeln!(w, "{{")?; w.indent(); for b in &self.bindings { writeln!(w, "this->{}();", b.setup_function_name())?; } for c in &self.callbacks { writeln!(w, "this->{}();", c.setup_function_name())?; } for b in &self.bindings { writeln!(w, "this->{}();", b.update_function_name())?; } w.unindent(); writeln!(w, "}}")?; writeln!(w) } fn write_binding_index<W: io::Write>(&self, w: &mut CodeWriter<W>) -> io::Result<()> { writeln!(w, "enum class BindingIndex : unsigned {{")?; w.indent(); for b in &self.bindings { writeln!(w, "{},", b.name())?; } w.unindent(); writeln!(w, "}};")?; writeln!(w) } fn write_binding_functions<W: io::Write>(&self, w: &mut CodeWriter<W>) -> io::Result<()> { for b in &self.bindings { b.write_setup_function(w)?; b.write_update_function(w)?; b.write_value_function(w)?; } Ok(()) } fn write_callback_functions<W: io::Write>(&self, w: &mut CodeWriter<W>) -> io::Result<()> { for c in &self.callbacks { c.write_setup_function(w)?; c.write_callback_function(w)?; } Ok(()) } fn write_fields<W: io::Write>(&self, w: &mut CodeWriter<W>) -> io::Result<()> { writeln!(w, "struct PropertyObserver")?; writeln!(w, "{{")?; w.indent(); writeln!(w, "QMetaObject::Connection connection;")?; writeln!(w, "QObject *object = nullptr;")?; w.unindent(); writeln!(w, "}};")?; writeln!(w)?; writeln!(w, "{} *const root_;", self.root_class)?; writeln!(w, "{} *const ui_;", self.ui_class)?; for b in &self.bindings { b.write_field(w)?; } if !self.bindings.is_empty() { // don't emit 0-sized array writeln!(w, "#ifndef QT_NO_DEBUG")?; writeln!( w, "quint32 bindingGuard_[{}] = {{0}};", self.bindings.len().div_ceil(32) )?; writeln!(w, "#endif")?; } writeln!(w) } } /// C++ function and statements for dynamic property binding. #[derive(Clone, Debug)] struct CxxBinding { function_name_suffix: String, receiver: String, update: CxxUpdateBinding, } impl CxxBinding { fn new( function_name_suffix: String, receiver: impl Into<String>, update: CxxUpdateBinding, ) -> Self { CxxBinding { function_name_suffix, receiver: receiver.into(), update, } } fn name(&self) -> &str { &self.function_name_suffix } fn setup_function_name(&self) -> String { format!("setup{}", self.function_name_suffix) } fn update_function_name(&self) -> String { format!("update{}", self.function_name_suffix) } fn write_setup_function<W: io::Write>(&self, w: &mut CodeWriter<W>) -> io::Result<()> { writeln!(w, "void {}()", self.setup_function_name())?; writeln!(w, "{{")?; w.indent(); for (sender, signal) in self.update.value_function.sender_signals().unique() { writeln!( w, "QObject::connect({}, {}, this->root_, [this]() {{ this->{}(); }});", sender, signal, self.update_function_name() )?; } w.unindent(); writeln!(w, "}}")?; writeln!(w) } fn write_update_function<W: io::Write>(&self, w: &mut CodeWriter<W>) -> io::Result<()> { let index = format!("static_cast<unsigned>(BindingIndex::{})", self.name()); let guard = "this->bindingGuard_[index >> 5]"; let mask = "(1U << (index & 0x1f))"; writeln!(w, "void {}()", self.update_function_name())?; writeln!(w, "{{")?; writeln!(w, "#ifndef QT_NO_DEBUG")?; w.indent(); writeln!(w, "constexpr unsigned index = {index};")?; writeln!( w, "Q_ASSERT_X(!({guard} & {mask}), __func__, {what:?});", what = "binding loop detected" )?; writeln!(w, "{guard} |= {mask};")?; writeln!(w, "#endif")?; writeln!( w, "{};", self.update.format_expression(&self.receiver, "->") )?; writeln!(w, "#ifndef QT_NO_DEBUG")?; writeln!(w, "{guard} &= ~{mask};")?; writeln!(w, "#endif")?; w.unindent(); writeln!(w, "}}")?; writeln!(w) } fn write_value_function<W: io::Write>(&self, w: &mut CodeWriter<W>) -> io::Result<()> { self.update .value_function .write_function(w, &self.update_function_name()) } fn write_field<W: io::Write>(&self, w: &mut CodeWriter<W>) -> io::Result<()> { self.update.value_function.write_field(w) } } /// C++ expression to update dynamic property binding. #[derive(Clone, Debug)] struct CxxUpdateBinding { read: String, write: String, value_function: CxxBindingValueFunction, } impl CxxUpdateBinding { fn build( property_code: &PropertyCode, value_function: CxxBindingValueFunction, diagnostics: &mut Diagnostics, ) -> Option<Self> { let read = if let Some(f) = property_code.desc().read_func_name() { f.to_owned() } else { diagnostics.push(Diagnostic::error( property_code.binding_node().byte_range(), "not a readable property", )); return None; }; let write = if let Some(f) = property_code.desc().write_func_name() { f.to_owned() } else { diagnostics.push(Diagnostic::error( property_code.binding_node().byte_range(), "not a writable property", )); return None; }; Some(CxxUpdateBinding { read, write, value_function, }) } fn format_expression(&self, receiver: &str, op: &str) -> String { match &self.value_function { CxxBindingValueFunction::Expr(f) => { format!( "{}{}{}(this->{}())", receiver, op, self.write, f.function_name() ) } CxxBindingValueFunction::GadgetMap(f) => { format!( "{}{}{}(this->{}({}{}{}()))", receiver, op, self.write, f.function_name(), receiver, op, self.read ) } } } } #[derive(Clone, Debug)] enum CxxBindingValueFunction { Expr(CxxEvalExprFunction), GadgetMap(CxxEvalGadgetMapFunction), } impl CxxBindingValueFunction { fn sender_signals(&self) -> Box<dyn Iterator<Item = &(String, String)> + '_> { match self { CxxBindingValueFunction::Expr(f) => Box::new(f.sender_signals()), CxxBindingValueFunction::GadgetMap(f) => Box::new(f.sender_signals()), } } fn write_function<W: io::Write>( &self, w: &mut CodeWriter<W>, update_function_name: &str, ) -> io::Result<()> { match self { CxxBindingValueFunction::Expr(f) => f.write_function(w, update_function_name), CxxBindingValueFunction::GadgetMap(f) => f.write_function(w, update_function_name), } } fn write_field<W: io::Write>(&self, w: &mut CodeWriter<W>) -> io::Result<()> { match self { CxxBindingValueFunction::Expr(f) => f.write_field(w), CxxBindingValueFunction::GadgetMap(f) => f.write_field(w), } } } /// C++ function to evaluate binding expression. #[derive(Clone, Debug)] struct CxxEvalExprFunction { name: String, value_type: String, sender_signals: Vec<(String, String)>, property_observer_count: usize, body: Vec<u8>, } impl CxxEvalExprFunction { fn build( code_translator: &CxxCodeBodyTranslator, name: impl Into<String>, value_ty: &TypeKind, code: &tir::CodeBody, ) -> Self { let sender_signals = code .static_property_deps .iter() .map(|(obj, signal)| { let sender = code_translator.format_named_object_ref(obj); (sender, format_signal_pointer(signal)) }) .collect(); assert_eq!(code.parameter_count, 0); let mut body = Vec::new(); let mut writer = CodeWriter::new(&mut body); writer.set_indent_level(1); code_translator .translate(&mut writer, code) .expect("write to bytes shouldn't fail"); CxxEvalExprFunction { name: name.into(), value_type: value_ty.qualified_cxx_name().into(), sender_signals, property_observer_count: code.property_observer_count, body, } } fn function_name(&self) -> String { format!("eval{}", self.name) } fn property_observer_name(&self) -> String { format!("observed{}_", self.name) } fn sender_signals(&self) -> impl Iterator<Item = &(String, String)> { self.sender_signals.iter() } fn write_function<W: io::Write>( &self, w: &mut CodeWriter<W>, update_function_name: &str, ) -> io::Result<()> { writeln!(w, "{} {}()", self.value_type, self.function_name())?; writeln!(w, "{{")?; if self.property_observer_count > 0 { let mut w = w.indented(); writeln!(w, "auto &observed = {};", self.property_observer_name())?; writeln!( w, "const auto update = [this]() {{ this->{}(); }};", update_function_name )?; } w.get_mut().write_all(&self.body)?; writeln!(w, "}}")?; writeln!(w) } fn write_field<W: io::Write>(&self, w: &mut CodeWriter<W>) -> io::Result<()> { if self.property_observer_count > 0 { // don't emit 0-sized array writeln!( w, "PropertyObserver {}[{}];", self.property_observer_name(), self.property_observer_count )?; } Ok(()) } } /// C++ function to evaluate gadget map binding expressions. #[derive(Clone, Debug)] struct CxxEvalGadgetMapFunction { name: String, value_type: String, bindings: Vec<CxxUpdateBinding>, } impl CxxEvalGadgetMapFunction { fn build( code_translator: &CxxCodeBodyTranslator, name_gen: &mut UniqueNameGenerator, name: impl Into<String>, value_cls: &Class, properties_map: &HashMap<&str, PropertyCode>, diagnostics: &mut Diagnostics, ) -> Self { let name = name.into(); let bindings = properties_map .iter() .sorted_by_key(|&(k, _)| k) .filter_map(|(_, property_code)| { let sub_name = name_gen.generate( name.clone() + &qtname::to_ascii_capitalized(property_code.desc().name()), ); let value_function = match property_code.kind() { PropertyCodeKind::Expr(ty, code) => { expr::verify_code_return_type(property_code.node(), code, ty, diagnostics)?; CxxBindingValueFunction::Expr(CxxEvalExprFunction::build( code_translator, sub_name, ty, code, )) } PropertyCodeKind::GadgetMap(cls, map) => { CxxBindingValueFunction::GadgetMap(CxxEvalGadgetMapFunction::build( code_translator, name_gen, sub_name, cls, map, diagnostics, )) } PropertyCodeKind::ObjectMap(..) => { diagnostics.push(Diagnostic::error( property_code.node().byte_range(), "nested dynamic binding is not supported", )); return None; } }; CxxUpdateBinding::build(property_code, value_function, diagnostics) }) .collect(); CxxEvalGadgetMapFunction { name, value_type: value_cls.qualified_cxx_name().into(), bindings, } } fn function_name(&self) -> String { format!("eval{}", self.name) } fn sender_signals(&self) -> impl Iterator<Item = &(String, String)> { self.bindings .iter() .flat_map(|b| b.value_function.sender_signals()) } fn write_function<W: io::Write>( &self, w: &mut CodeWriter<W>, update_function_name: &str, ) -> io::Result<()> { writeln!( w, "{} {}({} a)", self.value_type, self.function_name(), self.value_type )?; writeln!(w, "{{")?; w.indent(); for b in &self.bindings { writeln!(w, "{};", b.format_expression("a", "."))?; } writeln!(w, "return a;")?; w.unindent(); writeln!(w, "}}")?; writeln!(w)?; for b in &self.bindings { b.value_function.write_function(w, update_function_name)?; } Ok(()) } fn write_field<W: io::Write>(&self, w: &mut CodeWriter<W>) -> io::Result<()> { for b in &self.bindings { b.value_function.write_field(w)?; } Ok(()) } } /// C++ function and statements for callback connection. #[derive(Clone, Debug)] struct CxxCallback { name: String, sender: String, signal: String, parameters: Vec<(String, String)>, callback_function_body: Vec<u8>, } impl CxxCallback { fn build( code_translator: &CxxCodeBodyTranslator, name: String, obj_node: ObjectNode, callback_code: &CallbackCode, ) -> Self { let sender = code_translator .format_named_object_ref(&tir::NamedObjectRef(obj_node.name().to_owned())); let signal = format_signal_pointer(callback_code.desc()); let code = callback_code.code(); // TODO: use 'const T &' if parameter is gadget and not mutated let parameters = code.locals[0..code.parameter_count] .iter() .map(|a| { ( a.ty.qualified_cxx_name().into(), code_translator.format_local_ref(a.name), ) }) .collect(); let mut callback_function_body = Vec::new(); let mut writer = CodeWriter::new(&mut callback_function_body); writer.set_indent_level(1); code_translator .translate(&mut writer, code) .expect("write to bytes shouldn't fail"); CxxCallback { name, sender, signal, parameters, callback_function_body, } } fn setup_function_name(&self) -> String { format!("setup{}", self.name) } fn callback_function_name(&self) -> String { format!("on{}", self.name) } fn write_setup_function<W: io::Write>(&self, w: &mut CodeWriter<W>) -> io::Result<()> { writeln!(w, "void {}()", self.setup_function_name())?; writeln!(w, "{{")?; writeln!( w.indented(), "QObject::connect({}, {}, this->root_, [this]({}) {{ this->{}({}); }});", self.sender, self.signal, self.parameters .iter() .map(|(t, n)| format!("{t} {n}")) .join(", "), self.callback_function_name(), self.parameters.iter().map(|(_, n)| n).join(", "), )?; writeln!(w, "}}")?; writeln!(w) } fn write_callback_function<W: io::Write>(&self, w: &mut CodeWriter<W>) -> io::Result<()> { writeln!( w, "void {}({})", self.callback_function_name(), self.parameters .iter() .map(|(t, n)| format!("{t} {n}")) .join(", "), )?; writeln!(w, "{{")?; w.get_mut().write_all(&self.callback_function_body)?; writeln!(w, "}}")?; writeln!(w) } } #[derive(Clone, Debug)] struct CxxCodeBodyTranslator { root_object_name: tir::NamedObjectRef, tr_context: String, return_kind: CxxCodeReturnKind, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum CxxCodeReturnKind { Value, Void, } impl CxxCodeBodyTranslator { fn new( root_object_name: impl Into<String>, tr_context: impl Into<String>, return_kind: CxxCodeReturnKind, ) -> Self { CxxCodeBodyTranslator { root_object_name: tir::NamedObjectRef(root_object_name.into()), tr_context: tr_context.into(), return_kind, } } fn translate<W: io::Write>( &self, w: &mut CodeWriter<W>, code: &tir::CodeBody, ) -> io::Result<()> { self.write_locals(&mut w.indented(), &code.locals[code.parameter_count..])?; for (i, b) in code.basic_blocks.iter().enumerate() { writeln!(w, "{}:", self.format_basic_block_ref(tir::BasicBlockRef(i)))?; self.write_basic_block(&mut w.indented(), b)?; } Ok(()) } fn write_locals<W: io::Write>( &self, w: &mut CodeWriter<W>, locals: &[tir::Local], ) -> io::Result<()> { for a in locals { writeln!( w, "{} {};", a.ty.qualified_cxx_name(), self.format_local_ref(a.name) )?; } Ok(()) } fn write_basic_block<W: io::Write>( &self, w: &mut CodeWriter<W>, block: &tir::BasicBlock, ) -> io::Result<()> { use tir::{Operand, Terminator}; for s in &block.statements { self.write_statement(w, s)?; } match block.terminator() { Terminator::Br(x) => writeln!(w, "goto {};", self.format_basic_block_ref(*x))?, Terminator::BrCond(x, y, z) => { writeln!(w, "if ({})", self.format_operand(x))?; writeln!(w.indented(), "goto {};", self.format_basic_block_ref(*y))?; writeln!(w, "else")?; writeln!(w.indented(), "goto {};", self.format_basic_block_ref(*z))?; } Terminator::Return(Operand::Void(_)) => writeln!(w, "return;")?, Terminator::Return(x) => match self.return_kind { CxxCodeReturnKind::Value => { writeln!(w, "return {};", self.format_operand(x))?; } CxxCodeReturnKind::Void => { writeln!(w, "static_cast<void>({});", self.format_operand(x))?; writeln!(w, "return;")?; } }, Terminator::Unreachable => writeln!(w, "Q_UNREACHABLE();")?, } Ok(()) } fn write_statement<W: io::Write>( &self, w: &mut CodeWriter<W>, stmt: &tir::Statement, ) -> io::Result<()> { use tir::Statement; match stmt { Statement::Assign(l, r) => writeln!( w, "{} = {};", self.format_local_ref(*l), self.format_rvalue(r) ), Statement::Exec(r) => writeln!(w, "{};", self.format_rvalue(r)), Statement::ObserveProperty(h, l, signal) => { // Note that minimizing the signal/slot connections is NOT the goal of the dynamic // subscription. Uninteresting connection may be left if this statement is out // of the execution path. let observer = self.format_property_observer_ref(*h); let sender = self.format_local_ref(*l); // observer.object may point to deleted object, where new object could be // allocated. observer.connection should be invalidated in such cases. writeln!( w, "if (Q_UNLIKELY(!{}.connection || {}.object != {})) {{", observer, observer, sender )?; w.indent(); writeln!(w, "QObject::disconnect({}.connection);", observer)?; writeln!(w, "if ({}) {{", sender)?; writeln!( w.indented(), "{observer}.connection = QObject::connect({sender}, {signal}, this->root_, update);", signal = format_signal_pointer(signal), )?; writeln!(w, "}}")?; writeln!(w, "{}.object = {};", observer, sender)?; w.unindent(); writeln!(w, "}}") } } } fn format_basic_block_ref(&self, r: tir::BasicBlockRef) -> String { format!("b{}", r.0) } fn format_local_ref(&self, r: tir::LocalRef) -> String { format!("a{}", r.0) } fn format_named_object_ref(&self, r: &tir::NamedObjectRef) -> String { if r == &self.root_object_name { "this->root_".to_owned() } else { format!("this->ui_->{}", r.0) } } fn format_property_observer_ref(&self, r: tir::PropertyObserverRef) -> String { format!("observed[{}]", r.0) } fn format_rvalue(&self, rv: &tir::Rvalue) -> String { use tir::Rvalue; match rv { Rvalue::Copy(a) => self.format_operand(a), Rvalue::UnaryOp(op, a) => format!("{}{}", op, self.format_operand(a)), Rvalue::BinaryOp(op, l, r) => format!( "{} {} {}", self.format_operand(l), op, self.format_operand(r) ), Rvalue::StaticCast(ty, a) => format!( "static_cast<{}>({})", ty.qualified_cxx_name(), self.format_operand(a) ), Rvalue::VariantCast(ty, a) => format!( "{}{}value<{}>()", self.format_operand(a), // must be of QVariant type member_access_op(a), ty.qualified_cxx_name(), ), Rvalue::CallBuiltinFunction(f, args) => { let mut formatted_args = args.iter().map(|a| self.format_operand(a)); match f { BuiltinFunctionKind::ConsoleLog(lv) => { let handler = match lv { ConsoleLogLevel::Log | ConsoleLogLevel::Debug => "qDebug", ConsoleLogLevel::Info => "qInfo", ConsoleLogLevel::Warn => "qWarning", ConsoleLogLevel::Error => "qCritical", }; iter::once(format!("{handler}().noquote()")) .chain(formatted_args) .join(" << ") } BuiltinFunctionKind::Max => format!("std::max({})", formatted_args.join(", ")), BuiltinFunctionKind::Min => format!("std::min({})", formatted_args.join(", ")), BuiltinFunctionKind::Tr => format!( "QCoreApplication::translate({context:?}, {args})", context = self.tr_context, args = formatted_args.join(", "), ), } } Rvalue::CallMethod(obj, meth, args) => { format!( "{}{}{}({})", self.format_operand(obj), member_access_op(obj), meth.name(), args.iter().map(|a| self.format_operand(a)).join(", ") ) } Rvalue::ReadProperty(obj, prop) => { format!( "{}{}{}()", self.format_operand(obj), member_access_op(obj), prop.read_func_name() .expect("unreadable property must be rejected by TIR builder") ) } Rvalue::WriteProperty(obj, prop, r) => { format!( "{}{}{}({})", self.format_operand(obj), member_access_op(obj), prop.write_func_name() .expect("unwritable property must be rejected by TIR builder"), self.format_operand(r) ) } Rvalue::ReadSubscript(obj, index) => { format!( "{}{}at({})", // operator()[] may detach the shared data self.format_operand(obj), member_access_op(obj), self.format_operand(index), ) } Rvalue::WriteSubscript(obj, index, r) => { format!( "{}[{}] = {}", self.format_operand(obj), self.format_operand(index), self.format_operand(r), ) } Rvalue::MakeList(ty, xs) => { format!( "{}{{{}}}", ty.qualified_cxx_name(), xs.iter().map(|a| self.format_operand(a)).join(", ") ) } } } fn format_operand(&self, a: &tir::Operand) -> String { use tir::{ConstantValue, Operand}; match a { Operand::Constant(x) => match &x.value { ConstantValue::Bool(v) => { if *v { "true".to_owned() } else { "false".to_owned() } } ConstantValue::Integer(v) => v.to_string(), ConstantValue::Float(v) => format!("{v:e}"), ConstantValue::CString(v) => format!("{v:?}"), // TODO: escape per C spec) ConstantValue::QString(v) => format!("QStringLiteral({v:?})"), ConstantValue::NullPointer => "nullptr".to_owned(), ConstantValue::EmptyList => "{}".to_owned(), }, Operand::EnumVariant(x) => x.cxx_expression(), Operand::Local(x) => self.format_local_ref(x.name), Operand::NamedObject(x) => self.format_named_object_ref(&x.name), Operand::Void(_) => "void()".to_owned(), } } } fn member_access_op(a: &tir::Operand) -> &'static str { if a.type_desc().is_pointer() { "->" } else { "." } } fn format_signal_pointer(signal: &Method) -> String { let arg_types = signal .argument_types() .iter() .map(|ty| { if ty.is_const_ref_preferred() { format!("const {} &", ty.qualified_cxx_name()) } else { ty.qualified_cxx_name().into_owned() } }) .join(", "); format!( "QOverload<{arg_types}>::of(&{class}::{sig_name})", class = signal.object_class().qualified_cxx_name(), sig_name = signal.name() ) } #[derive(Debug)] struct CodeWriter<'w, W: io::Write> { inner: &'w mut W, indent_level: u32, line_start: bool, } impl<'w, W: io::Write> CodeWriter<'w, W> { pub fn new(inner: &'w mut W) -> Self { CodeWriter { inner, indent_level: 0, line_start: true, } } pub fn indented(&mut self) -> CodeWriter<'_, W> { CodeWriter { inner: self.inner, indent_level: self.indent_level + 1, line_start: true, } } pub fn set_indent_level(&mut self, level: u32) { self.indent_level = level; } pub fn indent(&mut self) { self.indent_level += 1; } pub fn unindent(&mut self) { self.indent_level -= 1; } pub fn get_mut(&mut self) -> &mut W { self.inner } } impl<W: io::Write> io::Write for CodeWriter<'_, W> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { // assumes buf doesn't contain '\n' in the middle let was_line_start = self.line_start; self.line_start = false; if was_line_start && !(buf.starts_with(b"\n") || buf.starts_with(b"#")) { for _ in 0..self.indent_level { self.inner.write_all(b" ")?; } } let n = self.inner.write(buf)?; if n == buf.len() { self.line_start = buf.ends_with(b"\n"); } Ok(n) } fn flush(&mut self) -> io::Result<()> { self.inner.flush() } } fn collect_system_includes(object_code_maps: &[ObjectCodeMap]) -> HashSet<&'static str> { let mut includes = HashSet::new(); for code in object_code_maps.iter().flat_map(|m| m.code_bodies()) { for stmt in code.basic_blocks.iter().flat_map(|block| &block.statements) { use tir::{Rvalue, Statement}; match stmt { Statement::Assign(_, r) | Statement::Exec(r) => { #[allow(clippy::single_match)] match r { Rvalue::CallBuiltinFunction(k, _) => match k { BuiltinFunctionKind::ConsoleLog(_) => { includes.insert("QtDebug"); } BuiltinFunctionKind::Max | BuiltinFunctionKind::Min => { includes.insert("algorithm"); } BuiltinFunctionKind::Tr => {} }, _ => {} } } Statement::ObserveProperty(..) => {} } } } includes }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/uigen/context.rs
Rust
use super::objcode::ObjectCodeMap; use crate::objtree::{ObjectNode, ObjectTree}; use crate::qmldoc::UiDocument; use crate::qtname::FileNameRules; use crate::typedexpr::{RefKind, RefSpace, TypeAnnotationSpace}; use crate::typemap::{ Class, Enum, ImportedModuleSpace, ModuleId, NamedType, TypeKind, TypeMap, TypeMapError, TypeSpace, }; use thiserror::Error; /// How to process dynamic bindings. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum DynamicBindingHandling { /// Silently drops dynamic bindings. Omit, /// Generates C++ code to set up dynamic bindings. Generate, /// Generates errors for dynamic bindings. Reject, } /// Resources passed around the UI object constructors. #[derive(Clone, Debug)] pub struct BuildContext<'a> { pub(super) type_map: &'a TypeMap, pub file_name_rules: FileNameRules, pub dynamic_binding_handling: DynamicBindingHandling, pub(super) classes: KnownClasses<'a>, } #[derive(Clone, Debug)] pub(super) struct BuildDocContext<'a, 't, 's> { pub type_name: &'s str, pub source: &'s str, pub file_name_rules: &'s FileNameRules, pub classes: &'s KnownClasses<'a>, pub type_space: &'s ImportedModuleSpace<'a>, pub object_tree: &'s ObjectTree<'a, 't>, object_code_maps: &'s [ObjectCodeMap<'a, 't, 's>], } /// Context where expression is supposed to be evaluated. #[derive(Clone, Debug)] pub(super) struct ObjectContext<'a, 't, 's> { pub source: &'s str, pub classes: &'s KnownClasses<'a>, pub type_space: &'s ImportedModuleSpace<'a>, pub object_tree: &'s ObjectTree<'a, 't>, obj_node: ObjectNode<'a, 't, 's>, } /// Classes to be used to switch uigen paths. #[derive(Clone, Debug)] pub(super) struct KnownClasses<'a> { pub action: Class<'a>, pub brush: Class<'a>, pub color: Class<'a>, pub combo_box: Class<'a>, pub cursor: Class<'a>, pub cursor_shape: Enum<'a>, pub font: Class<'a>, pub form_layout: Class<'a>, pub grid_layout: Class<'a>, pub hbox_layout: Class<'a>, pub icon: Class<'a>, pub key_sequence: Class<'a>, pub key_sequence_standard_key: Enum<'a>, pub layout: Class<'a>, pub list_widget: Class<'a>, pub margins: Class<'a>, pub menu: Class<'a>, pub object: Class<'a>, pub palette: Class<'a>, pub pixmap: Class<'a>, pub push_button: Class<'a>, pub rect: Class<'a>, pub size: Class<'a>, pub size_policy: Class<'a>, pub spacer_item: Class<'a>, pub tab_widget: Class<'a>, pub table_view: Class<'a>, pub tree_view: Class<'a>, pub vbox_layout: Class<'a>, pub widget: Class<'a>, } impl<'a> BuildContext<'a> { /// Sets up context with the given `type_map`. pub fn prepare( type_map: &'a TypeMap, file_name_rules: FileNameRules, dynamic_binding_handling: DynamicBindingHandling, ) -> Result<Self, BuildContextError> { const MODULE_NAME: &str = "qmluic.QtWidgets"; let module = type_map .get_module(ModuleId::Named(MODULE_NAME)) .ok_or(BuildContextError::ModuleNotFound(MODULE_NAME))?; let get_class = |name| match module.get_type(name) { Some(Ok(NamedType::Class(cls))) => Ok(cls), Some(Err(e)) => Err(BuildContextError::TypeResolution(name, e)), Some(Ok(_)) | None => Err(BuildContextError::ClassNotFound(name)), }; let get_enum = |scoped_name| { match module.get_type_scoped(scoped_name) { Some(Ok(NamedType::Enum(en))) => Ok(en), Some(Err(e)) => Err(BuildContextError::TypeResolution(scoped_name, e)), Some(Ok(_)) | None => { // not a "class", but who cares Err(BuildContextError::ClassNotFound(scoped_name)) } } }; let classes = KnownClasses { action: get_class("QAction")?, brush: get_class("QBrush")?, color: get_class("QColor")?, combo_box: get_class("QComboBox")?, cursor: get_class("QCursor")?, cursor_shape: get_enum("Qt::CursorShape")?, font: get_class("QFont")?, form_layout: get_class("QFormLayout")?, grid_layout: get_class("QGridLayout")?, hbox_layout: get_class("QHBoxLayout")?, icon: get_class("QIcon")?, key_sequence: get_class("QKeySequence")?, key_sequence_standard_key: get_enum("QKeySequence::StandardKey")?, layout: get_class("QLayout")?, list_widget: get_class("QListWidget")?, margins: get_class("QMargins")?, menu: get_class("QMenu")?, object: get_class("QObject")?, palette: get_class("QPalette")?, pixmap: get_class("QPixmap")?, push_button: get_class("QPushButton")?, rect: get_class("QRect")?, size: get_class("QSize")?, size_policy: get_class("QSizePolicy")?, spacer_item: get_class("QSpacerItem")?, tab_widget: get_class("QTabWidget")?, table_view: get_class("QTableView")?, tree_view: get_class("QTreeView")?, vbox_layout: get_class("QVBoxLayout")?, widget: get_class("QWidget")?, }; Ok(BuildContext { type_map, file_name_rules, dynamic_binding_handling, classes, }) } } impl<'a, 't, 's> BuildDocContext<'a, 't, 's> { pub fn new( doc: &'s UiDocument, type_space: &'s ImportedModuleSpace<'a>, object_tree: &'s ObjectTree<'a, 't>, object_code_maps: &'s [ObjectCodeMap<'a, 't, 's>], base_ctx: &'s BuildContext<'a>, ) -> Self { BuildDocContext { type_name: doc.type_name(), source: doc.source(), file_name_rules: &base_ctx.file_name_rules, classes: &base_ctx.classes, type_space, object_tree, object_code_maps, } } pub fn code_map_for_object(&self, obj_node: ObjectNode) -> &ObjectCodeMap<'a, 't, 's> { &self.object_code_maps[obj_node.flat_index()] } pub fn make_object_context( &self, obj_node: ObjectNode<'a, 't, 's>, ) -> ObjectContext<'a, 't, 's> { ObjectContext { source: self.source, classes: self.classes, type_space: self.type_space, object_tree: self.object_tree, obj_node, } } } impl<'a, 't, 's> ObjectContext<'a, 't, 's> { pub fn new( doc: &'s UiDocument, type_space: &'s ImportedModuleSpace<'a>, object_tree: &'s ObjectTree<'a, 't>, obj_node: ObjectNode<'a, 't, 's>, base_ctx: &'s BuildContext<'a>, ) -> Self { ObjectContext { source: doc.source(), classes: &base_ctx.classes, type_space, object_tree, obj_node, } } } impl<'a> RefSpace<'a> for ObjectContext<'a, '_, '_> { fn get_ref(&self, name: &str) -> Option<Result<RefKind<'a>, TypeMapError>> { // object id lookup is explicit, which should precede any other implicit this lookups. let me = &self.obj_node; #[allow(clippy::manual_map)] if let Some(obj) = self.object_tree.get_by_id(name) { Some(Ok(RefKind::Object(obj.class().clone()))) } else if let Some(r) = me.class().get_property(name) { Some(r.map(|p| RefKind::ObjectProperty(me.class().clone(), me.name().to_owned(), p))) } else if let Some(r) = me.class().get_public_method(name) { Some(r.map(|m| RefKind::ObjectMethod(me.class().clone(), me.name().to_owned(), m))) } else if let Some(r) = self.type_space.get_type(name) { Some(r.map(RefKind::Type)) } else { None } } fn this_object(&self) -> Option<(Class<'a>, String)> { let me = &self.obj_node; Some((me.class().clone(), me.name().to_owned())) } } impl<'a> TypeAnnotationSpace<'a> for ObjectContext<'a, '_, '_> { fn get_annotated_type_scoped( &self, scoped_name: &str, ) -> Option<Result<TypeKind<'a>, TypeMapError>> { self.type_space.get_type_scoped(scoped_name).map(|r| { r.map(|ty| match ty { NamedType::Class(cls) if cls.is_derived_from(&self.classes.object) => { TypeKind::Pointer(NamedType::Class(cls)) } NamedType::QmlComponent(_) => TypeKind::Pointer(ty), NamedType::Class(_) | NamedType::Enum(_) | NamedType::Namespace(_) | NamedType::Primitive(_) => TypeKind::Just(ty), }) }) } } /// Error occurred while setting up [`BuildContext`]. #[derive(Clone, Debug, Error)] pub enum BuildContextError { #[error("required class not found: {0}")] ClassNotFound(&'static str), #[error("required module not found: {0}")] ModuleNotFound(&'static str), #[error("required type '{0}' not resolved: {1}")] TypeResolution(&'static str, #[source] TypeMapError), }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/uigen/expr.rs
Rust
use super::context::ObjectContext; use super::gadget::{Gadget, GadgetKind, ModelItem, PaletteColorGroup}; use super::objcode::{PropertyCode, PropertyCodeKind}; use super::xmlutil; use super::XmlWriter; use crate::color::Color; use crate::diagnostic::{Diagnostic, Diagnostics}; use crate::qmlast::Node; use crate::tir; use crate::tir::interpret::{EvaluatedValue, StringKind}; use crate::typemap::{NamedType, PrimitiveType, TypeKind, TypeSpace}; use crate::typeutil; use quick_xml::events::{BytesStart, BytesText, Event}; use std::collections::HashMap; use std::fmt; use std::io; /// Variant for the constant expressions which can be serialized to UI XML. #[derive(Clone, Debug)] pub enum SerializableValue { Simple(SimpleValue), /// Generic structured value. Gadget(Gadget), /// Map of palette color roles created per color group. PaletteColorGroup(PaletteColorGroup), /// List of strings. StringList(Vec<String>, StringKind), } impl SerializableValue { pub(super) fn build( ctx: &ObjectContext, property_code: &PropertyCode, diagnostics: &mut Diagnostics, ) -> Option<Self> { let node = property_code.node(); match property_code.kind() { PropertyCodeKind::Expr(ty, code) => { let res = property_code.evaluate()?; // no warning; to be processed by cxx pass match ty { TypeKind::Just(t) => { parse_as_value_type(ctx, ty, t, node, code, res, diagnostics) } TypeKind::Pointer(NamedType::Class(_)) => { verify_code_return_type(node, code, ty, diagnostics)?; Some(SerializableValue::Simple(SimpleValue::Cstring( res.unwrap_object_ref(), ))) } TypeKind::List(t) if t.as_ref() == &TypeKind::STRING => { verify_code_return_type(node, code, ty, diagnostics)?; extract_string_list(node, res, diagnostics) } TypeKind::Pointer(_) | TypeKind::List(_) => { diagnostics.push(Diagnostic::error( node.byte_range(), format!("unexpected value type: {}", ty.qualified_cxx_name(),), )); None } } } PropertyCodeKind::GadgetMap(cls, map) => { if let Some(kind) = GadgetKind::from_class(cls, ctx.classes) { let v = Gadget::new(ctx, kind, map, diagnostics); Some(SerializableValue::Gadget(v)) } else if cls.name() == "QPaletteColorGroup" { let v = PaletteColorGroup::new(ctx, map, diagnostics); Some(SerializableValue::PaletteColorGroup(v)) } else { diagnostics.push(Diagnostic::error( node.byte_range(), format!("unsupported gadget type: {}", cls.qualified_cxx_name()), )); None } } PropertyCodeKind::ObjectMap(cls, _) => { diagnostics.push(Diagnostic::error( node.byte_range(), format!("unexpected value type: {}", cls.qualified_cxx_name()), )); None } } } /// Serializes this to UI XML. pub fn serialize_to_xml<W>(&self, writer: &mut XmlWriter<W>) -> io::Result<()> where W: io::Write, { use SerializableValue::*; match self { Simple(x) => x.serialize_to_xml(writer), Gadget(x) => x.serialize_to_xml(writer), PaletteColorGroup(x) => x.serialize_to_xml(writer), StringList(x, k) => serialize_string_list_to_xml(writer, "stringlist", x, *k), } } pub(super) fn serialize_to_xml_as<W, T>( &self, writer: &mut XmlWriter<W>, tag_name: T, ) -> io::Result<()> where W: io::Write, T: AsRef<str>, { use SerializableValue::*; match self { Simple(x) => x.serialize_to_xml_as(writer, tag_name), Gadget(x) => x.serialize_to_xml_as(writer, tag_name), PaletteColorGroup(x) => x.serialize_to_xml_as(writer, tag_name), StringList(x, k) => serialize_string_list_to_xml(writer, tag_name, x, *k), } } pub fn as_number(&self) -> Option<f64> { match self { SerializableValue::Simple(x) => x.as_number(), _ => None, } } pub fn as_enum(&self) -> Option<&str> { match self { SerializableValue::Simple(x) => x.as_enum(), _ => None, } } } /// Constant expression which can be serialized to UI XML as a simple tagged value. #[derive(Clone, Debug)] pub enum SimpleValue { Bool(bool), Number(f64), String(String, StringKind), Cstring(String), Enum(String), Set(String), CursorShape(String), Pixmap(String), } impl SimpleValue { /// Serializes this to UI XML. pub fn serialize_to_xml<W>(&self, writer: &mut XmlWriter<W>) -> io::Result<()> where W: io::Write, { use SimpleValue::*; let tag_name = match self { Bool(_) => "bool", Number(_) => "number", String { .. } => "string", Cstring(_) => "cstring", Enum(_) => "enum", Set(_) => "set", CursorShape(_) => "cursorShape", Pixmap(_) => "pixmap", }; self.serialize_to_xml_as(writer, tag_name) } pub(super) fn serialize_to_xml_as<W, T>( &self, writer: &mut XmlWriter<W>, tag_name: T, ) -> io::Result<()> where W: io::Write, T: AsRef<str>, { use SimpleValue::*; match self { String(s, k) => { let mut tag = BytesStart::new(tag_name.as_ref()); if *k == StringKind::NoTr { tag.push_attribute(("notr", "true")); } writer.write_event(Event::Start(tag.borrow()))?; writer.write_event(Event::Text(BytesText::new(s)))?; writer.write_event(Event::End(tag.to_end())) } _ => xmlutil::write_tagged_str(writer, tag_name, self.to_string()), } } pub fn as_bool(&self) -> Option<bool> { match self { SimpleValue::Bool(x) => Some(*x), _ => None, } } pub fn as_number(&self) -> Option<f64> { match self { SimpleValue::Number(x) => Some(*x), _ => None, } } pub fn as_enum(&self) -> Option<&str> { match self { SimpleValue::Enum(x) | SimpleValue::Set(x) => Some(x), _ => None, } } pub fn into_enum(self) -> Option<String> { match self { SimpleValue::Enum(x) | SimpleValue::Set(x) => Some(x), _ => None, } } } impl fmt::Display for SimpleValue { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use SimpleValue::*; match self { Bool(b) => write!(f, "{}", if *b { "true" } else { "false" }), Number(d) => write!(f, "{}", d), String(s, _) | Cstring(s) | Enum(s) | Set(s) | CursorShape(s) | Pixmap(s) => { write!(f, "{}", s) } } } } impl EvaluatedValue { fn unwrap_into_simple_value(self) -> SimpleValue { match self { EvaluatedValue::Bool(v) => SimpleValue::Bool(v), EvaluatedValue::Integer(v) => SimpleValue::Number(v as f64), EvaluatedValue::Float(v) => SimpleValue::Number(v), EvaluatedValue::String(s, k) => SimpleValue::String(s, k), // enum can't be mapped to SimpleValue without type information _ => panic!("evaluated type must be simple value"), } } } fn serialize_string_list_to_xml<W, T>( writer: &mut XmlWriter<W>, tag_name: T, strings: &[String], kind: StringKind, ) -> io::Result<()> where W: io::Write, T: AsRef<str>, { let mut tag = BytesStart::new(tag_name.as_ref()); if kind == StringKind::NoTr { tag.push_attribute(("notr", "true")); } writer.write_event(Event::Start(tag.borrow()))?; for s in strings { xmlutil::write_tagged_str(writer, "string", s)?; } writer.write_event(Event::End(tag.to_end())) } fn parse_as_value_type( ctx: &ObjectContext, expected_ty: &TypeKind, expected_just_ty: &NamedType, node: Node, code: &tir::CodeBody, res: EvaluatedValue, diagnostics: &mut Diagnostics, ) -> Option<SerializableValue> { match expected_just_ty { NamedType::Class(cls) if cls == &ctx.classes.brush => { let color = parse_color_value(node, code, res, diagnostics).map(SerializableValue::Gadget)?; let style = SimpleValue::Enum("Qt::SolidPattern".to_owned()); Some(SerializableValue::Gadget(Gadget { kind: GadgetKind::Brush, attributes: HashMap::from([("brushstyle".to_owned(), style)]), properties: HashMap::from([("color".to_owned(), color)]), })) } NamedType::Class(cls) if cls == &ctx.classes.color => { parse_color_value(node, code, res, diagnostics).map(SerializableValue::Gadget) } NamedType::Class(cls) if cls == &ctx.classes.cursor => { verify_code_return_type( node, code, &TypeKind::Just(NamedType::Enum(ctx.classes.cursor_shape.clone())), diagnostics, )?; let expr = res.unwrap_enum_set().join("|"); Some(SerializableValue::Simple(SimpleValue::CursorShape( strip_enum_prefix(&expr).to_owned(), ))) } NamedType::Class(cls) if cls == &ctx.classes.key_sequence => { let standard_key_en = &ctx.classes.key_sequence_standard_key; let return_t = code.resolve_return_type(diagnostics)?; let mut matches = |expected: &TypeKind| { typeutil::is_assignable(expected, &return_t) .map_err(|e| { diagnostics.push(Diagnostic::error(node.byte_range(), e.to_string())) }) .ok() }; if matches(&TypeKind::Just(NamedType::Enum(standard_key_en.clone())))? { let expr = res.unwrap_enum_set().join("|"); if standard_key_en.is_flag() { Some(SerializableValue::Simple(SimpleValue::Set(expr))) } else { Some(SerializableValue::Simple(SimpleValue::Enum(expr))) } } else if matches(&TypeKind::STRING)? { Some(SerializableValue::Simple(res.unwrap_into_simple_value())) } else { diagnostics.push(Diagnostic::error( node.byte_range(), format!( "expression type mismatch (expected: {} | {}, actual: {})", standard_key_en.qualified_cxx_name(), TypeKind::STRING.qualified_cxx_name(), return_t.qualified_name(), ), )); None } } NamedType::Class(cls) if cls == &ctx.classes.pixmap => { verify_code_return_type(node, code, &TypeKind::STRING, diagnostics)?; extract_static_string(node, res, diagnostics) .map(|s| SerializableValue::Simple(SimpleValue::Pixmap(s))) } NamedType::Enum(en) => { verify_code_return_type(node, code, expected_ty, diagnostics)?; let expr = res.unwrap_enum_set().join("|"); if en.is_flag() { Some(SerializableValue::Simple(SimpleValue::Set(expr))) } else { Some(SerializableValue::Simple(SimpleValue::Enum(expr))) } } NamedType::Primitive( PrimitiveType::Bool | PrimitiveType::Int | PrimitiveType::Uint | PrimitiveType::Double | PrimitiveType::QString, ) => { verify_code_return_type(node, code, expected_ty, diagnostics)?; Some(SerializableValue::Simple(res.unwrap_into_simple_value())) } NamedType::Primitive(PrimitiveType::Void) | NamedType::Namespace(_) => { diagnostics.push(Diagnostic::error( node.byte_range(), format!( "invalid expression type: {}", expected_ty.qualified_cxx_name(), ), )); None } NamedType::Primitive(PrimitiveType::QVariant) | NamedType::Class(_) | NamedType::QmlComponent(_) => { diagnostics.push(Diagnostic::error( node.byte_range(), format!( "unsupported constant expression type: {}", expected_ty.qualified_cxx_name(), ), )); None } } } #[must_use] pub(super) fn verify_code_return_type( node: Node, code: &tir::CodeBody, expected: &TypeKind, diagnostics: &mut Diagnostics, ) -> Option<()> { let return_t = code.resolve_return_type(diagnostics)?; if typeutil::is_assignable(expected, &return_t) .map_err(|e| diagnostics.push(Diagnostic::error(node.byte_range(), e.to_string()))) .ok()? { Some(()) } else { diagnostics.push(Diagnostic::error( node.byte_range(), format!( "expression type mismatch (expected: {}, actual: {})", expected.qualified_cxx_name(), return_t.qualified_name() ), )); None } } fn parse_color_value( node: Node, code: &tir::CodeBody, res: EvaluatedValue, diagnostics: &mut Diagnostics, ) -> Option<Gadget> { // TODO: handle Qt::GlobalColor enum verify_code_return_type(node, code, &TypeKind::STRING, diagnostics)?; extract_static_string(node, res, diagnostics).and_then(|s| match s.parse::<Color>() { Ok(c) => Some(c.into()), Err(e) => { diagnostics.push(Diagnostic::error(node.byte_range(), e.to_string())); None } }) } /// Evaluates the given code as a static item model. /// /// The return type of the given code is supposed to be `QAbstractItemModel *`. pub(super) fn build_item_model( property_code: &PropertyCode, diagnostics: &mut Diagnostics, ) -> Option<Vec<ModelItem>> { let node = property_code.node(); match property_code.kind() { PropertyCodeKind::Expr(_, code) => { let res = property_code.evaluate()?; // no warning; to be processed by cxx pass let ty = TypeKind::List(Box::new(TypeKind::STRING)); verify_code_return_type(node, code, &ty, diagnostics)?; let items = res .unwrap_string_list() .into_iter() .map(|(s, k)| ModelItem::with_text(s, k)) .collect(); Some(items) } PropertyCodeKind::GadgetMap(cls, _) | PropertyCodeKind::ObjectMap(cls, _) => { diagnostics.push(Diagnostic::error( node.byte_range(), format!("not a static item model: {}", cls.qualified_cxx_name()), )); None } } } /// Evaluates the given code as a list of identifiers referencing objects. pub(super) fn build_object_ref_list( property_code: &PropertyCode, diagnostics: &mut Diagnostics, ) -> Option<Vec<String>> { let node = property_code.node(); match property_code.kind() { PropertyCodeKind::Expr(ty, code) => { let res = property_code.evaluate()?; // no warning; to be processed by cxx pass verify_code_return_type(node, code, ty, diagnostics)?; res.into_object_ref_list() } PropertyCodeKind::GadgetMap(cls, _) | PropertyCodeKind::ObjectMap(cls, _) => { diagnostics.push(Diagnostic::error( node.byte_range(), format!("not an object ref list: {}", cls.qualified_cxx_name()), )); None } } } fn extract_static_string( node: Node, res: EvaluatedValue, diagnostics: &mut Diagnostics, ) -> Option<String> { if let (s, StringKind::NoTr) = res.unwrap_string() { Some(s) } else { diagnostics.push(Diagnostic::error( node.byte_range(), "must be a static string", )); None } } fn extract_string_list( node: Node, res: EvaluatedValue, diagnostics: &mut Diagnostics, ) -> Option<SerializableValue> { let xs = res.unwrap_string_list(); // unfortunately, notr attribute is list level let kind = xs.first().map(|(_, k)| *k).unwrap_or(StringKind::NoTr); if xs.iter().all(|(_, k)| *k == kind) { let ss = xs.into_iter().map(|(s, _)| s).collect(); Some(SerializableValue::StringList(ss, kind)) } else { diagnostics.push(Diagnostic::error( node.byte_range(), "cannot mix bare and translatable strings", )); None } } pub(super) fn strip_enum_prefix(s: &str) -> &str { s.split_once("::").map(|(_, t)| t).unwrap_or(s) }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/uigen/form.rs
Rust
use super::context::BuildDocContext; use super::object::Widget; use super::xmlutil; use super::XmlWriter; use crate::diagnostic::{Diagnostic, Diagnostics}; use crate::objtree::ObjectNode; use crate::qtname::FileNameRules; use crate::typemap::{Class, TypeSpace}; use itertools::Itertools as _; use quick_xml::events::{BytesStart, Event}; use std::io; /// Top-level object wrapper to be serialized to UI XML. #[derive(Clone, Debug)] pub struct UiForm { pub class: String, pub root_widget: Widget, pub custom_widgets: Vec<CustomWidget>, } impl UiForm { pub(super) fn build( ctx: &BuildDocContext, obj_node: ObjectNode, diagnostics: &mut Diagnostics, ) -> Self { let cls = obj_node.class(); if !cls.is_derived_from(&ctx.classes.widget) { diagnostics.push(Diagnostic::error( obj_node.obj().node().byte_range(), format!("class '{}' is not a QWidget", cls.qualified_cxx_name()), )); // but continue anyway to report as many errors as possible } let root_widget = Widget::build(ctx, obj_node, diagnostics); let custom_widgets = ctx .object_tree .flat_iter() .filter(|n| n.is_custom_type()) .map(|n| n.class().clone()) .unique() .filter_map(|cls| CustomWidget::from_class(&cls, ctx.file_name_rules)) .collect(); UiForm { class: ctx.type_name.to_owned(), root_widget, custom_widgets, } } /// Serializes this to UI XML. pub fn serialize_to_xml<W>(&self, writer: &mut XmlWriter<W>) -> io::Result<()> where W: io::Write, { let tag = BytesStart::new("ui").with_attributes([("version", "4.0")]); writer.write_event(Event::Start(tag.borrow()))?; xmlutil::write_tagged_str(writer, "class", &self.class)?; self.root_widget.serialize_to_xml(writer)?; if !self.custom_widgets.is_empty() { let tag = BytesStart::new("customwidgets"); writer.write_event(Event::Start(tag.borrow()))?; for w in &self.custom_widgets { w.serialize_to_xml(writer)?; } writer.write_event(Event::End(tag.to_end()))?; } writer.write_event(Event::End(tag.to_end()))?; writer.get_mut().write_all(b"\n")?; Ok(()) } } /// User type referenced from the [`UiForm`]. #[derive(Clone, Debug)] pub struct CustomWidget { pub class: String, pub extends: String, pub header: String, } impl CustomWidget { pub(super) fn from_class(cls: &Class, file_name_rules: &FileNameRules) -> Option<Self> { // If super class doesn't exist, diagnostic message would have been emitted while // building the object representation. So returns silently. let super_cls = cls.public_super_classes().next().and_then(|r| r.ok())?; Some(CustomWidget { class: cls.qualified_cxx_name().into(), extends: super_cls.qualified_cxx_name().into(), header: file_name_rules.type_name_to_cxx_header_name(cls.name()), }) } /// Serializes this to UI XML. pub fn serialize_to_xml<W>(&self, writer: &mut XmlWriter<W>) -> io::Result<()> where W: io::Write, { let tag = BytesStart::new("customwidget"); writer.write_event(Event::Start(tag.borrow()))?; xmlutil::write_tagged_str(writer, "class", &self.class)?; xmlutil::write_tagged_str(writer, "extends", &self.extends)?; xmlutil::write_tagged_str(writer, "header", &self.header)?; writer.write_event(Event::End(tag.to_end())) } }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/uigen/gadget.rs
Rust
use super::context::{KnownClasses, ObjectContext}; use super::expr::{self, SerializableValue, SimpleValue}; use super::objcode::PropertyCode; use super::property; use super::xmlutil; use super::XmlWriter; use crate::color::Color; use crate::diagnostic::{Diagnostic, Diagnostics}; use crate::qtname; use crate::tir::interpret::StringKind; use crate::typemap::Class; use itertools::Itertools as _; use quick_xml::events::{BytesStart, Event}; use std::collections::HashMap; use std::io; /// Constant map-like object which can be serialized to UI XML. #[derive(Clone, Debug)] pub struct Gadget { pub kind: GadgetKind, pub attributes: HashMap<String, SimpleValue>, pub properties: HashMap<String, SerializableValue>, } impl Gadget { pub(super) fn new( ctx: &ObjectContext, kind: GadgetKind, map: &HashMap<&str, PropertyCode>, diagnostics: &mut Diagnostics, ) -> Self { let (attributes, properties) = match kind { GadgetKind::Brush => make_brush_properties(ctx, map, diagnostics), GadgetKind::Icon => make_icon_properties(ctx, map, diagnostics), GadgetKind::Palette => make_palette_properties(ctx, map, diagnostics), GadgetKind::SizePolicy => make_size_policy_properties(ctx, map, diagnostics), _ => ( HashMap::new(), property::make_value_map(ctx, map, &[], diagnostics), ), }; Gadget { kind, attributes, properties, } } /// Serializes this to UI XML. pub fn serialize_to_xml<W>(&self, writer: &mut XmlWriter<W>) -> io::Result<()> where W: io::Write, { self.serialize_to_xml_as(writer, self.kind.as_tag_name()) } pub(super) fn serialize_to_xml_as<W, T>( &self, writer: &mut XmlWriter<W>, tag_name: T, ) -> io::Result<()> where W: io::Write, T: AsRef<str>, { let mut tag = BytesStart::new(tag_name.as_ref()); for (k, v) in self.attributes.iter().sorted_by_key(|&(k, _)| k) { match v { SimpleValue::Enum(s) if self.kind.no_enum_prefix() => { tag.push_attribute((k.as_str(), expr::strip_enum_prefix(s))) } _ => tag.push_attribute((k.as_str(), v.to_string().as_str())), } } writer.write_event(Event::Start(tag.borrow()))?; for (k, v) in self.properties.iter().sorted_by_key(|&(k, _)| k) { let t = k.to_ascii_lowercase(); // apparently tag name of .ui is lowercase match v { SerializableValue::Simple(SimpleValue::Enum(s)) if self.kind.no_enum_prefix() => { xmlutil::write_tagged_str(writer, &t, expr::strip_enum_prefix(s))?; } _ => v.serialize_to_xml_as(writer, &t)?, } } writer.write_event(Event::End(tag.to_end())) } } impl From<Color> for Gadget { fn from(color: Color) -> Self { let attr = |n: &str, v: u8| (n.to_owned(), SimpleValue::Number(v.into())); let prop = |n: &str, v: u8| { ( n.to_owned(), SerializableValue::Simple(SimpleValue::Number(v.into())), ) }; let (attributes, properties) = match color { Color::Rgb8(c) => ( // forcibly set alpha since QUiLoader can't handle color without alpha component HashMap::from([attr("alpha", 0xff)]), HashMap::from([ prop("red", c.red), prop("green", c.green), prop("blue", c.blue), ]), ), Color::Rgba8(c) => ( // "alpha" is attribute for unknown reason HashMap::from([attr("alpha", c.alpha)]), HashMap::from([ prop("red", c.red), prop("green", c.green), prop("blue", c.blue), ]), ), }; Gadget { kind: GadgetKind::Color, attributes, properties, } } } #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum GadgetKind { Brush, Color, Font, Icon, Margins, Palette, Rect, Size, SizePolicy, } impl GadgetKind { pub(super) fn from_class(cls: &Class, classes: &KnownClasses) -> Option<GadgetKind> { match cls { _ if cls == &classes.brush => Some(GadgetKind::Brush), // incompatible property names: color => Some(GadgetKind::Color), _ if cls == &classes.font => Some(GadgetKind::Font), _ if cls == &classes.icon => Some(GadgetKind::Icon), _ if cls == &classes.margins => Some(GadgetKind::Margins), _ if cls == &classes.palette => Some(GadgetKind::Palette), _ if cls == &classes.rect => Some(GadgetKind::Rect), _ if cls == &classes.size => Some(GadgetKind::Size), _ if cls == &classes.size_policy => Some(GadgetKind::SizePolicy), _ => None, } } pub fn as_tag_name(&self) -> &'static str { match self { GadgetKind::Brush => "brush", GadgetKind::Color => "color", GadgetKind::Font => "font", GadgetKind::Icon => "iconset", GadgetKind::Margins => "margins", // not supported by uic GadgetKind::Palette => "palette", GadgetKind::Rect => "rect", GadgetKind::Size => "size", GadgetKind::SizePolicy => "sizepolicy", } } fn no_enum_prefix(&self) -> bool { match self { GadgetKind::Brush => true, GadgetKind::Color => false, GadgetKind::Font => true, GadgetKind::Icon => false, GadgetKind::Margins => false, GadgetKind::Palette => false, GadgetKind::Rect => false, GadgetKind::Size => false, GadgetKind::SizePolicy => true, } } } fn make_brush_properties( ctx: &ObjectContext, map: &HashMap<&str, PropertyCode>, diagnostics: &mut Diagnostics, ) -> ( HashMap<String, SimpleValue>, HashMap<String, SerializableValue>, ) { let mut attributes = HashMap::new(); if let Some((_, s)) = property::get_simple_value(ctx, map, "style", diagnostics) { attributes.insert("brushstyle".to_owned(), s); } let properties = property::make_value_map(ctx, map, &["style"], diagnostics); (attributes, properties) } fn make_icon_properties( ctx: &ObjectContext, map: &HashMap<&str, PropertyCode>, diagnostics: &mut Diagnostics, ) -> ( HashMap<String, SimpleValue>, HashMap<String, SerializableValue>, ) { let mut attributes = HashMap::new(); if let Some((_, s)) = property::get_simple_value(ctx, map, "name", diagnostics) { attributes.insert("theme".to_owned(), s); } let properties = property::make_value_map(ctx, map, &["name"], diagnostics); (attributes, properties) } fn make_palette_properties( ctx: &ObjectContext, map: &HashMap<&str, PropertyCode>, diagnostics: &mut Diagnostics, ) -> ( HashMap<String, SimpleValue>, HashMap<String, SerializableValue>, ) { let mut color_groups = HashMap::from([ ("active", PaletteColorGroup::default()), ("inactive", PaletteColorGroup::default()), ("disabled", PaletteColorGroup::default()), ]); let mut default_roles = Vec::new(); for (k, p) in map { match SerializableValue::build(ctx, p, diagnostics) { Some(SerializableValue::PaletteColorGroup(g)) => { color_groups.insert(k, g); } Some(x) => { default_roles.push((qtname::to_ascii_capitalized(k), x)); } None => {} } } for g in color_groups.values_mut() { g.merge_default_roles(&default_roles); } let attributes = HashMap::new(); let properties = color_groups .into_iter() .map(|(k, g)| (k.to_owned(), SerializableValue::PaletteColorGroup(g))) .collect(); (attributes, properties) } fn make_size_policy_properties( ctx: &ObjectContext, map: &HashMap<&str, PropertyCode>, diagnostics: &mut Diagnostics, ) -> ( HashMap<String, SimpleValue>, HashMap<String, SerializableValue>, ) { let mut attributes = HashMap::new(); match ( property::get_simple_value(ctx, map, "horizontalPolicy", diagnostics), property::get_simple_value(ctx, map, "verticalPolicy", diagnostics), ) { (Some((_, h)), Some((_, v))) => { attributes.insert("hsizetype".to_owned(), h); attributes.insert("vsizetype".to_owned(), v); } (Some((p, _)), None) | (None, Some((p, _))) => { diagnostics.push(Diagnostic::error( p.binding_node().byte_range(), "both horizontal and vertical policies must be specified", )); } (None, None) => {} } let mut properties = HashMap::new(); for (k0, k1) in [ ("horizontalStretch", "horstretch"), ("verticalStretch", "verstretch"), ] { if let Some((p, v)) = map .get(k0) .and_then(|p| SerializableValue::build(ctx, p, diagnostics).map(|v| (p, v))) { if attributes.is_empty() { // uic would otherwise generate invalid code, which might look correct but is // actually parsed as a function declaration: // QSizePolicy sizePolicy(); diagnostics.push(Diagnostic::error( p.binding_node().byte_range(), "cannot specify stretch without horizontal and vertical policies", )); } else { properties.insert(k1.to_owned(), v); } } } let known_property_names = [ "horizontalPolicy", "verticalPolicy", "horizontalStretch", "verticalStretch", ]; for (_, p) in map .iter() .filter(|(n, _)| !known_property_names.contains(n)) { diagnostics.push(Diagnostic::error( p.binding_node().byte_range(), "unknown property of size policy", )); } (attributes, properties) } /// QComboBox/QAbstractItemView item. #[derive(Clone, Debug)] pub struct ModelItem { pub properties: HashMap<String, SerializableValue>, } impl ModelItem { pub(super) fn with_text(s: String, k: StringKind) -> Self { let properties = HashMap::from([( "text".to_owned(), SerializableValue::Simple(SimpleValue::String(s, k)), )]); ModelItem { properties } } pub(super) fn serialize_to_xml<W>(&self, writer: &mut XmlWriter<W>) -> io::Result<()> where W: io::Write, { let tag = BytesStart::new("item"); writer.write_event(Event::Start(tag.borrow()))?; serialize_item_properties_to_xml(writer, &self.properties)?; writer.write_event(Event::End(tag.to_end())) } } fn serialize_item_properties_to_xml<W>( writer: &mut XmlWriter<W>, properties: &HashMap<String, SerializableValue>, ) -> io::Result<()> where W: io::Write, { for (k, v) in properties.iter().sorted_by_key(|&(k, _)| k) { let tag = BytesStart::new("property").with_attributes([("name", k.as_ref())]); writer.write_event(Event::Start(tag.borrow()))?; v.serialize_to_xml(writer)?; writer.write_event(Event::End(tag.to_end()))?; } Ok(()) } /// Map of palette color role to brush. #[derive(Clone, Debug, Default)] pub struct PaletteColorGroup { pub roles: HashMap<String, SerializableValue>, } impl PaletteColorGroup { pub(super) fn new( ctx: &ObjectContext, map: &HashMap<&str, PropertyCode>, diagnostics: &mut Diagnostics, ) -> Self { let roles = map .iter() .filter_map(|(&k, p)| { let v = SerializableValue::build(ctx, p, diagnostics)?; Some((qtname::to_ascii_capitalized(k), v)) }) .collect(); PaletteColorGroup { roles } } pub(super) fn merge_default_roles(&mut self, default_roles: &[(String, SerializableValue)]) { for (k, v) in default_roles { self.roles.entry(k.to_owned()).or_insert_with(|| v.clone()); } } pub(super) fn serialize_to_xml<W>(&self, writer: &mut XmlWriter<W>) -> io::Result<()> where W: io::Write, { self.serialize_to_xml_as(writer, "colorgroup") // not supported by uic } pub(super) fn serialize_to_xml_as<W, T>( &self, writer: &mut XmlWriter<W>, tag_name: T, ) -> io::Result<()> where W: io::Write, T: AsRef<str>, { let group_tag = BytesStart::new(tag_name.as_ref()); writer.write_event(Event::Start(group_tag.borrow()))?; for (k, v) in self.roles.iter().sorted_by_key(|&(k, _)| k) { let tag = BytesStart::new("colorrole").with_attributes([("role", k.as_ref())]); writer.write_event(Event::Start(tag.borrow()))?; v.serialize_to_xml(writer)?; writer.write_event(Event::End(tag.to_end()))?; } writer.write_event(Event::End(group_tag.to_end())) } }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/uigen/layout.rs
Rust
use super::context::{BuildDocContext, ObjectContext}; use super::expr::SerializableValue; use super::objcode::PropertyCode; use super::object::{self, Widget}; use super::property::{self, PropertySetter}; use super::XmlWriter; use crate::diagnostic::{Diagnostic, Diagnostics}; use crate::objtree::ObjectNode; use crate::typemap::{Class, TypeSpace}; use itertools::Itertools as _; use quick_xml::events::{BytesStart, Event}; use std::collections::HashMap; use std::io; /// Layout definition which can be serialized to UI XML. #[derive(Clone, Debug)] pub struct Layout { pub class: String, pub name: String, attributes: LayoutAttributes, pub properties: HashMap<String, (SerializableValue, PropertySetter)>, pub children: Vec<LayoutItem>, } #[derive(Clone, Debug, Default)] pub struct LayoutAttributes { column_minimum_width: Vec<Option<i32>>, column_stretch: Vec<Option<i32>>, row_minimum_height: Vec<Option<i32>>, row_stretch: Vec<Option<i32>>, stretch: Vec<Option<i32>>, // for vbox/hbox } impl Layout { /// Creates a serializable tree by visiting the children recursively. pub(super) fn build( ctx: &BuildDocContext, obj_node: ObjectNode, diagnostics: &mut Diagnostics, ) -> Self { let cls = obj_node.class(); let obj_ctx = ctx.make_object_context(obj_node); let properties_code_map = ctx.code_map_for_object(obj_node).properties(); let (attributes, children) = if cls.is_derived_from(&ctx.classes.vbox_layout) { process_vbox_layout_children(ctx, obj_node, diagnostics) } else if cls.is_derived_from(&ctx.classes.hbox_layout) { process_hbox_layout_children(ctx, obj_node, diagnostics) } else if cls.is_derived_from(&ctx.classes.form_layout) { process_form_layout_children(ctx, obj_node, diagnostics) } else if cls.is_derived_from(&ctx.classes.grid_layout) { let flow = LayoutFlow::parse(&obj_ctx, properties_code_map, diagnostics); process_grid_layout_children(ctx, obj_node, flow, diagnostics) } else { diagnostics.push(Diagnostic::error( obj_node.obj().node().byte_range(), format!("unknown layout class: {}", cls.qualified_cxx_name()), )); // use the most restricted one to report as many errors as possible process_vbox_layout_children(ctx, obj_node, diagnostics) }; Self::new( &obj_ctx, obj_node.class(), obj_node.name(), attributes, properties_code_map, children, diagnostics, ) } pub(super) fn new( ctx: &ObjectContext, class: &Class, name: impl Into<String>, attributes: LayoutAttributes, properties_code_map: &HashMap<&str, PropertyCode>, children: Vec<LayoutItem>, diagnostics: &mut Diagnostics, ) -> Self { let pseudo_property_names = if class.is_derived_from(&ctx.classes.grid_layout) { ["flow", "columns", "rows"].as_ref() // see LayoutFlow } else { [].as_ref() }; let mut properties = property::make_serializable_map( ctx, properties_code_map, pseudo_property_names, diagnostics, ); // TODO: if metatypes were broken, contentsMargins could be of different type if let Some((SerializableValue::Gadget(m), s)) = properties.remove("contentsMargins") { // don't care the property setter since uic will anyway retranslate them properties.extend( m.properties .into_iter() .map(|(k, v)| (k + "Margin", (v, s))), ); } Layout { class: class.qualified_cxx_name().into_owned(), name: name.into(), attributes, properties, children, } } /// Serializes this to UI XML. pub fn serialize_to_xml<W>(&self, writer: &mut XmlWriter<W>) -> io::Result<()> where W: io::Write, { let mut tag = BytesStart::new("layout"); tag.push_attribute(("class", self.class.as_ref())); tag.push_attribute(("name", self.name.as_ref())); if !self.attributes.column_minimum_width.is_empty() { tag.push_attribute(( "columnminimumwidth", format_opt_i32_array(&self.attributes.column_minimum_width, 0).as_ref(), )); } if !self.attributes.column_stretch.is_empty() { tag.push_attribute(( "columnstretch", format_opt_i32_array(&self.attributes.column_stretch, 1).as_ref(), )); } if !self.attributes.row_minimum_height.is_empty() { tag.push_attribute(( "rowminimumheight", format_opt_i32_array(&self.attributes.row_minimum_height, 0).as_ref(), )); } if !self.attributes.row_stretch.is_empty() { tag.push_attribute(( "rowstretch", format_opt_i32_array(&self.attributes.row_stretch, 1).as_ref(), )); } if !self.attributes.stretch.is_empty() { tag.push_attribute(( "stretch", format_opt_i32_array(&self.attributes.stretch, 1).as_ref(), )); } writer.write_event(Event::Start(tag.borrow()))?; property::serialize_properties_to_xml(writer, "property", &self.properties)?; for c in &self.children { c.serialize_to_xml(writer)?; } writer.write_event(Event::End(tag.to_end()))?; Ok(()) } } /// Layout item definition which can be serialized to UI XML. #[derive(Clone, Debug)] pub struct LayoutItem { pub alignment: Option<String>, pub column: Option<i32>, pub column_span: Option<i32>, pub row: Option<i32>, pub row_span: Option<i32>, pub content: LayoutItemContent, } impl LayoutItem { fn new( row: Option<i32>, column: Option<i32>, attached: &LayoutItemAttached, content: LayoutItemContent, diagnostics: &mut Diagnostics, ) -> Self { LayoutItem { alignment: attached.alignment(diagnostics).map(|(_, v)| v), column, column_span: attached.column_span(diagnostics).map(|(_, v)| v), row, row_span: attached.row_span(diagnostics).map(|(_, v)| v), content, } } /// Serializes this to UI XML. pub fn serialize_to_xml<W>(&self, writer: &mut XmlWriter<W>) -> io::Result<()> where W: io::Write, { let mut tag = BytesStart::new("item"); if let Some(v) = &self.alignment { tag.push_attribute(("alignment", v.as_ref())); } if let Some(v) = self.column { tag.push_attribute(("column", v.to_string().as_ref())); } if let Some(v) = self.column_span { tag.push_attribute(("colspan", v.to_string().as_ref())); // not "columnspan" } if let Some(v) = self.row { tag.push_attribute(("row", v.to_string().as_ref())); } if let Some(v) = self.row_span { tag.push_attribute(("rowspan", v.to_string().as_ref())); } writer.write_event(Event::Start(tag.borrow()))?; self.content.serialize_to_xml(writer)?; writer.write_event(Event::End(tag.to_end()))?; Ok(()) } } /// Layout properties to be resolved into [`Layout`] and [`LayoutItem`]. #[derive(Debug)] struct LayoutItemAttached<'a, 't, 's, 'm> { ctx: ObjectContext<'a, 't, 's>, map: Option<&'m HashMap<&'s str, PropertyCode<'a, 't, 's>>>, } macro_rules! impl_attached_enum_property { ($name:ident, $key:expr) => { fn $name( &self, diagnostics: &mut Diagnostics, ) -> Option<(&'m PropertyCode<'a, 't, 's>, String)> { self.map .and_then(|m| property::get_enum(&self.ctx, m, $key, diagnostics)) } }; } macro_rules! impl_attached_i32_property { ($name:ident, $key:expr) => { fn $name( &self, diagnostics: &mut Diagnostics, ) -> Option<(&'m PropertyCode<'a, 't, 's>, i32)> { self.map .and_then(|m| property::get_i32(&self.ctx, m, $key, diagnostics)) } }; } impl<'a, 't, 's, 'm> LayoutItemAttached<'a, 't, 's, 'm> { fn prepare(ctx: &'m BuildDocContext<'a, 't, 's>, obj_node: ObjectNode<'a, 't, 's>) -> Self { let code_map = ctx.code_map_for_object(obj_node); let map = code_map .attached_properties(&ctx.classes.layout) .map(|(_, m)| m); LayoutItemAttached { ctx: ctx.make_object_context(obj_node), map, } } impl_attached_enum_property!(alignment, "alignment"); impl_attached_i32_property!(column, "column"); impl_attached_i32_property!(column_minimum_width, "columnMinimumWidth"); impl_attached_i32_property!(column_span, "columnSpan"); impl_attached_i32_property!(column_stretch, "columnStretch"); impl_attached_i32_property!(row, "row"); impl_attached_i32_property!(row_minimum_height, "rowMinimumHeight"); impl_attached_i32_property!(row_span, "rowSpan"); impl_attached_i32_property!(row_stretch, "rowStretch"); } /// Variant for the object managed by the layout item. #[derive(Clone, Debug)] pub enum LayoutItemContent { Layout(Layout), SpacerItem(SpacerItem), Widget(Widget), } impl LayoutItemContent { /// Generates layout content and its children recursively from the given `obj_node`. fn build(ctx: &BuildDocContext, obj_node: ObjectNode, diagnostics: &mut Diagnostics) -> Self { let cls = obj_node.class(); if cls.is_derived_from(&ctx.classes.layout) { LayoutItemContent::Layout(Layout::build(ctx, obj_node, diagnostics)) } else if cls.is_derived_from(&ctx.classes.spacer_item) { object::confine_children(obj_node, diagnostics); LayoutItemContent::SpacerItem(SpacerItem::new( &ctx.make_object_context(obj_node), obj_node.name(), ctx.code_map_for_object(obj_node).properties(), diagnostics, )) } else if cls.is_derived_from(&ctx.classes.widget) { LayoutItemContent::Widget(Widget::build(ctx, obj_node, diagnostics)) } else { diagnostics.push(Diagnostic::error( obj_node.obj().node().byte_range(), format!( "class '{}' is not a QLayout, QSpacerItem, nor QWidget", cls.qualified_cxx_name() ), )); // but process as widget to report as many errors as possible LayoutItemContent::Widget(Widget::build(ctx, obj_node, diagnostics)) } } pub fn serialize_to_xml<W>(&self, writer: &mut XmlWriter<W>) -> io::Result<()> where W: io::Write, { use LayoutItemContent::*; match self { Layout(x) => x.serialize_to_xml(writer), SpacerItem(x) => x.serialize_to_xml(writer), Widget(x) => x.serialize_to_xml(writer), } } } /// Spacer item definition which can be serialized to UI XML. #[derive(Clone, Debug)] pub struct SpacerItem { pub name: String, pub properties: HashMap<String, SerializableValue>, } impl SpacerItem { pub(super) fn new( ctx: &ObjectContext, name: impl Into<String>, properties_code_map: &HashMap<&str, PropertyCode>, diagnostics: &mut Diagnostics, ) -> Self { // no check for writable as all spacer properties are translated by uic let properties = property::make_value_map(ctx, properties_code_map, &[], diagnostics); SpacerItem { name: name.into(), properties, } } /// Serializes this to UI XML. pub fn serialize_to_xml<W>(&self, writer: &mut XmlWriter<W>) -> io::Result<()> where W: io::Write, { let tag = BytesStart::new("spacer").with_attributes([("name", self.name.as_ref())]); writer.write_event(Event::Start(tag.borrow()))?; for (k, v) in self.properties.iter().sorted_by_key(|&(k, _)| k) { let t = BytesStart::new("property").with_attributes([("name", k.as_ref())]); writer.write_event(Event::Start(t.borrow()))?; v.serialize_to_xml(writer)?; writer.write_event(Event::End(t.to_end()))?; } writer.write_event(Event::End(tag.to_end()))?; Ok(()) } } fn process_vbox_layout_children( ctx: &BuildDocContext, layout_obj_node: ObjectNode, diagnostics: &mut Diagnostics, ) -> (LayoutAttributes, Vec<LayoutItem>) { let mut attributes = LayoutAttributes::default(); let children = layout_obj_node .children() .enumerate() .map(|(row, n)| { let attached = LayoutItemAttached::prepare(ctx, n); let content = LayoutItemContent::build(ctx, n, diagnostics); maybe_insert_into_opt_i32_array( &mut attributes./*row_*/stretch, row, attached.row_stretch(diagnostics), diagnostics, ); LayoutItem::new(None, None, &attached, content, diagnostics) }) .collect(); (attributes, children) } fn process_hbox_layout_children( ctx: &BuildDocContext, layout_obj_node: ObjectNode, diagnostics: &mut Diagnostics, ) -> (LayoutAttributes, Vec<LayoutItem>) { let mut attributes = LayoutAttributes::default(); let children = layout_obj_node .children() .enumerate() .map(|(column, n)| { let attached = LayoutItemAttached::prepare(ctx, n); let content = LayoutItemContent::build(ctx, n, diagnostics); maybe_insert_into_opt_i32_array( &mut attributes./*column_*/stretch, column, attached.column_stretch(diagnostics), diagnostics, ); LayoutItem::new(None, None, &attached, content, diagnostics) }) .collect(); (attributes, children) } fn process_form_layout_children( ctx: &BuildDocContext, layout_obj_node: ObjectNode, diagnostics: &mut Diagnostics, ) -> (LayoutAttributes, Vec<LayoutItem>) { let attributes = LayoutAttributes::default(); let mut index_counter = LayoutIndexCounter::new(LayoutFlow::LeftToRight { columns: 2 }); let children = layout_obj_node .children() .map(|n| { let attached = LayoutItemAttached::prepare(ctx, n); let content = LayoutItemContent::build(ctx, n, diagnostics); let (row, column) = index_counter.parse_next(&attached, diagnostics); LayoutItem::new(Some(row), Some(column), &attached, content, diagnostics) }) .collect(); (attributes, children) } fn process_grid_layout_children( ctx: &BuildDocContext, layout_obj_node: ObjectNode, flow: LayoutFlow, diagnostics: &mut Diagnostics, ) -> (LayoutAttributes, Vec<LayoutItem>) { let mut attributes = LayoutAttributes::default(); let mut index_counter = LayoutIndexCounter::new(flow); let children = layout_obj_node .children() .map(|n| { let attached = LayoutItemAttached::prepare(ctx, n); let content = LayoutItemContent::build(ctx, n, diagnostics); let (row, column) = index_counter.parse_next(&attached, diagnostics); maybe_insert_into_opt_i32_array( &mut attributes.column_minimum_width, column as usize, attached.column_minimum_width(diagnostics), diagnostics, ); maybe_insert_into_opt_i32_array( &mut attributes.column_stretch, column as usize, attached.column_stretch(diagnostics), diagnostics, ); maybe_insert_into_opt_i32_array( &mut attributes.row_minimum_height, column as usize, attached.row_minimum_height(diagnostics), diagnostics, ); maybe_insert_into_opt_i32_array( &mut attributes.row_stretch, row as usize, attached.row_stretch(diagnostics), diagnostics, ); LayoutItem::new(Some(row), Some(column), &attached, content, diagnostics) }) .collect(); (attributes, children) } /// Generates contiguous `(row, column)` of layout items. #[derive(Clone, Debug)] struct LayoutIndexCounter { flow: LayoutFlow, next_row: i32, next_column: i32, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum LayoutFlow { LeftToRight { columns: i32 }, TopToBottom { rows: i32 }, } impl LayoutIndexCounter { fn new(flow: LayoutFlow) -> Self { LayoutIndexCounter { flow, next_row: 0, next_column: 0, } } fn next(&mut self, row: Option<i32>, column: Option<i32>) -> (i32, i32) { if let (Some(r), Some(c)) = (row, column) { self.next_row = r; self.next_column = c; } else if let Some(r) = row { self.next_row = r; self.next_column = match self.flow { LayoutFlow::LeftToRight { .. } => 0, LayoutFlow::TopToBottom { .. } => self.next_column, }; } else if let Some(c) = column { self.next_column = c; self.next_row = match self.flow { LayoutFlow::LeftToRight { .. } => self.next_row, LayoutFlow::TopToBottom { .. } => 0, }; } let cur = (self.next_row, self.next_column); match self.flow { LayoutFlow::LeftToRight { columns } => { self.next_column = (self.next_column + 1) % columns; self.next_row += (self.next_column == 0) as i32; } LayoutFlow::TopToBottom { rows } => { self.next_row = (self.next_row + 1) % rows; self.next_column += (self.next_row == 0) as i32; } } cur } fn parse_next( &mut self, attached: &LayoutItemAttached, diagnostics: &mut Diagnostics, ) -> (i32, i32) { const MAX_INDEX: i32 = 65535; // arbitrary value to avoid excessive allocation let (max_row, max_column) = match self.flow { LayoutFlow::LeftToRight { columns } => (MAX_INDEX, columns - 1), LayoutFlow::TopToBottom { rows } => (rows - 1, MAX_INDEX), }; self.next( maybe_parse_layout_index("row", attached.row(diagnostics), max_row, diagnostics), maybe_parse_layout_index( "column", attached.column(diagnostics), max_column, diagnostics, ), ) } } impl LayoutFlow { fn parse( ctx: &ObjectContext, properties_code_map: &HashMap<&str, PropertyCode>, diagnostics: &mut Diagnostics, ) -> Self { // should be kept sync with QGridLayout definition in metatype_tweak.rs let left_to_right = if let Some((p, s)) = property::get_enum(ctx, properties_code_map, "flow", diagnostics) { match s.as_ref() { "QGridLayout::LeftToRight" => true, "QGridLayout::TopToBottom" => false, s => { diagnostics.push(Diagnostic::error( p.node().byte_range(), format!("unsupported layout flow expression: {s}"), )); true // don't care } } } else { true // LeftToRight by default }; const MAX_COUNT: i32 = 65536; // arbitrary value to avoid excessive allocation if any let mut pop_count_property = |name| { property::get_i32(ctx, properties_code_map, name, diagnostics) .and_then(|(p, c)| { if c <= 0 { diagnostics.push(Diagnostic::error( p.node().byte_range(), format!("negative or zero {name} is not allowed"), )); None } else if c > MAX_COUNT { diagnostics.push(Diagnostic::error( p.node().byte_range(), format!("{name} is too large"), )); None } else { Some(c) } }) .unwrap_or(MAX_COUNT) }; // TODO: maybe warn unused columns/rows? let columns = pop_count_property("columns"); let rows = pop_count_property("rows"); if left_to_right { LayoutFlow::LeftToRight { columns } } else { LayoutFlow::TopToBottom { rows } } } } fn maybe_parse_layout_index( field_name: &str, index: Option<(&PropertyCode, i32)>, max_index: i32, diagnostics: &mut Diagnostics, ) -> Option<i32> { index.and_then(|(p, v)| { if v < 0 { diagnostics.push(Diagnostic::error( p.node().byte_range(), format!("negative {field_name} is not allowed"), )); None } else if v > max_index { diagnostics.push(Diagnostic::error( p.node().byte_range(), format!("{field_name} is too large"), )); None } else { Some(v) } }) } fn maybe_insert_into_opt_i32_array( array: &mut Vec<Option<i32>>, index: usize, value: Option<(&PropertyCode, i32)>, diagnostics: &mut Diagnostics, ) { if let Some((p1, v1)) = value { if index >= array.len() { array.resize_with(index + 1, Default::default); } match array[index] { Some(v0) if v0 != v1 => { diagnostics.push(Diagnostic::error( p1.node().byte_range(), format!("mismatched with the value previously set: {v0}"), )); } _ => { array[index] = Some(v1); } } } } fn format_opt_i32_array(array: &[Option<i32>], default: i32) -> String { array.iter().map(|x| x.unwrap_or(default)).join(",") } #[cfg(test)] mod tests { use super::*; #[test] fn index_counter_left_to_right() { let mut counter = LayoutIndexCounter::new(LayoutFlow::LeftToRight { columns: 2 }); assert_eq!(counter.next(None, None), (0, 0)); assert_eq!(counter.next(None, None), (0, 1)); assert_eq!(counter.next(None, None), (1, 0)); assert_eq!(counter.next(Some(2), None), (2, 0)); assert_eq!(counter.next(None, None), (2, 1)); assert_eq!(counter.next(None, Some(1)), (3, 1)); assert_eq!(counter.next(Some(4), Some(1)), (4, 1)); } #[test] fn index_counter_top_to_bottom() { let mut counter = LayoutIndexCounter::new(LayoutFlow::TopToBottom { rows: 3 }); assert_eq!(counter.next(None, None), (0, 0)); assert_eq!(counter.next(None, None), (1, 0)); assert_eq!(counter.next(None, None), (2, 0)); assert_eq!(counter.next(None, None), (0, 1)); assert_eq!(counter.next(None, Some(3)), (0, 3)); assert_eq!(counter.next(Some(2), None), (2, 3)); assert_eq!(counter.next(Some(3), Some(4)), (3, 4)); } }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/uigen/mod.rs
Rust
//! Qt user interface XML (.ui) generator. use self::objcode::ObjectCodeMap; use crate::diagnostic::{Diagnostic, Diagnostics}; use crate::objtree::ObjectTree; use crate::qmlast::{UiImportSource, UiProgram}; use crate::qmldir; use crate::qmldoc::UiDocument; use crate::typemap::{ImportedModuleSpace, ModuleId, ModuleIdBuf, TypeMap}; mod binding; mod context; mod expr; mod form; mod gadget; mod layout; mod objcode; mod object; mod property; mod xmlutil; pub use self::binding::*; // re-export pub use self::context::*; // re-export pub use self::expr::*; // re-export pub use self::form::*; // re-export pub use self::gadget::*; // re-export pub use self::layout::*; // re-export pub use self::object::*; // re-export pub type XmlWriter<W> = quick_xml::Writer<W>; /// Builds `UiForm` (and `UiSupportCode`) from the given `doc`. /// /// If `DynamicBindingHandling::Generate`, `UiSupportCode` is returned no matter if /// the given document contains dynamic bindings or not. pub fn build( base_ctx: &BuildContext, doc: &UiDocument, diagnostics: &mut Diagnostics, ) -> Option<(UiForm, Option<UiSupportCode>)> { let program = diagnostics.consume_err(UiProgram::from_node(doc.root_node(), doc.source()))?; let type_space = make_doc_module_space(doc, &program, base_ctx.type_map, diagnostics); let object_tree = ObjectTree::build( program.root_object_node(), doc.source(), &type_space, diagnostics, )?; let object_code_maps = build_object_code_maps(doc, &type_space, &object_tree, base_ctx, diagnostics); let ctx = BuildDocContext::new(doc, &type_space, &object_tree, &object_code_maps, base_ctx); let form = UiForm::build(&ctx, object_tree.root(), diagnostics); for p in object_code_maps .iter() .flat_map(|cm| cm.all_attached_properties().values().map(|(_, pm)| pm)) .flat_map(|pm| pm.values()) .filter(|p| !p.is_evaluated_constant()) { diagnostics.push(Diagnostic::error( p.binding_node().byte_range(), "unused or unsupported dynamic binding to attached property", )); } let ui_support = match base_ctx.dynamic_binding_handling { DynamicBindingHandling::Omit => None, DynamicBindingHandling::Generate => Some(UiSupportCode::build( doc.type_name(), &base_ctx.file_name_rules, &object_tree, &object_code_maps, diagnostics, )), DynamicBindingHandling::Reject => { for p in object_code_maps .iter() .flat_map(|m| m.properties().values()) .filter(|p| !p.is_evaluated_constant()) { if p.desc().is_writable() { diagnostics.push(Diagnostic::error( p.node().byte_range(), "unsupported dynamic binding", )); } else { diagnostics.push(Diagnostic::error( p.binding_node().byte_range(), "not a writable property", )); } } for c in object_code_maps.iter().flat_map(|cm| cm.callbacks()) { diagnostics.push(Diagnostic::error( c.binding_node().byte_range(), "signal callback cannot be translated without dynamic binding", )); } None } }; Some((form, ui_support)) } fn make_doc_module_space<'a>( doc: &UiDocument, program: &UiProgram, type_map: &'a TypeMap, diagnostics: &mut Diagnostics, ) -> ImportedModuleSpace<'a> { let mut module_space = ImportedModuleSpace::new(type_map); assert!(module_space.import_module(ModuleId::Builtins)); if let Some(p) = doc.path().and_then(|p| p.parent()) { // QML files in the base directory should be available by default let id = ModuleIdBuf::Directory(qmldir::normalize_path(p)); if !module_space.import_module(id.as_ref()) { diagnostics.push(Diagnostic::error(0..0, "directory module not found")); } } for imp in program.imports() { if imp.alias().is_some() { diagnostics.push(Diagnostic::error( imp.node().byte_range(), "aliased import is not supported", )); continue; } if imp.version().is_some() { diagnostics.push(Diagnostic::warning( imp.node().byte_range(), "import version is ignored", )); } // TODO: anchor diagnostic message onto imp.source() node let id = match imp.source() { UiImportSource::Identifier(x) => ModuleIdBuf::Named(x.to_string(doc.source()).into()), UiImportSource::String(x) => { if let Some(p) = doc.path().and_then(|p| p.parent()) { ModuleIdBuf::Directory(qmldir::normalize_path(p.join(x))) } else { diagnostics.push(Diagnostic::error( imp.node().byte_range(), "cannot resolve directory path against inline QML document", )); continue; } } }; if !module_space.import_module(id.as_ref()) { diagnostics.push(Diagnostic::error( imp.node().byte_range(), "module not found", )); } } module_space } fn build_object_code_maps<'a, 't, 's>( doc: &'s UiDocument, type_space: &'s ImportedModuleSpace<'a>, object_tree: &'s ObjectTree<'a, 't>, base_ctx: &'s BuildContext<'a>, diagnostics: &mut Diagnostics, ) -> Vec<ObjectCodeMap<'a, 't, 's>> { object_tree .flat_iter() .map(|obj_node| { let ctx = ObjectContext::new(doc, type_space, object_tree, obj_node, base_ctx); ObjectCodeMap::build(&ctx, obj_node, diagnostics) }) .collect() }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/uigen/objcode.rs
Rust
//! Code storage for UI object. use super::context::ObjectContext; use crate::diagnostic::{Diagnostic, Diagnostics}; use crate::objtree::ObjectNode; use crate::qmlast::{Node, UiBindingMap, UiBindingValue}; use crate::qtname; use crate::tir::interpret::EvaluatedValue; use crate::tir::{self, CodeBody}; use crate::typemap::{ Class, Method, MethodKind, MethodMatches, NamedType, Property, TypeKind, TypeSpace as _, }; use crate::typeutil; use once_cell::sync::OnceCell; use std::collections::{hash_map, HashMap}; use std::iter::FusedIterator; /// Stores codes found in UI object definition. #[derive(Debug)] pub(super) struct ObjectCodeMap<'a, 't, 's> { properties: HashMap<&'s str, PropertyCode<'a, 't, 's>>, callbacks: Vec<CallbackCode<'a, 't>>, attached_properties: HashMap<Class<'a>, (Class<'a>, HashMap<&'s str, PropertyCode<'a, 't, 's>>)>, } impl<'a, 't, 's> ObjectCodeMap<'a, 't, 's> { pub fn build( ctx: &ObjectContext<'a, 't, 's>, obj_node: ObjectNode<'a, 't, '_>, diagnostics: &mut Diagnostics, ) -> Self { let binding_map = diagnostics .consume_err(obj_node.obj().build_binding_map(ctx.source)) .unwrap_or_default(); let (properties, callbacks) = build_properties_callbacks(ctx, obj_node.class(), &binding_map, diagnostics); let attached_type_map = diagnostics .consume_err(obj_node.obj().build_attached_type_map(ctx.source)) .unwrap_or_default(); let attached_properties = attached_type_map .iter() .filter_map(|(names, (id, binding_map))| { // TODO: look up qualified name without joining let type_name = names.join("::"); let (cls, acls) = resolve_attached_class(ctx, id.node(), &type_name, diagnostics)?; let props = build_properties_map(ctx, &acls, binding_map, diagnostics); Some((cls, (acls, props))) }) .collect(); ObjectCodeMap { properties, callbacks, attached_properties, } } /// Map of property name to binding code. pub fn properties(&self) -> &HashMap<&'s str, PropertyCode<'a, 't, 's>> { &self.properties } /// List of signal callback codes. pub fn callbacks(&self) -> &[CallbackCode<'a, 't>] { &self.callbacks } /// Map of attaching class to attached properties map. pub fn all_attached_properties( &self, ) -> &HashMap<Class<'a>, (Class<'a>, HashMap<&'s str, PropertyCode<'a, 't, 's>>)> { &self.attached_properties } /// Looks up attached class and properties by the attaching class. pub fn attached_properties( &self, cls: &Class<'a>, ) -> Option<&(Class<'a>, HashMap<&'s str, PropertyCode<'a, 't, 's>>)> { self.attached_properties.get(cls) } /// Iterates `CodeBody` stored in this map. pub fn code_bodies<'m>(&'m self) -> impl Iterator<Item = &'m CodeBody<'a>> { let a = PropertyCodeBodies::new(&self.properties); let b = self.callbacks.iter().map(|c| &c.code); let c = self .attached_properties .values() .flat_map(|(_, m)| PropertyCodeBodies::new(m)); a.chain(b).chain(c) } } fn build_properties_callbacks<'a, 't, 's>( ctx: &ObjectContext<'a, 't, '_>, cls: &Class<'a>, binding_map: &UiBindingMap<'t, 's>, diagnostics: &mut Diagnostics, ) -> ( HashMap<&'s str, PropertyCode<'a, 't, 's>>, Vec<CallbackCode<'a, 't>>, ) { let mut properties = HashMap::new(); let mut callbacks = Vec::new(); for (&name, value) in binding_map { let cb_name = qtname::callback_to_signal_name(name); if let Some(r) = cls.get_property(name) { match r { Ok(desc) => { if let Some(p) = PropertyCode::build(ctx, desc, value, diagnostics) { properties.insert(name, p); } } Err(e) => { diagnostics.push(Diagnostic::error( value.binding_node().byte_range(), format!("property resolution failed: {e}"), )); } } } else if let Some(r) = cb_name.as_ref().and_then(|n| cls.get_public_method(n)) { match r.map(uniquify_methods) { Ok(Some(desc)) if desc.kind() == MethodKind::Signal => { if let Some(c) = CallbackCode::build(ctx, desc, value, diagnostics) { callbacks.push(c); } } Ok(Some(_)) => { diagnostics.push(Diagnostic::error( value.binding_node().byte_range(), "not a signal", )); } Ok(None) => { diagnostics.push(Diagnostic::error( value.binding_node().byte_range(), "cannot bind to overloaded signal", )); } Err(e) => { diagnostics.push(Diagnostic::error( value.binding_node().byte_range(), format!("signal resolution failed: {e}"), )); } } } else { let class_name = cls.qualified_cxx_name(); let msg = if let Some(n) = cb_name.as_ref() { format!("unknown signal of class '{}': {}", class_name, n) } else { format!("unknown property of class '{}': {}", class_name, name) }; diagnostics.push(Diagnostic::error(value.binding_node().byte_range(), msg)); } } (properties, callbacks) } fn build_properties_map<'a, 't, 's>( ctx: &ObjectContext<'a, 't, '_>, cls: &Class<'a>, binding_map: &UiBindingMap<'t, 's>, diagnostics: &mut Diagnostics, ) -> HashMap<&'s str, PropertyCode<'a, 't, 's>> { let (properties, callbacks) = build_properties_callbacks(ctx, cls, binding_map, diagnostics); for c in &callbacks { diagnostics.push(Diagnostic::error( c.binding_node().byte_range(), "attached/nested/gadget callback is not supported", )); } properties } fn resolve_attached_class<'a>( ctx: &ObjectContext<'a, '_, '_>, node: Node, type_name: &str, diagnostics: &mut Diagnostics, ) -> Option<(Class<'a>, Class<'a>)> { let cls = match ctx.type_space.get_type_scoped(type_name) { Some(Ok(ty)) => { if let Some(cls) = ty.into_class() { cls } else { diagnostics.push(Diagnostic::error( node.byte_range(), format!("invalid attaching type: {type_name}"), )); return None; } } Some(Err(e)) => { diagnostics.push(Diagnostic::error( node.byte_range(), format!("attaching type resolution failed: {e}"), )); return None; } None => { diagnostics.push(Diagnostic::error( node.byte_range(), format!("unknown attaching type: {type_name}"), )); return None; } }; let acls = match cls.attached_class() { Some(Ok(cls)) => cls, Some(Err(e)) => { diagnostics.push(Diagnostic::error( node.byte_range(), format!("attached type resolution failed: {e}"), )); return None; } None => { diagnostics.push(Diagnostic::error( node.byte_range(), format!("no attached type for type: {type_name}"), )); return None; } }; Some((cls, acls)) } fn uniquify_methods(methods: MethodMatches) -> Option<Method> { match methods { MethodMatches::Unique(m) => Some(m), MethodMatches::Overloaded(mut meths) => { // If a function has default parameters, more than one metatype entries are // generated: e.g. clicked(bool = false) -> [clicked(), clicked(bool)]. // There's no way to discriminate them from true overloaded functions, and // default parameters are common in button/action signals. Therefore, we assume // that two functions are identical if their leading arguments are the same. meths.sort_by_key(|m| -(m.arguments_len() as isize)); let mut known = meths.pop().expect("method matches should not be empty"); while let Some(m) = meths.pop() { if known.kind() == m.kind() && known.return_type() == m.return_type() && m.argument_types().starts_with(known.argument_types()) { known = m; } else { return None; } } Some(known) } } } /// Property binding code or map with its description. /// /// This keeps track of constant evaluation state, which shouldn't be updated after /// cloning the `PropertyCode` storage. Therefore, it does not implement `Clone`. #[derive(Debug)] pub(super) struct PropertyCode<'a, 't, 's> { desc: Property<'a>, node: Node<'t>, kind: PropertyCodeKind<'a, 't, 's>, evaluated_value: OnceCell<Option<EvaluatedValue>>, } impl<'a, 't, 's> PropertyCode<'a, 't, 's> { pub fn build( ctx: &ObjectContext<'a, 't, '_>, desc: Property<'a>, value: &UiBindingValue<'t, 's>, diagnostics: &mut Diagnostics, ) -> Option<Self> { let kind = PropertyCodeKind::build(ctx, desc.value_type().clone(), value, diagnostics)?; Some(PropertyCode { desc, node: value.node(), kind, evaluated_value: OnceCell::new(), }) } pub fn desc(&self) -> &Property<'a> { &self.desc } pub fn node(&self) -> Node<'t> { self.node } pub fn binding_node(&self) -> Node<'t> { // see UiBindingValue::binding_node() self.node .parent() .expect("binding value node should have parent") } pub fn kind(&self) -> &PropertyCodeKind<'a, 't, 's> { &self.kind } /// Whether or not this has been successfully evaluated to a constant value. /// /// If this is a map, returns true only if all descendant properties are constants. pub fn is_evaluated_constant(&self) -> bool { match &self.kind { PropertyCodeKind::Expr(..) => self .evaluated_value .get() .map(|v| v.is_some()) .unwrap_or(false), PropertyCodeKind::GadgetMap(_, map) | PropertyCodeKind::ObjectMap(_, map) => { map.values().all(|p| p.is_evaluated_constant()) } } } /// Evaluates the code once as constant expression, caches the evaluated value. /// /// If this is a map, returns None. pub fn evaluate(&self) -> Option<EvaluatedValue> { self.evaluated_value .get_or_init(|| self.evaluate_uncached()) .clone() } fn evaluate_uncached(&self) -> Option<EvaluatedValue> { match &self.kind { PropertyCodeKind::Expr(_, code) => tir::evaluate_code(code), PropertyCodeKind::GadgetMap(..) | PropertyCodeKind::ObjectMap(..) => None, } } } /// Variant for property binding codes. #[derive(Debug)] pub(super) enum PropertyCodeKind<'a, 't, 's> { /// Value expression. /// /// The return type of the code is not verified. Expr(TypeKind<'a>, CodeBody<'a>), /// Map of gadget (or value object) properties. GadgetMap(Class<'a>, HashMap<&'s str, PropertyCode<'a, 't, 's>>), /// Map of object properties. ObjectMap(Class<'a>, HashMap<&'s str, PropertyCode<'a, 't, 's>>), } impl<'a, 't, 's> PropertyCodeKind<'a, 't, 's> { pub fn build( ctx: &ObjectContext<'a, 't, '_>, ty: TypeKind<'a>, value: &UiBindingValue<'t, 's>, diagnostics: &mut Diagnostics, ) -> Option<Self> { match value { UiBindingValue::Node(n) => { // TODO: wanna verify return type, but can't because static uigen has // various implicit conversion rules (e.g. string -> color.) let mut code = tir::build(ctx, *n, ctx.source, diagnostics)?; tir::analyze_code_property_dependency(&mut code, diagnostics); Some(PropertyCodeKind::Expr(ty, code)) } UiBindingValue::Map(n, m) => match ty { TypeKind::Just(NamedType::Class(cls)) => { let map = build_properties_map(ctx, &cls, m, diagnostics); Some(PropertyCodeKind::GadgetMap(cls, map)) } TypeKind::Pointer(NamedType::Class(cls)) => { // TODO: handle callback on nested object let map = build_properties_map(ctx, &cls, m, diagnostics); Some(PropertyCodeKind::ObjectMap(cls, map)) } _ => { diagnostics.push(Diagnostic::error( n.byte_range(), format!( "binding map cannot be parsed as non-class type '{}'", ty.qualified_cxx_name() ), )); None } }, } } } /// Recursive iterator over `CodeBody` of properties stored in `ObjectCodeMap`. #[derive(Clone, Debug)] pub(super) struct PropertyCodeBodies<'a, 't, 's, 'm> { stack: Vec<hash_map::Values<'m, &'s str, PropertyCode<'a, 't, 's>>>, } impl<'a, 't, 's, 'm> PropertyCodeBodies<'a, 't, 's, 'm> { fn new(map: &'m HashMap<&'s str, PropertyCode<'a, 't, 's>>) -> Self { PropertyCodeBodies { stack: vec![map.values()], } } } impl<'a, 'm> Iterator for PropertyCodeBodies<'a, '_, '_, 'm> { type Item = &'m CodeBody<'a>; fn next(&mut self) -> Option<Self::Item> { while let Some(iter) = self.stack.last_mut() { if let Some(p) = iter.next() { match &p.kind { PropertyCodeKind::Expr(_, code) => return Some(code), PropertyCodeKind::GadgetMap(_, map) | PropertyCodeKind::ObjectMap(_, map) => { self.stack.push(map.values()) } } } else { self.stack.pop(); } } None } } impl FusedIterator for PropertyCodeBodies<'_, '_, '_, '_> {} /// Signal callback code with its description. #[derive(Clone, Debug)] pub(super) struct CallbackCode<'a, 't> { desc: Method<'a>, node: Node<'t>, code: CodeBody<'a>, } impl<'a, 't> CallbackCode<'a, 't> { pub fn build( ctx: &ObjectContext<'a, 't, '_>, desc: Method<'a>, value: &UiBindingValue<'t, '_>, diagnostics: &mut Diagnostics, ) -> Option<Self> { let code = match value { UiBindingValue::Node(n) => tir::build_callback(ctx, *n, ctx.source, diagnostics)?, UiBindingValue::Map(n, _) => { diagnostics.push(Diagnostic::error( n.byte_range(), "signal callback cannot be a map", )); return None; } }; if !verify_callback_parameter_type(&desc, &code, diagnostics) { return None; } Some(CallbackCode { desc, node: value.node(), code, }) } pub fn desc(&self) -> &Method<'a> { &self.desc } /* pub fn node(&self) -> Node<'t> { self.node } */ pub fn binding_node(&self) -> Node<'t> { // see UiBindingValue::binding_node() self.node .parent() .expect("binding value node should have parent") } pub fn code(&self) -> &CodeBody<'a> { &self.code } } #[must_use] fn verify_callback_parameter_type( desc: &Method, code: &CodeBody, diagnostics: &mut Diagnostics, ) -> bool { if code.parameter_count > desc.arguments_len() { let s = code.locals[desc.arguments_len()].byte_range.start; let e = code.locals[code.parameter_count - 1].byte_range.end; diagnostics.push(Diagnostic::error( s..e, format!( "too many callback arguments (expected: 0..{}, actual: {})", desc.arguments_len(), code.parameter_count, ), )); return false; } let incompatible_args: Vec<_> = desc .argument_types() .iter() .zip(&code.locals[..code.parameter_count]) .filter(|(ty, a)| !typeutil::is_concrete_assignable(&a.ty, ty).unwrap_or(false)) .collect(); for (ty, a) in &incompatible_args { let msg = format!( "incompatible callback arguments (expected: {}, actual: {})", ty.qualified_cxx_name(), a.ty.qualified_cxx_name(), ); diagnostics.push(Diagnostic::error(a.byte_range.clone(), msg)); } incompatible_args.is_empty() }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/uigen/object.rs
Rust
use super::context::{BuildDocContext, ObjectContext}; use super::expr::{self, SerializableValue}; use super::gadget::ModelItem; use super::layout::Layout; use super::objcode::{PropertyCode, PropertyCodeKind}; use super::property::{self, PropertySetter}; use super::XmlWriter; use crate::diagnostic::{Diagnostic, Diagnostics}; use crate::objtree::ObjectNode; use crate::qtname; use crate::typemap::{Class, TypeSpace}; use quick_xml::events::{BytesStart, Event}; use std::collections::HashMap; use std::io; /// Reserved name for <addaction name="separator"/>. const ACTION_SEPARATOR_NAME: &str = "separator"; /// Variant for the object definitions which can be serialized to UI XML. #[derive(Clone, Debug)] pub enum UiObject { Action(Action), ActionSeparator, Layout(Layout), Menu(Widget), Widget(Widget), } impl UiObject { /// Creates a serializable tree by visiting the given node and its children recursively. pub(super) fn build( ctx: &BuildDocContext, obj_node: ObjectNode, diagnostics: &mut Diagnostics, ) -> Self { let cls = obj_node.class(); if cls.is_derived_from(&ctx.classes.action) { confine_children(obj_node, diagnostics); if is_action_separator(ctx, obj_node, diagnostics) { UiObject::ActionSeparator } else { UiObject::Action(Action::new( &ctx.make_object_context(obj_node), obj_node.name(), ctx.code_map_for_object(obj_node).properties(), diagnostics, )) } } else if cls.is_derived_from(&ctx.classes.layout) { UiObject::Layout(Layout::build(ctx, obj_node, diagnostics)) } else if cls.is_derived_from(&ctx.classes.menu) { UiObject::Menu(Widget::build(ctx, obj_node, diagnostics)) } else if cls.is_derived_from(&ctx.classes.widget) { UiObject::Widget(Widget::build(ctx, obj_node, diagnostics)) } else { diagnostics.push(Diagnostic::error( obj_node.obj().node().byte_range(), format!( "class '{}' is not a QAction, QLayout, nor QWidget", cls.qualified_cxx_name() ), )); // but process as widget to report as many errors as possible UiObject::Widget(Widget::build(ctx, obj_node, diagnostics)) } } /// Serializes this to UI XML. pub fn serialize_to_xml<W>(&self, writer: &mut XmlWriter<W>) -> io::Result<()> where W: io::Write, { use UiObject::*; match self { Action(x) => x.serialize_to_xml(writer), ActionSeparator => Ok(()), Layout(x) => x.serialize_to_xml(writer), Menu(x) | Widget(x) => x.serialize_to_xml(writer), } } } fn is_action_separator( ctx: &BuildDocContext, obj_node: ObjectNode, diagnostics: &mut Diagnostics, ) -> bool { // Only QAction { separator: true } can be translated to <addaction name="separator"/>. // Others will be mapped to a QAction having dynamic "separator" property since // "separator" isn't actually a Q_PROPERTY. // TODO: can't be a static separator if object id is referenced from any other expression let code_map = ctx.code_map_for_object(obj_node); let properties_code_map = code_map.properties(); if obj_node.class().is_derived_from(&ctx.classes.action) && code_map.callbacks().is_empty() && properties_code_map.len() == 1 && properties_code_map.contains_key("separator") { let obj_ctx = ctx.make_object_context(obj_node); property::get_bool(&obj_ctx, properties_code_map, "separator", diagnostics) .map(|(_, b)| b) .unwrap_or(false) } else { false } } /// Action definition which can be serialized to UI XML. #[derive(Clone, Debug)] pub struct Action { pub name: String, pub properties: HashMap<String, (SerializableValue, PropertySetter)>, } impl Action { fn new( ctx: &ObjectContext, name: impl Into<String>, properties_code_map: &HashMap<&str, PropertyCode>, diagnostics: &mut Diagnostics, ) -> Self { let properties = property::make_serializable_map( ctx, properties_code_map, &["separator"], // can't be handled by uic diagnostics, ); Action { name: name.into(), properties, } } /// Serializes this to UI XML. pub fn serialize_to_xml<W>(&self, writer: &mut XmlWriter<W>) -> io::Result<()> where W: io::Write, { let tag = BytesStart::new("action").with_attributes([("name", self.name.as_ref())]); writer.write_event(Event::Start(tag.borrow()))?; property::serialize_properties_to_xml(writer, "property", &self.properties)?; writer.write_event(Event::End(tag.to_end()))?; Ok(()) } } /// Widget definition which can be serialized to UI XML. #[derive(Clone, Debug)] pub struct Widget { pub class: String, pub name: String, pub attributes: HashMap<String, (SerializableValue, PropertySetter)>, pub properties: HashMap<String, (SerializableValue, PropertySetter)>, pub actions: Vec<String>, pub items: Vec<ModelItem>, pub children: Vec<UiObject>, } impl Widget { /// Creates a serializable tree by visiting the children recursively. pub(super) fn build( ctx: &BuildDocContext, obj_node: ObjectNode, diagnostics: &mut Diagnostics, ) -> Self { let children = if obj_node.class().is_derived_from(&ctx.classes.tab_widget) { process_tab_widget_children(ctx, obj_node, diagnostics) } else { process_widget_children(ctx, obj_node, diagnostics) }; let properties_code_map = ctx.code_map_for_object(obj_node).properties(); let actions = if let Some(p) = properties_code_map.get("actions") { if let Some(refs) = expr::build_object_ref_list(p, diagnostics) { refs.into_iter() .map(|id| { let o = ctx .object_tree .get_by_id(&id) .expect("object ref must be valid"); if is_action_separator(ctx, o, diagnostics) { ACTION_SEPARATOR_NAME.to_owned() } else { id } }) .collect() } else { vec![] } } else { collect_action_like_children(&children) }; Self::new( &ctx.make_object_context(obj_node), obj_node.class(), obj_node.name(), properties_code_map, actions, children, diagnostics, ) } pub(super) fn new( ctx: &ObjectContext, class: &Class, name: impl Into<String>, properties_code_map: &HashMap<&str, PropertyCode>, actions: Vec<String>, children: Vec<UiObject>, diagnostics: &mut Diagnostics, ) -> Self { let mut pseudo_property_names = vec!["actions", "model"]; let items = if class.is_derived_from(&ctx.classes.combo_box) || class.is_derived_from(&ctx.classes.list_widget) { if let Some(p) = properties_code_map.get("model") { expr::build_item_model(p, diagnostics).unwrap_or_default() } else { vec![] } } else { vec![] }; let mut attributes = HashMap::new(); if class.is_derived_from(&ctx.classes.table_view) { pseudo_property_names.extend(["horizontalHeader", "verticalHeader"]); flatten_object_properties_into_attributes( ctx, &mut attributes, properties_code_map, "horizontalHeader", diagnostics, ); flatten_object_properties_into_attributes( ctx, &mut attributes, properties_code_map, "verticalHeader", diagnostics, ); } if class.is_derived_from(&ctx.classes.tree_view) { pseudo_property_names.extend(["header"]); flatten_object_properties_into_attributes( ctx, &mut attributes, properties_code_map, "header", diagnostics, ); } let mut properties = property::make_serializable_map( ctx, properties_code_map, &pseudo_property_names, diagnostics, ); if class.is_derived_from(&ctx.classes.push_button) { // see metatype_tweak.rs, "default" is a reserved word if let Some((mut k, (v, _))) = properties.remove_entry("default_") { k.pop(); properties.insert(k, (v, PropertySetter::StdSet)); } } Widget { class: class.qualified_cxx_name().into_owned(), name: name.into(), attributes, properties, actions, items, children, } } /// Serializes this to UI XML. pub fn serialize_to_xml<W>(&self, writer: &mut XmlWriter<W>) -> io::Result<()> where W: io::Write, { let tag = BytesStart::new("widget") .with_attributes([("class", self.class.as_ref()), ("name", self.name.as_ref())]); writer.write_event(Event::Start(tag.borrow()))?; property::serialize_properties_to_xml(writer, "attribute", &self.attributes)?; property::serialize_properties_to_xml(writer, "property", &self.properties)?; for n in &self.actions { writer.write_event(Event::Empty( BytesStart::new("addaction").with_attributes([("name", n.as_ref())]), ))?; } for e in &self.items { e.serialize_to_xml(writer)?; } for c in &self.children { c.serialize_to_xml(writer)?; } writer.write_event(Event::End(tag.to_end()))?; Ok(()) } } fn process_tab_widget_children( ctx: &BuildDocContext, obj_node: ObjectNode, diagnostics: &mut Diagnostics, ) -> Vec<UiObject> { obj_node .children() .map(|n| { let mut o = UiObject::build(ctx, n, diagnostics); match &mut o { UiObject::Menu(w) | UiObject::Widget(w) => { let code_map = ctx.code_map_for_object(n); if let Some((_, map)) = code_map.attached_properties(&ctx.classes.tab_widget) { w.attributes.extend( property::make_value_map( &ctx.make_object_context(n), map, &[], diagnostics, ) .into_iter() // don't care the setter since uic will handle them specially .map(|(k, v)| (k, (v, PropertySetter::StdSet))), ); } } UiObject::Action(_) | UiObject::ActionSeparator | UiObject::Layout(_) => {} } o }) .collect() } fn process_widget_children( ctx: &BuildDocContext, obj_node: ObjectNode, diagnostics: &mut Diagnostics, ) -> Vec<UiObject> { obj_node .children() .map(|n| UiObject::build(ctx, n, diagnostics)) .collect() } fn collect_action_like_children(children: &[UiObject]) -> Vec<String> { children .iter() .filter_map(|child| match child { UiObject::Action(a) => Some(a.name.clone()), UiObject::ActionSeparator => Some(ACTION_SEPARATOR_NAME.to_owned()), UiObject::Menu(w) => Some(w.name.clone()), UiObject::Layout(_) | UiObject::Widget(_) => None, }) .collect() } fn flatten_object_properties_into_attributes( ctx: &ObjectContext, attributes: &mut HashMap<String, (SerializableValue, PropertySetter)>, properties_code_map: &HashMap<&str, PropertyCode>, name: &str, diagnostics: &mut Diagnostics, ) { if let Some(property_code) = properties_code_map.get(name) { match property_code.kind() { PropertyCodeKind::ObjectMap(_, map) => { attributes.extend( property::make_serializable_map(ctx, map, &[], diagnostics) .into_iter() .map(|(k, v)| (name.to_owned() + &qtname::to_ascii_capitalized(&k), v)), ); } _ => { diagnostics.push(Diagnostic::error( property_code.node().byte_range(), "not a properties map", )); } } } } pub(super) fn confine_children(obj_node: ObjectNode, diagnostics: &mut Diagnostics) { if let Some(n) = obj_node.children().next() { // TODO: error on obj.node(), and add hint to child nodes diagnostics.push(Diagnostic::error( n.obj().node().byte_range(), format!( "'{}' should have no children", obj_node.class().qualified_cxx_name() ), )); } }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/uigen/property.rs
Rust
use super::context::ObjectContext; use super::expr::{SerializableValue, SimpleValue}; use super::objcode::PropertyCode; use super::XmlWriter; use crate::diagnostic::{Diagnostic, Diagnostics}; use itertools::Itertools as _; use quick_xml::events::{BytesStart, Event}; use std::collections::HashMap; use std::fmt::Debug; use std::io; /// Type of the property setter to be used by `uic`. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum PropertySetter { /// `QObject::setProperty(<name>, <value>)` Var, /// `set<Name>(<value>)` StdSet, } /// Creates a map of serializable properties from the given code map. /// /// `excludes` is a list of property names which should have been processed in a special /// manner by the caller. The list should be small in practice. pub(super) fn make_serializable_map( ctx: &ObjectContext, properties_code_map: &HashMap<&str, PropertyCode>, excludes: &[&str], diagnostics: &mut Diagnostics, ) -> HashMap<String, (SerializableValue, PropertySetter)> { properties_code_map .iter() .filter(|(name, _)| !excludes.contains(name)) .filter_map(|(&name, property_code)| { // evaluate once to sort out constant/dynamic nature let v = SerializableValue::build(ctx, property_code, diagnostics)?; if property_code.desc().is_writable() { let s = if property_code.desc().is_std_set() { PropertySetter::StdSet } else { PropertySetter::Var }; Some((name.to_owned(), (v, s))) } else { diagnostics.push(Diagnostic::error( property_code.binding_node().byte_range(), "not a writable property", )); None } }) .collect() } /// Creates a map of gadget properties from the given code map. /// /// Unlike `make_serializable_map()`, this does not check for the property's setter /// availability since the gadget properties will be passed as constructor arguments. pub(super) fn make_value_map( ctx: &ObjectContext, properties_code_map: &HashMap<&str, PropertyCode>, excludes: &[&str], diagnostics: &mut Diagnostics, ) -> HashMap<String, SerializableValue> { properties_code_map .iter() .filter(|(name, _)| !excludes.contains(name)) .filter_map(|(&name, property_code)| { let v = SerializableValue::build(ctx, property_code, diagnostics)?; Some((name.to_owned(), v)) }) .collect() } pub(super) fn get_simple_value<'a, 't, 's, 'm>( ctx: &ObjectContext, properties_code_map: &'m HashMap<&str, PropertyCode<'a, 't, 's>>, name: impl AsRef<str>, diagnostics: &mut Diagnostics, ) -> Option<(&'m PropertyCode<'a, 't, 's>, SimpleValue)> { let p = properties_code_map.get(name.as_ref())?; match SerializableValue::build(ctx, p, diagnostics) { Some(SerializableValue::Simple(s)) => Some((p, s)), Some(_) => { diagnostics.push(Diagnostic::error( p.node().byte_range(), "unexpected value type", )); None } None => None, } } pub(super) fn get_bool<'a, 't, 's, 'm>( ctx: &ObjectContext, properties_code_map: &'m HashMap<&str, PropertyCode<'a, 't, 's>>, name: impl AsRef<str>, diagnostics: &mut Diagnostics, ) -> Option<(&'m PropertyCode<'a, 't, 's>, bool)> { let (p, v) = get_simple_value(ctx, properties_code_map, name, diagnostics)?; if let Some(b) = v.as_bool() { Some((p, b)) } else { diagnostics.push(Diagnostic::error( p.node().byte_range(), "unexpected value type", )); None } } pub(super) fn get_enum<'a, 't, 's, 'm>( ctx: &ObjectContext, properties_code_map: &'m HashMap<&str, PropertyCode<'a, 't, 's>>, name: impl AsRef<str>, diagnostics: &mut Diagnostics, ) -> Option<(&'m PropertyCode<'a, 't, 's>, String)> { let (p, v) = get_simple_value(ctx, properties_code_map, name, diagnostics)?; if let Some(s) = v.into_enum() { Some((p, s)) } else { diagnostics.push(Diagnostic::error( p.node().byte_range(), "unexpected value type", )); None } } pub(super) fn get_i32<'a, 't, 's, 'm>( ctx: &ObjectContext, properties_code_map: &'m HashMap<&str, PropertyCode<'a, 't, 's>>, name: impl AsRef<str>, diagnostics: &mut Diagnostics, ) -> Option<(&'m PropertyCode<'a, 't, 's>, i32)> { let (p, v) = get_simple_value(ctx, properties_code_map, name, diagnostics)?; if let Some(d) = v.as_number() { Some((p, d as i32)) } else { diagnostics.push(Diagnostic::error( p.node().byte_range(), "unexpected value type", )); None } } pub(super) fn serialize_properties_to_xml<W, T>( writer: &mut XmlWriter<W>, tag_name: T, properties: &HashMap<String, (SerializableValue, PropertySetter)>, ) -> io::Result<()> where W: io::Write, T: AsRef<str>, { let tag_name = tag_name.as_ref(); for (k, (v, s)) in properties.iter().sorted_by_key(|&(k, _)| k) { let mut tag = BytesStart::new(tag_name).with_attributes([("name", k.as_ref())]); if *s != PropertySetter::StdSet { tag.push_attribute(("stdset", "0")); } writer.write_event(Event::Start(tag.borrow()))?; v.serialize_to_xml(writer)?; writer.write_event(Event::End(tag.to_end()))?; } Ok(()) }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/src/uigen/xmlutil.rs
Rust
//! Utility for UI XML generation. use super::XmlWriter; use quick_xml::events::{BytesStart, BytesText, Event}; use std::io; pub(super) fn write_tagged_str<W, S, T>( writer: &mut XmlWriter<W>, tag: T, content: S, ) -> io::Result<()> where W: io::Write, S: AsRef<str>, T: AsRef<str>, { let tag = BytesStart::new(tag.as_ref()); writer.write_event(Event::Start(tag.borrow()))?; writer.write_event(Event::Text(BytesText::new(content.as_ref())))?; writer.write_event(Event::End(tag.to_end()))?; Ok(()) }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/tests/test_tir_build.rs
Rust
use self::tir_testenv::*; pub mod tir_testenv; #[test] fn float_literal_zeros() { insta::assert_snapshot!(dump("+0.0"), @r###" .0: return 0.0: double "###); insta::assert_snapshot!(dump("-0.0"), @r###" .0: return -0.0: double "###); insta::assert_snapshot!(dump("+0.0 === -0.0"), @r###" .0: return true: bool "###); } #[test] fn string_literal() { insta::assert_snapshot!(dump("'foo'"), @r###" .0: return "foo": QString "###); } #[test] fn enum_ref() { insta::assert_snapshot!(dump("Foo.Bar0"), @r###" .0: return 'Foo::Bar0': Foo::Bar "###); } #[test] fn untyped_null_literal() { insta::assert_snapshot!(dump("null"), @r###" .0: return nullptr: nullptr_t "###); } #[test] fn empty_array_literal() { insta::assert_snapshot!(dump("[]"), @r###" .0: return {}: list "###); } #[test] fn string_array_literal() { insta::assert_snapshot!(dump("['foo', 'bar']"), @r###" %0: QStringList .0: %0 = make_list 'QStringList', {"foo": QString, "bar": QString} return %0: QStringList "###); } #[test] fn object_array_literal() { insta::assert_snapshot!(dump("[foo, foo2, foo_sub as Foo, null]"), @r###" %0: Foo* %1: QList<Foo*> .0: %0 = copy [foo_sub]: FooSub* %1 = make_list 'QList<Foo*>', {[foo]: Foo*, [foo2]: Foo*, %0: Foo*, nullptr: nullptr_t} return %1: QList<Foo*> "###); } #[test] fn object_array_literal_no_implicit_upcast() { let env = Env::new(); assert!(env.try_build("[foo, foo_sub]").is_err()); } #[test] fn dynamic_array_literal() { insta::assert_snapshot!(dump("[foo.text, foo2.text]"), @r###" %0: QString %1: QString %2: QStringList .0: %0 = read_property [foo]: Foo*, "text" %1 = read_property [foo2]: Foo*, "text" %2 = make_list 'QStringList', {%0: QString, %1: QString} return %2: QStringList "###); } #[test] fn incompatible_array_literal() { let env = Env::new(); assert!(env.try_build("[foo, 'bar']").is_err()); } #[test] fn local_declaration_with_literal() { insta::assert_snapshot!(dump("{ let s = 'hello'; s }"), @r###" %0: QString .0: %0 = copy "hello": QString return %0: QString "###); } #[test] fn local_declaration_with_property() { insta::assert_snapshot!(dump("{ let s = foo.checked; s }"), @r###" %0: bool %1: bool .0: %0 = read_property [foo]: Foo*, "checked" %1 = copy %0: bool return %1: bool "###); } #[test] fn local_declaration_with_ternary() { insta::assert_snapshot!(dump("{ let s = foo.checked ? 1 : 2; s }"), @r###" %0: bool %1: int %2: int .0: %0 = read_property [foo]: Foo*, "checked" br_cond %0: bool, .1, .2 .1: %1 = copy 1: integer br .3 .2: %1 = copy 2: integer br .3 .3: %2 = copy %1: int return %2: int "###); } #[test] fn local_declaration_in_nested_block() { insta::assert_snapshot!(dump(r###"{ let a = 'outer'; { let a = a + 'inner'; foo.text = a; } foo2.text = a; }"###), @r###" %0: QString %1: QString %2: QString .0: %0 = copy "outer": QString %1 = binary_op '+', %0: QString, "inner": QString %2 = copy %1: QString write_property [foo]: Foo*, "text", %2: QString write_property [foo2]: Foo*, "text", %0: QString return _: void "###); } #[test] fn local_declaration_without_value_but_type_annotation() { insta::assert_snapshot!(dump("{ let s: int; s = 0 }"), @r###" %0: int .0: %0 = copy 0: integer return _: void "###); } #[test] fn local_declaration_with_value_and_type_annotation() { insta::assert_snapshot!(dump("{ let s: uint = 0 }"), @r###" %0: uint .0: %0 = copy 0: integer return _: void "###); } #[test] fn local_declaration_with_null_and_type_annotation() { insta::assert_snapshot!(dump("{ let s: Foo = null }"), @r###" %0: Foo* .0: %0 = copy nullptr: nullptr_t return _: void "###); } #[test] fn local_declaration_with_null_but_no_type_annotation() { let env = Env::new(); assert!(env.try_build("{ let a = null }").is_err()); } #[test] fn local_declaration_with_void() { let env = Env::new(); assert!(env.try_build("{ let a = foo.done() }").is_err()); } #[test] fn local_declaration_type_mismatch() { let env = Env::new(); assert!(env.try_build("{ let a: int = 'whatever') }").is_err()); } #[test] fn const_declaration_without_value_but_type_annotation() { let env = Env::new(); assert!(env.try_build("{ const a: int }").is_err()); } #[test] fn local_assignment_branched() { insta::assert_snapshot!(dump(r###"{ let a = ''; if (foo.checked) { a = foo.text; } else if (foo2.checked) { a = foo2.text; } foo3.text = a; }"###), @r###" %0: QString %1: bool %2: QString %3: bool %4: QString .0: %0 = copy "": QString %1 = read_property [foo]: Foo*, "checked" br_cond %1: bool, .1, .2 .1: %2 = read_property [foo]: Foo*, "text" %0 = copy %2: QString br .5 .2: %3 = read_property [foo2]: Foo*, "checked" br_cond %3: bool, .3, .4 .3: %4 = read_property [foo2]: Foo*, "text" %0 = copy %4: QString br .4 .4: br .5 .5: write_property [foo3]: Foo*, "text", %0: QString return _: void "###); } #[test] fn local_assignment_type_mismatch() { let env = Env::new(); assert!(env.try_build("{ let a = true; a = foo.text }").is_err()); } #[test] fn const_declaration() { insta::assert_snapshot!(dump("{ const s = 'hello'; s }"), @r###" %0: QString .0: %0 = copy "hello": QString return %0: QString "###); } #[test] fn const_reassignment() { let env = Env::new(); assert!(env.try_build("{ const a = 0; a = 1 }").is_err()); } #[test] fn local_declaration_with_object_then_read_property() { insta::assert_snapshot!(dump("{ let o = foo; o.checked }"), @r###" %0: Foo* %1: bool .0: %0 = copy [foo]: Foo* %1 = read_property %0: Foo*, "checked" return %1: bool "###); } #[test] fn local_declaration_with_object_then_write_property() { insta::assert_snapshot!(dump("{ let o = foo; o.checked = true }"), @r###" %0: Foo* .0: %0 = copy [foo]: Foo* write_property %0: Foo*, "checked", true: bool return _: void "###); } #[test] fn local_name_as_type_member() { let env = Env::new(); assert!(env.try_build("{ let whatever = 0; Foo.whatever }").is_err()); } #[test] fn global_name_as_type_member() { let env = Env::new(); assert!(env.try_build("{ Foo.qsTr('') }").is_err()); } #[test] fn named_object_ref() { insta::assert_snapshot!(dump("foo"), @r###" .0: return [foo]: Foo* "###); } #[test] fn read_object_property() { insta::assert_snapshot!(dump("foo.checked"), @r###" %0: bool .0: %0 = read_property [foo]: Foo*, "checked" return %0: bool "###); } #[test] fn write_object_property() { insta::assert_snapshot!(dump("foo.checked = true"), @r###" .0: write_property [foo]: Foo*, "checked", true: bool return _: void "###); } #[test] fn read_list_subscript() { insta::assert_snapshot!(dump("foo.stringList[0]"), @r###" %0: QStringList %1: QString .0: %0 = read_property [foo]: Foo*, "stringList" %1 = read_subscript %0: QStringList, 0: integer return %1: QString "###); } #[test] fn write_list_subscript() { insta::assert_snapshot!(dump("{ let a = foo.stringList; a[0] = 'baz'; }"), @r###" %0: QStringList %1: QStringList .0: %0 = read_property [foo]: Foo*, "stringList" %1 = copy %0: QStringList write_subscript %1: QStringList, 0: integer, "baz": string return _: void "###); } #[test] fn write_list_subscript_incompatible_type() { let env = Env::new(); assert!(env.try_build("{ let a = ['foo']; a[0] = 0; }").is_err()); } #[test] fn write_list_subscript_rvalue() { let env = Env::new(); assert!(env.try_build("{ foo.stringList[0] = 'baz'; }").is_err()); } #[test] fn call_object_method() { insta::assert_snapshot!(dump("foo.done(1)"), @r###" .0: call_method [foo]: Foo*, "done", {1: integer} return _: void "###); } #[test] fn call_string_arg_method() { insta::assert_snapshot!(dump("'Hello %1'.arg('world')"), @r###" %0: QString .0: %0 = call_method "Hello %1": QString, "arg", {"world": QString} return %0: QString "###); } #[test] fn call_string_is_empty_method() { insta::assert_snapshot!(dump("'Hello %1'.isEmpty()"), @r###" %0: bool .0: %0 = call_method "Hello %1": QString, "isEmpty", {} return %0: bool "###); } #[test] fn call_array_is_empty_method() { insta::assert_snapshot!(dump("[0, 1, 2].isEmpty()"), @r###" %0: QList<int> %1: bool .0: %0 = make_list 'QList<int>', {0: integer, 1: integer, 2: integer} %1 = call_method %0: QList<int>, "isEmpty", {} return %1: bool "###); } #[test] fn call_console_log_function() { insta::assert_snapshot!(dump(r###"{ console.log(); console.debug("foo"); console.info(1); console.warn("bar", 2); console.error("baz", 3.0, foo); }"###), @r###" .0: call_builtin_function ConsoleLog(Log), {} call_builtin_function ConsoleLog(Debug), {"foo": string} call_builtin_function ConsoleLog(Info), {1: integer} call_builtin_function ConsoleLog(Warn), {"bar": string, 2: integer} call_builtin_function ConsoleLog(Error), {"baz": string, 3.0: double, [foo]: Foo*} return _: void "###); } #[test] fn call_max_function_against_ints() { insta::assert_snapshot!(dump("Math.max(foo.currentIndex, 0)"), @r###" %0: int %1: int .0: %0 = read_property [foo]: Foo*, "currentIndex" %1 = call_builtin_function Max, {%0: int, 0: integer} return %1: int "###); } #[test] fn call_min_function_against_strings() { insta::assert_snapshot!(dump("Math.min('foo', 'bar')"), @r###" %0: QString .0: %0 = call_builtin_function Min, {"foo": QString, "bar": QString} return %0: QString "###); } #[test] fn call_min_function_against_incompatible_args() { let env = Env::new(); assert!(env.try_build("Math.min(0, 1.0)").is_err()); } #[test] fn call_tr_function() { insta::assert_snapshot!(dump("qsTr('Hello')"), @r###" %0: QString .0: %0 = call_builtin_function Tr, {"Hello": string} return %0: QString "###); } #[test] fn call_tr_function_on_dynamic_string() { let env = Env::new(); assert!(env.try_build("qsTr(foo.text)").is_err()); } #[test] fn constant_number_arithmetic() { insta::assert_snapshot!(dump("(-1 + 2 * 3) / +4"), @r###" .0: return 1: integer "###); insta::assert_snapshot!(dump("(-1. + 2. * 3.) / +4."), @r###" .0: return 1.25: double "###); } #[test] fn constant_string_concatenation() { insta::assert_snapshot!(dump("'foo' + 'bar'"), @r###" .0: return "foobar": QString "###); } #[test] fn constant_bool_bitwise() { insta::assert_snapshot!(dump("false ^ true | false"), @r###" .0: return true: bool "###); } #[test] fn dynamic_bool_bitwise() { insta::assert_snapshot!(dump("foo.checked ^ foo2.checked | foo3.checked"), @r###" %0: bool %1: bool %2: bool %3: bool %4: bool .0: %0 = read_property [foo]: Foo*, "checked" %1 = read_property [foo2]: Foo*, "checked" %2 = binary_op '^', %0: bool, %1: bool %3 = read_property [foo3]: Foo*, "checked" %4 = binary_op '|', %2: bool, %3: bool return %4: bool "###); } #[test] fn dynamic_integer_arithmetic() { insta::assert_snapshot!(dump("-foo.currentIndex + 1"), @r###" %0: int %1: int %2: int .0: %0 = read_property [foo]: Foo*, "currentIndex" %1 = unary_op '-', %0: int %2 = binary_op '+', %1: int, 1: integer return %2: int "###); } #[test] fn dynamic_string_concatenation() { insta::assert_snapshot!(dump("'Hello ' + foo.text"), @r###" %0: QString %1: QString .0: %0 = read_property [foo]: Foo*, "text" %1 = binary_op '+', "Hello ": QString, %0: QString return %1: QString "###); } #[test] fn constant_integer_bitwise() { insta::assert_snapshot!(dump("((1 ^ 3) | 4) & ~0"), @r###" .0: return 6: integer "###); } #[test] fn constant_enum_bitwise() { insta::assert_snapshot!(dump("(Foo.Bar0 ^ Foo.Bar1 | Foo.Bar2) & ~Foo.Bar3"), @r###" %0: Foo::Bar %1: Foo::Bar %2: Foo::Bar %3: Foo::Bar .0: %0 = binary_op '^', 'Foo::Bar0': Foo::Bar, 'Foo::Bar1': Foo::Bar %1 = binary_op '|', %0: Foo::Bar, 'Foo::Bar2': Foo::Bar %2 = unary_op '~', 'Foo::Bar3': Foo::Bar %3 = binary_op '&', %1: Foo::Bar, %2: Foo::Bar return %3: Foo::Bar "###); } #[test] fn dynamic_integer_bitwise() { insta::assert_snapshot!(dump("~foo.currentIndex & foo2.currentIndex"), @r###" %0: int %1: int %2: int %3: int .0: %0 = read_property [foo]: Foo*, "currentIndex" %1 = unary_op '~', %0: int %2 = read_property [foo2]: Foo*, "currentIndex" %3 = binary_op '&', %1: int, %2: int return %3: int "###); } #[test] fn constant_bool_logical() { insta::assert_snapshot!(dump("!true && true || false"), @r###" %0: bool %1: bool .0: %0 = copy false: bool br_cond false: bool, .1, .2 .1: %0 = copy true: bool br .2 .2: %1 = copy true: bool br_cond %0: bool, .4, .3 .3: %1 = copy false: bool br .4 .4: return %1: bool "###); } #[test] fn dynamic_bool_logical() { insta::assert_snapshot!(dump("!foo.checked && foo2.checked || foo3.checked"), @r###" %0: bool %1: bool %2: bool %3: bool %4: bool %5: bool .0: %0 = read_property [foo]: Foo*, "checked" %1 = unary_op '!', %0: bool %3 = copy false: bool br_cond %1: bool, .1, .2 .1: %2 = read_property [foo2]: Foo*, "checked" %3 = copy %2: bool br .2 .2: %5 = copy true: bool br_cond %3: bool, .4, .3 .3: %4 = read_property [foo3]: Foo*, "checked" %5 = copy %4: bool br .4 .4: return %5: bool "###); } #[test] fn dynamic_bool_logical_and_in_ternary_condition() { insta::assert_snapshot!(dump("foo !== null && foo.checked ? foo.text : ''"), @r###" %0: bool %1: bool %2: bool %3: QString %4: QString .0: %0 = binary_op '!=', [foo]: Foo*, nullptr: nullptr_t %2 = copy false: bool br_cond %0: bool, .1, .2 .1: %1 = read_property [foo]: Foo*, "checked" %2 = copy %1: bool br .2 .2: br_cond %2: bool, .3, .4 .3: %3 = read_property [foo]: Foo*, "text" %4 = copy %3: QString br .5 .4: %4 = copy "": QString br .5 .5: return %4: QString "###); } #[test] fn const_literal_comparison() { insta::assert_snapshot!(dump("1 == 1"), @r###" .0: return true: bool "###); insta::assert_snapshot!(dump("1 > 2"), @r###" .0: return false: bool "###); insta::assert_snapshot!(dump("'bar' <= 'baz'"), @r###" .0: return true: bool "###); } #[test] fn const_enum_comparison() { insta::assert_snapshot!(dump("Foo.Bar1 == Foo.Bar2"), @r###" %0: bool .0: %0 = binary_op '==', 'Foo::Bar1': Foo::Bar, 'Foo::Bar2': Foo::Bar return %0: bool "###); } #[test] fn dynamic_integer_comparison() { insta::assert_snapshot!(dump("foo.currentIndex > 0"), @r###" %0: int %1: bool .0: %0 = read_property [foo]: Foo*, "currentIndex" %1 = binary_op '>', %0: int, 0: integer return %1: bool "###); } #[test] fn dynamic_string_comparison() { insta::assert_snapshot!(dump("'yoda' != foo.text"), @r###" %0: QString %1: bool .0: %0 = read_property [foo]: Foo*, "text" %1 = binary_op '!=', "yoda": QString, %0: QString return %1: bool "###); } #[test] fn untyped_null_literal_comparison() { insta::assert_snapshot!(dump("null == null"), @r###" .0: return true: bool "###); } #[test] fn pointer_comparison() { insta::assert_snapshot!(dump("foo == foo2"), @r###" %0: bool .0: %0 = binary_op '==', [foo]: Foo*, [foo2]: Foo* return %0: bool "###); } #[test] fn pointer_to_null_literal_comparison() { insta::assert_snapshot!(dump("foo == null"), @r###" %0: bool .0: %0 = binary_op '==', [foo]: Foo*, nullptr: nullptr_t return %0: bool "###); } #[test] fn pointer_comparison_no_implicit_upcast() { let env = Env::new(); assert!(env.try_build("foo == foo_sub").is_err()); } #[test] fn pointer_comparison_with_explicit_upcast() { insta::assert_snapshot!(dump("foo == (foo_sub as Foo)"), @r###" %0: Foo* %1: bool .0: %0 = copy [foo_sub]: FooSub* %1 = binary_op '==', [foo]: Foo*, %0: Foo* return %1: bool "###); } #[test] fn incompatible_pointer_comparison() { let env = Env::new(); assert!(env.try_build("foo == bar").is_err()); } #[test] fn type_cast_noop() { insta::assert_snapshot!(dump("true as bool"), @r###" .0: return true: bool "###); } #[test] fn type_cast_noop_string() { insta::assert_snapshot!(dump("'foo' as QString"), @r###" .0: return "foo": QString "###); } #[test] fn type_cast_implicit_integer() { insta::assert_snapshot!(dump("1 as uint"), @r###" %0: uint .0: %0 = copy 1: integer return %0: uint "###); } #[test] fn type_cast_integer_literal_as_double() { insta::assert_snapshot!(dump("1 as double"), @r###" %0: double .0: %0 = static_cast 'double', 1: integer return %0: double "###); } #[test] fn type_cast_double_as_integer() { insta::assert_snapshot!(dump("1e3 as uint"), @r###" %0: uint .0: %0 = static_cast 'uint', 1000.0: double return %0: uint "###); } #[test] fn type_cast_dynamic_integer_as_uint() { insta::assert_snapshot!(dump("foo.currentIndex as uint"), @r###" %0: int %1: uint .0: %0 = read_property [foo]: Foo*, "currentIndex" %1 = static_cast 'uint', %0: int return %1: uint "###); } #[test] fn type_cast_dynamic_bool_as_int() { insta::assert_snapshot!(dump("foo.checked as int"), @r###" %0: bool %1: int .0: %0 = read_property [foo]: Foo*, "checked" %1 = static_cast 'int', %0: bool return %1: int "###); } #[test] fn type_cast_enum_as_int() { insta::assert_snapshot!(dump("Foo.Bar0 as int"), @r###" %0: int .0: %0 = static_cast 'int', 'Foo::Bar0': Foo::Bar return %0: int "###); } #[test] fn type_cast_literal_as_void() { insta::assert_snapshot!(dump("0 as void"), @r###" .0: static_cast 'void', 0: integer return _: void "###); } #[test] fn type_cast_dynamic_expr_as_void() { insta::assert_snapshot!(dump("foo.text as void"), @r###" %0: QString .0: %0 = read_property [foo]: Foo*, "text" static_cast 'void', %0: QString return _: void "###); } #[test] fn type_cast_variant_as_int() { insta::assert_snapshot!(dump("foo.currentData as int"), @r###" %0: QVariant %1: int .0: %0 = read_property [foo]: Foo*, "currentData" %1 = variant_cast 'int', %0: QVariant return %1: int "###); } #[test] fn type_cast_invalid() { let env = Env::new(); assert!(env.try_build("'' as Foo").is_err()); } #[test] fn ternary_simple() { insta::assert_snapshot!(dump("foo.checked ? 1 : 2"), @r###" %0: bool %1: int .0: %0 = read_property [foo]: Foo*, "checked" br_cond %0: bool, .1, .2 .1: %1 = copy 1: integer br .3 .2: %1 = copy 2: integer br .3 .3: return %1: int "###); } #[test] fn ternary_string_literal() { insta::assert_snapshot!(dump("foo.checked ? 'yes' : 'no'"), @r###" %0: bool %1: QString .0: %0 = read_property [foo]: Foo*, "checked" br_cond %0: bool, .1, .2 .1: %1 = copy "yes": QString br .3 .2: %1 = copy "no": QString br .3 .3: return %1: QString "###); } #[test] fn ternary_no_implicit_upcast() { let env = Env::new(); assert!(env.try_build("foo.checked ? foo : foo_sub").is_err()); } #[test] fn ternary_with_explicit_upcast() { insta::assert_snapshot!(dump("foo.checked ? foo : (foo_sub as Foo)"), @r###" %0: bool %1: Foo* %2: Foo* .0: %0 = read_property [foo]: Foo*, "checked" br_cond %0: bool, .1, .2 .1: %2 = copy [foo]: Foo* br .3 .2: %1 = copy [foo_sub]: FooSub* %2 = copy %1: Foo* br .3 .3: return %2: Foo* "###); } #[test] fn ternary_dynamic_result() { insta::assert_snapshot!(dump("foo.checked ? foo.text : foo2.text"), @r###" %0: bool %1: QString %2: QString %3: QString .0: %0 = read_property [foo]: Foo*, "checked" br_cond %0: bool, .1, .2 .1: %1 = read_property [foo]: Foo*, "text" %3 = copy %1: QString br .3 .2: %2 = read_property [foo2]: Foo*, "text" %3 = copy %2: QString br .3 .3: return %3: QString "###); } #[test] fn ternary_nested_condition() { insta::assert_snapshot!( dump("(foo.checked ? foo2.checked : foo3.checked) ? foo2.text : foo3.text"), @r###" %0: bool %1: bool %2: bool %3: bool %4: QString %5: QString %6: QString .0: %0 = read_property [foo]: Foo*, "checked" br_cond %0: bool, .1, .2 .1: %1 = read_property [foo2]: Foo*, "checked" %3 = copy %1: bool br .3 .2: %2 = read_property [foo3]: Foo*, "checked" %3 = copy %2: bool br .3 .3: br_cond %3: bool, .4, .5 .4: %4 = read_property [foo2]: Foo*, "text" %6 = copy %4: QString br .6 .5: %5 = read_property [foo3]: Foo*, "text" %6 = copy %5: QString br .6 .6: return %6: QString "###); } #[test] fn ternary_nested_consequence() { insta::assert_snapshot!( dump("foo.checked ? (foo2.checked ? foo.text : foo2.text) : foo3.text"), @r###" %0: bool %1: bool %2: QString %3: QString %4: QString %5: QString %6: QString .0: %0 = read_property [foo]: Foo*, "checked" br_cond %0: bool, .1, .5 .1: %1 = read_property [foo2]: Foo*, "checked" br_cond %1: bool, .2, .3 .2: %2 = read_property [foo]: Foo*, "text" %4 = copy %2: QString br .4 .3: %3 = read_property [foo2]: Foo*, "text" %4 = copy %3: QString br .4 .4: %6 = copy %4: QString br .6 .5: %5 = read_property [foo3]: Foo*, "text" %6 = copy %5: QString br .6 .6: return %6: QString "###); } #[test] fn ternary_nested_alternative() { insta::assert_snapshot!( dump("foo.checked ? foo.text : (foo2.checked ? foo2.text : foo3.text)"), @r###" %0: bool %1: QString %2: bool %3: QString %4: QString %5: QString %6: QString .0: %0 = read_property [foo]: Foo*, "checked" br_cond %0: bool, .1, .2 .1: %1 = read_property [foo]: Foo*, "text" %6 = copy %1: QString br .6 .2: %2 = read_property [foo2]: Foo*, "checked" br_cond %2: bool, .3, .4 .3: %3 = read_property [foo2]: Foo*, "text" %5 = copy %3: QString br .5 .4: %4 = read_property [foo3]: Foo*, "text" %5 = copy %4: QString br .5 .5: %6 = copy %5: QString br .6 .6: return %6: QString "###); } #[test] fn ternary_concatenation() { insta::assert_snapshot!( dump("(foo.checked ? foo.text : foo2.text) + (foo3.checked ? foo3.text : foo4.text)"), @r###" %0: bool %1: QString %2: QString %3: QString %4: bool %5: QString %6: QString %7: QString %8: QString .0: %0 = read_property [foo]: Foo*, "checked" br_cond %0: bool, .1, .2 .1: %1 = read_property [foo]: Foo*, "text" %3 = copy %1: QString br .3 .2: %2 = read_property [foo2]: Foo*, "text" %3 = copy %2: QString br .3 .3: %4 = read_property [foo3]: Foo*, "checked" br_cond %4: bool, .4, .5 .4: %5 = read_property [foo3]: Foo*, "text" %7 = copy %5: QString br .6 .5: %6 = read_property [foo4]: Foo*, "text" %7 = copy %6: QString br .6 .6: %8 = binary_op '+', %3: QString, %7: QString return %8: QString "###); } #[test] fn multiple_statements() { insta::assert_snapshot!( dump("{ qsTr('hello'); foo.done(0); 'discarded'; foo.done(1); 'world' }"), @r###" %0: QString .0: %0 = call_builtin_function Tr, {"hello": string} call_method [foo]: Foo*, "done", {0: integer} call_method [foo]: Foo*, "done", {1: integer} return "world": QString "###); } #[test] fn empty_statement() { insta::assert_snapshot!( dump(";"), @r###" .0: return _: void "###); } #[test] fn if_statement_literal() { insta::assert_snapshot!(dump("if (foo.checked) { 'yes' }"), @r###" %0: bool .0: %0 = read_property [foo]: Foo*, "checked" br_cond %0: bool, .1, .2 .1: return "yes": QString .2: return _: void "###); } #[test] fn if_else_statement_literal() { insta::assert_snapshot!(dump("if (foo.checked) { 'yes' } else { 'no' }"), @r###" %0: bool .0: %0 = read_property [foo]: Foo*, "checked" br_cond %0: bool, .1, .2 .1: return "yes": QString .2: return "no": QString .3: unreachable "###); } #[test] fn if_else_statement_literal_incompatible_completion() { insta::assert_snapshot!(dump("if (foo.checked) { 'yes' } else { false }"), @r###" %0: bool .0: %0 = read_property [foo]: Foo*, "checked" br_cond %0: bool, .1, .2 .1: return "yes": QString .2: return false: bool .3: unreachable "###); } #[test] fn if_statement_call() { insta::assert_snapshot!(dump("if (foo.checked) { foo.done(0) }"), @r###" %0: bool .0: %0 = read_property [foo]: Foo*, "checked" br_cond %0: bool, .1, .2 .1: call_method [foo]: Foo*, "done", {0: integer} return _: void .2: return _: void "###); } #[test] fn if_else_statement_call() { insta::assert_snapshot!( dump("if (foo.checked) { foo.done(0); 'yes' } else { foo.done(1); 'no' }"), @r###" %0: bool .0: %0 = read_property [foo]: Foo*, "checked" br_cond %0: bool, .1, .2 .1: call_method [foo]: Foo*, "done", {0: integer} return "yes": QString .2: call_method [foo]: Foo*, "done", {1: integer} return "no": QString .3: unreachable "###); } #[test] fn if_else_statement_call_incompatible_completion() { insta::assert_snapshot!( dump("if (foo.checked) { foo.done(0); 'yes' } else { foo.done(1); false }"), @r###" %0: bool .0: %0 = read_property [foo]: Foo*, "checked" br_cond %0: bool, .1, .2 .1: call_method [foo]: Foo*, "done", {0: integer} return "yes": QString .2: call_method [foo]: Foo*, "done", {1: integer} return false: bool .3: unreachable "###); } #[test] fn if_else_statement_chained() { insta::assert_snapshot!( dump(r###" if (foo.checked) { foo.text } else if (foo2.checked) { foo2.text } else { foo3.text } "###), @r###" %0: bool %1: QString %2: bool %3: QString %4: QString .0: %0 = read_property [foo]: Foo*, "checked" br_cond %0: bool, .1, .2 .1: %1 = read_property [foo]: Foo*, "text" return %1: QString .2: %2 = read_property [foo2]: Foo*, "checked" br_cond %2: bool, .3, .4 .3: %3 = read_property [foo2]: Foo*, "text" return %3: QString .4: %4 = read_property [foo3]: Foo*, "text" return %4: QString .5: unreachable .6: unreachable "###); } #[test] fn if_statement_ternary_in_condition() { insta::assert_snapshot!( dump("if (foo.checked ? foo2.checked : foo3.checked) { foo.done(0) }"), @r###" %0: bool %1: bool %2: bool %3: bool .0: %0 = read_property [foo]: Foo*, "checked" br_cond %0: bool, .1, .2 .1: %1 = read_property [foo2]: Foo*, "checked" %3 = copy %1: bool br .3 .2: %2 = read_property [foo3]: Foo*, "checked" %3 = copy %2: bool br .3 .3: br_cond %3: bool, .4, .5 .4: call_method [foo]: Foo*, "done", {0: integer} return _: void .5: return _: void "###); } #[test] fn if_else_statement_ternary_in_condition() { insta::assert_snapshot!( dump("if (foo.checked ? foo2.checked : foo3.checked) { foo.done(0) } else { foo.done(1) }"), @r###" %0: bool %1: bool %2: bool %3: bool .0: %0 = read_property [foo]: Foo*, "checked" br_cond %0: bool, .1, .2 .1: %1 = read_property [foo2]: Foo*, "checked" %3 = copy %1: bool br .3 .2: %2 = read_property [foo3]: Foo*, "checked" %3 = copy %2: bool br .3 .3: br_cond %3: bool, .4, .5 .4: call_method [foo]: Foo*, "done", {0: integer} return _: void .5: call_method [foo]: Foo*, "done", {1: integer} return _: void .6: unreachable "###); } #[test] fn if_else_statement_empty_body() { insta::assert_snapshot!( dump("if (foo.checked) {} else {}"), @r###" %0: bool .0: %0 = read_property [foo]: Foo*, "checked" br_cond %0: bool, .1, .2 .1: return _: void .2: return _: void .3: unreachable "###); } #[test] fn return_nothing() { insta::assert_snapshot!(dump("{ return; }"), @r###" .0: return _: void .1: unreachable "###); } #[test] fn return_literal() { insta::assert_snapshot!(dump("{ return 'hello'; }"), @r###" .0: return "hello": QString .1: unreachable "###); } #[test] fn return_dynamic_expression() { insta::assert_snapshot!(dump("{ return foo.checked; }"), @r###" %0: bool .0: %0 = read_property [foo]: Foo*, "checked" return %0: bool .1: unreachable "###); } #[test] fn return_if() { insta::assert_snapshot!( dump(r###"{ if (foo.checked) return foo.text; if (foo2.checked) return foo2.text; foo3.text }"###), @r###" %0: bool %1: QString %2: bool %3: QString %4: QString .0: %0 = read_property [foo]: Foo*, "checked" br_cond %0: bool, .1, .3 .1: %1 = read_property [foo]: Foo*, "text" return %1: QString .2: br .3 .3: %2 = read_property [foo2]: Foo*, "checked" br_cond %2: bool, .4, .6 .4: %3 = read_property [foo2]: Foo*, "text" return %3: QString .5: br .6 .6: %4 = read_property [foo3]: Foo*, "text" return %4: QString "###); } #[test] fn return_if_else_commplete() { insta::assert_snapshot!( dump(r###"{ if (foo.checked) { return foo.text; } else if (foo2.checked) { return foo2.text; } else { return foo3.text; } }"###), @r###" %0: bool %1: QString %2: bool %3: QString %4: QString .0: %0 = read_property [foo]: Foo*, "checked" br_cond %0: bool, .1, .3 .1: %1 = read_property [foo]: Foo*, "text" return %1: QString .2: unreachable .3: %2 = read_property [foo2]: Foo*, "checked" br_cond %2: bool, .4, .6 .4: %3 = read_property [foo2]: Foo*, "text" return %3: QString .5: unreachable .6: %4 = read_property [foo3]: Foo*, "text" return %4: QString .7: unreachable .8: unreachable .9: unreachable "###); } #[test] fn return_if_else_partial() { insta::assert_snapshot!( dump(r###"{ if (foo.checked) { return foo.text; } else if (foo2.checked) { foo2.text; } else { return foo3.text; } }"###), @r###" %0: bool %1: QString %2: bool %3: QString %4: QString .0: %0 = read_property [foo]: Foo*, "checked" br_cond %0: bool, .1, .3 .1: %1 = read_property [foo]: Foo*, "text" return %1: QString .2: unreachable .3: %2 = read_property [foo2]: Foo*, "checked" br_cond %2: bool, .4, .5 .4: %3 = read_property [foo2]: Foo*, "text" return %3: QString .5: %4 = read_property [foo3]: Foo*, "text" return %4: QString .6: unreachable .7: unreachable .8: unreachable "###); } #[test] fn return_if_else_partial_and_trailing_code() { insta::assert_snapshot!( dump(r###"{ if (foo.checked) { return foo.text; } else if (foo2.checked) { foo2.text; } else { return foo3.text; } foo4.text; }"###), @r###" %0: bool %1: QString %2: bool %3: QString %4: QString %5: QString .0: %0 = read_property [foo]: Foo*, "checked" br_cond %0: bool, .1, .3 .1: %1 = read_property [foo]: Foo*, "text" return %1: QString .2: br .8 .3: %2 = read_property [foo2]: Foo*, "checked" br_cond %2: bool, .4, .5 .4: %3 = read_property [foo2]: Foo*, "text" br .7 .5: %4 = read_property [foo3]: Foo*, "text" return %4: QString .6: br .7 .7: br .8 .8: %5 = read_property [foo4]: Foo*, "text" return %5: QString "###); } #[test] fn return_with_trailing_garbage() { insta::assert_snapshot!( dump(r###"{ if (foo.checked) { return foo.text; return; } else { { return foo2.text; } foo3.text; } foo4.text; }"###), @r###" %0: bool %1: QString %2: QString %3: QString %4: QString .0: %0 = read_property [foo]: Foo*, "checked" br_cond %0: bool, .1, .4 .1: %1 = read_property [foo]: Foo*, "text" return %1: QString .2: return _: void .3: br .6 .4: %2 = read_property [foo2]: Foo*, "text" return %2: QString .5: %3 = read_property [foo3]: Foo*, "text" br .6 .6: %4 = read_property [foo4]: Foo*, "text" return %4: QString "###); } #[test] fn switch_basic() { insta::assert_snapshot!( dump(r###"{ let s = foo.text; switch (s) { case "foo2": foo2.text; break; case "foo3": foo3.text; break; default: foo.text; } }"###), @r###" %0: QString %1: QString %2: bool %3: bool %4: QString %5: QString %6: QString .0: %0 = read_property [foo]: Foo*, "text" %1 = copy %0: QString %2 = binary_op '==', %1: QString, "foo2": QString br_cond %2: bool, .4, .1 .1: %3 = binary_op '==', %1: QString, "foo3": QString br_cond %3: bool, .6, .8 .2: br .4 .3: unreachable .4: %4 = read_property [foo2]: Foo*, "text" return %4: QString .5: br .6 .6: %5 = read_property [foo3]: Foo*, "text" return %5: QString .7: br .8 .8: %6 = read_property [foo]: Foo*, "text" return %6: QString .9: unreachable "###); } #[test] fn switch_default_only() { insta::assert_snapshot!( dump(r###"{ switch (foo.currentIndex) { default: foo.done(0); } foo.done(-1); }"###), @r###" %0: int .0: %0 = read_property [foo]: Foo*, "currentIndex" br .2 .1: br .3 .2: call_method [foo]: Foo*, "done", {0: integer} br .3 .3: call_method [foo]: Foo*, "done", {-1: integer} return _: void "###); } #[test] fn switch_default_only_break() { insta::assert_snapshot!( dump(r###"{ switch (foo.currentIndex) { default: foo.done(0); break; } foo.done(-1); }"###), @r###" %0: int .0: %0 = read_property [foo]: Foo*, "currentIndex" br .2 .1: br .4 .2: call_method [foo]: Foo*, "done", {0: integer} br .1 .3: br .4 .4: call_method [foo]: Foo*, "done", {-1: integer} return _: void "###); } #[test] fn switch_case_only() { insta::assert_snapshot!( dump(r###"{ switch (foo.currentIndex) { case 1: foo.done(1); break; } foo.done(-1); }"###), @r###" %0: int %1: bool .0: %0 = read_property [foo]: Foo*, "currentIndex" %1 = binary_op '==', %0: int, 1: integer br_cond %1: bool, .3, .5 .1: br .3 .2: br .5 .3: call_method [foo]: Foo*, "done", {1: integer} br .2 .4: br .5 .5: call_method [foo]: Foo*, "done", {-1: integer} return _: void "###); } #[test] fn switch_default_first_fall_through() { insta::assert_snapshot!( dump(r###"{ switch (foo.currentIndex) { default: foo.done(0); case 1: foo.done(1); case 2: foo.done(2); } foo.done(-1); }"###), @r###" %0: int %1: bool %2: bool .0: %0 = read_property [foo]: Foo*, "currentIndex" %1 = binary_op '==', %0: int, 1: integer br_cond %1: bool, .5, .1 .1: %2 = binary_op '==', %0: int, 2: integer br_cond %2: bool, .6, .4 .2: br .4 .3: br .7 .4: call_method [foo]: Foo*, "done", {0: integer} br .5 .5: call_method [foo]: Foo*, "done", {1: integer} br .6 .6: call_method [foo]: Foo*, "done", {2: integer} br .7 .7: call_method [foo]: Foo*, "done", {-1: integer} return _: void "###); } #[test] fn switch_default_mid_fall_through() { insta::assert_snapshot!( dump(r###"{ switch (foo.currentIndex) { case 1: foo.done(1); default: foo.done(0); case 2: foo.done(2); } foo.done(-1); }"###), @r###" %0: int %1: bool %2: bool .0: %0 = read_property [foo]: Foo*, "currentIndex" %1 = binary_op '==', %0: int, 1: integer br_cond %1: bool, .4, .1 .1: %2 = binary_op '==', %0: int, 2: integer br_cond %2: bool, .6, .5 .2: br .4 .3: br .7 .4: call_method [foo]: Foo*, "done", {1: integer} br .5 .5: call_method [foo]: Foo*, "done", {0: integer} br .6 .6: call_method [foo]: Foo*, "done", {2: integer} br .7 .7: call_method [foo]: Foo*, "done", {-1: integer} return _: void "###); } #[test] fn switch_default_end_fall_through() { insta::assert_snapshot!( dump(r###"{ switch (foo.currentIndex) { case 1: foo.done(1); case 2: foo.done(2); default: foo.done(0); } foo.done(-1); }"###), @r###" %0: int %1: bool %2: bool .0: %0 = read_property [foo]: Foo*, "currentIndex" %1 = binary_op '==', %0: int, 1: integer br_cond %1: bool, .4, .1 .1: %2 = binary_op '==', %0: int, 2: integer br_cond %2: bool, .5, .6 .2: br .4 .3: br .7 .4: call_method [foo]: Foo*, "done", {1: integer} br .5 .5: call_method [foo]: Foo*, "done", {2: integer} br .6 .6: call_method [foo]: Foo*, "done", {0: integer} br .7 .7: call_method [foo]: Foo*, "done", {-1: integer} return _: void "###); } #[test] fn switch_empty_fall_through() { insta::assert_snapshot!( dump(r###"{ switch (foo.currentIndex) { case 1: case 2: foo.done(1); break; case 3: foo.done(3); break; } foo.done(-1); }"###), @r###" %0: int %1: bool %2: bool %3: bool .0: %0 = read_property [foo]: Foo*, "currentIndex" %1 = binary_op '==', %0: int, 1: integer br_cond %1: bool, .5, .1 .1: %2 = binary_op '==', %0: int, 2: integer br_cond %2: bool, .6, .2 .2: %3 = binary_op '==', %0: int, 3: integer br_cond %3: bool, .8, .10 .3: br .5 .4: br .10 .5: br .6 .6: call_method [foo]: Foo*, "done", {1: integer} br .4 .7: br .8 .8: call_method [foo]: Foo*, "done", {3: integer} br .4 .9: br .10 .10: call_method [foo]: Foo*, "done", {-1: integer} return _: void "###); } #[test] fn switch_return() { insta::assert_snapshot!( dump(r###"{ switch (foo.currentIndex) { case 0: return "0"; case 1: return "1"; default: return "default"; } "unreachable" }"###), @r###" %0: int %1: bool %2: bool .0: %0 = read_property [foo]: Foo*, "currentIndex" %1 = binary_op '==', %0: int, 0: integer br_cond %1: bool, .4, .1 .1: %2 = binary_op '==', %0: int, 1: integer br_cond %2: bool, .6, .8 .2: br .4 .3: br .10 .4: return "0": QString .5: br .6 .6: return "1": QString .7: br .8 .8: return "default": QString .9: br .10 .10: return "unreachable": QString "###); } #[test] fn switch_conditional_break() { insta::assert_snapshot!( dump(r###"{ switch (foo.currentIndex) { case 2: if (foo2.checked) break; return "2"; case 3: if (foo3.checked) break; return "3"; default: if (foo.checked) break; return "default"; } "break" }"###), @r###" %0: int %1: bool %2: bool %3: bool %4: bool %5: bool .0: %0 = read_property [foo]: Foo*, "currentIndex" %1 = binary_op '==', %0: int, 2: integer br_cond %1: bool, .4, .1 .1: %2 = binary_op '==', %0: int, 3: integer br_cond %2: bool, .9, .14 .2: br .4 .3: br .19 .4: %3 = read_property [foo2]: Foo*, "checked" br_cond %3: bool, .5, .7 .5: br .3 .6: br .7 .7: return "2": QString .8: br .9 .9: %4 = read_property [foo3]: Foo*, "checked" br_cond %4: bool, .10, .12 .10: br .3 .11: br .12 .12: return "3": QString .13: br .14 .14: %5 = read_property [foo]: Foo*, "checked" br_cond %5: bool, .15, .17 .15: br .3 .16: br .17 .17: return "default": QString .18: br .19 .19: return "break": QString "###); } #[test] fn switch_ternary_in_left_value() { insta::assert_snapshot!( dump(r###"{ switch (foo.checked ? foo.currentIndex : foo2.currentIndex) { case 1: foo.done(1); break; case 2: foo.done(2); break; } foo.done(-1); }"###), @r###" %0: bool %1: int %2: int %3: int %4: bool %5: bool .0: %0 = read_property [foo]: Foo*, "checked" br_cond %0: bool, .1, .2 .1: %1 = read_property [foo]: Foo*, "currentIndex" %3 = copy %1: int br .3 .2: %2 = read_property [foo2]: Foo*, "currentIndex" %3 = copy %2: int br .3 .3: %4 = binary_op '==', %3: int, 1: integer br_cond %4: bool, .7, .4 .4: %5 = binary_op '==', %3: int, 2: integer br_cond %5: bool, .9, .11 .5: br .7 .6: br .11 .7: call_method [foo]: Foo*, "done", {1: integer} br .6 .8: br .9 .9: call_method [foo]: Foo*, "done", {2: integer} br .6 .10: br .11 .11: call_method [foo]: Foo*, "done", {-1: integer} return _: void "###); } #[test] fn callback_block() { let env = Env::new(); let code = env.build_callback( r###"{ foo.done(0) }"###, ); insta::assert_snapshot!(dump_code(&code), @r###" .0: call_method [foo]: Foo*, "done", {0: integer} return _: void "###); assert_eq!(code.parameter_count, 0); } #[test] fn callback_expr() { let env = Env::new(); let code = env.build_callback("foo.done(0)"); insta::assert_snapshot!(dump_code(&code), @r###" .0: call_method [foo]: Foo*, "done", {0: integer} return _: void "###); assert_eq!(code.parameter_count, 0); } #[test] fn callback_function_no_arg() { let env = Env::new(); let code = env.build_callback( r###"function() { foo.done(0) }"###, ); insta::assert_snapshot!(dump_code(&code), @r###" .0: call_method [foo]: Foo*, "done", {0: integer} return _: void "###); assert_eq!(code.parameter_count, 0); } #[test] fn callback_function_with_arg() { let env = Env::new(); let code = env.build_callback( r###"function(obj: Foo, code: int) { obj.done(code); }"###, ); insta::assert_snapshot!(dump_code(&code), @r###" %0: Foo* %1: int .0: call_method %0: Foo*, "done", {%1: int} return _: void "###); assert_eq!(code.parameter_count, 2); } #[test] fn callback_arrow_function_no_arg_no_block() { let env = Env::new(); let code = env.build_callback("() => foo.done(0)"); insta::assert_snapshot!(dump_code(&code), @r###" .0: call_method [foo]: Foo*, "done", {0: integer} return _: void "###); assert_eq!(code.parameter_count, 0); } #[test] fn callback_function_parenthesized() { let env = Env::new(); assert!(env.try_build_callback("(function() {})").is_err()); }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/tests/test_tir_interpreter.rs
Rust
use self::tir_testenv::*; use qmluic::tir; use qmluic::tir::interpret::{EvaluatedValue, StringKind}; pub mod tir_testenv; fn try_eval(expr_source: &str) -> Option<EvaluatedValue> { let env = Env::new(); let code = env.build(expr_source); tir::evaluate_code(&code) } fn eval(expr_source: &str) -> EvaluatedValue { try_eval(expr_source).unwrap() } #[test] fn integer_math() { assert_eq!(eval("1 - 2 * (-3)").unwrap_integer(), 7); assert_eq!(eval("7 / 3").unwrap_integer(), 2); } #[test] fn string() { assert_eq!( eval("'foo' + 'bar'").unwrap_string(), ("foobar".to_owned(), StringKind::NoTr) ); assert_eq!( eval("qsTr('foo' + 'bar')").unwrap_string(), ("foobar".to_owned(), StringKind::Tr) ); assert!(try_eval("qsTr('foo') + qsTr('bar')").is_none()); assert_eq!( eval("['foo', qsTr('bar')]").unwrap_string_list(), [ ("foo".to_owned(), StringKind::NoTr), ("bar".to_owned(), StringKind::Tr) ] ); } #[test] fn enum_set() { assert_eq!(eval("Foo.Bar0").unwrap_enum_set(), ["Foo::Bar0"]); assert_eq!( eval("Foo.Bar0 | Foo.Bar1").unwrap_enum_set(), ["Foo::Bar0", "Foo::Bar1"] ); assert!(try_eval("Foo.Bar0 & Foo.Bar1").is_none()); } #[test] fn object_ref() { assert_eq!(eval("foo").unwrap_object_ref(), "foo"); assert_eq!( eval("[foo, foo2]").into_object_ref_list().unwrap(), ["foo", "foo2"] ); }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/tests/test_tir_property_analysis.rs
Rust
use self::tir_testenv::*; use qmluic::diagnostic::Diagnostics; use qmluic::tir::{self, CodeBody}; pub mod tir_testenv; fn analyze_code(code: &mut CodeBody) { let mut diagnostics = Diagnostics::new(); tir::analyze_code_property_dependency(code, &mut diagnostics); assert!(!diagnostics.has_error()); } #[test] fn direct_static_deps_simple() { let env = Env::new(); let mut code = env.build( r###"{ !foo.checked }"###, ); analyze_code(&mut code); insta::assert_snapshot!(dump_code(&code), @r###" %0: bool %1: bool .0: %0 = read_property [foo]: Foo*, "checked" %1 = unary_op '!', %0: bool return %1: bool static_property_deps: [foo], "toggled" "###); } #[test] fn direct_static_deps_branched() { let env = Env::new(); let mut code = env.build( r###"{ foo.checked ? foo2.text : foo3.text }"###, ); analyze_code(&mut code); insta::assert_snapshot!(dump_code(&code), @r###" %0: bool %1: QString %2: QString %3: QString .0: %0 = read_property [foo]: Foo*, "checked" br_cond %0: bool, .1, .2 .1: %1 = read_property [foo2]: Foo*, "text" %3 = copy %1: QString br .3 .2: %2 = read_property [foo3]: Foo*, "text" %3 = copy %2: QString br .3 .3: return %3: QString static_property_deps: [foo], "toggled" [foo2], "textChanged" [foo3], "textChanged" "###); } #[test] fn indirect_static_deps_branch_local() { let env = Env::new(); let mut code = env.build( r###"{ if (foo.checked) { let w = foo2; return w.text } else { let w = foo3; return w.text; } }"###, ); analyze_code(&mut code); insta::assert_snapshot!(dump_code(&code), @r###" %0: bool %1: Foo* %2: QString %3: Foo* %4: QString .0: %0 = read_property [foo]: Foo*, "checked" br_cond %0: bool, .1, .3 .1: %1 = copy [foo2]: Foo* %2 = read_property %1: Foo*, "text" return %2: QString .2: unreachable .3: %3 = copy [foo3]: Foo* %4 = read_property %3: Foo*, "text" return %4: QString .4: unreachable .5: unreachable static_property_deps: [foo], "toggled" [foo2], "textChanged" [foo3], "textChanged" "###); } #[test] fn indirect_static_deps_reassigned() { let env = Env::new(); let mut code = env.build( r###"{ let w = foo; let s = w.text; w = foo2; s + w.text }"###, ); analyze_code(&mut code); insta::assert_snapshot!(dump_code(&code), @r###" %0: Foo* %1: QString %2: QString %3: QString %4: QString .0: %0 = copy [foo]: Foo* %1 = read_property %0: Foo*, "text" %2 = copy %1: QString %0 = copy [foo2]: Foo* %3 = read_property %0: Foo*, "text" %4 = binary_op '+', %2: QString, %3: QString return %4: QString static_property_deps: [foo], "textChanged" [foo2], "textChanged" "###); } #[test] fn dynamic_deps_branchy() { let env = Env::new(); let mut code = env.build( r###"{ (foo.checked ? foo2 : foo3).text }"###, ); analyze_code(&mut code); insta::assert_snapshot!(dump_code(&code), @r###" %0: bool %1: Foo* %2: QString .0: %0 = read_property [foo]: Foo*, "checked" br_cond %0: bool, .1, .2 .1: %1 = copy [foo2]: Foo* br .3 .2: %1 = copy [foo3]: Foo* br .3 .3: ^0 = observe_property %1, "textChanged" %2 = read_property %1: Foo*, "text" return %2: QString static_property_deps: [foo], "toggled" "###); assert_eq!(code.property_observer_count, 1); } #[test] fn dynamic_deps_reassigned() { let env = Env::new(); let mut code = env.build( r###"{ let w = foo.checked ? foo2 : foo3; let s = w.text; w = foo2.checked ? foo3 : foo4; return s + w.text; }"###, ); analyze_code(&mut code); insta::assert_snapshot!(dump_code(&code), @r###" %0: bool %1: Foo* %2: Foo* %3: QString %4: QString %5: bool %6: Foo* %7: QString %8: QString .0: %0 = read_property [foo]: Foo*, "checked" br_cond %0: bool, .1, .2 .1: %1 = copy [foo2]: Foo* br .3 .2: %1 = copy [foo3]: Foo* br .3 .3: %2 = copy %1: Foo* ^0 = observe_property %2, "textChanged" %3 = read_property %2: Foo*, "text" %4 = copy %3: QString %5 = read_property [foo2]: Foo*, "checked" br_cond %5: bool, .4, .5 .4: %6 = copy [foo3]: Foo* br .6 .5: %6 = copy [foo4]: Foo* br .6 .6: %2 = copy %6: Foo* ^1 = observe_property %2, "textChanged" %7 = read_property %2: Foo*, "text" %8 = binary_op '+', %4: QString, %7: QString return %8: QString .7: unreachable static_property_deps: [foo], "toggled" [foo2], "toggled" "###); assert_eq!(code.property_observer_count, 2); } #[test] fn dynamic_deps_multiple() { let env = Env::new(); let mut code = env.build( r###"{ let w1 = foo.checked ? foo2 : foo3; let w2 = foo2.checked ? foo3 : foo4; return w1.text + w2.text; }"###, ); analyze_code(&mut code); insta::assert_snapshot!(dump_code(&code), @r###" %0: bool %1: Foo* %2: Foo* %3: bool %4: Foo* %5: Foo* %6: QString %7: QString %8: QString .0: %0 = read_property [foo]: Foo*, "checked" br_cond %0: bool, .1, .2 .1: %1 = copy [foo2]: Foo* br .3 .2: %1 = copy [foo3]: Foo* br .3 .3: %2 = copy %1: Foo* %3 = read_property [foo2]: Foo*, "checked" br_cond %3: bool, .4, .5 .4: %4 = copy [foo3]: Foo* br .6 .5: %4 = copy [foo4]: Foo* br .6 .6: %5 = copy %4: Foo* ^0 = observe_property %2, "textChanged" %6 = read_property %2: Foo*, "text" ^1 = observe_property %5, "textChanged" %7 = read_property %5: Foo*, "text" %8 = binary_op '+', %6: QString, %7: QString return %8: QString .7: unreachable static_property_deps: [foo], "toggled" [foo2], "toggled" "###); assert_eq!(code.property_observer_count, 2); } #[test] fn constant_simple() { let env = Env::new(); let mut code = env.build("foo.constInt"); analyze_code(&mut code); insta::assert_snapshot!(dump_code(&code), @r###" %0: int .0: %0 = read_property [foo]: Foo*, "constInt" return %0: int "###); }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
lib/tests/tir_testenv/mod.rs
Rust
//! Environment and utility for TIR tests. use qmluic::diagnostic::Diagnostics; use qmluic::metatype; use qmluic::qmlast::{StatementNode, UiObjectDefinition, UiProgram}; use qmluic::qmldoc::UiDocument; use qmluic::tir::{self, CodeBody}; use qmluic::typedexpr::{RefKind, RefSpace, TypeAnnotationSpace}; use qmluic::typemap::{ Class, ImportedModuleSpace, ModuleData, ModuleId, ModuleIdBuf, TypeKind, TypeMap, TypeMapError, TypeSpace as _, }; pub struct Env { type_map: TypeMap, module_id: ModuleIdBuf, } impl Env { pub fn new() -> Self { let mut type_map = TypeMap::with_primitive_types(); let module_id = ModuleIdBuf::Named("foo".to_owned()); let mut module_data = ModuleData::with_builtins(); let foo_meta = metatype::Class { class_name: "Foo".to_owned(), qualified_class_name: "Foo".to_owned(), object: true, enums: vec![metatype::Enum::with_values( "Bar", ["Bar0", "Bar1", "Bar2", "Bar3"], )], properties: vec![ metatype::Property { name: "checked".to_owned(), r#type: "bool".to_owned(), read: Some("isChecked".to_owned()), write: Some("setChecked".to_owned()), notify: Some("toggled".to_owned()), ..Default::default() }, metatype::Property { name: "currentData".to_owned(), r#type: "QVariant".to_owned(), read: Some("currentData".to_owned()), notify: Some("currentDataChanged".to_owned()), ..Default::default() }, metatype::Property { name: "currentIndex".to_owned(), r#type: "int".to_owned(), read: Some("currentIndex".to_owned()), write: Some("setCurrentIndex".to_owned()), notify: Some("currentIndexChanged".to_owned()), ..Default::default() }, metatype::Property { name: "text".to_owned(), r#type: "QString".to_owned(), read: Some("text".to_owned()), write: Some("setText".to_owned()), notify: Some("textChanged".to_owned()), ..Default::default() }, metatype::Property { name: "constInt".to_owned(), r#type: "int".to_owned(), read: Some("constInt".to_owned()), constant: true, ..Default::default() }, metatype::Property { name: "stringList".to_owned(), r#type: "QStringList".to_owned(), read: Some("stringList".to_owned()), write: Some("setStringList".to_owned()), notify: Some("stringListChanged".to_owned()), ..Default::default() }, ], signals: vec![ metatype::Method::nullary("toggled", "void"), metatype::Method::nullary("currentDataChanged", "void"), metatype::Method::nullary("currentIndexChanged", "void"), metatype::Method::nullary("textChanged", "void"), ], slots: vec![metatype::Method::with_argument_types( "done", "void", ["int"], )], ..Default::default() }; let foo_sub_meta = metatype::Class::with_supers("FooSub", ["Foo"]); let bar_meta = metatype::Class::new("Bar"); module_data.extend([foo_meta, foo_sub_meta, bar_meta, metatype::Class::new("A")]); type_map.insert_module(module_id.clone(), module_data); Env { type_map, module_id, } } pub fn build(&self, expr_source: &str) -> CodeBody { self.try_build(expr_source).unwrap() } pub fn try_build(&self, expr_source: &str) -> Result<CodeBody, Diagnostics> { self.try_build_with(expr_source, tir::build) } pub fn build_callback(&self, expr_source: &str) -> CodeBody { self.try_build_callback(expr_source).unwrap() } pub fn try_build_callback(&self, expr_source: &str) -> Result<CodeBody, Diagnostics> { self.try_build_with(expr_source, tir::build_callback) } fn try_build_with<'a>( &'a self, expr_source: &str, build: impl FnOnce(&Context<'a>, StatementNode, &str, &mut Diagnostics) -> Option<CodeBody<'a>>, ) -> Result<CodeBody<'a>, Diagnostics> { let mut type_space = ImportedModuleSpace::new(&self.type_map); assert!(type_space.import_module(ModuleId::Builtins)); assert!(type_space.import_module(self.module_id.as_ref())); let ctx = Context { type_space }; let doc = UiDocument::parse(format!("A {{ a: {expr_source}}}"), "MyType", None); let program = UiProgram::from_node(doc.root_node(), doc.source()).unwrap(); let obj = UiObjectDefinition::from_node(program.root_object_node(), doc.source()).unwrap(); let map = obj.build_binding_map(doc.source()).unwrap(); let node = map.get("a").unwrap().get_node().unwrap(); let mut diagnostics = Diagnostics::new(); build(&ctx, node, doc.source(), &mut diagnostics).ok_or(diagnostics) } } impl Default for Env { fn default() -> Self { Self::new() } } struct Context<'a> { type_space: ImportedModuleSpace<'a>, } impl<'a> RefSpace<'a> for Context<'a> { fn get_ref(&self, name: &str) -> Option<Result<RefKind<'a>, TypeMapError>> { let unwrap_class_ref = |name| { let ty = self.type_space.get_type(name).unwrap().unwrap(); Some(Ok(RefKind::Object(ty.into_class().unwrap()))) }; match name { "foo" | "foo2" | "foo3" | "foo4" => unwrap_class_ref("Foo"), "foo_sub" => unwrap_class_ref("FooSub"), "bar" => unwrap_class_ref("Bar"), _ => self.type_space.get_ref(name), } } fn this_object(&self) -> Option<(Class<'a>, String)> { None } } impl<'a> TypeAnnotationSpace<'a> for Context<'a> { fn get_annotated_type_scoped( &self, scoped_name: &str, ) -> Option<Result<TypeKind<'a>, TypeMapError>> { self.type_space.get_type_scoped(scoped_name).map(|r| { r.map(|ty| { if ty.name() == "Foo" { TypeKind::Pointer(ty) } else { TypeKind::Just(ty) } }) }) } } pub fn dump(expr_source: &str) -> String { let env = Env::new(); let code = env.build(expr_source); dump_code(&code) } pub fn dump_code(code: &CodeBody) -> String { let mut buf = Vec::new(); tir::dump_code_body(&mut buf, code).unwrap(); String::from_utf8(buf).unwrap() }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
src/lib.rs
Rust
#![forbid(unsafe_code)] mod qtpaths; pub mod reporting; mod uiviewer; pub use qtpaths::{QtPaths, QtVersion}; pub use uiviewer::UiViewer;
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
src/main.rs
Rust
#![forbid(unsafe_code)] use anyhow::{anyhow, Context as _}; use camino::{Utf8Component, Utf8Path, Utf8PathBuf}; use clap::{Args, Parser, Subcommand}; use notify::{RecursiveMode, Watcher as _}; use once_cell::sync::OnceCell; use qmluic::diagnostic::{Diagnostics, ProjectDiagnostics}; use qmluic::metatype; use qmluic::metatype_tweak; use qmluic::qmldir; use qmluic::qmldoc::UiDocumentsCache; use qmluic::qtname::FileNameRules; use qmluic::typemap::{ModuleData, ModuleId, TypeMap}; use qmluic::uigen::{self, BuildContext, DynamicBindingHandling, XmlWriter}; use qmluic_cli::{reporting, QtPaths, QtVersion, UiViewer}; use std::collections::HashSet; use std::fs; use std::io::{self, BufWriter, Write as _}; use std::path::Path; use std::process; use std::sync::mpsc; use tempfile::NamedTempFile; use thiserror::Error; #[derive(Clone, Debug, Parser)] struct Cli { #[command(flatten)] global_args: GlobalArgs, #[command(subcommand)] command: Command, } #[derive(Args, Clone, Debug)] struct GlobalArgs { /// Command to query Qt installation paths. #[arg(long, global = true, default_value = "qmake")] qmake: String, } #[derive(Clone, Debug, Subcommand)] enum Command { DumpMetatypes(DumpMetatypesArgs), GenerateUi(GenerateUiArgs), Preview(PreviewArgs), } #[derive(Debug, Error)] enum CommandError { #[error("(see diagnostic messages)")] DiagnosticGenerated, #[error(transparent)] Other(#[from] anyhow::Error), } #[derive(Clone, Debug)] struct CommandHelper { global_args: GlobalArgs, qt_paths_cache: OnceCell<QtPaths>, } impl CommandHelper { fn new(global_args: GlobalArgs) -> Self { CommandHelper { global_args, qt_paths_cache: OnceCell::new(), } } pub fn qt_paths(&self) -> anyhow::Result<&QtPaths> { self.qt_paths_cache.get_or_try_init(|| { QtPaths::query_with(&self.global_args.qmake).with_context(|| { format!("failed to query Qt paths with '{}'", self.global_args.qmake) }) }) } } fn main() { pretty_env_logger::init_custom_env("QMLUIC_LOG"); let cli = Cli::parse(); let helper = CommandHelper::new(cli.global_args); match dispatch(&helper, &cli.command) { Ok(()) => {} Err(CommandError::DiagnosticGenerated) => { process::exit(1); } Err(CommandError::Other(err)) => { eprintln!( "{}: {}", console::style("error").for_stderr().red().bold(), console::style(&err).for_stderr().bold() ); for cause in err.chain().skip(1) { eprintln!("{}: {}", console::style("cause").for_stderr().blue(), cause); } process::exit(1); } } } fn dispatch(helper: &CommandHelper, command: &Command) -> Result<(), CommandError> { match command { Command::DumpMetatypes(args) => dump_metatypes(helper, args), Command::GenerateUi(args) => generate_ui(helper, args), Command::Preview(args) => preview(helper, args), } } /// Apply tweaks on QtWidgets metatypes and output modified version /// /// If --output-qmltypes is specified, qmltyperegistrar will be invoked with the metatypes /// to generate qmltypes. #[derive(Args, Clone, Debug)] struct DumpMetatypesArgs { /// Source metatypes file (.json) input: Utf8PathBuf, #[arg(short = 'o', long)] /// Write metatypes output to file (e.g. metatypes.json) output_metatypes: Option<Utf8PathBuf>, #[arg(long)] /// Write qmltypes output to file (e.g. plugins.qmltypes) output_qmltypes: Option<Utf8PathBuf>, } fn dump_metatypes(helper: &CommandHelper, args: &DumpMetatypesArgs) -> Result<(), CommandError> { eprintln!( "{} {}", console::style("processing").for_stderr().green().bold(), &args.input ); let data = fs::read_to_string(&args.input) .with_context(|| format!("failed to load metatypes file: {}", args.input))?; // TODO: report ignored: https://github.com/dtolnay/serde-ignored ? let mut units: Vec<metatype::CompilationUnit> = serde_json::from_str(&data) .with_context(|| format!("failed to parse metatypes file: {}", args.input))?; for u in units.iter_mut() { metatype_tweak::fix_classes(&mut u.classes); for c in u.classes.iter_mut() { // TODO: maybe restrict to QWidget/QLayout classes? c.class_infos .push(metatype::ClassInfo::new("QML.Element", "auto")); } } // attached type shouldn't be exported as QML.Element units.push(metatype::CompilationUnit { classes: metatype_tweak::internal_gui_classes().into_iter().collect(), ..Default::default() }); units.push(metatype::CompilationUnit { classes: metatype_tweak::internal_widgets_classes() .into_iter() .collect(), ..Default::default() }); if let Some(metatypes_path) = &args.output_metatypes { let perm = fs::metadata(&args.input) .context("failed to get source file permission")? .permissions(); // assume this is the default file permissions with_output_file(metatypes_path, perm, |out| { serde_json::to_writer_pretty(BufWriter::new(out), &units) }) .with_context(|| format!("failed to dump metatypes to file: {metatypes_path}"))?; if let Some(qmltypes_path) = &args.output_qmltypes { generate_qmltypes(helper.qt_paths()?, qmltypes_path, metatypes_path)?; } } else if let Some(qmltypes_path) = &args.output_qmltypes { let mut metatypes_file = NamedTempFile::new().context("failed to create temporary metatypes file")?; serde_json::to_writer_pretty(BufWriter::new(&mut metatypes_file), &units) .context("failed to dump temporary metatypes")?; metatypes_file .flush() .context("failed to dump temporary metatypes")?; generate_qmltypes( helper.qt_paths()?, qmltypes_path, metatypes_file .path() .try_into() .expect("temporary file name should be valid utf-8"), )?; } else { let stdout = io::stdout(); serde_json::to_writer_pretty(BufWriter::new(stdout.lock()), &units) .context("failed to dump metatypes")?; } Ok(()) } fn generate_qmltypes( qt_paths: &QtPaths, output_qmltypes: &Utf8Path, source_metatypes: &Utf8Path, ) -> Result<(), CommandError> { let bin_path = match qt_paths { QtPaths { version: Some(QtVersion { major: 6, .. }), install_libexecs: Some(p), .. } => p, QtPaths { version: Some(QtVersion { major: 5, .. }), install_bins: Some(p), .. } => p, _ => return Err(anyhow!("qmltyperegistrar path cannot be detected").into()), }; let metatypes_path = qt_paths .install_libs .as_ref() .map(|p| p.join("metatypes")) .ok_or_else(|| anyhow!("Qt metatypes path cannot be detected"))?; let qt_version = qt_paths .version .ok_or_else(|| anyhow!("Qt version cannot be detected"))?; if output_qmltypes.as_str().starts_with('-') { // qmltyperegistrar doesn't support "--" separator return Err(CommandError::Other(anyhow!( "invalid output file name: {output_qmltypes}" ))); } let mut cmd = process::Command::new(bin_path.join("qmltyperegistrar")); cmd.arg("--import-name") .arg("qmluic.QtWidgets") .arg("--major-version") .arg(qt_version.major.to_string()) .arg("--foreign-types") .arg(metatypes_path.join(format!("qt{}core_metatypes.json", qt_version.major))) .arg("--generate-qmltypes") .arg(output_qmltypes) .arg(source_metatypes) .stdout(process::Stdio::null()); log::debug!("executing {cmd:?}"); let status = cmd.status().context("failed to run qmltyperegistrar")?; if status.success() { Ok(()) } else { Err(CommandError::Other(anyhow!( "qmltyperegistrar exited with {}", status.code().unwrap_or(-1) ))) } } /// Generate UI XML (.ui) from QML (.qml) #[derive(Args, Clone, Debug)] struct GenerateUiArgs { /// QML files to parse #[arg(required = true)] sources: Vec<Utf8PathBuf>, /// Create output files in the given directory. /// /// If specified, the source file paths must be relative and not contain "..". #[arg(short = 'O', long)] output_directory: Option<Utf8PathBuf>, #[arg(long)] /// Qt metatypes.json files/directories to load /// /// By default, qt${major}core/gui/widgets_*.json will be loaded from the /// QT_INSTALL_LIBS/metatypes directory. foreign_types: Vec<Utf8PathBuf>, /// Do not generate C++ code to set up dynamic bindings #[arg(long)] no_dynamic_binding: bool, /// Do not convert output file names to lowercase #[arg(long)] no_lowercase_file_name: bool, } fn generate_ui(helper: &CommandHelper, args: &GenerateUiArgs) -> Result<(), CommandError> { if args.output_directory.is_some() && args.sources.iter().any(|p| { !p.components() .all(|c| matches!(c, Utf8Component::CurDir | Utf8Component::Normal(_))) }) { return Err(CommandError::Other(anyhow!( "source file paths must be relative if --output-directory is specified", ))); } let mut type_map = load_type_map(helper, &args.foreign_types)?; let mut docs_cache = UiDocumentsCache::new(); let mut project_diagnostics = ProjectDiagnostics::new(); qmldir::populate_directories( &mut type_map, &mut docs_cache, &args.sources, &mut project_diagnostics, ) .map_err(anyhow::Error::from)?; if !project_diagnostics.is_empty() { // for the specified sources, more detailed diagnostics will be emitted later let sources: HashSet<_> = args.sources.iter().map(qmldir::normalize_path).collect(); for (p, ds) in project_diagnostics .iter() .filter(|(p, _)| !sources.contains(p)) { reporting::print_diagnostics(docs_cache.get(p).unwrap(), ds)?; } } let file_name_rules = FileNameRules { lowercase: !args.no_lowercase_file_name, ..Default::default() }; let dynamic_binding_handling = if args.no_dynamic_binding { DynamicBindingHandling::Reject } else { DynamicBindingHandling::Generate }; let ctx = BuildContext::prepare(&type_map, file_name_rules, dynamic_binding_handling) .map_err(anyhow::Error::from)?; for p in &args.sources { generate_ui_file(&ctx, &docs_cache, p, args.output_directory.as_deref())?; } Ok(()) } fn generate_ui_file( ctx: &BuildContext, docs_cache: &UiDocumentsCache, source: &Utf8Path, output_directory: Option<&Utf8Path>, ) -> Result<(), CommandError> { eprintln!( "{} {}", console::style("processing").for_stderr().green().bold(), source ); let doc = docs_cache .get(source) .ok_or_else(|| anyhow!("QML source not loaded (bad file suffix?): {source}"))?; if doc.has_syntax_error() { reporting::print_syntax_errors(doc)?; return Err(CommandError::DiagnosticGenerated); } log::debug!("building ui for {source:?}"); let mut diagnostics = Diagnostics::new(); let (form, ui_support_opt) = match uigen::build(ctx, doc, &mut diagnostics) { Some(x) if !diagnostics.has_error() => { reporting::print_diagnostics(doc, &diagnostics)?; // emit warnings if any x } _ => { reporting::print_diagnostics(doc, &diagnostics)?; return Err(CommandError::DiagnosticGenerated); } }; let (ui_out_path, ui_support_h_out_path) = { let ui_path = source.with_file_name(ctx.file_name_rules.type_name_to_ui_name(doc.type_name())); let ui_support_h_path = source.with_file_name( ctx.file_name_rules .type_name_to_ui_support_cxx_header_name(doc.type_name()), ); if let Some(dir) = output_directory { (dir.join(ui_path), dir.join(ui_support_h_path)) } else { (ui_path, ui_support_h_path) } }; let perm = fs::metadata(source) .context("failed to get source file permission")? .permissions(); // assume this is the default file permissions let mut ui_serialized = Vec::new(); form.serialize_to_xml(&mut XmlWriter::new_with_indent(&mut ui_serialized, b' ', 1)) .context("failed to serializee UI XML")?; // do not touch the output file if unchanged so the subsequent build steps wouldn't run if !fs::read(&ui_out_path) .map(|d| d == ui_serialized) .unwrap_or(false) { with_output_file(&ui_out_path, perm.clone(), |out| { out.write_all(&ui_serialized) }) .context("failed to write UI XML")?; } if let Some(ui_support) = ui_support_opt { let mut h_data = Vec::new(); ui_support .write_header(&mut h_data) .context("failed to generate UI support header")?; if !fs::read(&ui_support_h_out_path) .map(|d| d == h_data) .unwrap_or(false) { with_output_file(&ui_support_h_out_path, perm, |out| out.write_all(&h_data)) .context("failed to write UI support header")?; } } Ok(()) } /// Preview UI QML (.qml) /// /// The previewer tries to render the UI QML document even it had syntax/semantic errors. #[derive(Args, Clone, Debug)] struct PreviewArgs { /// QML file to load source: Utf8PathBuf, #[arg(long)] /// Qt metatypes.json files/directories to load /// /// By default, qt${major}core/gui/widgets_*.json will be loaded from the /// QT_INSTALL_LIBS/metatypes directory. foreign_types: Vec<Utf8PathBuf>, } fn preview(helper: &CommandHelper, args: &PreviewArgs) -> Result<(), CommandError> { let mut type_map = load_type_map(helper, &args.foreign_types)?; let mut docs_cache = UiDocumentsCache::new(); let mut project_diagnostics = ProjectDiagnostics::new(); qmldir::populate_directories( &mut type_map, &mut docs_cache, [&args.source], &mut project_diagnostics, ) .map_err(anyhow::Error::from)?; for (p, ds) in project_diagnostics.iter() { reporting::print_diagnostics(docs_cache.get(p).unwrap(), ds)?; } let mut viewer = UiViewer::spawn()?; let file_name_rules = FileNameRules::default(); let ctx = BuildContext::prepare(&type_map, file_name_rules, DynamicBindingHandling::Omit) .map_err(anyhow::Error::from)?; preview_file(&mut viewer, &ctx, &mut docs_cache, &args.source)?; #[derive(Debug)] enum Message { Filesystem(notify::Result<notify::Event>), Interrupted, } let (tx, rx) = mpsc::channel(); let tx2 = tx.clone(); let mut watcher = notify::recommended_watcher(move |r| { let _ = tx.send(Message::Filesystem(r)); }) .context("failed to create file watcher")?; ctrlc::set_handler(move || { let _ = tx2.send(Message::Interrupted); }) .context("failed to register signal handler")?; let canonical_doc_path = args .source .canonicalize() .context("failed to get canonical doc path")?; // watches the parent directory as the doc file may be recreated let watch_base_path = canonical_doc_path .parent() .expect("file path should have parent"); watcher .watch(watch_base_path, RecursiveMode::NonRecursive) .with_context(|| format!("failed to watch {:?}", watch_base_path))?; while let Ok(m) = rx.recv() { log::trace!("message: {m:?}"); match m { Message::Filesystem(Ok(ev)) => { use notify::EventKind; if matches!(ev.kind, EventKind::Create(_) | EventKind::Modify(_)) && ev.paths.contains(&canonical_doc_path) { // TODO: refresh populated qmldirs as needed docs_cache.remove(&args.source); preview_file(&mut viewer, &ctx, &mut docs_cache, &args.source)?; } } Message::Filesystem(Err(_)) => {} Message::Interrupted => break, } } // TODO: quit on previewer window closed viewer.wait()?; Ok(()) } fn preview_file( viewer: &mut UiViewer, ctx: &BuildContext, docs_cache: &mut UiDocumentsCache, source: &Utf8Path, ) -> Result<(), CommandError> { eprintln!( "{} {}", console::style("processing").for_stderr().green().bold(), source ); let doc = docs_cache .read(source) .with_context(|| format!("failed to load QML document: {source}"))?; if doc.has_syntax_error() { reporting::print_syntax_errors(doc)?; } log::debug!("building ui for {:?}", source); let mut diagnostics = Diagnostics::new(); let maybe_form = uigen::build(ctx, doc, &mut diagnostics); reporting::print_diagnostics(doc, &diagnostics)?; if let Some((form, None)) = maybe_form { let mut data = Vec::new(); form.serialize_to_xml(&mut XmlWriter::new(&mut data)) .context("failed to serialize UI to XML")?; viewer.write_ui_data(&data)?; } Ok(()) } fn load_type_map( helper: &CommandHelper, foreign_type_paths: &[Utf8PathBuf], ) -> anyhow::Result<TypeMap> { let mut type_map = TypeMap::with_primitive_types(); let mut classes = if foreign_type_paths.is_empty() { load_metatypes(&find_installed_metatype_files(helper.qt_paths()?)?)? } else { load_metatypes(foreign_type_paths)? }; metatype_tweak::apply_all(&mut classes); let mut module_data = ModuleData::with_builtins(); module_data.extend(classes); type_map.insert_module(ModuleId::Named("qmluic.QtWidgets"), module_data); Ok(type_map) } fn load_metatypes(paths: &[Utf8PathBuf]) -> anyhow::Result<Vec<metatype::Class>> { fn load_into(classes: &mut Vec<metatype::Class>, path: &Utf8Path) -> io::Result<()> { log::trace!("loading metatypes file {path:?}"); let data = fs::read_to_string(path)?; let cs = metatype::extract_classes_from_str(&data)?; classes.extend(cs); Ok(()) } log::debug!("loading metatypes from {paths:?}"); paths.iter().try_fold(vec![], |mut classes, path| { if path.is_dir() { for r in path.read_dir_utf8()? { let e = r?; let p = e.path(); if p.as_str().ends_with(".json") { load_into(&mut classes, p)?; } } } else { load_into(&mut classes, path)?; } Ok(classes) }) } fn find_installed_metatype_files(paths: &QtPaths) -> anyhow::Result<Vec<Utf8PathBuf>> { // Recent versions of Qt 6 appear to install metatypes under the ARCHDATA // directory. Old Qt 6 and Qt 5 install them to LIBS. let base_path = [paths.install_archdata.as_ref(), paths.install_libs.as_ref()] .iter() .flatten() .map(|p| p.join("metatypes")) .find(|p| p.exists()) .ok_or_else(|| anyhow!("Qt metatypes path cannot be detected"))?; let major = paths .version .as_ref() .map(|v| v.major) .ok_or_else(|| anyhow!("Qt metatypes version cannot be detected"))?; let prefixes = [ format!("qt{major}core_"), format!("qt{major}gui_"), format!("qt{major}widgets_"), ]; let mut file_paths = Vec::new(); for r in base_path.read_dir_utf8()? { let e = r?; let p = e.path(); if p.file_name() .map(|s| prefixes.iter().any(|p| s.starts_with(p)) && s.ends_with(".json")) .unwrap_or(false) { file_paths.push(p.to_owned()); } } Ok(file_paths) } fn with_output_file<P, F, E>(path: P, perm: fs::Permissions, f: F) -> anyhow::Result<()> where P: AsRef<Path>, F: FnOnce(&mut NamedTempFile) -> Result<(), E>, E: std::error::Error + Send + Sync + 'static, { let path = path.as_ref(); let dir = path.parent().ok_or_else(|| anyhow!("invalid file name"))?; fs::create_dir_all(dir).context("failed to create output directory")?; let mut out = NamedTempFile::new_in(dir)?; f(&mut out)?; out.as_file().set_permissions(perm)?; out.persist(path)?; Ok(()) }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
src/qtpaths.rs
Rust
use camino::Utf8PathBuf; use std::ffi::OsStr; use std::fmt; use std::io; use std::process::Command; use std::str; use thiserror::Error; /// Information about Qt installation. #[derive(Clone, Debug, Default)] pub struct QtPaths { pub sysroot: Option<Utf8PathBuf>, pub install_prefix: Option<Utf8PathBuf>, pub install_archdata: Option<Utf8PathBuf>, pub install_data: Option<Utf8PathBuf>, pub install_docs: Option<Utf8PathBuf>, pub install_headers: Option<Utf8PathBuf>, pub install_libs: Option<Utf8PathBuf>, pub install_libexecs: Option<Utf8PathBuf>, pub install_bins: Option<Utf8PathBuf>, pub install_tests: Option<Utf8PathBuf>, pub install_plugins: Option<Utf8PathBuf>, pub install_imports: Option<Utf8PathBuf>, pub install_qml: Option<Utf8PathBuf>, pub install_translations: Option<Utf8PathBuf>, pub install_configuration: Option<Utf8PathBuf>, pub install_examples: Option<Utf8PathBuf>, pub install_demos: Option<Utf8PathBuf>, pub host_prefix: Option<Utf8PathBuf>, pub host_data: Option<Utf8PathBuf>, pub host_bins: Option<Utf8PathBuf>, pub host_libs: Option<Utf8PathBuf>, // QMAKE_SPEC:linux-g++ // QMAKE_XSPEC:linux-g++ // QMAKE_VERSION:3.1 pub version: Option<QtVersion>, } impl QtPaths { /// Queries paths by executing `qmake -query`. pub fn query() -> Result<Self, QueryError> { Self::query_with("qmake") } pub fn query_with<S>(program: S) -> Result<Self, QueryError> where S: AsRef<OsStr>, { let mut cmd = Command::new(program); cmd.arg("-query"); log::debug!("executing {cmd:?}"); let output = cmd.output()?; if !output.status.success() { return Err(QueryError::CommandFailed( String::from_utf8_lossy(&output.stderr).to_string(), )); } Self::parse(str::from_utf8(&output.stdout)?) } fn parse(data: &str) -> Result<Self, QueryError> { let mut paths = QtPaths::default(); for line in data.lines() { if let Some((k, v)) = line.split_once(':') { match k { "QT_SYSROOT" => paths.sysroot = to_path_buf(v), "QT_INSTALL_PREFIX" => paths.install_prefix = to_path_buf(v), "QT_INSTALL_ARCHDATA" => paths.install_archdata = to_path_buf(v), "QT_INSTALL_DATA" => paths.install_data = to_path_buf(v), "QT_INSTALL_DOCS" => paths.install_docs = to_path_buf(v), "QT_INSTALL_HEADERS" => paths.install_headers = to_path_buf(v), "QT_INSTALL_LIBS" => paths.install_libs = to_path_buf(v), "QT_INSTALL_LIBEXECS" => paths.install_libexecs = to_path_buf(v), "QT_INSTALL_BINS" => paths.install_bins = to_path_buf(v), "QT_INSTALL_TESTS" => paths.install_tests = to_path_buf(v), "QT_INSTALL_PLUGINS" => paths.install_plugins = to_path_buf(v), "QT_INSTALL_IMPORTS" => paths.install_imports = to_path_buf(v), "QT_INSTALL_QML" => paths.install_qml = to_path_buf(v), "QT_INSTALL_TRANSLATIONS" => paths.install_translations = to_path_buf(v), "QT_INSTALL_CONFIGURATION" => paths.install_configuration = to_path_buf(v), "QT_INSTALL_EXAMPLES" => paths.install_examples = to_path_buf(v), "QT_INSTALL_DEMOS" => paths.install_demos = to_path_buf(v), "QT_HOST_PREFIX" => paths.host_prefix = to_path_buf(v), "QT_HOST_DATA" => paths.host_data = to_path_buf(v), "QT_HOST_BINS" => paths.host_bins = to_path_buf(v), "QT_HOST_LIBS" => paths.host_libs = to_path_buf(v), "QT_VERSION" => paths.version = Some(v.try_into()?), _ => {} } } } Ok(paths) } } #[derive(Debug, Error)] pub enum QueryError { #[error(transparent)] Io(#[from] io::Error), #[error("qmake -query failed: {0}")] CommandFailed(String), #[error("invalid content: {0}")] InvalidData(#[from] str::Utf8Error), #[error("invalid version digits: {0}")] ParseVersion(String), } #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct QtVersion { pub major: u8, pub minor: u8, pub patch: u8, } impl TryFrom<&str> for QtVersion { type Error = QueryError; fn try_from(value: &str) -> Result<Self, Self::Error> { let parse_one = |x: Option<&str>| { x.and_then(|s| s.parse().ok()) .ok_or_else(|| QueryError::ParseVersion(value.to_owned())) }; let mut digits = value.splitn(3, '.'); let major = parse_one(digits.next())?; let minor = parse_one(digits.next())?; let patch = parse_one(digits.next())?; if digits.next().is_none() { Ok(QtVersion { major, minor, patch, }) } else { Err(QueryError::ParseVersion(value.to_owned())) } } } impl fmt::Display for QtVersion { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}.{}.{}", self.major, self.minor, self.patch) } } fn to_path_buf(s: &str) -> Option<Utf8PathBuf> { if s.is_empty() { None } else { Some(Utf8PathBuf::from(s)) } }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
src/reporting.rs
Rust
use camino::{Utf8Path, Utf8PathBuf}; use codespan_reporting::diagnostic::{Label, LabelStyle, Severity}; use codespan_reporting::files::SimpleFile; use codespan_reporting::term; use qmluic::diagnostic::{DiagnosticKind, Diagnostics}; use qmluic::qmldoc::{SyntaxError, SyntaxErrorKind, UiDocument}; use std::borrow::Cow; use std::env; use std::iter; use std::path::Path; use termcolor::{ColorChoice, StandardStream}; pub type ReportableDiagnostic = codespan_reporting::diagnostic::Diagnostic<()>; pub fn print_syntax_errors(doc: &UiDocument) -> anyhow::Result<()> { let errors = doc.collect_syntax_errors(); print_reportable_diagnostics(doc, make_reportable_syntax_errors(&errors)) } pub fn print_diagnostics(doc: &UiDocument, diagnostics: &Diagnostics) -> anyhow::Result<()> { print_reportable_diagnostics(doc, make_reportable_diagnostics(diagnostics)) } pub fn make_reportable_syntax_errors<'a>( errors: &'a [SyntaxError], ) -> impl Iterator<Item = ReportableDiagnostic> + 'a { errors.iter().map(|e| { let d = ReportableDiagnostic::error(); match e.kind() { SyntaxErrorKind::Error => d .with_message("syntax error") .with_labels(vec![Label::primary((), e.byte_range())]), _ => d .with_message(format!("syntax error: {}", e)) .with_labels(vec![ Label::primary((), e.byte_range()).with_message(e.to_string()) ]), } }) } pub fn make_reportable_diagnostics( diagnostics: &Diagnostics, ) -> impl Iterator<Item = ReportableDiagnostic> + '_ { diagnostics.iter().map(|diag| { let severity = match diag.kind() { DiagnosticKind::Error => Severity::Error, DiagnosticKind::Warning => Severity::Warning, }; let labels = if diag.labels().is_empty() { vec![Label::primary((), diag.byte_range())] } else { diag.labels() .iter() .map(|(r, s)| { let k = if r == &diag.byte_range() { LabelStyle::Primary } else { LabelStyle::Secondary }; Label::new(k, (), r.clone()).with_message(s) }) .collect() }; ReportableDiagnostic { severity, code: None, message: diag.message().into(), labels, notes: diag.notes().into(), } }) } fn print_reportable_diagnostics<I>(doc: &UiDocument, diagnostics: I) -> anyhow::Result<()> where I: IntoIterator<Item = ReportableDiagnostic>, { let stderr = StandardStream::stderr(ColorChoice::Auto); let config = term::Config::default(); let rel_path = doc.path().map(make_cwd_relative_path); let files = SimpleFile::new( rel_path.unwrap_or_else(|| Cow::Borrowed("<unknown>".into())), doc.source(), ); for d in diagnostics { term::emit_to_write_style(&mut stderr.lock(), &config, &files, &d)?; } Ok(()) } /// Turns the given `path` into relative path from the `start`. /// /// Both `path` and `start` are supposed to be absolute paths. /// /// ``` /// # use camino::Utf8Path; /// # use std::path::Path; /// # use qmluic_cli::reporting::*; /// assert_eq!(make_relative_path(Utf8Path::new("/foo"), Path::new("/foo")), /// Utf8Path::new(".")); /// assert_eq!(make_relative_path(Utf8Path::new("/foo/bar"), Path::new("/foo")), /// Utf8Path::new("bar")); /// assert_eq!(make_relative_path(Utf8Path::new("/foo"), Path::new("/foo/bar")), /// Utf8Path::new("..")); /// assert_eq!(make_relative_path(Utf8Path::new("/foo/bar"), Path::new("/foo/foo/baz")), /// Utf8Path::new("../../bar")); /// assert_eq!(make_relative_path(Utf8Path::new("/foo/bar"), Path::new("/baz")), /// Utf8Path::new("../foo/bar")); /// ``` pub fn make_relative_path(path: &Utf8Path, start: impl AsRef<Path>) -> Cow<'_, Utf8Path> { // find common prefix for (i, base) in start.as_ref().ancestors().enumerate() { if let Ok(p) = path.strip_prefix(base) { if i == 0 && p.as_str().is_empty() { return Cow::Borrowed(".".into()); } else if i == 0 { return Cow::Borrowed(p); } else { let mut rel_path = Utf8PathBuf::from_iter(iter::repeat("..").take(i)); rel_path.push(p); return Cow::Owned(rel_path); } } } // no way to make it relative (e.g. different Windows drive letter?) Cow::Borrowed(path) } /// Turns the given `path` into relative path from the current working directory. pub fn make_cwd_relative_path(path: &Utf8Path) -> Cow<'_, Utf8Path> { // qmldir::normalize_path() uses canonicalize(), which disagree with the cwd on Windows. if let Ok(cwd) = env::current_dir().and_then(|p| p.canonicalize()) { make_relative_path(path, cwd) } else { Cow::Borrowed(path) } }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
src/uiviewer.rs
Rust
use anyhow::Context as _; use std::env; use std::ffi::OsStr; use std::io::{self, Read as _, Write as _}; use std::process::{Child, ChildStdin, ChildStdout, Command, ExitStatus, Stdio}; /// Interface to UI viewer process. #[derive(Debug)] pub struct UiViewer { child: Child, stdin: ChildStdin, stdout: ChildStdout, } impl UiViewer { pub fn spawn() -> anyhow::Result<UiViewer> { let bin_dir = env::current_exe().context("failed to get executable path")?; Self::spawn_program(bin_dir.with_file_name("qmluic-uiviewer")) } pub fn spawn_program<S>(program: S) -> anyhow::Result<UiViewer> where S: AsRef<OsStr>, { let mut cmd = Command::new(program); cmd.arg("--pipe") .stdin(Stdio::piped()) .stdout(Stdio::piped()); log::debug!("spawning {cmd:?}"); let mut child = cmd .spawn() .with_context(|| format!("failed to spawn {:?}", cmd.get_program()))?; let stdin = child.stdin.take().unwrap(); let stdout = child.stdout.take().unwrap(); let mut viewer = UiViewer { child, stdin, stdout, }; log::trace!("waiting for viewer start message"); viewer .read_response() .context("failed to wait for viewer start message")?; Ok(viewer) } pub fn wait(mut self) -> anyhow::Result<ExitStatus> { drop(self.stdin); self.child.wait().context("failed to wait for viewer exit") } pub fn write_ui_data(&mut self, data: &[u8]) -> anyhow::Result<()> { let len = i32::try_from(data.len()).context("serialized XML too large")?; log::trace!("sending serialized data to viewer"); self.write_data(len, data) .context("failed to communicate with viewer")?; log::trace!("waiting for viewer response"); self.read_response() .context("failed to get viewer response")?; Ok(()) } fn read_response(&mut self) -> io::Result<i32> { let mut buf = [0; 4]; self.stdout.read_exact(&mut buf)?; Ok(i32::from_ne_bytes(buf)) } fn write_data(&mut self, len: i32, data: &[u8]) -> io::Result<()> { self.stdin.write_all(&len.to_ne_bytes())?; self.stdin.write_all(data)?; self.stdin.flush() } }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
tests/common/mod.rs
Rust
use assert_cmd::Command; use camino::Utf8Path; use codespan_reporting::files::SimpleFile; use codespan_reporting::term; use qmluic::diagnostic::{Diagnostics, ProjectDiagnostics}; use qmluic::metatype; use qmluic::metatype_tweak; use qmluic::qmldir; use qmluic::qmldoc::{UiDocument, UiDocumentsCache}; use qmluic::qtname::FileNameRules; use qmluic::typemap::{ModuleData, ModuleId, TypeMap}; use qmluic::uigen::{self, BuildContext, DynamicBindingHandling, XmlWriter}; use qmluic_cli::reporting::{self, ReportableDiagnostic}; use std::ffi::OsStr; use std::fs; use std::path::{Path, PathBuf}; use std::str; use tempfile::TempDir; pub struct TestEnv { temp_dir: TempDir, } impl TestEnv { pub fn prepare() -> Self { let temp_dir = TempDir::new().unwrap(); TestEnv { temp_dir } } pub fn base_path(&self) -> &Path { self.temp_dir.path() } pub fn join(&self, path: impl AsRef<Path>) -> PathBuf { self.base_path().join(path) } pub fn create_dir_all(&self, path: impl AsRef<Path>) { fs::create_dir_all(self.join(path)).unwrap(); } pub fn write_dedent(&self, path: impl AsRef<Path>, data: impl AsRef<str>) { let full_path = self.join(path); fs::create_dir_all(full_path.parent().unwrap()).unwrap(); fs::write(&full_path, dedent(data)).unwrap(); } pub fn read_to_string(&self, path: impl AsRef<Path>) -> String { fs::read_to_string(self.join(path)).unwrap() } pub fn generate_ui_cmd(&self, args: impl IntoIterator<Item = impl AsRef<OsStr>>) -> Command { let mut cmd = assert_cmd::cargo::cargo_bin_cmd!("qmluic"); cmd.current_dir(self.base_path()) .env("NO_COLOR", "") .arg("generate-ui") .arg("--foreign-types") .arg(Path::new("contrib/metatypes").canonicalize().unwrap()) .args(args); cmd } } pub fn dedent(data: impl AsRef<str>) -> String { let data = data.as_ref(); let mut leader: String = data .chars() .take_while(|&c| c == '\n' || c == ' ') .collect(); let data = &data[leader.len()..]; if !leader.starts_with('\n') { leader.insert(0, '\n'); } assert_eq!(leader.chars().filter(|&c| c == '\n').count(), 1); data.replace(&leader, "\n") } pub fn parse_doc(source: impl AsRef<str>) -> UiDocument { UiDocument::parse(dedent(source), "MyType", None) } pub fn translate_file(path: impl AsRef<Utf8Path>) -> Result<(String, String), String> { let doc = UiDocument::read(path).unwrap(); translate_doc(&doc, DynamicBindingHandling::Generate) } pub fn translate_str(source: impl AsRef<str>) -> Result<String, String> { let doc = UiDocument::parse(dedent(source), "MyType", None); let (ui_xml, _) = translate_doc(&doc, DynamicBindingHandling::Reject)?; Ok(ui_xml) } pub fn translate_doc( doc: &UiDocument, dynamic_binding_handling: DynamicBindingHandling, ) -> Result<(String, String), String> { if doc.has_syntax_error() { return Err(format_reportable_diagnostics( doc, reporting::make_reportable_syntax_errors(&doc.collect_syntax_errors()), )); } let mut type_map = TypeMap::with_primitive_types(); let mut classes = load_metatypes(); metatype_tweak::apply_all(&mut classes); let mut module_data = ModuleData::with_builtins(); module_data.extend(classes); type_map.insert_module(ModuleId::Named("qmluic.QtWidgets"), module_data); if let Some(p) = doc.path() { let mut docs_cache = UiDocumentsCache::new(); let mut project_diagnostics = ProjectDiagnostics::new(); qmldir::populate_directories( &mut type_map, &mut docs_cache, [p], &mut project_diagnostics, ) .unwrap(); } let ctx = BuildContext::prepare( &type_map, FileNameRules::default(), dynamic_binding_handling, ) .unwrap(); let mut diagnostics = Diagnostics::new(); let (form, ui_support_opt) = match uigen::build(&ctx, doc, &mut diagnostics) { Some(x) if diagnostics.is_empty() => x, _ => { // may be only warnings, but we do want to test warning outputs return Err(format_reportable_diagnostics( doc, reporting::make_reportable_diagnostics(&diagnostics), )); } }; let mut form_buf = Vec::new(); form.serialize_to_xml(&mut XmlWriter::new_with_indent(&mut form_buf, b' ', 1)) .unwrap(); let mut ui_support_buf = Vec::new(); if let Some(ui_support) = ui_support_opt { ui_support.write_header(&mut ui_support_buf).unwrap(); } Ok(( String::from_utf8(form_buf).unwrap(), String::from_utf8(ui_support_buf).unwrap(), )) } fn load_metatypes() -> Vec<metatype::Class> { let paths = [ "contrib/metatypes/qt5core_metatypes.json", "contrib/metatypes/qt5gui_metatypes.json", "contrib/metatypes/qt5widgets_metatypes.json", ]; paths .iter() .flat_map(|p| { let data = fs::read_to_string(p).unwrap(); metatype::extract_classes_from_str(&data).unwrap() }) .collect() } fn format_reportable_diagnostics( doc: &UiDocument, diagnostics: impl IntoIterator<Item = ReportableDiagnostic>, ) -> String { let mut buf = String::new(); let config = term::Config::default(); let files = SimpleFile::new( doc.path() .and_then(|p| p.file_name()) .unwrap_or("<unknown>"), doc.source(), ); for d in diagnostics { term::emit_to_string(&mut buf, &config, &files, &d).unwrap(); } buf }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
tests/test_generate_ui_command.rs
Rust
use self::common::TestEnv; use std::str; pub mod common; #[test] fn test_simple_file() { let env = TestEnv::prepare(); env.write_dedent( "Simple.qml", r###" import qmluic.QtWidgets QDialog {} "###, ); let a = env .generate_ui_cmd(["--no-dynamic-binding", "Simple.qml"]) .assert() .success(); insta::assert_snapshot!( str::from_utf8(&a.get_output().stderr).unwrap(), @"processing Simple.qml"); insta::assert_snapshot!(env.read_to_string("simple.ui"), @r###" <ui version="4.0"> <class>Simple</class> <widget class="QDialog" name="dialog"> </widget> </ui> "###); assert!(!env.join("uisupport_simple.h").exists()); } #[test] fn test_output_directory() { let env = TestEnv::prepare(); env.write_dedent("Base.qml", "import qmluic.QtWidgets; QWidget {}"); env.write_dedent("dir/Nested.qml", "import qmluic.QtWidgets; QWidget {}"); env.generate_ui_cmd(["-O", "out/put", "Base.qml", "dir/Nested.qml"]) .assert() .success(); assert!(env.join("out/put/base.ui").exists()); assert!(env.join("out/put/uisupport_base.h").exists()); assert!(env.join("out/put/dir/nested.ui").exists()); assert!(env.join("out/put/dir/uisupport_nested.h").exists()); } #[test] fn test_output_directory_absolute() { let env = TestEnv::prepare(); env.write_dedent("Foo.qml", "import qmluic.QtWidgets; QWidget {}"); let a = env .generate_ui_cmd(["-O", "out", env.join("Foo.qml").to_str().unwrap()]) .assert() .failure(); insta::assert_snapshot!( str::from_utf8(&a.get_output().stderr).unwrap(), @"error: source file paths must be relative if --output-directory is specified"); } #[test] fn test_output_directory_escaped() { let env = TestEnv::prepare(); env.write_dedent("Foo.qml", "import qmluic.QtWidgets; QWidget {}"); env.create_dir_all("dir"); let a = env .generate_ui_cmd(["-O", "out", "./../Foo.qml"]) .current_dir(env.join("dir")) .assert() .failure(); insta::assert_snapshot!( str::from_utf8(&a.get_output().stderr).unwrap(), @"error: source file paths must be relative if --output-directory is specified"); } #[test] fn test_property_error() { let env = TestEnv::prepare(); env.write_dedent( "PropError.qml", r###" import qmluic.QtWidgets QDialog { unknown: "" } "###, ); let a = env.generate_ui_cmd(["PropError.qml"]).assert().failure(); insta::assert_snapshot!(str::from_utf8(&a.get_output().stderr).unwrap(), @r###" processing PropError.qml error: unknown property of class 'QDialog': unknown ┌─ PropError.qml:3:5 │ 3 │ unknown: "" │ ^^^^^^^^^^^ "###); assert!(!env.join("properror.ui").exists()); } #[test] fn test_syntax_error_general() { let env = TestEnv::prepare(); env.write_dedent( "SyntaxError.qml", r###" import qmluic.QtWidgets QDialog { windowTitle: "what" "ever" } "###, ); let a = env.generate_ui_cmd(["SyntaxError.qml"]).assert().failure(); insta::assert_snapshot!(str::from_utf8(&a.get_output().stderr).unwrap(), @r###" processing SyntaxError.qml error: syntax error ┌─ SyntaxError.qml:2:24 │ 2 │ QDialog { windowTitle: "what" "ever" } │ ^^^^^^ "###); assert!(!env.join("syntaxerror.ui").exists()); } #[test] fn test_syntax_error_missing() { let env = TestEnv::prepare(); env.write_dedent( "SyntaxError.qml", r###" import qmluic.QtWidgets QDialog { windowTitle: "what" "###, ); let a = env.generate_ui_cmd(["SyntaxError.qml"]).assert().failure(); insta::assert_snapshot!(str::from_utf8(&a.get_output().stderr).unwrap(), @r###" processing SyntaxError.qml error: syntax error: missing } ┌─ SyntaxError.qml:2:30 │ 2 │ QDialog { windowTitle: "what" │ ^ missing } "###); assert!(!env.join("syntaxerror.ui").exists()); } #[test] fn test_warning() { let env = TestEnv::prepare(); env.write_dedent( "Warning.qml", r###" import qmluic.QtWidgets 6.2 QDialog {} "###, ); let a = env.generate_ui_cmd(["Warning.qml"]).assert().success(); insta::assert_snapshot!(str::from_utf8(&a.get_output().stderr).unwrap(), @r###" processing Warning.qml warning: import version is ignored ┌─ Warning.qml:1:1 │ 1 │ import qmluic.QtWidgets 6.2 │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^ "###); assert!(env.join("warning.ui").exists()); }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
tests/test_uigen_attached_property.rs
Rust
pub mod common; #[test] fn test_unknown_attached_type() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QWidget { Whatever.property: 1 } "###).unwrap_err(), @r###" error: unknown attaching type: Whatever ┌─ <unknown>:3:5 │ 3 │ Whatever.property: 1 │ ^^^^^^^^ "###); } #[test] fn test_no_attached_type() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QWidget { QWidget.property: 1 } "###).unwrap_err(), @r###" error: no attached type for type: QWidget ┌─ <unknown>:3:5 │ 3 │ QWidget.property: 1 │ ^^^^^^^ "###); } #[test] fn test_enum_as_attached_type() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QWidget { Qt.Alignment.property: 1 } "###).unwrap_err(), @r###" error: invalid attaching type: Qt::Alignment ┌─ <unknown>:3:5 │ 3 │ Qt.Alignment.property: 1 │ ^^^^^^^^^^^^ "###); } #[test] fn test_unused_attached() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QWidget { QTabWidget.title: "Hello" } "###).unwrap_err(), @r###" error: unused or unsupported dynamic binding to attached property ┌─ <unknown>:3:5 │ 3 │ QTabWidget.title: "Hello" │ ^^^^^^^^^^^^^^^^^^^^^^^^^ "###); } #[test] fn test_partially_used_layout_attached() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QWidget { QVBoxLayout { QWidget { QLayout.columnStretch: 1 QLayout.rowStretch: 2 } } } "###).unwrap_err(), @r###" error: unused or unsupported dynamic binding to attached property ┌─ <unknown>:5:13 │ 5 │ QLayout.columnStretch: 1 │ ^^^^^^^^^^^^^^^^^^^^^^^^ "###); } #[test] fn test_tab_widget() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QTabWidget { QWidget { QTabWidget.title: "Hello" QTabWidget.toolTip: "Hello world!" } } "###).unwrap(), @r###" <ui version="4.0"> <class>MyType</class> <widget class="QTabWidget" name="tabWidget"> <widget class="QWidget" name="widget"> <attribute name="title"> <string notr="true">Hello</string> </attribute> <attribute name="toolTip"> <string notr="true">Hello world!</string> </attribute> </widget> </widget> </ui> "###); }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
tests/test_uigen_examples.rs
Rust
pub mod common; #[test] fn test_binding_loop() { let (ui_xml, ui_support_h) = common::translate_file("examples/BindingLoop.qml").unwrap(); insta::assert_snapshot!(ui_xml); insta::assert_snapshot!(ui_support_h); } #[test] fn test_hg_email_dialog() { let (ui_xml, ui_support_h) = common::translate_file("examples/HgEmailDialog.qml").unwrap(); insta::assert_snapshot!(ui_xml); insta::assert_snapshot!(ui_support_h); } #[test] fn test_item_views() { let (ui_xml, ui_support_h) = common::translate_file("examples/ItemViews.qml").unwrap(); insta::assert_snapshot!(ui_xml); insta::assert_snapshot!(ui_support_h); } #[test] fn test_layout_flow() { let (ui_xml, ui_support_h) = common::translate_file("examples/LayoutFlow.qml").unwrap(); insta::assert_snapshot!(ui_xml); insta::assert_snapshot!(ui_support_h); } #[test] fn test_main_window() { let (ui_xml, ui_support_h) = common::translate_file("examples/MainWindow.qml").unwrap(); insta::assert_snapshot!(ui_xml); insta::assert_snapshot!(ui_support_h); } #[test] fn test_settings_dialog() { let (ui_xml, ui_support_h) = common::translate_file("examples/SettingsDialog.qml").unwrap(); insta::assert_snapshot!(ui_xml); insta::assert_snapshot!(ui_support_h); } #[test] fn test_static_item_model() { let (ui_xml, ui_support_h) = common::translate_file("examples/StaticItemModel.qml").unwrap(); insta::assert_snapshot!(ui_xml); insta::assert_snapshot!(ui_support_h); } #[test] fn test_various_layouts() { let (ui_xml, ui_support_h) = common::translate_file("examples/VariousLayouts.qml").unwrap(); insta::assert_snapshot!(ui_xml); insta::assert_snapshot!(ui_support_h); } #[test] fn test_customwidget_common_my_dialog_button_box() { let (ui_xml, ui_support_h) = common::translate_file("examples/customwidget/common/MyDialogButtonBox.qml").unwrap(); insta::assert_snapshot!(ui_xml); insta::assert_snapshot!(ui_support_h); } #[test] fn test_customwidget_main_dialog() { let (ui_xml, ui_support_h) = common::translate_file("examples/customwidget/MainDialog.qml").unwrap(); insta::assert_snapshot!(ui_xml); insta::assert_snapshot!(ui_support_h); } #[test] fn test_customwidget_settings_form() { let (ui_xml, ui_support_h) = common::translate_file("examples/customwidget/SettingsForm.qml").unwrap(); insta::assert_snapshot!(ui_xml); insta::assert_snapshot!(ui_support_h); }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
tests/test_uigen_gadget.rs
Rust
use qmluic::uigen::DynamicBindingHandling; pub mod common; #[test] fn test_brush() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QGraphicsView { backgroundBrush.color: "#123abc" backgroundBrush.style: Qt.Dense4Pattern } "###).unwrap(), @r###" <ui version="4.0"> <class>MyType</class> <widget class="QGraphicsView" name="graphicsView"> <property name="backgroundBrush"> <brush brushstyle="Dense4Pattern"> <color alpha="255"> <blue>188</blue> <green>58</green> <red>18</red> </color> </brush> </property> </widget> </ui> "###); } #[test] fn test_brush_solid_color() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QGraphicsView { backgroundBrush: "#80123abc" } "###).unwrap(), @r###" <ui version="4.0"> <class>MyType</class> <widget class="QGraphicsView" name="graphicsView"> <property name="backgroundBrush"> <brush brushstyle="SolidPattern"> <color alpha="128"> <blue>188</blue> <green>58</green> <red>18</red> </color> </brush> </property> </widget> </ui> "###); } #[test] fn test_color() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QColorDialog { currentColor: "#123abc" } "###).unwrap(), @r###" <ui version="4.0"> <class>MyType</class> <widget class="QColorDialog" name="colorDialog"> <property name="currentColor"> <color alpha="255"> <blue>188</blue> <green>58</green> <red>18</red> </color> </property> </widget> </ui> "###); } #[test] fn test_color_alpha() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QColorDialog { currentColor: "#80123abc" } "###).unwrap(), @r###" <ui version="4.0"> <class>MyType</class> <widget class="QColorDialog" name="colorDialog"> <property name="currentColor"> <color alpha="128"> <blue>188</blue> <green>58</green> <red>18</red> </color> </property> </widget> </ui> "###); } #[test] fn test_invalid_color() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QColorDialog { currentColor: "#wtf" } "###).unwrap_err(), @r###" error: invalid hex color ┌─ <unknown>:2:30 │ 2 │ QColorDialog { currentColor: "#wtf" } │ ^^^^^^ "###); } #[test] fn test_cursor() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QWidget { cursor: Qt.IBeamCursor } "###).unwrap(), @r###" <ui version="4.0"> <class>MyType</class> <widget class="QWidget" name="widget"> <property name="cursor"> <cursorShape>IBeamCursor</cursorShape> </property> </widget> </ui> "###); } #[test] fn test_font() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QLabel { font.family: "Monospace" font.pointSize: 9 font.weight: 75 font.italic: false font.bold: true font.strikeout: true font.styleStrategy: QFont.PreferDefault font.kerning: true } "###).unwrap(), @r###" <ui version="4.0"> <class>MyType</class> <widget class="QLabel" name="label"> <property name="font"> <font> <bold>true</bold> <family notr="true">Monospace</family> <italic>false</italic> <kerning>true</kerning> <pointsize>9</pointsize> <strikeout>true</strikeout> <stylestrategy>PreferDefault</stylestrategy> <weight>75</weight> </font> </property> </widget> </ui> "###); } #[test] fn test_icon_themed() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QToolButton { icon.name: "edit-copy" } "###).unwrap(), @r###" <ui version="4.0"> <class>MyType</class> <widget class="QToolButton" name="toolButton"> <property name="icon"> <iconset theme="edit-copy"> </iconset> </property> </widget> </ui> "###); } #[test] fn test_icon_state_pixmaps() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QToolButton { icon.normalOff: "normal-off.png" icon.normalOn: "normal-on.png" } "###).unwrap(), @r###" <ui version="4.0"> <class>MyType</class> <widget class="QToolButton" name="toolButton"> <property name="icon"> <iconset> <normaloff>normal-off.png</normaloff> <normalon>normal-on.png</normalon> </iconset> </property> </widget> </ui> "###); } #[test] fn test_palette_color_group() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QWidget { palette.active { window: "black"; windowText: "white" } } "###).unwrap(), @r###" <ui version="4.0"> <class>MyType</class> <widget class="QWidget" name="widget"> <property name="palette"> <palette> <active> <colorrole role="Window"> <brush brushstyle="SolidPattern"> <color alpha="255"> <blue>0</blue> <green>0</green> <red>0</red> </color> </brush> </colorrole> <colorrole role="WindowText"> <brush brushstyle="SolidPattern"> <color alpha="255"> <blue>255</blue> <green>255</green> <red>255</red> </color> </brush> </colorrole> </active> <disabled> </disabled> <inactive> </inactive> </palette> </property> </widget> </ui> "###); } #[test] fn test_palette_default_role() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QWidget { palette.window: "black" palette.disabled.window: "gray" } "###).unwrap(), @r###" <ui version="4.0"> <class>MyType</class> <widget class="QWidget" name="widget"> <property name="palette"> <palette> <active> <colorrole role="Window"> <brush brushstyle="SolidPattern"> <color alpha="255"> <blue>0</blue> <green>0</green> <red>0</red> </color> </brush> </colorrole> </active> <disabled> <colorrole role="Window"> <brush brushstyle="SolidPattern"> <color alpha="255"> <blue>128</blue> <green>128</green> <red>128</red> </color> </brush> </colorrole> </disabled> <inactive> <colorrole role="Window"> <brush brushstyle="SolidPattern"> <color alpha="255"> <blue>0</blue> <green>0</green> <red>0</red> </color> </brush> </colorrole> </inactive> </palette> </property> </widget> </ui> "###); } #[test] fn test_pixmap() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QLabel { pixmap: ":/a.png" } "###).unwrap(), @r###" <ui version="4.0"> <class>MyType</class> <widget class="QLabel" name="label"> <property name="pixmap"> <pixmap>:/a.png</pixmap> </property> </widget> </ui> "###); } #[test] fn test_size_policy() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QWidget { sizePolicy.horizontalPolicy: QSizePolicy.Preferred sizePolicy.verticalPolicy: QSizePolicy.Expanding } "###).unwrap(), @r###" <ui version="4.0"> <class>MyType</class> <widget class="QWidget" name="widget"> <property name="sizePolicy"> <sizepolicy hsizetype="Preferred" vsizetype="Expanding"> </sizepolicy> </property> </widget> </ui> "###); } #[test] fn test_size_policy_with_stretch() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QWidget { sizePolicy.horizontalPolicy: QSizePolicy.Preferred sizePolicy.verticalPolicy: QSizePolicy.Expanding sizePolicy.horizontalStretch: 2 sizePolicy.verticalStretch: 1 } "###).unwrap(), @r###" <ui version="4.0"> <class>MyType</class> <widget class="QWidget" name="widget"> <property name="sizePolicy"> <sizepolicy hsizetype="Preferred" vsizetype="Expanding"> <horstretch>2</horstretch> <verstretch>1</verstretch> </sizepolicy> </property> </widget> </ui> "###); } #[test] fn test_unpaired_size_policy() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QWidget { sizePolicy.horizontalPolicy: QSizePolicy.Expanding } "###).unwrap_err(), @r###" error: both horizontal and vertical policies must be specified ┌─ <unknown>:3:5 │ 3 │ sizePolicy.horizontalPolicy: QSizePolicy.Expanding │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ "###); } #[test] fn test_stretch_without_size_policy() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QWidget { sizePolicy.horizontalStretch: 2 } "###).unwrap_err(), @r###" error: cannot specify stretch without horizontal and vertical policies ┌─ <unknown>:3:5 │ 3 │ sizePolicy.horizontalStretch: 2 │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ "###); } #[test] fn test_string_list_tr() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QTextBrowser { searchPaths: [qsTr("a"), qsTr("b")] } "###).unwrap(), @r###" <ui version="4.0"> <class>MyType</class> <widget class="QTextBrowser" name="textBrowser"> <property name="searchPaths"> <stringlist> <string>a</string> <string>b</string> </stringlist> </property> </widget> </ui> "###); } #[test] fn test_string_list_notr() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QTextBrowser { searchPaths: ["a", "b"] } "###).unwrap(), @r###" <ui version="4.0"> <class>MyType</class> <widget class="QTextBrowser" name="textBrowser"> <property name="searchPaths"> <stringlist notr="true"> <string>a</string> <string>b</string> </stringlist> </property> </widget> </ui> "###); } #[test] fn test_string_list_empty() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QTextBrowser { searchPaths: [] } "###).unwrap(), @r###" <ui version="4.0"> <class>MyType</class> <widget class="QTextBrowser" name="textBrowser"> <property name="searchPaths"> <stringlist notr="true"> </stringlist> </property> </widget> </ui> "###); } #[test] fn test_string_list_mixed() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QTextBrowser { searchPaths: [qsTr("a"), "b"] } "###).unwrap_err(), @r###" error: cannot mix bare and translatable strings ┌─ <unknown>:2:29 │ 2 │ QTextBrowser { searchPaths: [qsTr("a"), "b"] } │ ^^^^^^^^^^^^^^^^ "###); } #[test] fn test_string_list_constructor() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QTextBrowser { searchPaths: [windowTitle] } "###, ); let (_, ui_support_h) = common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap(); insta::assert_snapshot!(ui_support_h); } #[test] fn test_string_list_subscript() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QTextBrowser { id: root QPushButton { onClicked: { let a = root.searchPaths; a[0] = a[1]; // crash if a.size() < 2 root.searchPaths = a; } } } "###, ); let (_, ui_support_h) = common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap(); insta::assert_snapshot!(ui_support_h); } #[test] fn test_gadget_property_read_expr() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QLabel { text: fontEdit.currentFont.family QFontComboBox { id: fontEdit } } "###, ); let (_, ui_support_h) = common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap(); insta::assert_snapshot!(ui_support_h); } #[test] fn test_gadget_property_write_expr() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QLabel { font: { let f = fontEdit.currentFont; f.pointSize = sizeEdit.value; return f; } QFontComboBox { id: fontEdit } QSpinBox { id: sizeEdit } } "###, ); let (_, ui_support_h) = common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap(); insta::assert_snapshot!(ui_support_h); } #[test] fn test_gadget_property_write_to_rvalue() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QFontComboBox { onCurrentFontChanged: { currentFont.pointSize = 100; } } "###, ); insta::assert_snapshot!( common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap_err(), @r###" error: rvalue gadget property is not assignable ┌─ <unknown>:4:9 │ 4 │ currentFont.pointSize = 100; │ ^^^^^^^^^^^^^^^^^^^^^ "###); } #[test] fn test_gadget_property_write_to_rvalue_via_local() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QFontComboBox { onCurrentFontChanged: { let obj = this; obj.currentFont.pointSize = 100; } } "###, ); insta::assert_snapshot!( common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap_err(), @r###" error: rvalue gadget property is not assignable ┌─ <unknown>:5:9 │ 5 │ obj.currentFont.pointSize = 100; │ ^^^^^^^^^^^^^^^^^^^^^^^^^ "###); } #[test] fn test_gadget_binding() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QLabel { font.family: familyEdit.text font.pointSize: sizeEdit.value QLineEdit { id: familyEdit } QSpinBox { id: sizeEdit } } "###, ); let (_, ui_support_h) = common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap(); insta::assert_snapshot!(ui_support_h); } #[test] fn test_dynamic_gadget_property_sources() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QLabel { font.family: (check.checked ? family1Edit : family2Edit).text font.pointSize: (check.checked ? size1Edit : size2Edit).value QCheckBox { id: check } QLineEdit { id: family1Edit } QSpinBox { id: size1Edit } QLineEdit { id: family2Edit } QSpinBox { id: size2Edit } } "###, ); let (_, ui_support_h) = common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap(); insta::assert_snapshot!(ui_support_h); }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
tests/test_uigen_item_model.rs
Rust
pub mod common; #[test] fn test_string_list_as_combo_box_item() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QComboBox { model: ["foo", qsTr("bar")] } "###).unwrap(), @r###" <ui version="4.0"> <class>MyType</class> <widget class="QComboBox" name="comboBox"> <item> <property name="text"> <string notr="true">foo</string> </property> </item> <item> <property name="text"> <string>bar</string> </property> </item> </widget> </ui> "###); } #[test] fn test_empty_list_as_combo_box_item() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QComboBox { model: [] } "###).unwrap(), @r###" <ui version="4.0"> <class>MyType</class> <widget class="QComboBox" name="comboBox"> </widget> </ui> "###); } #[test] fn test_string_list_as_list_widget_item() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QListWidget { model: ["foo"] } "###).unwrap(), @r###" <ui version="4.0"> <class>MyType</class> <widget class="QListWidget" name="listWidget"> <item> <property name="text"> <string notr="true">foo</string> </property> </item> </widget> </ui> "###); } #[test] fn test_string_list_as_list_view_item() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QListView { model: ["foo"] } "###).unwrap_err(), @r###" error: not a writable property ┌─ <unknown>:2:13 │ 2 │ QListView { model: ["foo"] } │ ^^^^^^^^^^^^^^ "###); }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
tests/test_uigen_signal_callback.rs
Rust
use qmluic::uigen::DynamicBindingHandling; pub mod common; #[test] fn test_unknown_signal() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QWidget { onWhatever: ; } "###).unwrap_err(), @r###" error: unknown signal of class 'QWidget': whatever ┌─ <unknown>:3:5 │ 3 │ onWhatever: ; │ ^^^^^^^^^^^^^ "###); } #[test] fn test_invalid_binding_map_callback() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QDialog { onAccepted.whatever: ; } "###).unwrap_err(), @r###" error: signal callback cannot be a map ┌─ <unknown>:3:16 │ 3 │ onAccepted.whatever: ; │ ^^^^^^^^ "###); } #[test] fn test_callback_without_dynamic_binding() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QDialog { onAccepted: ; } "###).unwrap_err(), @r###" error: signal callback cannot be translated without dynamic binding ┌─ <unknown>:3:5 │ 3 │ onAccepted: ; │ ^^^^^^^^^^^^^ "###); } #[test] fn test_root_connection() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QDialog { onAccepted: ; } "###, ); let (_, ui_support_h) = common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap(); insta::assert_snapshot!(ui_support_h); } #[test] fn test_non_root_connection() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QDialog { id: root QDialogButtonBox { onAccepted: root.accept() } } "###, ); let (_, ui_support_h) = common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap(); insta::assert_snapshot!(ui_support_h); } #[test] fn test_default_argument_deduction() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QDialog { id: root // clicked(bool checked = false) QPushButton { onClicked: root.close() } } "###, ); let (_, ui_support_h) = common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap(); insta::assert_snapshot!(ui_support_h); } #[test] fn test_take_signal_parameter() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QDialog { QLineEdit { id: edit onCursorPositionChanged: function(oldPos: int, newPos: int) { label.text = "old: %1, new: %2".arg(oldPos).arg(newPos); } } QLabel { id: label } } "###, ); let (_, ui_support_h) = common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap(); insta::assert_snapshot!(ui_support_h); } #[test] fn test_too_many_callback_parameters() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QDialogButtonBox { onClicked: (a: QAbstractButton, b: int) => {} } "###, ); insta::assert_snapshot!( common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap_err(), @r###" error: too many callback arguments (expected: 0..1, actual: 2) ┌─ <unknown>:3:37 │ 3 │ onClicked: (a: QAbstractButton, b: int) => {} │ ^^^^^^ "###); } #[test] fn test_incompatible_callback_parameters() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QDialogButtonBox { onClicked: (a: QPushButton) => {} } "###, ); insta::assert_snapshot!( common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap_err(), @r###" error: incompatible callback arguments (expected: QAbstractButton*, actual: QPushButton*) ┌─ <unknown>:3:17 │ 3 │ onClicked: (a: QPushButton) => {} │ ^^^^^^^^^^^^^^ "###); } #[test] fn test_upcast_callback_parameters() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QDialogButtonBox { onClicked: (a: QWidget) => {} } "###, ); assert!(common::translate_doc(&doc, DynamicBindingHandling::Generate).is_ok()); } #[test] fn test_redefine_callback_parameters() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QLineEdit { onCursorPositionChanged: (pos: int, pos: int) => {} } "###, ); insta::assert_snapshot!( common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap_err(), @r###" error: redefinition of parameter: pos ┌─ <unknown>:3:41 │ 3 │ onCursorPositionChanged: (pos: int, pos: int) => {} │ ^^^ "###); } #[test] fn test_callback_parameter_without_type_annotation() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QLineEdit { onCursorPositionChanged: (pos) => {} } "###, ); insta::assert_snapshot!( common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap_err(), @r###" error: function parameter must have type annotation ┌─ <unknown>:3:31 │ 3 │ onCursorPositionChanged: (pos) => {} │ ^^^ "###); } #[test] fn test_callback_parameter_of_void_type() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QLineEdit { onCursorPositionChanged: (pos: void) => {} } "###, ); insta::assert_snapshot!( common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap_err(), @r###" error: operation 'function parameter' on unsupported type: void ┌─ <unknown>:3:31 │ 3 │ onCursorPositionChanged: (pos: void) => {} │ ^^^^^^^^^ "###); } #[test] fn test_method_call_bad_arg_count() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QDialog { id: root QDialogButtonBox { onAccepted: root.accept(0) } } "###).unwrap_err(), @r###" error: invalid argument: expects (), but got (integer) ┌─ <unknown>:4:36 │ 4 │ QDialogButtonBox { onAccepted: root.accept(0) } │ ^^^^^^^^^^^^^^ "###); } #[test] fn test_method_call_bad_arg_type() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QDialog { id: root QDialogButtonBox { onAccepted: root.done("whatever") } } "###).unwrap_err(), @r###" error: invalid argument: expects (int), but got (QString) ┌─ <unknown>:4:36 │ 4 │ QDialogButtonBox { onAccepted: root.done("whatever") } │ ^^^^^^^^^^^^^^^^^^^^^ "###); } #[test] fn test_implicit_this_method_call() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QDialog { QPushButton { onClicked: hide() } } "###, ); let (_, ui_support_h) = common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap(); insta::assert_snapshot!(ui_support_h); } #[test] fn test_explicit_this_method_call() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QDialog { QPushButton { onClicked: this.hide() } } "###, ); let (_, ui_support_h) = common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap(); insta::assert_snapshot!(ui_support_h); } #[test] fn test_property_assignment() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QDialog { id: root QPushButton { onClicked: root.windowTitle = "clicked" } } "###, ); let (_, ui_support_h) = common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap(); insta::assert_snapshot!(ui_support_h); } #[test] fn test_property_assignment_incompatible_type() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QDialog { id: root QPushButton { onClicked: root.windowTitle = 1 } } "###).unwrap_err(), @r###" error: operation '=' on incompatible types: QString and integer ┌─ <unknown>:4:30 │ 4 │ QPushButton { onClicked: root.windowTitle = 1 } │ ^^^^^^^^^^^^^^^^^^^^ "###); } #[test] fn test_property_assignment_readonly() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QDialog { id: root QPushButton { onClicked: root.width = 1 } } "###).unwrap_err(), @r###" error: not a writable property ┌─ <unknown>:4:30 │ 4 │ QPushButton { onClicked: root.width = 1 } │ ^^^^^^^^^^^^^^ "###); } #[test] fn test_multiple_statements() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QDialog { id: root QPushButton { onClicked: { root.showMaximized(); root.raise(); } } } "###, ); let (_, ui_support_h) = common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap(); insta::assert_snapshot!(ui_support_h); } #[test] fn test_let_object() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QPushButton { id: button onClicked: { let b = button; b.text = "clicked"; } } "###, ); let (_, ui_support_h) = common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap(); insta::assert_snapshot!(ui_support_h); } #[test] fn test_if_else_complete() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QCheckBox { text: if (checked) { "checked" } else { "unchecked" } } "###, ); let (_, ui_support_h) = common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap(); insta::assert_snapshot!(ui_support_h); } #[test] fn test_variant_cast() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QComboBox { onCurrentTextChanged: { windowTitle = currentData as QString; } } "###, ); let (_, ui_support_h) = common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap(); insta::assert_snapshot!(ui_support_h); }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
tests/test_uigen_widget.rs
Rust
use qmluic::uigen::DynamicBindingHandling; pub mod common; #[test] fn test_root_must_be_widget() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QVBoxLayout {} "###).unwrap_err(), @r###" error: class 'QVBoxLayout' is not a QWidget ┌─ <unknown>:2:1 │ 2 │ QVBoxLayout {} │ ^^^^^^^^^^^^^^ "###); } #[test] fn test_duplicated_id() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QWidget { QWidget { id: foo } QWidget { id: foo } } "###).unwrap_err(), @r###" error: duplicated object id: foo ┌─ <unknown>:4:19 │ 3 │ QWidget { id: foo } │ --- id is first defined here 4 │ QWidget { id: foo } │ ^^^ duplicated id is defined here "###); } #[test] fn test_reserved_word_workaround() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QPushButton { default_: true } "###).unwrap(), @r###" <ui version="4.0"> <class>MyType</class> <widget class="QPushButton" name="pushButton"> <property name="default"> <bool>true</bool> </property> </widget> </ui> "###); } #[test] fn test_width_is_readonly() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QWidget { width: 100 } "###).unwrap_err(), @r###" error: not a writable property ┌─ <unknown>:2:11 │ 2 │ QWidget { width: 100 } │ ^^^^^^^^^^ "###); } #[test] fn test_dynamic_width_is_readonly() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QWidget { width: spinBox.value QSpinBox { id: spinBox } } "###, ); insta::assert_snapshot!( common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap_err(), @r###" error: not a writable property ┌─ <unknown>:3:5 │ 3 │ width: spinBox.value │ ^^^^^^^^^^^^^^^^^^^^ "###); } #[test] fn test_unobservable_property() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QWidget { id: root QLabel { text: "width: %1".arg(root.width) } } "###, ); insta::assert_snapshot!( common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap_err(), @r###" error: unobservable property: width ┌─ <unknown>:4:37 │ 4 │ QLabel { text: "width: %1".arg(root.width) } │ ^^^^ "###); } #[test] fn test_incompatible_return_type() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QWidget { windowTitle: { switch (edit.text) { case "hello": return "world"; } } QLineEdit { id: edit } } "###, ); insta::assert_snapshot!( common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap_err(), @r###" error: cannot deduce return type from 'QString' and 'void' ┌─ <unknown>:8:6 │ 6 │ return "world"; │ ------- type: QString 7 │ } 8 │ } │ ^ type: void "###); } #[test] fn test_assign_double() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QDoubleSpinBox { value: 1.0 } "###).unwrap(), @r###" <ui version="4.0"> <class>MyType</class> <widget class="QDoubleSpinBox" name="doubleSpinBox"> <property name="value"> <number>1</number> </property> </widget> </ui> "###); } #[test] fn test_assign_qreal() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QDial { notchTarget: 3.7 } "###).unwrap(), @r###" <ui version="4.0"> <class>MyType</class> <widget class="QDial" name="dial"> <property name="notchTarget"> <number>3.7</number> </property> </widget> </ui> "###); } #[test] fn test_assign_float_to_int() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QSpinBox { value: 1.0 } "###).unwrap_err(), @r###" error: expression type mismatch (expected: int, actual: double) ┌─ <unknown>:2:19 │ 2 │ QSpinBox { value: 1.0 } │ ^^^ "###); } #[test] fn test_object_property_binding() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QWidget { QCheckBox { id: source } QWidget { visible: source.checked } } "###, ); let (ui_xml, ui_support_h) = common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap(); insta::assert_snapshot!(ui_xml); insta::assert_snapshot!(ui_support_h); } #[test] fn test_object_property_binding_to_root() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QDialog { windowTitle: edit.text QLineEdit { id: edit } } "###, ); let (ui_xml, ui_support_h) = common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap(); insta::assert_snapshot!(ui_xml); insta::assert_snapshot!(ui_support_h); } #[test] fn test_object_property_binding_unsupported() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QWidget { QCheckBox { id: source } QWidget { visible: source.checked } } "###).unwrap_err(), @r###" error: unsupported dynamic binding ┌─ <unknown>:4:25 │ 4 │ QWidget { visible: source.checked } │ ^^^^^^^^^^^^^^ "###); } #[test] fn test_implicit_this_property_binding() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QCheckBox { checked: windowTitle === "" } "###, ); let (_, ui_support_h) = common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap(); insta::assert_snapshot!(ui_support_h); } #[test] fn test_explicit_this_property_binding() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QCheckBox { checked: this.windowTitle === "" } "###, ); let (_, ui_support_h) = common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap(); insta::assert_snapshot!(ui_support_h); } #[test] fn test_indirect_property_binding() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QWidget { QCheckBox { id: source } QWidget { visible: { let w = source; w.checked } } } "###, ); let (_, ui_support_h) = common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap(); insta::assert_snapshot!(ui_support_h); } #[test] fn test_dynamic_property_source() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QWidget { windowTitle: (source.checked ? edit1 : edit2).text QCheckBox { id: source } QLineEdit { id: edit1 } QLineEdit { id: edit2 } } "###, ); let (_, ui_support_h) = common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap(); insta::assert_snapshot!(ui_support_h); } #[test] fn test_dynamic_binding_type_mismatch() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QWidget { windowTitle: source.checked QCheckBox { id: source } } "###, ); insta::assert_snapshot!( common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap_err(), @r###" error: expression type mismatch (expected: QString, actual: bool) ┌─ <unknown>:3:19 │ 3 │ windowTitle: source.checked │ ^^^^^^^^^^^^^^ "###); } #[test] fn test_omit_dynamic_binding() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QWidget { QCheckBox { id: source } QWidget { visible: source.checked } } "###, ); let (ui_xml, _) = common::translate_doc(&doc, DynamicBindingHandling::Omit).unwrap(); insta::assert_snapshot!(ui_xml, @r###" <ui version="4.0"> <class>MyType</class> <widget class="QWidget" name="widget1"> <widget class="QCheckBox" name="source"> </widget> <widget class="QWidget" name="widget"> </widget> </widget> </ui> "###); } #[test] fn test_deduplicate_dynamic_binding_senders() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QDialog { windowTitle: combo.currentIndex === 0 ? "-" : combo.currentText QComboBox { id: combo } } "###, ); let (_, ui_support_h) = common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap(); insta::assert_snapshot!(ui_support_h); } #[test] fn test_deduplicate_dynamic_binding_connections() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QDialog { windowTitle: edit.text + edit.text QLineEdit { id: edit } } "###, ); let (_, ui_support_h) = common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap(); insta::assert_snapshot!(ui_support_h); } #[test] fn test_deduplicate_dynamic_binding_sender_receiver() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QLineEdit { id: edit enabled: edit.text === "" } "###, ); let (_, ui_support_h) = common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap(); insta::assert_snapshot!(ui_support_h); } #[test] fn test_dynamic_binding_with_static_cast() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QWidget { QDoubleSpinBox { id: edit } QComboBox { currentIndex: edit.value as int } } "###, ); let (_, ui_support_h) = common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap(); insta::assert_snapshot!(ui_support_h); } #[test] fn test_integer_arithmetic_type_mismatch() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QWidget { windowTitle: "sum: %1".arg(edit1.value + edit2.value) QSpinBox { id: edit1 } QDoubleSpinBox { id: edit2 } } "###).unwrap_err(), @r###" error: operation '+' on incompatible types: int and double ┌─ <unknown>:3:33 │ 3 │ windowTitle: "sum: %1".arg(edit1.value + edit2.value) │ ----------- ----------- type: double │ │ │ type: int │ = use (expr as double) or (expr as int) for numeric cast "###); } #[test] fn test_object_comparison_type_mismatch() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QWidget { visible: combo !== edit QComboBox { id: combo } QLineEdit { id: edit } } "###).unwrap_err(), @r###" error: operation '!=' on incompatible types: QComboBox* and QLineEdit* ┌─ <unknown>:3:15 │ 3 │ visible: combo !== edit │ ----- ---- type: QLineEdit* │ │ │ type: QComboBox* │ = use (expr as QWidget) to upcast to base class "###); } #[test] fn test_unsupported_binary_expression() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QWidget { windowTitle: "foo" - "bar" } "###).unwrap_err(), @r###" error: operation '-' on unsupported type: string ┌─ <unknown>:3:19 │ 3 │ windowTitle: "foo" - "bar" │ ----- ----- type: string │ │ │ type: string "###); } #[test] fn test_unsupported_shift_expression() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QWidget { windowTitle: "foo" << 1 } "###).unwrap_err(), @r###" error: operation '<<' on unsupported types: string and integer ┌─ <unknown>:3:19 │ 3 │ windowTitle: "foo" << 1 │ ----- - type: integer │ │ │ type: string "###); } #[test] fn test_ternary_expression_type_mismatch() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QWidget { windowTitle: source.checked ? 1 : "whatever" QCheckBox { id: source } } "###).unwrap_err(), @r###" error: operation 'ternary' on incompatible types: integer and QString ┌─ <unknown>:3:36 │ 3 │ windowTitle: source.checked ? 1 : "whatever" │ - ---------- type: QString │ │ │ type: integer "###); } #[test] fn test_ternary_condition_string() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QLabel { text: windowTitle ? windowTitle : "untitled" } "###).unwrap_err(), @r###" error: condition must be of bool type, but got: QString ┌─ <unknown>:3:11 │ 3 │ text: windowTitle ? windowTitle : "untitled" │ ^^^^^^^^^^^ type: QString │ = use (!expr.isEmpty()) to test empty string "###); } #[test] fn test_if_condition_int() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QSpinBox { onEditingFinished: { if (value) {} } } "###).unwrap_err(), @r###" error: condition must be of bool type, but got: int ┌─ <unknown>:4:12 │ 4 │ if (value) {} │ ^^^^^^^ type: int │ = use (expr != 0) to test zero "###); } #[test] fn test_if_condition_flag() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QLabel { onLinkActivated: { if (alignment & Qt.AlignLeft) {} } } "###).unwrap_err(), @r###" error: condition must be of bool type, but got: Qt::Alignment ┌─ <unknown>:4:12 │ 4 │ if (alignment & Qt.AlignLeft) {} │ ^^^^^^^^^^^^^^^^^^^^^^^^^^ type: Qt::Alignment │ = use ((expr as int) != 0) to test flag "###); } #[test] fn test_if_condition_pointer_negated() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QLabel { id: obj onLinkActivated: { if (!obj) return; } } "###).unwrap_err(), @r###" error: operation '!' on unsupported type: QLabel* ┌─ <unknown>:5:14 │ 5 │ if (!obj) │ --- type: QLabel* │ = use (expr == null) to test null pointer "###); } #[test] fn test_console_log() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QPushButton { id: button onClicked: { console.log(); console.debug("foo"); console.info(1); console.warn("bar", 2); console.error("baz", 3.0, button); } } "###, ); let (_, ui_support_h) = common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap(); insta::assert_snapshot!(ui_support_h); } #[test] fn test_min_max() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QLabel { QComboBox { id: combo; currentIndex: Math.max(spin.value, 0) } QSpinBox { id: spin } text: Math.min(combo.currentText, "foo") } "###, ); let (_, ui_support_h) = common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap(); insta::assert_snapshot!(ui_support_h); } #[test] fn test_qstring_arg() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QWidget { QLabel { text: "dynamic %1".arg(combo.currentIndex) } QLabel { text: "static %1".arg(1) } QComboBox { id: combo } } "###, ); let (_, ui_support_h) = common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap(); insta::assert_snapshot!(ui_support_h); } #[test] fn test_nullable_property_sources() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QLabel { text: { let w = check.checked ? edit : null; w !== null ? w.text : "" } QCheckBox { id: check } QLineEdit { id: edit } } "###, ); let (_, ui_support_h) = common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap(); insta::assert_snapshot!(ui_support_h); } #[test] fn test_unique_binding_method_name() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QWidget { id: main windowTitle: edit1.text // "main" + "WindowTitle" QGroupBox { id: mainWindow title: edit2.text // "mainWindow" + "Title" } QLineEdit { id: edit1 } QLineEdit { id: edit2 } } "###, ); let (_, ui_support_h) = common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap(); insta::assert_snapshot!(ui_support_h); } #[test] fn test_dynamic_tab_widget_attached() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QTabWidget { QWidget { id: tab QTabWidget.title: tab.windowTitle } } "###, ); insta::assert_snapshot!( common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap_err(), @r###" error: unused or unsupported dynamic binding to attached property ┌─ <unknown>:5:9 │ 5 │ QTabWidget.title: tab.windowTitle │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ "###); } #[test] fn test_static_actions_list() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QMenu { actions: [act, menu.menuAction(), sep] QAction { id: act } QMenu { id: menu } QAction { id: sep; separator: true } } "###).unwrap(), @r###" <ui version="4.0"> <class>MyType</class> <widget class="QMenu" name="menu1"> <addaction name="act"/> <addaction name="menu"/> <addaction name="separator"/> <action name="act"> </action> <widget class="QMenu" name="menu"> </widget> </widget> </ui> "###); } #[test] fn test_actions_list_incompatible_type() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QMenu { actions: [ act1, act2, menu, ] QAction { id: act1 } QAction { id: act2 } QMenu { id: menu } } "###).unwrap_err(), @r###" error: incompatible array element types at index 2: QAction* and QMenu* ┌─ <unknown>:5:9 │ 5 │ act2, │ ---- type: QAction* 6 │ menu, │ ---- type: QMenu* │ = call .menuAction() to obtain QAction* associated with menu "###); } #[test] fn test_action_separator_false() { insta::assert_snapshot!(common::translate_str(r###" import qmluic.QtWidgets QMenu { QAction { separator: false } } "###).unwrap(), @r###" <ui version="4.0"> <class>MyType</class> <widget class="QMenu" name="menu"> <addaction name="action"/> <action name="action"> </action> </widget> </ui> "###); } #[test] fn test_action_seaparator_dynamic() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QWidget { QCheckBox { id: check } QAction { separator: check.checked } } "###, ); let (ui_xml, ui_support_h) = common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap(); insta::assert_snapshot!(ui_xml, @r###" <ui version="4.0"> <class>MyType</class> <widget class="QWidget" name="widget"> <addaction name="action"/> <widget class="QCheckBox" name="check"> </widget> <action name="action"> </action> </widget> </ui> "###); insta::assert_snapshot!(ui_support_h); } #[test] fn test_action_seaparator_with_other_properties() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QWidget { QAction { separator: true; text: "whatever" } } "###, ); let (ui_xml, ui_support_h) = common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap(); insta::assert_snapshot!(ui_xml, @r###" <ui version="4.0"> <class>MyType</class> <widget class="QWidget" name="widget"> <addaction name="action"/> <action name="action"> <property name="text"> <string notr="true">whatever</string> </property> </action> </widget> </ui> "###); insta::assert_snapshot!(ui_support_h); } #[test] fn test_action_seaparator_with_callback() { let doc = common::parse_doc( r###" import qmluic.QtWidgets QWidget { QAction { separator: true; onHovered: {} } } "###, ); let (ui_xml, ui_support_h) = common::translate_doc(&doc, DynamicBindingHandling::Generate).unwrap(); insta::assert_snapshot!(ui_xml, @r###" <ui version="4.0"> <class>MyType</class> <widget class="QWidget" name="widget"> <addaction name="action"/> <action name="action"> </action> </widget> </ui> "###); insta::assert_snapshot!(ui_support_h); }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
uiviewer/main.cpp
C++
#include <QApplication> #include <QBuffer> #include <QCommandLineParser> #include <QFile> #include <QLoggingCategory> #include <QUiLoader> #include <QWidget> #include <QtDebug> #include <memory> #include "pipeserver.h" #include "uiviewerdialog.h" namespace { std::unique_ptr<QWidget> loadUiFile(QUiLoader &loader, const QString &fileName) { QFile file(fileName); if (!file.open(QFile::ReadOnly)) { qWarning() << "failed to open .ui file:" << file.fileName(); return {}; } return std::unique_ptr<QWidget>(loader.load(&file)); } std::unique_ptr<QWidget> loadUiData(QUiLoader &loader, const QByteArray &data) { auto tmp = data; QBuffer buf(&tmp); buf.open(QIODevice::ReadOnly); return std::unique_ptr<QWidget>(loader.load(&buf)); } } int main(int argc, char *argv[]) { QApplication app(argc, argv); app.setApplicationDisplayName(QApplication::translate("main", "UI Viewer")); QCommandLineParser parser; parser.addHelpOption(); parser.addOption({ "pipe", QApplication::translate("main", "update ui via stdio") }); parser.addPositionalArgument("file", QApplication::translate("main", ".ui file to load"), "[file]"); parser.process(app); #ifdef QT_NO_DEBUG QLoggingCategory::setFilterRules(QStringLiteral("*.debug=false\n*.info=false")); #endif const auto args = parser.positionalArguments(); if (args.size() > 1) return 1; UiViewerDialog dlg; QUiLoader loader; if (!args.isEmpty()) { auto w = loadUiFile(loader, args.first()); if (w) { dlg.setContentWidget(std::move(w)); } } PipeServer pipeServer; if (parser.isSet("pipe")) { QObject::connect(&pipeServer, &PipeServer::dataReceived, &dlg, [&loader, &dlg](const QByteArray &data) { auto w = loadUiData(loader, data); if (w) { dlg.setContentWidget(std::move(w)); } }); QObject::connect(&pipeServer, &PipeServer::finished, &dlg, [&dlg]() { dlg.setClosable(true); }); QObject::connect(&app, &QApplication::aboutToQuit, &pipeServer, [&pipeServer]() { qInfo() << "waiting for pipe thread shutdown"; pipeServer.wait(); }); pipeServer.start(); dlg.setClosable(false); } dlg.show(); return app.exec(); }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
uiviewer/pipeserver.cpp
C++
#include <QFile> #include <QtDebug> #include <cstdint> #include "pipeserver.h" PipeServer::PipeServer(QObject *parent) : QThread(parent) { } void PipeServer::run() { // AFAIK, QFile basically implements blocking interface. QFile fin, fout; if (!fin.open(0, QIODevice::ReadOnly | QIODevice::Unbuffered)) { qWarning() << "failed to open stdin"; return; } if (!fout.open(1, QIODevice::WriteOnly | QIODevice::Unbuffered)) { qWarning() << "failed to open stdout"; return; } union { char d[4]; int32_t n; } msg; // teach that the viewer process is ready msg.n = 0; fout.write(msg.d, sizeof(msg)); // --> {size, payload} // <-- {size} (denoting that the data is processed) for (;;) { if (fin.read(msg.d, sizeof(msg)) != sizeof(msg)) return; // EOF int32_t payloadSize = msg.n; if (payloadSize < 0) { qWarning() << "invalid payload size:" << payloadSize; continue; } const auto data = fin.read(payloadSize); if (data.size() != payloadSize) return; // EOF msg.n = data.size(); fout.write(msg.d, sizeof(msg)); qInfo() << "received payload of" << data.size() << "bytes"; emit dataReceived(data); } }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
uiviewer/pipeserver.h
C/C++ Header
#pragma once #include <QByteArray> #include <QThread> /// Thread to receive data via stdio. /// /// This is blocking thread since stdin can't be polled via QFile. The thread will /// terminate when stdin is closed by peer. class PipeServer : public QThread { Q_OBJECT public: explicit PipeServer(QObject *parent = nullptr); protected: void run() override; signals: void dataReceived(const QByteArray &data); };
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
uiviewer/uiviewerdialog.cpp
C++
#include <QCloseEvent> #include <QEvent> #include <QKeyEvent> #include <QKeySequence> #include <QMessageBox> #include <QMetaObject> #include "uiviewerdialog.h" #include "ui_uiviewerdialog.h" UiViewerDialog::UiViewerDialog(QWidget *parent) : QDialog(parent), ui_(std::make_unique<Ui::UiViewerDialog>()) { ui_->setupUi(this); connect(ui_->separateWindowCheck, &QCheckBox::clicked, this, &UiViewerDialog::reparentContentWidget); } UiViewerDialog::~UiViewerDialog() = default; void UiViewerDialog::closeEvent(QCloseEvent *event) { if (closable_) return; QMessageBox::information(this, {}, tr("Cannot close viewer while pipe server is running.\n\n" "Terminate the preview command instead.")); event->ignore(); } void UiViewerDialog::keyPressEvent(QKeyEvent *event) { if (event->matches(QKeySequence::Cancel)) { event->ignore(); return; // do not close by escape key } QDialog::keyPressEvent(event); } void UiViewerDialog::setClosable(bool closable) { closable_ = closable; } void UiViewerDialog::setContentWidget(std::unique_ptr<QWidget> widget) { contentWidget_ = std::move(widget); contentWidget_->installEventFilter(this); contentWindowFlags_ = contentWidget_->windowFlags(); // backup setWindowTitle(contentWidget_->windowTitle().isEmpty() ? tr("UI Viewer") : tr("%1 - UI Viewer").arg(contentWidget_->windowTitle())); reparentContentWidget(); } bool UiViewerDialog::eventFilter(QObject *watched, QEvent *event) { if (watched != contentWidget_.get()) return QDialog::eventFilter(watched, event); switch (event->type()) { case QEvent::Hide: if (event->spontaneous()) return false; // move widget back to content area on close ui_->separateWindowCheck->setChecked(false); QMetaObject::invokeMethod(this, &UiViewerDialog::reparentContentWidget, Qt::QueuedConnection); return false; default: return false; } } void UiViewerDialog::reparentContentWidget() { if (!contentWidget_) return; contentWidget_->removeEventFilter(this); // widget will temporarily get hidden if (ui_->separateWindowCheck->isChecked()) { ui_->contentLayout->removeWidget(contentWidget_.get()); contentWidget_->setWindowFlags(contentWindowFlags_ | Qt::Window); } else { contentWidget_->setWindowFlags(contentWindowFlags_ & ~Qt::Window); ui_->contentLayout->addWidget(contentWidget_.get()); } contentWidget_->show(); contentWidget_->installEventFilter(this); }
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
uiviewer/uiviewerdialog.h
C/C++ Header
#ifndef UIVIEWERDIALOG_H #define UIVIEWERDIALOG_H #include <QDialog> #include <QWidget> #include <memory> namespace Ui { class UiViewerDialog; } class UiViewerDialog : public QDialog { Q_OBJECT public: explicit UiViewerDialog(QWidget *parent = nullptr); ~UiViewerDialog() override; void setClosable(bool closable); void setContentWidget(std::unique_ptr<QWidget> widget); protected: void closeEvent(QCloseEvent *event) override; void keyPressEvent(QKeyEvent *event) override; bool eventFilter(QObject *watched, QEvent *event) override; private slots: void reparentContentWidget(); private: std::unique_ptr<Ui::UiViewerDialog> ui_; std::unique_ptr<QWidget> contentWidget_; Qt::WindowFlags contentWindowFlags_; bool closable_ = true; }; #endif // UIVIEWERDIALOG_H
yuja/qmluic
9
QML -> QtWidgets UI/C++ transpiler
Rust
yuja
Yuya Nishihara
bindings/node/binding.cc
C++
#include "tree_sitter/parser.h" #include <node.h> #include "nan.h" using namespace v8; extern "C" TSLanguage * tree_sitter_sixtyfps(); namespace { NAN_METHOD(New) {} void Init(Local<Object> exports, Local<Object> module) { Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New); tpl->SetClassName(Nan::New("Language").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Local<Function> constructor = Nan::GetFunction(tpl).ToLocalChecked(); Local<Object> instance = constructor->NewInstance(Nan::GetCurrentContext()).ToLocalChecked(); Nan::SetInternalFieldPointer(instance, 0, tree_sitter_sixtyfps()); Nan::Set(instance, Nan::New("name").ToLocalChecked(), Nan::New("sixtyfps").ToLocalChecked()); Nan::Set(module, Nan::New("exports").ToLocalChecked(), instance); } NODE_MODULE(tree_sitter_sixtyfps_binding, Init) } // namespace
yuja/tree-sitter-sixtyfps
0
SixtyFPS grammar for the tree-sitter parsing library
JavaScript
yuja
Yuya Nishihara
bindings/node/index.js
JavaScript
try { module.exports = require("../../build/Release/tree_sitter_sixtyfps_binding"); } catch (error1) { if (error1.code !== 'MODULE_NOT_FOUND') { throw error1; } try { module.exports = require("../../build/Debug/tree_sitter_sixtyfps_binding"); } catch (error2) { if (error2.code !== 'MODULE_NOT_FOUND') { throw error2; } throw error1 } } try { module.exports.nodeTypeInfo = require("../../src/node-types.json"); } catch (_) {}
yuja/tree-sitter-sixtyfps
0
SixtyFPS grammar for the tree-sitter parsing library
JavaScript
yuja
Yuya Nishihara
bindings/rust/build.rs
Rust
fn main() { let src_dir = std::path::Path::new("src"); let mut c_config = cc::Build::new(); c_config.include(&src_dir); c_config .flag_if_supported("-Wno-unused-parameter") .flag_if_supported("-Wno-unused-but-set-variable") .flag_if_supported("-Wno-trigraphs"); let parser_path = src_dir.join("parser.c"); c_config.file(&parser_path); println!("cargo:rerun-if-changed={}", parser_path.to_str().unwrap()); let scanner_path = src_dir.join("scanner.c"); c_config.file(&scanner_path); println!("cargo:rerun-if-changed={}", scanner_path.to_str().unwrap()); c_config.compile("parser-scanner"); }
yuja/tree-sitter-sixtyfps
0
SixtyFPS grammar for the tree-sitter parsing library
JavaScript
yuja
Yuya Nishihara
bindings/rust/lib.rs
Rust
//! This crate provides SixtyFPS language support for the [tree-sitter][] parsing library. //! //! Typically, you will use the [language][language func] function to add this language to a //! tree-sitter [Parser][], and then use the parser to parse some code: //! //! ``` //! let code = ""; //! let mut parser = tree_sitter::Parser::new(); //! parser.set_language(tree_sitter_sixtyfps::language()).expect("Error loading SixtyFPS grammar"); //! let tree = parser.parse(code, None).unwrap(); //! ``` //! //! [Language]: https://docs.rs/tree-sitter/*/tree_sitter/struct.Language.html //! [language func]: fn.language.html //! [Parser]: https://docs.rs/tree-sitter/*/tree_sitter/struct.Parser.html //! [tree-sitter]: https://tree-sitter.github.io/ use tree_sitter::Language; extern "C" { fn tree_sitter_sixtyfps() -> Language; } /// Get the tree-sitter [Language][] for this grammar. /// /// [Language]: https://docs.rs/tree-sitter/*/tree_sitter/struct.Language.html pub fn language() -> Language { unsafe { tree_sitter_sixtyfps() } } /// The content of the [`node-types.json`][] file for this grammar. /// /// [`node-types.json`]: https://tree-sitter.github.io/tree-sitter/using-parsers#static-node-types pub const NODE_TYPES: &'static str = include_str!("../../src/node-types.json"); // Uncomment these to include any queries that this grammar contains // pub const HIGHLIGHTS_QUERY: &'static str = include_str!("../../queries/highlights.scm"); // pub const INJECTIONS_QUERY: &'static str = include_str!("../../queries/injections.scm"); // pub const LOCALS_QUERY: &'static str = include_str!("../../queries/locals.scm"); // pub const TAGS_QUERY: &'static str = include_str!("../../queries/tags.scm"); #[cfg(test)] mod tests { #[test] fn test_can_load_grammar() { let mut parser = tree_sitter::Parser::new(); parser .set_language(super::language()) .expect("Error loading SixtyFPS language"); } }
yuja/tree-sitter-sixtyfps
0
SixtyFPS grammar for the tree-sitter parsing library
JavaScript
yuja
Yuya Nishihara
contrib/lsp-sixtyfps.el
Emacs Lisp
;;; lsp-sityfps.el --- LSP client for SixtyFPS UI -*- lexical-binding: t; -*- ;; Author: Yuya Nishihara <yuya@tcha.org> ;; Package-Requires: ((emacs "26.1") (lsp-mode "8.0")) ;;; Code: (require 'lsp-mode) (add-to-list 'lsp-language-id-configuration '(sixtyfps-mode . "sixtyfps")) (lsp-register-client (make-lsp-client :new-connection (lsp-stdio-connection "sixtyfps-lsp") :activation-fn (lsp-activate-on "sixtyfps") :server-id 'sixtyfps)) (provide 'lsp-sixtyfps) ;;; lsp-sixtyfps.el ends here
yuja/tree-sitter-sixtyfps
0
SixtyFPS grammar for the tree-sitter parsing library
JavaScript
yuja
Yuya Nishihara
contrib/sixtyfps-mode.el
Emacs Lisp
;;; sityfps-mode.el --- Major mode for editing SixtyFPS UI -*- lexical-binding: t; -*- ;; Author: Yuya Nishihara <yuya@tcha.org> ;; Package-Requires: ((emacs "26.1") (tree-sitter "0.16.1") (tree-sitter-indent "0.3")) ;;; Code: (require 'tree-sitter) (require 'tree-sitter-hl) (require 'tree-sitter-indent) (defconst sixtyfps-mode--tree-sitter-patterns [ ;; Comments (line_comment) @comment (block_comment) @comment ;; Keywords ["animate" "as" "callback" "else" "export" "for" "from" "global" "if" "import" "in" "out" "property" "return" "states" "struct" "transitions" "when"] @keyword ;; Tokens ["," "." ":" ";"] @punctuation.delimiter ["*" "+" "-" "/" "!" "!=" "<" "<=" "==" ">" ">=" "&&" "||" "*=" "+=" "-=" "/=" ":=" "=" "->" "<=>" "=>"] @punctuation.operator ["(" ")" "[" "]" "{" "}"] @punctuation.bracket ;; Literals [(self) (parent) (root)] @variable.builtin [(string_fragment) (escape_sequence) "\""] @string (template_substitution ["\\{" "}"] @string) (number_literal) @number (color_literal) @string.special (bool_literal) @constant.builtin ;; At keywords (children_placeholder) @variable.builtin (at_image_url) @function.builtin (at_linear_gradient) @function.builtin ;; Functions (callback_declaration name: (identifier) @function) (callback_declaration binding: (two_way_binding name: (identifier) @function)) (callback_connection name: (identifier) @function) (callback_connection_parameters (identifier) @variable.parameter) (function_call_expression function: (qualified_name (identifier) @function.call \.)) ;; Properties (property_declaration ["<" ">"] @punctuation.bracket) (property_declaration name: (identifier) @property.definition) (property_declaration [(binding name: (identifier) @property.definition) (two_way_binding name: (identifier) @property.definition)]) (binding name: (identifier) @property) (qualified_binding name: (qualified_name (identifier) @property)) (two_way_binding name: (identifier) @property) (qualified_property_names (qualified_name (identifier) @property)) (state id: (identifier) @variable) (transition id: (identifier) @variable) ;; Types and variable identifiers (import_export_identifier (identifier) @type) (component id: (identifier) @type) (global_component id: (identifier) @type) (sub_element id: (identifier) @variable) (repeated_element [model_data: (identifier) @variable index: (identifier) @variable]) (object_member name: (identifier) @property) (struct_declaration name: (identifier) @type) (object_type_member name: (identifier) @property.definition) (qualified_type_name (identifier) @type) ((identifier) @type (.match? @type "^[A-Z]")) ; assume uppercase names are types ;(identifier) @variable ]) (defcustom sixtyfps-indent-offset 4 "Indent offset for SixtyFPS major mode." :type 'integer :group 'sixtyfps) ;; Empty line won't be indented properly, but let's start with structurally correct rule. ;; https://codeberg.org/FelipeLema/tree-sitter-indent.el/issues/8 (defconst sixtyfps-mode--indent-scopes '((indent-all ;; these nodes are always indented . ()) (indent-rest ;; if parent node is one of this and node is not first -> indent . (self_assignment conditional_expression binary_expression)) (indent-body ;; if parent node is one of this and current node is in middle -> indent . (import_export_identifier_list element_content states transitions property_animations property_bindings property_changes code_block array array_type object_literal object_type)) (paren-indent ;; if parent node is one of these -> indent to paren opener . (callback_connection_parameters callback_declaration_parameters arguments at_linear_gradient_arguments parenthesized_expression)) (align-char-to ;; chaining char -> node types we move parentwise to find the first chaining char . ()) (aligned-siblings ;; siblings (nodes with same parent) should be aligned to the first child . ()) (multi-line-text ;; if node is one of this, then don't modify the indent ;; this is basically a peaceful way out by saying "this looks like something ;; that cannot be indented using AST, so best I leave it as-is" . ()) (outdent ;; these nodes always outdent (1 shift in opposite direction) . ()))) (defvar sixtyfps-mode-map (let ((map (make-sparse-keymap))) map) "Keymap for SixtyFPS major mode.") (defvar sixtyfps-mode-syntax-table (let ((table (make-syntax-table))) table)) ;;;###autoload (define-derived-mode sixtyfps-mode prog-mode "SixtyFPS" "Major mode for SixtyFPS UI. \\{sixtyfps-mode-map}" :group 'sixtyfps :syntax-table sixtyfps-mode-syntax-table ; copied from csharp-tree-sitter.el ; https://github.com/ubolonton/emacs-tree-sitter/issues/84 (unless font-lock-defaults (setq font-lock-defaults '(nil))) (setq-local tree-sitter-hl-default-patterns sixtyfps-mode--tree-sitter-patterns) (setq-local indent-line-function #'tree-sitter-indent-line) (setq-local tree-sitter-indent-offset sixtyfps-indent-offset) (setq-local tree-sitter-indent-current-scopes sixtyfps-mode--indent-scopes) (tree-sitter-hl-mode)) (add-to-list 'tree-sitter-major-mode-language-alist '(sixtyfps-mode . sixtyfps)) ;;;###autoload (add-to-list 'auto-mode-alist '("\\.60\\'" . sixtyfps-mode)) (add-to-list 'auto-mode-alist '("\\.slint\\'" . sixtyfps-mode)) (provide 'sixtyfps-mode) ;;; sixtyfps-mode.el ends here
yuja/tree-sitter-sixtyfps
0
SixtyFPS grammar for the tree-sitter parsing library
JavaScript
yuja
Yuya Nishihara
grammar.js
JavaScript
// Implemented based on // https://github.com/slint-ui/slint/ // docs/langref.md // internal/compiler/{lexer.rs,parser.rs,parser/*.rs} // {expression_tree.rs,object_tree.rs} // 136f2686b4e33241da8e7ab97bf27712a8d5bf56 module.exports = grammar({ name: 'sixtyfps', externals: $ => [ $.block_comment, ], extras: $ => [ /\p{space}/, $.line_comment, $.block_comment, ], supertypes: $ => [ $._expression, ], inline: $ => [ $._component, $._element_content_member, $._statement, $._at_keyword, $._type, $._literal, $._identifier, ], precedences: $ => [ ['unary', 'mul', 'add', 'equality', 'logical', 'ternary'], [$.object_literal, $.code_block], ], word: $ => $.identifier, rules: { document: $ => repeat(choice( $._component, $.exports_list, $.import_specifier, $.struct_declaration, )), // TODO: consolidate export/import node names exports_list: $ => seq( 'export', choice( field('names', $.import_export_identifier_list), $._component, $.struct_declaration, ), ), import_specifier: $ => seq( 'import', optional(seq( field('names', $.import_export_identifier_list), 'from', )), field('source', $.string_literal), ';', ), import_export_identifier_list: $ => seq( '{', sep($.import_export_identifier, ','), '}', ), import_export_identifier: $ => seq( field('name', $.identifier), optional(seq( 'as', field('alias', $.identifier), )), ), _component: $ => choice( $.component, $.global_component, ), component: $ => seq( field('id', $.identifier), ':=', field('root_element', $.element), ), global_component: $ => seq( 'global', field('id', $.identifier), ':=', field('root_element', $.element_content), ), sub_element: $ => seq( optional(seq( field('id', $.identifier), ':=', )), $.element, ), repeated_element: $ => seq( 'for', field('model_data', optional($.identifier)), optional(seq( '[', field('index', $.identifier), ']', )), 'in', field('model', $._expression), ':', $.sub_element, ), conditional_element: $ => seq( 'if', field('condition', $._expression), ':', $.sub_element, ), element: $ => seq( field('base_type', alias($.qualified_name, $.qualified_type_name)), $.element_content, ), element_content: $ => seq( '{', repeat($._element_content_member), '}', ), _element_content_member: $ => choice( $.property_declaration, $.binding, $.callback_declaration, $.callback_connection, $.sub_element, $.repeated_element, $.conditional_element, $.property_animation, $.two_way_binding, $.states, $.transitions, $.children_placeholder, ), property_declaration: $ => seq( 'property', choice( seq( '<', field('type', $._type), '>', // TODO: better structure choice( seq( field('name', $.identifier), ';', ), field('binding', $.binding), field('binding', $.two_way_binding), ), ), seq( field('binding', $.two_way_binding), ), ), ), binding: $ => seq( field('name', $.identifier), ':', field('expr', $.binding_expression), ), qualified_binding: $ => seq( field('name', $.qualified_name), ':', field('expr', $.binding_expression), ), binding_expression: $ => choice( seq( $.code_block, optional(';'), ), seq( $._expression, ';', ), ), two_way_binding: $ => seq( field('name', $.identifier), '<=>', field('expr', $._expression), ';', ), property_animation: $ => seq( 'animate', field('property_names', choice( alias('*', $.property_wildcard), $.qualified_property_names, )), field('bindings', $.property_bindings), ), qualified_property_names: $ => sep1($.qualified_name, ','), property_bindings: $ => seq( '{', repeat($.binding), '}', ), states: $ => seq( 'states', '[', repeat($.state), ']', ), state: $ => seq( field('id', $.identifier), optional(seq( 'when', field('condition', $._expression), )), ':', field('property_changes', $.property_changes), ), property_changes: $ => seq( '{', repeat($.qualified_binding), '}', ), transitions: $ => seq( 'transitions', '[', repeat($.transition), ']', ), transition: $ => seq( field('direction', choice('in', 'out')), field('id', $.identifier), ':', field('animations', $.property_animations), ), property_animations: $ => seq( '{', repeat($.property_animation), '}', ), callback_declaration: $ => seq( 'callback', // TODO: better name vs binding structure choice( seq( field('name', $.identifier), optional(seq( field('parameters', $.callback_declaration_parameters), optional(seq( '->', field('return_type', $._type), )), )), ';', ), field('binding', $.two_way_binding), ), ), callback_declaration_parameters: $ => seq( '(', trailingCommaSep($._type), ')', ), callback_connection: $ => seq( field('name', $.identifier), optional(field('parameters', $.callback_connection_parameters)), '=>', field('expr', $.code_block), ), callback_connection_parameters: $ => seq( '(', trailingCommaSep($.identifier), ')', ), children_placeholder: $ => seq( '@', 'children', ), code_block: $ => seq( '{', repeat($._statement), optional(choice( $.self_assignment, $._expression, )), '}', ), _statement: $ => choice( $.empty_statement, $.if_statement, $.return_statement, $._self_assignment_statement, $._expression_statement, ), empty_statement: $ => ';', // TODO: naming rule conflicts: SyntaxKind::ConditionalExpression if_statement: $ => seq( 'if', field('condition', $.parenthesized_expression), field('true_expr', $.code_block), optional(seq( 'else', field('false_expr', choice($.if_statement, $.code_block)), )), ), return_statement: $ => seq( 'return', optional($._expression), ';', ), self_assignment: $ => seq( field('lhs', $._expression), field('op', choice('-=', '+=', '*=', '/=', '=')), field('rhs', $._expression), ), _self_assignment_statement: $ => seq( $.self_assignment, ';', ), _expression_statement: $ => seq( $._expression, ';', ), // $._identifier in place of $.qualified_name: parse_expression_helper() leverages // parse_qualified_name() to consume as many dotted names as possible, but that // would syntactically conflict with $.member_access. _expression: $ => choice( $._literal, $.parenthesized_expression, $.function_call_expression, $.index_expression, $.conditional_expression, $._identifier, $.binary_expression, $.array, $.object_literal, $.unary_op_expression, $.member_access, $._at_keyword, ), member_access: $ => seq( field('base', $._expression), '.', field('id', $._identifier), ), parenthesized_expression: $ => seq( '(', $._expression, ')', ), // It appears any expression can be a function name, which might be unintentional. function_call_expression: $ => seq( field('function', $._expression), field('arguments', $.arguments), ), arguments: $ => seq( '(', trailingCommaSep($._expression), ')', ), index_expression: $ => seq( field('array', $._expression), '[', field('index', $._expression), ']', ), unary_op_expression: $ => prec.right('unary', seq( field('op', choice('+', '-', '!')), field('sub', $._expression), )), binary_expression: $ => choice( prec.left('mul', seq( field('lhs', $._expression), field('op', choice('*', '/')), field('rhs', $._expression), )), prec.left('add', seq( field('lhs', $._expression), field('op', choice('+', '-')), field('rhs', $._expression), )), prec.left('equality', seq( field('lhs', $._expression), field('op', choice('==', '!=', '>=', '<=', '<', '>')), field('rhs', $._expression), )), prec.left('logical', seq( field('lhs', $._expression), field('op', choice('||', '&&')), field('rhs', $._expression), )), ), conditional_expression: $ => prec.right('ternary', seq( field('condition', $._expression), '?', field('true_expr', $._expression), ':', field('false_expr', $._expression), )), array: $ => seq( '[', trailingCommaSep($._expression), ']', ), // TODO: drop _literal from node name? object_literal: $ => seq( '{', trailingCommaSep($.object_member), '}', ), object_member: $ => seq( field('name', $.identifier), ':', field('expr', $._expression), ), _at_keyword: $ => choice( $.at_image_url, $.at_linear_gradient, ), at_image_url: $ => seq( '@', choice('image-url', 'image_url'), '(', field('source', $.string_literal), ')', ), at_linear_gradient: $ => seq( '@', choice('linear-gradient', 'linear_gradient'), field('arguments', $.at_linear_gradient_arguments), ), // TODO: strictness of @keyword arguments at_linear_gradient_arguments: $ => seq( '(', trailingCommaSep(choice($._expression, $.gradient_stop)), ')', ), gradient_stop: $ => seq( field('color', choice($.color_literal, $._identifier, $.member_access)), field('position', $.number_literal), ), struct_declaration: $ => seq( 'struct', field('name', $.identifier), ':=', field('fields', $.object_type), ), _type: $ => choice( $.array_type, $.object_type, alias($.qualified_name, $.qualified_type_name), ), array_type: $ => seq( '[', $._type, ']', ), object_type: $ => seq( '{', trailingCommaSep($.object_type_member), '}', ), object_type_member: $ => seq( field('name', $.identifier), ':', field('type', $._type), ), line_comment: $ => token(seq( '//', /.*/, )), _literal: $ => choice( $.string_literal, $.number_literal, $.color_literal, $.bool_literal, ), string_literal: $ => seq( '"', repeat(choice( $.escape_sequence, $.template_substitution, $.string_fragment, )), token.immediate('"'), ), escape_sequence: $ => token.immediate(seq( '\\', /./, // TODO: consume escaped sequence to highlight it )), template_substitution: $ => seq( '\\{', $._expression, '}', ), string_fragment: $ => token.immediate(/[^"\\]+/), number_literal: $ => seq( token(seq( /[0-9]+/, optional(/\.[0-9]*/), )), optional($.unit), ), unit: $ => choice( token.immediate('%'), token.immediate(/[a-zA-Z]+/), ), color_literal: $ => /#[a-zA-Z0-9]*/, bool_literal: $ => choice( 'true', 'false', ), self: $ => 'self', parent: $ => 'parent', root: $ => 'root', // isn't a special id, but reserved // TODO: lex_identifier() accepts c.is_alphanumeric(), which may contain // non-ASCII Alpha/Nd/Nl/No character. identifier: $ => token(seq( /[a-zA-Z_]/, repeat(/[a-zA-Z0-9_\-]/), )), _identifier: $ => choice( $.self, $.parent, $.root, $.identifier, ), // TODO: restrict use of reserved identifiers in type/property position? qualified_name: $ => sep1(choice( $._identifier, ), '.'), }, }); function sep(rule, sep) { return optional(sep1(rule, sep)); } function sep1(rule, sep) { return seq(rule, repeat(seq(sep, rule))); } function trailingCommaSep(rule) { return optional(seq( sep1(rule, ','), optional(','), )); }
yuja/tree-sitter-sixtyfps
0
SixtyFPS grammar for the tree-sitter parsing library
JavaScript
yuja
Yuya Nishihara
queries/highlights.scm
Scheme
; Functions (callback_declaration name: (identifier) @function) (callback_declaration binding: (two_way_binding name: (identifier) @function)) (callback_connection name: (identifier) @function) (callback_connection_parameters (identifier) @variable.parameter) ; Properties (property_declaration ["<" ">"] @punctuation.bracket) (property_declaration name: (identifier) @property) (binding name: (identifier) @property) (qualified_binding name: (qualified_name (identifier) @property)) (two_way_binding name: (identifier) @property) (qualified_property_names (qualified_name (identifier) @property)) ; At keywords (children_placeholder) @variable.builtin (at_image_url) @function.builtin (at_linear_gradient) @function.builtin ; Types and variable identifiers (import_export_identifier (identifier) @type) (component id: (identifier) @type) (global_component id: (identifier) @type) (sub_element id: (identifier) @variable) (object_member name: (identifier) @property) (qualified_type_name (identifier) @type) ((identifier) @type (#match? @type "^[A-Z]")) ; assume uppercase names are types (identifier) @variable ; Literals [ (self) (parent) (root) ] @variable.builtin (line_comment) @comment (block_comment) @comment (string_literal) @string (number_literal) @number (color_literal) @string.special (bool_literal) @constant.builtin ; Tokens [ "," "." ":" ";" ] @punctuation.delimiter [ "*" "+" "-" "/" "!" "!=" "<" "<=" "==" ">" ">=" "&&" "||" "*=" "+=" "-=" "/=" ":=" "=" "->" "<=>" "=>" ] @punctuation.operator [ "(" ")" "[" "]" "{" "}" ] @punctuation.bracket ; Keywords [ "animate" "as" "callback" "else" "export" "for" "from" "global" "if" "import" "in" "out" "property" "return" "states" "struct" "transitions" "when" ] @keyword
yuja/tree-sitter-sixtyfps
0
SixtyFPS grammar for the tree-sitter parsing library
JavaScript
yuja
Yuya Nishihara
queries/locals.scm
Scheme
; Scopes ; TODO: this is just a stub [ (binding_expression) (callback_declaration) (callback_connection) ] @local.scope ; Definitions (callback_connection_parameters (identifier) @local.definition) ; References (identifier) @local.reference
yuja/tree-sitter-sixtyfps
0
SixtyFPS grammar for the tree-sitter parsing library
JavaScript
yuja
Yuya Nishihara
src/scanner.c
C
#include <tree_sitter/parser.h> enum TokenType { BLOCK_COMMENT, }; static void advance(TSLexer *lexer) { lexer->advance(lexer, false); } static void skip(TSLexer *lexer) { lexer->advance(lexer, true); } static bool scan_block_comment(TSLexer *lexer, int depth) { bool pending_star = false; while (lexer->lookahead && depth > 0) { switch (lexer->lookahead) { case '*': advance(lexer); pending_star = true; break; case '/': if (pending_star) { advance(lexer); pending_star = false; --depth; } else { advance(lexer); if (lexer->lookahead != '*') continue; advance(lexer); ++depth; } break; default: advance(lexer); pending_star = false; } } if (depth > 0) return false; lexer->result_symbol = BLOCK_COMMENT; return true; } void *tree_sitter_sixtyfps_external_scanner_create() { return NULL; } void tree_sitter_sixtyfps_external_scanner_destroy(void *p) { } unsigned tree_sitter_sixtyfps_external_scanner_serialize(void *p, char *buffer) { return 0; } void tree_sitter_sixtyfps_external_scanner_deserialize(void *p, const char *b, unsigned n) { } bool tree_sitter_sixtyfps_external_scanner_scan(void *payload, TSLexer *lexer, const bool *valid_symbols) { while (iswspace(lexer->lookahead)) { skip(lexer); } if (lexer->lookahead == '/' && valid_symbols[BLOCK_COMMENT]) { advance(lexer); if (lexer->lookahead != '*') return false; advance(lexer); return scan_block_comment(lexer, /*depth=*/1); } return false; }
yuja/tree-sitter-sixtyfps
0
SixtyFPS grammar for the tree-sitter parsing library
JavaScript
yuja
Yuya Nishihara
jdext.js
JavaScript
#!/usr/bin/env node const fs = require('fs'); exports.extract = (jdsave, webm)=>{ const j = fs.readFileSync(jdsave); if (j[512495]!=0 || j[512496]!=0x1A) throw new Error('cannot find video start byte'); const v = Buffer.from(j.buffer, 512496); fs.writeFileSync(webm, v); }; if (module.parent) return; if (process.argv.length < 4) return console.warn('not enought arguments\nexample: ./jdext.js JDSave_1 myvideo.webm'); try { exports.extract(process.argv[2], process.argv[3]); } catch(e){ console.error(`${e.stack}\n\nplease copy log from above and report the issue here https://github.com/39dotyt/jdext/issues`); }
yurijmikhalevich/jdext
6
JustDance saved video extractor
JavaScript
yurijmikhalevich
Yurij Mikhalevich
Makes magic at QAWolf 🐺
autogen.py
Python
import os import shutil from pathlib import Path from keras_autodoc import DocumentationGenerator rootdir = Path(__file__).parent docsdir = os.path.join(rootdir, "docs-src", "docs") srcdocsdir = os.path.join(docsdir, "visionpod") pages = {"core.PodModule.md": ["visionpod.core.module.PodModule"]} level = ".." if os.getcwd() == "docs-src" else "." doc_generator = DocumentationGenerator(pages) doc_generator.generate(f"{level}/docs-src/docs/visionpod") root_readme = os.path.join(rootdir, "README.md") docs_intro = os.path.join(docsdir, "intro.md") shutil.copyfile(src=root_readme, dst=docs_intro) with open(docs_intro, "r", encoding="utf-8") as intro_file: text = intro_file.readlines() with open(docs_intro, "w", encoding="utf-8") as intro_file: text.insert(0, "---\n") text.insert(1, "sidebar_position: 1\n") text.insert(2, "---\n\n") intro_file.writelines("".join(text)) intro_file.close()
yurijmikhalevich/lightning-pod-vision
0
An End to End ML Product Example
yurijmikhalevich
Yurij Mikhalevich
Makes magic at QAWolf 🐺
docs-src/babel.config.js
JavaScript
module.exports = { presets: [require.resolve('@docusaurus/core/lib/babel/preset')], };
yurijmikhalevich/lightning-pod-vision
0
An End to End ML Product Example
yurijmikhalevich
Yurij Mikhalevich
Makes magic at QAWolf 🐺
docs-src/docusaurus.config.js
JavaScript
// @ts-check // Note: type annotations allow type checking and IDEs autocompletion const lightCodeTheme = require('prism-react-renderer/themes/github'); const darkCodeTheme = require('prism-react-renderer/themes/dracula'); /** @type {import('@docusaurus/types').Config} */ const config = { title: 'Lightning Pod Vision', // tagline: 'Dinosaurs are cool', // favicon: 'img/favicon.ico', // Set the production url of your site here url: 'https://visionpod-docs.vercel.app/', // Set the /<baseUrl>/ pathname under which your site is served // For GitHub pages deployment, it is often '/<projectName>/' baseUrl: '/', // GitHub pages deployment config. // If you aren't using GitHub pages, you don't need these. organizationName: 'JustinGoheen', // Usually your GitHub org/user name. projectName: 'lightning-pod-vision', // Usually your repo name. onBrokenLinks: 'warn', onBrokenMarkdownLinks: 'warn', // Even if you don't use internalization, you can use this field to set useful // metadata like html lang. For example, if your site is Chinese, you may want // to replace "en" with "zh-Hans". i18n: { defaultLocale: 'en', locales: ['en'], }, presets: [ [ 'classic', /** @type {import('@docusaurus/preset-classic').Options} */ ({ docs: { sidebarPath: require.resolve('./sidebars.js'), // Please change this to your repo. // Remove this to remove the "edit this page" links. // editUrl: // 'https://github.com/facebook/docusaurus/tree/main/packages/create-docusaurus/templates/shared/', exclude: ['**/tutorial-basics/**', '**/tutorial-extras/**'], }, blog: { showReadingTime: true, // Please change this to your repo. // Remove this to remove the "edit this page" links. // editUrl: // 'https://github.com/facebook/docusaurus/tree/main/packages/create-docusaurus/templates/shared/', }, theme: { customCss: require.resolve('./src/css/custom.css'), }, }), ], ], themeConfig: /** @type {import('@docusaurus/preset-classic').ThemeConfig} */ ({ // Replace with your project's social card image: 'img/docusaurus-social-card.jpg', navbar: { title: 'Lightning Pod Vision', // logo: { // alt: 'My Site Logo', // // src: 'img/logo.svg', // }, items: [ { type: 'doc', docId: 'intro', position: 'left', label: 'Tutorial', }, {to: '/blog', label: 'Blog', position: 'left'}, { href: 'https://github.com/JustinGoheen/lightning-pod-vision', label: 'GitHub', position: 'right', }, ], }, footer: { style: 'dark', // links: [ // { // title: 'Docs', // items: [ // { // label: 'Getting Started', // to: '/docs/intro', // }, // ], // }, // { // title: 'Community', // items: [ // { // label: 'Stack Overflow', // href: 'https://stackoverflow.com/questions/tagged/docusaurus', // }, // { // label: 'Discord', // href: 'https://discordapp.com/invite/docusaurus', // }, // { // label: 'Twitter', // href: 'https://twitter.com/docusaurus', // }, // ], // }, // { // title: 'More', // items: [ // { // label: 'Blog', // to: '/blog', // }, // { // label: 'GitHub', // href: 'https://github.com/JustinGoheen/lightning-pod-vision', // }, // ], // }, // ], copyright: `Copyright © ${new Date().getFullYear()} Justin Goheen.`, }, prism: { theme: lightCodeTheme, darkTheme: darkCodeTheme, }, }), }; module.exports = config;
yurijmikhalevich/lightning-pod-vision
0
An End to End ML Product Example
yurijmikhalevich
Yurij Mikhalevich
Makes magic at QAWolf 🐺
docs-src/sidebars.js
JavaScript
/** * Creating a sidebar enables you to: - create an ordered group of docs - render a sidebar for each doc of that group - provide next/previous navigation The sidebars can be generated from the filesystem, or explicitly defined here. Create as many sidebars as you want. */ // @ts-check /** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ const sidebars = { // By default, Docusaurus generates a sidebar from the docs folder structure tutorialSidebar: [{type: 'autogenerated', dirName: '.'}], // But you can create a sidebar manually /* tutorialSidebar: [ 'intro', 'hello', { type: 'category', label: 'Tutorial', items: ['tutorial-basics/create-a-document'], }, ], */ }; module.exports = sidebars;
yurijmikhalevich/lightning-pod-vision
0
An End to End ML Product Example
yurijmikhalevich
Yurij Mikhalevich
Makes magic at QAWolf 🐺
docs-src/src/components/HomepageFeatures/index.tsx
TypeScript (TSX)
import React from 'react'; import clsx from 'clsx'; import styles from './styles.module.css'; type FeatureItem = { title: string; Svg: React.ComponentType<React.ComponentProps<'svg'>>; description: JSX.Element; }; const FeatureList: FeatureItem[] = [ { title: 'Easy to Use', Svg: require('@site/static/img/undraw_docusaurus_mountain.svg').default, description: ( <> Docusaurus was designed from the ground up to be easily installed and used to get your website up and running quickly. </> ), }, { title: 'Focus on What Matters', Svg: require('@site/static/img/undraw_docusaurus_tree.svg').default, description: ( <> Docusaurus lets you focus on your docs, and we&apos;ll do the chores. Go ahead and move your docs into the <code>docs</code> directory. </> ), }, { title: 'Powered by React', Svg: require('@site/static/img/undraw_docusaurus_react.svg').default, description: ( <> Extend or customize your website layout by reusing React. Docusaurus can be extended while reusing the same header and footer. </> ), }, ]; function Feature({title, Svg, description}: FeatureItem) { return ( <div className={clsx('col col--4')}> <div className="text--center"> <Svg className={styles.featureSvg} role="img" /> </div> <div className="text--center padding-horiz--md"> <h3>{title}</h3> <p>{description}</p> </div> </div> ); } export default function HomepageFeatures(): JSX.Element { return ( <section className={styles.features}> <div className="container"> <div className="row"> {FeatureList.map((props, idx) => ( <Feature key={idx} {...props} /> ))} </div> </div> </section> ); }
yurijmikhalevich/lightning-pod-vision
0
An End to End ML Product Example
yurijmikhalevich
Yurij Mikhalevich
Makes magic at QAWolf 🐺
docs-src/src/components/HomepageFeatures/styles.module.css
CSS
.features { display: flex; align-items: center; padding: 2rem 0; width: 100%; } .featureSvg { height: 200px; width: 200px; }
yurijmikhalevich/lightning-pod-vision
0
An End to End ML Product Example
yurijmikhalevich
Yurij Mikhalevich
Makes magic at QAWolf 🐺
docs-src/src/css/custom.css
CSS
/** * Any CSS included here will be global. The classic template * bundles Infima by default. Infima is a CSS framework designed to * work well for content-centric websites. */ /* You can override the default Infima variables here. */ :root { --ifm-color-primary: #2e8555; --ifm-color-primary-dark: #29784c; --ifm-color-primary-darker: #277148; --ifm-color-primary-darkest: #205d3b; --ifm-color-primary-light: #33925d; --ifm-color-primary-lighter: #359962; --ifm-color-primary-lightest: #3cad6e; --ifm-code-font-size: 95%; --docusaurus-highlighted-code-line-bg: rgba(0, 0, 0, 0.1); } /* For readability concerns, you should choose a lighter palette in dark mode. */ [data-theme='dark'] { --ifm-color-primary: #25c2a0; --ifm-color-primary-dark: #21af90; --ifm-color-primary-darker: #1fa588; --ifm-color-primary-darkest: #1a8870; --ifm-color-primary-light: #29d5b0; --ifm-color-primary-lighter: #32d8b4; --ifm-color-primary-lightest: #4fddbf; --docusaurus-highlighted-code-line-bg: rgba(0, 0, 0, 0.3); }
yurijmikhalevich/lightning-pod-vision
0
An End to End ML Product Example
yurijmikhalevich
Yurij Mikhalevich
Makes magic at QAWolf 🐺
docs-src/src/pages/index.module.css
CSS
/** * CSS files with the .module.css suffix will be treated as CSS modules * and scoped locally. */ .heroBanner { padding: 4rem 0; text-align: center; position: relative; overflow: hidden; } @media screen and (max-width: 996px) { .heroBanner { padding: 2rem; } } .buttons { display: flex; align-items: center; justify-content: center; }
yurijmikhalevich/lightning-pod-vision
0
An End to End ML Product Example
yurijmikhalevich
Yurij Mikhalevich
Makes magic at QAWolf 🐺
docs-src/src/pages/index.tsx
TypeScript (TSX)
import React from 'react'; import clsx from 'clsx'; import Link from '@docusaurus/Link'; import useDocusaurusContext from '@docusaurus/useDocusaurusContext'; import Layout from '@theme/Layout'; import HomepageFeatures from '@site/src/components/HomepageFeatures'; import styles from './index.module.css'; function HomepageHeader() { const {siteConfig} = useDocusaurusContext(); return ( <header className={clsx('hero', styles.heroBanner)}> <div className="container"> <h1 className="hero__title">{siteConfig.title}</h1> <p className="hero__subtitle">{siteConfig.tagline} An End to End ML Product </p> <div className={styles.buttons}> <Link className="button button--secondary button--lg" to="/docs/intro"> Docs </Link> &nbsp;&nbsp;&nbsp; <Link className="button button--secondary button--lg" to="/blog"> Blog </Link> </div> </div> </header> ); } export default function Home(): JSX.Element { const {siteConfig} = useDocusaurusContext(); return ( <Layout title={`Hello from ${siteConfig.title}`} description="An end to end ML product template <head />"> <HomepageHeader /> {/* <main> <HomepageFeatures /> </main> */} </Layout> ); }
yurijmikhalevich/lightning-pod-vision
0
An End to End ML Product Example
yurijmikhalevich
Yurij Mikhalevich
Makes magic at QAWolf 🐺
lightning-app/app.py
Python
# Copyright Justin R. Goheen. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pathlib import Path from lightning import LightningApp, LightningFlow from lightning.app.frontend import StaticWebFrontend class ReactUI(LightningFlow): def __init__(self): super().__init__() def configure_layout(self): return StaticWebFrontend(Path(__file__).parents[1] / "next-app/.next/") class RootFlow(LightningFlow): def __init__(self): super().__init__() self.react_ui = ReactUI() def run(self): self.react_ui.run() def configure_layout(self): return [{"name": "ReactUI", "content": self.react_ui}] app = LightningApp(RootFlow())
yurijmikhalevich/lightning-pod-vision
0
An End to End ML Product Example
yurijmikhalevich
Yurij Mikhalevich
Makes magic at QAWolf 🐺
next-app/next.config.js
JavaScript
/** @type {import('next').NextConfig} */ const nextConfig = { reactStrictMode: true, eslint: { ignoreDuringBuilds: true, } }; module.exports = nextConfig;
yurijmikhalevich/lightning-pod-vision
0
An End to End ML Product Example
yurijmikhalevich
Yurij Mikhalevich
Makes magic at QAWolf 🐺
next-app/src/components/graphs/imageGrid.tsx
TypeScript (TSX)
import { Container, Grid, Box, Typography } from "@mui/material"; export const ImageGrid = (props: any) => ( <Container> <Grid container spacing={4}> <Grid item> <Box sx={{ width: 300, height: 300, backgroundColor: "primary.light", }} > <Typography>Ground Truth</Typography> </Box> </Grid> <Grid item> <Box sx={{ width: 300, height: 300, backgroundColor: "primary.light", }} > <Typography>Decoded Image</Typography> </Box> </Grid> </Grid> </Container> );
yurijmikhalevich/lightning-pod-vision
0
An End to End ML Product Example
yurijmikhalevich
Yurij Mikhalevich
Makes magic at QAWolf 🐺
next-app/src/components/mainPage/navBar.tsx
TypeScript (TSX)
import * as React from "react"; import AppBar from "@mui/material/AppBar"; import Box from "@mui/material/Box"; import Toolbar from "@mui/material/Toolbar"; import Typography from "@mui/material/Typography"; export default function NavBar() { return ( <Box sx={{ flexGrow: 1 }}> <AppBar position="static" color="primary"> <Toolbar> <Typography component="div" sx={{ flexGrow: 1 }}> Linear Encoder-Decoder </Typography> </Toolbar> </AppBar> </Box> ); }
yurijmikhalevich/lightning-pod-vision
0
An End to End ML Product Example
yurijmikhalevich
Yurij Mikhalevich
Makes magic at QAWolf 🐺
next-app/src/components/metrics/metricFour.tsx
TypeScript (TSX)
import { Card, CardContent, Grid, Typography } from "@mui/material"; export const MetricFour = (props: any) => ( <Card {...props}> <CardContent> <Grid container spacing={3}> <Grid item> <Typography variant="h5">Metric Name</Typography> <Typography>0.xx</Typography> </Grid> </Grid> </CardContent> </Card> );
yurijmikhalevich/lightning-pod-vision
0
An End to End ML Product Example
yurijmikhalevich
Yurij Mikhalevich
Makes magic at QAWolf 🐺
next-app/src/components/metrics/metricOne.tsx
TypeScript (TSX)
import { Card, CardContent, Grid, Typography } from "@mui/material"; export const MetricOne = (props: any) => ( <Card {...props}> <CardContent> <Grid container spacing={3}> <Grid item> <Typography variant="h5">Metric Name</Typography> <Typography>0.xx</Typography> </Grid> </Grid> </CardContent> </Card> );
yurijmikhalevich/lightning-pod-vision
0
An End to End ML Product Example
yurijmikhalevich
Yurij Mikhalevich
Makes magic at QAWolf 🐺
next-app/src/components/metrics/metricThree.tsx
TypeScript (TSX)
import { Card, CardContent, Grid, Typography } from "@mui/material"; export const MetricThree = (props: any) => ( <Card {...props}> <CardContent> <Grid container spacing={3}> <Grid item> <Typography variant="h5">Metric Name</Typography> <Typography>0.xx</Typography> </Grid> </Grid> </CardContent> </Card> );
yurijmikhalevich/lightning-pod-vision
0
An End to End ML Product Example
yurijmikhalevich
Yurij Mikhalevich
Makes magic at QAWolf 🐺
next-app/src/components/metrics/metricTwo.tsx
TypeScript (TSX)
import { Card, CardContent, Grid, Typography } from "@mui/material"; export const MetricTwo = (props: any) => ( <Card {...props}> <CardContent> <Grid container spacing={3}> <Grid item> <Typography variant="h5">Metric Name</Typography> <Typography>0.xx</Typography> </Grid> </Grid> </CardContent> </Card> );
yurijmikhalevich/lightning-pod-vision
0
An End to End ML Product Example
yurijmikhalevich
Yurij Mikhalevich
Makes magic at QAWolf 🐺
next-app/src/components/metrics/metricsGrid.tsx
TypeScript (TSX)
import { Container, Grid } from "@mui/material"; import { MetricOne } from "./metricOne"; import { MetricTwo } from "./metricTwo"; import { MetricThree } from "./metricThree"; import { MetricFour } from "./metricFour"; export const MetricsGrid = () => ( <Grid container spacing={3} direction={"row"}> <Grid item lg={3} sm={6} xl={3} xs={12}> <MetricOne /> </Grid> <Grid item xl={3} lg={3} sm={6} xs={12}> <MetricTwo /> </Grid> <Grid item xl={3} lg={3} sm={6} xs={12}> <MetricThree /> </Grid> <Grid item xl={3} lg={3} sm={6} xs={12}> <MetricFour /> </Grid> </Grid> );
yurijmikhalevich/lightning-pod-vision
0
An End to End ML Product Example
yurijmikhalevich
Yurij Mikhalevich
Makes magic at QAWolf 🐺