}
+// Keep this function for debugging.
+/*
+func dump(msg string, val reflect.Value) {
+ fmt.Printf("%s:\n", msg)
+ ast.Print(fset, val.Interface())
+ fmt.Println()
+}
+*/
+
+
// rewriteFile applies the rewrite rule 'pattern -> replace' to an entire file.
func rewriteFile(pattern, replace ast.Expr, p *ast.File) *ast.File {
m := make(map[string]reflect.Value)
}
+// Values/types for special cases.
+var (
+ objectPtrNil = reflect.NewValue((*ast.Object)(nil))
+
+ identType = reflect.Typeof((*ast.Ident)(nil))
+ objectPtrType = reflect.Typeof((*ast.Object)(nil))
+ positionType = reflect.Typeof(token.NoPos)
+)
+
+
// apply replaces each AST field x in val with f(x), returning val.
// To avoid extra conversions, f operates on the reflect.Value form.
func apply(f func(reflect.Value) reflect.Value, val reflect.Value) reflect.Value {
if !val.IsValid() {
return reflect.Value{}
}
+
+ // *ast.Objects introduce cycles and are likely incorrect after
+ // rewrite; don't follow them but replace with nil instead
+ if val.Type() == objectPtrType {
+ return objectPtrNil
+ }
+
switch v := reflect.Indirect(val); v.Kind() {
case reflect.Slice:
for i := 0; i < v.Len(); i++ {
}
-var positionType = reflect.Typeof(token.NoPos)
-var identType = reflect.Typeof((*ast.Ident)(nil))
-
-
func isWildcard(s string) bool {
rune, size := utf8.DecodeRuneInString(s)
return size == len(s) && unicode.IsLower(rune)
// Special cases.
switch pattern.Type() {
- case positionType:
- // token positions don't need to match
- return true
case identType:
// For identifiers, only the names need to match
// (and none of the other *ast.Object information).
p := pattern.Interface().(*ast.Ident)
v := val.Interface().(*ast.Ident)
return p == nil && v == nil || p != nil && v != nil && p.Name == v.Name
+ case objectPtrType, positionType:
+ // object pointers and token positions don't need to match
+ return true
}
p := reflect.Indirect(pattern)
switch p.Kind() {
case reflect.Slice:
- v := v
if p.Len() != v.Len() {
return false
}
return true
case reflect.Struct:
- v := v
if p.NumField() != v.NumField() {
return false
}
return true
case reflect.Interface:
- v := v
return match(m, p.Elem(), v.Elem())
}
case reflect.Ptr:
v := reflect.Zero(p.Type())
- v.Set(subst(m, p.Elem(), pos).Addr())
+ if elem := p.Elem(); elem.IsValid() {
+ v.Set(subst(m, elem, pos).Addr())
+ }
return v
case reflect.Interface:
v := reflect.Zero(p.Type())
- v.Set(subst(m, p.Elem(), pos))
+ if elem := p.Elem(); elem.IsValid() {
+ v.Set(subst(m, elem, pos))
+ }
return v
}