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
use std::collections::{BTreeMap, HashMap, HashSet};
use std::convert::TryFrom;
use std::fmt::Display;

use crate::clarity::contexts::{Environment, LocalContext};
use crate::clarity::database::ClarityDatabase;
use crate::clarity::diagnostic::Level;
use crate::clarity::errors::Error;
use crate::clarity::eval;
use crate::clarity::functions::NativeFunctions;
use crate::clarity::representations::Span;
use crate::clarity::representations::SymbolicExpression;
use crate::clarity::types::{QualifiedContractIdentifier, StandardPrincipalData, Value};
use crate::clarity::{ContractName, SymbolicExpressionType};
use crate::repl::ast::build_ast;

use super::contracts::Contract;
use super::EvalHook;

#[cfg(feature = "cli")]
pub mod cli;
#[cfg(feature = "dap")]
pub mod dap;

#[derive(Clone)]
pub struct Source {
    name: QualifiedContractIdentifier,
}

impl Display for Source {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.name)
    }
}

pub struct Breakpoint {
    id: usize,
    verified: bool,
    data: BreakpointData,
    source: Source,
    span: Option<Span>,
}

impl Display for Breakpoint {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}: {}{}", self.id, self.source, self.data)
    }
}

pub enum BreakpointData {
    Source(SourceBreakpoint),
    Function(FunctionBreakpoint),
    Data(DataBreakpoint),
}

impl Display for BreakpointData {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            BreakpointData::Source(source) => write!(f, "{}", source),
            BreakpointData::Function(function) => write!(f, "{}", function),
            BreakpointData::Data(data) => write!(f, "{}", data),
        }
    }
}

#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
pub struct SourceBreakpoint {
    line: u32,
    column: Option<u32>,
}

impl Display for SourceBreakpoint {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let column = if let Some(column) = self.column {
            format!(":{}", column)
        } else {
            String::new()
        };
        write!(f, ":{}{}", self.line, column)
    }
}

#[derive(Clone, Copy, PartialEq, Debug)]
pub enum AccessType {
    Read,
    Write,
    ReadWrite,
}

impl Display for AccessType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AccessType::Read => write!(f, "(r)"),
            AccessType::Write => write!(f, "(w)"),
            AccessType::ReadWrite => write!(f, "(rw)"),
        }
    }
}

pub struct DataBreakpoint {
    name: String,
    access_type: AccessType,
}

impl Display for DataBreakpoint {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, ".{} {}", self.name, self.access_type)
    }
}

pub struct FunctionBreakpoint {
    name: String,
}

impl Display for FunctionBreakpoint {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, ".{}", self.name)
    }
}

#[derive(PartialEq, Debug, Clone)]
pub(crate) enum State {
    Start,
    Continue,
    StepOver(u64),
    StepIn,
    Finish(u64),
    Finished,
    Break(usize),
    DataBreak(usize, AccessType),
    Pause,
    Quit,
}

struct ExprState {
    id: u64,
    active_breakpoints: Vec<usize>,
}

impl ExprState {
    pub fn new(id: u64) -> ExprState {
        ExprState {
            id,
            active_breakpoints: Vec::new(),
        }
    }
}

impl PartialEq for ExprState {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id
    }
}

pub struct DebugState {
    breakpoints: BTreeMap<usize, Breakpoint>,
    watchpoints: BTreeMap<usize, Breakpoint>,
    break_locations: HashMap<QualifiedContractIdentifier, HashSet<usize>>,
    watch_variables: HashMap<(QualifiedContractIdentifier, String), HashSet<usize>>,
    active_breakpoints: HashSet<usize>,
    state: State,
    stack: Vec<ExprState>,
    unique_id: usize,
    debug_cmd_contract: QualifiedContractIdentifier,
    debug_cmd_source: String,
}

impl DebugState {
    pub fn new(contract_id: &QualifiedContractIdentifier, snippet: &str) -> DebugState {
        DebugState {
            breakpoints: BTreeMap::new(),
            watchpoints: BTreeMap::new(),
            break_locations: HashMap::new(),
            watch_variables: HashMap::new(),
            active_breakpoints: HashSet::new(),
            state: State::Start,
            stack: Vec::new(),
            unique_id: 0,
            debug_cmd_contract: contract_id.clone(),
            debug_cmd_source: snippet.to_string(),
        }
    }

