ast-grep-config 0.42.0

Search and Rewrite code at large scale using precise AST pattern
Documentation
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
//! Parameterized utility rules have two parts:
//!
//! 1. Definition: declare a utility template and its parameters, for example
//!    `id: wrap` with `arguments: [BODY]`.
//! 2. Call: reference that template from `matches` and provide concrete rules
//!    for each parameter, for example `matches: { wrap: { BODY: ... } }`.
//!
//! This module contains both halves of that flow: parsing and validating
//! parameterized utility definitions, and lowering/executing parameterized
//! utility calls.
//!
//! At the moment, parameterized definitions are only supported for global
//! utilities. Local `utils:` entries cannot declare parameters.

use super::deserialize_env::DeserializeEnv;
use super::referent_rule::{ReferentRule, ReferentRuleError, RegistrationRef};
use super::{deserialize_rule, Rule, RuleSerializeError, SerializableRule};
use crate::RuleCore;

use ast_grep_core::language::Language;
use ast_grep_core::meta_var::{MetaVarEnv, MetaVariable};
use ast_grep_core::ops as o;
use ast_grep_core::{Doc, Matcher, Node};

use bit_set::BitSet;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use thiserror::Error;

use std::borrow::Cow;
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;

thread_local! {
  static VERIFY_STACK: RefCell<HashSet<String>> = RefCell::new(HashSet::new());
  static ARG_RULE_FRAME: RefCell<Option<Arc<BindingFrame>>> = const { RefCell::new(None) };
  static ARG_RULE_EXPORT_ENV: RefCell<Vec<*mut ()>> = const { RefCell::new(Vec::new()) };
}

#[derive(Clone)]
struct BindingFrame {
  bindings: Arc<HashMap<String, Arc<Rule>>>,
  parent: Option<Arc<BindingFrame>>,
}

type SerializableUtilityArgs = HashMap<String, SerializableRule>;
type SerializableUtilityCalls = HashMap<String, SerializableUtilityArgs>;
type SerializableUtilityItems = Vec<(String, SerializableUtilityArgs)>;

pub(crate) struct Def<M> {
  pub params: Vec<String>,
  pub matcher: M,
}

impl<M> Def<M> {
  pub(crate) fn new(params: Vec<String>, matcher: M) -> Self {
    Self { params, matcher }
  }
}

pub(crate) type GlobalTemplate = Def<RuleCore>;

#[derive(Debug, Error)]
pub enum ParameterizedUtilError {
  #[error("Utility id `{0}` contains reserved characters.")]
  InvalidUtilityId(String),
  #[error("Utility `{util}` declares invalid argument `{arg}`.")]
  InvalidUtilityArgument { util: String, arg: String },
  #[error("Utility `{util}` declares duplicate argument `{arg}`.")]
  DuplicateUtilityArgument { util: String, arg: String },
  #[error("Utility call must contain at least one callee.")]
  InvalidUtilityCall,
  #[error("Utility `{0}` requires arguments and cannot be used as `matches: {0}`.")]
  MissingUtilityArguments(String),
  #[error("Utility `{0}` does not accept arguments.")]
  UnexpectedUtilityArguments(String),
  #[error("Utility parameter `{0}` cannot be called with arguments.")]
  UtilityParameterCalled(String),
  #[error("Parameterized utility `{callee}` is missing argument `{arg}`.")]
  MissingUtilityArgument { callee: String, arg: String },
  #[error("Parameterized utility `{callee}` does not declare argument `{arg}`.")]
  UnknownUtilityArgument { callee: String, arg: String },
}

#[derive(Serialize, Deserialize, Clone, JsonSchema)]
#[serde(transparent)]
pub struct SerializableUtilityCall(pub SerializableUtilityCalls);

impl SerializableUtilityCall {
  pub(super) fn iter(&self) -> impl Iterator<Item = (&String, &SerializableUtilityArgs)> {
    self.0.iter()
  }

  fn into_items(self) -> Result<SerializableUtilityItems, ParameterizedUtilError> {
    if self.0.is_empty() {
      return Err(ParameterizedUtilError::InvalidUtilityCall);
    }
    Ok(self.0.into_iter().collect())
  }
}

