1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
// Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation
// Copyright (C) 2020 Stacks Open Internet Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

use crate::vm::errors::RuntimeErrorType;
use crate::vm::types::{TraitIdentifier, Value};
use regex::Regex;
use stacks_common::codec::Error as codec_error;
use stacks_common::codec::{read_next, write_next, StacksMessageCodec};
use std::borrow::Borrow;

use std::convert::TryFrom;
use std::fmt;
use std::io::{Read, Write};
use std::ops::Deref;

pub const CONTRACT_MIN_NAME_LENGTH: usize = 1;
pub const CONTRACT_MAX_NAME_LENGTH: usize = 40;
pub const MAX_STRING_LEN: u8 = 128;

lazy_static! {
    pub static ref STANDARD_PRINCIPAL_REGEX_STRING: String =
        "[0123456789ABCDEFGHJKMNPQRSTVWXYZ]{28,41}".into();
    pub static ref CONTRACT_NAME_REGEX_STRING: String = format!(
        r#"([a-zA-Z](([a-zA-Z0-9]|[-_])){{{},{}}})"#,
        CONTRACT_MIN_NAME_LENGTH - 1,
        // NOTE: this is deliberate.  Earlier versions of the node will accept contract principals whose names are up to
        // 128 bytes.  This behavior must be preserved for backwards-compatibility.
        MAX_STRING_LEN - 1
    );
    pub static ref CONTRACT_PRINCIPAL_REGEX_STRING: String = format!(
        r#"{}(\.){}"#,
        *STANDARD_PRINCIPAL_REGEX_STRING, *CONTRACT_NAME_REGEX_STRING
    );
    pub static ref PRINCIPAL_DATA_REGEX_STRING: String = format!(
        "({})|({})",
        *STANDARD_PRINCIPAL_REGEX_STRING, *CONTRACT_PRINCIPAL_REGEX_STRING
    );
    pub static ref CLARITY_NAME_REGEX_STRING: String =
        "^[a-zA-Z]([a-zA-Z0-9]|[-_!?+<>=/*])*$|^[-+=/*]$|^[<>]=?$".into();
    pub static ref CLARITY_NAME_REGEX: Regex =
        Regex::new(CLARITY_NAME_REGEX_STRING.as_str()).unwrap();
    pub static ref CONTRACT_NAME_REGEX: Regex =
        Regex::new(format!("^{}$|^__transient$", CONTRACT_NAME_REGEX_STRING.as_str()).as_str())
            .unwrap();
}

guarded_string!(
    ClarityName,
    "ClarityName",
    CLARITY_NAME_REGEX,
    RuntimeErrorType,
    RuntimeErrorType::BadNameValue
);
guarded_string!(
    ContractName,
    "ContractName",
    CONTRACT_NAME_REGEX,
    RuntimeErrorType,
    RuntimeErrorType::BadNameValue
);

impl StacksMessageCodec for ClarityName {
    fn consensus_serialize<W: Write>(&self, fd: &mut W) -> Result<(), codec_error> {
        // ClarityName can't be longer than vm::representations::MAX_STRING_LEN, which itself is
        // a u8, so we should be good here.
        if self.as_bytes().len() > MAX_STRING_LEN as usize {
            return Err(codec_error::SerializeError(
                "Failed to serialize clarity name: too long".to_string(),
            ));
        }
        write_next(fd, &(self.as_bytes().len() as u8))?;
        fd.write_all(self.as_bytes())
            .map_err(codec_error::WriteError)?;
        Ok(())
    }

    fn consensus_deserialize<R: Read>(fd: &mut R) -> Result<ClarityName, codec_error> {
        let len_byte: u8 = read_next(fd)?;
        if len_byte > MAX_STRING_LEN {
            return Err(codec_error::DeserializeError(
                "Failed to deserialize clarity name: too long".to_string(),
            ));
        }
        let mut bytes = vec![0u8; len_byte as usize];
        fd.read_exact(&mut bytes).map_err(codec_error::ReadError)?;

        // must encode a valid string
        let s = String::from_utf8(bytes).map_err(|_e| {
            codec_error::DeserializeError(
                "Failed to parse Clarity name: could not contruct from utf8".to_string(),
            )
        })?;

        // must decode to a clarity name
        let name = ClarityName::try_from(s).map_err(|e| {
            codec_error::DeserializeError(format!("Failed to parse Clarity name: {:?}", e))
        })?;
        Ok(name)
    }
}

impl StacksMessageCodec for ContractName {
    fn consensus_serialize<W: Write>(&self, fd: &mut W) -> Result<(), codec_error> {
        if self.as_bytes().len() < CONTRACT_MIN_NAME_LENGTH as usize
            || self.as_bytes().len() > CONTRACT_MAX_NAME_LENGTH as usize
        {
            return Err(codec_error::SerializeError(format!(
                "Failed to serialize contract name: too short or too long: {}",
                self.as_bytes().len()
            )));
        }
        write_next(fd, &(self.as_bytes().len() as u8))?;
        fd.write_all(self.as_bytes())
            .map_err(codec_error::WriteError)?;
        Ok(())
    }