    fn get_unique_id(&mut self) -> usize {
        self.unique_id += 1;
        self.unique_id
    }

    fn continue_execution(&mut self) {
        self.state = State::Continue;
    }

    fn step_over(&mut self, id: u64) {
        self.state = State::StepOver(id);
    }

    fn step_in(&mut self) {
        self.state = State::StepIn;
    }

    fn finish(&mut self) {
        if self.stack.len() >= 2 {
            self.state = State::Finish(self.stack[self.stack.len() - 2].id);
        } else {
            self.state = State::Continue;
        }
    }

    fn quit(&mut self) {
        self.state = State::Quit;
    }

    fn add_breakpoint(&mut self, mut breakpoint: Breakpoint) -> usize {
        let id = self.get_unique_id();
        breakpoint.id = id;

        if let Some(set) = self.break_locations.get_mut(&breakpoint.source.name) {
            set.insert(breakpoint.id);
        } else {
            let mut set = HashSet::new();
            set.insert(id);
            self.break_locations
                .insert(breakpoint.source.name.clone(), set);
        }

        self.breakpoints.insert(id, breakpoint);
        id
    }

    fn delete_all_breakpoints(&mut self) {
        for (id, breakpoint) in &self.breakpoints {
            let set = self
                .break_locations
                .get_mut(&breakpoint.source.name)
                .unwrap();
            set.remove(&breakpoint.id);
        }
        self.breakpoints.clear();
    }

    fn delete_breakpoint(&mut self, id: usize) -> bool {
        if let Some(breakpoint) = self.breakpoints.remove(&id) {
            let set = self
                .break_locations
                .get_mut(&breakpoint.source.name)
                .unwrap();
            set.remove(&breakpoint.id);
            true
        } else {
            false
        }
    }

    fn add_watchpoint(
        &mut self,
        contract_id: &QualifiedContractIdentifier,
        name: &str,
        access_type: AccessType,
    ) {
        let breakpoint = Breakpoint {
            id: self.get_unique_id(),
            verified: true,
            data: BreakpointData::Data(DataBreakpoint {
                name: name.to_string(),
                access_type,
            }),
            source: Source {
                name: contract_id.clone(),
            },
            span: None,
        };
        let name = match &breakpoint.data {
            BreakpointData::Data(data) => data.name.clone(),
            _ => panic!("called add_watchpoint with non-data breakpoint"),
        };

        let key = (breakpoint.source.name.clone(), name);
        if let Some(set) = self.watch_variables.get_mut(&key) {
            set.insert(breakpoint.id);
        } else {
            let mut set = HashSet::new();
            set.insert(breakpoint.id);
            self.watch_variables.insert(key, set);
        }

        self.watchpoints.insert(breakpoint.id, breakpoint);
    }

    fn delete_all_watchpoints(&mut self) {
        for (id, breakpoint) in &self.watchpoints {
            let name = match &breakpoint.data {
                BreakpointData::Data(data) => data.name.clone(),
                _ => continue,
            };
            let set = self
                .watch_variables
                .get_mut(&(breakpoint.source.name.clone(), name))
                .unwrap();
            set.remove(&breakpoint.id);
        }
        self.watchpoints.clear();
    }

    fn delete_watchpoint(&mut self, id: usize) -> bool {
        if let Some(breakpoint) = self.watchpoints.remove(&id) {
            let name = match breakpoint.data {
                BreakpointData::Data(data) => data.name,
                _ => panic!("called delete_watchpoint with non-data breakpoint"),
            };
            let set = self
                .watch_variables
                .get_mut(&(breakpoint.source.name, name))
                .unwrap();
            set.remove(&breakpoint.id);
            true
        } else {
            false
        }
    }

    fn pause(&mut self) {
        self.state = State::Pause;
    }

