Compare commits
8
Commits
4aa1211d73
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c2113215e9 | ||
|
|
e4f7e32887 | ||
|
|
f4a9dae250 | ||
|
|
0bc23404da | ||
|
|
1704be1cbc | ||
|
|
8b3a956bbe | ||
|
|
acc8cab583 | ||
|
|
b5773b5525 |
@@ -15,4 +15,9 @@ 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
|
||||
|
||||
@@ -62,6 +62,8 @@ pragma [ clang diagnostic ignored "-Wformat-security" ]
|
||||
|
||||
Regular expressions are permitted in the names of classes, functions,
|
||||
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
|
||||
as specified in `nswrap.yaml` or, by default, `ns` if a package name is not
|
||||
@@ -131,14 +133,14 @@ For example, `NSString` provides the folowing `compare` methods:
|
||||
These are translated into Go as:
|
||||
|
||||
```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 { }
|
||||
|
||||
func (o NSString) CompareOptionsRangeLocale(string NSString, mask NSStringCompareOptions,
|
||||
func (o *NSString) CompareOptionsRangeLocale(string *NSString, mask NSStringCompareOptions,
|
||||
rangeOfReceiverToCompare NSRange, locale NSObject) NSComparisonResult { }
|
||||
```
|
||||
|
||||
@@ -156,11 +158,45 @@ fmt.Printf("%s\n",str)
|
||||
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
|
||||
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`
|
||||
that take, respectively, Go strings and Go byte arrays (`[]byte`) and return
|
||||
`*Char` in Go. As demonstrated above, NSWrap also provides a `String()`
|
||||
methods so that the `*Char` and `NSString` types implement the `Stringer`
|
||||
Go interface.
|
||||
`*Char` in Go. As demonstrated above, NSWrap also provides `String()`
|
||||
methods so that the `*Char` and `*NSString` types implement the `Stringer`
|
||||
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
|
||||
|
||||
@@ -171,14 +207,23 @@ follows:
|
||||
type Id struct {
|
||||
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 {
|
||||
Ptr() unsafe.Pointer
|
||||
}
|
||||
```
|
||||
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
|
||||
|
||||
@@ -190,7 +235,7 @@ embeds `Id` to be used with generic Objective-C functions. For example:
|
||||
|
||||
```go
|
||||
o1 := ns.NSStringWithGoString("my string")
|
||||
s1 := ns.NSSetWithOBjects(o1)
|
||||
s1 := ns.NSSetWithObjects(o1)
|
||||
a := ns.NSMutableArrayWithObjects(o1,s1)
|
||||
```
|
||||
Since `NSString` and `NSSet` in Go both implement the `NSObject` interface,
|
||||
@@ -204,70 +249,73 @@ implements the required delegate protocol.
|
||||
|
||||
* Inheritance
|
||||
|
||||
Objective-C only provides single inheritance. In Go, this is modeled using
|
||||
embedding. Top level objects that inherit from `NSObject` in Objective-C
|
||||
Objective-C allows single inheritance. NSWrap automatically adds
|
||||
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.
|
||||
Other objects embed their superclass. For example:
|
||||
Other objects embed their direct superclass. For example:
|
||||
|
||||
```go
|
||||
type NSArray struct { Id }
|
||||
func (o NSArray) Ptr() unsafe.Pointer { return o.ptr }
|
||||
func (o Id) NSArray() NSArray {
|
||||
ret := NSArray{}
|
||||
ret.ptr = o.ptr
|
||||
return ret
|
||||
func (o *NSArray) Ptr() unsafe.Pointer { if o == nil { return nil }; return o.ptr }
|
||||
func (o *Id) NSArray() *NSArray {
|
||||
return (*NSArray)(unsafe.Pointer(o))
|
||||
}
|
||||
|
||||
type NSMutableArray struct { NSArray }
|
||||
func (o NSMutableArray) Ptr() unsafe.Pointer { return o.ptr }
|
||||
func (o Id) NSMutableArray() NSMutableArray {...}
|
||||
func (o *NSMutableArray) Ptr() unsafe.Pointer { if o == nil { return nil }; return o.ptr }
|
||||
func (o *Id) NSMutableArray() *NSMutableArray {
|
||||
return (*NSMutableArray)(unsafe.Pointer(o))
|
||||
}
|
||||
```
|
||||
|
||||
Observe:
|
||||
```go
|
||||
b := ns.NSButtonAlloc() // NSButton > NSControl > NSView > NSResponder > NSObject
|
||||
b.InitWithFrame(ns.NSMakeRect(100,100,200,200)) // Method of NSView
|
||||
b.SetTitle(nst("PUSH")) // Method of NSButton
|
||||
b.InitWithFrame(ns.NSMakeRect(100,100,200,200))
|
||||
b.SetTitle(nst("PUSH"))
|
||||
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,
|
||||
there is no `InitWithFrame` method for receivers of this type. This is
|
||||
not necessary because `NSButton` embeds `NSControl` which in turn embeds
|
||||
`NSView`. The `InitWithFrame` method only needs to be implemented for `NSView`
|
||||
receivers. Go will automatically find the indirectly embedded `NSView` and
|
||||
call the right method.
|
||||
the `initWithFrame` method is defined in AppKit for `NSView`. NSWrap will find this
|
||||
method and add it to the Go `NSButton` type when creating your wrapper because
|
||||
`NSButton` inherits from `NSControl` which inherits from `NSView`.
|
||||
|
||||
Note that, since `InitWithFrame()` is defined only for `NSView` and returns
|
||||
an `NSView` type,
|
||||
the following will not work. Look out for this if you like to chain your
|
||||
`Alloc` and `Init` methods and are getting type errors:
|
||||
|
||||
```go
|
||||
//DO NOT DO THIS -- InitWithFrame returns NSView, not NSButton
|
||||
b := ns.NSButtonAlloc().InitWithFrame(ns.MakeRect(100,100,200,200))
|
||||
```
|
||||
|
||||
Go has no trouble finding embedded methods for your `NSButton` and will
|
||||
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()`, `RespondsToSelector`
|
||||
As of this
|
||||
writing, on MacOS 10.13.6, NSWrap binds 115 instance methods for `NSObject`,
|
||||
so things like `Hash()`, `IsEqualTo()`, `ClassName()`, `RespondsToSelector()`
|
||||
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).
|
||||
All objects implement the `NSObject` interface, but from time to time you
|
||||
will encounter a method that takes a parameter of a different type that may
|
||||
not exactly match the type you have. For example, if you want to pass your
|
||||
`NSButton` as a parameter to a method that accepts an `NSView` type, you need
|
||||
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
|
||||
`NSView` Go type.
|
||||
|
||||
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
|
||||
always return `Id`. See below under Enumerators for an example, but make
|
||||
at run-time to any other class. You will need this for Enumerators and
|
||||
functions like `NSArray`'s `GetObjects`, for example,
|
||||
which always return `*Id`. Make
|
||||
sure you know (or test) what type your objects are before converting them.
|
||||
You can
|
||||
implement a somewhat less convenient version of a Go type switch this way.
|
||||
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
|
||||
classes inherits from `Id`, it is possible to send any message to any
|
||||
@@ -314,11 +362,12 @@ functions.
|
||||
Pointers to pointers are sometimes passed to Objective-C methods or functions
|
||||
as a way of receiving output from those functions, especially because
|
||||
Objective-C does not allow for multiple return values. In those cases, after
|
||||
the CGo call, the method parameter will be treated as a nil-terminated array of
|
||||
the CGo call, the method parameter will be treated as an array of
|
||||
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.
|
||||
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
|
||||
`NSDictionary`:
|
||||
@@ -329,28 +378,31 @@ An example in Core Foundation is the `getObjects:andKeys:count` method for
|
||||
ns.NSArrayWithObjects(nst("obj1"),nst("obj2")),
|
||||
ns.NSArrayWithObjects(nst("key1"),nst("key2")),
|
||||
)
|
||||
os,ks := make([]ns.Id,0,5), make([]ns.Id,0,5) // length 0, capacity 5 slices
|
||||
dict.GetObjects(&os,&ks,5)
|
||||
va,ka := make([]*ns.Id,0,5), make([]*ns.Id,0,5) // length 0, capacity 5 slices
|
||||
dict.GetObjectsAndKeysCount(&va,&ka,5)
|
||||
// last parameter is the count, must be less than or equal to the input slice capacity
|
||||
fmt.Printf("Length of os is now %d\n",len(os)) // os and ks slices are now length = 2
|
||||
for i,k := range ks {
|
||||
fmt.Printf("-- %s -> %s\n",k.NSString(),os[i].NSString())
|
||||
fmt.Printf("Length of va is now %d\n",len(va)) // va and ka slices are now length = 2
|
||||
for i,k := range ka {
|
||||
fmt.Printf("-- %s -> %s\n",k.NSString(),va[i].NSString())
|
||||
}
|
||||
```
|
||||
|
||||
NSWrap will never check the "count" parameter, so the user will always need
|
||||
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
|
||||
where you need to get an error message out of a function or method.
|
||||
where you need to get an error message out of a function or method, or in other
|
||||
cases where an Objective-C method wants to provide multiple return values.
|
||||
Here is an example using `[NSString stringWithContentsOfURL...]`:
|
||||
|
||||
```go
|
||||
err := make([]ns.NSError,1)
|
||||
n1 = ns.NSStringWithContentsOfURLEncoding(ns.NSURLWithGoString("htttypo://example.com"),0,&err)
|
||||
fmt.Printf("err: %s\n",err[0].LocalizedDescription())
|
||||
err := make([]*ns.NSError,1)
|
||||
n1 = ns.NSStringWithContentsOfURLEncoding(ns.NSURLWithGoString("htttypo://example.com"), 0, &err)
|
||||
if len(err) > 0 {
|
||||
fmt.Printf("err: %s\n",err[0].LocalizedDescription())
|
||||
//err: The file couldn’t be opened because URL type htttypo isn’t supported.
|
||||
}
|
||||
```
|
||||
|
||||
## Selectors
|
||||
@@ -370,15 +422,17 @@ appMenu.AddItemWithTitle(
|
||||
## Enumerators
|
||||
|
||||
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.
|
||||
|
||||
```go
|
||||
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 {
|
||||
case o.IsKindOfClass(ns.NSStringClass()):
|
||||
fmt.Println(o.NSString().UTF8String())
|
||||
fmt.Printf("%d: %s\n", i, o.NSString())
|
||||
i++
|
||||
return true // continue enumeration
|
||||
default:
|
||||
fmt.Println("Unknown class")
|
||||
@@ -392,7 +446,7 @@ identification.
|
||||
|
||||
## 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
|
||||
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
|
||||
@@ -415,10 +469,9 @@ results in:
|
||||
```go
|
||||
//ns/main.go
|
||||
...
|
||||
type NSWindowOrderingMode C.enum_NSWindowOrderingMode
|
||||
const NSWindowAbove NSWindowOrderingMode = C.NSWindowAbove
|
||||
const NSWindowBelow NSWindowOrderingMode = C.NSWindowBelow
|
||||
const NSWindowOut NSWindowOrderingMode = C.NSWindowOut
|
||||
const NSWindowAbove NSInteger = C.NSWindowAbove
|
||||
const NSWindowBelow NSInteger = C.NSWindowBelow
|
||||
const NSWindowOut NSInteger = C.NSWindowOut
|
||||
|
||||
const _CLOCK_REALTIME = C._CLOCK_REALTIME
|
||||
const _CLOCK_MONOTONIC = C._CLOCK_MONOTONIC
|
||||
@@ -426,70 +479,6 @@ const _CLOCK_MONOTONIC_RAW = C._CLOCK_MONOTONIC_RAW
|
||||
...
|
||||
```
|
||||
|
||||
|
||||
## Memory management
|
||||
|
||||
Objective-C objects are always allocated and returned from CGo code, and
|
||||
therefore these pointers are not garbage collected by Go. You can use any
|
||||
of the standard Objective-C memory management techniques for those pointers,
|
||||
which seem to work but have not been extensively tested.
|
||||
|
||||
Since everything inherits methods from `NSObject`, you can call `Retain()`,
|
||||
`Release()` and `Autorelease()` on any object.
|
||||
|
||||
If the autorelease configuration directive is set to "true", all allocation functions
|
||||
created by NSWrap (i.e. those ending in `Alloc`) will call `autorelease` before they
|
||||
return an object. Alternately, objects can be manually sent an autorelease message.
|
||||
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()
|
||||
//del.Autorelease() // if autorelease: true is not set in nswrap.yaml
|
||||
menu := ns.NSMenuAlloc().InitWithTitle(nst("Main"))
|
||||
//menu.Autorelease()
|
||||
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.
|
||||
|
||||
* Pitfalls
|
||||
|
||||
Go concurrency does not play well with Objective-C memory management. In particular,
|
||||
an AutoreleasePool needs to be allocated and drained from the same thread, and
|
||||
only objects allocated within that thread will be drained. Objects allocated and
|
||||
autoreleased from a different goroutine in the same thread are at risk of being
|
||||
prematurely drained. Therefore, you should only work with one AutoreleasePool at
|
||||
a time, and only within a thread that is locked to the OS thread
|
||||
(by calling `runtime.LockOSThread()`). If you will be allocating Objective-C objects
|
||||
from multiple goroutines, it is best not to use the `autorelease: true` directive
|
||||
as that will cause all objects to receive an `autorelease` message even if they are
|
||||
created outside the thread where are using your autorelease pool.
|
||||
See `examples/memory` for some basic tests and read the comments to larn what to avoid.
|
||||
|
||||
## Delegates
|
||||
|
||||
The `delegates` directive in `nswrap.yaml` creates a new Objective-C
|
||||
@@ -531,7 +520,8 @@ registered,
|
||||
it will be called with all of its parameters converted to their Go type
|
||||
equivalents. User-defined callbacks are registered by calling a function
|
||||
with the method name in TitleCase + `Callback`, so in the example above,
|
||||
you would call `ns.CentralManagerDidUpdateStateCallback(...)` with the name of
|
||||
if your delegate was named `del`, you would call
|
||||
`del.CentralManagerDidUpdateStateCallback(...)` with the name of
|
||||
your callback function to register to receive notifications when your central
|
||||
manager updates its state.
|
||||
|
||||
@@ -543,15 +533,20 @@ registers a callback for `centralManagerDidUpdateState`, allocates
|
||||
a `CBCentralManager` object, and installs our delegate:
|
||||
|
||||
```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() {
|
||||
...
|
||||
del := ns.CBDelegateAlloc()
|
||||
del = ns.CBDelegateAlloc()
|
||||
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
|
||||
@@ -562,12 +557,12 @@ messages will point you in the right direction.
|
||||
|
||||
```
|
||||
$ go build
|
||||
./main.go:127:43: cannot use didFinishLaunching (type func(ns.NSNotification, bool)) as type
|
||||
func(ns.NSNotification) in argument to del.ApplicationDidFinishLaunchingCallback
|
||||
./main.go:127:43: cannot use didFinishLaunching (type func(ns.CBDelegate, *ns.NSNotification, bool)) as type
|
||||
func(ns.CBDelegate, *ns.NSNotification) in argument to del.ApplicationDidFinishLaunchingCallback
|
||||
```
|
||||
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
|
||||
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
|
||||
|
||||
@@ -576,8 +571,7 @@ 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
|
||||
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
|
||||
this functionality.
|
||||
Go and you will want to make use of `runtime.LockOSThread()`.
|
||||
|
||||
This is actually a full working Cocoa application:
|
||||
|
||||
@@ -612,34 +606,43 @@ frameworks: [ Foundation, AppKit, CoreGraphics ]
|
||||
//go:generate nswrap
|
||||
package main
|
||||
|
||||
//go:generate nswrap
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"runtime"
|
||||
"git.wow.st/gmp/nswrap/examples/app/ns" // point to your own 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!")
|
||||
}
|
||||
|
||||
func shouldTerminate(s ns.NSApplication) ns.BOOL {
|
||||
return 1
|
||||
func shouldTerminate(self ns.AppDelegate, s *ns.NSApplication) ns.BOOL {
|
||||
return true
|
||||
}
|
||||
|
||||
var (
|
||||
a *ns.NSApplication // global vars so these are not garbage collected
|
||||
del *ns.AppDelegate
|
||||
win *ns.NSWindow
|
||||
)
|
||||
|
||||
func main() {
|
||||
runtime.LockOSThread()
|
||||
a := ns.NSApplicationSharedApplication()
|
||||
a.SetActivationPolicy(ns.NSApplicationActivationPolicyRegular)
|
||||
del := ns.AppDelegateAlloc()
|
||||
a = ns.NSApplicationSharedApplication()
|
||||
a.SetActivationPolicy(ns.NSApplicationActivationPolicy(ns.NSApplicationActivationPolicyRegular))
|
||||
del = ns.AppDelegateAlloc()
|
||||
del.ApplicationDidFinishLaunchingCallback(didFinishLaunching)
|
||||
del.ApplicationShouldTerminateAfterLastWindowClosedCallback(shouldTerminate)
|
||||
a.SetDelegate(del)
|
||||
|
||||
win := ns.NSWindowAlloc().InitWithContentRectStyleMask(
|
||||
win = ns.NSWindowAlloc().InitWithContentRectStyleMask(
|
||||
ns.NSMakeRect(200,200,600,600),
|
||||
ns.NSWindowStyleMaskTitled | ns.NSWindowStyleMaskClosable,
|
||||
ns.NSBackingStoreBuffered,
|
||||
0,
|
||||
ns.NSWindowStyleMask(ns.NSWindowStyleMaskTitled | ns.NSWindowStyleMaskClosable),
|
||||
ns.NSBackingStoreType(ns.NSBackingStoreBuffered),
|
||||
false,
|
||||
)
|
||||
win.SetTitle(ns.NSStringWithGoString("Hi World"))
|
||||
win.MakeKeyAndOrderFront(win)
|
||||
@@ -647,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
|
||||
menus, visual format-based auto layout, and a custom button class.
|
||||
|
||||
## Subclasses
|
||||
|
||||
### NOTE: SUBCLASS FUNCTIONALITY IS CURRENTLY PARTIALLY BROKEN
|
||||
|
||||
NSWrap includes functionality to generate subclasses as specified in
|
||||
`nswrap.yaml`.
|
||||
|
||||
@@ -667,7 +672,7 @@ subclasses:
|
||||
yourClass: # the superclass to inherit from
|
||||
- init.* # what methods to override
|
||||
- -(void)hi_there:(int)x # Objective-C prototype of your new method(s)
|
||||
# |--this hyphen indicates 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
|
||||
@@ -682,12 +687,11 @@ 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
|
||||
to specify more than one superclass in a `subclasses` entry.
|
||||
|
||||
Go callbacks for overridden methods are passed a special struct
|
||||
as their first parameter. This struct is filled with superclass methods, which
|
||||
allows you to do things like this:
|
||||
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(super ns.MyClassSupermethods, param NSString) {
|
||||
func methodCallback(self ns.MyClass, super ns.MyClassSupermethods, param NSString) {
|
||||
...
|
||||
super.Method(param)
|
||||
}
|
||||
@@ -708,7 +712,7 @@ subclasses:
|
||||
```
|
||||
|
||||
```go
|
||||
func pressed() {
|
||||
func pressed(self ns.GButton, super ns.GButtonSupermethods) {
|
||||
fmt.Println("Button pressed!")
|
||||
}
|
||||
...
|
||||
@@ -728,9 +732,109 @@ 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
|
||||
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
|
||||
|
||||
## Blocks
|
||||
## Blocks and Function Pointers
|
||||
|
||||
NSWrap does not support methods or functions that take C functions or blocks
|
||||
as parameters or return values.
|
||||
@@ -742,7 +846,7 @@ and got carried away.
|
||||
|
||||
# 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
|
||||
infrastructure was lifted from Elliot Chance's equally excellent
|
||||
[c2go](https://github.com/elliotchance/c2go). Kiyoshi Murata's
|
||||
|
||||
@@ -5,6 +5,7 @@ type AsmLabelAttr struct {
|
||||
Addr Address
|
||||
Pos Position
|
||||
Inherited bool
|
||||
LiteralLabel bool
|
||||
FunctionName string
|
||||
ChildNodes []Node
|
||||
}
|
||||
@@ -13,7 +14,8 @@ func parseAsmLabelAttr(line string) Node {
|
||||
groups := groupsFromRegex(
|
||||
`<(?P<position>.*)>
|
||||
(?P<inherited> Inherited)?
|
||||
"(?P<function>.+)"`,
|
||||
"(?P<function>.+)"
|
||||
(?P<isliterallabel> IsLiteralLabel)?`,
|
||||
line,
|
||||
)
|
||||
if groups == nil {
|
||||
@@ -24,6 +26,7 @@ func parseAsmLabelAttr(line string) Node {
|
||||
Addr: ParseAddress(groups["address"]),
|
||||
Pos: NewPositionFromString(groups["position"]),
|
||||
Inherited: len(groups["inherited"]) > 0,
|
||||
LiteralLabel: len(groups["isliterallabel"]) > 0,
|
||||
FunctionName: groups["function"],
|
||||
ChildNodes: []Node{},
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ func TestAsmLabelAttr(t *testing.T) {
|
||||
Addr: 0x7ff26d8224e8,
|
||||
Pos: NewPositionFromString("/usr/include/sys/cdefs.h:569:36"),
|
||||
Inherited: false,
|
||||
LiteralLabel: false,
|
||||
FunctionName: "_fopen",
|
||||
ChildNodes: []Node{},
|
||||
},
|
||||
@@ -21,6 +22,7 @@ func TestAsmLabelAttr(t *testing.T) {
|
||||
Addr: 0x7fd55a169318,
|
||||
Pos: NewPositionFromString("/usr/include/stdio.h:325:47"),
|
||||
Inherited: true,
|
||||
LiteralLabel: false,
|
||||
FunctionName: "_popen",
|
||||
ChildNodes: []Node{},
|
||||
},
|
||||
@@ -28,6 +30,18 @@ func TestAsmLabelAttr(t *testing.T) {
|
||||
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)
|
||||
|
||||
@@ -89,10 +89,14 @@ func Parse(fullline string) Node {
|
||||
return parseBlockPointerType(line)
|
||||
case "BreakStmt":
|
||||
return parseBreakStmt(line)
|
||||
case "BuiltinAttr":
|
||||
return parseBuiltinAttr(line)
|
||||
case "BuiltinType":
|
||||
return parseBuiltinType(line)
|
||||
case "CallExpr":
|
||||
return parseCallExpr(line)
|
||||
case "ConstantExpr":
|
||||
return parseConstantExpr(line)
|
||||
case "ConvertVectorExpr":
|
||||
return parseConvertVectorExpr(line)
|
||||
case "CaseStmt":
|
||||
@@ -107,6 +111,8 @@ func Parse(fullline string) Node {
|
||||
return parseCFReturnsNotRetainedAttr(line)
|
||||
case "CharacterLiteral":
|
||||
return parseCharacterLiteral(line)
|
||||
case "ColdAttr":
|
||||
return parseColdAttr(line)
|
||||
case "CompoundLiteralExpr":
|
||||
return parseCompoundLiteralExpr(line)
|
||||
case "CompoundStmt":
|
||||
@@ -285,6 +291,8 @@ func Parse(fullline string) Node {
|
||||
return parseObjCRootClassAttr(line)
|
||||
case "ObjCPropertyDecl":
|
||||
return parseObjCPropertyDecl(line)
|
||||
case "ObjCTypeParam":
|
||||
return parseObjCTypeParam(line)
|
||||
case "ObjCTypeParamDecl":
|
||||
return parseObjCTypeParamDecl(line)
|
||||
case "OffsetOfExpr":
|
||||
|
||||
@@ -9,6 +9,7 @@ type AvailabilityAttr struct {
|
||||
Version string
|
||||
Unknown1 string
|
||||
Unknown2 string
|
||||
Unknown3 string
|
||||
IsUnavailable bool
|
||||
Message1 string
|
||||
Message2 string
|
||||
@@ -26,7 +27,7 @@ func parseAvailabilityAttr(line string) Node {
|
||||
(?P<unknown2>[\d_.]+)
|
||||
(?P<unavalable> Unavailable)?
|
||||
"(?P<message1>.*?)"
|
||||
(?P<message2> ".*?")?`,
|
||||
(?P<message2> ".*?")?( (?P<unknown3>[\d_.]+))?`,
|
||||
line,
|
||||
)
|
||||
if groups == nil {
|
||||
@@ -40,6 +41,7 @@ func parseAvailabilityAttr(line string) Node {
|
||||
Version: groups["version"],
|
||||
Unknown1: groups["unknown1"],
|
||||
Unknown2: groups["unknown2"],
|
||||
Unknown3: groups["unknown3"],
|
||||
IsUnavailable: len(groups["unavalable"]) > 0,
|
||||
Message1: removeQuotes(groups["message1"]),
|
||||
Message2: removeQuotes(groups["message2"]),
|
||||
|
||||
@@ -13,6 +13,7 @@ func TestAvailabilityAttr(t *testing.T) {
|
||||
Version: "10.10",
|
||||
Unknown1: "0",
|
||||
Unknown2: "0",
|
||||
Unknown3: "",
|
||||
IsUnavailable: false,
|
||||
Message1: "",
|
||||
Message2: "",
|
||||
@@ -30,6 +31,7 @@ func TestAvailabilityAttr(t *testing.T) {
|
||||
Version: "3.0",
|
||||
Unknown1: "0",
|
||||
Unknown2: "0",
|
||||
Unknown3: "",
|
||||
IsUnavailable: false,
|
||||
Message1: "",
|
||||
Message2: "",
|
||||
@@ -47,6 +49,7 @@ func TestAvailabilityAttr(t *testing.T) {
|
||||
Version: "10.0",
|
||||
Unknown1: "0",
|
||||
Unknown2: "0",
|
||||
Unknown3: "",
|
||||
IsUnavailable: false,
|
||||
Message1: "",
|
||||
Message2: "",
|
||||
@@ -64,6 +67,7 @@ func TestAvailabilityAttr(t *testing.T) {
|
||||
Version: "10.0",
|
||||
Unknown1: "0",
|
||||
Unknown2: "0",
|
||||
Unknown3: "",
|
||||
IsUnavailable: false,
|
||||
Message1: "",
|
||||
Message2: "",
|
||||
@@ -81,6 +85,7 @@ func TestAvailabilityAttr(t *testing.T) {
|
||||
Version: "0",
|
||||
Unknown1: "0",
|
||||
Unknown2: "0",
|
||||
Unknown3: "",
|
||||
IsUnavailable: true,
|
||||
Message1: "Use snprintf instead.",
|
||||
Message2: "",
|
||||
@@ -98,6 +103,7 @@ func TestAvailabilityAttr(t *testing.T) {
|
||||
Version: "0",
|
||||
Unknown1: "0",
|
||||
Unknown2: "0",
|
||||
Unknown3: "",
|
||||
IsUnavailable: true,
|
||||
Message1: "Use mkstemp(3) instead.",
|
||||
Message2: "",
|
||||
@@ -115,6 +121,7 @@ func TestAvailabilityAttr(t *testing.T) {
|
||||
Version: "10.10",
|
||||
Unknown1: "0",
|
||||
Unknown2: "0",
|
||||
Unknown3: "",
|
||||
IsUnavailable: false,
|
||||
Message1: "",
|
||||
Message2: "",
|
||||
@@ -132,6 +139,25 @@ func TestAvailabilityAttr(t *testing.T) {
|
||||
Version: "10.5",
|
||||
Unknown1: "0",
|
||||
Unknown2: "0",
|
||||
Unknown3: "",
|
||||
IsUnavailable: false,
|
||||
Message1: "",
|
||||
Message2: "",
|
||||
IsInherited: true,
|
||||
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: "",
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
+3
-1
@@ -4,12 +4,13 @@ package ast
|
||||
type IfStmt struct {
|
||||
Addr Address
|
||||
Pos Position
|
||||
HasElse bool
|
||||
ChildNodes []Node
|
||||
}
|
||||
|
||||
func parseIfStmt(line string) Node {
|
||||
groups := groupsFromRegex(
|
||||
"<(?P<position>.*)>",
|
||||
"<(?P<position>.*)>(?P<has_else> has_else)?",
|
||||
line,
|
||||
)
|
||||
if groups == nil {
|
||||
@@ -19,6 +20,7 @@ func parseIfStmt(line string) Node {
|
||||
return &IfStmt{
|
||||
Addr: ParseAddress(groups["address"]),
|
||||
Pos: NewPositionFromString(groups["position"]),
|
||||
HasElse: len(groups["has_else"]) > 0,
|
||||
ChildNodes: []Node{},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,17 @@ func TestIfStmt(t *testing.T) {
|
||||
nodes := map[string]testNode{
|
||||
`0x7fc0a69091d0 <line:11:7, line:18:7>`: testNode{&IfStmt{
|
||||
Addr: 0x7fc0a69091d0,
|
||||
HasElse: false,
|
||||
Pos: NewPositionFromString("line:11:7, line:18:7"),
|
||||
ChildNodes: []Node{},
|
||||
},
|
||||
0x7fc0a69091d0,
|
||||
NewPositionFromString("line:11:7, line:18:7"),
|
||||
[]Node{},
|
||||
},
|
||||
`0x7fc0a69091d0 <line:11:7, line:18:7> has_else`: testNode{&IfStmt{
|
||||
Addr: 0x7fc0a69091d0,
|
||||
HasElse: true,
|
||||
Pos: NewPositionFromString("line:11:7, line:18:7"),
|
||||
ChildNodes: []Node{},
|
||||
},
|
||||
|
||||
@@ -18,8 +18,8 @@ type ObjCInterfaceDecl struct {
|
||||
func parseObjCInterfaceDecl(line string) Node {
|
||||
groups := groupsFromRegex(
|
||||
`(?:prev (?P<prev>0x[0-9a-f]+) )?
|
||||
<(?P<position><invalid sloc>|.*)>
|
||||
(?P<position2> <invalid sloc>| col:\d+| line:\d+:\d+)
|
||||
<(?P<position><invalid sloc>|[^>]*)>
|
||||
(?P<position2>( <invalid sloc>| col:\d+| line:\d+:\d+| <scratch space>:\d+:\d+))
|
||||
(?P<implicit> implicit)?
|
||||
(?P<name> \w+)?`,
|
||||
line,
|
||||
|
||||
@@ -15,7 +15,7 @@ type ObjCMethodDecl struct {
|
||||
Parameters []string
|
||||
Type string
|
||||
Type2 string
|
||||
Attr string
|
||||
Attr []string
|
||||
ChildNodes []Node
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ func parseObjCMethodDecl(line string) Node {
|
||||
(?P<implicit> implicit)?
|
||||
(?P<methodtype> \+| \-)
|
||||
(?P<names>.*?)
|
||||
'(?P<type>[^']*?)'
|
||||
'(?P<type>.*?)'
|
||||
(:'(?P<type2>.*?)')?
|
||||
(?P<attr> .*)?`,
|
||||
line,
|
||||
@@ -43,6 +43,8 @@ func parseObjCMethodDecl(line string) Node {
|
||||
params = parts[:len(parts)-1]
|
||||
}
|
||||
|
||||
attrs := strings.Split(strings.TrimSpace(groups["attr"]), " ")
|
||||
|
||||
return &ObjCMethodDecl{
|
||||
Addr: ParseAddress(groups["address"]),
|
||||
Pos: NewPositionFromString(groups["position"]),
|
||||
@@ -53,7 +55,7 @@ func parseObjCMethodDecl(line string) Node {
|
||||
Parameters: params,
|
||||
Type: strings.TrimSpace(groups["type"]),
|
||||
//Type2: strings.TrimSpace(groups["type2"]),
|
||||
Attr: strings.TrimSpace(groups["attr"]),
|
||||
Attr: attrs,
|
||||
ChildNodes: []Node{},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ func TestObjCMethodDecl(t *testing.T) {
|
||||
ClassMethod: false,
|
||||
Parameters: []string{"isEqual"},
|
||||
Implicit: false,
|
||||
Attr: []string{""},
|
||||
ChildNodes: []Node{},
|
||||
},
|
||||
0x7f92a58a7570,
|
||||
@@ -32,6 +33,7 @@ func TestObjCMethodDecl(t *testing.T) {
|
||||
ClassMethod: false,
|
||||
Parameters: []string{},
|
||||
Implicit: false,
|
||||
Attr: []string{""},
|
||||
ChildNodes: []Node{},
|
||||
},
|
||||
0x7f92a58a7978,
|
||||
@@ -48,6 +50,7 @@ func TestObjCMethodDecl(t *testing.T) {
|
||||
ClassMethod: false,
|
||||
Parameters: []string{"respondsToSelector"},
|
||||
Implicit: false,
|
||||
Attr: []string{""},
|
||||
ChildNodes: []Node{},
|
||||
},
|
||||
0x7f92a58a82b0,
|
||||
@@ -64,6 +67,7 @@ func TestObjCMethodDecl(t *testing.T) {
|
||||
ClassMethod: true,
|
||||
Parameters: []string{"instancesRespondToSelector"},
|
||||
Implicit: false,
|
||||
Attr: []string{""},
|
||||
ChildNodes: []Node{},
|
||||
},
|
||||
0x7f92a58a82b0,
|
||||
@@ -80,6 +84,7 @@ func TestObjCMethodDecl(t *testing.T) {
|
||||
ClassMethod: false,
|
||||
Parameters: []string{"performSelector", "withObject", "withObject"},
|
||||
Implicit: false,
|
||||
Attr: []string{""},
|
||||
ChildNodes: []Node{},
|
||||
},
|
||||
0x7f92a58a7cd8,
|
||||
@@ -96,6 +101,7 @@ func TestObjCMethodDecl(t *testing.T) {
|
||||
ClassMethod: false,
|
||||
Parameters: []string{},
|
||||
Implicit: true,
|
||||
Attr: []string{""},
|
||||
ChildNodes: []Node{},
|
||||
},
|
||||
0x7f92a4459318,
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package ast
|
||||
|
||||
// ObjCTypeParam is expression.
|
||||
type ObjCTypeParam struct {
|
||||
Addr Address
|
||||
Type string
|
||||
ChildNodes []Node
|
||||
}
|
||||
|
||||
func parseObjCTypeParam(line string) Node {
|
||||
groups := groupsFromRegex(
|
||||
"'(?P<type>.*?)'",
|
||||
line,
|
||||
)
|
||||
if groups == nil {
|
||||
return &Unknown{}
|
||||
}
|
||||
|
||||
return &ObjCTypeParam{
|
||||
Addr: ParseAddress(groups["address"]),
|
||||
Type: groups["type"],
|
||||
ChildNodes: []Node{},
|
||||
}
|
||||
}
|
||||
|
||||
// AddChild adds a new child node. Child nodes can then be accessed with the
|
||||
// Children attribute.
|
||||
func (n *ObjCTypeParam) 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 *ObjCTypeParam) 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 *ObjCTypeParam) Children() []Node {
|
||||
return n.ChildNodes
|
||||
}
|
||||
|
||||
// Position returns the position in the original source code.
|
||||
func (n *ObjCTypeParam) Position() Position {
|
||||
return Position{}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package ast
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestObjCTypeParam(t *testing.T) {
|
||||
nodes := map[string]testNode{
|
||||
`0x7f9bf3033240 'int'`: testNode{&ObjCTypeParam{
|
||||
Addr: 0x7f9bf3033240,
|
||||
Type: "int",
|
||||
ChildNodes: []Node{},
|
||||
},
|
||||
0x7f9bf3033240,
|
||||
Position{},
|
||||
[]Node{},
|
||||
},
|
||||
`0x7f9bf3035c20 'unsigned int'`: testNode{&ObjCTypeParam{
|
||||
Addr: 0x7f9bf3035c20,
|
||||
Type: "unsigned int",
|
||||
ChildNodes: []Node{},
|
||||
},
|
||||
0x7f9bf3035c20,
|
||||
Position{},
|
||||
[]Node{},
|
||||
},
|
||||
}
|
||||
|
||||
runNodeTests(t, nodes)
|
||||
}
|
||||
@@ -5,11 +5,12 @@ package ast
|
||||
type WarnUnusedResultAttr struct {
|
||||
Addr Address
|
||||
Pos Position
|
||||
Text string
|
||||
ChildNodes []Node
|
||||
}
|
||||
|
||||
func parseWarnUnusedResultAttr(line string) Node {
|
||||
groups := groupsFromRegex(`<(?P<position>.*)>( warn_unused_result)?`, line)
|
||||
groups := groupsFromRegex(`<(?P<position>.*)>( warn_unused_result)?( ".*")?`, line)
|
||||
if groups == nil {
|
||||
return &Unknown{}
|
||||
}
|
||||
|
||||
@@ -24,6 +24,15 @@ func TestWarnUnusedResultAttr(t *testing.T) {
|
||||
NewPositionFromString("line:481:52"),
|
||||
[]Node{},
|
||||
},
|
||||
`0x1fac810 <line:481:52> warn_unused_result ""`: testNode{&WarnUnusedResultAttr{
|
||||
Addr: 0x1fac810,
|
||||
Pos: NewPositionFromString("line:481:52"),
|
||||
ChildNodes: []Node{},
|
||||
},
|
||||
0x1fac810,
|
||||
NewPositionFromString("line:481:52"),
|
||||
[]Node{},
|
||||
},
|
||||
}
|
||||
|
||||
runNodeTests(t, nodes)
|
||||
|
||||
+27
-18
@@ -12,25 +12,29 @@ import (
|
||||
//Shortcut for literal NSStrings
|
||||
var nst = ns.NSStringWithGoString
|
||||
|
||||
func pb1() {
|
||||
func pb1(self ns.GButton, super ns.GButtonSupermethods) {
|
||||
fmt.Println("Pushed button 1")
|
||||
}
|
||||
|
||||
func pb2() {
|
||||
func pb2(self ns.GButton, super ns.GButtonSupermethods) {
|
||||
fmt.Println("Pushed button 2")
|
||||
a.Terminate(a)
|
||||
}
|
||||
|
||||
func didFinishLaunching(n *ns.NSNotification) {
|
||||
func db(self ns.GButton, super ns.GButtonSupermethods) {
|
||||
fmt.Println("button deallocated")
|
||||
}
|
||||
|
||||
func didFinishLaunching(self ns.AppDelegate, n *ns.NSNotification) {
|
||||
fmt.Println("Go: did finish launching")
|
||||
fmt.Printf("Notification: %s\n", n.Name().UTF8String())
|
||||
//Set up an NSWindow
|
||||
win = ns.NSWindowAlloc().InitWithContentRectStyleMask(
|
||||
ns.NSMakeRect(200, 200, 600, 600),
|
||||
ns.NSWindowStyleMaskTitled|ns.NSWindowStyleMaskClosable|
|
||||
ns.NSWindowStyleMaskResizable,
|
||||
ns.NSBackingStoreBuffered,
|
||||
0,
|
||||
ns.NSWindowStyleMask(ns.NSWindowStyleMaskTitled|ns.NSWindowStyleMaskClosable|
|
||||
ns.NSWindowStyleMaskResizable),
|
||||
ns.NSBackingStoreType(ns.NSBackingStoreBuffered),
|
||||
false,
|
||||
)
|
||||
// We do not need to retain this because we are in garbage collection mode
|
||||
// and have assigned it to a global variable.
|
||||
@@ -68,20 +72,22 @@ func didFinishLaunching(n *ns.NSNotification) {
|
||||
|
||||
b1.Init()
|
||||
b1.PressedCallback(pb1)
|
||||
b1.DeallocCallback(db)
|
||||
b1.SetAction(ns.Selector("pressed"))
|
||||
b1.SetTarget(b1)
|
||||
b1.SetTitle(nst("PUSH"))
|
||||
|
||||
b2.Init()
|
||||
b2.PressedCallback(pb2)
|
||||
b2.DeallocCallback(db)
|
||||
b2.SetTarget(b2)
|
||||
b2.SetAction(ns.Selector("pressed"))
|
||||
b2.SetTitle(nst("QUIT"))
|
||||
|
||||
//add some layout constraints
|
||||
|
||||
b1.SetTranslatesAutoresizingMaskIntoConstraints(0)
|
||||
b2.SetTranslatesAutoresizingMaskIntoConstraints(0)
|
||||
b1.SetTranslatesAutoresizingMaskIntoConstraints(false)
|
||||
b2.SetTranslatesAutoresizingMaskIntoConstraints(false)
|
||||
|
||||
cv := win.ContentView()
|
||||
|
||||
@@ -97,26 +103,28 @@ func didFinishLaunching(n *ns.NSNotification) {
|
||||
cv.AddConstraints(ns.NSLayoutConstraintsWithVisualFormat(
|
||||
nst("H:|-[b1]"), 0, nil, viewmap))
|
||||
cv.AddConstraints(ns.NSLayoutConstraintsWithVisualFormat(
|
||||
nst("H:[b1]-[b2]"), ns.NSLayoutFormatAlignAllBaseline, nil, viewmap))
|
||||
nst("H:[b1]-[b2]"), ns.NSLayoutFormatOptions(ns.NSLayoutFormatAlignAllBaseline), nil, viewmap))
|
||||
|
||||
a.ActivateIgnoringOtherApps(1)
|
||||
a.ActivateIgnoringOtherApps(true)
|
||||
}
|
||||
|
||||
func shouldTerminateAfterLastWindowClosed(s *ns.NSApplication) ns.BOOL {
|
||||
return 1
|
||||
func shouldTerminateAfterLastWindowClosed(self ns.AppDelegate, s *ns.NSApplication) ns.BOOL {
|
||||
fmt.Println("Go: should terminate after last window closed")
|
||||
return true
|
||||
}
|
||||
|
||||
func willTerminate(n *ns.NSNotification) {
|
||||
func willTerminate(self ns.AppDelegate, n *ns.NSNotification) {
|
||||
fmt.Println("Go: will terminate")
|
||||
}
|
||||
|
||||
func didBecomeActive(n *ns.NSNotification) {
|
||||
func didBecomeActive(self ns.AppDelegate, n *ns.NSNotification) {
|
||||
fmt.Println("Go: did become active")
|
||||
fmt.Printf("Notification: %s\n", n.Name().UTF8String())
|
||||
}
|
||||
|
||||
var (
|
||||
a *ns.NSApplication
|
||||
del *ns.AppDelegate
|
||||
win *ns.NSWindow
|
||||
)
|
||||
|
||||
@@ -124,10 +132,11 @@ func app() {
|
||||
// Lock OS thread because Cocoa uses thread-local storage
|
||||
runtime.LockOSThread()
|
||||
a = ns.NSApplicationSharedApplication()
|
||||
a.SetActivationPolicy(ns.NSApplicationActivationPolicyRegular)
|
||||
a.SetActivationPolicy(ns.NSApplicationActivationPolicy(ns.NSApplicationActivationPolicyRegular))
|
||||
|
||||
// Set up an AppDelegate
|
||||
del := ns.AppDelegateAlloc()
|
||||
// assign it to a global variable so it doesn't get garbage collected
|
||||
del = ns.AppDelegateAlloc()
|
||||
del.ApplicationDidFinishLaunchingCallback(didFinishLaunching)
|
||||
del.ApplicationShouldTerminateAfterLastWindowClosedCallback(shouldTerminateAfterLastWindowClosed)
|
||||
del.ApplicationWillTerminateCallback(willTerminate)
|
||||
@@ -149,6 +158,6 @@ func main() {
|
||||
}()
|
||||
|
||||
// Run our app in an autorelease pool just for fun
|
||||
go ns.Autoreleasepool(app)
|
||||
go app()
|
||||
select {}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# nswrap.yaml
|
||||
inputfiles:
|
||||
- /System/Library/Frameworks/Foundation.framework/Headers/Foundation.h
|
||||
- /System/Library/Frameworks/AppKit.framework/Headers/AppKit.h
|
||||
- /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.h
|
||||
- /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/AppKit.framework/Headers/AppKit.h
|
||||
|
||||
classes:
|
||||
- NSAutoreleasePool
|
||||
@@ -41,8 +41,7 @@ subclasses:
|
||||
GButton:
|
||||
NSButton:
|
||||
- -(void)pressed
|
||||
- dealloc
|
||||
|
||||
frameworks: [ Foundation, AppKit ]
|
||||
pragma: [ clang diagnostic ignored "-Wformat-security" ]
|
||||
#autorelease: true
|
||||
gogc: true
|
||||
|
||||
+11
-11
@@ -5,14 +5,14 @@ import "C"
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"git.wow.st/gmp/nswrap/examples/bluetooth/ns"
|
||||
"runtime"
|
||||
"time"
|
||||
"git.wow.st/gmp/nswrap/examples/bluetooth/ns"
|
||||
)
|
||||
|
||||
func updateState(c *ns.CBCentralManager) {
|
||||
func updateState(self ns.CBDelegate, c *ns.CBCentralManager) {
|
||||
fmt.Printf("Go: did update state\n")
|
||||
switch cm.CBManager.State() {
|
||||
switch ns.NSInteger(cm.CBManager.State()) {
|
||||
case ns.CBManagerStateUnknown:
|
||||
fmt.Printf(" unknown\n")
|
||||
case ns.CBManagerStateResetting:
|
||||
@@ -30,7 +30,7 @@ func updateState(c *ns.CBCentralManager) {
|
||||
fmt.Printf("Go: updateState returning\n")
|
||||
}
|
||||
|
||||
func discoverPeripheral(c *ns.CBCentralManager, p *ns.CBPeripheral, d *ns.NSDictionary, rssi *ns.NSNumber) {
|
||||
func discoverPeripheral(self ns.CBDelegate, c *ns.CBCentralManager, p *ns.CBPeripheral, d *ns.NSDictionary, rssi *ns.NSNumber) {
|
||||
fmt.Printf("Did discover peripheral\n")
|
||||
c.StopScan()
|
||||
|
||||
@@ -51,7 +51,7 @@ func discoverPeripheral(c *ns.CBCentralManager, p *ns.CBPeripheral, d *ns.NSDict
|
||||
c.ConnectPeripheral(peripheral, nil)
|
||||
}
|
||||
|
||||
func connectPeripheral(c *ns.CBCentralManager, p *ns.CBPeripheral) {
|
||||
func connectPeripheral(self ns.CBDelegate, c *ns.CBCentralManager, p *ns.CBPeripheral) {
|
||||
fmt.Printf("Did connect peripheral\n")
|
||||
|
||||
// set ourselves up as a peripheral delegate
|
||||
@@ -64,7 +64,7 @@ func connectPeripheral(c *ns.CBCentralManager, p *ns.CBPeripheral) {
|
||||
fmt.Printf("Go: discoverPeripheral returning\n")
|
||||
}
|
||||
|
||||
func discoverServices(p *ns.CBPeripheral, e *ns.NSError) {
|
||||
func discoverServices(self ns.CBDelegate, p *ns.CBPeripheral, e *ns.NSError) {
|
||||
fmt.Printf("Did discover services\n")
|
||||
p.Services().ObjectEnumerator().ForIn(func(o *ns.Id) bool {
|
||||
serv := o.CBService()
|
||||
@@ -97,17 +97,17 @@ func hr(d *ns.NSData) int {
|
||||
}
|
||||
}
|
||||
|
||||
func discoverCharacteristics(p *ns.CBPeripheral, s *ns.CBService, e *ns.NSError) {
|
||||
func discoverCharacteristics(self ns.CBDelegate, p *ns.CBPeripheral, s *ns.CBService, e *ns.NSError) {
|
||||
fmt.Printf("Did discover characteristics\n")
|
||||
uuid := s.UUID()
|
||||
fmt.Printf("----%s\n", uuid.UUIDString().UTF8String())
|
||||
fmt.Printf("----%s\n", uuid.UUIDString())
|
||||
if uuid.IsEqualTo(hrm_uuid) {
|
||||
s.Characteristics().ObjectEnumerator().ForIn(func(o *ns.Id) bool {
|
||||
chr := o.CBCharacteristic()
|
||||
chuuid := chr.UUID()
|
||||
fmt.Printf("------%s\n", chuuid.UUIDString().UTF8String())
|
||||
fmt.Printf("------%s\n", chuuid.UUIDString())
|
||||
if chuuid.IsEqualTo(hrv_uuid) {
|
||||
p.SetNotifyValue(1, chr)
|
||||
p.SetNotifyValue((ns.BOOL)(true), chr)
|
||||
v := chr.Value()
|
||||
fmt.Println(hr(v))
|
||||
}
|
||||
@@ -117,7 +117,7 @@ func discoverCharacteristics(p *ns.CBPeripheral, s *ns.CBService, e *ns.NSError)
|
||||
fmt.Printf("Go: discoverCharacteristics returning\n")
|
||||
}
|
||||
|
||||
func updateValue(p *ns.CBPeripheral, chr *ns.CBCharacteristic, e *ns.NSError) {
|
||||
func updateValue(self ns.CBDelegate, p *ns.CBPeripheral, chr *ns.CBCharacteristic, e *ns.NSError) {
|
||||
if chr.UUID().IsEqualTo(hrv_uuid) {
|
||||
v := chr.Value()
|
||||
fmt.Printf("Heart rate: %d\n", hr(v))
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
inputfiles:
|
||||
- /System/Library/Frameworks/Foundation.framework/Headers/Foundation.h
|
||||
- /System/Library/Frameworks/CoreBluetooth.framework/Headers/CoreBluetooth.h
|
||||
- /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.h
|
||||
- /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/CoreBluetooth.framework/Headers/CoreBluetooth.h
|
||||
|
||||
classes:
|
||||
- NSObject
|
||||
@@ -39,4 +39,3 @@ delegates:
|
||||
- peripheralDidUpdateValueForCharacteristic
|
||||
|
||||
pragma: [ clang diagnostic ignored "-Wformat-security" ]
|
||||
gogc: true
|
||||
|
||||
+43
-12
@@ -4,6 +4,7 @@ package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"git.wow.st/gmp/nswrap/examples/foundation/ns"
|
||||
)
|
||||
@@ -43,8 +44,10 @@ func main() {
|
||||
fmt.Printf("i1 = %@\n", i1)
|
||||
fmt.Printf("i1.Ptr() = %p\n", i1.Ptr())
|
||||
fmt.Printf("\nNSArray.ObjectEnumerator().ForIn():\n")
|
||||
x := 0
|
||||
a.ObjectEnumerator().ForIn(func(o *ns.Id) bool {
|
||||
fmt.Println(o.NSString())
|
||||
fmt.Printf("%d: %s\n", x, o.NSString())
|
||||
x++
|
||||
return true
|
||||
})
|
||||
fmt.Printf("\nNSSetWithObjectsCount():\n")
|
||||
@@ -69,6 +72,7 @@ func main() {
|
||||
}
|
||||
return true
|
||||
})
|
||||
fmt.Printf("a = %p a.NSArray = %p\n", a, &a.NSArray)
|
||||
fmt.Printf("\nNSArrayWithObjects() (length 1)\n")
|
||||
a2 = ns.NSArrayWithObjects(n1)
|
||||
a2.ObjectEnumerator().ForIn(func(o *ns.Id) bool {
|
||||
@@ -102,19 +106,26 @@ func main() {
|
||||
ns.NSArrayWithObjects(nst("obj1"), nst("obj2")),
|
||||
ns.NSArrayWithObjects(nst("key1"), nst("key2")),
|
||||
)
|
||||
os := make([]*ns.Id, 0, 5)
|
||||
fmt.Printf("Length of os is %d\n", len(os))
|
||||
ks := make([]*ns.Id, 0, 5)
|
||||
fmt.Printf("\nGetObjects()\n")
|
||||
d.GetObjects(&os, &ks, 4)
|
||||
fmt.Printf("Length of os is now %d\n", len(os))
|
||||
for i, k := range ks {
|
||||
fmt.Printf("-- %s -> %s\n", k.NSString(), os[i].NSString())
|
||||
oarr := make([]*ns.Id, 0, 5)
|
||||
fmt.Printf("Length of oarr is %d\n", len(oarr))
|
||||
karr := make([]*ns.Id, 0, 5)
|
||||
fmt.Printf("\nGetObjectsAndKeysCount()\n")
|
||||
d.GetObjectsAndKeys(&oarr, &karr, 4)
|
||||
fmt.Printf("Length of oarr is now %d\n", len(oarr))
|
||||
for i, k := range karr {
|
||||
fmt.Printf("-- %s -> %s\n", k.NSString(), oarr[i].NSString())
|
||||
}
|
||||
fmt.Printf("\nNSStringWithContentsOfURLEncoding()\n")
|
||||
err := make([]*ns.NSError, 1)
|
||||
n1 = ns.NSStringWithContentsOfURLEncoding(ns.NSURLWithGoString("htttypo://example.com"), 0, &err)
|
||||
fmt.Printf("err: %s\n", err[0].LocalizedDescription())
|
||||
n1 = ns.NSStringWithContentsOfURLEncoding(ns.NSURLWithGoString("http://captive.apple.com"), ns.NSUTF8StringEncoding, &err)
|
||||
if len(err) == 0 {
|
||||
fmt.Printf("n1 = %s\n", n1)
|
||||
}
|
||||
n1 = ns.NSStringWithContentsOfURLEncoding(ns.NSURLWithGoString("htttypo://example.com"), ns.NSUTF8StringEncoding, &err)
|
||||
if len(err) > 0 {
|
||||
fmt.Printf("err[0] = %p -> %p\n", err[0], err[0].Ptr())
|
||||
fmt.Printf("err: %s\n", err[0].LocalizedDescription())
|
||||
}
|
||||
|
||||
fmt.Printf("\nNSStringWithFormat()\n")
|
||||
str := ns.NSStringWithFormat(nst("(%@) (%@)\n(%@)\n"), n2, n3, s1)
|
||||
@@ -126,7 +137,27 @@ func main() {
|
||||
fmt.Printf("\nArrayWithObjects\n")
|
||||
a2 = ns.NSArrayWithObjects(gs1, gs2)
|
||||
a2.ObjectEnumerator().ForIn(func(o *ns.Id) bool {
|
||||
fmt.Printf("--%s\n",o.NSString())
|
||||
fmt.Printf("--%s\n", o.NSString())
|
||||
return true
|
||||
})
|
||||
dir, e := os.Getwd()
|
||||
if e != nil {
|
||||
fmt.Printf("Failed to get current working directory. %s\n", err)
|
||||
os.Exit(-1)
|
||||
}
|
||||
path := nst(dir)
|
||||
filter := ns.NSArrayWithObjects(nst("ast"), nst("yaml"))
|
||||
ost := make([]*ns.NSString, 0, 1)
|
||||
oar := make([]*ns.NSArray, 0, 1)
|
||||
fmt.Printf("\nCompletePathIntoString()\n")
|
||||
i := path.CompletePathIntoString(&ost, false, &oar, filter)
|
||||
fmt.Printf("%d matches\n", i)
|
||||
if i > 0 {
|
||||
fmt.Printf("ost = %s\n", ost[0])
|
||||
fmt.Printf("oar =\n")
|
||||
oar[0].ObjectEnumerator().ForIn(func(o *ns.Id) bool {
|
||||
fmt.Printf("--%s\n", o.NSString())
|
||||
return true
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
inputfiles:
|
||||
- /System/Library/Frameworks/Foundation.framework/Headers/Foundation.h
|
||||
- /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.h
|
||||
classes:
|
||||
- NSAutoreleasePool
|
||||
- NSArray
|
||||
@@ -19,7 +19,7 @@ classes:
|
||||
- NSFileManager
|
||||
- NSObject
|
||||
functions: [ NSMakeRange ]
|
||||
enums: [ P_ALL, CF.* ]
|
||||
enums: [ P_ALL, CF.*, .*StringEncoding ]
|
||||
frameworks: [ Foundation ]
|
||||
pragma: [ clang diagnostic ignored "-Wformat-security" ]
|
||||
vaargs: 32
|
||||
|
||||
@@ -2,25 +2,24 @@ package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"unsafe"
|
||||
"git.wow.st/gmp/nswrap/examples/functions/ns"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var s ns.Stat
|
||||
ns.Puts(ns.CharWithGoString("Hi there"))
|
||||
ret := ns.Fstat(3,&s)
|
||||
fmt.Printf("Fstat: %d\n",ret)
|
||||
ret := ns.Fstat(3, &s)
|
||||
fmt.Printf("Fstat: %d\n", ret)
|
||||
|
||||
fmt.Printf("Opening file\n")
|
||||
f := ns.Fopen(ns.CharWithGoString("nswrap.yaml"),ns.CharWithGoString("r"))
|
||||
ret = ns.Fstat(3,&s)
|
||||
fmt.Printf("Fstat: %d\n",ret)
|
||||
chr := make([]byte,4096)
|
||||
f := ns.Fopen(ns.CharWithGoString("nswrap.yaml"), ns.CharWithGoString("r"))
|
||||
ret = ns.Fstat(3, &s)
|
||||
fmt.Printf("Fstat: %d\n", ret)
|
||||
chr := make([]byte, 4096)
|
||||
i := ns.Fread(unsafe.Pointer(&chr[0]), 1, 4096, f)
|
||||
if i < 4096 {
|
||||
chr = chr[:i]
|
||||
}
|
||||
fmt.Printf("file contents:\n%s\n",string(chr))
|
||||
fmt.Printf("file contents:\n%s\n", string(chr))
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
inputfiles:
|
||||
- /usr/include/stdio.h
|
||||
- /usr/include/stdlib.h
|
||||
- /usr/include/sys/stat.h
|
||||
- /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/stdio.h
|
||||
- /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/stdlib.h
|
||||
- /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/sys/stat.h
|
||||
sysimports:
|
||||
- stdio.h
|
||||
- stdlib.h
|
||||
|
||||
+72
-16
@@ -9,8 +9,8 @@ import (
|
||||
"git.wow.st/gmp/nswrap/examples/gc/ns"
|
||||
)
|
||||
|
||||
func releaseX(x int) func (ns.MyClassSupermethods) {
|
||||
return func(super ns.MyClassSupermethods) {
|
||||
func releaseX(x int) func(ns.MyClass, ns.MyClassSupermethods) {
|
||||
return func(self ns.MyClass, super ns.MyClassSupermethods) {
|
||||
//fmt.Printf("--release %d\n", x)
|
||||
super.Release() // comment out for leak
|
||||
}
|
||||
@@ -19,7 +19,7 @@ func releaseX(x int) func (ns.MyClassSupermethods) {
|
||||
func memtest1() {
|
||||
fmt.Println("memtest1 started")
|
||||
for {
|
||||
arr := make([]*ns.MyClass,1000)
|
||||
arr := make([]*ns.MyClass, 1000)
|
||||
for i := 0; i < 1000; i++ {
|
||||
// Alloc methods set a finalizer that causes the Go GC to
|
||||
// Release these objects.
|
||||
@@ -33,7 +33,7 @@ func memtest1() {
|
||||
// Manually run the Go GC at every loop iteration. May not be needed
|
||||
// in a real program.
|
||||
runtime.GC()
|
||||
time.Sleep(time.Second/50)
|
||||
time.Sleep(time.Second / 50)
|
||||
//fmt.Printf("Loop complete\n")
|
||||
}
|
||||
}
|
||||
@@ -42,8 +42,8 @@ func memtest2() {
|
||||
fmt.Println("memtest2 started")
|
||||
i := 0
|
||||
for {
|
||||
o1 := ns.NSStringAlloc().InitWithGoString(fmt.Sprintf("two string %d",i))
|
||||
o2 := ns.NSStringWithGoString(fmt.Sprintf("two string %d",i))
|
||||
o1 := ns.NSStringAlloc().InitWithGoString(fmt.Sprintf("two string %d", i))
|
||||
o2 := ns.NSStringWithGoString(fmt.Sprintf("two string %d", i))
|
||||
|
||||
// NSWrap runs object constructors inside an @autoreleasepool block,
|
||||
// and then calls "retain" on them before returning to Go. A Go
|
||||
@@ -58,9 +58,9 @@ func memtest2() {
|
||||
// init methods in Objective-C always return a retained object.
|
||||
// init may or may not return the same object that was sent in.
|
||||
|
||||
a1 = a1.InitWithObjects(o1,o2,o3,o4)
|
||||
a1 = a1.InitWithObjects(o1, o2, o3, o4)
|
||||
|
||||
a2 := ns.NSArrayWithObjects(o1,o2,o3,o4)
|
||||
a2 := ns.NSArrayWithObjects(o1, o2, o3, o4)
|
||||
|
||||
// you can always nest alloc and init.
|
||||
|
||||
@@ -74,7 +74,7 @@ func memtest2() {
|
||||
_ = a3
|
||||
|
||||
runtime.GC()
|
||||
time.Sleep(time.Second/50)
|
||||
time.Sleep(time.Second / 50)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,7 +103,7 @@ func memtest3() {
|
||||
// check that our string was retained.
|
||||
|
||||
s1 := arr.ObjectAtIndex(0)
|
||||
gstr := s1.NSString().UTF8String().String()
|
||||
gstr := s1.NSString().String()
|
||||
_ = gstr
|
||||
}
|
||||
}
|
||||
@@ -121,7 +121,8 @@ func memtest4() {
|
||||
_ = o1
|
||||
_ = c1
|
||||
runtime.GC()
|
||||
time.Sleep(time.Second/50)
|
||||
time.Sleep(time.Second / 50)
|
||||
c1.Free() // you need to manually free UTF8Strings
|
||||
}
|
||||
}
|
||||
|
||||
@@ -133,7 +134,7 @@ func memtest5() {
|
||||
// a new NSString object at each loop iteration and cannot be reusing
|
||||
// the same string object.
|
||||
|
||||
str := ns.NSStringWithGoString(fmt.Sprintf("blue string %d",i))
|
||||
str := ns.NSStringWithGoString(fmt.Sprintf("blue string %d", i))
|
||||
|
||||
// SubstringFromIndex should be returning a newly allocated NSString,
|
||||
// which is getting retained by NSWrap and released by a Go GC
|
||||
@@ -145,26 +146,81 @@ func memtest5() {
|
||||
u := sub.UTF8String()
|
||||
u2 := sub2.UTF8String()
|
||||
u3 := sub3.UTF8String()
|
||||
time.Sleep(time.Second / 50)
|
||||
runtime.GC()
|
||||
i++
|
||||
u.Free()
|
||||
u2.Free()
|
||||
u3.Free()
|
||||
_ = u
|
||||
_ = u2
|
||||
_ = u3
|
||||
time.Sleep(time.Second/50)
|
||||
runtime.GC()
|
||||
i++
|
||||
//fmt.Printf("loop completed\n")
|
||||
}
|
||||
}
|
||||
|
||||
func tmpdict(i int) *ns.NSString {
|
||||
o1 := ns.NSStringWithGoString(fmt.Sprintf("temp string 1-%d", i))
|
||||
o2 := ns.NSStringWithGoString(fmt.Sprintf("temp string 2-%d", i))
|
||||
k1 := ns.NSStringWithGoString(fmt.Sprintf("temp key 1-%d", i))
|
||||
k2 := ns.NSStringWithGoString(fmt.Sprintf("temp key 2-%d", i))
|
||||
dict := ns.NSDictionaryWithObjectsAndKeys(o1, k1, o2, k2)
|
||||
ret := dict.ValueForKey(k1)
|
||||
//fmt.Printf("tmpdict(): string = %s\n",ret.NSString())
|
||||
|
||||
defer runtime.GC() // o1, o2, k1, k2, and dict can be released after we return
|
||||
return ret.NSString() // should be retained by NSDictionary.ValueForKey()
|
||||
}
|
||||
|
||||
func tmparr(i int) *ns.NSString {
|
||||
o1 := ns.NSStringWithGoString(fmt.Sprintf("temp string 3-%d", i))
|
||||
o2 := ns.NSStringWithGoString(fmt.Sprintf("temp string 4-%d", i))
|
||||
arr := ns.NSArrayWithObjects(o1, o2)
|
||||
os := make([]*ns.Id, 0, 2)
|
||||
arr.GetObjectsRange(&os, ns.NSMakeRange(0, 2))
|
||||
|
||||
defer runtime.GC() // collect o1, o2 and arr
|
||||
return os[1].NSString() // should have been retained by NSArray.GetObjects()
|
||||
}
|
||||
|
||||
func memtest6() {
|
||||
fmt.Println("memtest6 started")
|
||||
i := 0
|
||||
for {
|
||||
s1 := tmpdict(i)
|
||||
s2 := tmparr(i)
|
||||
time.Sleep(time.Second / 5)
|
||||
u1 := s1.String() // make sure s1 and s2 are still available
|
||||
u2 := s2.String()
|
||||
e1 := fmt.Sprintf("temp string 1-%d", i)
|
||||
if u1 != e1 {
|
||||
fmt.Printf("tmpdict() error: %s != %s\n", u1, e1)
|
||||
}
|
||||
e2 := fmt.Sprintf("temp string 4-%d", i)
|
||||
if u2 != e2 {
|
||||
fmt.Printf("tmparr() error: %s != %s\n", u2, e2)
|
||||
|
||||
}
|
||||
i++
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
fmt.Printf("MultiThreaded? %t\n", ns.NSThreadIsMultiThreaded())
|
||||
th := ns.NSThreadNew()
|
||||
th.Start()
|
||||
fmt.Printf("MultiThreaded? %t\n", ns.NSThreadIsMultiThreaded())
|
||||
go memtest1()
|
||||
go memtest2()
|
||||
go memtest3()
|
||||
go memtest4()
|
||||
go memtest5()
|
||||
go memtest6()
|
||||
|
||||
go func() {
|
||||
for {
|
||||
// print a progress indicator
|
||||
fmt.Printf("t = %s\n",time.Now())
|
||||
fmt.Printf("t = %s\n", time.Now())
|
||||
time.Sleep(time.Second * 10)
|
||||
}
|
||||
}()
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
inputfiles:
|
||||
- /System/Library/Frameworks/Foundation.framework/Headers/Foundation.h
|
||||
- /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.h
|
||||
classes:
|
||||
- NSAutoreleasePool
|
||||
- NSArray
|
||||
- NSMutableArray
|
||||
- NSString
|
||||
- NSObject
|
||||
- NSDictionary
|
||||
- NSThread
|
||||
subclasses:
|
||||
MyClass:
|
||||
NSObject:
|
||||
@@ -16,4 +17,4 @@ functions:
|
||||
frameworks:
|
||||
- Foundation
|
||||
pragma: [ clang diagnostic ignored "-Wformat-security" ]
|
||||
gogc: true
|
||||
#nogc: true
|
||||
|
||||
+11
-12
@@ -1,3 +1,4 @@
|
||||
// An example of manual memory management (nogc directive in nswrap.yaml)
|
||||
package main
|
||||
|
||||
import "C"
|
||||
@@ -9,13 +10,13 @@ import (
|
||||
"git.wow.st/gmp/nswrap/examples/memory/ns"
|
||||
)
|
||||
|
||||
func dealloc() {
|
||||
func dealloc(self ns.MyClass, super ns.MyClassSupermethods) {
|
||||
//[super dealloc] is called for you automatically, so no Supermethods
|
||||
//struct is provided here.
|
||||
fmt.Println("--dealloc called")
|
||||
}
|
||||
|
||||
func release(super ns.MyClassSupermethods) {
|
||||
func release(self ns.MyClass, super ns.MyClassSupermethods) {
|
||||
fmt.Println("--release called")
|
||||
super.Release() // comment out for leak
|
||||
}
|
||||
@@ -38,8 +39,6 @@ func memtest1() {
|
||||
for {
|
||||
pool := ns.NSAutoreleasePoolAlloc().Init()
|
||||
o1 := ns.MyClassAlloc()
|
||||
//If autorelease: true is set in nswrap.yaml, the manual calls to
|
||||
//autorelease are not necessary.
|
||||
o1.Autorelease()
|
||||
o1.DeallocCallback(dealloc)
|
||||
o1.ReleaseCallback(release)
|
||||
@@ -93,19 +92,19 @@ func memtest3() {
|
||||
ns.Autoreleasepool(func() {
|
||||
arr := ns.NSMutableArrayAlloc().Init()
|
||||
arr.Autorelease()
|
||||
arr.AddObject(ns.NSStringWithGoString(fmt.Sprintf("my string %d",i)))
|
||||
s1 := ns.NSStringWithGoString(fmt.Sprintf("my other string %d",i))
|
||||
fmt.Printf("%s\n",arr.ObjectAtIndex(0).NSString())
|
||||
arr.AddObject(ns.NSStringWithGoString(fmt.Sprintf("my string %d", i)))
|
||||
s1 := ns.NSStringWithGoString(fmt.Sprintf("my other string %d", i))
|
||||
fmt.Printf("%s\n", arr.ObjectAtIndex(0).NSString())
|
||||
_ = s1
|
||||
|
||||
for x := 0; x < 3; x++ {
|
||||
ns.Autoreleasepool(func() {
|
||||
str := arr.ObjectAtIndex(0).NSString()
|
||||
fmt.Printf("%d->%s\n",x,str) // does not leak in an autorelease pool
|
||||
fmt.Printf("%d->%s\n", x, str) // does not leak in an autorelease pool
|
||||
time.Sleep(time.Second / 5)
|
||||
})
|
||||
}
|
||||
time.Sleep(time.Second/2)
|
||||
time.Sleep(time.Second / 2)
|
||||
i++
|
||||
})
|
||||
}
|
||||
@@ -133,6 +132,9 @@ func memtest4() {
|
||||
go memtest1()
|
||||
go memtest2()
|
||||
go memtest3()
|
||||
go memtest1()
|
||||
go memtest2()
|
||||
go memtest3()
|
||||
}
|
||||
|
||||
func memtest4a() {
|
||||
@@ -196,9 +198,6 @@ func main() {
|
||||
//Within an autorelease pool, do not do anything that can result in a
|
||||
//switch to a different thread.
|
||||
|
||||
//go memtest1()
|
||||
//go memtest2()
|
||||
//go memtest3()
|
||||
go memtest4()
|
||||
select {}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
inputfiles:
|
||||
- /System/Library/Frameworks/Foundation.framework/Headers/Foundation.h
|
||||
- /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.h
|
||||
classes:
|
||||
- NSAutoreleasePool
|
||||
- NSArray
|
||||
@@ -14,3 +14,4 @@ subclasses:
|
||||
frameworks:
|
||||
- Foundation
|
||||
pragma: [ clang diagnostic ignored "-Wformat-security" ]
|
||||
nogc: true
|
||||
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
ns "git.wow.st/gmp/nswrap/examples/simple/ClassOne"
|
||||
)
|
||||
|
||||
func cb(super ns.ClassThreeSupermethods) ns.Int {
|
||||
func cb(self ns.ClassThree, super ns.ClassThreeSupermethods) ns.Int {
|
||||
fmt.Printf("In Go callback\n")
|
||||
return 0
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package: ClassOne
|
||||
inputfiles: [ ClassOne/simple.h ]
|
||||
classes:
|
||||
- NSObject
|
||||
- ClassOne
|
||||
- ClassTwo
|
||||
subclasses:
|
||||
@@ -8,8 +9,7 @@ subclasses:
|
||||
ClassTwo:
|
||||
- geti1
|
||||
- -(void)myMethod1:(int)a
|
||||
- +(const NSObject* _Nonnull)myMethod2:(int)a options:(NSDictionary<NSString*,NSObject*> *)opt
|
||||
- -(const NSObject* _Nonnull)myMethod2:(int)a options:(NSDictionary<NSString*,NSObject*> *)opt
|
||||
|
||||
imports: [ simple.h ]
|
||||
frameworks: [ Foundation ]
|
||||
#arc: true
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"runtime"
|
||||
"sync"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"git.wow.st/gmp/nswrap/examples/strings/ns"
|
||||
)
|
||||
|
||||
func incr() func(bool) (int, float64) {
|
||||
i := 0
|
||||
b := 0.0
|
||||
var mx sync.Mutex
|
||||
return func(bad bool) (int, float64) {
|
||||
mx.Lock()
|
||||
if bad {
|
||||
b++
|
||||
defer mx.Unlock()
|
||||
} else {
|
||||
defer func() { i++; mx.Unlock() }()
|
||||
}
|
||||
if b == 0 {
|
||||
return i, 0.0
|
||||
} else {
|
||||
return i, (b / float64(i)) * 100
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type tracker struct {
|
||||
add, drop func(*ns.Id)
|
||||
check func()
|
||||
i func(bool) (int, float64)
|
||||
}
|
||||
|
||||
type record struct {
|
||||
ptr unsafe.Pointer
|
||||
goPtr *ns.Id
|
||||
when time.Time
|
||||
}
|
||||
|
||||
func newTracker() (func(*ns.Id), func(*ns.Id), func()) {
|
||||
addch := make(chan *ns.Id)
|
||||
dropch := make(chan *ns.Id)
|
||||
data := []record{}
|
||||
var mux sync.Mutex
|
||||
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case x := <-addch:
|
||||
mux.Lock()
|
||||
data = append(data, record{
|
||||
x.Ptr(),
|
||||
x,
|
||||
time.Now(),
|
||||
})
|
||||
mux.Unlock()
|
||||
case x := <-dropch:
|
||||
mux.Lock()
|
||||
data = append(data, record{
|
||||
nil,
|
||||
x,
|
||||
time.Now(),
|
||||
})
|
||||
mux.Unlock()
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
add := func(x *ns.Id) {
|
||||
addch <- x
|
||||
}
|
||||
drop := func(x *ns.Id) {
|
||||
dropch <- x
|
||||
}
|
||||
check := func() {
|
||||
live := map[unsafe.Pointer]*ns.Id{}
|
||||
bad := false
|
||||
mux.Lock()
|
||||
for _, r := range data {
|
||||
if r.ptr != nil {
|
||||
if live[r.ptr] != nil {
|
||||
fmt.Printf("COLLISION: %p & %p -> %p\n", r.goPtr, live[r.ptr], r.ptr)
|
||||
bad = true
|
||||
}
|
||||
live[r.ptr] = r.goPtr
|
||||
} else {
|
||||
delete(live, r.ptr)
|
||||
}
|
||||
}
|
||||
fmt.Printf("Checked %d records -- ", len(data))
|
||||
if bad {
|
||||
fmt.Printf("failed\n")
|
||||
} else {
|
||||
fmt.Printf("ok\n")
|
||||
}
|
||||
mux.Unlock()
|
||||
}
|
||||
return add, drop, check
|
||||
}
|
||||
|
||||
func mkstrings(t tracker) {
|
||||
for {
|
||||
//fmt.Printf("main thread: %t\n",ns.NSThreadIsMainThread())
|
||||
x, b := t.i(false)
|
||||
str := fmt.Sprintf("string %d", x)
|
||||
s := ns.NSStringWithGoString(str)
|
||||
//t.add(&s.Id)
|
||||
for j := 0; j < 10; j++ {
|
||||
sout := s.String()
|
||||
if str != sout {
|
||||
_, b = t.i(true)
|
||||
fmt.Printf("%3.2f%% -- %d: '%s' '%s'\n", b, x, str, sout)
|
||||
}
|
||||
time.Sleep(time.Second / 1000)
|
||||
}
|
||||
if x%1000 == 0 {
|
||||
fmt.Printf("%3.2f%% -- %s\n", b, time.Now().Format("03:04:05.000"))
|
||||
}
|
||||
//t.drop(&s.Id)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
runtime.GOMAXPROCS(4)
|
||||
fmt.Printf("Starting\n")
|
||||
//ns.NSThreadNew().Start()
|
||||
fmt.Printf("multithreaded: %t\n", ns.NSThreadIsMultiThreaded())
|
||||
//pool := ns.NSAutoreleasePoolAlloc()
|
||||
add, drop, check := newTracker()
|
||||
i := tracker{add, drop, check, incr()}
|
||||
go mkstrings(i)
|
||||
go mkstrings(i)
|
||||
go mkstrings(i)
|
||||
go mkstrings(i)
|
||||
go mkstrings(i)
|
||||
go mkstrings(i)
|
||||
go mkstrings(i)
|
||||
go mkstrings(i)
|
||||
go func() {
|
||||
for {
|
||||
runtime.GC()
|
||||
time.Sleep(time.Second / 100)
|
||||
}
|
||||
}()
|
||||
|
||||
time.Sleep(time.Second * 600)
|
||||
i.check()
|
||||
|
||||
//pool.Drain()
|
||||
os.Exit(0)
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
inputfiles:
|
||||
- /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.h
|
||||
classes:
|
||||
- NSString
|
||||
- NSThread
|
||||
frameworks:
|
||||
- Foundation
|
||||
pragma: [ clang diagnostic ignored "-Wformat-security" ]
|
||||
#nogc: true
|
||||
@@ -0,0 +1,31 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"git.wow.st/gmp/nswrap/examples/subclass/ns"
|
||||
)
|
||||
|
||||
func c1release(self ns.C1, super ns.C1Supermethods) {
|
||||
fmt.Printf("c1release()\n")
|
||||
super.Release()
|
||||
fmt.Printf("c1release() done\n")
|
||||
}
|
||||
|
||||
func c2myMethod(self ns.C2) {
|
||||
fmt.Printf("c2myMethod()\n")
|
||||
}
|
||||
|
||||
func main() {
|
||||
fmt.Printf("Starting\n")
|
||||
|
||||
c1 := ns.C1Alloc()
|
||||
c1.ReleaseCallback(c1release)
|
||||
c1.Release()
|
||||
|
||||
c2 := ns.C2Alloc()
|
||||
c2.MyMethodCallback(c2myMethod)
|
||||
c2.Release()
|
||||
|
||||
fmt.Printf("Done\n")
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
inputfiles: [ /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.h ]
|
||||
classes:
|
||||
- NSObject
|
||||
- NSString
|
||||
subclasses:
|
||||
c1:
|
||||
NSObject:
|
||||
- dealloc
|
||||
- release
|
||||
c2:
|
||||
NSObject:
|
||||
- -(void)myMethod
|
||||
# c3:
|
||||
# NSObject:
|
||||
# - -(void)myMethod:(int)i
|
||||
# c4:
|
||||
# NSObject:
|
||||
# - release
|
||||
# - -(int)myMethod:(int)i
|
||||
# c5:
|
||||
# NSObject:
|
||||
# - release
|
||||
# - -(void)myMethod
|
||||
|
||||
frameworks: [ Foundation ]
|
||||
pragma: [ clang diagnostic ignored "-Wformat-security" ]
|
||||
@@ -0,0 +1,8 @@
|
||||
module git.wow.st/gmp/nswrap
|
||||
|
||||
go 1.16
|
||||
|
||||
require (
|
||||
github.com/a8m/envsubst v1.2.0
|
||||
gopkg.in/yaml.v2 v2.4.0
|
||||
)
|
||||
@@ -0,0 +1,5 @@
|
||||
github.com/a8m/envsubst v1.2.0 h1:yvzAhJD2QKdo35Ut03wIfXQmg+ta3wC/1bskfZynz+Q=
|
||||
github.com/a8m/envsubst v1.2.0/go.mod h1:PpvLvNWa+Rvu/10qXmFbFiGICIU5hZvFJNPCCkUaObg=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||
@@ -12,34 +12,47 @@ import (
|
||||
"strings"
|
||||
|
||||
"git.wow.st/gmp/nswrap/ast"
|
||||
"git.wow.st/gmp/nswrap/types"
|
||||
"git.wow.st/gmp/nswrap/wrap"
|
||||
|
||||
"github.com/a8m/envsubst"
|
||||
"gopkg.in/yaml.v2"
|
||||
)
|
||||
|
||||
var Debug = false
|
||||
var Profile = false
|
||||
|
||||
//automatically add interfaces if they are found in the input interface
|
||||
//declarations
|
||||
var autoadd = []string{
|
||||
"NSObject",
|
||||
}
|
||||
|
||||
type conf struct {
|
||||
Positions bool
|
||||
Package string
|
||||
Inputfiles []string
|
||||
Astfile string
|
||||
Debugast bool
|
||||
Classes []string
|
||||
Functions []string
|
||||
Enums []string
|
||||
Delegates map[string]map[string][]string
|
||||
Subclasses map[string]map[string][]string
|
||||
Frameworks []string
|
||||
Frameworkdirs []string
|
||||
Imports []string
|
||||
Sysimports []string
|
||||
Pragma []string
|
||||
Vaargs int
|
||||
Positions bool
|
||||
Package string
|
||||
Inputfiles []string
|
||||
Astfile string
|
||||
Debugast bool
|
||||
Classes []string
|
||||
Functions []string
|
||||
FunctionIgnore []string
|
||||
Enums []string
|
||||
Delegates map[string]map[string][]string
|
||||
Subclasses map[string]map[string][]string
|
||||
Frameworks []string
|
||||
Libraries []string
|
||||
Frameworkdirs []string
|
||||
Imports []string
|
||||
Sysimports []string
|
||||
Pragma []string
|
||||
Typesubs map[string]string
|
||||
Vaargs int
|
||||
Clang string
|
||||
//Arc flag for debugging only, builds will break
|
||||
Arc bool
|
||||
Autorelease bool
|
||||
Gogc bool
|
||||
Nogc bool
|
||||
}
|
||||
|
||||
var Config conf
|
||||
@@ -227,7 +240,12 @@ func Start() (err error) {
|
||||
}
|
||||
cargs = append(cargs, Config.Inputfiles...)
|
||||
fmt.Printf("Generating AST\n")
|
||||
astPP, err = exec.Command("clang", cargs...).Output()
|
||||
clang := "clang"
|
||||
if Config.Clang != "" {
|
||||
clang = Config.Clang
|
||||
}
|
||||
fmt.Printf("%s %s\n", clang, strings.Join(cargs, " "))
|
||||
astPP, err = exec.Command(clang, cargs...).Output()
|
||||
if err != nil {
|
||||
// If clang fails it still prints out the AST, so we have to run it
|
||||
// again to get the real error.
|
||||
@@ -251,19 +269,20 @@ func Start() (err error) {
|
||||
if Config.Positions {
|
||||
ast.TrackPositions = true
|
||||
}
|
||||
if Config.Gogc && Config.Autorelease {
|
||||
fmt.Printf("Cannot use Autorelease and Gogc directives at the same time\n")
|
||||
os.Exit(-1)
|
||||
}
|
||||
wrap.Gogc = true
|
||||
|
||||
if Config.Arc {
|
||||
wrap.Arc = true
|
||||
wrap.Gogc = false
|
||||
}
|
||||
if Config.Autorelease {
|
||||
wrap.Autorelease = true
|
||||
wrap.Gogc = false
|
||||
}
|
||||
if Config.Gogc {
|
||||
wrap.Gogc = true
|
||||
if Config.Nogc {
|
||||
wrap.Gogc = false
|
||||
}
|
||||
|
||||
//NOTE: converting in parallel is slower on my system
|
||||
//nodes := convertLinesToNodesParallel(lines)
|
||||
nodes := convertLinesToNodes(lines)
|
||||
@@ -274,12 +293,14 @@ func Start() (err error) {
|
||||
w := wrap.NewWrapper(Debug)
|
||||
w.Package = Config.Package
|
||||
w.Frameworks = Config.Frameworks
|
||||
w.Libraries = Config.Libraries
|
||||
w.Frameworkdirs = Config.Frameworkdirs
|
||||
w.Import(Config.Imports)
|
||||
w.SysImport(Config.Sysimports)
|
||||
w.Pragmas = Config.Pragma
|
||||
w.Delegate(Config.Delegates)
|
||||
w.Subclass(Config.Subclasses)
|
||||
types.Typesubs = Config.Typesubs
|
||||
if Config.Vaargs == 0 {
|
||||
Config.Vaargs = 16
|
||||
}
|
||||
@@ -297,6 +318,9 @@ func Start() (err error) {
|
||||
}
|
||||
}
|
||||
}
|
||||
if matches(x.Name, autoadd) {
|
||||
Config.Classes = append(Config.Classes, x.Name)
|
||||
}
|
||||
case *ast.ObjCCategoryDecl:
|
||||
w.AddCategory(x)
|
||||
case *ast.TypedefDecl:
|
||||
@@ -304,7 +328,8 @@ func Start() (err error) {
|
||||
w.AddTypedef(x.Name, x.Type)
|
||||
}
|
||||
case *ast.FunctionDecl:
|
||||
if matches(x.Name, Config.Functions) {
|
||||
if matches(x.Name, Config.Functions) &&
|
||||
!matches(x.Name, Config.FunctionIgnore) {
|
||||
w.AddFunction(x)
|
||||
}
|
||||
case *ast.ObjCProtocolDecl:
|
||||
@@ -331,9 +356,18 @@ func main() {
|
||||
defer pprof.StopCPUProfile()
|
||||
}
|
||||
|
||||
confbytes, err := ioutil.ReadFile("nswrap.yaml")
|
||||
conffile := "nswrap.yaml"
|
||||
if len(os.Args) > 1 {
|
||||
conffile = os.Args[1]
|
||||
}
|
||||
confbytes, err := ioutil.ReadFile(conffile)
|
||||
if err != nil {
|
||||
fmt.Printf("%s\n\nFATAL ERROR: Configuration file must be present in directory where nswrap\nis invoked.\n", err)
|
||||
fmt.Printf("%s\n\nFATAL ERROR: Configuration file not found (default: nswrap.yaml)\n", err)
|
||||
os.Exit(-1)
|
||||
}
|
||||
confbytes, err = envsubst.Bytes(confbytes)
|
||||
if err != nil {
|
||||
fmt.Printf("FATAL ERROR: Shell string variable substitution faled: %s\n", err)
|
||||
os.Exit(-1)
|
||||
}
|
||||
if err = yaml.UnmarshalStrict(confbytes, &Config); err != nil {
|
||||
|
||||
@@ -42,7 +42,7 @@ func ChildOf(ret *Node, p Parser) Parser {
|
||||
}
|
||||
}
|
||||
|
||||
//Children takes a parser returns a parser that adds the children of its
|
||||
//Children takes a parser and returns a parser that adds the children of its
|
||||
//output node to the tree. If multiple parsers are passed in, they are
|
||||
//passed to Seq(...)
|
||||
func Children(ps ...Parser) Parser {
|
||||
|
||||
+87
-23
@@ -7,6 +7,9 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
var Gogc bool
|
||||
var Typesubs map[string]string
|
||||
|
||||
//super is a map recording which class is the parent of each other class
|
||||
var super map[string]string
|
||||
|
||||
@@ -199,25 +202,45 @@ func (t *Type) GoType() string {
|
||||
return _goType(t.CType())
|
||||
}
|
||||
|
||||
func typeSub(gt string) string {
|
||||
if Typesubs == nil {
|
||||
return gt
|
||||
}
|
||||
i := 0
|
||||
for ; i < len(gt); i++ {
|
||||
if gt[i] != '*' {
|
||||
break
|
||||
}
|
||||
}
|
||||
gtp := gt[:i]
|
||||
gte := gt[i:]
|
||||
for k, v := range Typesubs {
|
||||
if gte == k {
|
||||
return gtp + v
|
||||
}
|
||||
}
|
||||
return gt
|
||||
}
|
||||
|
||||
func _goType(ct string) string {
|
||||
ct = strings.Title(ct)
|
||||
ct = strings.ReplaceAll(ct, " ", "")
|
||||
ct = strings.TrimPrefix(ct, "Struct")
|
||||
ct = swapstars(ct)
|
||||
if len(ct) > 0 && ct[0] == '*' && IsGoInterface(ct[1:]) {
|
||||
return ct
|
||||
return typeSub(ct)
|
||||
}
|
||||
|
||||
if ct == "Id" {
|
||||
ct = "*Id"
|
||||
}
|
||||
if ShouldWrap(ct) {
|
||||
return ct
|
||||
return typeSub(ct)
|
||||
}
|
||||
if len(ct) > 4 && ct[len(ct)-4:len(ct)] == "Void" {
|
||||
ct = ct[:len(ct)-5] + "unsafe.Pointer"
|
||||
}
|
||||
return ct
|
||||
return typeSub(ct)
|
||||
}
|
||||
|
||||
func (t *Type) CType() string {
|
||||
@@ -269,20 +292,32 @@ func (t *Type) GoTypeDecl(fin bool) string {
|
||||
type %s = %s
|
||||
`, gt, tdgt)
|
||||
}
|
||||
cgt := td.CGoType()
|
||||
eq := ""
|
||||
if len(cgt) > 9 && cgt[:9] == "C.struct_" {
|
||||
//cgt = "C." + cgt[9:]
|
||||
eq = "= "
|
||||
}
|
||||
return fmt.Sprintf(`
|
||||
type %s %s
|
||||
`, gt, td.CGoType())
|
||||
type %s %s%s
|
||||
`, gt, eq, cgt)
|
||||
}
|
||||
if Debug {
|
||||
fmt.Printf(" writing GoTypeDecl for %s\n",gt)
|
||||
fmt.Printf(" writing GoTypeDecl for %s\n", gt)
|
||||
}
|
||||
switch gt {
|
||||
case "", "Void":
|
||||
return ""
|
||||
default:
|
||||
cgt := t.CGoType()
|
||||
eq := ""
|
||||
if len(cgt) > 9 && cgt[:9] == "C.struct_" {
|
||||
//cgt = "C." + cgt[9:]
|
||||
eq = "= "
|
||||
}
|
||||
return fmt.Sprintf(`
|
||||
type %s %s
|
||||
`, gt, t.CGoType())
|
||||
type %s %s%s
|
||||
`, gt, eq, cgt)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -290,12 +325,12 @@ func (t *Type) GoInterfaceDecl(fin bool) string {
|
||||
ct := t.CType()
|
||||
gt := t.GoType()
|
||||
if Debug {
|
||||
fmt.Printf(" writing GoInterfaceDecl for %s\n",gt)
|
||||
fmt.Printf(" writing GoInterfaceDecl for %s\n", gt)
|
||||
}
|
||||
if gt[0] == '*' {
|
||||
gt = gt[1:] // dereference wrapped types
|
||||
ct = ct[:len(ct)-1]
|
||||
fmt.Printf(" dereferenced %s\n",gt)
|
||||
//fmt.Printf(" dereferenced %s\n", gt)
|
||||
}
|
||||
super := Super(ct)
|
||||
if super == "" {
|
||||
@@ -382,7 +417,7 @@ func (t *Type) CToGo(cval string) string {
|
||||
}
|
||||
|
||||
// Call a C function from Go with a given return type and parameter types
|
||||
func GoToC(sname, name string, pnames, snames []string, rtype *Type, ptypes []*Type, fun, fin bool, cm bool) string {
|
||||
func GoToC(sname, name string, pnames, snames []string, rtype *Type, ptypes []*Type, fun, fin bool, cm bool, goImports map[string]bool) string {
|
||||
if rtype == nil {
|
||||
//fmt.Println("nil sent to GoToC")
|
||||
return ""
|
||||
@@ -405,7 +440,7 @@ func GoToC(sname, name string, pnames, snames []string, rtype *Type, ptypes []*T
|
||||
rtgt = "*Id"
|
||||
}
|
||||
ret.WriteString(fmt.Sprintf(
|
||||
`ret := &%s{}
|
||||
`ret := &%s{}
|
||||
ret.ptr = unsafe.Pointer(`, rtgt[1:]))
|
||||
case TypedefShouldWrap(rtgt):
|
||||
isptr = true
|
||||
@@ -414,11 +449,11 @@ func GoToC(sname, name string, pnames, snames []string, rtype *Type, ptypes []*T
|
||||
rtgt = "*Id"
|
||||
}
|
||||
ret.WriteString(fmt.Sprintf(
|
||||
`ret := &%s{}
|
||||
`ret := &%s{}
|
||||
ret.ptr = unsafe.Pointer(`, rtgt[1:]))
|
||||
default:
|
||||
if rtgt == "BOOL" {
|
||||
ret.WriteString("ret := (")
|
||||
ret.WriteString("ret := (bool)(")
|
||||
rtgt = "bool"
|
||||
} else {
|
||||
ret.WriteString("ret := (" + rtgt + ")(")
|
||||
@@ -442,7 +477,11 @@ func GoToC(sname, name string, pnames, snames []string, rtype *Type, ptypes []*T
|
||||
case TypedefShouldWrap(ptgt) && !pt.Variadic && !fun:
|
||||
p = pn + ".Ptr()"
|
||||
case snames[i] != "":
|
||||
p = "unsafe.Pointer(&" + snames[i] + "[0])"
|
||||
cast := pt.CGoType()
|
||||
if len(ptgt) > 2 && ptgt[:1] == "*" && PtrShouldWrap(ptgt[1:]) {
|
||||
cast = "*unsafe.Pointer"
|
||||
}
|
||||
p = fmt.Sprintf("(%s)(unsafe.Pointer(&%s[0]))", cast, snames[i])
|
||||
case pt.Variadic:
|
||||
p = "unsafe.Pointer(&" + p + ")"
|
||||
case pt.IsPointer() && !fun:
|
||||
@@ -462,22 +501,30 @@ func GoToC(sname, name string, pnames, snames []string, rtype *Type, ptypes []*T
|
||||
if isptr {
|
||||
ret.WriteString(")")
|
||||
}
|
||||
if rt == "BOOL" {
|
||||
ret.WriteString(" != 0")
|
||||
}
|
||||
for i, sname := range snames {
|
||||
if sname == "" {
|
||||
continue
|
||||
}
|
||||
ptgt := ptypes[i].GoType()
|
||||
if !(len(ptgt) > 2 && ptgt[:1] == "*" && PtrShouldWrap(ptgt[1:])) {
|
||||
continue
|
||||
}
|
||||
if len(ptgt) < 2 {
|
||||
fmt.Printf("Error in function translation -- argument %s to %s should be pointer to pointer\n",pnames[i],name)
|
||||
fmt.Printf("Error in function translation -- argument %s to %s should be pointer to pointer\n", pnames[i], name)
|
||||
os.Exit(-1)
|
||||
}
|
||||
ptgt = ptgt[2:]
|
||||
if IsGoInterface(ptgt) {
|
||||
ptgt = "Id"
|
||||
}
|
||||
dogc := ""
|
||||
if Gogc {
|
||||
goImports["runtime"] = true
|
||||
dogc = fmt.Sprintf(`
|
||||
runtime.SetFinalizer((*%s)[i], func(o *%s) {
|
||||
o.Release()
|
||||
})`, pnames[i], ptgt)
|
||||
}
|
||||
ret.WriteString(fmt.Sprintf(`
|
||||
(*%s) = (*%s)[:cap(*%s)]
|
||||
for i := 0; i < len(*%s); i++ {
|
||||
@@ -486,20 +533,25 @@ func GoToC(sname, name string, pnames, snames []string, rtype *Type, ptypes []*T
|
||||
break
|
||||
}
|
||||
if (*%s)[i] == nil {
|
||||
(*%s)[i] = &%s{}
|
||||
(*%s)[i] = &%s{}%s
|
||||
}
|
||||
(*%s)[i].ptr = %s[i]
|
||||
}`, pnames[i], pnames[i], pnames[i], pnames[i], sname, pnames[i], pnames[i], pnames[i], pnames[i], ptgt, pnames[i], sname))
|
||||
}`, pnames[i], pnames[i], pnames[i], pnames[i], sname, pnames[i], pnames[i], pnames[i], pnames[i], ptgt, dogc, pnames[i], sname))
|
||||
}
|
||||
if rt != "void" {
|
||||
cmp := ""
|
||||
if sw {
|
||||
ka := ""
|
||||
if !cm {
|
||||
goImports["runtime"] = true
|
||||
ka = "runtime.KeepAlive(o); "
|
||||
}
|
||||
if !cm && sname != "copy" && sname != "mutableCopy" {
|
||||
cmp = fmt.Sprintf(`
|
||||
if ret.ptr == o.ptr { return (%s)(unsafe.Pointer(o)) }`,rtgt)
|
||||
if ret.ptr == o.ptr { %sreturn (%s)(unsafe.Pointer(o)) }`, ka, rtgt)
|
||||
}
|
||||
ret.WriteString(fmt.Sprintf(`
|
||||
if ret.ptr == nil { return ret }%s`,cmp))
|
||||
if ret.ptr == nil { %sreturn ret }%s`, ka, cmp))
|
||||
}
|
||||
if fin {
|
||||
dbg := ""
|
||||
@@ -510,13 +562,25 @@ func GoToC(sname, name string, pnames, snames []string, rtype *Type, ptypes []*T
|
||||
dbg2 = fmt.Sprintf(`fmt.Printf("Finalizer (%s): release %%p -> %%p\n", o, o.ptr)
|
||||
`, rtgt)
|
||||
}
|
||||
goImports["runtime"] = true
|
||||
ret.WriteString(fmt.Sprintf(`
|
||||
%sruntime.SetFinalizer(ret, func(o %s) {
|
||||
%so.Release()
|
||||
})`, dbg, rtgt, dbg2))
|
||||
}
|
||||
if !cm {
|
||||
goImports["runtime"] = true
|
||||
ret.WriteString(`
|
||||
runtime.KeepAlive(o)`)
|
||||
}
|
||||
ret.WriteString(`
|
||||
return ret`)
|
||||
} else {
|
||||
if !cm {
|
||||
goImports["runtime"] = true
|
||||
ret.WriteString(`
|
||||
runtime.KeepAlive(o)`)
|
||||
}
|
||||
}
|
||||
return ret.String()
|
||||
}
|
||||
|
||||
+34
-14
@@ -72,8 +72,8 @@ func TestType(t *testing.T) {
|
||||
str = "NSString**"
|
||||
n = &Node{"TypeName", "", []*Node{
|
||||
&Node{"TypedefName", "NSString", []*Node{}},
|
||||
&Node{"Pointer", "*", []*Node{}},
|
||||
&Node{"Pointer", "*", []*Node{}}}}
|
||||
&Node{"Pointer", "*", []*Node{}},
|
||||
&Node{"Pointer", "*", []*Node{}}}}
|
||||
chk_newtype()
|
||||
chk(tp.IsPointer(), true)
|
||||
chk(tp.Typedef(), nil)
|
||||
@@ -82,8 +82,8 @@ func TestType(t *testing.T) {
|
||||
str = "NSObject**"
|
||||
n = &Node{"TypeName", "", []*Node{
|
||||
&Node{"TypedefName", "NSObject", []*Node{}},
|
||||
&Node{"Pointer", "*", []*Node{}},
|
||||
&Node{"Pointer", "*", []*Node{}}}}
|
||||
&Node{"Pointer", "*", []*Node{}},
|
||||
&Node{"Pointer", "*", []*Node{}}}}
|
||||
chk_newtype()
|
||||
chk(tp.IsPointer(), true)
|
||||
nsopp := tp
|
||||
@@ -217,9 +217,7 @@ type NSObject interface {
|
||||
type NSString struct { Id }
|
||||
func (o *NSString) Ptr() unsafe.Pointer { if o == nil { return nil }; return o.ptr }
|
||||
func (o *Id) NSString() *NSString {
|
||||
ret := &NSString{}
|
||||
ret.ptr = o.ptr
|
||||
return ret
|
||||
return (*NSString)(unsafe.Pointer(o))
|
||||
}
|
||||
`)
|
||||
str = "int(void)"
|
||||
@@ -274,36 +272,46 @@ func (o *Id) NSString() *NSString {
|
||||
ptypes := []*Type{nsop, nstp, tint, voidpp}
|
||||
pnames := []string{"p1", "p2", "p3", "p4"}
|
||||
snames := []string{"", "", "", ""}
|
||||
goImports := make(map[string]bool)
|
||||
|
||||
chk_gotoc := func(expected string) {
|
||||
chk(GoToC("myFun", pnames, snames, rtype, ptypes, false, false, false), expected)
|
||||
chk(GoToC("myFun", "myFun", pnames, snames, rtype, ptypes, false, false, false, goImports), expected)
|
||||
}
|
||||
|
||||
chk_gotoc("")
|
||||
|
||||
rtype = void
|
||||
chk_gotoc(`C.myFun(p1.Ptr(), p2.Ptr(), (C.int)(p3), unsafe.Pointer(p4))`)
|
||||
chk_gotoc(`C.myFun(p1.Ptr(), p2.Ptr(), (C.int)(p3), unsafe.Pointer(p4))
|
||||
runtime.KeepAlive(o)`)
|
||||
|
||||
rtype = bl
|
||||
chk_gotoc(
|
||||
`ret := (C.myFun(p1.Ptr(), p2.Ptr(), (C.int)(p3), unsafe.Pointer(p4))) != 0
|
||||
`ret := (bool)(C.myFun(p1.Ptr(), p2.Ptr(), (C.int)(p3), unsafe.Pointer(p4)))
|
||||
runtime.KeepAlive(o)
|
||||
return ret`)
|
||||
|
||||
rtype = voidpp
|
||||
chk_gotoc(
|
||||
`ret := (*unsafe.Pointer)(unsafe.Pointer(C.myFun(p1.Ptr(), p2.Ptr(), (C.int)(p3), unsafe.Pointer(p4))))
|
||||
runtime.KeepAlive(o)
|
||||
return ret`)
|
||||
|
||||
rtype = nstp
|
||||
chk_gotoc(
|
||||
`ret := &NSString{}
|
||||
ret.ptr = unsafe.Pointer(C.myFun(p1.Ptr(), p2.Ptr(), (C.int)(p3), unsafe.Pointer(p4)))
|
||||
if ret.ptr == nil { runtime.KeepAlive(o); return ret }
|
||||
if ret.ptr == o.ptr { runtime.KeepAlive(o); return (*NSString)(unsafe.Pointer(o)) }
|
||||
runtime.KeepAlive(o)
|
||||
return ret`)
|
||||
|
||||
rtype = nsop
|
||||
chk_gotoc(
|
||||
`ret := &Id{}
|
||||
ret.ptr = unsafe.Pointer(C.myFun(p1.Ptr(), p2.Ptr(), (C.int)(p3), unsafe.Pointer(p4)))
|
||||
if ret.ptr == nil { runtime.KeepAlive(o); return ret }
|
||||
if ret.ptr == o.ptr { runtime.KeepAlive(o); return (*Id)(unsafe.Pointer(o)) }
|
||||
runtime.KeepAlive(o)
|
||||
return ret`)
|
||||
|
||||
ptypes[1].Variadic = true
|
||||
@@ -311,6 +319,9 @@ func (o *Id) NSString() *NSString {
|
||||
chk_gotoc(
|
||||
`ret := &Id{}
|
||||
ret.ptr = unsafe.Pointer(C.myFun(p1.Ptr(), unsafe.Pointer(&p2), (C.int)(p3), unsafe.Pointer(p4)))
|
||||
if ret.ptr == nil { runtime.KeepAlive(o); return ret }
|
||||
if ret.ptr == o.ptr { runtime.KeepAlive(o); return (*Id)(unsafe.Pointer(o)) }
|
||||
runtime.KeepAlive(o)
|
||||
return ret`)
|
||||
|
||||
ptypes[1].Variadic = false
|
||||
@@ -318,7 +329,7 @@ func (o *Id) NSString() *NSString {
|
||||
ptypes[1] = nsopp
|
||||
chk_gotoc(
|
||||
`ret := &Id{}
|
||||
ret.ptr = unsafe.Pointer(C.myFun(p1.Ptr(), unsafe.Pointer(&p2p[0]), (C.int)(p3), unsafe.Pointer(p4)))
|
||||
ret.ptr = unsafe.Pointer(C.myFun(p1.Ptr(), (*unsafe.Pointer)(unsafe.Pointer(&p2p[0])), (C.int)(p3), unsafe.Pointer(p4)))
|
||||
(*p2) = (*p2)[:cap(*p2)]
|
||||
for i := 0; i < len(*p2); i++ {
|
||||
if p2p[i] == nil {
|
||||
@@ -330,6 +341,9 @@ func (o *Id) NSString() *NSString {
|
||||
}
|
||||
(*p2)[i].ptr = p2p[i]
|
||||
}
|
||||
if ret.ptr == nil { runtime.KeepAlive(o); return ret }
|
||||
if ret.ptr == o.ptr { runtime.KeepAlive(o); return (*Id)(unsafe.Pointer(o)) }
|
||||
runtime.KeepAlive(o)
|
||||
return ret`)
|
||||
snames[1] = ""
|
||||
snames[2] = "p3p"
|
||||
@@ -337,7 +351,7 @@ func (o *Id) NSString() *NSString {
|
||||
ptypes[2] = nstpp
|
||||
chk_gotoc(
|
||||
`ret := &Id{}
|
||||
ret.ptr = unsafe.Pointer(C.myFun(p1.Ptr(), p2.Ptr(), unsafe.Pointer(&p3p[0]), unsafe.Pointer(p4)))
|
||||
ret.ptr = unsafe.Pointer(C.myFun(p1.Ptr(), p2.Ptr(), (*unsafe.Pointer)(unsafe.Pointer(&p3p[0])), unsafe.Pointer(p4)))
|
||||
(*p3) = (*p3)[:cap(*p3)]
|
||||
for i := 0; i < len(*p3); i++ {
|
||||
if p3p[i] == nil {
|
||||
@@ -349,11 +363,14 @@ func (o *Id) NSString() *NSString {
|
||||
}
|
||||
(*p3)[i].ptr = p3p[i]
|
||||
}
|
||||
if ret.ptr == nil { runtime.KeepAlive(o); return ret }
|
||||
if ret.ptr == o.ptr { runtime.KeepAlive(o); return (*Id)(unsafe.Pointer(o)) }
|
||||
runtime.KeepAlive(o)
|
||||
return ret`)
|
||||
|
||||
chk(GoToC("myFun", pnames, snames, rtype, ptypes, true, false, false),
|
||||
chk(GoToC("myFun", "myFun", pnames, snames, rtype, ptypes, true, false, false, goImports),
|
||||
`ret := &Id{}
|
||||
ret.ptr = unsafe.Pointer(C.myFun(p1.Ptr(), p2.Ptr(), unsafe.Pointer(&p3p[0]), p4))
|
||||
ret.ptr = unsafe.Pointer(C.myFun(p1.Ptr(), p2.Ptr(), (*unsafe.Pointer)(unsafe.Pointer(&p3p[0])), p4))
|
||||
(*p3) = (*p3)[:cap(*p3)]
|
||||
for i := 0; i < len(*p3); i++ {
|
||||
if p3p[i] == nil {
|
||||
@@ -365,5 +382,8 @@ func (o *Id) NSString() *NSString {
|
||||
}
|
||||
(*p3)[i].ptr = p3p[i]
|
||||
}
|
||||
if ret.ptr == nil { runtime.KeepAlive(o); return ret }
|
||||
if ret.ptr == o.ptr { runtime.KeepAlive(o); return (*Id)(unsafe.Pointer(o)) }
|
||||
runtime.KeepAlive(o)
|
||||
return ret`)
|
||||
}
|
||||
|
||||
+102
-1
@@ -37,6 +37,7 @@ func MethodSignature(s string, n *Node) (string, *Node) {
|
||||
Parenthesized(TypeName),
|
||||
Identifier,
|
||||
Opt(MethodParameterList),
|
||||
Opt(Word("NS_RETURNS_INNER_POINTER")),
|
||||
))(s, n)
|
||||
}
|
||||
|
||||
@@ -66,6 +67,16 @@ func MethodParameter(s string, n *Node) (string, *Node) {
|
||||
|
||||
func _TypeName(s string, n *Node) (string, *Node) {
|
||||
return ChildOf(NewNode("TypeName"), Seq(
|
||||
Opt(APIAvailable),
|
||||
Opt(APIUnavailable),
|
||||
Opt(SwiftUnavailable),
|
||||
Opt(APIDeprecated),
|
||||
Opt(APIDeprecatedWithReplacement),
|
||||
Opt(NSAvailable),
|
||||
Opt(NSAvailableMac),
|
||||
Opt(NSDeprecated),
|
||||
Opt(DispatchReturns),
|
||||
Opt(ReturnsInnerPointer),
|
||||
SpecifierQualifierList,
|
||||
Opt(AbstractDeclarator),
|
||||
))(s, n)
|
||||
@@ -112,11 +123,27 @@ func ArrayDeclarator(s string, n *Node) (string, *Node) {
|
||||
}
|
||||
|
||||
func FunctionDeclarator(s string, n *Node) (string, *Node) {
|
||||
return ChildOf(NewNode("Function"),
|
||||
return ChildOf(NewNode("Function"), Seq(
|
||||
Parenthesized(Opt(ParameterList)),
|
||||
ZeroOrMore(Attribute),
|
||||
))(s, n)
|
||||
}
|
||||
|
||||
func Attribute(s string, n *Node) (string, *Node) {
|
||||
return Seq(
|
||||
Word("__attribute__"),
|
||||
ChildOf(NewNode("parens"), Parenthesized(Parenthesized(
|
||||
Attr,
|
||||
))),
|
||||
)(s, n)
|
||||
}
|
||||
|
||||
func Attr(s string, n *Node) (string, *Node) {
|
||||
return NodeNamed("Attribute", OneOf(
|
||||
Word("noreturn"),
|
||||
))(s, n)
|
||||
}
|
||||
|
||||
func DirectAbstractDeclarator(s string, n *Node) (string, *Node) {
|
||||
return OneOf(
|
||||
ParenAbstractDeclarator,
|
||||
@@ -240,6 +267,80 @@ func TypeQualifier(s string, n *Node) (string, *Node) {
|
||||
))(s, n)
|
||||
}
|
||||
|
||||
func APIAvailable(s string, n *Node) (string, *Node) {
|
||||
return ChildOf(NewNode("APIAvailable"), Seq(
|
||||
Word("API_AVAILABLE"),
|
||||
Parenthesized(NodeNamed("Version",Regexp(`\w+\(\d+(\.\d+(\.\d+)?)?\)`))),
|
||||
))(s, n)
|
||||
}
|
||||
|
||||
func APIUnavailable(s string, n *Node) (string, *Node) {
|
||||
return ChildOf(NewNode("APIUnavailable"), Seq(
|
||||
Word("API_UNAVAILABLE"),
|
||||
Parenthesized(NodeNamed("Version",Regexp(`[^)]*`))),
|
||||
))(s, n)
|
||||
}
|
||||
|
||||
func APIDeprecated(s string, n *Node) (string, *Node) {
|
||||
return ChildOf(NewNode("APIDeprecated"), Seq(
|
||||
NodeNamed("APIDeprecated",Regexp(`API_DEPRECATED`)),
|
||||
Parenthesized(Seq(
|
||||
NodeNamed("Message",Regexp(`"[^"]*"`)),
|
||||
Lit(","),
|
||||
NodeNamed("Version",Regexp(`\w+\(\d+(\.\d+)?,\s*((\d+(\.\d+)?)|(API_TO_BE_DEPRECATED))\)`)),
|
||||
)),
|
||||
))(s, n)
|
||||
}
|
||||
|
||||
func APIDeprecatedWithReplacement(s string, n *Node) (string, *Node) {
|
||||
return ChildOf(NewNode("APIDeprecated"), Seq(
|
||||
NodeNamed("APIDeprecated",Regexp(`API_DEPRECATED_WITH_REPLACEMENT`)),
|
||||
Parenthesized(Seq(
|
||||
NodeNamed("Message",Regexp(`"[^"]*"`)),
|
||||
Lit(","),
|
||||
NodeNamed("Version",Regexp(`\w+\(\d+(\.\d+)?,\s*((\d+(\.\d+)?)|(API_TO_BE_DEPRECATED))\)`)),
|
||||
)),
|
||||
))(s, n)
|
||||
}
|
||||
|
||||
func SwiftUnavailable(s string, n *Node) (string, *Node) {
|
||||
return ChildOf(NewNode("SwiftUnavailable"), Seq(
|
||||
Word("NS_SWIFT_UNAVAILABLE"),
|
||||
Parenthesized(NodeNamed("Message",Regexp(`[^)]*`))),
|
||||
))(s, n)
|
||||
}
|
||||
|
||||
func NSAvailable(s string, n *Node) (string, *Node) {
|
||||
return ChildOf(NewNode("NSAvailable"), Seq(
|
||||
Word("NS_AVAILABLE"),
|
||||
Parenthesized(NodeNamed("Versions",Regexp(`\d+_\d+(,\s*\d+_\d+)?`))),
|
||||
))(s, n)
|
||||
}
|
||||
|
||||
func NSAvailableMac(s string, n *Node) (string, *Node) {
|
||||
return ChildOf(NewNode("NSAvailableMac"), Seq(
|
||||
Word("NS_AVAILABLE_MAC"),
|
||||
Parenthesized(NodeNamed("Versions",Regexp(`\d+_\d+(,\s*\d+_\d+)?`))),
|
||||
))(s, n)
|
||||
}
|
||||
|
||||
func NSDeprecated(s string, n *Node) (string, *Node) {
|
||||
return ChildOf(NewNode("NSDeprecated"), Seq(
|
||||
Word("NS_DEPRECATED"),
|
||||
Parenthesized(NodeNamed("Versions",Regexp(`\d+_\d+(,\s*\d+_\d+(,\s*\d+_\d+(,\s*\d+_\d+)?)?)?`))),
|
||||
))(s, n)
|
||||
}
|
||||
|
||||
func DispatchReturns(s string, n *Node) (string, *Node) {
|
||||
return NodeNamed("DispatchReturns",Regexp("DISPATCH_[A-Z_]+"))(s, n)
|
||||
}
|
||||
|
||||
func ReturnsInnerPointer(s string, n *Node) (string, *Node) {
|
||||
return ChildOf(NewNode("ReturnsInnerPointer"),
|
||||
Word("NS_RETURNS_INNER_POINTER"),
|
||||
)(s, n)
|
||||
}
|
||||
|
||||
func StructOrUnionSpecifier(s string, n *Node) (string, *Node) {
|
||||
return OneOf(
|
||||
// Seq(StructOrUnion,Opt(Identifier),StructDeclarationList),
|
||||
|
||||
+14
-7
@@ -9,7 +9,7 @@ var (
|
||||
)
|
||||
|
||||
func dbg(f string, xs ...interface{}) {
|
||||
if Debug && false {
|
||||
if Debug {
|
||||
fmt.Printf(f, xs...)
|
||||
}
|
||||
}
|
||||
@@ -117,13 +117,22 @@ func (n *Node) IsArray() bool {
|
||||
return n.ArrayOf() != nil
|
||||
}
|
||||
|
||||
func isQualifier(s string) bool {
|
||||
return (s == "KindQualifier" ||
|
||||
s == "APIAvailable" ||
|
||||
s == "APIUnavailable" ||
|
||||
s == "APIDeprecated" ||
|
||||
s == "SwiftUnavailable" ||
|
||||
s == "NSAvailable" ||
|
||||
s == "NSAvailableMac")
|
||||
}
|
||||
|
||||
func (n *Node) IsStruct() bool {
|
||||
if n == nil || len(n.Children) < 1 {
|
||||
return false
|
||||
}
|
||||
i := 0
|
||||
for ; i < len(n.Children) &&
|
||||
n.Children[i].Kind == "KindQualifier"; i++ {
|
||||
for ; i < len(n.Children) && isQualifier(n.Children[i].Kind); i++ {
|
||||
}
|
||||
return n.Children[i].Kind == "Struct"
|
||||
}
|
||||
@@ -152,8 +161,7 @@ func (n *Node) IsId() bool {
|
||||
return false
|
||||
}
|
||||
i := 0
|
||||
for ; i < len(n.Children) &&
|
||||
n.Children[i].Kind == "KindQualifier"; i++ {
|
||||
for ; i < len(n.Children) && isQualifier(n.Children[i].Kind); i++ {
|
||||
}
|
||||
return !n.IsFunction() &&
|
||||
n.Children[i].Kind == "TypedefName" &&
|
||||
@@ -165,8 +173,7 @@ func (n *Node) IsInstancetype() bool {
|
||||
return false
|
||||
}
|
||||
i := 0
|
||||
for ; i < len(n.Children) &&
|
||||
n.Children[i].Kind == "KindQualifier"; i++ {
|
||||
for ; i < len(n.Children) && isQualifier(n.Children[i].Kind); i++ {
|
||||
}
|
||||
return n.Children[i].Kind == "TypedefName" &&
|
||||
n.Children[i].Content == "instancetype"
|
||||
|
||||
@@ -127,6 +127,16 @@ func (n *Node) _CType(ignore map[string]bool) string {
|
||||
return ret
|
||||
}
|
||||
switch n.Kind {
|
||||
case "APIAvailable":
|
||||
case "DispatchReturns":
|
||||
case "APIUnavailable":
|
||||
case "APIDeprecated":
|
||||
case "APIDeprecatedWithReplacement":
|
||||
case "NSAvailable":
|
||||
case "NSAvailableMac":
|
||||
case "NSDeprecated":
|
||||
case "SwiftUnavailable":
|
||||
case "ReturnsInnerPointer":
|
||||
case "Parenthesized":
|
||||
ret.WriteString("(" + strings.Join(childStrings(n), " ") + ")")
|
||||
case "Function":
|
||||
|
||||
+595
-223
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user