    fn consensus_deserialize<R: Read>(fd: &mut R) -> Result<ContractName, codec_error> {
        let len_byte: u8 = read_next(fd)?;
        if (len_byte as usize) < CONTRACT_MIN_NAME_LENGTH
            || (len_byte as usize) > CONTRACT_MAX_NAME_LENGTH
        {
            return Err(codec_error::DeserializeError(format!(
                "Failed to deserialize contract name: too short or too long: {}",
                len_byte
            )));
        }
        let mut bytes = vec![0u8; len_byte as usize];
        fd.read_exact(&mut bytes).map_err(codec_error::ReadError)?;

        // must encode a valid string
        let s = String::from_utf8(bytes).map_err(|_e| {
            codec_error::DeserializeError(
                "Failed to parse Contract name: could not construct from utf8".to_string(),
            )
        })?;

        let name = ContractName::try_from(s).map_err(|e| {
            codec_error::DeserializeError(format!("Failed to parse Contract name: {:?}", e))
        })?;
        Ok(name)
    }
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub enum PreSymbolicExpressionType {
    AtomValue(Value),
    Atom(ClarityName),
    List(Box<[PreSymbolicExpression]>),
    Tuple(Box<[PreSymbolicExpression]>),
    SugaredContractIdentifier(ContractName),
    SugaredFieldIdentifier(ContractName, ClarityName),
    FieldIdentifier(TraitIdentifier),
    TraitReference(ClarityName),
    Comment(String),
    Placeholder(String),
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct PreSymbolicExpression {
    pub pre_expr: PreSymbolicExpressionType,
    pub id: u64,

    #[cfg(feature = "developer-mode")]
    pub span: Span,
}

pub trait SymbolicExpressionCommon {
    type S: SymbolicExpressionCommon;
    fn set_id(&mut self, id: u64);
    fn match_list_mut(&mut self) -> Option<&mut [Self::S]>;
}

impl SymbolicExpressionCommon for PreSymbolicExpression {
    type S = PreSymbolicExpression;
    fn set_id(&mut self, id: u64) {
        self.id = id;
    }
    fn match_list_mut(&mut self) -> Option<&mut [PreSymbolicExpression]> {
        if let PreSymbolicExpressionType::List(ref mut list) = self.pre_expr {
            Some(list)
        } else {
            None
        }
    }
}

impl SymbolicExpressionCommon for SymbolicExpression {
    type S = SymbolicExpression;
    fn set_id(&mut self, id: u64) {
        self.id = id;
    }
    fn match_list_mut(&mut self) -> Option<&mut [SymbolicExpression]> {
        if let SymbolicExpressionType::List(ref mut list) = self.expr {
            Some(list)
        } else {
            None
        }
    }
}

impl PreSymbolicExpression {
    #[cfg(feature = "developer-mode")]
    fn cons() -> PreSymbolicExpression {
        PreSymbolicExpression {
            id: 0,
            span: Span::zero(),
            pre_expr: PreSymbolicExpressionType::AtomValue(Value::Bool(false)),
        }
    }
    #[cfg(not(feature = "developer-mode"))]
    fn cons() -> PreSymbolicExpression {
        PreSymbolicExpression {
            id: 0,
            pre_expr: PreSymbolicExpressionType::AtomValue(Value::Bool(false)),
        }
    }

    #[cfg(feature = "developer-mode")]
    pub fn set_span(&mut self, start_line: u32, start_column: u32, end_line: u32, end_column: u32) {
        self.span = Span {
            start_line,
            start_column,
            end_line,
            end_column,
        }
    }

    #[cfg(not(feature = "developer-mode"))]
    pub fn set_span(
        &mut self,
        _start_line: u32,
        _start_column: u32,
        _end_line: u32,
        _end_column: u32,
    ) {
    }

    pub fn sugared_contract_identifier(val: ContractName) -> PreSymbolicExpression {
        PreSymbolicExpression {
            pre_expr: PreSymbolicExpressionType::SugaredContractIdentifier(val),
            ..PreSymbolicExpression::cons()
        }
    }

    pub fn sugared_field_identifier(
        contract_name: ContractName,
        name: ClarityName,
    ) -> PreSymbolicExpression {
        PreSymbolicExpression {
            pre_expr: PreSymbolicExpressionType::SugaredFieldIdentifier(contract_name, name),
            ..PreSymbolicExpression::cons()
        }
    }

    pub fn atom_value(val: Value) -> PreSymbolicExpression {
        PreSymbolicExpression {
            pre_expr: PreSymbolicExpressionType::AtomValue(val),
            ..PreSymbolicExpression::cons()
        }
    }

    pub fn atom(val: ClarityName) -> PreSymbolicExpression {
        PreSymbolicExpression {
            pre_expr: PreSymbolicExpressionType::Atom(val),
            ..PreSymbolicExpression::cons()
        }
    }

    pub fn trait_reference(val: ClarityName) -> PreSymbolicExpression {
        PreSymbolicExpression {
            pre_expr: PreSymbolicExpressionType::TraitReference(val),
            ..PreSymbolicExpression::cons()
        }
    }

    pub fn field_identifier(val: TraitIdentifier) -> PreSymbolicExpression {
        PreSymbolicExpression {
            pre_expr: PreSymbolicExpressionType::FieldIdentifier(val),
            ..PreSymbolicExpression::cons()
        }
    }

    pub fn list(val: Box<[PreSymbolicExpression]>) -> PreSymbolicExpression {
        PreSymbolicExpression {
            pre_expr: PreSymbolicExpressionType::List(val),
            ..PreSymbolicExpression::cons()
        }
    }

    pub fn tuple(val: Box<[PreSymbolicExpression]>) -> PreSymbolicExpression {
        PreSymbolicExpression {
            pre_expr: PreSymbolicExpressionType::Tuple(val),
            ..PreSymbolicExpression::cons()
        }
    }

    pub fn placeholder(s: String) -> PreSymbolicExpression {
        PreSymbolicExpression {
            pre_expr: PreSymbolicExpressionType::Placeholder(s),
            ..PreSymbolicExpression::cons()
        }
    }

    pub fn comment(comment: String) -> PreSymbolicExpression {
        PreSymbolicExpression {
            pre_expr: PreSymbolicExpressionType::Comment(comment),
            ..PreSymbolicExpression::cons()
        }
    }

    pub fn match_trait_reference(&self) -> Option<&ClarityName> {
        if let PreSymbolicExpressionType::TraitReference(ref value) = self.pre_expr {
            Some(value)
        } else {
            None
        }
    }

    pub fn match_atom_value(&self) -> Option<&Value> {
        if let PreSymbolicExpressionType::AtomValue(ref value) = self.pre_expr {
            Some(value)
        } else {
            None
        }
    }

    pub fn match_atom(&self) -> Option<&ClarityName> {
        if let PreSymbolicExpressionType::Atom(ref value) = self.pre_expr {
            Some(value)
        } else {
            None
        }
    }

    pub fn match_list(&self) -> Option<&[PreSymbolicExpression]> {
        if let PreSymbolicExpressionType::List(ref list) = self.pre_expr {
            Some(list)
        } else {
            None
        }
    }

    pub fn match_field_identifier(&self) -> Option<&TraitIdentifier> {
        if let PreSymbolicExpressionType::FieldIdentifier(ref value) = self.pre_expr {
            Some(value)
        } else {
            None
        }
    }

    pub fn match_placeholder(&self) -> Option<&str> {
        if let PreSymbolicExpressionType::Placeholder(ref s) = self.pre_expr {
            Some(s.as_str())
        } else {
            None
        }
    }

    pub fn match_comment(&self) -> Option<&str> {
        if let PreSymbolicExpressionType::Comment(ref s) = self.pre_expr {
            Some(s.as_str())
        } else {
            None
        }
    }
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub enum SymbolicExpressionType {
    AtomValue(Value),
    Atom(ClarityName),
    List(Box<[SymbolicExpression]>),
    LiteralValue(Value),
    Field(TraitIdentifier),
    TraitReference(ClarityName, TraitDefinition),
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub enum TraitDefinition {
    Defined(TraitIdentifier),
    Imported(TraitIdentifier),
}

pub fn depth_traverse<F, T, E>(expr: &SymbolicExpression, mut visit: F) -> Result<T, E>
where
    F: FnMut(&SymbolicExpression) -> Result<T, E>,
{
    let mut stack = vec![];
    let mut last = None;
    stack.push(expr);
    while let Some(current) = stack.pop() {
        last = Some(visit(current)?);
        if let Some(list) = current.match_list() {
            for item in list.iter() {
                stack.push(item);
            }
        }
    }

    Ok(last.unwrap())
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct SymbolicExpression {
    pub expr: SymbolicExpressionType,
    // this id field is used by compiler passes to store information in
    //  maps.
    // first pass       -> fill out unique ids
    // ...typing passes -> store information in hashmap according to id.
    //
    // this is a fairly standard technique in compiler passes
    pub id: u64,

    #[cfg(feature = "developer-mode")]
    pub span: Span,
}

impl SymbolicExpression {
    #[cfg(feature = "developer-mode")]
    fn cons() -> SymbolicExpression {
        SymbolicExpression {
            id: 0,
            span: Span::zero(),
            expr: SymbolicExpressionType::AtomValue(Value::Bool(false)),
        }
    }
    #[cfg(not(feature = "developer-mode"))]
    fn cons() -> SymbolicExpression {
        SymbolicExpression {
            id: 0,
            expr: SymbolicExpressionType::AtomValue(Value::Bool(false)),
        }
    }

    #[cfg(feature = "developer-mode")]
    pub fn set_span(&mut self, start_line: u32, start_column: u32, end_line: u32, end_column: u32) {
        self.span = Span {
            start_line,
            start_column,
            end_line,
            end_column,
        }
    }

    #[cfg(not(feature = "developer-mode"))]
    pub fn set_span(
        &mut self,
        _start_line: u32,
        _start_column: u32,
        _end_line: u32,
        _end_column: u32,
    ) {
    }

    pub fn atom_value(val: Value) -> SymbolicExpression {
        SymbolicExpression {
            expr: SymbolicExpressionType::AtomValue(val),
            ..SymbolicExpression::cons()
        }
    }

    pub fn atom(val: ClarityName) -> SymbolicExpression {
        SymbolicExpression {
            expr: SymbolicExpressionType::Atom(val),
            ..SymbolicExpression::cons()
        }
    }

    pub fn literal_value(val: Value) -> SymbolicExpression {
        SymbolicExpression {
            expr: SymbolicExpressionType::LiteralValue(val),
            ..SymbolicExpression::cons()
        }
    }

    pub fn list(val: Box<[SymbolicExpression]>) -> SymbolicExpression {
        SymbolicExpression {
            expr: SymbolicExpressionType::List(val),
            ..SymbolicExpression::cons()
        }
    }

    pub fn trait_reference(
        val: ClarityName,
        trait_definition: TraitDefinition,
    ) -> SymbolicExpression {
        SymbolicExpression {
            expr: SymbolicExpressionType::TraitReference(val, trait_definition),
            ..SymbolicExpression::cons()
        }
    }

    pub fn field(val: TraitIdentifier) -> SymbolicExpression {
        SymbolicExpression {
            expr: SymbolicExpressionType::Field(val),
            ..SymbolicExpression::cons()
        }
    }

    // These match functions are used to simplify calling code
    //   areas a lot. There is a frequent code pattern where
    //   a block _expects_ specific symbolic expressions, leading
    //   to a lot of very verbose `if let x = {` expressions.

    pub fn match_list(&self) -> Option<&[SymbolicExpression]> {
        if let SymbolicExpressionType::List(ref list) = self.expr {
            Some(list)
        } else {
            None
        }
    }

    pub fn match_atom(&self) -> Option<&ClarityName> {
        if let SymbolicExpressionType::Atom(ref value) = self.expr {
            Some(value)
        } else {
            None
        }
    }

    pub fn match_atom_value(&self) -> Option<&Value> {
        if let SymbolicExpressionType::AtomValue(ref value) = self.expr {
            Some(value)
        } else {
            None
        }
    }

    pub fn match_literal_value(&self) -> Option<&Value> {
        if let SymbolicExpressionType::LiteralValue(ref value) = self.expr {
            Some(value)
        } else {
            None
        }
    }

    pub fn match_trait_reference(&self) -> Option<&ClarityName> {
        if let SymbolicExpressionType::TraitReference(ref value, _) = self.expr {
            Some(value)
        } else {
            None
        }
    }

    pub fn match_field(&self) -> Option<&TraitIdentifier> {
        if let SymbolicExpressionType::Field(ref value) = self.expr {
            Some(value)
        } else {
            None
        }
    }
}

impl fmt::Display for SymbolicExpression {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.expr {
            SymbolicExpressionType::List(ref list) => {
                write!(f, "(")?;
                for item in list.iter() {
                    write!(f, " {}", item)?;
                }
                write!(f, " )")?;
            }
            SymbolicExpressionType::Atom(ref value) => {
                write!(f, "{}", &**value)?;
            }
            SymbolicExpressionType::AtomValue(ref value)
            | SymbolicExpressionType::LiteralValue(ref value) => {
                write!(f, "{}", value)?;
            }
            SymbolicExpressionType::TraitReference(ref value, _) => {
                write!(f, "<{}>", &**value)?;
            }
            SymbolicExpressionType::Field(ref value) => {
                write!(f, "<{}>", value)?;
            }
        };

        Ok(())
    }
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Span {
    pub start_line: u32,
    pub start_column: u32,
    pub end_line: u32,
    pub end_column: u32,
}

impl Span {
    pub fn zero() -> Span {
        Span {
            start_line: 0,
            start_column: 0,
            end_line: 0,
            end_column: 0,
        }
    }
}