    fn evaluate(
        &mut self,
        env: &mut Environment,
        context: &LocalContext,
        snippet: &str,
    ) -> Result<Value, Vec<String>> {
        let contract_id = QualifiedContractIdentifier::transient();
        let lines = snippet.lines();
        let formatted_lines: Vec<String> = lines.map(|l| l.to_string()).collect();
        let (ast, mut diagnostics, success) = build_ast(&contract_id, snippet, &mut ());
        if ast.expressions.len() != 1 {
            return Err(vec!["expected a single expression".to_string()]);
        }
        if !success {
            let mut errors = Vec::new();
            for diagnostic in diagnostics.drain(..).filter(|d| d.level == Level::Error) {
                errors.append(&mut diagnostic.output("print expression", &formatted_lines));
            }
            return Err(errors);
        }

        match eval(&ast.expressions[0], env, &context) {
            Ok(value) => Ok(value),
            Err(e) => Err(vec![format!("{}: {}", red!("error"), e)]),
        }
    }

    fn did_hit_source_breakpoint(
        &self,
        contract_id: &QualifiedContractIdentifier,
        span: &Span,
    ) -> Option<usize> {
        if let Some(set) = self.break_locations.get(contract_id) {
            for id in set {
                // Don't break in a subexpression of an expression which has
                // already triggered this breakpoint
                if self.active_breakpoints.contains(id) {
                    continue;
                }

                let breakpoint = match self.breakpoints.get(id) {
                    Some(breakpoint) => breakpoint,
                    None => panic!("internal error: breakpoint {} not found", id),
                };

                if let Some(break_span) = &breakpoint.span {
                    if break_span.start_line == span.start_line
                        && (break_span.start_column == 0
                            || break_span.start_column == span.start_column)
                    {
                        return Some(breakpoint.id);
                    }
                }
            }
        }
        None
    }

