File: dereference.go

package info (click to toggle)
c2go 0.26.11-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,052 kB
  • sloc: ansic: 6,037; sh: 82; makefile: 5
file content (51 lines) | stat: -rw-r--r-- 1,472 bytes parent folder | download | duplicates (3)
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
package types

import (
	"errors"
	"fmt"
	"strings"

	"github.com/elliotchance/c2go/util"
)

// IsDereferenceType - check is that type dereference
func IsDereferenceType(cType string) bool {
	return strings.ContainsAny(cType, "[]*")
}

// GetDereferenceType returns the C type that would be the result of
// dereferencing (unary "*" operator or accessing a single array element on a
// pointer) a value.
//
// For example if the input type is "char *", then dereferencing or accessing a
// single element would result in a "char".
//
// If the dereferenced type cannot be determined or is impossible ("char" cannot
// be dereferenced, for example) then an error is returned.
func GetDereferenceType(cType string) (_ string, err error) {
	defer func() {
		if err != nil {
			err = fmt.Errorf("Error in GetDereferenceType : %v", err)
		}
	}()

	// In the form of: "int [2][3][4]" -> "int [3][4]"
	search := util.GetRegex(`([\w\* ]+)\s*\[\d+\]((\[\d+\])+)`).FindStringSubmatch(cType)
	if len(search) > 0 {
		return search[1] + search[2], nil
	}

	// In the form of: "char [8]" -> "char"
	search = util.GetRegex(`([\w\* ]+)\s*\[\d+\]`).FindStringSubmatch(cType)
	if len(search) > 0 {
		return strings.TrimSpace(search[1]), nil
	}

	// In the form of: "char **" -> "char *"
	search = util.GetRegex(`([\w ]+)\s*(\*+)`).FindStringSubmatch(cType)
	if len(search) > 0 {
		return strings.TrimSpace(search[1] + search[2][0:len(search[2])-1]), nil
	}

	return "", errors.New(cType)
}