fn contains_reserved_utility_chars(raw: &str) -> bool {
  raw.contains(['(', ')', ',', '='])
}

pub(super) fn validate_utility_id(raw: &str) -> Result<(), ParameterizedUtilError> {
  if raw.is_empty() || contains_reserved_utility_chars(raw) {
    return Err(ParameterizedUtilError::InvalidUtilityId(raw.into()));
  }
  Ok(())
}

pub(super) fn validate_utility_arguments(
  util: &str,
  params: &[String],
) -> Result<(), ParameterizedUtilError> {
  let mut seen = HashSet::new();
  for param in params {
    if param.is_empty() || contains_reserved_utility_chars(param) {
      return Err(ParameterizedUtilError::InvalidUtilityArgument {
        util: util.into(),
        arg: param.clone(),
      });
    }
    if !seen.insert(param.as_str()) {
      return Err(ParameterizedUtilError::DuplicateUtilityArgument {
        util: util.into(),
        arg: param.clone(),
      });
    }
  }
  Ok(())
}

pub(super) fn deserialize_utility_call_matches<L: Language>(
  call: SerializableUtilityCall,
  env: &DeserializeEnv<L>,
) -> Result<Rule, RuleSerializeError> {
  let mut rules = Vec::new();
  for (callee, args) in call.into_items()? {
    rules.push(lower_utility_call(callee, args, env)?);
  }
  if rules.len() == 1 {
    Ok(rules.pop().expect("must contain one rule"))
  } else {
    Ok(Rule::All(o::All::new(rules)))
  }
}

fn lower_utility_call<L: Language>(
  callee: String,
  args: HashMap<String, SerializableRule>,
  env: &DeserializeEnv<L>,
) -> Result<Rule, RuleSerializeError> {
  if env.registration.has_current_param(&callee) {
    return Err(ParameterizedUtilError::UtilityParameterCalled(callee).into());
  }
  let template_params = env
    .registration
    .get_util_template_params(&callee)
    .ok_or_else(|| {
      if env.registration.has_util(&callee) {
        ParameterizedUtilError::UnexpectedUtilityArguments(callee.clone()).into()
      } else {
        RuleSerializeError::MatchesReference(ReferentRuleError::UndefinedUtil(callee.clone()))
      }
    })?;
  validate_utility_args(&callee, template_params, &args)?;
  let lowered_args = lower_utility_args(args, env)?;
  if lowered_args.values().any(|arg| arg.check_cyclic(&callee)) {
    return Err(ReferentRuleError::CyclicRule(callee).into());
  }
  let matches = ReferentRule::new(callee.clone(), lowered_args, &env.registration);
  Ok(Rule::Matches(matches))
}

pub(crate) fn verify_parameterized_referent(
  rule_id: &str,
  args: &Arc<HashMap<String, Arc<Rule>>>,
  reg_ref: &RegistrationRef,
) -> Result<(), RuleSerializeError> {
  let should_verify = VERIFY_STACK.with(|stack| {
    let mut stack = stack.borrow_mut();
    if stack.contains(rule_id) {
      false
    } else {
      stack.insert(rule_id.to_string());
      true
    }
  });
  if !should_verify {
    return Ok(());
  }
  let result = args
    .values()
    .try_for_each(|arg| arg.verify_util())
    .and_then(|_| {
      reg_ref
        .get_global_templates()
        .get(rule_id)
        .map(|_| Ok(()))
        .unwrap_or_else(|| {
          if reg_ref.get_local().contains_key(rule_id) || reg_ref.get_global().contains_key(rule_id)
          {
            Err(ParameterizedUtilError::UnexpectedUtilityArguments(rule_id.to_string()).into())
          } else {
            Err(RuleSerializeError::MatchesReference(
              ReferentRuleError::UndefinedUtil(rule_id.to_string()),
            ))
          }
        })
    });
  VERIFY_STACK.with(|stack| {
    stack.borrow_mut().remove(rule_id);
  });
  result
}

