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