    fn did_hit_data_breakpoint(
        &self,
        contract_id: &QualifiedContractIdentifier,
        expr: &SymbolicExpression,
    ) -> Option<(usize, AccessType)> {
        match &expr.expr {
            SymbolicExpressionType::List(list) => {
                // Check if we hit a data breakpoint
                if let Some((function_name, args)) = list.split_first() {
                    if let Some(function_name) = function_name.match_atom() {
                        if let Some(native_function) =
                            NativeFunctions::lookup_by_name(function_name)
                        {
                            use crate::clarity::functions::NativeFunctions::*;
                            if let Some((name, access_type)) = match native_function {
                                FetchVar => Some((
                                    args[0].match_atom().unwrap().to_string(),
                                    AccessType::Read,
                                )),
                                SetVar => Some((
                                    args[0].match_atom().unwrap().to_string(),
                                    AccessType::Write,
                                )),
                                FetchEntry => Some((
                                    args[0].match_atom().unwrap().to_string(),
                                    AccessType::Read,
                                )),
                                SetEntry => Some((
                                    args[0].match_atom().unwrap().to_string(),
                                    AccessType::Write,
                                )),
                                InsertEntry => Some((
                                    args[0].match_atom().unwrap().to_string(),
                                    AccessType::Write,
                                )),
                                DeleteEntry => Some((
                                    args[0].match_atom().unwrap().to_string(),
                                    AccessType::Write,
                                )),
                                _ => None,
                            } {
                                let key = (contract_id.clone(), name);
                                if let Some(set) = self.watch_variables.get(&key) {
                                    for id in set {
                                        let watchpoint = match self.watchpoints.get(id) {
                                            Some(watchpoint) => watchpoint,
                                            None => panic!(
                                                "internal error: watchpoint {} not found",
                                                id
                                            ),
                                        };

                                        if let BreakpointData::Data(data) = &watchpoint.data {
                                            match (data.access_type, access_type) {
                                                (AccessType::Read, AccessType::Read)
                                                | (AccessType::Write, AccessType::Write)
                                                | (AccessType::ReadWrite, AccessType::Read)
                                                | (AccessType::ReadWrite, AccessType::Write) => {
                                                    return Some((watchpoint.id, access_type))
                                                }
                                                _ => (),
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                None
            }
            _ => None,
        }
    }

    // Returns a bool which indicates if execution should resume (true) or if
    // it should wait for input (false).
    fn will_begin_eval(
        &mut self,
        env: &mut Environment,
        context: &LocalContext,
        expr: &SymbolicExpression,
    ) -> bool {
        self.stack.push(ExprState::new(expr.id));

        // If user quit debug session, we can't stop executing, but don't do anything else.
        if self.state == State::Quit {
            return true;
        }

        // Check if we have hit a source breakpoint
        if let Some(breakpoint) =
            self.did_hit_source_breakpoint(&env.contract_context.contract_identifier, &expr.span)
        {
            self.active_breakpoints.insert(breakpoint);
            let top = self.stack.last_mut().unwrap();
            top.active_breakpoints.push(breakpoint);

            self.state = State::Break(breakpoint);
        }

        // Always skip over non-list expressions (values).
        match expr.expr {
            SymbolicExpressionType::List(_) => (),
            _ => return true,
        };

        if let Some((watchpoint, access_type)) =
            self.did_hit_data_breakpoint(&env.contract_context.contract_identifier, expr)
        {
            self.state = State::DataBreak(watchpoint, access_type);
        }

        match self.state {
            State::Continue | State::Quit | State::Finish(_) => return true,
            State::StepOver(step_over_id) => {
                if self
                    .stack
                    .iter()
                    .find(|&state| state.id == step_over_id)
                    .is_some()
                {
                    // We're still inside the expression which should be stepped over,
                    // so return to execution.
                    return true;
                }
            }
            State::Start
            | State::StepIn
            | State::Break(_)
            | State::DataBreak(..)
            | State::Pause
            | State::Finished => (),
        };

        false
    }

    // Returns a bool which indicates if the result should be printed (finish)
    fn did_finish_eval(
        &mut self,
        env: &mut Environment,
        context: &LocalContext,
        expr: &SymbolicExpression,
        res: &Result<Value, Error>,
    ) -> bool {
        let state = self.stack.pop().unwrap();
        assert_eq!(state.id, expr.id);

        // Remove any active breakpoints for this expression
        for breakpoint in state.active_breakpoints {
            self.active_breakpoints.remove(&breakpoint);
        }

        // Only print the returned value if this resolves a finish command
        match self.state {
            State::Finish(finish_id) if finish_id == state.id => {
                self.state = State::Finished;
                true
            }
            _ => false,
        }
    }
}

pub fn extract_watch_variable<'a>(
    env: &mut Environment,
    expr: &'a str,
    default_sender: Option<&StandardPrincipalData>,
) -> Result<(Contract, &'a str), String> {
    // Syntax could be:
    // - principal.contract.name
    // - .contract.name
    // - name
    let parts: Vec<&str> = expr.split('.').collect();
    let (contract_id, name) = match parts.len() {
        1 => {
            if default_sender.is_some() {
                return Err(format!("must use qualified name"));
            } else {
                (env.contract_context.contract_identifier.clone(), parts[0])
            }
        }
        3 => {
            let contract_id = if parts[0].is_empty() {
                if let Some(sender) = default_sender {
                    QualifiedContractIdentifier::new(
                        sender.clone(),
                        ContractName::try_from(parts[1]).unwrap(),
                    )
                } else {
                    QualifiedContractIdentifier::new(
                        env.contract_context.contract_identifier.issuer.clone(),
                        ContractName::try_from(parts[1]).unwrap(),
                    )
                }
            } else {
                match QualifiedContractIdentifier::parse(expr.rsplit_once('.').unwrap().0) {
                    Ok(contract_identifier) => contract_identifier,
                    Err(e) => {
                        return Err(format!(
                            "unable to parse watchpoint contract identifier: {}",
                            e
                        ));
                    }
                }
            };
            (contract_id, parts[2])
        }
        _ => return Err("invalid watchpoint format".to_string()),
    };

    let contract = if env.global_context.database.has_contract(&contract_id) {
        match env.global_context.database.get_contract(&contract_id) {
            Ok(contract) => contract,
            Err(e) => {
                return Err(format!("{}", e));
            }
        }
    } else {
        return Err(format!("{} does not exist", contract_id));
    };

    if contract.contract_context.meta_data_var.get(name).is_none()
        && contract.contract_context.meta_data_map.get(name).is_none()
    {
        return Err(format!("no such variable: {}.{}", contract_id, name));
    }

    Ok((contract, name))
}