Compare commits

..
28 Commits
Author SHA1 Message Date
gmp c2113215e9 Update documentation. 2021-11-16 18:12:37 -05:00
gmp e4f7e32887 Update to Big Sur 15.5.2 / Clang 12.0.5. Improved handing of avaiability
attributes and boolean values.
2021-11-16 16:02:08 -05:00
gmp f4a9dae250 Update to latest Clang AST spec. 2021-06-11 11:24:25 -04:00
gmp 0bc23404da Doc updates. 2020-06-25 16:56:55 -04:00
gmp 1704be1cbc Remove a stray debugging statement. 2020-06-25 13:18:03 -04:00
gmp 8b3a956bbe Comprehensive update, add some GC fixes, update examples to new MacOS
header file layout.
2020-06-24 13:03:53 -04:00
gmp acc8cab583 Fix various memory management bugs in GC mode. 2019-06-27 11:41:58 -04:00
gmp b5773b5525 Make GC mode the default. 2019-06-19 14:29:24 -04:00
gmp 4aa1211d73 Complete working GC mode. 2019-06-19 14:07:33 -04:00
gmp c8209dd260 Interim commit. 2019-06-18 17:29:52 -04:00
gmp e5c8e114bf Add garbage collection memory mangement mode (gogc). Lots of fixes
related to pointer handling and memory management.
2019-06-18 09:15:46 -04:00
gmp 79bb282188 Complete conversion to pointer wrapped types. Update tests, fix
parameter handling for functions.
2019-06-13 16:47:36 -04:00
gmp ac9eecafd8 Convert all Go wrapped objects to pointers so the Go GC can track
all of the Objective-C pointers. Still working on bug with typedefs
to wrapped types.
2019-06-13 09:25:53 -04:00
gmp b0139b9aa8 Bug fixes and clean up how methods are added to an interface from
superclasses and protocols. Ensure that "Unavailable" attributes are
handled properly.
2019-06-11 16:41:21 -04:00
gmp 9a4fabda24 Run gofmt -w on everything. Add 'gogc' option to use Go garbage
collector for memory management.
2019-06-11 12:38:22 -04:00
gmp d0654613ea Documentation updates. 2019-06-06 00:30:21 -04:00
gmp 90166a4379 Bug fixes. Read availability attributes when adding interfaces and
categories. Memory leak fixes. Add "autorelease" confiruation directive.
Fix parameter types for subclass method overriding.
2019-06-06 00:22:07 -04:00
gmp 50b9387a91 Add frameworkdirs: directive to allow the user to point to directories
where Objective-C frameworks can be found. Rework the cgoFlags. Search
Objective-C protocols when looking for subclass methods to override.
2019-06-04 21:18:06 -04:00
gmp f93a893060 Bug fix in Objective-C method signature parsing. 2019-06-04 13:01:51 -04:00
gmp 773886e0f1 Complete unit tests for nswrap/types. 2019-06-04 11:27:46 -04:00
gmp a251e7382e Improve test coverage. 2019-06-04 00:14:04 -04:00
gmp d8552bcf9d Use strict unmarshal for configuration file, to detect typos in
config directives. Do not panic on failed regexp in AST parsing,
instead return &ast.Unknown{} for further debugging. Add debutast:
directive to print context when AST nodes are not recognized.
2019-06-03 11:07:12 -04:00
gmp 4f0cdf4d1a Some AST tweaks and add astfile: config option to read AST from a file
instead of running Clang. Attempt to port to MacOS Mojave.
2019-06-01 15:10:51 -04:00
gmp a7df3a4e71 Enable -fobjc-arc for AST generation when arc=true in nswrap.yaml.
This still doesn't work
2019-05-31 16:28:51 -04:00
gmp e29ae58a9c Add experimental "arc" directive to nswrap.yaml to experiment
with enabling Objective-C automatic reference counting. Bindings
currently will not compile with this turned on.
2019-05-31 12:42:52 -04:00
gmp 5a5a4f9406 AST tweaks and new tests. 2019-05-31 10:21:04 -04:00
gmp 96edbba641 Documentation updates. 2019-05-29 22:57:10 -04:00
gmp 8ce3b6a6de Remove dependencies, improve documentation. 2019-05-29 22:36:49 -04:00
374 changed files with 11761 additions and 2007 deletions
+12 -1
View File
@@ -5,8 +5,19 @@ examples/app/app
examples/app/ns examples/app/ns
examples/bluetooth/bluetooth examples/bluetooth/bluetooth
examples/bluetooth/ns examples/bluetooth/ns
examples/bluetooth/old
examples/foundation/foundation examples/foundation/foundation
examples/foundation/ns examples/foundation/ns
examples/simple/simple examples/simple/simple
examples/simple/ClassOne examples/simple/ClassOne
examples/memory/memory
examples/memory/ns
examples/gc/gc
examples/gc/ns
examples/functions/functions
examples/functions/ns
examples/subclass/ns
examples/subclass/subclass
examples/strings/strings
examples/strings/ns
ns-old
outputclang.txt
+335 -190
View File
@@ -2,7 +2,7 @@
Create Go language bindings for Objective-C. Create Go language bindings for Objective-C.
Using NSWrap, you can easily work with many MacOS interfaces, subclasses, Using NSWrap, you can work with MacOS interfaces, subclasses,
library functions, protocols and delegates entirely in Go. library functions, protocols and delegates entirely in Go.
# Getting Started # Getting Started
@@ -13,20 +13,15 @@ NSWrap runs on MacOS and requires `clang` (from the XCode command line
tools) and the MacOS system header files. tools) and the MacOS system header files.
```sh ```sh
go get git.wow.st/gmp/nswrap/... go get git.wow.st/gmp/nswrap
``` ```
From your `go` source directory, type: The `nswrap` command line tool should now be installed in your `go/bin` path.
```sh
cd git.wow.st/gmp/nswrap
go install
```
Since NSWrap uses `clang` to generate an AST from Objective-C input files, you Since NSWrap uses `clang` to generate an AST from Objective-C input files, you
will need to install XCode and its associated command line tools. Enter will need to install XCode and its associated command line tools. Enter
`clang --version` from your terminal prompt to see if you have it installed `clang --version` from your terminal prompt to see if you have it installed.
already. You will also need to have the Objective-C header files for the You will also need the Objective-C header files for the
various frameworks you want to use. Look for them in various frameworks you want to use. Look for them in
`/System/Library/Frameworks/*/Headers`. `/System/Library/Frameworks/*/Headers`.
@@ -67,6 +62,8 @@ pragma [ clang diagnostic ignored "-Wformat-security" ]
Regular expressions are permitted in the names of classes, functions, Regular expressions are permitted in the names of classes, functions,
protocols and protocol methods, overridden superclass methods, and enums. protocols and protocol methods, overridden superclass methods, and enums.
Since the `NSObject` class is necessary for memory management, NSWrap will
automatically include it if it is encountered in an input header file.
When invoked, NSWrap creates a subdirectory with the name of the package When invoked, NSWrap creates a subdirectory with the name of the package
as specified in `nswrap.yaml` or, by default, `ns` if a package name is not as specified in `nswrap.yaml` or, by default, `ns` if a package name is not
@@ -90,11 +87,11 @@ package as your automatically generated bindings.
NSWrap will create bindings for all classes identified in the `classes` NSWrap will create bindings for all classes identified in the `classes`
directive of the configuration file. All of the class and instance methods directive of the configuration file. All of the class and instance methods
are bound to Go and all types identified in the process are wrapped are bound to Go and all types identified in the process are wrapped
in Go types (as described below), except for methods that contain prohibited in Go types (as described below), except for methods that contain unsupported
return types or paramater types (such as blocks and function pointers). return types or paramater types such as blocks and function pointers.
```go ```go
s1 := ns.NSStringAlloc() // allocate and autorelease an instance of NSString s1 := ns.NSStringAlloc() // allocate an instance of NSString
s2 := ns.NSStringWithSting(s1) // call a class method of NSString s2 := ns.NSStringWithSting(s1) // call a class method of NSString
class := ns.NSStringClass() // class method returning the class of NSString class := ns.NSStringClass() // class method returning the class of NSString
fmt.Println(s2.UTF8String()) // call UTF8String, an NSString instance method fmt.Println(s2.UTF8String()) // call UTF8String, an NSString instance method
@@ -106,21 +103,20 @@ with the class name, and, if necessary, disambiguated for overloaded
Objective-C methods. Any redundant initial Objective-C methods. Any redundant initial
characters are elided (e.g. the Objective-C characters are elided (e.g. the Objective-C
`[NSString stringWithString:aString]` is shortened in Go to `[NSString stringWithString:aString]` is shortened in Go to
`ns.NSStringWithString(aString)`). Instance methods are carried over `ns.NSStringWithString(aString)`). Instance methods are converted to
as-is but in TitleCase, and disambiguated for method overloading as described TitleCase and disambiguated for method overloading as described below.
below.
Note that while return types and parameter types needed for the binding will Note that while return types and parameter types needed for the binding will
be defined and wrapped for you in Go types, be defined and wrapped for you in Go types,
you will not get any of their methods you will not get any of their methods
unless those types also appear in your NSWrap configuration file. unless those types also appear in your NSWrap configuration file.
For example, the `NSDictionaryWithObjects(...)` constructor takes two `NSArray` For example, the `[NSDictionary WithObjects: forKeys:]` constructor takes two
parameters, so if you want to use it you will probably want `NSArray` parameters, so if you want to use it from Go you will probably want
to have `NSArray` in your configuration file in addition to `NSDictionary`. to have `NSArray` in your configuration file in addition to `NSDictionary`.
## Overloaded Methods ## Overloaded Methods
Because Go does not allow overloaded function definitions, NSWrap automatically Because Go does not allow overloaded functions, NSWrap automatically
disambiguates overloaded method names as required. disambiguates overloaded method names as required.
This is done by successively adding parameter names onto the end of the Go This is done by successively adding parameter names onto the end of the Go
function name until a unique name is created. function name until a unique name is created.
@@ -137,14 +133,14 @@ For example, `NSString` provides the folowing `compare` methods:
These are translated into Go as: These are translated into Go as:
```go ```go
func (o NSString) Compare(string NSString) NSComparisonResult { } func (o *NSString) Compare(string *NSString) NSComparisonResult { }
func (o NSString) CompareOptions(string NSString, mask NSStringCompareOptions) NSComparisonResult { } func (o *NSString) CompareOptions(string *NSString, mask NSStringCompareOptions) NSComparisonResult { }
func (o NSString) CompareOptionsRange(string NSString, mask NSStringCompareOptions, func (o *NSString) CompareOptionsRange(string *NSString, mask NSStringCompareOptions,
rangeOfReceiverToCompare NSRange) NSComparisonResult { } rangeOfReceiverToCompare NSRange) NSComparisonResult { }
func (o NSString) CompareOptionsRangeLocale(string NSString, mask NSStringCompareOptions, func (o *NSString) CompareOptionsRangeLocale(string *NSString, mask NSStringCompareOptions,
rangeOfReceiverToCompare NSRange, locale NSObject) NSComparisonResult { } rangeOfReceiverToCompare NSRange, locale NSObject) NSComparisonResult { }
``` ```
@@ -162,127 +158,175 @@ fmt.Printf("%s\n",str)
NSWrap creates a `Char` Go type that is equivalent to a C `char`. A pointer to NSWrap creates a `Char` Go type that is equivalent to a C `char`. A pointer to
`Char` in Go code can therefore be used with Objective-C functions and methods `Char` in Go code can therefore be used with Objective-C functions and methods
that take a `char*` parameter. that take a `char*` parameter.
When NSWrap binds a method that returns `*Char` (and is in garbage collected mode,
the default), it first calls `strdup`
on the output of the underlying Objective-C method. Therefore, the returned
pointer is manually allocated and will need to be freed later from Go. NSWrap
creates a
`(*Char).Free()` method for use when these pointers are no longer needed.
This copying is necessary because the Objective-C runtime will sometimes
return pointers to internal objects that are impossible to manage from the
Go side. NSWrap aims to cause any internal objects to be deallocated as soon
as possible so they do not cause memory leaks. This means that any returned
C strings need to be copied and memory managed manually from the Go side.
NSWrap provides the helper functions `CharWithGoString` and `CharWithBytes` NSWrap provides the helper functions `CharWithGoString` and `CharWithBytes`
that take, respectively, Go strings and Go byte arrays (`[]byte`) and return that take, respectively, Go strings and Go byte arrays (`[]byte`) and return
`*Char` in Go. As demonstrated above, NSWrap also provides a `String()` `*Char` in Go. As demonstrated above, NSWrap also provides `String()`
methods so that the `*Char` and `NSString` types implement the `Stringer` methods so that the `*Char` and `*NSString` types implement the `Stringer`
Go interface. Go interface and therefore can be sent directly to functions like `fmt.Printf`.
The `String()` method on `*NSString` creates a temporary `*Char` internally
but frees it for you before returning. Since methods returning
`*Char` return a pointer that needs to be manually freed, it is important
to use these properly in order to avoid leaks:
```go
nst := ns.NSStringWithGoString("one string")
// NO: the next line leaks a *Char (UTF8String)
//mygostring := nst.UTF8String().String()
// OK: NSWrap creates a temporary *Char and frees it for you:
mygostring := nst.String()
// ALSO OK: manually free your own temporary *Char:
mytmpchar := nst.UTF8String()
mygostring = mytmpchar.String()
mytmpchar.Free()
```
In most cases it will be more convenient to convert directly to Go strings instead
of `*Char`.
## Working With NSObject and its Descendants ## Working With NSObject and its Descendants
Objective-C Objects are represented in Go by a type and an interface as Objective-C objects are represented in Go by a type and an interface as
follows: follows:
```go ```go
type Id struct { type Id struct {
ptr unsafe.Pointer ptr unsafe.Pointer
} }
func (o Id) Ptr() unsafe.Pointer { return o.ptr } func (o *Id) Ptr() unsafe.Pointer { if o == nil { return nil }; return o.ptr }
type NSObject interface { type NSObject interface {
Ptr() unsafe.Pointer Ptr() unsafe.Pointer
} }
``` ```
Other object types in Go are structs that directly or indirectly embed `Id` Other object types in Go are structs that directly or indirectly embed `Id`
and therefore implement `NSObject`. and therefore contain an `unsafe.Pointer` to an Objective-C object, and
implement `NSObject` by inheriting the `Ptr()` method.
Because of this implementation, you will note that every Objective-C object
is represented by at least two pointers -- an underlying pointer to the
Objective-C object
in CGo memory (allocated by the Objective-C runtime), as well as a pointer
allocated by the Go runtime to an `Id` type, or to another type that directly
or indirectly embeds `Id`. This "dual pointer" approach is necessary to ensure
that memory management can be made to work correctly (see below for details).
* The NSObject Interface * The NSObject Interface
The `Id` type in Go represents the Objective-C type `id`, which is a pointer The `Id` type in Go represents the Objective-C type `id`, which is a pointer
to an Objective-C object. Because `cgo` does not understand this type, to an Objective-C object. Because `cgo` does not understand this type,
NSWrap will always translate it to a `void*` on the C side. NSWrap will always translate it to a `void*` on the C side.
The `NSObject` interface in Go allows any `NS` type to be used with The `NSObject` interface in Go allows any type that directly or indirectly
generic Objective-C functions. For example: embeds `Id` to be used with generic Objective-C functions. For example:
```go ```go
o1 := ns.NSStringWithGoString("my string") o1 := ns.NSStringWithGoString("my string")
s1 := ns.NSSetWithOBjects(o1) s1 := ns.NSSetWithObjects(o1)
a := ns.NSMutableArrayWithObjects(o1,s1) a := ns.NSMutableArrayWithObjects(o1,s1)
``` ```
Since `NSString` and `NSSet` in Go both implement the `NSObject` interface, Since `NSString` and `NSSet` in Go both implement the `NSObject` interface,
they can both be used as parameters to the `NSMutableArray` constructor. they can both be used as parameters to the `NSMutableArray` constructor.
This will help you, too, with delegates This will help you, too, when working with delegates
(see below). Classes that accept delegates will generally accept any (see below). Classes that accept delegates will generally accept any
`NSObject` in ther `initWithDelegate()` or `setDelegate()` methods, and `NSObject` in their `initWithDelegate()` or `setDelegate()` methods, and
may or may not test at runtime if the provided object actually may or may not test at runtime if the provided object actually
implements the required delegate protocol. implements the required delegate protocol.
* Inheritance * Inheritance
Objective-C permits single inheritance. In Go, this is modeled using Objective-C allows single inheritance. NSWrap automatically adds
embedding. Top level objects that inherit from `NSObject` in Objective-C inherited methods to classes that are includled in your binding.
Types created by NSWrap also "embed" their parent class. For example, top
level objects that inherit from `NSObject` in Objective-C
embed the Go type `Id` and therefore implement the `NSObject` Go interface. embed the Go type `Id` and therefore implement the `NSObject` Go interface.
Other objects embed their superclass. For example: Other objects embed their direct superclass. For example:
```go ```go
type NSArray struct { Id } type NSArray struct { Id }
func (o NSArray) Ptr() unsafe.Pointer { return o.ptr } func (o *NSArray) Ptr() unsafe.Pointer { if o == nil { return nil }; return o.ptr }
func (o Id) NSArray() NSArray { func (o *Id) NSArray() *NSArray {
ret := NSArray{} return (*NSArray)(unsafe.Pointer(o))
ret.ptr = o.ptr
return ret
} }
type NSMutableArray struct { NSArray } type NSMutableArray struct { NSArray }
func (o NSMutableArray) Ptr() unsafe.Pointer { return o.ptr } func (o *NSMutableArray) Ptr() unsafe.Pointer { if o == nil { return nil }; return o.ptr }
func (o Id) NSMutableArray() NSMutableArray {...} func (o *Id) NSMutableArray() *NSMutableArray {
return (*NSMutableArray)(unsafe.Pointer(o))
}
``` ```
Observe: Observe:
```go ```go
b := ns.NSButtonAlloc() // NSButton > NSControl > NSView > NSResponder > NSObject b := ns.NSButtonAlloc() // NSButton > NSControl > NSView > NSResponder > NSObject
b.InitWithFrame(ns.NSMakeRect(100,100,200,200)) // Method of NSView b.InitWithFrame(ns.NSMakeRect(100,100,200,200))
b.SetTitle(nst("PUSH")) // Method of NSButton b.SetTitle(nst("PUSH"))
vw := win.ContentView() vw := win.ContentView()
vw.AddSubview(b.NSView) // Pass the button's embedded NSView vw.AddSubview(&b.NSView) // Pass the button's embedded NSView
``` ```
In Go, `NSButtonAlloc` returns a Go object of type `ns.NSButton`. However, In Go, `NSButtonAlloc` returns a Go object of type `ns.NSButton`. However,
there is no `InitWithFrame` method for receivers of this type. This is the `initWithFrame` method is defined in AppKit for `NSView`. NSWrap will find this
not necessary because `NSButton` embeds `NSControl` which in turn embeds method and add it to the Go `NSButton` type when creating your wrapper because
`NSView`. The `InitWithFrame` method only needs to be implemented for `NSView` `NSButton` inherits from `NSControl` which inherits from `NSView`.
receivers. Go will automatically find the indirectly embedded `NSView` and
call the right method.
Go's type inference appears to be slightly broken (as of 1.12.1) because As of this
the following does not work. Look out for this if you are getting type writing, on MacOS 10.13.6, NSWrap binds 115 instance methods for `NSObject`,
errors: so things like `Hash()`, `IsEqualTo()`, `ClassName()`, `RespondsToSelector()`
and many many others are available and can be called on any object directly
from Go.
```go All objects implement the `NSObject` interface, but from time to time you
//DO NOT DO THIS will encounter a method that takes a parameter of a different type that may
b := ns.NSButtonAlloc().InitWithFrame(ns.MakeRect(100,100,200,200)) not exactly match the type you have. For example, if you want to pass your
//For some reason Go thinks b has type ns.NSView, because InitWithFrame is defined for ns.NSView, even though `NSButton` as a parameter to a method that accepts an `NSView` type, you need
//NSButtonAlloc() returns an ns.NSButton. to explicitly pass its embedded `NSView` (`&b.NSView` in the example above).
``` This approach is safer than "converting" the button to an `NSView` (see below)
because it will only work on objects that directly or indirectly embed an
Go has no trouble finding embedded methods for your `NSButton` and will `NSView` Go type.
happily search up the chain through `NSControl`, `NSView`, `NSResponder` and
`NSObject` and all of their associated protocols and categories. As of this
writing, on MacOS 10.13.6, NSWrap binds 90 instance methods for `NSObject`,
so things like `Hash()`, `IsEqualTo()`, `ClassName()` and many many
others are available and can be called on any object directly from Go.
Go does not perform the same type
magic when you use variables as function or method parameters.
If you want to pass your `NSButton` as a parameter to a method that accepts
an `NSView` type, you need to explicitly pass the embedded `NSView`
(`b.NSView` in the example above).
NSWrap creates a method for `Id` allowing objects to be converted NSWrap creates a method for `Id` allowing objects to be converted
at run-time to any other class. You will need this for Enumerators, which at run-time to any other class. You will need this for Enumerators and
always return `Id`. See below under Enumerators for an example, but make functions like `NSArray`'s `GetObjects`, for example,
sure you know (or test) what type your objects are before converting them, which always return `*Id`. Make
or else you will get an exception from the Objective-C runtime. sure you know (or test) what type your objects are before converting them.
You can implement a version of a Go type switch this way:
```go
switch {
case o.IsKindOfClass(ns.NSStringClass()):
// do something with o.NSString()
case o.IsKindOfClass(ns.NSSetClass()):
// do something with o.NSSet()
default:
...
}
```
Because `Id` can be converted to any type, and every object in the Foundation Because `Id` can be converted to any type, and every object in the Foundation
classes inherits from `Id`, it is possible to send any message to any classes inherits from `Id`, it is possible to send any message to any
object, if you are feeling lucky. You are going to have to explicitly object, if you are feeling lucky. If you are not lucky you will get an
exception from the Objective-C runtime. You are going to have to explicitly
convert your object to the wrong type before the compiler will let you do this. convert your object to the wrong type before the compiler will let you do this.
```go ```go
a := ns.NSArrayWithObjects(o1,o2) // NSArray embeds Id a := ns.NSArrayWithObjects(o1,o2) // NSArray embeds Id
fmt.Println(a.NSString().UTF8String()) // DON'T! fmt.Println(a.NSString().UTF8String()) // DON'T!
// | | \-method of NSString, returns *Char, a "Stringer" type // | | \-method of NSString, returns *Char, a "Stringer"
// | \-method of Id returning NSString // | \-method of Id returning NSString
// \-calls "String()" on its parameters // \-calls "String()" on its parameters
``` ```
@@ -301,22 +345,29 @@ As seen above with the `NSMutableArrayWithObjects()` constructor example,
NSWrap supports variadic NSWrap supports variadic
functions. Because of the limitations of `cgo`, there is a numerical limit functions. Because of the limitations of `cgo`, there is a numerical limit
to the number of parameters in a variadic function call, which defaults to to the number of parameters in a variadic function call, which defaults to
16 but can be set with the `vaargs` configuration directive. 16 but can be set with the `vaargs` configuration directive. NSWrap will
automatically include a `nil` sentinel when calling any Objective-C
methods with variadic parameter lists. The direct types `va_list` and
`va_list_tag` are not currently supported.
## Pointers to Pointers ## Pointers to Pointers
When NSWrap encounters a pointer to a pointer to an Objective-C object, it When NSWrap encounters a pointer to a pointer to an Objective-C object, it
treats it as an array of objects and translates it into a pointer to a treats it as an array of objects and translates it into a pointer to a
Go slice. If you are passing empty slices into these functions, be sure to Go slice. If you are passing empty slices into these functions, be sure to
pre-allocate them to a sufficient size and capacity (see below for an pre-allocate them to a sufficient capacity. Ssee below for an
example). These Go slices can be used for input and output of methods and example. These Go slices can be used for input and output of methods and
functions. functions.
Pointers to pointers are sometimes passed to Objective-C methods or functions Pointers to pointers are sometimes passed to Objective-C methods or functions
as a way of receiving output from those functions. In those cases, after the as a way of receiving output from those functions, especially because
CGo call, the method parameter is treated as a nil-terminated array of object Objective-C does not allow for multiple return values. In those cases, after
pointers. The object pointers are copied into the input Go slice, which is the CGo call, the method parameter will be treated as an array of
then truncated to the appropriate length. object pointers that may have been modified by the Objective-C function or
method. NSWrap will copy the object pointers back into the input Go slice, up
to its capacity (which will never be changed). The input Go slice is then
truncated to the appropriate length. If there is no output, the length will
be set to 0.
An example in Core Foundation is the `getObjects:andKeys:count` method for An example in Core Foundation is the `getObjects:andKeys:count` method for
`NSDictionary`: `NSDictionary`:
@@ -327,23 +378,31 @@ An example in Core Foundation is the `getObjects:andKeys:count` method for
ns.NSArrayWithObjects(nst("obj1"),nst("obj2")), ns.NSArrayWithObjects(nst("obj1"),nst("obj2")),
ns.NSArrayWithObjects(nst("key1"),nst("key2")), ns.NSArrayWithObjects(nst("key1"),nst("key2")),
) )
os,ks := make([]ns.Id,0,5), make([]ns.Id,0,5) // length 0, capacity 5 slices va,ka := make([]*ns.Id,0,5), make([]*ns.Id,0,5) // length 0, capacity 5 slices
dict.GetObjects(&os,&ks,5) // count = 5, must be the same size or smaller than the input slice capacity dict.GetObjectsAndKeysCount(&va,&ka,5)
fmt.Printf("Length of os is now %d\n",len(os)) // os and ks slices are now length = 2 // last parameter is the count, must be less than or equal to the input slice capacity
for i,k := range ks { fmt.Printf("Length of va is now %d\n",len(va)) // va and ka slices are now length = 2
fmt.Printf("-- %s -> %s\n",k.NSString(),os[i].NSString()) for i,k := range ka {
fmt.Printf("-- %s -> %s\n",k.NSString(),va[i].NSString())
} }
``` ```
NSWrap will not check the "count" parameter, so the user will always need
to make sure it is less than or equal to the capacity of the input
Go slices.
Using pointers to pointers is necessary in many Core Foundation situations Using pointers to pointers is necessary in many Core Foundation situations
where you need to get an error message out of a function or method, for example where you need to get an error message out of a function or method, or in other
in `[NSString stringWithContentsOfURL...]`: cases where an Objective-C method wants to provide multiple return values.
Here is an example using `[NSString stringWithContentsOfURL...]`:
```go ```go
err := make([]ns.NSError,1) err := make([]*ns.NSError,1)
n1 = ns.NSStringWithContentsOfURLEncoding(ns.NSURLWithGoString("htttypo://example.com"),0,&err) n1 = ns.NSStringWithContentsOfURLEncoding(ns.NSURLWithGoString("htttypo://example.com"), 0, &err)
if len(err) > 0 {
fmt.Printf("err: %s\n",err[0].LocalizedDescription()) fmt.Printf("err: %s\n",err[0].LocalizedDescription())
//err: The file couldn’t be opened because URL type htttypo isn’t supported. //err: The file couldn’t be opened because URL type htttypo isn’t supported.
}
``` ```
## Selectors ## Selectors
@@ -363,15 +422,17 @@ appMenu.AddItemWithTitle(
## Enumerators ## Enumerators
NSWrap provides a `ForIn` method for the `NSEnumerator` type. Call it with a NSWrap provides a `ForIn` method for the `NSEnumerator` type. Call it with a
`func(ns.Id) bool` parameter that returns `true` to continue and `false` to `func(*ns.Id) bool` parameter that returns `true` to continue and `false` to
stop the enumeration. stop the enumeration.
```go ```go
a := ns.NSArrayWithObjects(o1,o2,o3) a := ns.NSArrayWithObjects(o1,o2,o3)
a.ObjectEnumerator().ForIn(func (o ns.Id) bool { i := 0
a.ObjectEnumerator().ForIn(func (o *ns.Id) bool {
switch { switch {
case o.IsKindOfClass(ns.NSStringClass()): case o.IsKindOfClass(ns.NSStringClass()):
fmt.Println(o.NSString().UTF8String()) fmt.Printf("%d: %s\n", i, o.NSString())
i++
return true // continue enumeration return true // continue enumeration
default: default:
fmt.Println("Unknown class") fmt.Println("Unknown class")
@@ -385,7 +446,7 @@ identification.
## Enum Definitions ## Enum Definitions
NSWrap translates C `enum` values into Go constants. The enums you need are NSWrap translates C `enum` values into Go constants. The enums you want are
specified in `nswrap.yaml` by regular expression, which, in the case of named specified in `nswrap.yaml` by regular expression, which, in the case of named
enums, must match the name of the `enum` itself, or in the case of anonymous enums, must match the name of the `enum` itself, or in the case of anonymous
enums, must match the name of the constant(s) you are looking for as declared enums, must match the name of the constant(s) you are looking for as declared
@@ -408,10 +469,9 @@ results in:
```go ```go
//ns/main.go //ns/main.go
... ...
type NSWindowOrderingMode C.enum_NSWindowOrderingMode const NSWindowAbove NSInteger = C.NSWindowAbove
const NSWindowAbove NSWindowOrderingMode = C.NSWindowAbove const NSWindowBelow NSInteger = C.NSWindowBelow
const NSWindowBelow NSWindowOrderingMode = C.NSWindowBelow const NSWindowOut NSInteger = C.NSWindowOut
const NSWindowOut NSWindowOrderingMode = C.NSWindowOut
const _CLOCK_REALTIME = C._CLOCK_REALTIME const _CLOCK_REALTIME = C._CLOCK_REALTIME
const _CLOCK_MONOTONIC = C._CLOCK_MONOTONIC const _CLOCK_MONOTONIC = C._CLOCK_MONOTONIC
@@ -419,57 +479,14 @@ const _CLOCK_MONOTONIC_RAW = C._CLOCK_MONOTONIC_RAW
... ...
``` ```
## Memory management
You can call `Retain()`, `Release()` and `Autorelease()` on any object.
All allocation functions generated by NSWrap call `autorelease` before they
return an object. If you are not working in an environment (such as an
Application Delegate callback) that provides an autorelease pool, you can
create your own:
* Work directly with NSAutoreleasePool objects
```go
swamp := ns.NSAutoreleasePoolAlloc().Init()
del := ns.AppDelegateAlloc()
menu := ns.NSMenuAlloc().InitWithTitle(nst("Main"))
str := ns.NSStringWithGoString("these objects will be automatically deallocated when swamp is drained.")
...
swamp.Drain()
```
* ...or use the AutoreleasePool() helper function
NSWrap provides a helper function that can be passed a `func()` with no
parameters or return value. It is conventient to give it an anonymous function
and write your code in line, just like you would if you were using an
`@autoreleasepool { }` block.
```go
ns.AutoreleasePool(func() {
a := MyObjectAlloc().Init()
b := MyOtherObjectAlloc().Init()
...
})
```
You will need to make sure `NSAutoreleasePool` is included in the `classes`
directive in your configuration file before working with
`NSAutoreleasePool` objects or the `AutoreleasePool` helper function.
Memory management seems to work but there ought to be a comprehensive
tests before anyone should feel confident with it.
## Delegates ## Delegates
The `delegates` directive in `nswrap.yaml` creates a new Objective-C The `delegates` directive in `nswrap.yaml` creates a new Objective-C
class and associated Go wrapper functions. For example, the following class and associated Go wrapper functions. For example, the following
configuration file creates a class called `CBDelegate` that implements configuration file creates a class called `CBDelegate` that implements
the Objective-C protocols `CBCentralManagerDelegate` and the `CBCentralManagerDelegate` and `CBPeripheralDelegate`
`CBPeripheralDelegate`, along with the Go code you need to allocate protocols from Core Bluetooth, along with the Go code you need to allocate
and use instances of the class. and use instances of the new class.
```yaml ```yaml
# nswrap.yaml # nswrap.yaml
@@ -492,36 +509,44 @@ delegates:
... ...
``` ```
The generated delegate inherits from NSObject and is identified as implementing The generated delegate inherits from `NSObject` and, in its interface
the protocols specified in `nswrap.yaml`. declaration, is advertised as implementing the protocols specified in
`nswrap.yaml`.
When a delegate is activated and one of the callback methods named in the When a delegate is activated and one of the callback methods named in the
configuration file is called, the delegate will call back into an exported Go configuration file is called, the delegate will call back into a Go
function. If a user-defined callback function has been specified, function exported by NSWrap. If a user-defined callback function has been
registered,
it will be called with all of its parameters converted to their Go type it will be called with all of its parameters converted to their Go type
equivalents. User-defined callbacks are registered by calling a function equivalents. User-defined callbacks are registered by calling a function
with the method name in TitleCase + `Callback`, so in the example above, with the method name in TitleCase + `Callback`, so in the example above,
call `ns.CentralManagerDidUpdateStateCallback(...)` with the name of your if your delegate was named `del`, you would call
callback function to register to receive notifications when your central `del.CentralManagerDidUpdateStateCallback(...)` with the name of
your callback function to register to receive notifications when your central
manager updates its state. manager updates its state.
The code in `examples/bluetooth` implements a working Bluetooth Low Energy The example in `examples/bluetooth` implements a working Bluetooth Low-Energy
heart rate monitor entirely in Go. heart rate monitor entirely in Go.
The following Go code creates a CBDelegate object in Go, The following Go code instantiates a `CBDelegate` object,
registers a callback for `centralManagerDidUpdateState`, allocates registers a callback for `centralManagerDidUpdateState`, allocates
a CBCentralManager object, and installs our delegate: a `CBCentralManager` object, and installs our delegate:
```go ```go
func cb(c ns.CBCentralManager) { func cb(self ns.CBDelegate, c *ns.CBCentralManager) {
... ...
} }
var (
del *ns.CBDelegate // use global variables so these don't get garbage collected
cm *ns.CBCentralManager
)
func main() { func main() {
... ...
del := ns.CBDelegateAlloc() del = ns.CBDelegateAlloc()
del.CentralManagerDidUpdateStateCallback(cb) del.CentralManagerDidUpdateStateCallback(cb)
cm := ns.CBCentralManagerAlloc().InitWithDelegateQueue(del,queue) cm = ns.CBCentralManagerAlloc().InitWithDelegateQueue(del,queue)
``` ```
When you provide user-defined callback functions, you will need to specify When you provide user-defined callback functions, you will need to specify
@@ -532,24 +557,23 @@ messages will point you in the right direction.
``` ```
$ go build $ go build
./main.go:127:43: cannot use didFinishLaunching (type func(ns.NSNotification, bool)) as type ./main.go:127:43: cannot use didFinishLaunching (type func(ns.CBDelegate, *ns.NSNotification, bool)) as type
func(ns.NSNotification) in argument to del.ApplicationDidFinishLaunchingCallback func(ns.CBDelegate, *ns.NSNotification) in argument to del.ApplicationDidFinishLaunchingCallback
``` ```
In the above example, build failed because an extra `bool` parameter was In the above example, the build failed because an extra `bool` parameter was
included in the callback function. The compiler is telling you that the right included in the callback function. The compiler is telling you that the right
type for the callback is `func(ns.NSNotification)` with no return value. type for the callback is `func(*ns.NSNotification)` with no return value.
## Working with AppKit ## Working with AppKit
You can wrap the AppKit framework classes and create an NSApplication You can wrap the AppKit framework classes and create an `NSApplication`
Delegate. This allows you to build a Cocoa app entirely in Go. Delegate. This allows you to build a Cocoa application entirely in Go.
Because AppKit uses thread local storage, you will need to make sure all Because AppKit uses thread local storage, you will need to make sure all
calls into it are done from the main OS thread. This can be a challenge in calls into it are done from the main OS thread. This can be a challenge in
Go even though runtime.LockOSThread() is supposed to provide Go and you will want to make use of `runtime.LockOSThread()`.
this functionality. Good luck with that!
This is actually a full working example: This is actually a full working Cocoa application:
```yaml ```yaml
# nswrap.yaml # nswrap.yaml
@@ -582,34 +606,43 @@ frameworks: [ Foundation, AppKit, CoreGraphics ]
//go:generate nswrap //go:generate nswrap
package main package main
//go:generate nswrap
package main
import ( import (
"fmt" "fmt"
"runtime" "runtime"
"git.wow.st/gmp/nswrap/examples/app/ns" // point to your NSWrap output directory "ns" // point to your own NSWrap output directory
) )
func didFinishLaunching(n ns.NSNotification) { func didFinishLaunching(self ns.AppDelegate, n *ns.NSNotification) {
fmt.Println("Go: did finish launching!") fmt.Println("Go: did finish launching!")
} }
func shouldTerminate(s ns.NSApplication) ns.BOOL { func shouldTerminate(self ns.AppDelegate, s *ns.NSApplication) ns.BOOL {
return 1 return true
} }
var (
a *ns.NSApplication // global vars so these are not garbage collected
del *ns.AppDelegate
win *ns.NSWindow
)
func main() { func main() {
runtime.LockOSThread() runtime.LockOSThread()
a := ns.NSApplicationSharedApplication() a = ns.NSApplicationSharedApplication()
a.SetActivationPolicy(ns.NSApplicationActivationPolicyRegular) a.SetActivationPolicy(ns.NSApplicationActivationPolicy(ns.NSApplicationActivationPolicyRegular))
del := ns.AppDelegateAlloc() del = ns.AppDelegateAlloc()
del.ApplicationDidFinishLaunchingCallback(didFinishLaunching) del.ApplicationDidFinishLaunchingCallback(didFinishLaunching)
del.ApplicationShouldTerminateAfterLastWindowClosedCallback(shouldTerminate) del.ApplicationShouldTerminateAfterLastWindowClosedCallback(shouldTerminate)
a.SetDelegate(del) a.SetDelegate(del)
win := ns.NSWindowAlloc().InitWithContentRectStyleMask( win = ns.NSWindowAlloc().InitWithContentRectStyleMask(
ns.NSMakeRect(200,200,600,600), ns.NSMakeRect(200,200,600,600),
ns.NSWindowStyleMaskTitled | ns.NSWindowStyleMaskClosable, ns.NSWindowStyleMask(ns.NSWindowStyleMaskTitled | ns.NSWindowStyleMaskClosable),
ns.NSBackingStoreBuffered, ns.NSBackingStoreType(ns.NSBackingStoreBuffered),
0, false,
) )
win.SetTitle(ns.NSStringWithGoString("Hi World")) win.SetTitle(ns.NSStringWithGoString("Hi World"))
win.MakeKeyAndOrderFront(win) win.MakeKeyAndOrderFront(win)
@@ -617,12 +650,14 @@ func main() {
} }
``` ```
Pretty simple right? Not really, NSWrap just generated almost 15,000 lines of Pretty simple right? Not really, NSWrap just generated 114,000 lines of
code. See `examples/app` for a slightly more complex example with working code. See `examples/app` for a slightly more complex example with working
menus and visual format-based auto layout. menus, visual format-based auto layout, and a custom button class.
## Subclasses ## Subclasses
### NOTE: SUBCLASS FUNCTIONALITY IS CURRENTLY PARTIALLY BROKEN
NSWrap includes functionality to generate subclasses as specified in NSWrap includes functionality to generate subclasses as specified in
`nswrap.yaml`. `nswrap.yaml`.
@@ -637,7 +672,7 @@ subclasses:
yourClass: # the superclass to inherit from yourClass: # the superclass to inherit from
- init.* # what methods to override - init.* # what methods to override
- -(void)hi_there:(int)x # Objective-C prototype of your new method(s) - -(void)hi_there:(int)x # Objective-C prototype of your new method(s)
# |--note the hyphen indicating that this is an instance method # \--the initial hyphen indicates that this is an instance method
``` ```
In the example above, your new class will be named `myClass` in Objective-C In the example above, your new class will be named `myClass` in Objective-C
@@ -652,8 +687,18 @@ name, its return type, and the names and types of its parameters if any.
Since multiple inheritance is not permitted in Objective-C, it is not possible Since multiple inheritance is not permitted in Objective-C, it is not possible
to specify more than one superclass in a `subclasses` entry. to specify more than one superclass in a `subclasses` entry.
Go callbacks for overridden methods are passed a special struct filled with
superclass methods, which allows you to do things like this:
```go
func methodCallback(self ns.MyClass, super ns.MyClassSupermethods, param NSString) {
...
super.Method(param)
}
```
You can use subclasses to define new AppKit controls with configurable You can use subclasses to define new AppKit controls with configurable
callbacks. For example, lets make an `NSButton` that calls back into Go when callbacks. For example, let's make an `NSButton` that calls back into Go when
you press it: you press it:
```yaml ```yaml
@@ -667,7 +712,7 @@ subclasses:
``` ```
```go ```go
func pressed() { func pressed(self ns.GButton, super ns.GButtonSupermethods) {
fmt.Println("Button pressed!") fmt.Println("Button pressed!")
} }
... ...
@@ -683,13 +728,113 @@ func didFinishLaunching(n ns.NSNotification) {
} }
``` ```
Later on you can add the your new button to a view and tell Cocoa where to lay Later on you can add your new button to a view and tell Cocoa where to lay
it out. It's all a little verbose, but that's because for some reason you it out. It's all a little verbose, but that's because for some reason you
decided to write Objective-C code in Go. decided to write Objective-C code in Go.
## Memory management
As mentioned above, NSWrap is designed for there to be at least one Go pointer
associated with each underlying Objective-C object pointer.
Since Objective-C memory
is always allocated by the Objective-C runtime, it is not possible for the Go
runtime to have visibility into these memory regions or to directly manage memory
used by the CGo code. However, Go will keep track of the associated Go pointer
that was created the first time the corresponding Objective-C object was passed
over to the Go side and an `Id` or other NSWrap struct type was allocated.
Because of this,
it is possible to hook into the Go garbage collection system in an attempt to
manage Objective-C memory strictly from the Go side. When there are no remaining Go
pointers to an NSWrap `Id` struct, it will be deallocated by the Go garbage collector
and a finalizer will be called that `release`es the corresponding Objective-C
object.
The memory management rules work as follows:
* Objects in Go are represented by pointers to types that implement the `NSObject`
interface
* NSObject has one method, `Ptr()`, which returns an `unsafe.Pointer` to an
Objective-C object.
* All methods that return objects to Go call `retain` except for `new`, `init`,
`alloc`, `copy` and `mutableCopy`, which already return retained objects from the
Objective-C runtime.
* Go wrappers for Objective-C methods call `runtime.SetFinalizer()`, which calls
`release` when the associated Go struct is garbage collected.
* All Objective-C methods are run inside an `@autoreleasepool {}` block to prevent
internal memory leaks within the Objective-C libraries and frameworks.
* Objects sent to you in callback functions are not memory managed by Go
and must be manually
managed using `Retain()` and `Release()` methods if you need to take ownership of them.
A rule of thumb is that if you assign such an object to a persistent Go variable for
use outside of the callback, call `Retain()`.
Because of the linkage with the Go garbage collector described above, there should be
no need for any memory management code to be written from the Go side, except in the
case mentioned above where your Go delegate receives objects that need to be kept
around outside of the callback.
Since everything in Objective C inherits methods from `NSObject`, you can call
`Retain()`, `Release()` and `Autorelease()` on any object. You can technically bind
the `NSAutoreleasePool` class and create and drain instances of it from the Go side,
but this is not recommended in the default, garbage collected mode and can run into
problems because the Go runtime is inherently multithreaded. See `examples/memory`
for an example of manual memory management, which should be possible to do reliably
but I'm not sure why you would go through the trouble.
NSWrap is doing a number of things behind the scenes to make garbage collection work.
As mentioned,
all Objective-C methods are called within an `@autorelease {}` block. This is
necessary because some foundation classes (notably `NSString`) create internal
objects that are `autoreleased` but never returned to the caller. These objects can
never be deallocated unless the method in question was called within an autorelease
pool.
NSWrap assumes you
are going to take ownership of every Objective-C object returned by a method, either
directly as a return value or through a pointer to a pointer given as a parameter.
Therefore, NSWrap calls `retain` on all of these objects before going back to the
Go side, unless the object is either `nil` or equivalent to the input object.
NSWrap also will not call `retain` on the return values of `init`, `new`, `copy`,
`mutableCopy` or `alloc` methods. If you do not want ownership of the object,
simply assign it to a local varable and the garbage collector will take care of
releasing it.
In
order for this to work on a pointer to a pointer parameter, NSWrap treats the
input
parameter as an array with a length specified by either a `range` parameter (of
type `NSRange`) or a `count` parameter of an integer type. If there is neither a
`range` or `count` parameter, NSWrap assumes the array is length 1.
As an example, in Objective-C, if you were to take an object out of an `NSArray`
and the array was later deallocated, there is no guarantee that the object you
obtained is still around unless you called `retain` on it. This is not necessary
with NSWrap, which automatically retains objects returned by methods like
`objectAtIndex:` and `getObjects:range` and manages them with the Go garbage
collector.
The methods described above work for methods that return Objective-C
objects, which can be `retain`ed, but not with methods that return other types of
pointers such as C strings. NSWrap has a special case for C strings (`*Char`
in Go), calling
`strdup` on the return value within the `@autoreleasepool` block. This
ensures that the string is preserved even if it points to a termporary
autoreleased
object. Since this behavior results in newly allocated memory, these pointers will
need to be freed from Go later on. Since these are pointers to C memory,
it is not possible to set a finalizer on these pointers for garbage collection
by Go.
Note that the Go garbage collector is lazy and will not activate unless your
application is running low on heap space. That means in practice that Objective-C
objects are going to stick around a lot longer than they might in a pure
Objective-C application. If this is an issue, simply run the Go GC manually with
`runtime.GC()`.
# Limitations # Limitations
## Blocks ## Blocks and Function Pointers
NSWrap does not support methods or functions that take C functions or blocks NSWrap does not support methods or functions that take C functions or blocks
as parameters or return values. as parameters or return values.
@@ -701,7 +846,7 @@ and got carried away.
# Acknowledgements # Acknowledgements
This work was inspired by Maxim's excellent This work was inspired by Maxim Kupriianov's excellent
[c-for-go](https://github.com/xlab/c-for-go). Much of the [c-for-go](https://github.com/xlab/c-for-go). Much of the
infrastructure was lifted from Elliot Chance's equally excellent infrastructure was lifted from Elliot Chance's equally excellent
[c2go](https://github.com/elliotchance/c2go). Kiyoshi Murata's [c2go](https://github.com/elliotchance/c2go). Kiyoshi Murata's
+4 -1
View File
@@ -9,11 +9,14 @@ type AlignedAttr struct {
ChildNodes []Node ChildNodes []Node
} }
func parseAlignedAttr(line string) *AlignedAttr { func parseAlignedAttr(line string) Node {
groups := groupsFromRegex( groups := groupsFromRegex(
"<(?P<position>.*)>(?P<aligned> aligned)?", "<(?P<position>.*)>(?P<aligned> aligned)?",
line, line,
) )
if groups == nil {
return &Unknown{}
}
return &AlignedAttr{ return &AlignedAttr{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
+11 -3
View File
@@ -5,19 +5,27 @@ import (
) )
func TestAlignedAttr(t *testing.T) { func TestAlignedAttr(t *testing.T) {
nodes := map[string]Node{ nodes := map[string]testNode{
`0x7f8a1d8ccfd0 <col:47, col:57> aligned`: &AlignedAttr{ `0x7f8a1d8ccfd0 <col:47, col:57> aligned`: testNode{&AlignedAttr{
Addr: 0x7f8a1d8ccfd0, Addr: 0x7f8a1d8ccfd0,
Pos: NewPositionFromString("col:47, col:57"), Pos: NewPositionFromString("col:47, col:57"),
IsAligned: true, IsAligned: true,
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
`0x2c8ba10 <col:42>`: &AlignedAttr{ 0x7f8a1d8ccfd0,
NewPositionFromString("col:47, col:57"),
[]Node{},
},
`0x2c8ba10 <col:42>`: testNode{&AlignedAttr{
Addr: 0x2c8ba10, Addr: 0x2c8ba10,
Pos: NewPositionFromString("col:42"), Pos: NewPositionFromString("col:42"),
IsAligned: false, IsAligned: false,
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
0x2c8ba10,
NewPositionFromString("col:42"),
[]Node{},
},
} }
runNodeTests(t, nodes) runNodeTests(t, nodes)
+9 -7
View File
@@ -2,8 +2,7 @@ package ast
import ( import (
"strings" "strings"
//"git.wow.st/gmp/nswrap/util"
"github.com/elliotchance/c2go/util"
) )
// AllocSizeAttr is a type of attribute that is optionally attached to a variable // AllocSizeAttr is a type of attribute that is optionally attached to a variable
@@ -12,23 +11,26 @@ type AllocSizeAttr struct {
Addr Address Addr Address
Pos Position Pos Position
Inherited bool Inherited bool
A int A string
B int B string
ChildNodes []Node ChildNodes []Node
} }
func parseAllocSizeAttr(line string) *AllocSizeAttr { func parseAllocSizeAttr(line string) Node {
groups := groupsFromRegex( groups := groupsFromRegex(
`<(?P<position>.*)>(?P<inherited> Inherited)?(?P<a> \d+)(?P<b> \d+)?`, `<(?P<position>.*)>(?P<inherited> Inherited)?(?P<a> \d+)(?P<b> \d+)?`,
line, line,
) )
if groups == nil {
return &Unknown{}
}
return &AllocSizeAttr{ return &AllocSizeAttr{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
Pos: NewPositionFromString(groups["position"]), Pos: NewPositionFromString(groups["position"]),
Inherited: len(groups["inherited"]) > 0, Inherited: len(groups["inherited"]) > 0,
A: util.Atoi(strings.TrimSpace(groups["a"])), A: strings.TrimSpace(groups["a"]),
B: util.Atoi(strings.TrimSpace(groups["b"])), B: strings.TrimSpace(groups["b"]),
ChildNodes: []Node{}, ChildNodes: []Node{},
} }
} }
+27 -7
View File
@@ -5,22 +5,42 @@ import (
) )
func TestAllocSizeAttr(t *testing.T) { func TestAllocSizeAttr(t *testing.T) {
nodes := map[string]Node{ nodes := map[string]testNode{
`0x7f8e390a5d38 <col:100, col:114> 1 2`: &AllocSizeAttr{ `0x7f8e390a5d38 <col:100, col:114> 1 2`: testNode{&AllocSizeAttr{
Addr: 0x7f8e390a5d38, Addr: 0x7f8e390a5d38,
Pos: NewPositionFromString("col:100, col:114"), Pos: NewPositionFromString("col:100, col:114"),
A: 1, A: "1",
B: 2, B: "2",
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
`0x7fbd1a167f48 </usr/include/stdlib.h:342:37> Inherited 1 0`: &AllocSizeAttr{ 0x7f8e390a5d38,
NewPositionFromString("col:100, col:114"),
[]Node{},
},
`0x7fbd1a167f48 </usr/include/stdlib.h:342:37> Inherited 1 0`: testNode{&AllocSizeAttr{
Addr: 0x7fbd1a167f48, Addr: 0x7fbd1a167f48,
Pos: NewPositionFromString("/usr/include/stdlib.h:342:37"), Pos: NewPositionFromString("/usr/include/stdlib.h:342:37"),
Inherited: true, Inherited: true,
A: 1, A: "1",
B: 0, B: "0",
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
0x7fbd1a167f48,
NewPositionFromString("/usr/include/stdlib.h:342:37"),
[]Node{},
},
`0x7fbd1a167f48 </usr/include/stdlib.h:342:37> Inherited 1`: testNode{&AllocSizeAttr{
Addr: 0x7fbd1a167f48,
Pos: NewPositionFromString("/usr/include/stdlib.h:342:37"),
Inherited: true,
A: "1",
B: "",
ChildNodes: []Node{},
},
0x7fbd1a167f48,
NewPositionFromString("/usr/include/stdlib.h:342:37"),
[]Node{},
},
} }
runNodeTests(t, nodes) runNodeTests(t, nodes)
+4 -1
View File
@@ -8,11 +8,14 @@ type AlwaysInlineAttr struct {
ChildNodes []Node ChildNodes []Node
} }
func parseAlwaysInlineAttr(line string) *AlwaysInlineAttr { func parseAlwaysInlineAttr(line string) Node {
groups := groupsFromRegex( groups := groupsFromRegex(
"<(?P<position>.*)> always_inline", "<(?P<position>.*)> always_inline",
line, line,
) )
if groups == nil {
return &Unknown{}
}
return &AlwaysInlineAttr{ return &AlwaysInlineAttr{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
+6 -2
View File
@@ -5,12 +5,16 @@ import (
) )
func TestAlwaysInlineAttr(t *testing.T) { func TestAlwaysInlineAttr(t *testing.T) {
nodes := map[string]Node{ nodes := map[string]testNode{
`0x7fce780f5018 </usr/include/sys/cdefs.h:313:68> always_inline`: &AlwaysInlineAttr{ `0x7fce780f5018 </usr/include/sys/cdefs.h:313:68> always_inline`: testNode{&AlwaysInlineAttr{
Addr: 0x7fce780f5018, Addr: 0x7fce780f5018,
Pos: NewPositionFromString("/usr/include/sys/cdefs.h:313:68"), Pos: NewPositionFromString("/usr/include/sys/cdefs.h:313:68"),
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
0x7fce780f5018,
NewPositionFromString("/usr/include/sys/cdefs.h:313:68"),
[]Node{},
},
} }
runNodeTests(t, nodes) runNodeTests(t, nodes)
+47
View File
@@ -0,0 +1,47 @@
package ast
// ArcWeakrefUnavailableAttr
type ArcWeakrefUnavailableAttr struct {
Addr Address
Pos Position
ChildNodes []Node
}
func parseArcWeakrefUnavailableAttr(line string) Node {
groups := groupsFromRegex(
"<(?P<position>.*)>",
line,
)
if groups == nil {
return &Unknown{}
}
return &ArcWeakrefUnavailableAttr{
Addr: ParseAddress(groups["address"]),
Pos: NewPositionFromString(groups["position"]),
ChildNodes: []Node{},
}
}
// AddChild adds a new child node. Child nodes can then be accessed with the
// Children attribute.
func (n *ArcWeakrefUnavailableAttr) AddChild(node Node) {
n.ChildNodes = append(n.ChildNodes, node)
}
// Address returns the numeric address of the node. See the documentation for
// the Address type for more information.
func (n *ArcWeakrefUnavailableAttr) Address() Address {
return n.Addr
}
// Children returns the child nodes. If this node does not have any children or
// this node does not support children it will always return an empty slice.
func (n *ArcWeakrefUnavailableAttr) Children() []Node {
return n.ChildNodes
}
// Position returns the position in the original source code.
func (n *ArcWeakrefUnavailableAttr) Position() Position {
return n.Pos
}
+21
View File
@@ -0,0 +1,21 @@
package ast
import (
"testing"
)
func TestArcWeakrefUnavailableAttr(t *testing.T) {
nodes := map[string]testNode{
`0x7fc0a69091d1 <line:11:7, line:18:7>`: testNode{&ArcWeakrefUnavailableAttr{
Addr: 0x7fc0a69091d1,
Pos: NewPositionFromString("line:11:7, line:18:7"),
ChildNodes: []Node{},
},
0x7fc0a69091d1,
NewPositionFromString("line:11:7, line:18:7"),
[]Node{},
},
}
runNodeTests(t, nodes)
}
+5 -12
View File
@@ -1,20 +1,13 @@
package ast package ast
import ( import (
"reflect"
"testing" "testing"
"github.com/elliotchance/c2go/util"
) )
func TestArrayFiller(t *testing.T) { func TestArrayFiller(t *testing.T) {
expected := &ArrayFiller{ i := 0
ChildNodes: []Node{}, runNodeTest(t, Parse(`array filler`),
} testNode{&ArrayFiller{ChildNodes: []Node{}},
actual := Parse(`array filler`) 0, NewPositionFromString(""), []Node{}},
&i)
if !reflect.DeepEqual(expected, actual) {
t.Errorf("%s", util.ShowDiff(formatMultiLine(expected),
formatMultiLine(actual)))
}
} }
+4 -1
View File
@@ -11,13 +11,16 @@ type ArraySubscriptExpr struct {
ChildNodes []Node ChildNodes []Node
} }
func parseArraySubscriptExpr(line string) *ArraySubscriptExpr { func parseArraySubscriptExpr(line string) Node {
groups := groupsFromRegex( groups := groupsFromRegex(
`<(?P<position>.*)> '(?P<type>.*?)'(:'(?P<type2>.*?)')? `<(?P<position>.*)> '(?P<type>.*?)'(:'(?P<type2>.*?)')?
(?P<lvalue> lvalue)? (?P<lvalue> lvalue)?
(?P<vcomp> vectorcomponent)?`, (?P<vcomp> vectorcomponent)?`,
line, line,
) )
if groups == nil {
return &Unknown{}
}
return &ArraySubscriptExpr{ return &ArraySubscriptExpr{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
+16 -4
View File
@@ -5,8 +5,8 @@ import (
) )
func TestArraySubscriptExpr(t *testing.T) { func TestArraySubscriptExpr(t *testing.T) {
nodes := map[string]Node{ nodes := map[string]testNode{
`0x7fe35b85d180 <col:63, col:69> 'char *' lvalue`: &ArraySubscriptExpr{ `0x7fe35b85d180 <col:63, col:69> 'char *' lvalue`: testNode{&ArraySubscriptExpr{
Addr: 0x7fe35b85d180, Addr: 0x7fe35b85d180,
Pos: NewPositionFromString("col:63, col:69"), Pos: NewPositionFromString("col:63, col:69"),
Type: "char *", Type: "char *",
@@ -14,7 +14,11 @@ func TestArraySubscriptExpr(t *testing.T) {
IsLvalue: true, IsLvalue: true,
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
`0x2416660 <col:2, col:5> 'u32':'unsigned int' lvalue`: &ArraySubscriptExpr{ 0x7fe35b85d180,
NewPositionFromString("col:63, col:69"),
[]Node{},
},
`0x2416660 <col:2, col:5> 'u32':'unsigned int' lvalue`: testNode{&ArraySubscriptExpr{
Addr: 0x2416660, Addr: 0x2416660,
Pos: NewPositionFromString("col:2, col:5"), Pos: NewPositionFromString("col:2, col:5"),
Type: "u32", Type: "u32",
@@ -22,7 +26,11 @@ func TestArraySubscriptExpr(t *testing.T) {
IsLvalue: true, IsLvalue: true,
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
`0x3f147c0 <col:39, col:55> 'extCoord':'extCoord' lvalue`: &ArraySubscriptExpr{ 0x2416660,
NewPositionFromString("col:2, col:5"),
[]Node{},
},
`0x3f147c0 <col:39, col:55> 'extCoord':'extCoord' lvalue`: testNode{&ArraySubscriptExpr{
Addr: 0x3f147c0, Addr: 0x3f147c0,
Pos: NewPositionFromString("col:39, col:55"), Pos: NewPositionFromString("col:39, col:55"),
Type: "extCoord", Type: "extCoord",
@@ -30,6 +38,10 @@ func TestArraySubscriptExpr(t *testing.T) {
IsLvalue: true, IsLvalue: true,
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
0x3f147c0,
NewPositionFromString("col:39, col:55"),
[]Node{},
},
} }
runNodeTests(t, nodes) runNodeTests(t, nodes)
+8 -2
View File
@@ -5,22 +5,28 @@ type AsmLabelAttr struct {
Addr Address Addr Address
Pos Position Pos Position
Inherited bool Inherited bool
LiteralLabel bool
FunctionName string FunctionName string
ChildNodes []Node ChildNodes []Node
} }
func parseAsmLabelAttr(line string) *AsmLabelAttr { func parseAsmLabelAttr(line string) Node {
groups := groupsFromRegex( groups := groupsFromRegex(
`<(?P<position>.*)> `<(?P<position>.*)>
(?P<inherited> Inherited)? (?P<inherited> Inherited)?
"(?P<function>.+)"`, "(?P<function>.+)"
(?P<isliterallabel> IsLiteralLabel)?`,
line, line,
) )
if groups == nil {
return &Unknown{}
}
return &AsmLabelAttr{ return &AsmLabelAttr{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
Pos: NewPositionFromString(groups["position"]), Pos: NewPositionFromString(groups["position"]),
Inherited: len(groups["inherited"]) > 0, Inherited: len(groups["inherited"]) > 0,
LiteralLabel: len(groups["isliterallabel"]) > 0,
FunctionName: groups["function"], FunctionName: groups["function"],
ChildNodes: []Node{}, ChildNodes: []Node{},
} }
+25 -3
View File
@@ -5,21 +5,43 @@ import (
) )
func TestAsmLabelAttr(t *testing.T) { func TestAsmLabelAttr(t *testing.T) {
nodes := map[string]Node{ nodes := map[string]testNode{
`0x7ff26d8224e8 </usr/include/sys/cdefs.h:569:36> "_fopen"`: &AsmLabelAttr{ `0x7ff26d8224e8 </usr/include/sys/cdefs.h:569:36> "_fopen"`: testNode{&AsmLabelAttr{
Addr: 0x7ff26d8224e8, Addr: 0x7ff26d8224e8,
Pos: NewPositionFromString("/usr/include/sys/cdefs.h:569:36"), Pos: NewPositionFromString("/usr/include/sys/cdefs.h:569:36"),
Inherited: false, Inherited: false,
LiteralLabel: false,
FunctionName: "_fopen", FunctionName: "_fopen",
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
`0x7fd55a169318 </usr/include/stdio.h:325:47> Inherited "_popen"`: &AsmLabelAttr{ 0x7ff26d8224e8,
NewPositionFromString("/usr/include/sys/cdefs.h:569:36"),
[]Node{},
},
`0x7fd55a169318 </usr/include/stdio.h:325:47> Inherited "_popen"`: testNode{&AsmLabelAttr{
Addr: 0x7fd55a169318, Addr: 0x7fd55a169318,
Pos: NewPositionFromString("/usr/include/stdio.h:325:47"), Pos: NewPositionFromString("/usr/include/stdio.h:325:47"),
Inherited: true, Inherited: true,
LiteralLabel: false,
FunctionName: "_popen", FunctionName: "_popen",
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
0x7fd55a169318,
NewPositionFromString("/usr/include/stdio.h:325:47"),
[]Node{},
},
`0x7fd55a169318 </usr/include/stdio.h:325:47> "_kill" IsLiteralLabel`: testNode{&AsmLabelAttr{
Addr: 0x7fd55a169318,
Pos: NewPositionFromString("/usr/include/stdio.h:325:47"),
Inherited: false,
LiteralLabel: true,
FunctionName: "_kill",
ChildNodes: []Node{},
},
0x7fd55a169318,
NewPositionFromString("/usr/include/stdio.h:325:47"),
[]Node{},
},
} }
runNodeTests(t, nodes) runNodeTests(t, nodes)
+103 -8
View File
@@ -2,13 +2,17 @@
package ast package ast
import ( import (
"fmt"
"strconv" "strconv"
"strings" "strings"
"github.com/elliotchance/c2go/util" "git.wow.st/gmp/nswrap/util"
) )
var TrackPositions bool = false var (
TrackPositions bool = false
Debug = false
)
// Node represents any node in the AST. // Node represents any node in the AST.
type Node interface { type Node interface {
@@ -69,6 +73,8 @@ func Parse(fullline string) Node {
return parseAlwaysInlineAttr(line) return parseAlwaysInlineAttr(line)
case "ArraySubscriptExpr": case "ArraySubscriptExpr":
return parseArraySubscriptExpr(line) return parseArraySubscriptExpr(line)
case "ArcWeakrefUnavailableAttr":
return parseArcWeakrefUnavailableAttr(line)
case "AsmLabelAttr": case "AsmLabelAttr":
return parseAsmLabelAttr(line) return parseAsmLabelAttr(line)
case "AttributedType": case "AttributedType":
@@ -83,14 +89,30 @@ func Parse(fullline string) Node {
return parseBlockPointerType(line) return parseBlockPointerType(line)
case "BreakStmt": case "BreakStmt":
return parseBreakStmt(line) return parseBreakStmt(line)
case "BuiltinAttr":
return parseBuiltinAttr(line)
case "BuiltinType": case "BuiltinType":
return parseBuiltinType(line) return parseBuiltinType(line)
case "CallExpr": case "CallExpr":
return parseCallExpr(line) return parseCallExpr(line)
case "ConstantExpr":
return parseConstantExpr(line)
case "ConvertVectorExpr":
return parseConvertVectorExpr(line)
case "CaseStmt": case "CaseStmt":
return parseCaseStmt(line) return parseCaseStmt(line)
case "CFAuditedTransferAttr":
return parseCFAuditedTransferAttr(line)
case "CFConsumedAttr":
return parseCFConsumedAttr(line)
case "CFReturnsRetainedAttr":
return parseCFReturnsRetainedAttr(line)
case "CFReturnsNotRetainedAttr":
return parseCFReturnsNotRetainedAttr(line)
case "CharacterLiteral": case "CharacterLiteral":
return parseCharacterLiteral(line) return parseCharacterLiteral(line)
case "ColdAttr":
return parseColdAttr(line)
case "CompoundLiteralExpr": case "CompoundLiteralExpr":
return parseCompoundLiteralExpr(line) return parseCompoundLiteralExpr(line)
case "CompoundStmt": case "CompoundStmt":
@@ -129,12 +151,16 @@ func Parse(fullline string) Node {
return parseEnumConstantDecl(line) return parseEnumConstantDecl(line)
case "EnumDecl": case "EnumDecl":
return parseEnumDecl(line) return parseEnumDecl(line)
case "EnumExtensibilityAttr":
return parseEnumExtensibilityAttr(line)
case "EnumType": case "EnumType":
return parseEnumType(line) return parseEnumType(line)
case "Field": case "Field":
return parseField(line) return parseField(line)
case "FieldDecl": case "FieldDecl":
return parseFieldDecl(line) return parseFieldDecl(line)
case "FlagEnumAttr":
return parseFlagEnumAttr(line)
case "FloatingLiteral": case "FloatingLiteral":
return parseFloatingLiteral(line) return parseFloatingLiteral(line)
case "FormatAttr": case "FormatAttr":
@@ -157,6 +183,10 @@ func Parse(fullline string) Node {
return parseGCCAsmStmt(line) return parseGCCAsmStmt(line)
case "GotoStmt": case "GotoStmt":
return parseGotoStmt(line) return parseGotoStmt(line)
case "IBActionAttr":
return parseIBActionAttr(line)
case "IBOutletAttr":
return parseIBOutletAttr(line)
case "IfStmt": case "IfStmt":
return parseIfStmt(line) return parseIfStmt(line)
case "ImplicitCastExpr": case "ImplicitCastExpr":
@@ -179,10 +209,18 @@ func Parse(fullline string) Node {
return parseMallocAttr(line) return parseMallocAttr(line)
case "MaxFieldAlignmentAttr": case "MaxFieldAlignmentAttr":
return parseMaxFieldAlignmentAttr(line) return parseMaxFieldAlignmentAttr(line)
case "MayAliasAttr":
return parseMayAliasAttr(line)
case "MemberExpr": case "MemberExpr":
return parseMemberExpr(line) return parseMemberExpr(line)
case "MinVectorWidthAttr":
return parseMinVectorWidthAttr(line)
case "ModeAttr": case "ModeAttr":
return parseModeAttr(line) return parseModeAttr(line)
case "NoDebugAttr":
return parseNoDebugAttr(line)
case "NoEscapeAttr":
return parseNoEscapeAttr(line)
case "NoInlineAttr": case "NoInlineAttr":
return parseNoInlineAttr(line) return parseNoInlineAttr(line)
case "NoThrowAttr": case "NoThrowAttr":
@@ -191,22 +229,50 @@ func Parse(fullline string) Node {
return parseNonNullAttr(line) return parseNonNullAttr(line)
case "NotTailCalledAttr": case "NotTailCalledAttr":
return parseNotTailCalledAttr(line) return parseNotTailCalledAttr(line)
case "NSConsumedAttr":
return parseNSConsumedAttr(line)
case "NSConsumesSelfAttr":
return parseNSConsumesSelfAttr(line)
case "NSErrorDomainAttr":
return parseNSErrorDomainAttr(line)
case "NSReturnsRetainedAttr":
return parseNSReturnsRetainedAttr(line)
case "ObjCBoolLiteralExpr":
return parseObjCBoolLiteralExpr(line)
case "ObjCBoxableAttr":
return parseObjCBoxableAttr(line)
case "ObjCBridgeAttr":
return parseObjCBridgeAttr(line)
case "ObjCBridgeRelatedAttr":
return parseObjCBridgeRelatedAttr(line)
case "ObjCBridgeMutableAttr":
return parseObjCBridgeMutableAttr(line)
case "ObjCCategoryDecl": case "ObjCCategoryDecl":
return parseObjCCategoryDecl(line) return parseObjCCategoryDecl(line)
case "ObjCImplementation": case "ObjCDesignatedInitializerAttr":
return parseObjCImplementation(line) return parseObjCDesignatedInitializerAttr(line)
case "ObjCExceptionAttr":
return parseObjCExceptionAttr(line)
case "ObjCExplicitProtocolImplAttr":
return parseObjCExplicitProtocolImplAttr(line)
case "ObjCIndependentClassAttr":
return parseObjCIndependentClassAttr(line)
case "ObjCInterface": case "ObjCInterface":
return parseObjCInterface(line,false) return parseObjCInterface(line, false)
case "super ObjCInterface": case "super ObjCInterface":
return parseObjCInterface(line,true) return parseObjCInterface(line, true)
case "ObjCInterfaceDecl": case "ObjCInterfaceDecl":
return parseObjCInterfaceDecl(line) return parseObjCInterfaceDecl(line)
case "ObjCInterfaceType": case "ObjCInterfaceType":
return parseObjCInterfaceType(line) return parseObjCInterfaceType(line)
case "ObjCIvarDecl":
return parseObjCIvarDecl(line)
case "getter ObjCMethod": case "getter ObjCMethod":
return parseObjCMethod(line) return parseObjCMethod(line)
case "ObjCMethod": case "ObjCMethod":
return parseObjCMethod(line) return parseObjCMethod(line)
case "ObjCMessageExpr":
return parseObjCMessageExpr(line)
case "ObjCMethodDecl": case "ObjCMethodDecl":
return parseObjCMethodDecl(line) return parseObjCMethodDecl(line)
case "ObjCObjectType": case "ObjCObjectType":
@@ -215,10 +281,18 @@ func Parse(fullline string) Node {
return parseObjCObjectPointerType(line) return parseObjCObjectPointerType(line)
case "ObjCProtocol": case "ObjCProtocol":
return parseObjCProtocol(line) return parseObjCProtocol(line)
case "ObjCReturnsInnerPointerAttr":
return parseObjCReturnsInnerPointerAttr(line)
case "ObjCRequiresSuperAttr":
return parseObjCRequiresSuperAttr(line)
case "ObjCProtocolDecl": case "ObjCProtocolDecl":
return parseObjCProtocolDecl(line) return parseObjCProtocolDecl(line)
case "ObjCRootClassAttr":
return parseObjCRootClassAttr(line)
case "ObjCPropertyDecl": case "ObjCPropertyDecl":
return parseObjCPropertyDecl(line) return parseObjCPropertyDecl(line)
case "ObjCTypeParam":
return parseObjCTypeParam(line)
case "ObjCTypeParamDecl": case "ObjCTypeParamDecl":
return parseObjCTypeParamDecl(line) return parseObjCTypeParamDecl(line)
case "OffsetOfExpr": case "OffsetOfExpr":
@@ -259,12 +333,26 @@ func Parse(fullline string) Node {
return parseReturnsTwiceAttr(line) return parseReturnsTwiceAttr(line)
case "SentinelAttr": case "SentinelAttr":
return parseSentinelAttr(line) return parseSentinelAttr(line)
case "ShuffleVectorExpr":
return parseShuffleVectorExpr(line)
case "StmtExpr": case "StmtExpr":
return parseStmtExpr(line) return parseStmtExpr(line)
case "StringLiteral": case "StringLiteral":
return parseStringLiteral(line) return parseStringLiteral(line)
case "SwiftBridgedTypedefAttr":
return parseSwiftBridgedTypedefAttr(line)
case "SwiftErrorAttr":
return parseSwiftErrorAttr(line)
case "SwiftNameAttr":
return parseSwiftNameAttr(line)
case "SwiftNewtypeAttr":
return parseSwiftNewtypeAttr(line)
case "SwiftPrivateAttr":
return parseSwiftPrivateAttr(line)
case "SwitchStmt": case "SwitchStmt":
return parseSwitchStmt(line) return parseSwitchStmt(line)
case "TargetAttr":
return parseTargetAttr(line)
case "TextComment": case "TextComment":
return parseTextComment(line) return parseTextComment(line)
case "TranslationUnitDecl": case "TranslationUnitDecl":
@@ -283,6 +371,8 @@ func Parse(fullline string) Node {
return parseUnaryOperator(line) return parseUnaryOperator(line)
case "UnavailableAttr": case "UnavailableAttr":
return parseUnavailableAttr(line) return parseUnavailableAttr(line)
case "UsedAttr":
return parseUsedAttr(line)
case "UnusedAttr": case "UnusedAttr":
return parseUnusedAttr(line) return parseUnusedAttr(line)
case "VAArgExpr": case "VAArgExpr":
@@ -303,6 +393,8 @@ func Parse(fullline string) Node {
return parseWarnUnusedResultAttr(line) return parseWarnUnusedResultAttr(line)
case "WeakAttr": case "WeakAttr":
return parseWeakAttr(line) return parseWeakAttr(line)
case "WeakImportAttr":
return parseWeakImportAttr(line)
case "WhileStmt": case "WhileStmt":
return parseWhileStmt(line) return parseWhileStmt(line)
case "...": case "...":
@@ -310,7 +402,7 @@ func Parse(fullline string) Node {
case "NullStmt": case "NullStmt":
return nil return nil
default: default:
return parseUnknown(nodeName,line) return parseUnknown(nodeName, line)
} }
} }
@@ -325,7 +417,10 @@ func groupsFromRegex(rx, line string) map[string]string {
re := util.GetRegex(rx) re := util.GetRegex(rx)
match := re.FindStringSubmatch(line) match := re.FindStringSubmatch(line)
if len(match) == 0 { if len(match) == 0 {
panic("could not match regexp with string\n" + rx + "\n" + line + "\n") if Debug {
fmt.Printf("AST parser: could not match regexp with string. Regexp:\n" + rx + "\nOriginal line:\n" + line + "\n\n")
}
return nil
} }
result := make(map[string]string) result := make(map[string]string)
+54 -16
View File
@@ -6,9 +6,20 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/elliotchance/c2go/util" "git.wow.st/gmp/nswrap/util"
) )
type testNode struct {
n Node
addr Address
pos Position
children []Node
}
func init() {
TrackPositions = true
}
func formatMultiLine(o interface{}) string { func formatMultiLine(o interface{}) string {
s := fmt.Sprintf("%#v", o) s := fmt.Sprintf("%#v", o)
s = strings.Replace(s, "{", "{\n", -1) s = strings.Replace(s, "{", "{\n", -1)
@@ -17,23 +28,50 @@ func formatMultiLine(o interface{}) string {
return s return s
} }
func runNodeTests(t *testing.T, tests map[string]Node) { func runNodeTest(t *testing.T, actual Node, expected testNode, i *int) {
i := 1 testName := fmt.Sprintf("Example%d", *i)
for line, expected := range tests { t.Run(testName+"a", func(t *testing.T) {
testName := fmt.Sprintf("Example%d", i) if !reflect.DeepEqual(expected.n, actual) {
i++ t.Errorf("%s", util.ShowDiff(formatMultiLine(expected.n),
t.Run(testName, func(t *testing.T) {
// Append the name of the struct onto the front. This would make the
// complete line it would normally be parsing.
name := reflect.TypeOf(expected).Elem().Name()
actual := Parse(name + " " + line)
if !reflect.DeepEqual(expected, actual) {
t.Errorf("%s", util.ShowDiff(formatMultiLine(expected),
formatMultiLine(actual))) formatMultiLine(actual)))
} }
}) })
t.Run(testName+"b", func(t *testing.T) {
if !reflect.DeepEqual(actual.Address(), expected.addr) {
t.Errorf("Address mismatch")
}
})
t.Run(testName+"c", func(t *testing.T) {
if !reflect.DeepEqual(actual.Position(), expected.pos) {
t.Errorf("Position mismatch")
}
})
t.Run(testName+"d", func(t *testing.T) {
if !reflect.DeepEqual(actual.Children(), expected.children) {
t.Errorf("Children mismatch")
}
})
t.Run(testName+"e", func(t *testing.T) {
cs := expected.children
node := &Unknown{}
actual.AddChild(node)
cs = append(cs, node)
if !reflect.DeepEqual(actual.Children(), cs) {
t.Errorf("Children mismatch")
}
})
(*i)++
}
func runNodeTests(t *testing.T, tests map[string]testNode) {
i := 1
for line, expected := range tests {
// Append the name of the struct onto the front. This would
// make the complete line it would normally be parsing.
name := reflect.TypeOf(expected.n).Elem().Name()
actual := Parse(name + " " + line)
runNodeTest(t, actual, expected, &i)
} }
} }
@@ -58,7 +96,7 @@ func TestPrint(t *testing.T) {
} }
var lines = []string{ var lines = []string{
// c2go ast sqlite3.c | head -5000 | sed 's/^[ |`-]*//' | sed 's/<<<NULL>>>/NullStmt/g' | gawk 'length > 0 {print "`" $0 "`,"}' // c2go ast sqlite3.c | head -5000 | sed 's/^[ |`-]*//' | sed 's/<<<NULL>>>/NullStmt/g' | gawk 'length > 0 {print "`" $0 "`,"}'
} }
func BenchmarkParse(b *testing.B) { func BenchmarkParse(b *testing.B) {
+5 -2
View File
@@ -8,17 +8,20 @@ type AttributedType struct {
ChildNodes []Node ChildNodes []Node
} }
func parseAttributedType(line string) *AttributedType { func parseAttributedType(line string) Node {
groups := groupsFromRegex( groups := groupsFromRegex(
`'(?P<type>.*)' `'(?P<type>.*)'
(?P<sugar> sugar)?`, (?P<sugar> sugar)?`,
line, line,
) )
if groups == nil {
return &Unknown{}
}
return &AttributedType{ return &AttributedType{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
Type: groups["type"], Type: groups["type"],
Sugar: len(groups["sugar"])>0, Sugar: len(groups["sugar"]) > 0,
ChildNodes: []Node{}, ChildNodes: []Node{},
} }
} }
+82
View File
@@ -0,0 +1,82 @@
package ast
import (
"testing"
)
func TestAttributedType(t *testing.T) {
nodes := map[string]testNode{
`0x10c0d6770 'CVDisplayLinkRef _Nonnull' sugar`: testNode{&AttributedType{
Addr: 0x10c0d6770,
Type: `CVDisplayLinkRef _Nonnull`,
Sugar: true,
ChildNodes: []Node{},
},
0x10c0d6770,
NewPositionFromString(""),
[]Node{},
},
`0x10c0d68b0 'const CVTimeStamp * _Nonnull' sugar`: testNode{&AttributedType{
Addr: 0x10c0d68b0,
Type: `const CVTimeStamp * _Nonnull`,
Sugar: true,
ChildNodes: []Node{},
},
0x10c0d68b0,
NewPositionFromString(""),
[]Node{},
},
`0x10c0d6ab0 'CVOptionFlags * _Nonnull' sugar`: testNode{&AttributedType{
Addr: 0x10c0d6ab0,
Type: `CVOptionFlags * _Nonnull`,
Sugar: true,
ChildNodes: []Node{},
},
0x10c0d6ab0,
NewPositionFromString(""),
[]Node{},
},
`0x10c0fc7d0 'CVPixelBufferRef _Nonnull' sugar`: testNode{&AttributedType{
Addr: 0x10c0fc7d0,
Type: `CVPixelBufferRef _Nonnull`,
Sugar: true,
ChildNodes: []Node{},
},
0x10c0fc7d0,
NewPositionFromString(""),
[]Node{},
},
`0x7faa1906d680 'NSError * _Nullable' sugar`: testNode{&AttributedType{
Addr: 0x7faa1906d680,
Type: `NSError * _Nullable`,
Sugar: true,
ChildNodes: []Node{},
},
0x7faa1906d680,
NewPositionFromString(""),
[]Node{},
},
`0x7faa19085760 'id<NSSecureCoding> _Nullable' sugar`: testNode{&AttributedType{
Addr: 0x7faa19085760,
Type: `id<NSSecureCoding> _Nullable`,
Sugar: true,
ChildNodes: []Node{},
},
0x7faa19085760,
NewPositionFromString(""),
[]Node{},
},
`0x7faa19085840 'NSError * _Null_unspecified' sugar`: testNode{&AttributedType{
Addr: 0x7faa19085840,
Type: `NSError * _Null_unspecified`,
Sugar: true,
ChildNodes: []Node{},
},
0x7faa19085840,
NewPositionFromString(""),
[]Node{},
},
}
runNodeTests(t, nodes)
}
+7 -2
View File
@@ -9,6 +9,7 @@ type AvailabilityAttr struct {
Version string Version string
Unknown1 string Unknown1 string
Unknown2 string Unknown2 string
Unknown3 string
IsUnavailable bool IsUnavailable bool
Message1 string Message1 string
Message2 string Message2 string
@@ -16,7 +17,7 @@ type AvailabilityAttr struct {
ChildNodes []Node ChildNodes []Node
} }
func parseAvailabilityAttr(line string) *AvailabilityAttr { func parseAvailabilityAttr(line string) Node {
groups := groupsFromRegex( groups := groupsFromRegex(
`<(?P<position>.*)> `<(?P<position>.*)>
(?P<inherited> Inherited)? (?P<inherited> Inherited)?
@@ -26,9 +27,12 @@ func parseAvailabilityAttr(line string) *AvailabilityAttr {
(?P<unknown2>[\d_.]+) (?P<unknown2>[\d_.]+)
(?P<unavalable> Unavailable)? (?P<unavalable> Unavailable)?
"(?P<message1>.*?)" "(?P<message1>.*?)"
(?P<message2> ".*?")?`, (?P<message2> ".*?")?( (?P<unknown3>[\d_.]+))?`,
line, line,
) )
if groups == nil {
return &Unknown{}
}
return &AvailabilityAttr{ return &AvailabilityAttr{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
@@ -37,6 +41,7 @@ func parseAvailabilityAttr(line string) *AvailabilityAttr {
Version: groups["version"], Version: groups["version"],
Unknown1: groups["unknown1"], Unknown1: groups["unknown1"],
Unknown2: groups["unknown2"], Unknown2: groups["unknown2"],
Unknown3: groups["unknown3"],
IsUnavailable: len(groups["unavalable"]) > 0, IsUnavailable: len(groups["unavalable"]) > 0,
Message1: removeQuotes(groups["message1"]), Message1: removeQuotes(groups["message1"]),
Message2: removeQuotes(groups["message2"]), Message2: removeQuotes(groups["message2"]),
+83 -25
View File
@@ -5,111 +5,169 @@ import (
) )
func TestAvailabilityAttr(t *testing.T) { func TestAvailabilityAttr(t *testing.T) {
nodes := map[string]Node{ nodes := map[string]testNode{
`0x7fc5ff8e5d18 </usr/include/AvailabilityInternal.h:21697:88, col:124> macos 10.10 0 0 "" ""`: &AvailabilityAttr{ `0x7fc5ff8e5d18 </usr/include/AvailabilityInternal.h:21697:88, col:124> macos 10.10 0 0 "" ""`: testNode{&AvailabilityAttr{
Addr: 0x7fc5ff8e5d18, Addr: 0x7fc5ff8e5d18,
Pos: NewPositionFromString("/usr/include/AvailabilityInternal.h:21697:88, col:124"), Pos: NewPositionFromString("/usr/include/AvailabilityInternal.h:21697:88, col:124"),
OS: "macos", OS: "macos",
Version: "10.10", Version: "10.10",
Unknown1: 0, Unknown1: "0",
Unknown2: 0, Unknown2: "0",
Unknown3: "",
IsUnavailable: false, IsUnavailable: false,
Message1: "", Message1: "",
Message2: "", Message2: "",
IsInherited: false, IsInherited: false,
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
`0x7fc5ff8e60d0 </usr/include/Availability.h:215:81, col:115> watchos 3.0 0 0 "" ""`: &AvailabilityAttr{ 0x7fc5ff8e5d18,
NewPositionFromString("/usr/include/AvailabilityInternal.h:21697:88, col:124"),
[]Node{},
},
`0x7fc5ff8e60d0 </usr/include/Availability.h:215:81, col:115> watchos 3.0 0 0 "" ""`: testNode{&AvailabilityAttr{
Addr: 0x7fc5ff8e60d0, Addr: 0x7fc5ff8e60d0,
Pos: NewPositionFromString("/usr/include/Availability.h:215:81, col:115"), Pos: NewPositionFromString("/usr/include/Availability.h:215:81, col:115"),
OS: "watchos", OS: "watchos",
Version: "3.0", Version: "3.0",
Unknown1: 0, Unknown1: "0",
Unknown2: 0, Unknown2: "0",
Unknown3: "",
IsUnavailable: false, IsUnavailable: false,
Message1: "", Message1: "",
Message2: "", Message2: "",
IsInherited: false, IsInherited: false,
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
`0x7fc5ff8e6170 <col:81, col:115> tvos 10.0 0 0 "" ""`: &AvailabilityAttr{ 0x7fc5ff8e60d0,
NewPositionFromString("/usr/include/Availability.h:215:81, col:115"),
[]Node{},
},
`0x7fc5ff8e6170 <col:81, col:115> tvos 10.0 0 0 "" ""`: testNode{&AvailabilityAttr{
Addr: 0x7fc5ff8e6170, Addr: 0x7fc5ff8e6170,
Pos: NewPositionFromString("col:81, col:115"), Pos: NewPositionFromString("col:81, col:115"),
OS: "tvos", OS: "tvos",
Version: "10.0", Version: "10.0",
Unknown1: 0, Unknown1: "0",
Unknown2: 0, Unknown2: "0",
Unknown3: "",
IsUnavailable: false, IsUnavailable: false,
Message1: "", Message1: "",
Message2: "", Message2: "",
IsInherited: false, IsInherited: false,
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
`0x7fc5ff8e61d8 <col:81, col:115> ios 10.0 0 0 "" ""`: &AvailabilityAttr{ 0x7fc5ff8e6170,
NewPositionFromString("col:81, col:115"),
[]Node{},
},
`0x7fc5ff8e61d8 <col:81, col:115> ios 10.0 0 0 "" ""`: testNode{&AvailabilityAttr{
Addr: 0x7fc5ff8e61d8, Addr: 0x7fc5ff8e61d8,
Pos: NewPositionFromString("col:81, col:115"), Pos: NewPositionFromString("col:81, col:115"),
OS: "ios", OS: "ios",
Version: "10.0", Version: "10.0",
Unknown1: 0, Unknown1: "0",
Unknown2: 0, Unknown2: "0",
Unknown3: "",
IsUnavailable: false, IsUnavailable: false,
Message1: "", Message1: "",
Message2: "", Message2: "",
IsInherited: false, IsInherited: false,
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
`0x7fc5ff8f0e18 </usr/include/sys/cdefs.h:275:50, col:99> swift 0 0 0 Unavailable "Use snprintf instead." ""`: &AvailabilityAttr{ 0x7fc5ff8e61d8,
NewPositionFromString("col:81, col:115"),
[]Node{},
},
`0x7fc5ff8f0e18 </usr/include/sys/cdefs.h:275:50, col:99> swift 0 0 0 Unavailable "Use snprintf instead." ""`: testNode{&AvailabilityAttr{
Addr: 0x7fc5ff8f0e18, Addr: 0x7fc5ff8f0e18,
Pos: NewPositionFromString("/usr/include/sys/cdefs.h:275:50, col:99"), Pos: NewPositionFromString("/usr/include/sys/cdefs.h:275:50, col:99"),
OS: "swift", OS: "swift",
Version: "0", Version: "0",
Unknown1: 0, Unknown1: "0",
Unknown2: 0, Unknown2: "0",
Unknown3: "",
IsUnavailable: true, IsUnavailable: true,
Message1: "Use snprintf instead.", Message1: "Use snprintf instead.",
Message2: "", Message2: "",
IsInherited: false, IsInherited: false,
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
`0x7fc5ff8f1988 <line:275:50, col:99> swift 0 0 0 Unavailable "Use mkstemp(3) instead." ""`: &AvailabilityAttr{ 0x7fc5ff8f0e18,
NewPositionFromString("/usr/include/sys/cdefs.h:275:50, col:99"),
[]Node{},
},
`0x7fc5ff8f1988 <line:275:50, col:99> swift 0 0 0 Unavailable "Use mkstemp(3) instead." ""`: testNode{&AvailabilityAttr{
Addr: 0x7fc5ff8f1988, Addr: 0x7fc5ff8f1988,
Pos: NewPositionFromString("line:275:50, col:99"), Pos: NewPositionFromString("line:275:50, col:99"),
OS: "swift", OS: "swift",
Version: "0", Version: "0",
Unknown1: 0, Unknown1: "0",
Unknown2: 0, Unknown2: "0",
Unknown3: "",
IsUnavailable: true, IsUnavailable: true,
Message1: "Use mkstemp(3) instead.", Message1: "Use mkstemp(3) instead.",
Message2: "", Message2: "",
IsInherited: false, IsInherited: false,
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
`0x104035438 </usr/include/AvailabilityInternal.h:14571:88, col:124> macosx 10.10 0 0 ""`: &AvailabilityAttr{ 0x7fc5ff8f1988,
NewPositionFromString("line:275:50, col:99"),
[]Node{},
},
`0x104035438 </usr/include/AvailabilityInternal.h:14571:88, col:124> macosx 10.10 0 0 ""`: testNode{&AvailabilityAttr{
Addr: 0x104035438, Addr: 0x104035438,
Pos: NewPositionFromString("/usr/include/AvailabilityInternal.h:14571:88, col:124"), Pos: NewPositionFromString("/usr/include/AvailabilityInternal.h:14571:88, col:124"),
OS: "macosx", OS: "macosx",
Version: "10.10", Version: "10.10",
Unknown1: 0, Unknown1: "0",
Unknown2: 0, Unknown2: "0",
Unknown3: "",
IsUnavailable: false, IsUnavailable: false,
Message1: "", Message1: "",
Message2: "", Message2: "",
IsInherited: false, IsInherited: false,
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
`0x7f9bd588b1a8 </usr/include/gethostuuid.h:39:65, col:100> Inherited macos 10.5 0 0 "" ""`: &AvailabilityAttr{ 0x104035438,
NewPositionFromString("/usr/include/AvailabilityInternal.h:14571:88, col:124"),
[]Node{},
},
`0x7f9bd588b1a8 </usr/include/gethostuuid.h:39:65, col:100> Inherited macos 10.5 0 0 "" ""`: testNode{&AvailabilityAttr{
Addr: 0x7f9bd588b1a8, Addr: 0x7f9bd588b1a8,
Pos: NewPositionFromString("/usr/include/gethostuuid.h:39:65, col:100"), Pos: NewPositionFromString("/usr/include/gethostuuid.h:39:65, col:100"),
OS: "macos", OS: "macos",
Version: "10.5", Version: "10.5",
Unknown1: 0, Unknown1: "0",
Unknown2: 0, Unknown2: "0",
Unknown3: "",
IsUnavailable: false, IsUnavailable: false,
Message1: "", Message1: "",
Message2: "", Message2: "",
IsInherited: true, IsInherited: true,
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
0x7f9bd588b1a8,
NewPositionFromString("/usr/include/gethostuuid.h:39:65, col:100"),
[]Node{},
},
`0x7f9bd588b1a8 </usr/include/gethostuuid.h:39:65, col:100> Inherited macos 10.5 0 0 "" "" 1`: testNode{&AvailabilityAttr{
Addr: 0x7f9bd588b1a8,
Pos: NewPositionFromString("/usr/include/gethostuuid.h:39:65, col:100"),
OS: "macos",
Version: "10.5",
Unknown1: "0",
Unknown2: "0",
Unknown3: "1",
IsUnavailable: false,
Message1: "",
Message2: "",
IsInherited: true,
ChildNodes: []Node{},
},
0x7f9bd588b1a8,
NewPositionFromString("/usr/include/gethostuuid.h:39:65, col:100"),
[]Node{},
},
} }
runNodeTests(t, nodes) runNodeTests(t, nodes)
+4 -1
View File
@@ -10,11 +10,14 @@ type BinaryOperator struct {
ChildNodes []Node ChildNodes []Node
} }
func parseBinaryOperator(line string) *BinaryOperator { func parseBinaryOperator(line string) Node {
groups := groupsFromRegex( groups := groupsFromRegex(
"<(?P<position>.*)> '(?P<type1>.*?)'(:'(?P<type2>.*?)')? '(?P<operator>.*?)'", "<(?P<position>.*)> '(?P<type1>.*?)'(:'(?P<type2>.*?)')? '(?P<operator>.*?)'",
line, line,
) )
if groups == nil {
return &Unknown{}
}
return &BinaryOperator{ return &BinaryOperator{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
+12 -4
View File
@@ -5,22 +5,30 @@ import (
) )
func TestBinaryOperator(t *testing.T) { func TestBinaryOperator(t *testing.T) {
nodes := map[string]Node{ nodes := map[string]testNode{
`0x7fca2d8070e0 <col:11, col:23> 'unsigned char' '='`: &BinaryOperator{ `0x7fca2d8070e0 <col:11, col:23> 'unsigned char' '='`: testNode{&BinaryOperator{
Addr: 0x7fca2d8070e0, Addr: 0x7fca2d8070e0,
Pos: NewPositionFromString("col:11, col:23"), Pos: NewPositionFromString("col:11, col:23"),
Type: "unsigned char", Type: "unsigned char",
Operator: "=", Operator: "=",
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
`0x1ff95b8 <line:78:2, col:7> 'T_ENUM':'T_ENUM' '='`: &BinaryOperator{ 0x7fca2d8070e0,
NewPositionFromString("col:11, col:23"),
[]Node{},
},
`0x1ff95b8 <line:78:2, col:7> 'T_ENUM':'T_ENUM' '='`: testNode{&BinaryOperator{
Addr: 0x1ff95b8, Addr: 0x1ff95b8,
Pos: NewPositionFromString("line:78:2, col:7"), Pos: NewPositionFromString("line:78:2, col:7"),
Type: "T_ENUM", Type: "T_ENUM",
Type2: "T_ENUM", Type2: "",
Operator: "=", Operator: "=",
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
0x1ff95b8,
NewPositionFromString("line:78:2, col:7"),
[]Node{},
},
} }
runNodeTests(t, nodes) runNodeTests(t, nodes)
+4 -1
View File
@@ -8,11 +8,14 @@ type BlockCommandComment struct {
ChildNodes []Node ChildNodes []Node
} }
func parseBlockCommandComment(line string) *BlockCommandComment { func parseBlockCommandComment(line string) Node {
groups := groupsFromRegex( groups := groupsFromRegex(
`<(?P<position>.*)> Name="(?P<name>.*)"`, `<(?P<position>.*)> Name="(?P<name>.*)"`,
line, line,
) )
if groups == nil {
return &Unknown{}
}
return &BlockCommandComment{ return &BlockCommandComment{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
+6 -2
View File
@@ -5,13 +5,17 @@ import (
) )
func TestBlockCommandComment(t *testing.T) { func TestBlockCommandComment(t *testing.T) {
nodes := map[string]Node{ nodes := map[string]testNode{
`0x1069fae60 <col:4, line:163:57> Name="abstract"`: &BlockCommandComment{ `0x1069fae60 <col:4, line:163:57> Name="abstract"`: testNode{&BlockCommandComment{
Addr: 0x1069fae60, Addr: 0x1069fae60,
Pos: NewPositionFromString("col:4, line:163:57"), Pos: NewPositionFromString("col:4, line:163:57"),
Name: "abstract", Name: "abstract",
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
0x1069fae60,
NewPositionFromString("col:4, line:163:57"),
[]Node{},
},
} }
runNodeTests(t, nodes) runNodeTests(t, nodes)
+4 -1
View File
@@ -7,11 +7,14 @@ type BlockPointerType struct {
ChildNodes []Node ChildNodes []Node
} }
func parseBlockPointerType(line string) *BlockPointerType { func parseBlockPointerType(line string) Node {
groups := groupsFromRegex( groups := groupsFromRegex(
"'(?P<type>.*)'", "'(?P<type>.*)'",
line, line,
) )
if groups == nil {
return &Unknown{}
}
return &BlockPointerType{ return &BlockPointerType{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
+30
View File
@@ -0,0 +1,30 @@
package ast
import (
"testing"
)
func TestBlockPointerType(t *testing.T) {
nodes := map[string]testNode{
`0x7fa3b88bbb30 'void (^)(void)'`: testNode{&BlockPointerType{
Addr: 0x7fa3b88bbb30,
Type: `void (^)(void)`,
ChildNodes: []Node{},
},
0x7fa3b88bbb30,
NewPositionFromString(""),
[]Node{},
},
`0x7fa3b88bbb30 'NSComparisonResult (^)(id _Nonnull, id _Nonnull)'`: testNode{&BlockPointerType{
Addr: 0x7fa3b88bbb30,
Type: `NSComparisonResult (^)(id _Nonnull, id _Nonnull)`,
ChildNodes: []Node{},
},
0x7fa3b88bbb30,
NewPositionFromString(""),
[]Node{},
},
}
runNodeTests(t, nodes)
}
+4 -1
View File
@@ -7,11 +7,14 @@ type BreakStmt struct {
ChildNodes []Node ChildNodes []Node
} }
func parseBreakStmt(line string) *BreakStmt { func parseBreakStmt(line string) Node {
groups := groupsFromRegex( groups := groupsFromRegex(
"<(?P<position>.*)>", "<(?P<position>.*)>",
line, line,
) )
if groups == nil {
return &Unknown{}
}
return &BreakStmt{ return &BreakStmt{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
+6 -2
View File
@@ -5,12 +5,16 @@ import (
) )
func TestBreakStmt(t *testing.T) { func TestBreakStmt(t *testing.T) {
nodes := map[string]Node{ nodes := map[string]testNode{
`0x7fca2d8070e0 <col:11, col:23>`: &BreakStmt{ `0x7fca2d8070e0 <col:11, col:23>`: testNode{&BreakStmt{
Addr: 0x7fca2d8070e0, Addr: 0x7fca2d8070e0,
Pos: NewPositionFromString("col:11, col:23"), Pos: NewPositionFromString("col:11, col:23"),
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
0x7fca2d8070e0,
NewPositionFromString("col:11, col:23"),
[]Node{},
},
} }
runNodeTests(t, nodes) runNodeTests(t, nodes)
+58
View File
@@ -0,0 +1,58 @@
package ast
// BuiltinAttr is a type of attribute that is optionally attached to a variable
// or struct field definition.
type BuiltinAttr struct {
Addr Address
Pos Position
ChildNodes []Node
Implicit bool
Inherited bool
Value string
}
func parseBuiltinAttr(line string) Node {
groups := groupsFromRegex(
`<(?P<position>.*)>
(?P<inherited> Inherited)?
(?P<implicit> Implicit)?
(?P<value> \d+)?
`,
line,
)
if groups == nil {
return &Unknown{}
}
return &BuiltinAttr{
Addr: ParseAddress(groups["address"]),
Pos: NewPositionFromString(groups["position"]),
ChildNodes: []Node{},
Inherited: len(groups["inherited"]) > 0,
Implicit: len(groups["implicit"]) > 0,
Value: groups["value"],
}
}
// AddChild adds a new child node. Child nodes can then be accessed with the
// Children attribute.
func (n *BuiltinAttr) AddChild(node Node) {
n.ChildNodes = append(n.ChildNodes, node)
}
// Address returns the numeric address of the node. See the documentation for
// the Address type for more information.
func (n *BuiltinAttr) Address() Address {
return n.Addr
}
// Children returns the child nodes. If this node does not have any children or
// this node does not support children it will always return an empty slice.
func (n *BuiltinAttr) Children() []Node {
return n.ChildNodes
}
// Position returns the position in the original source code.
func (n *BuiltinAttr) Position() Position {
return n.Pos
}
+56
View File
@@ -0,0 +1,56 @@
package ast
import (
"testing"
)
func TestBuiltinAttr(t *testing.T) {
nodes := map[string]testNode{
`0x7fa1488273a0 <line:7:4, line:11:4>`: testNode{&BuiltinAttr{
Addr: 0x7fa1488273a0,
Pos: NewPositionFromString("line:7:4, line:11:4"),
ChildNodes: []Node{},
Inherited: false,
Implicit: false,
},
0x7fa1488273a0,
NewPositionFromString("line:7:4, line:11:4"),
[]Node{},
},
`0x5605ceaf4b88 <col:12> Implicit`: testNode{&BuiltinAttr{
Addr: 0x5605ceaf4b88,
Pos: NewPositionFromString("col:12"),
ChildNodes: []Node{},
Inherited: false,
Implicit: true,
},
0x5605ceaf4b88,
NewPositionFromString("col:12"),
[]Node{},
},
`0x4153c50 </usr/include/unistd.h:779:46> Inherited`: testNode{&BuiltinAttr{
Addr: 0x4153c50,
Pos: NewPositionFromString("/usr/include/unistd.h:779:46"),
ChildNodes: []Node{},
Inherited: true,
Implicit: false,
},
0x4153c50,
NewPositionFromString("/usr/include/unistd.h:779:46"),
[]Node{},
},
`0x1038b8828 <col:20> Inherited Implicit`: testNode{&BuiltinAttr{
Addr: 0x1038b8828,
Pos: NewPositionFromString("col:20"),
ChildNodes: []Node{},
Inherited: true,
Implicit: true,
},
0x1038b8828,
NewPositionFromString("col:20"),
[]Node{},
},
}
runNodeTests(t, nodes)
}
+4 -1
View File
@@ -7,11 +7,14 @@ type BuiltinType struct {
ChildNodes []Node ChildNodes []Node
} }
func parseBuiltinType(line string) *BuiltinType { func parseBuiltinType(line string) Node {
groups := groupsFromRegex( groups := groupsFromRegex(
"'(?P<type>.*?)'", "'(?P<type>.*?)'",
line, line,
) )
if groups == nil {
return &Unknown{}
}
return &BuiltinType{ return &BuiltinType{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
+11 -3
View File
@@ -5,17 +5,25 @@ import (
) )
func TestBuiltinType(t *testing.T) { func TestBuiltinType(t *testing.T) {
nodes := map[string]Node{ nodes := map[string]testNode{
`0x7f8a43023f40 '__int128'`: &BuiltinType{ `0x7f8a43023f40 '__int128'`: testNode{&BuiltinType{
Addr: 0x7f8a43023f40, Addr: 0x7f8a43023f40,
Type: "__int128", Type: "__int128",
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
`0x7f8a43023ea0 'unsigned long long'`: &BuiltinType{ 0x7f8a43023f40,
NewPositionFromString(""),
[]Node{},
},
`0x7f8a43023ea0 'unsigned long long'`: testNode{&BuiltinType{
Addr: 0x7f8a43023ea0, Addr: 0x7f8a43023ea0,
Type: "unsigned long long", Type: "unsigned long long",
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
0x7f8a43023ea0,
NewPositionFromString(""),
[]Node{},
},
} }
runNodeTests(t, nodes) runNodeTests(t, nodes)
+4 -1
View File
@@ -16,11 +16,14 @@ var CStyleCastExprNullToPointer = "NullToPointer"
// CStyleCastExprToVoid - string of kind ToVoid // CStyleCastExprToVoid - string of kind ToVoid
var CStyleCastExprToVoid = "ToVoid" var CStyleCastExprToVoid = "ToVoid"
func parseCStyleCastExpr(line string) *CStyleCastExpr { func parseCStyleCastExpr(line string) Node {
groups := groupsFromRegex( groups := groupsFromRegex(
"<(?P<position>.*)> '(?P<type1>.*?)'(:'(?P<type2>.*?)')? <(?P<kind>.*)>", "<(?P<position>.*)> '(?P<type1>.*?)'(:'(?P<type2>.*?)')? <(?P<kind>.*)>",
line, line,
) )
if groups == nil {
return &Unknown{}
}
return &CStyleCastExpr{ return &CStyleCastExpr{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
+12 -4
View File
@@ -5,22 +5,30 @@ import (
) )
func TestCStyleCastExpr(t *testing.T) { func TestCStyleCastExpr(t *testing.T) {
nodes := map[string]Node{ nodes := map[string]testNode{
`0x7fddc18fb2e0 <col:50, col:56> 'char' <IntegralCast>`: &CStyleCastExpr{ `0x7fddc18fb2e0 <col:50, col:56> 'char' <IntegralCast>`: testNode{&CStyleCastExpr{
Addr: 0x7fddc18fb2e0, Addr: 0x7fddc18fb2e0,
Pos: NewPositionFromString("col:50, col:56"), Pos: NewPositionFromString("col:50, col:56"),
Type: "char", Type: "char",
Kind: "IntegralCast", Kind: "IntegralCast",
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
`0x2781518 <col:7, col:17> 'T_ENUM':'T_ENUM' <IntegralCast>`: &CStyleCastExpr{ 0x7fddc18fb2e0,
NewPositionFromString("col:50, col:56"),
[]Node{},
},
`0x2781518 <col:7, col:17> 'T_ENUM':'T_ENUM' <IntegralCast>`: testNode{&CStyleCastExpr{
Addr: 0x2781518, Addr: 0x2781518,
Pos: NewPositionFromString("col:7, col:17"), Pos: NewPositionFromString("col:7, col:17"),
Type: "T_ENUM", Type: "T_ENUM",
Type2: "T_ENUM", Type2: "",
Kind: "IntegralCast", Kind: "IntegralCast",
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
0x2781518,
NewPositionFromString("col:7, col:17"),
[]Node{},
},
} }
runNodeTests(t, nodes) runNodeTests(t, nodes)
+4 -1
View File
@@ -8,11 +8,14 @@ type CallExpr struct {
ChildNodes []Node ChildNodes []Node
} }
func parseCallExpr(line string) *CallExpr { func parseCallExpr(line string) Node {
groups := groupsFromRegex( groups := groupsFromRegex(
"<(?P<position>.*)> '(?P<type>.*?)'", "<(?P<position>.*)> '(?P<type>.*?)'",
line, line,
) )
if groups == nil {
return &Unknown{}
}
return &CallExpr{ return &CallExpr{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
+11 -3
View File
@@ -5,19 +5,27 @@ import (
) )
func TestCallExpr(t *testing.T) { func TestCallExpr(t *testing.T) {
nodes := map[string]Node{ nodes := map[string]testNode{
`0x7f9bf3033240 <col:11, col:25> 'int'`: &CallExpr{ `0x7f9bf3033240 <col:11, col:25> 'int'`: testNode{&CallExpr{
Addr: 0x7f9bf3033240, Addr: 0x7f9bf3033240,
Pos: NewPositionFromString("col:11, col:25"), Pos: NewPositionFromString("col:11, col:25"),
Type: "int", Type: "int",
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
`0x7f9bf3035c20 <line:7:4, col:64> 'int'`: &CallExpr{ 0x7f9bf3033240,
NewPositionFromString("col:11, col:25"),
[]Node{},
},
`0x7f9bf3035c20 <line:7:4, col:64> 'int'`: testNode{&CallExpr{
Addr: 0x7f9bf3035c20, Addr: 0x7f9bf3035c20,
Pos: NewPositionFromString("line:7:4, col:64"), Pos: NewPositionFromString("line:7:4, col:64"),
Type: "int", Type: "int",
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
0x7f9bf3035c20,
NewPositionFromString("line:7:4, col:64"),
[]Node{},
},
} }
runNodeTests(t, nodes) runNodeTests(t, nodes)
+4 -1
View File
@@ -7,8 +7,11 @@ type CaseStmt struct {
ChildNodes []Node ChildNodes []Node
} }
func parseCaseStmt(line string) *CaseStmt { func parseCaseStmt(line string) Node {
groups := groupsFromRegex(`<(?P<position>.*)>`, line) groups := groupsFromRegex(`<(?P<position>.*)>`, line)
if groups == nil {
return &Unknown{}
}
return &CaseStmt{ return &CaseStmt{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
+6 -2
View File
@@ -5,12 +5,16 @@ import (
) )
func TestCaseStmt(t *testing.T) { func TestCaseStmt(t *testing.T) {
nodes := map[string]Node{ nodes := map[string]testNode{
`0x7fc8b5094688 <line:11:5, line:12:21>`: &CaseStmt{ `0x7fc8b5094688 <line:11:5, line:12:21>`: testNode{&CaseStmt{
Addr: 0x7fc8b5094688, Addr: 0x7fc8b5094688,
Pos: NewPositionFromString("line:11:5, line:12:21"), Pos: NewPositionFromString("line:11:5, line:12:21"),
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
0x7fc8b5094688,
NewPositionFromString("line:11:5, line:12:21"),
[]Node{},
},
} }
runNodeTests(t, nodes) runNodeTests(t, nodes)
+49
View File
@@ -0,0 +1,49 @@
package ast
// CFAuditedTransferAttr
type CFAuditedTransferAttr struct {
Addr Address
Pos Position
Content string
ChildNodes []Node
}
func parseCFAuditedTransferAttr(line string) Node {
groups := groupsFromRegex(
"<(?P<position>.*)>(?P<content>.*)",
line,
)
if groups == nil {
return &Unknown{}
}
return &CFAuditedTransferAttr{
Addr: ParseAddress(groups["address"]),
Pos: NewPositionFromString(groups["position"]),
Content: groups["content"],
ChildNodes: []Node{},
}
}
// AddChild adds a new child node. Child nodes can then be accessed with the
// Children attribute.
func (n *CFAuditedTransferAttr) AddChild(node Node) {
n.ChildNodes = append(n.ChildNodes, node)
}
// Address returns the numeric address of the node. See the documentation for
// the Address type for more information.
func (n *CFAuditedTransferAttr) Address() Address {
return n.Addr
}
// Children returns the child nodes. If this node does not have any children or
// this node does not support children it will always return an empty slice.
func (n *CFAuditedTransferAttr) Children() []Node {
return n.ChildNodes
}
// Position returns the position in the original source code.
func (n *CFAuditedTransferAttr) Position() Position {
return n.Pos
}
+22
View File
@@ -0,0 +1,22 @@
package ast
import (
"testing"
)
func TestCFAuditedTransferAttr(t *testing.T) {
nodes := map[string]testNode{
`0x7fc0a69091d1 <line:11:7, line:18:7> content`: testNode{&CFAuditedTransferAttr{
Addr: 0x7fc0a69091d1,
Pos: NewPositionFromString("line:11:7, line:18:7"),
Content: " content",
ChildNodes: []Node{},
},
0x7fc0a69091d1,
NewPositionFromString("line:11:7, line:18:7"),
[]Node{},
},
}
runNodeTests(t, nodes)
}
+49
View File
@@ -0,0 +1,49 @@
package ast
// CFConsumedAttr
type CFConsumedAttr struct {
Addr Address
Pos Position
Content string
ChildNodes []Node
}
func parseCFConsumedAttr(line string) Node {
groups := groupsFromRegex(
"<(?P<position>.*)>(?P<content>.*)",
line,
)
if groups == nil {
return &Unknown{}
}
return &CFConsumedAttr{
Addr: ParseAddress(groups["address"]),
Pos: NewPositionFromString(groups["position"]),
Content: groups["content"],
ChildNodes: []Node{},
}
}
// AddChild adds a new child node. Child nodes can then be accessed with the
// Children attribute.
func (n *CFConsumedAttr) AddChild(node Node) {
n.ChildNodes = append(n.ChildNodes, node)
}
// Address returns the numeric address of the node. See the documentation for
// the Address type for more information.
func (n *CFConsumedAttr) Address() Address {
return n.Addr
}
// Children returns the child nodes. If this node does not have any children or
// this node does not support children it will always return an empty slice.
func (n *CFConsumedAttr) Children() []Node {
return n.ChildNodes
}
// Position returns the position in the original source code.
func (n *CFConsumedAttr) Position() Position {
return n.Pos
}
+22
View File
@@ -0,0 +1,22 @@
package ast
import (
"testing"
)
func TestCFConsumedAttr(t *testing.T) {
nodes := map[string]testNode{
`0x7fc0a69091d1 <line:11:7, line:18:7> content`: testNode{&CFConsumedAttr{
Addr: 0x7fc0a69091d1,
Pos: NewPositionFromString("line:11:7, line:18:7"),
Content: " content",
ChildNodes: []Node{},
},
0x7fc0a69091d1,
NewPositionFromString("line:11:7, line:18:7"),
[]Node{},
},
}
runNodeTests(t, nodes)
}
+47
View File
@@ -0,0 +1,47 @@
package ast
// CFReturnsNotRetainedAttr
type CFReturnsNotRetainedAttr struct {
Addr Address
Pos Position
ChildNodes []Node
}
func parseCFReturnsNotRetainedAttr(line string) Node {
groups := groupsFromRegex(
"<(?P<position>.*)>",
line,
)
if groups == nil {
return &Unknown{}
}
return &CFReturnsNotRetainedAttr{
Addr: ParseAddress(groups["address"]),
Pos: NewPositionFromString(groups["position"]),
ChildNodes: []Node{},
}
}
// AddChild adds a new child node. Child nodes can then be accessed with the
// Children attribute.
func (n *CFReturnsNotRetainedAttr) AddChild(node Node) {
n.ChildNodes = append(n.ChildNodes, node)
}
// Address returns the numeric address of the node. See the documentation for
// the Address type for more information.
func (n *CFReturnsNotRetainedAttr) Address() Address {
return n.Addr
}
// Children returns the child nodes. If this node does not have any children or
// this node does not support children it will always return an empty slice.
func (n *CFReturnsNotRetainedAttr) Children() []Node {
return n.ChildNodes
}
// Position returns the position in the original source code.
func (n *CFReturnsNotRetainedAttr) Position() Position {
return n.Pos
}
+21
View File
@@ -0,0 +1,21 @@
package ast
import (
"testing"
)
func TestCFReturnsNotRetainedAttr(t *testing.T) {
nodes := map[string]testNode{
`0x7fc0a69091d1 <line:11:7, line:18:7>`: testNode{&CFReturnsNotRetainedAttr{
Addr: 0x7fc0a69091d1,
Pos: NewPositionFromString("line:11:7, line:18:7"),
ChildNodes: []Node{},
},
0x7fc0a69091d1,
NewPositionFromString("line:11:7, line:18:7"),
[]Node{},
},
}
runNodeTests(t, nodes)
}
+47
View File
@@ -0,0 +1,47 @@
package ast
// CFReturnsRetainedAttr
type CFReturnsRetainedAttr struct {
Addr Address
Pos Position
ChildNodes []Node
}
func parseCFReturnsRetainedAttr(line string) Node {
groups := groupsFromRegex(
"<(?P<position>.*)>",
line,
)
if groups == nil {
return &Unknown{}
}
return &CFReturnsRetainedAttr{
Addr: ParseAddress(groups["address"]),
Pos: NewPositionFromString(groups["position"]),
ChildNodes: []Node{},
}
}
// AddChild adds a new child node. Child nodes can then be accessed with the
// Children attribute.
func (n *CFReturnsRetainedAttr) AddChild(node Node) {
n.ChildNodes = append(n.ChildNodes, node)
}
// Address returns the numeric address of the node. See the documentation for
// the Address type for more information.
func (n *CFReturnsRetainedAttr) Address() Address {
return n.Addr
}
// Children returns the child nodes. If this node does not have any children or
// this node does not support children it will always return an empty slice.
func (n *CFReturnsRetainedAttr) Children() []Node {
return n.ChildNodes
}
// Position returns the position in the original source code.
func (n *CFReturnsRetainedAttr) Position() Position {
return n.Pos
}
+21
View File
@@ -0,0 +1,21 @@
package ast
import (
"testing"
)
func TestCFReturnsRetainedAttr(t *testing.T) {
nodes := map[string]testNode{
`0x7fc0a69091d1 <line:11:7, line:18:7>`: testNode{&CFReturnsRetainedAttr{
Addr: 0x7fc0a69091d1,
Pos: NewPositionFromString("line:11:7, line:18:7"),
ChildNodes: []Node{},
},
0x7fc0a69091d1,
NewPositionFromString("line:11:7, line:18:7"),
[]Node{},
},
}
runNodeTests(t, nodes)
}
+5 -2
View File
@@ -1,7 +1,7 @@
package ast package ast
import ( import (
"github.com/elliotchance/c2go/util" "git.wow.st/gmp/nswrap/util"
) )
// CharacterLiteral is type of character literal // CharacterLiteral is type of character literal
@@ -13,11 +13,14 @@ type CharacterLiteral struct {
ChildNodes []Node ChildNodes []Node
} }
func parseCharacterLiteral(line string) *CharacterLiteral { func parseCharacterLiteral(line string) Node {
groups := groupsFromRegex( groups := groupsFromRegex(
"<(?P<position>.*)> '(?P<type>.*?)' (?P<value>\\d+)", "<(?P<position>.*)> '(?P<type>.*?)' (?P<value>\\d+)",
line, line,
) )
if groups == nil {
return &Unknown{}
}
return &CharacterLiteral{ return &CharacterLiteral{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
+6 -2
View File
@@ -5,14 +5,18 @@ import (
) )
func TestCharacterLiteral(t *testing.T) { func TestCharacterLiteral(t *testing.T) {
nodes := map[string]Node{ nodes := map[string]testNode{
`0x7f980b858308 <col:62> 'int' 10`: &CharacterLiteral{ `0x7f980b858308 <col:62> 'int' 10`: testNode{&CharacterLiteral{
Addr: 0x7f980b858308, Addr: 0x7f980b858308,
Pos: NewPositionFromString("col:62"), Pos: NewPositionFromString("col:62"),
Type: "int", Type: "int",
Value: 10, Value: 10,
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
0x7f980b858308,
NewPositionFromString("col:62"),
[]Node{},
},
} }
runNodeTests(t, nodes) runNodeTests(t, nodes)
+48
View File
@@ -0,0 +1,48 @@
package ast
// ColdAttr is a type of attribute that is optionally attached to function
// declaration.
type ColdAttr struct {
Addr Address
Pos Position
ChildNodes []Node
}
func parseColdAttr(line string) Node {
groups := groupsFromRegex(
"<(?P<position>.*)>",
line,
)
if groups == nil {
return &Unknown{}
}
return &ColdAttr{
Addr: ParseAddress(groups["address"]),
Pos: NewPositionFromString(groups["position"]),
ChildNodes: []Node{},
}
}
// AddChild adds a new child node. Child nodes can then be accessed with the
// Children attribute.
func (n *ColdAttr) AddChild(node Node) {
n.ChildNodes = append(n.ChildNodes, node)
}
// Address returns the numeric address of the node. See the documentation for
// the Address type for more information.
func (n *ColdAttr) Address() Address {
return n.Addr
}
// Children returns the child nodes. If this node does not have any children or
// this node does not support children it will always return an empty slice.
func (n *ColdAttr) Children() []Node {
return n.ChildNodes
}
// Position returns the position in the original source code.
func (n *ColdAttr) Position() Position {
return n.Pos
}
+21
View File
@@ -0,0 +1,21 @@
package ast
import (
"testing"
)
func TestColdAttr(t *testing.T) {
nodes := map[string]testNode{
`0x7fc8fa094558 <col:107>`: testNode{&ColdAttr{
Addr: 0x7fc8fa094558,
Pos: NewPositionFromString("col:107"),
ChildNodes: []Node{},
},
0x7fc8fa094558,
NewPositionFromString("col:107"),
[]Node{},
},
}
runNodeTests(t, nodes)
}
+4 -1
View File
@@ -11,7 +11,7 @@ type CompoundAssignOperator struct {
ChildNodes []Node ChildNodes []Node
} }
func parseCompoundAssignOperator(line string) *CompoundAssignOperator { func parseCompoundAssignOperator(line string) Node {
groups := groupsFromRegex( groups := groupsFromRegex(
`<(?P<position>.*)> `<(?P<position>.*)>
'(?P<type>.+?)' '(?P<type>.+?)'
@@ -20,6 +20,9 @@ func parseCompoundAssignOperator(line string) *CompoundAssignOperator {
ComputeResultTy='(?P<crestype>.+?)'`, ComputeResultTy='(?P<crestype>.+?)'`,
line, line,
) )
if groups == nil {
return &Unknown{}
}
return &CompoundAssignOperator{ return &CompoundAssignOperator{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
+6 -2
View File
@@ -5,8 +5,8 @@ import (
) )
func TestCompoundAssignOperator(t *testing.T) { func TestCompoundAssignOperator(t *testing.T) {
nodes := map[string]Node{ nodes := map[string]testNode{
`0x2dc5758 <line:5:2, col:7> 'int' '+=' ComputeLHSTy='int' ComputeResultTy='int'`: &CompoundAssignOperator{ `0x2dc5758 <line:5:2, col:7> 'int' '+=' ComputeLHSTy='int' ComputeResultTy='int'`: testNode{&CompoundAssignOperator{
Addr: 0x2dc5758, Addr: 0x2dc5758,
Pos: NewPositionFromString("line:5:2, col:7"), Pos: NewPositionFromString("line:5:2, col:7"),
Type: "int", Type: "int",
@@ -15,6 +15,10 @@ func TestCompoundAssignOperator(t *testing.T) {
ComputationResultType: "int", ComputationResultType: "int",
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
0x2dc5758,
NewPositionFromString("line:5:2, col:7"),
[]Node{},
},
} }
runNodeTests(t, nodes) runNodeTests(t, nodes)
+4 -1
View File
@@ -9,11 +9,14 @@ type CompoundLiteralExpr struct {
ChildNodes []Node ChildNodes []Node
} }
func parseCompoundLiteralExpr(line string) *CompoundLiteralExpr { func parseCompoundLiteralExpr(line string) Node {
groups := groupsFromRegex( groups := groupsFromRegex(
`<(?P<position>.*)> '(?P<type1>.*?)'(:'(?P<type2>.*?)')? lvalue`, `<(?P<position>.*)> '(?P<type1>.*?)'(:'(?P<type2>.*?)')? lvalue`,
line, line,
) )
if groups == nil {
return &Unknown{}
}
return &CompoundLiteralExpr{ return &CompoundLiteralExpr{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
+6 -2
View File
@@ -5,14 +5,18 @@ import (
) )
func TestCompoundLiteralExpr(t *testing.T) { func TestCompoundLiteralExpr(t *testing.T) {
nodes := map[string]Node{ nodes := map[string]testNode{
`0x5575acce81f0 <col:21, col:40> 'struct node':'struct node' lvalue`: &CompoundLiteralExpr{ `0x5575acce81f0 <col:21, col:40> 'struct node':'struct node' lvalue`: testNode{&CompoundLiteralExpr{
Addr: 0x5575acce81f0, Addr: 0x5575acce81f0,
Pos: NewPositionFromString("col:21, col:40"), Pos: NewPositionFromString("col:21, col:40"),
Type1: "struct node", Type1: "struct node",
Type2: "struct node", Type2: "struct node",
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
0x5575acce81f0,
NewPositionFromString("col:21, col:40"),
[]Node{},
},
} }
runNodeTests(t, nodes) runNodeTests(t, nodes)
+4 -1
View File
@@ -10,11 +10,14 @@ type CompoundStmt struct {
BelongsToSwitch bool BelongsToSwitch bool
} }
func parseCompoundStmt(line string) *CompoundStmt { func parseCompoundStmt(line string) Node {
groups := groupsFromRegex( groups := groupsFromRegex(
"<(?P<position>.*)>", "<(?P<position>.*)>",
line, line,
) )
if groups == nil {
return &Unknown{}
}
return &CompoundStmt{ return &CompoundStmt{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
+11 -3
View File
@@ -5,17 +5,25 @@ import (
) )
func TestCompoundStmt(t *testing.T) { func TestCompoundStmt(t *testing.T) {
nodes := map[string]Node{ nodes := map[string]testNode{
`0x7fbd0f014f18 <col:54, line:358:1>`: &CompoundStmt{ `0x7fbd0f014f18 <col:54, line:358:1>`: testNode{&CompoundStmt{
Addr: 0x7fbd0f014f18, Addr: 0x7fbd0f014f18,
Pos: NewPositionFromString("col:54, line:358:1"), Pos: NewPositionFromString("col:54, line:358:1"),
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
`0x7fbd0f8360b8 <line:4:1, line:13:1>`: &CompoundStmt{ 0x7fbd0f014f18,
NewPositionFromString("col:54, line:358:1"),
[]Node{},
},
`0x7fbd0f8360b8 <line:4:1, line:13:1>`: testNode{&CompoundStmt{
Addr: 0x7fbd0f8360b8, Addr: 0x7fbd0f8360b8,
Pos: NewPositionFromString("line:4:1, line:13:1"), Pos: NewPositionFromString("line:4:1, line:13:1"),
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
0x7fbd0f8360b8,
NewPositionFromString("line:4:1, line:13:1"),
[]Node{},
},
} }
runNodeTests(t, nodes) runNodeTests(t, nodes)
+4 -1
View File
@@ -8,11 +8,14 @@ type ConditionalOperator struct {
ChildNodes []Node ChildNodes []Node
} }
func parseConditionalOperator(line string) *ConditionalOperator { func parseConditionalOperator(line string) Node {
groups := groupsFromRegex( groups := groupsFromRegex(
`<(?P<position>.*)> '(?P<type>.*?)'`, `<(?P<position>.*)> '(?P<type>.*?)'`,
line, line,
) )
if groups == nil {
return &Unknown{}
}
return &ConditionalOperator{ return &ConditionalOperator{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
+6 -2
View File
@@ -5,13 +5,17 @@ import (
) )
func TestConditionalOperator(t *testing.T) { func TestConditionalOperator(t *testing.T) {
nodes := map[string]Node{ nodes := map[string]testNode{
`0x7fc6ae0bc678 <col:6, col:89> 'void'`: &ConditionalOperator{ `0x7fc6ae0bc678 <col:6, col:89> 'void'`: testNode{&ConditionalOperator{
Addr: 0x7fc6ae0bc678, Addr: 0x7fc6ae0bc678,
Pos: NewPositionFromString("col:6, col:89"), Pos: NewPositionFromString("col:6, col:89"),
Type: "void", Type: "void",
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
0x7fc6ae0bc678,
NewPositionFromString("col:6, col:89"),
[]Node{},
},
} }
runNodeTests(t, nodes) runNodeTests(t, nodes)
+1 -1
View File
@@ -9,7 +9,7 @@ type ConstAttr struct {
ChildNodes []Node ChildNodes []Node
} }
func parseConstAttr(line string) *ConstAttr { func parseConstAttr(line string) Node {
groups := groupsFromRegex( groups := groupsFromRegex(
"<(?P<position>.*)>(?P<tags>.*)", "<(?P<position>.*)>(?P<tags>.*)",
line, line,
+6 -2
View File
@@ -5,13 +5,17 @@ import (
) )
func TestConstAttr(t *testing.T) { func TestConstAttr(t *testing.T) {
nodes := map[string]Node{ nodes := map[string]testNode{
`0x7fa3b88bbb38 <line:4:1, line:13:1>foo`: &ConstAttr{ `0x7fa3b88bbb38 <line:4:1, line:13:1>foo`: testNode{&ConstAttr{
Addr: 0x7fa3b88bbb38, Addr: 0x7fa3b88bbb38,
Pos: NewPositionFromString("line:4:1, line:13:1"), Pos: NewPositionFromString("line:4:1, line:13:1"),
Tags: "foo", Tags: "foo",
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
0x7fa3b88bbb38,
NewPositionFromString("line:4:1, line:13:1"),
[]Node{},
},
} }
runNodeTests(t, nodes) runNodeTests(t, nodes)
+5 -2
View File
@@ -1,7 +1,7 @@
package ast package ast
import ( import (
"github.com/elliotchance/c2go/util" "git.wow.st/gmp/nswrap/util"
) )
// ConstantArrayType is constant array type // ConstantArrayType is constant array type
@@ -12,11 +12,14 @@ type ConstantArrayType struct {
ChildNodes []Node ChildNodes []Node
} }
func parseConstantArrayType(line string) *ConstantArrayType { func parseConstantArrayType(line string) Node {
groups := groupsFromRegex( groups := groupsFromRegex(
"'(?P<type>.*)' (?P<size>\\d+)", "'(?P<type>.*)' (?P<size>\\d+)",
line, line,
) )
if groups == nil {
return &Unknown{}
}
return &ConstantArrayType{ return &ConstantArrayType{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
+11 -3
View File
@@ -5,19 +5,27 @@ import (
) )
func TestConstantArrayType(t *testing.T) { func TestConstantArrayType(t *testing.T) {
nodes := map[string]Node{ nodes := map[string]testNode{
`0x7f94ad016a40 'struct __va_list_tag [1]' 1 `: &ConstantArrayType{ `0x7f94ad016a40 'struct __va_list_tag [1]' 1 `: testNode{&ConstantArrayType{
Addr: 0x7f94ad016a40, Addr: 0x7f94ad016a40,
Type: "struct __va_list_tag [1]", Type: "struct __va_list_tag [1]",
Size: 1, Size: 1,
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
`0x7f8c5f059d20 'char [37]' 37 `: &ConstantArrayType{ 0x7f94ad016a40,
NewPositionFromString(""),
[]Node{},
},
`0x7f8c5f059d20 'char [37]' 37 `: testNode{&ConstantArrayType{
Addr: 0x7f8c5f059d20, Addr: 0x7f8c5f059d20,
Type: "char [37]", Type: "char [37]",
Size: 37, Size: 37,
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
0x7f8c5f059d20,
NewPositionFromString(""),
[]Node{},
},
} }
runNodeTests(t, nodes) runNodeTests(t, nodes)
+53
View File
@@ -0,0 +1,53 @@
package ast
// ConstantExpr is expression.
type ConstantExpr struct {
Addr Address
Pos Position
Type string
Type2 string
Extra string
ChildNodes []Node
}
func parseConstantExpr(line string) Node {
groups := groupsFromRegex(
`<(?P<position>.*)> '(?P<type>[\w ]+)'(:'(?P<type2>[\w ]+)')?( .*)?`,
line,
)
if groups == nil {
return &Unknown{}
}
return &ConstantExpr{
Addr: ParseAddress(groups["address"]),
Pos: NewPositionFromString(groups["position"]),
Type: groups["type"],
Type2: groups["type2"],
Extra: groups["extra"],
ChildNodes: []Node{},
}
}
// AddChild adds a new child node. Child nodes can then be accessed with the
// Children attribute.
func (n *ConstantExpr) AddChild(node Node) {
n.ChildNodes = append(n.ChildNodes, node)
}
// Address returns the numeric address of the node. See the documentation for
// the Address type for more information.
func (n *ConstantExpr) Address() Address {
return n.Addr
}
// Children returns the child nodes. If this node does not have any children or
// this node does not support children it will always return an empty slice.
func (n *ConstantExpr) Children() []Node {
return n.ChildNodes
}
// Position returns the position in the original source code.
func (n *ConstantExpr) Position() Position {
return n.Pos
}
+64
View File
@@ -0,0 +1,64 @@
package ast
import (
"testing"
)
func TestConstantExpr(t *testing.T) {
nodes := map[string]testNode{
`0x7f9bf3033240 <col:11, col:25> 'int'`: testNode{&ConstantExpr{
Addr: 0x7f9bf3033240,
Pos: NewPositionFromString("col:11, col:25"),
Type: "int",
ChildNodes: []Node{},
},
0x7f9bf3033240,
NewPositionFromString("col:11, col:25"),
[]Node{},
},
`0x7f9bf3035c20 <line:7:4, col:64> 'int'`: testNode{&ConstantExpr{
Addr: 0x7f9bf3035c20,
Pos: NewPositionFromString("line:7:4, col:64"),
Type: "int",
ChildNodes: []Node{},
},
0x7f9bf3035c20,
NewPositionFromString("line:7:4, col:64"),
[]Node{},
},
`0x7f9bf3035c20 <line:7:4, col:64> 'unsigned int'`: testNode{&ConstantExpr{
Addr: 0x7f9bf3035c20,
Pos: NewPositionFromString("line:7:4, col:64"),
Type: "unsigned int",
ChildNodes: []Node{},
},
0x7f9bf3035c20,
NewPositionFromString("line:7:4, col:64"),
[]Node{},
},
`0x7f9bf3035c20 <line:7:4, col:64> 'NSModalResponse':'long' Int: 1`: testNode{&ConstantExpr{
Addr: 0x7f9bf3035c20,
Pos: NewPositionFromString("line:7:4, col:64"),
Type: "NSModalResponse",
Type2: "long",
ChildNodes: []Node{},
},
0x7f9bf3035c20,
NewPositionFromString("line:7:4, col:64"),
[]Node{},
},
`0x7f9bf3035c20 <line:7:4, col:64> 'NSModalResponse':'unsigned long' Int: 1`: testNode{&ConstantExpr{
Addr: 0x7f9bf3035c20,
Pos: NewPositionFromString("line:7:4, col:64"),
Type: "NSModalResponse",
Type2: "unsigned long",
ChildNodes: []Node{},
},
0x7f9bf3035c20,
NewPositionFromString("line:7:4, col:64"),
[]Node{},
},
}
runNodeTests(t, nodes)
}
+4 -1
View File
@@ -7,11 +7,14 @@ type ContinueStmt struct {
ChildNodes []Node ChildNodes []Node
} }
func parseContinueStmt(line string) *ContinueStmt { func parseContinueStmt(line string) Node {
groups := groupsFromRegex( groups := groupsFromRegex(
"<(?P<position>.*)>", "<(?P<position>.*)>",
line, line,
) )
if groups == nil {
return &Unknown{}
}
return &ContinueStmt{ return &ContinueStmt{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
+6 -2
View File
@@ -5,12 +5,16 @@ import (
) )
func TestContinueStmt(t *testing.T) { func TestContinueStmt(t *testing.T) {
nodes := map[string]Node{ nodes := map[string]testNode{
`0x1e044e0 <col:20>`: &ContinueStmt{ `0x1e044e0 <col:20>`: testNode{&ContinueStmt{
Addr: 0x1e044e0, Addr: 0x1e044e0,
Pos: NewPositionFromString("col:20"), Pos: NewPositionFromString("col:20"),
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
0x1e044e0,
NewPositionFromString("col:20"),
[]Node{},
},
} }
runNodeTests(t, nodes) runNodeTests(t, nodes)
+53
View File
@@ -0,0 +1,53 @@
package ast
// ConvertVectorExpr
type ConvertVectorExpr struct {
Addr Address
Pos Position
Type string
Type2 string
ChildNodes []Node
}
func parseConvertVectorExpr(line string) Node {
groups := groupsFromRegex(
`<(?P<position><invalid sloc>|.*?)>
(?P<type> '.*?')?
(?P<type2>:'.*?')?`,
line,
)
if groups == nil {
return &Unknown{}
}
return &ConvertVectorExpr{
Addr: ParseAddress(groups["address"]),
Pos: NewPositionFromString(groups["position"]),
Type: removeQuotes(groups["type"]),
Type2: groups["type2"],
ChildNodes: []Node{},
}
}
// AddChild adds a new child node. Child nodes can then be accessed with the
// Children attribute.
func (n *ConvertVectorExpr) AddChild(node Node) {
n.ChildNodes = append(n.ChildNodes, node)
}
// Address returns the numeric address of the node. See the documentation for
// the Address type for more information.
func (n *ConvertVectorExpr) Address() Address {
return n.Addr
}
// Children returns the child nodes. If this node does not have any children or
// this node does not support children it will always return an empty slice.
func (n *ConvertVectorExpr) Children() []Node {
return n.ChildNodes
}
// Position returns the position in the original source code.
func (n *ConvertVectorExpr) Position() Position {
return n.Pos
}
+34
View File
@@ -0,0 +1,34 @@
package ast
import (
"testing"
)
func TestConvertVectorExpr(t *testing.T) {
nodes := map[string]testNode{
`0x7fdef0862430 <line:120:1, col:16>`: testNode{&ConvertVectorExpr{
Addr: 0x7fdef0862430,
Pos: NewPositionFromString("line:120:1, col:16"),
Type: "",
Type2: "",
ChildNodes: []Node{},
},
0x7fdef0862430,
NewPositionFromString("line:120:1, col:16"),
[]Node{},
},
`0x113368318 <line:1354:20, line:1355:70> '__v2df':'__attribute__((__vector_size__(2 * sizeof(double)))) double'`: testNode{&ConvertVectorExpr{
Addr: 0x113368318,
Pos: NewPositionFromString("line:1354:20, line:1355:70"),
Type: `__v2df`,
Type2: `:'__attribute__((__vector_size__(2 * sizeof(double)))) double'`,
ChildNodes: []Node{},
},
0x113368318,
NewPositionFromString("line:1354:20, line:1355:70"),
[]Node{},
},
}
runNodeTests(t, nodes)
}
+4 -1
View File
@@ -7,11 +7,14 @@ type DecayedType struct {
ChildNodes []Node ChildNodes []Node
} }
func parseDecayedType(line string) *DecayedType { func parseDecayedType(line string) Node {
groups := groupsFromRegex( groups := groupsFromRegex(
"'(?P<type>.*)' sugar", "'(?P<type>.*)' sugar",
line, line,
) )
if groups == nil {
return &Unknown{}
}
return &DecayedType{ return &DecayedType{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
+6 -2
View File
@@ -5,12 +5,16 @@ import (
) )
func TestDecayedType(t *testing.T) { func TestDecayedType(t *testing.T) {
nodes := map[string]Node{ nodes := map[string]testNode{
`0x7f1234567890 'struct __va_list_tag *' sugar`: &DecayedType{ `0x7f1234567890 'struct __va_list_tag *' sugar`: testNode{&DecayedType{
Addr: 0x7f1234567890, Addr: 0x7f1234567890,
Type: "struct __va_list_tag *", Type: "struct __va_list_tag *",
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
0x7f1234567890,
NewPositionFromString(""),
[]Node{},
},
} }
runNodeTests(t, nodes) runNodeTests(t, nodes)
+4 -1
View File
@@ -15,7 +15,7 @@ type DeclRefExpr struct {
ChildNodes []Node ChildNodes []Node
} }
func parseDeclRefExpr(line string) *DeclRefExpr { func parseDeclRefExpr(line string) Node {
groups := groupsFromRegex( groups := groupsFromRegex(
`<(?P<position>.*)> `<(?P<position>.*)>
'(?P<type>.*?)'(:'(?P<type1>.*?)')? '(?P<type>.*?)'(:'(?P<type1>.*?)')?
@@ -28,6 +28,9 @@ func parseDeclRefExpr(line string) *DeclRefExpr {
`, `,
line, line,
) )
if groups == nil {
return &Unknown{}
}
return &DeclRefExpr{ return &DeclRefExpr{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
+26 -6
View File
@@ -5,8 +5,8 @@ import (
) )
func TestDeclRefExpr(t *testing.T) { func TestDeclRefExpr(t *testing.T) {
nodes := map[string]Node{ nodes := map[string]testNode{
`0x7fc972064460 <col:8> 'FILE *' lvalue ParmVar 0x7fc9720642d0 '_p' 'FILE *'`: &DeclRefExpr{ `0x7fc972064460 <col:8> 'FILE *' lvalue ParmVar 0x7fc9720642d0 '_p' 'FILE *'`: testNode{&DeclRefExpr{
Addr: 0x7fc972064460, Addr: 0x7fc972064460,
Pos: NewPositionFromString("col:8"), Pos: NewPositionFromString("col:8"),
Type: "FILE *", Type: "FILE *",
@@ -19,7 +19,11 @@ func TestDeclRefExpr(t *testing.T) {
Type3: "", Type3: "",
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
`0x7fc97206a958 <col:11> 'int (int, FILE *)' Function 0x7fc972064198 '__swbuf' 'int (int, FILE *)'`: &DeclRefExpr{ 0x7fc972064460,
NewPositionFromString("col:8"),
[]Node{},
},
`0x7fc97206a958 <col:11> 'int (int, FILE *)' Function 0x7fc972064198 '__swbuf' 'int (int, FILE *)'`: testNode{&DeclRefExpr{
Addr: 0x7fc97206a958, Addr: 0x7fc97206a958,
Pos: NewPositionFromString("col:11"), Pos: NewPositionFromString("col:11"),
Type: "int (int, FILE *)", Type: "int (int, FILE *)",
@@ -32,7 +36,11 @@ func TestDeclRefExpr(t *testing.T) {
Type3: "", Type3: "",
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
`0x7fa36680f170 <col:19> 'struct programming':'struct programming' lvalue Var 0x7fa36680dc20 'variable' 'struct programming':'struct programming'`: &DeclRefExpr{ 0x7fc97206a958,
NewPositionFromString("col:11"),
[]Node{},
},
`0x7fa36680f170 <col:19> 'struct programming':'struct programming' lvalue Var 0x7fa36680dc20 'variable' 'struct programming':'struct programming'`: testNode{&DeclRefExpr{
Addr: 0x7fa36680f170, Addr: 0x7fa36680f170,
Pos: NewPositionFromString("col:19"), Pos: NewPositionFromString("col:19"),
Type: "struct programming", Type: "struct programming",
@@ -45,7 +53,11 @@ func TestDeclRefExpr(t *testing.T) {
Type3: "struct programming", Type3: "struct programming",
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
`0x35cb438 <col:13> 'int' EnumConstant 0x35ca300 'Jan' 'int'`: &DeclRefExpr{ 0x7fa36680f170,
NewPositionFromString("col:19"),
[]Node{},
},
`0x35cb438 <col:13> 'int' EnumConstant 0x35ca300 'Jan' 'int'`: testNode{&DeclRefExpr{
Addr: 0x35cb438, Addr: 0x35cb438,
Pos: NewPositionFromString("col:13"), Pos: NewPositionFromString("col:13"),
Type: "int", Type: "int",
@@ -58,7 +70,11 @@ func TestDeclRefExpr(t *testing.T) {
Type3: "", Type3: "",
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
`0x1ff8770 <col:33> 'T_ENUM':'T_ENUM' lvalue Var 0x1ff8600 'cc' 'T_ENUM':'T_ENUM'`: &DeclRefExpr{ 0x35cb438,
NewPositionFromString("col:13"),
[]Node{},
},
`0x1ff8770 <col:33> 'T_ENUM':'T_ENUM' lvalue Var 0x1ff8600 'cc' 'T_ENUM':'T_ENUM'`: testNode{&DeclRefExpr{
Addr: 0x1ff8770, Addr: 0x1ff8770,
Pos: NewPositionFromString("col:33"), Pos: NewPositionFromString("col:33"),
Type: "T_ENUM", Type: "T_ENUM",
@@ -71,6 +87,10 @@ func TestDeclRefExpr(t *testing.T) {
Type3: "T_ENUM", Type3: "T_ENUM",
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
0x1ff8770,
NewPositionFromString("col:33"),
[]Node{},
},
} }
runNodeTests(t, nodes) runNodeTests(t, nodes)
+4 -1
View File
@@ -7,11 +7,14 @@ type DeclStmt struct {
ChildNodes []Node ChildNodes []Node
} }
func parseDeclStmt(line string) *DeclStmt { func parseDeclStmt(line string) Node {
groups := groupsFromRegex( groups := groupsFromRegex(
"<(?P<position>.*)>", "<(?P<position>.*)>",
line, line,
) )
if groups == nil {
return &Unknown{}
}
return &DeclStmt{ return &DeclStmt{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
+6 -2
View File
@@ -5,12 +5,16 @@ import (
) )
func TestDeclStmt(t *testing.T) { func TestDeclStmt(t *testing.T) {
nodes := map[string]Node{ nodes := map[string]testNode{
`0x7fb791846e80 <line:11:4, col:31>`: &DeclStmt{ `0x7fb791846e80 <line:11:4, col:31>`: testNode{&DeclStmt{
Addr: 0x7fb791846e80, Addr: 0x7fb791846e80,
Pos: NewPositionFromString("line:11:4, col:31"), Pos: NewPositionFromString("line:11:4, col:31"),
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
0x7fb791846e80,
NewPositionFromString("line:11:4, col:31"),
[]Node{},
},
} }
runNodeTests(t, nodes) runNodeTests(t, nodes)
+4 -1
View File
@@ -7,8 +7,11 @@ type DefaultStmt struct {
ChildNodes []Node ChildNodes []Node
} }
func parseDefaultStmt(line string) *DefaultStmt { func parseDefaultStmt(line string) Node {
groups := groupsFromRegex(`<(?P<position>.*)>`, line) groups := groupsFromRegex(`<(?P<position>.*)>`, line)
if groups == nil {
return &Unknown{}
}
return &DefaultStmt{ return &DefaultStmt{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
+6 -2
View File
@@ -5,12 +5,16 @@ import (
) )
func TestDefaultStmt(t *testing.T) { func TestDefaultStmt(t *testing.T) {
nodes := map[string]Node{ nodes := map[string]testNode{
`0x7f951308bfb0 <line:17:5, line:18:34>`: &DefaultStmt{ `0x7f951308bfb0 <line:17:5, line:18:34>`: testNode{&DefaultStmt{
Addr: 0x7f951308bfb0, Addr: 0x7f951308bfb0,
Pos: NewPositionFromString("line:17:5, line:18:34"), Pos: NewPositionFromString("line:17:5, line:18:34"),
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
0x7f951308bfb0,
NewPositionFromString("line:17:5, line:18:34"),
[]Node{},
},
} }
runNodeTests(t, nodes) runNodeTests(t, nodes)
+4 -1
View File
@@ -11,11 +11,14 @@ type DeprecatedAttr struct {
ChildNodes []Node ChildNodes []Node
} }
func parseDeprecatedAttr(line string) *DeprecatedAttr { func parseDeprecatedAttr(line string) Node {
groups := groupsFromRegex( groups := groupsFromRegex(
`<(?P<position>.*)>(?P<inherited> Inherited)? "(?P<message1>.*?)"(?P<message2> ".*?")?`, `<(?P<position>.*)>(?P<inherited> Inherited)? "(?P<message1>.*?)"(?P<message2> ".*?")?`,
line, line,
) )
if groups == nil {
return &Unknown{}
}
return &DeprecatedAttr{ return &DeprecatedAttr{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
+16 -4
View File
@@ -5,8 +5,8 @@ import (
) )
func TestDeprecatedAttr(t *testing.T) { func TestDeprecatedAttr(t *testing.T) {
nodes := map[string]Node{ nodes := map[string]testNode{
`0x7fec4b0ab9c0 <line:180:48, col:63> "This function is provided for compatibility reasons only. Due to security concerns inherent in the design of tempnam(3), it is highly recommended that you use mkstemp(3) instead." ""`: &DeprecatedAttr{ `0x7fec4b0ab9c0 <line:180:48, col:63> "This function is provided for compatibility reasons only. Due to security concerns inherent in the design of tempnam(3), it is highly recommended that you use mkstemp(3) instead." ""`: testNode{&DeprecatedAttr{
Addr: 0x7fec4b0ab9c0, Addr: 0x7fec4b0ab9c0,
Pos: NewPositionFromString("line:180:48, col:63"), Pos: NewPositionFromString("line:180:48, col:63"),
Message1: "This function is provided for compatibility reasons only. Due to security concerns inherent in the design of tempnam(3), it is highly recommended that you use mkstemp(3) instead.", Message1: "This function is provided for compatibility reasons only. Due to security concerns inherent in the design of tempnam(3), it is highly recommended that you use mkstemp(3) instead.",
@@ -14,7 +14,11 @@ func TestDeprecatedAttr(t *testing.T) {
IsInherited: false, IsInherited: false,
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
`0xb75d00 <line:1107:12> "This function or variable may be unsafe. Consider using _snwprintf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details." ""`: &DeprecatedAttr{ 0x7fec4b0ab9c0,
NewPositionFromString("line:180:48, col:63"),
[]Node{},
},
`0xb75d00 <line:1107:12> "This function or variable may be unsafe. Consider using _snwprintf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details." ""`: testNode{&DeprecatedAttr{
Addr: 0xb75d00, Addr: 0xb75d00,
Pos: NewPositionFromString("line:1107:12"), Pos: NewPositionFromString("line:1107:12"),
Message1: "This function or variable may be unsafe. Consider using _snwprintf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.", Message1: "This function or variable may be unsafe. Consider using _snwprintf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.",
@@ -22,7 +26,11 @@ func TestDeprecatedAttr(t *testing.T) {
IsInherited: false, IsInherited: false,
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
`0xb75d00 <line:1107:12> Inherited "This function or variable may be unsafe. Consider using _snwprintf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details." ""`: &DeprecatedAttr{ 0xb75d00,
NewPositionFromString("line:1107:12"),
[]Node{},
},
`0xb75d00 <line:1107:12> Inherited "This function or variable may be unsafe. Consider using _snwprintf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details." ""`: testNode{&DeprecatedAttr{
Addr: 0xb75d00, Addr: 0xb75d00,
Pos: NewPositionFromString("line:1107:12"), Pos: NewPositionFromString("line:1107:12"),
Message1: "This function or variable may be unsafe. Consider using _snwprintf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.", Message1: "This function or variable may be unsafe. Consider using _snwprintf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.",
@@ -30,6 +38,10 @@ func TestDeprecatedAttr(t *testing.T) {
IsInherited: true, IsInherited: true,
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
0xb75d00,
NewPositionFromString("line:1107:12"),
[]Node{},
},
} }
runNodeTests(t, nodes) runNodeTests(t, nodes)
+4 -1
View File
@@ -8,11 +8,14 @@ type DisableTailCallsAttr struct {
ChildNodes []Node ChildNodes []Node
} }
func parseDisableTailCallsAttr(line string) *DisableTailCallsAttr { func parseDisableTailCallsAttr(line string) Node {
groups := groupsFromRegex( groups := groupsFromRegex(
"<(?P<position>.*)>", "<(?P<position>.*)>",
line, line,
) )
if groups == nil {
return &Unknown{}
}
return &DisableTailCallsAttr{ return &DisableTailCallsAttr{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
+6 -2
View File
@@ -5,12 +5,16 @@ import (
) )
func TestDisableTailCallsAttr(t *testing.T) { func TestDisableTailCallsAttr(t *testing.T) {
nodes := map[string]Node{ nodes := map[string]testNode{
`0x7fc8fa094558 <col:107> `: &DisableTailCallsAttr{ `0x7fc8fa094558 <col:107> `: testNode{&DisableTailCallsAttr{
Addr: 0x7fc8fa094558, Addr: 0x7fc8fa094558,
Pos: NewPositionFromString("col:107"), Pos: NewPositionFromString("col:107"),
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
0x7fc8fa094558,
NewPositionFromString("col:107"),
[]Node{},
},
} }
runNodeTests(t, nodes) runNodeTests(t, nodes)
+4 -1
View File
@@ -7,11 +7,14 @@ type DoStmt struct {
ChildNodes []Node ChildNodes []Node
} }
func parseDoStmt(line string) *DoStmt { func parseDoStmt(line string) Node {
groups := groupsFromRegex( groups := groupsFromRegex(
"<(?P<position>.*)>", "<(?P<position>.*)>",
line, line,
) )
if groups == nil {
return &Unknown{}
}
return &DoStmt{ return &DoStmt{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
+6 -2
View File
@@ -5,12 +5,16 @@ import (
) )
func TestDoStmt(t *testing.T) { func TestDoStmt(t *testing.T) {
nodes := map[string]Node{ nodes := map[string]testNode{
`0x7ff36d0a0938 <line:11:5, line:14:23>`: &DoStmt{ `0x7ff36d0a0938 <line:11:5, line:14:23>`: testNode{&DoStmt{
Addr: 0x7ff36d0a0938, Addr: 0x7ff36d0a0938,
Pos: NewPositionFromString("line:11:5, line:14:23"), Pos: NewPositionFromString("line:11:5, line:14:23"),
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
0x7ff36d0a0938,
NewPositionFromString("line:11:5, line:14:23"),
[]Node{},
},
} }
runNodeTests(t, nodes) runNodeTests(t, nodes)
+4 -1
View File
@@ -8,11 +8,14 @@ type ElaboratedType struct {
ChildNodes []Node ChildNodes []Node
} }
func parseElaboratedType(line string) *ElaboratedType { func parseElaboratedType(line string) Node {
groups := groupsFromRegex( groups := groupsFromRegex(
"'(?P<type>.*?)' (?P<tags>.+)", "'(?P<type>.*?)' (?P<tags>.+)",
line, line,
) )
if groups == nil {
return &Unknown{}
}
return &ElaboratedType{ return &ElaboratedType{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
+6 -2
View File
@@ -5,13 +5,17 @@ import (
) )
func TestElaboratedType(t *testing.T) { func TestElaboratedType(t *testing.T) {
nodes := map[string]Node{ nodes := map[string]testNode{
`0x7f873686c120 'union __mbstate_t' sugar`: &ElaboratedType{ `0x7f873686c120 'union __mbstate_t' sugar`: testNode{&ElaboratedType{
Addr: 0x7f873686c120, Addr: 0x7f873686c120,
Type: "union __mbstate_t", Type: "union __mbstate_t",
Tags: "sugar", Tags: "sugar",
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
0x7f873686c120,
NewPositionFromString(""),
[]Node{},
},
} }
runNodeTests(t, nodes) runNodeTests(t, nodes)
+5 -2
View File
@@ -8,12 +8,15 @@ type EmptyDecl struct {
ChildNodes []Node ChildNodes []Node
} }
func parseEmptyDecl(line string) *EmptyDecl { func parseEmptyDecl(line string) Node {
groups := groupsFromRegex( groups := groupsFromRegex(
`<(?P<position>.*)> `<(?P<position>.*)>
( (?P<position2>.*))?`, ( (?P<position2>[^\s]+))?`,
line, line,
) )
if groups == nil {
return &Unknown{}
}
return &EmptyDecl{ return &EmptyDecl{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
+6 -2
View File
@@ -5,13 +5,17 @@ import (
) )
func TestEmptyDecl(t *testing.T) { func TestEmptyDecl(t *testing.T) {
nodes := map[string]Node{ nodes := map[string]testNode{
`0x480bec8 <col:13> col:13`: &EmptyDecl{ `0x480bec8 <col:13> col:13`: testNode{&EmptyDecl{
Addr: 0x480bec8, Addr: 0x480bec8,
Pos: NewPositionFromString("col:13"), Pos: NewPositionFromString("col:13"),
Position2: NewPositionFromString("col:13"), Position2: NewPositionFromString("col:13"),
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
0x480bec8,
NewPositionFromString("col:13"),
[]Node{},
},
} }
runNodeTests(t, nodes) runNodeTests(t, nodes)
+4 -1
View File
@@ -7,11 +7,14 @@ type Enum struct {
ChildNodes []Node ChildNodes []Node
} }
func parseEnum(line string) *Enum { func parseEnum(line string) Node {
groups := groupsFromRegex( groups := groupsFromRegex(
"'(?P<name>.*?)'", "'(?P<name>.*?)'",
line, line,
) )
if groups == nil {
return &Unknown{}
}
return &Enum{ return &Enum{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
+5 -2
View File
@@ -16,7 +16,7 @@ type EnumConstantDecl struct {
ChildNodes []Node ChildNodes []Node
} }
func parseEnumConstantDecl(line string) *EnumConstantDecl { func parseEnumConstantDecl(line string) Node {
groups := groupsFromRegex( groups := groupsFromRegex(
`<(?P<position>.*)> `<(?P<position>.*)>
( (?P<position2>[^ ]+))? ( (?P<position2>[^ ]+))?
@@ -26,6 +26,9 @@ func parseEnumConstantDecl(line string) *EnumConstantDecl {
(?P<type2>:'.*?')?`, (?P<type2>:'.*?')?`,
line, line,
) )
if groups == nil {
return &Unknown{}
}
/*type2 := groups["type2"] /*type2 := groups["type2"]
if type2 != "" { if type2 != "" {
@@ -35,7 +38,7 @@ func parseEnumConstantDecl(line string) *EnumConstantDecl {
return &EnumConstantDecl{ return &EnumConstantDecl{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
Pos: NewPositionFromString(groups["position"]), Pos: NewPositionFromString(groups["position"]),
//Position2: groups["position2"], Position2: groups["position2"],
Referenced: len(groups["referenced"]) > 0, Referenced: len(groups["referenced"]) > 0,
Name: strings.TrimSpace(groups["name"]), Name: strings.TrimSpace(groups["name"]),
Type: removeQuotes(groups["type"]), Type: removeQuotes(groups["type"]),
+11 -3
View File
@@ -5,8 +5,8 @@ import (
) )
func TestEnumConstantDecl(t *testing.T) { func TestEnumConstantDecl(t *testing.T) {
nodes := map[string]Node{ nodes := map[string]testNode{
`0x1660db0 <line:185:3> __codecvt_noconv 'int'`: &EnumConstantDecl{ `0x1660db0 <line:185:3> __codecvt_noconv 'int'`: testNode{&EnumConstantDecl{
Addr: 0x1660db0, Addr: 0x1660db0,
Pos: NewPositionFromString("line:185:3"), Pos: NewPositionFromString("line:185:3"),
Position2: "", Position2: "",
@@ -15,7 +15,11 @@ func TestEnumConstantDecl(t *testing.T) {
Type: "int", Type: "int",
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
`0x3c77ba8 <line:59:3, col:65> col:3 referenced _ISalnum 'int'`: &EnumConstantDecl{ 0x1660db0,
NewPositionFromString("line:185:3"),
[]Node{},
},
`0x3c77ba8 <line:59:3, col:65> col:3 referenced _ISalnum 'int'`: testNode{&EnumConstantDecl{
Addr: 0x3c77ba8, Addr: 0x3c77ba8,
Pos: NewPositionFromString("line:59:3, col:65"), Pos: NewPositionFromString("line:59:3, col:65"),
Position2: "col:3", Position2: "col:3",
@@ -24,6 +28,10 @@ func TestEnumConstantDecl(t *testing.T) {
Type: "int", Type: "int",
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
0x3c77ba8,
NewPositionFromString("line:59:3, col:65"),
[]Node{},
},
} }
runNodeTests(t, nodes) runNodeTests(t, nodes)
+5 -2
View File
@@ -15,7 +15,7 @@ type EnumDecl struct {
ChildNodes []Node ChildNodes []Node
} }
func parseEnumDecl(line string) *EnumDecl { func parseEnumDecl(line string) Node {
groups := groupsFromRegex( groups := groupsFromRegex(
`(?:prev (?P<prev>0x[0-9a-f]+) )? `(?:prev (?P<prev>0x[0-9a-f]+) )?
<(?P<position>.*)> <(?P<position>.*)>
@@ -25,6 +25,9 @@ func parseEnumDecl(line string) *EnumDecl {
(?P<type2>:'.*')?`, (?P<type2>:'.*')?`,
line, line,
) )
if groups == nil {
return &Unknown{}
}
/*type2 := groups["type2"] /*type2 := groups["type2"]
if type2 != "" { if type2 != "" {
@@ -34,7 +37,7 @@ func parseEnumDecl(line string) *EnumDecl {
return &EnumDecl{ return &EnumDecl{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
Pos: NewPositionFromString(groups["position"]), Pos: NewPositionFromString(groups["position"]),
//Position2: groups["position2"], Position2: groups["position2"],
Name: strings.TrimSpace(groups["name"]), Name: strings.TrimSpace(groups["name"]),
Type: removeQuotes(groups["type"]), Type: removeQuotes(groups["type"]),
//Type2: type2, //Type2: type2,
+11 -3
View File
@@ -5,21 +5,29 @@ import (
) )
func TestEnumDecl(t *testing.T) { func TestEnumDecl(t *testing.T) {
nodes := map[string]Node{ nodes := map[string]testNode{
`0x22a6c80 <line:180:1, line:186:1> __codecvt_result`: &EnumDecl{ `0x22a6c80 <line:180:1, line:186:1> __codecvt_result`: testNode{&EnumDecl{
Addr: 0x22a6c80, Addr: 0x22a6c80,
Pos: NewPositionFromString("line:180:1, line:186:1"), Pos: NewPositionFromString("line:180:1, line:186:1"),
Position2: "", Position2: "",
Name: "__codecvt_result", Name: "__codecvt_result",
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
`0x32fb5a0 <enum.c:3:1, col:45> col:6 week`: &EnumDecl{ 0x22a6c80,
NewPositionFromString("line:180:1, line:186:1"),
[]Node{},
},
`0x32fb5a0 <enum.c:3:1, col:45> col:6 week`: testNode{&EnumDecl{
Addr: 0x32fb5a0, Addr: 0x32fb5a0,
Pos: NewPositionFromString("enum.c:3:1, col:45"), Pos: NewPositionFromString("enum.c:3:1, col:45"),
Position2: " col:6", Position2: " col:6",
Name: "week", Name: "week",
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
0x32fb5a0,
NewPositionFromString("enum.c:3:1, col:45"),
[]Node{},
},
} }
runNodeTests(t, nodes) runNodeTests(t, nodes)
+49
View File
@@ -0,0 +1,49 @@
package ast
// EnumExtensibilityAttr
type EnumExtensibilityAttr struct {
Addr Address
Pos Position
Content string
ChildNodes []Node
}
func parseEnumExtensibilityAttr(line string) Node {
groups := groupsFromRegex(
"<(?P<position>.*)>(?P<content>.*)",
line,
)
if groups == nil {
return &Unknown{}
}
return &EnumExtensibilityAttr{
Addr: ParseAddress(groups["address"]),
Pos: NewPositionFromString(groups["position"]),
Content: groups["content"],
ChildNodes: []Node{},
}
}
// AddChild adds a new child node. Child nodes can then be accessed with the
// Children attribute.
func (n *EnumExtensibilityAttr) AddChild(node Node) {
n.ChildNodes = append(n.ChildNodes, node)
}
// Address returns the numeric address of the node. See the documentation for
// the Address type for more information.
func (n *EnumExtensibilityAttr) Address() Address {
return n.Addr
}
// Children returns the child nodes. If this node does not have any children or
// this node does not support children it will always return an empty slice.
func (n *EnumExtensibilityAttr) Children() []Node {
return n.ChildNodes
}
// Position returns the position in the original source code.
func (n *EnumExtensibilityAttr) Position() Position {
return n.Pos
}
+22
View File
@@ -0,0 +1,22 @@
package ast
import (
"testing"
)
func TestEnumExtensibilityAttr(t *testing.T) {
nodes := map[string]testNode{
`0x7fc0a69091d1 <line:11:7, line:18:7> content`: testNode{&EnumExtensibilityAttr{
Addr: 0x7fc0a69091d1,
Pos: NewPositionFromString("line:11:7, line:18:7"),
Content: " content",
ChildNodes: []Node{},
},
0x7fc0a69091d1,
NewPositionFromString("line:11:7, line:18:7"),
[]Node{},
},
}
runNodeTests(t, nodes)
}
+6 -2
View File
@@ -5,12 +5,16 @@ import (
) )
func TestEnum(t *testing.T) { func TestEnum(t *testing.T) {
nodes := map[string]Node{ nodes := map[string]testNode{
`0x7f980b858308 'foo'`: &Enum{ `0x7f980b858308 'foo'`: testNode{&Enum{
Addr: 0x7f980b858308, Addr: 0x7f980b858308,
Name: "foo", Name: "foo",
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
0x7f980b858308,
NewPositionFromString(""),
[]Node{},
},
} }
runNodeTests(t, nodes) runNodeTests(t, nodes)
+4 -1
View File
@@ -7,11 +7,14 @@ type EnumType struct {
ChildNodes []Node ChildNodes []Node
} }
func parseEnumType(line string) *EnumType { func parseEnumType(line string) Node {
groups := groupsFromRegex( groups := groupsFromRegex(
"'(?P<name>.*?)'", "'(?P<name>.*?)'",
line, line,
) )
if groups == nil {
return &Unknown{}
}
return &EnumType{ return &EnumType{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
+6 -2
View File
@@ -5,12 +5,16 @@ import (
) )
func TestEnumType(t *testing.T) { func TestEnumType(t *testing.T) {
nodes := map[string]Node{ nodes := map[string]testNode{
`0x7f980b858309 'foo'`: &EnumType{ `0x7f980b858309 'foo'`: testNode{&EnumType{
Addr: 0x7f980b858309, Addr: 0x7f980b858309,
Name: "foo", Name: "foo",
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
0x7f980b858309,
NewPositionFromString(""),
[]Node{},
},
} }
runNodeTests(t, nodes) runNodeTests(t, nodes)
+4 -1
View File
@@ -8,11 +8,14 @@ type Field struct {
ChildNodes []Node ChildNodes []Node
} }
func parseField(line string) *Field { func parseField(line string) Node {
groups := groupsFromRegex( groups := groupsFromRegex(
`'(?P<string1>.*?)' '(?P<string2>.*?)'`, `'(?P<string1>.*?)' '(?P<string2>.*?)'`,
line, line,
) )
if groups == nil {
return &Unknown{}
}
return &Field{ return &Field{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
+4 -1
View File
@@ -17,7 +17,7 @@ type FieldDecl struct {
ChildNodes []Node ChildNodes []Node
} }
func parseFieldDecl(line string) *FieldDecl { func parseFieldDecl(line string) Node {
groups := groupsFromRegex( groups := groupsFromRegex(
`<(?P<position>.*)> `<(?P<position>.*)>
(?P<position2> col:\d+| line:\d+:\d+)? (?P<position2> col:\d+| line:\d+:\d+)?
@@ -29,6 +29,9 @@ func parseFieldDecl(line string) *FieldDecl {
`, `,
line, line,
) )
if groups == nil {
return &Unknown{}
}
return &FieldDecl{ return &FieldDecl{
Addr: ParseAddress(groups["address"]), Addr: ParseAddress(groups["address"]),
+51 -11
View File
@@ -5,8 +5,8 @@ import (
) )
func TestFieldDecl(t *testing.T) { func TestFieldDecl(t *testing.T) {
nodes := map[string]Node{ nodes := map[string]testNode{
`0x7fef510c4848 <line:141:2, col:6> col:6 _ur 'int'`: &FieldDecl{ `0x7fef510c4848 <line:141:2, col:6> col:6 _ur 'int'`: testNode{&FieldDecl{
Addr: 0x7fef510c4848, Addr: 0x7fef510c4848,
Pos: NewPositionFromString("line:141:2, col:6"), Pos: NewPositionFromString("line:141:2, col:6"),
Position2: "col:6", Position2: "col:6",
@@ -17,7 +17,11 @@ func TestFieldDecl(t *testing.T) {
Referenced: false, Referenced: false,
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
`0x7fef510c46f8 <line:139:2, col:16> col:16 _ub 'struct __sbuf':'struct __sbuf'`: &FieldDecl{ 0x7fef510c4848,
NewPositionFromString("line:141:2, col:6"),
[]Node{},
},
`0x7fef510c46f8 <line:139:2, col:16> col:16 _ub 'struct __sbuf':'struct __sbuf'`: testNode{&FieldDecl{
Addr: 0x7fef510c46f8, Addr: 0x7fef510c46f8,
Pos: NewPositionFromString("line:139:2, col:16"), Pos: NewPositionFromString("line:139:2, col:16"),
Position2: "col:16", Position2: "col:16",
@@ -28,7 +32,11 @@ func TestFieldDecl(t *testing.T) {
Referenced: false, Referenced: false,
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
`0x7fef510c3fe0 <line:134:2, col:19> col:19 _read 'int (* _Nullable)(void *, char *, int)':'int (*)(void *, char *, int)'`: &FieldDecl{ 0x7fef510c46f8,
NewPositionFromString("line:139:2, col:16"),
[]Node{},
},
`0x7fef510c3fe0 <line:134:2, col:19> col:19 _read 'int (* _Nullable)(void *, char *, int)':'int (*)(void *, char *, int)'`: testNode{&FieldDecl{
Addr: 0x7fef510c3fe0, Addr: 0x7fef510c3fe0,
Pos: NewPositionFromString("line:134:2, col:19"), Pos: NewPositionFromString("line:134:2, col:19"),
Position2: "col:19", Position2: "col:19",
@@ -39,7 +47,11 @@ func TestFieldDecl(t *testing.T) {
Referenced: false, Referenced: false,
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
`0x7fef51073a60 <line:105:2, col:40> col:40 __cleanup_stack 'struct __darwin_pthread_handler_rec *'`: &FieldDecl{ 0x7fef510c3fe0,
NewPositionFromString("line:134:2, col:19"),
[]Node{},
},
`0x7fef51073a60 <line:105:2, col:40> col:40 __cleanup_stack 'struct __darwin_pthread_handler_rec *'`: testNode{&FieldDecl{
Addr: 0x7fef51073a60, Addr: 0x7fef51073a60,
Pos: NewPositionFromString("line:105:2, col:40"), Pos: NewPositionFromString("line:105:2, col:40"),
Position2: "col:40", Position2: "col:40",
@@ -50,7 +62,11 @@ func TestFieldDecl(t *testing.T) {
Referenced: false, Referenced: false,
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
`0x7fef510738e8 <line:100:2, col:43> col:7 __opaque 'char [16]'`: &FieldDecl{ 0x7fef51073a60,
NewPositionFromString("line:105:2, col:40"),
[]Node{},
},
`0x7fef510738e8 <line:100:2, col:43> col:7 __opaque 'char [16]'`: testNode{&FieldDecl{
Addr: 0x7fef510738e8, Addr: 0x7fef510738e8,
Pos: NewPositionFromString("line:100:2, col:43"), Pos: NewPositionFromString("line:100:2, col:43"),
Position2: "col:7", Position2: "col:7",
@@ -61,7 +77,11 @@ func TestFieldDecl(t *testing.T) {
Referenced: false, Referenced: false,
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
`0x7fe9f5072268 <line:129:2, col:6> col:6 referenced _lbfsize 'int'`: &FieldDecl{ 0x7fef510738e8,
NewPositionFromString("line:100:2, col:43"),
[]Node{},
},
`0x7fe9f5072268 <line:129:2, col:6> col:6 referenced _lbfsize 'int'`: testNode{&FieldDecl{
Addr: 0x7fe9f5072268, Addr: 0x7fe9f5072268,
Pos: NewPositionFromString("line:129:2, col:6"), Pos: NewPositionFromString("line:129:2, col:6"),
Position2: "col:6", Position2: "col:6",
@@ -72,7 +92,11 @@ func TestFieldDecl(t *testing.T) {
Referenced: true, Referenced: true,
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
`0x7f9bc9083d00 <line:91:5, line:97:8> line:91:5 'unsigned short'`: &FieldDecl{ 0x7fe9f5072268,
NewPositionFromString("line:129:2, col:6"),
[]Node{},
},
`0x7f9bc9083d00 <line:91:5, line:97:8> line:91:5 'unsigned short'`: testNode{&FieldDecl{
Addr: 0x7f9bc9083d00, Addr: 0x7f9bc9083d00,
Pos: NewPositionFromString("line:91:5, line:97:8"), Pos: NewPositionFromString("line:91:5, line:97:8"),
Position2: "line:91:5", Position2: "line:91:5",
@@ -83,7 +107,11 @@ func TestFieldDecl(t *testing.T) {
Referenced: false, Referenced: false,
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
`0x30363a0 <col:18, col:29> __val 'int [2]'`: &FieldDecl{ 0x7f9bc9083d00,
NewPositionFromString("line:91:5, line:97:8"),
[]Node{},
},
`0x30363a0 <col:18, col:29> __val 'int [2]'`: testNode{&FieldDecl{
Addr: 0x30363a0, Addr: 0x30363a0,
Pos: NewPositionFromString("col:18, col:29"), Pos: NewPositionFromString("col:18, col:29"),
Position2: "", Position2: "",
@@ -94,7 +122,11 @@ func TestFieldDecl(t *testing.T) {
Referenced: false, Referenced: false,
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
`0x17aeac0 <line:3:9> col:9 implicit referenced 'struct vec3d_t::(anonymous at main.c:3:9)'`: &FieldDecl{ 0x30363a0,
NewPositionFromString("col:18, col:29"),
[]Node{},
},
`0x17aeac0 <line:3:9> col:9 implicit referenced 'struct vec3d_t::(anonymous at main.c:3:9)'`: testNode{&FieldDecl{
Addr: 0x17aeac0, Addr: 0x17aeac0,
Pos: NewPositionFromString("line:3:9"), Pos: NewPositionFromString("line:3:9"),
Position2: "col:9", Position2: "col:9",
@@ -105,7 +137,11 @@ func TestFieldDecl(t *testing.T) {
Referenced: true, Referenced: true,
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
`0x56498bf52160 <line:269:5, col:21> col:21 type 'enum __pid_type':'enum __pid_type'`: &FieldDecl{ 0x17aeac0,
NewPositionFromString("line:3:9"),
[]Node{},
},
`0x56498bf52160 <line:269:5, col:21> col:21 type 'enum __pid_type':'enum __pid_type'`: testNode{&FieldDecl{
Addr: 0x56498bf52160, Addr: 0x56498bf52160,
Pos: NewPositionFromString("line:269:5, col:21"), Pos: NewPositionFromString("line:269:5, col:21"),
Position2: "col:21", Position2: "col:21",
@@ -116,6 +152,10 @@ func TestFieldDecl(t *testing.T) {
Referenced: false, Referenced: false,
ChildNodes: []Node{}, ChildNodes: []Node{},
}, },
0x56498bf52160,
NewPositionFromString("line:269:5, col:21"),
[]Node{},
},
} }
runNodeTests(t, nodes) runNodeTests(t, nodes)

Some files were not shown because too many files have changed in this diff Show More