pub(crate) fn parameterized_potential_kinds(
  rule_id: &str,
  reg_ref: &RegistrationRef,
) -> Option<BitSet> {
  reg_ref
    .get_global_templates()
    .get(rule_id)
    .and_then(|template| template.matcher.potential_kinds())
}

pub(crate) fn match_parameterized_referent<'tree, D: Doc>(
  rule_id: &str,
  args: Arc<HashMap<String, Arc<Rule>>>,
  exported_vars: &HashSet<String>,
  reg_ref: &RegistrationRef,
  node: Node<'tree, D>,
  env: &mut Cow<MetaVarEnv<'tree, D>>,
) -> Option<Node<'tree, D>> {
  reg_ref
    .get_global_templates()
    .get(rule_id)
    .and_then(|template| match_global_template(template, args.clone(), exported_vars, node, env))
}

fn validate_utility_args(
  callee: &str,
  params: &[String],
  args: &HashMap<String, SerializableRule>,
) -> Result<(), ParameterizedUtilError> {
  for name in args.keys() {
    if !params.iter().any(|param| param == name) {
      return Err(ParameterizedUtilError::UnknownUtilityArgument {
        callee: callee.into(),
        arg: name.clone(),
      });
    }
  }
  // After verifying all arg keys are valid params, a length mismatch
  // means a declared param is missing from the call arguments.
  if args.len() < params.len() {
    let missing = params.iter().find(|p| !args.contains_key(p.as_str()));
    return Err(ParameterizedUtilError::MissingUtilityArgument {
      callee: callee.into(),
      arg: missing.unwrap().clone(),
    });
  }
  Ok(())
}

fn lower_utility_args<L: Language>(
  args: HashMap<String, SerializableRule>,
  env: &DeserializeEnv<L>,
) -> Result<HashMap<String, Rule>, RuleSerializeError> {
  let mut lowered = HashMap::with_capacity(args.len());
  for (name, rule) in args {
    lowered.insert(name, deserialize_rule(rule, env)?);
  }
  Ok(lowered)
}

pub(crate) fn with_arg_bindings<T>(
  bindings: Arc<HashMap<String, Arc<Rule>>>,
  f: impl FnOnce() -> T,
) -> T {
  let parent = ARG_RULE_FRAME.with(|current| current.borrow().clone());
  let frame = Arc::new(BindingFrame { bindings, parent });
  with_binding_frame(Some(frame), f)
}

pub(crate) fn match_bound_rule<'tree, D: Doc>(
  name: &str,
  node: Node<'tree, D>,
  env: &mut Cow<MetaVarEnv<'tree, D>>,
) -> Option<Node<'tree, D>> {
  let (rule, parent) = lookup_bound_rule(name)?;
  with_current_arg_export_env(|export_env: Option<&mut MetaVarEnv<'tree, D>>| {
    if let Some(export_env) = export_env {
      let exported_vars: HashSet<String> =
        rule.defined_vars().into_iter().map(String::from).collect();
      // Bound argument rules are intentionally isolated from the caller env.
      // They match against a temporary env seeded only from prior argument
      // exports in the current parameterized call. Export to the caller happens
      // later, after the whole template has matched, so export conflicts do not
      // trigger backtracking here.
      let mut local_env = Cow::Owned(export_env.clone());
      let matched = with_binding_frame(parent, || rule.match_node_with_env(node, &mut local_env))?;
      export_vars(local_env.as_ref(), export_env, &exported_vars)?;
      Some(matched)
    } else {
      with_binding_frame(parent, || rule.match_node_with_env(node, env))
    }
  })
}

fn match_global_template<'tree, D: Doc>(
  template: &GlobalTemplate,
  bindings: Arc<HashMap<String, Arc<Rule>>>,
  exported_vars: &HashSet<String>,
  node: Node<'tree, D>,
  env: &mut Cow<MetaVarEnv<'tree, D>>,
) -> Option<Node<'tree, D>> {
  let mut local_env = Cow::Owned(MetaVarEnv::new());
  let mut export_env = MetaVarEnv::new();
  let matched = with_arg_export_env(&mut export_env, || {
    with_arg_bindings(bindings, || {
      template.matcher.match_node_with_env(node, &mut local_env)
    })
  })?;
  if !exported_vars.is_empty() {
    export_vars(&export_env, env.to_mut(), exported_vars)?;
  }
  Some(matched)
}

