makepad_live_compiler/
live_node.rs

1use {
2    std::{
3        collections::HashMap,
4        sync::Arc,
5        fmt,
6        ops::{Deref, DerefMut},
7    },
8    crate::{
9        makepad_math::{
10            Vec2,
11            Vec3,
12            Vec4
13        },
14        live_registry::LiveScopeTarget,
15        makepad_live_tokenizer::{LiveId},
16        live_ptr::{LiveModuleId, LivePtr},
17        live_token::{LiveToken, LiveTokenId},
18    }
19};
20
21#[derive(Clone, Debug, PartialEq)]
22pub struct LiveNode { // 48 bytes. Don't really see ways to compress
23    pub origin: LiveNodeOrigin,
24    pub id: LiveId,
25    pub value: LiveValue,
26}
27
28#[derive(Clone, Debug, PartialEq)]
29pub struct LiveFont {
30    pub paths: Arc<Vec<Arc<String>>>,
31    pub ascender_fudge: f32,
32    pub descender_fudge: f32
33}
34
35impl LiveFont{
36    pub fn to_live_id(&self)->LiveId{
37        let mut live_id = LiveId::seeded();
38        for path in &*self.paths{
39            live_id = live_id.str_append(path)
40        }
41        live_id.bytes_append(&self.ascender_fudge.to_be_bytes())
42        .bytes_append(&self.descender_fudge.to_be_bytes())
43    }
44}
45 
46#[derive(Clone, Debug, PartialEq)]
47pub enum LiveValue {
48    None,
49    // string types
50    Str(&'static str),
51    String(Arc<String>),
52    InlineString(InlineString),
53    Dependency(Arc<String>),
54    Font(LiveFont),
55    Bool(bool),
56    Int64(i64),
57    Uint64(u64),
58    Float32(f32),
59    Float64(f64),
60    Color(u32),
61    Vec2(Vec2),
62    Vec3(Vec3),
63    Vec4(Vec4),
64
65    Id(LiveId),
66    IdPath(Arc<Vec<LiveId>>),
67
68    ExprBinOp(LiveBinOp),
69    ExprUnOp(LiveUnOp),
70    ExprMember(LiveId),
71    ExprCall {ident: LiveId, args: usize},
72     // enum thing
73    BareEnum (LiveId),
74    // tree items
75    Root(Box<LiveNodeRoot>),//{id_resolve:Box<HashMap<LiveId,LiveScopeTarget>>},
76    Array,
77    Expr,// {expand_index: Option<u32>},
78    TupleEnum (LiveId),
79    NamedEnum (LiveId),
80    Object,
81    Clone{clone:LiveId},
82    Deref{live_type: LiveType, clone:LiveId},
83    Class {live_type: LiveType, class_parent: LivePtr},
84    Close,
85    
86    // shader code and other DSLs
87    DSL {
88        token_start: u32,
89        token_count: u32,
90        expand_index: Option<u32>
91    },
92    Import (Box<LiveImport>),
93}
94
95#[derive(Clone, Debug, Default, PartialEq)]
96pub struct LiveNodeRoot{
97    pub locals: HashMap<LiveId,LiveScopeTarget>,
98    pub exports: HashMap<LiveId, usize>
99}
100
101#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
102pub struct LiveImport{
103    pub module_id: LiveModuleId,
104    pub import_id: LiveId,
105}
106
107#[derive(Debug, Clone, PartialEq)]
108pub struct LiveBinding{
109    pub from: LiveIdPath,
110    pub to: LiveIdPath
111}
112
113#[derive(Debug, Clone, PartialEq)]
114pub struct LiveIdPath(pub Vec<LiveId>);
115
116impl LiveValue {
117    pub fn update_from_live_token(&mut self, token: &LiveToken) -> bool {
118        match self {
119            Self::String(rcstring)  => {
120                if let LiveToken::String(other_rcstring) = token {
121                    *rcstring = other_rcstring.clone();
122                    return true
123                }
124            },
125            Self::Color(o) => if let LiveToken::Color(i) = token {
126                *o = *i;
127                return true
128            },
129            Self::Bool(o) => if let LiveToken::Bool(i) = token {
130                *o = *i;
131                return true
132            },
133            Self::Int64(o) => {
134                if let LiveToken::Int(i) = token {
135                    *o = *i;
136                    return true
137                }
138                if let LiveToken::Float(v) = token {
139                    *self = LiveValue::Float64(*v);
140                    return true
141                }
142            }
143            Self::Float64(o) => {
144                if let LiveToken::Float(i) = token {
145                    *o = *i;
146                    return true
147                }
148                if let LiveToken::Int(v) = token {
149                    *self = LiveValue::Int64(*v);
150                    return true
151                }
152            }
153            Self::Float32(o) => {
154                if let LiveToken::Float(i) = token {
155                    *o = *i as f32;
156                    return true
157                }
158                if let LiveToken::Int(v) = token {
159                    *self = LiveValue::Int64(*v);
160                    return true
161                }
162            }
163            _ => ()
164            
165        }
166        false
167    }
168}
169
170impl LiveNode {
171    
172    pub fn empty() -> Self {
173        Self {
174            origin: LiveNodeOrigin::empty(),
175            id: LiveId(0),
176            value: LiveValue::None
177        }
178    }
179    pub fn from_id_value(id: LiveId, value: LiveValue) -> Self {
180        Self {
181            origin: LiveNodeOrigin::empty(),
182            id,
183            value
184        }
185    }
186    
187    pub fn from_value(value: LiveValue) -> Self {
188        Self {
189            origin: LiveNodeOrigin::empty(),
190            id: LiveId(0),
191            value
192        }
193    }
194    
195    pub fn is_token_id_inside_dsl(&self, other_token: LiveTokenId) -> bool {
196        if let Some(token_id) = self.origin.token_id() {
197            if token_id.file_id() != other_token.file_id() {
198                return false
199            }
200        }
201        else {
202            return false;
203        }
204        match &self.value {
205            LiveValue::DSL {token_start, token_count, ..} => {
206                let token_index = other_token.token_index();
207                token_index as u32 >= *token_start && (token_index as u32) < token_start + token_count
208            }
209            _ => false
210        }
211    }
212    
213    pub fn prop(&self) -> LiveProp {
214        LiveProp(self.id, self.origin.prop_type())
215    }
216    
217}
218
219#[derive(Copy, Clone, Debug)]
220pub struct LiveProp(pub LiveId, pub LivePropType);
221impl LiveProp {
222    pub fn field(id: LiveId) -> Self {Self (id, LivePropType::Field)}
223    pub fn instance(id: LiveId) -> Self {Self (id, LivePropType::Instance)}
224}
225
226pub trait LiveIdAsProp {
227    fn as_field(&self) -> LiveProp;
228    fn as_instance(&self) -> LiveProp;
229}
230
231impl LiveIdAsProp for LiveId {
232    fn as_field(&self) -> LiveProp {LiveProp(*self, LivePropType::Field)}
233    fn as_instance(&self) -> LiveProp {LiveProp(*self, LivePropType::Instance)}
234}
235
236#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
237pub struct LiveNodeOrigin(u64);
238
239impl fmt::Debug for LiveNodeOrigin {
240    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
241        write!(f, "token_id:{:?} first_def:{:?} edit_info:{:?} prop_type:{:?}", self.token_id(), self.first_def(), self.edit_info(), self.prop_type())
242    }
243}
244
245// this layout can be reshuffled and just be made bigger.
246// However it keeps the LiveNode size at 40 bytes which is nice for now.
247
248// 10 bit file id (1024)
249// 18 bit token id (262k tokens, avg tokensize: 5 = 1.25 megs of code used to find original token of property
250
251// 10 bit first def file_id
252// 18 bit first def token_id
253
254// 6 bits (64) edit_info index
255// 1 bit node_has_prefix
256// 2 bits LivePropType
257
258// ok if we are a DSL node then what else do we need. we need a node index pointer.
259
260#[derive(Debug, Clone, Copy, PartialEq)]
261#[repr(usize)]
262pub enum LivePropType {
263    Field = 0,
264    Instance = 1,
265    //Template = 2,
266    Nameless = 3
267}
268
269impl LiveNodeOrigin {
270    pub fn empty() -> Self {
271        Self (0)
272    }
273    
274    pub fn field() -> Self {
275        Self (0).with_prop_type(LivePropType::Field)
276    }
277    
278    pub fn instance() -> Self {
279        Self (0).with_prop_type(LivePropType::Instance)
280    }
281    
282    
283    pub fn from_token_id(token_id: LiveTokenId) -> Self {
284        Self ((token_id.to_bits() as u64) | ((token_id.to_bits() as u64) << 28))
285    }
286    
287    pub fn token_id(&self) -> Option<LiveTokenId> {
288        LiveTokenId::from_bits((self.0 & 0x0fff_ffff) as u32)
289    }
290    
291    
292    pub fn set_first_def(&mut self, token_id: Option<LiveTokenId>) -> &mut Self {
293        if let Some(token_id) = token_id {
294            self.0 = (self.0 & 0xff00_0000_0fff_ffff) | ((token_id.to_bits() as u64) << 28);
295        }
296        self
297    }
298    
299    pub fn first_def(&self) -> Option<LiveTokenId> {
300        LiveTokenId::from_bits(((self.0 >> 28) & 0x0fff_ffff) as u32)
301    }
302    
303    pub fn set_edit_info(&mut self, edit_info: Option<LiveEditInfo>) -> &mut Self {
304        if let Some(edit_info) = edit_info {
305            self.0 = (self.0 & 0xE0FF_FFFF_FFFF_FFFF) | ((edit_info.to_bits() as u64) << 56);
306        }
307        self
308    }
309    
310    pub fn with_edit_info(mut self, edit_info: Option<LiveEditInfo>) -> Self {
311        self.set_edit_info(edit_info);
312        self
313    }
314    
315    pub fn edit_info(&self) -> Option<LiveEditInfo> {
316        LiveEditInfo::from_bits(((self.0 & 0x1f00_0000_0000_0000) >> 56) as u32)
317    }
318    
319    pub fn set_node_has_prefix(&mut self, node_has_prefix: bool) {
320        if node_has_prefix {
321            self.0 |= 0x2000_0000_0000_0000;
322        }
323    }
324    
325    pub fn with_node_has_prefix(mut self, node_has_prefix: bool) -> Self {
326        self.set_node_has_prefix(node_has_prefix);
327        self
328    }
329    
330    pub fn node_has_prefix(&self) -> bool {
331        self.0 & 0x2000_0000_0000_0000 != 0
332    }
333    
334    pub fn with_prop_type(mut self, prop_type: LivePropType) -> Self {
335        self.0 |= (prop_type as u64) << 62; //0x8000_0000_0000_0000;
336        self
337    }
338    
339    pub fn set_prop_type(&mut self, prop_type: LivePropType) {
340        self.0 = (self.0 & (!0xC000_0000_0000_0000)) | ((prop_type as u64) << 62);
341    }
342    
343    pub fn prop_type(&self) -> LivePropType {
344        LivePropType::from_usize(((self.0 & 0xC000_0000_0000_0000) >> 62) as usize)
345    }
346    
347    pub fn has_prop_type(&self, origin: LivePropType) -> bool {
348        (self.0 & 0xC000_0000_0000_0000) >> 62 == origin as u64
349    }
350    
351    pub fn inherit_origin(&mut self, origin: Self) {
352        let edit_info = origin.edit_info();
353        let first_def = origin.first_def();
354        let node_has_prefix = origin.node_has_prefix();
355        self.set_edit_info(edit_info);
356        self.set_first_def(first_def);
357        self.set_node_has_prefix(node_has_prefix);
358    }
359}
360
361impl LivePropType {
362    pub fn from_usize(val: usize) -> Self {
363        match val {
364            0 => Self::Field,
365            1 => Self::Instance,
366            //2 => Self::Template,
367            _ => Self::Nameless
368        }
369    }
370}
371
372pub struct LiveEditInfo(u32);
373
374impl fmt::Debug for LiveEditInfo {
375    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
376        write!(f, "{:?}", self.edit_info_index())
377    }
378}
379
380impl LiveEditInfo {
381    pub fn new(edit_info_index: usize) -> Self {
382        if edit_info_index & 0xf != 0 || edit_info_index > 0x3e0 {
383            panic!();
384        }
385        LiveEditInfo(((edit_info_index as u32) >> 4) + 1)
386    }
387    
388    pub fn edit_info_index(&self) -> usize {
389        (((self.0) as usize - 1) << 4) & 0x3f0
390    }
391    
392    pub fn to_bits(&self) -> u32 {self.0}
393    pub fn from_bits(v: u32) -> Option<Self> {
394        if (v & 0xFFFF_FF00) != 0 {
395            panic!();
396        }
397        if v == 0 {
398            None
399        } else {
400            Some(Self(v))
401        }
402    }
403}
404
405pub type LiveType = std::any::TypeId;
406
407#[derive(Clone, Debug)]
408pub struct LiveTypeInfo {
409    pub live_type: LiveType,
410    pub type_name: LiveId,
411    pub module_id: LiveModuleId,
412    pub live_ignore: bool,
413    pub fields: Vec<LiveTypeField>
414}
415
416#[derive(Clone, Debug)]
417pub struct LiveTypeField {
418    pub id: LiveId,
419    pub live_type_info: LiveTypeInfo,
420    pub live_field_kind: LiveFieldKind
421}
422
423#[derive(Copy, Clone, PartialEq, Debug)]
424pub enum LiveFieldKind {
425    Calc,
426    Deref,
427    Animator,
428    Live,
429    LiveOption
430}
431
432#[derive(Copy, Clone, Debug, PartialEq)]
433pub enum LiveBinOp {
434    Or,
435    And,
436    Eq,
437    Ne,
438    Lt,
439    Le,
440    Gt,
441    Ge,
442    Add,
443    Sub,
444    Mul,
445    Div,
446}
447
448#[derive(Copy, Clone, Debug, PartialEq)]
449pub enum LiveUnOp {
450    Not,
451    Neg,
452}
453
454impl LiveNode{
455        
456    pub fn is_instance_prop(&self) -> bool {
457        self.origin.has_prop_type(LivePropType::Instance)
458    }
459        
460    pub fn is_field_prop(&self,) -> bool {
461        self.origin.has_prop_type(LivePropType::Field)
462    }
463            
464}
465
466const INLINE_STRING_BUFFER_SIZE: usize = 22;
467#[derive(Clone, Debug, PartialEq)]
468pub struct InlineString {
469    length: u8,
470    buffer: [u8; INLINE_STRING_BUFFER_SIZE]
471}
472
473impl InlineString {
474    pub fn from_str(inp: &str) -> Option<Self> {
475        let bytes = inp.as_bytes();
476        if bytes.len()<INLINE_STRING_BUFFER_SIZE {
477            let mut buffer = [0u8; INLINE_STRING_BUFFER_SIZE];
478            buffer[..bytes.len()].copy_from_slice(bytes);
479            return Some(Self {length: bytes.len() as u8, buffer})
480        }
481        None
482    }
483        
484    pub fn as_str(&self) -> &str {
485        unsafe {std::str::from_utf8_unchecked(std::slice::from_raw_parts(self.buffer.as_ptr(), self.length as usize))}
486    }
487}
488
489impl LiveValue {
490    pub fn is_open(&self) -> bool {
491        match self {
492            Self::Array |
493            Self::Expr {..} |
494            Self::TupleEnum {..} |
495            Self::NamedEnum {..} |
496            Self::Object | // subnodes including this one
497            Self::Clone {..} | // subnodes including this one
498            Self::Class {..} | 
499            Self::Deref {..} | 
500            Self::Root {..} => true, // subnodes including this one
501            _ => false
502        }
503    }
504    
505    pub fn is_close(&self) -> bool {
506        matches!(self, Self::Close)
507    }
508    
509    pub fn is_enum(&self) -> bool {
510        matches!(self, Self::BareEnum {..} |
511            Self::TupleEnum {..} |
512            Self::NamedEnum {..})
513    }
514    
515    pub fn is_array(&self) -> bool {
516        matches!(self, Self::Array)
517    }
518    
519    pub fn is_expr(&self) -> bool {
520        matches!(self, Self::Expr {..})
521    }
522    
523    pub fn is_class(&self) -> bool {
524        matches!(self, Self::Class {..})
525    }
526    
527    pub fn is_clone(&self) -> bool {
528        matches!(self, Self::Clone {..})
529    }
530    
531    pub fn is_object(&self) -> bool {
532        matches!(self, Self::Object)
533    }
534    
535    pub fn is_dsl(&self) -> bool {
536        matches!(self, Self::DSL {..})
537    }
538    
539    pub fn set_dsl_expand_index_if_none(&mut self, index: usize) {
540        if let Self::DSL {expand_index, ..} = self {
541            if expand_index.is_none() {
542                *expand_index = Some(index as u32)
543            }
544        }
545    }
546    /*
547    pub fn set_expr_expand_index_if_none(&mut self, index: usize) {
548        if let Self::Expr {expand_index, ..} = self {
549            if expand_index.is_none() {
550                *expand_index = Some(index as u32)
551            }
552        }
553    }
554    
555    pub fn get_expr_expand_index(&self) -> Option<u32> {
556        match self {
557            Self::Expr {expand_index, ..} => *expand_index,
558            _ => None
559        }
560    }*/
561    
562    pub fn is_id(&self) -> bool {
563        matches!(self, Self::Id(_))
564    }
565    
566    pub fn is_color(&self) -> bool {
567        matches!(self, Self::Color(_))
568    }
569    
570    pub fn is_value_type(&self) -> bool {
571        matches!(self, Self::Id(_) |
572            Self::Str(_) |
573            Self::String(_) |
574            Self::InlineString {..} |
575            Self::Dependency {..} |
576            Self::Bool(_) |
577            Self::Int64(_) |
578            Self::Uint64(_) |
579            Self::Float64(_) |
580            Self::Float32(_) |
581            Self::Color(_) |
582            Self::Vec2(_) |
583            Self::Vec3(_) |
584            Self::Vec4(_))
585    }
586
587    pub fn is_single_node(&self) -> bool {
588        self.is_value_type() || match self {
589            Self::None=> true,
590            Self::Id(_) |
591            Self::IdPath(_) |
592            Self::BareEnum(_) => true,
593            _ => false
594        }
595    }
596    
597    pub fn is_structy_type(&self) -> bool {
598        match self {
599            Self::Object | // subnodes including this one
600            Self::Clone {..} | // subnodes including this one
601            Self::Class {..} => true, // subnodes including this one
602            _ => false
603        }
604    }
605    
606    pub fn is_number_type(&self) -> bool {
607        matches!(self, Self::Int64(_) |
608            Self::Float32(_) |
609            Self::Float64(_))
610    }
611    
612    pub fn as_float(&self) -> Option<f64> {
613        match self {
614            Self::Float64(v) => Some(*v),
615            Self::Float32(v) => Some(*v as f64),
616            Self::Int64(v) => Some(*v as f64),
617            Self::Uint64(v) => Some(*v as f64),
618            _ => None
619        }
620    }
621
622    pub fn as_int(&self) -> Option<i64> {
623        match self {
624            Self::Float64(v) => Some(*v as i64),
625            Self::Float32(v) => Some(*v as i64),
626            Self::Int64(v) => Some(*v),
627            Self::Uint64(v) => Some(*v as i64),
628            _ => None
629        }
630    }    
631    pub fn as_vec2(&self) -> Option<Vec2> {
632        match self {
633            Self::Vec2(v) => Some(*v),
634            _ => None
635        }
636    }
637    pub fn as_vec3(&self) -> Option<Vec3> {
638        match self {
639            Self::Vec3(v) => Some(*v),
640            _ => None
641        }
642    }
643    
644    pub fn as_vec4(&self) -> Option<Vec4> {
645        match self {
646            Self::Vec4(v) => Some(*v),
647            Self::Color(c) => Some(Vec4::from_u32(*c)),
648            _ => None
649        }
650    }
651    
652    pub fn as_bool(&self) -> Option<bool> {
653        match self {
654            Self::Bool(v) => Some(*v),
655            _ => None
656        }
657    }
658    
659    pub fn enum_eq(&self, id_eq:&[LiveId])->LiveValue{
660        match self{
661            Self::BareEnum(id) if *id == id_eq[0]=>{
662                LiveValue::Bool(true)
663            }
664            _=>LiveValue::Bool(false)
665        }
666    }
667    
668    pub fn enum_neq(&self, id_eq:&[LiveId])->LiveValue{
669        match self{
670            Self::BareEnum(id) if *id != id_eq[0]=>{
671                LiveValue::Bool(true)
672            }
673            _=>LiveValue::Bool(false)
674        }
675    }
676    /*
677    pub fn named_class_id(&self) -> Option<Id> {
678        match self {
679            Self::Class {class} => Some(*class),
680            _ => None
681        }
682    }*/
683    
684    pub fn set_clone_name(&mut self, set_name: LiveId) {
685        if let Self::Clone{clone,..} = self {
686            *clone = set_name
687        }
688    }
689    
690    pub fn get_clone_name(&self) -> LiveId {
691        match self {
692            Self::Clone{clone,..} => *clone,
693            _ => LiveId(0)
694        }
695    }
696    
697    pub fn variant_id(&self) -> usize {
698        match self {
699            Self::None => 0,
700            Self::Str(_) => 1,
701            Self::String(_) => 2,
702            Self::InlineString {..} => 3,
703            Self::Dependency {..} => 4,
704            Self::Bool(_) => 5,
705            Self::Int64(_) => 6,
706            Self::Uint64(_) => 7,
707            Self::Float64(_) => 8,
708            Self::Float32(_) => 9,
709            Self::Color(_) => 10,
710            Self::Vec2(_) => 11,
711            Self::Vec3(_) => 12,
712            Self::Vec4(_) => 13,
713            Self::Id(_) => 14,
714            Self::IdPath{..}=>15,
715            Self::ExprBinOp(_) => 16,
716            Self::ExprUnOp(_) => 17,
717            Self::ExprMember(_) => 18,
718            Self::ExprCall {..} => 19,
719            
720            Self::BareEnum {..} => 20,
721            Self::Array => 21,
722            Self::Expr {..} => 22,
723            Self::TupleEnum {..} => 23,
724            Self::NamedEnum {..} => 24,
725            Self::Object => 25,
726            Self::Clone {..} => 26,
727            Self::Class {..} => 27,
728            Self::Deref {..} => 28,
729            Self::Root{..}=>29,
730            Self::Close => 30,
731            
732            Self::DSL {..} => 31,
733            Self::Import {..} => 32,
734            Self::Font {..} => 33,
735            //Self::Registry {..} => 30,
736        }
737    }
738}
739
740impl Deref for LiveNode {
741    type Target = LiveValue;
742    fn deref(&self) -> &Self::Target {&self.value}
743}
744
745impl DerefMut for LiveNode {
746    fn deref_mut(&mut self) -> &mut Self::Target {&mut self.value}
747}
748