fn export_vars<'tree, D: Doc>(
  from: &MetaVarEnv<'tree, D>,
  to: &mut MetaVarEnv<'tree, D>,
  vars: &HashSet<String>,
) -> Option<()> {
  if vars.is_empty() {
    return Some(());
  }
  for var in vars {
    if let Some(node) = from.get_match(var.as_str()) {
      to.insert(var, node.clone())?;
      continue;
    }
    let multi = from.get_multiple_matches(var.as_str());
    if !multi.is_empty() {
      to.insert_multi(var, multi)?;
      continue;
    }
    if let Some(bytes) = from.get_transformed(var.as_str()) {
      to.insert_transformation(
        &MetaVariable::Capture(var.to_string(), false),
        var,
        bytes.clone(),
      );
    }
  }
  Some(())
}

fn lookup_bound_rule(name: &str) -> Option<(Arc<Rule>, Option<Arc<BindingFrame>>)> {
  ARG_RULE_FRAME.with(|current| {
    let borrow = current.borrow();
    let active = borrow.as_ref()?;
    let rule = active.bindings.get(name)?;
    Some((rule.clone(), active.parent.clone()))
  })
}

fn with_binding_frame<T>(frame: Option<Arc<BindingFrame>>, f: impl FnOnce() -> T) -> T {
  struct FrameGuard(Option<Arc<BindingFrame>>);
  impl Drop for FrameGuard {
    fn drop(&mut self) {
      ARG_RULE_FRAME.with(|current| {
        *current.borrow_mut() = self.0.take();
      });
    }
  }
  let previous = ARG_RULE_FRAME.with(|current| current.replace(frame));
  let _guard = FrameGuard(previous);
  f()
}

fn with_arg_export_env<'tree, D: Doc, T>(
  env: &mut MetaVarEnv<'tree, D>,
  f: impl FnOnce() -> T,
) -> T {
  struct ExportEnvGuard;
  impl Drop for ExportEnvGuard {
    fn drop(&mut self) {
      ARG_RULE_EXPORT_ENV.with(|stack| {
        stack.borrow_mut().pop();
      });
    }
  }
  ARG_RULE_EXPORT_ENV.with(|stack| {
    stack
      .borrow_mut()
      .push(env as *mut MetaVarEnv<'tree, D> as *mut ());
  });
  let _guard = ExportEnvGuard;
  f()
}

fn with_current_arg_export_env<'tree, D: Doc, T>(
  f: impl FnOnce(Option<&mut MetaVarEnv<'tree, D>>) -> T,
) -> T {
  let ptr = ARG_RULE_EXPORT_ENV.with(|stack| stack.borrow().last().copied());
  let env = ptr.map(|ptr| {
    // SAFETY: pointers are only pushed by `with_arg_export_env` for the duration
    // of the matching call on the same thread and with the same `D`/`'tree`.
    unsafe { &mut *(ptr as *mut MetaVarEnv<'tree, D>) }
  });
  f(env)
}

#[cfg(test)]
mod test {
  use super::*;

  #[test]
  fn test_validate_utility_id() {
    assert!(validate_utility_id("wrap").is_ok());
    assert!(matches!(
      validate_utility_id("wrap(BODY)"),
      Err(ParameterizedUtilError::InvalidUtilityId(id)) if id == "wrap(BODY)"
    ));
  }

  #[test]
  fn test_validate_utility_arguments() {
    assert!(validate_utility_arguments("wrap", &["BODY".into(), "EXPR".into()]).is_ok());
    assert!(matches!(
      validate_utility_arguments("wrap", &["BODY".into(), "BODY".into()]),
      Err(ParameterizedUtilError::DuplicateUtilityArgument { util, arg })
        if util == "wrap" && arg == "BODY"
    ));
    assert!(matches!(
      validate_utility_arguments("wrap", &["BODY(EXPR)".into()]),
      Err(ParameterizedUtilError::InvalidUtilityArgument { util, arg })
        if util == "wrap" && arg == "BODY(EXPR)"
    ));
  }
}