repo_id
stringclasses 927
values | file_path
stringlengths 99
214
| content
stringlengths 2
4.15M
|
|---|---|---|
ivy
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/doc.go
|
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This is an empty package.
// We have this package to convince this is buildable and go mod tidy can work.
package dummy
|
ivy
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/go.mod
|
module golang.org/x/mobile/example/ivy
go 1.17
require (
golang.org/x/mobile v0.0.0-20210924032853-1c027f395ef7
robpike.io/ivy v0.2.7
)
require (
golang.org/x/mod v0.4.2 // indirect
golang.org/x/sys v0.0.0-20210510120138-977fb7262007 // indirect
golang.org/x/tools v0.1.2 // indirect
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
)
|
ivy
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/go.sum
|
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/exp v0.0.0-20190731235908-ec7cb31e5a56/go.mod h1:JhuoJpWY28nO4Vef9tZUw9qufEGTyX1+7lmHxV5q5G4=
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE=
golang.org/x/mobile v0.0.0-20210924032853-1c027f395ef7 h1:CyFUjc175y/mbMjxe+WdqI72jguLyjQChKCDe9mfTvg=
golang.org/x/mobile v0.0.0-20210924032853-1c027f395ef7/go.mod h1:c4YKU3ZylDmvbw+H/PSvm42vhdWbuxCzbonauEAP9B8=
golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY=
golang.org/x/mod v0.4.2 h1:Gz96sIWK3OalVv/I/qNygP42zyoKp3xptRVCWRFEBvo=
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210510120138-977fb7262007 h1:gG67DSER+11cZvqIMb8S8bt0vZtiN6xWYARwirrOSfE=
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.2 h1:kRBLX7v7Af8W7Gdbbc908OJcdgtK8bOz9Uaj8/F1ACA=
golang.org/x/tools v0.1.2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
robpike.io/ivy v0.2.7 h1:XVYgWSm7THVm1bk1jfRBB9xhso459T22gbpotHbhk7M=
robpike.io/ivy v0.2.7/go.mod h1:6B/DGaft5rvYiF7MgCTiZAAvH5W7vtu0eS2BW77updo=
|
android
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/android/README.md
|
## Ivy Big Number Calculator (Android)
[Ivy (robpike.io/ivy)](https://robpike.io/ivy) is an interpreter for an APL-like language written in Go.
This repository hosts a minimal Android project used for its [Android version](https://play.google.com/store/apps/details?id=org.golang.ivy&hl=en_US&gl=US).
### How to build
Requirements
- Go 1.17 or newer
- Android SDK
- Android NDK
- `golang.org/x/mobile/cmd/gomobile`
The `gomobile` command respects the `ANDROID_HOME` and `ANDROID_NDK_HOME` environment variables. If `gomobile` can't find your SDK and NDK, you can set these environment variables to specify their locations:
```
export ANDROID_HOME=/path/to/sdk-directory
export ANDROID_NDK_HOME=/path/to/ndk-directory
```
From this directory, run:
```sh
go install golang.org/x/mobile/cmd/gomobile@latest
go install golang.org/x/mobile/cmd/gobind@latest
# Make sure `gomobile` and `gobind` is in your `PATH`.
gomobile bind -o app/ivy.aar robpike.io/ivy/mobile
```
Open this directory from Android Studio, and build.
`robpike.io/ivy` and `golang.org/x/mobile` are required dependencies of this main module. In order to update them:
```
go get -d golang.org/x/mobile@latest
go get -d robpike.io/ivy/mobile
go mod tidy
```
|
android
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/android/build.gradle
|
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
mavenCentral()
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.0.3'
}
}
allprojects {
repositories {
mavenCentral()
google()
}
}
|
android
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/android/settings.gradle
|
include ':app'
|
app
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/android/app/proguard-rules.pro
|
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /Users/hakim/Library/Android/sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
|
app
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/android/app/build.gradle
|
apply plugin: 'com.android.application'
android {
compileSdkVersion 30
defaultConfig {
applicationId 'org.golang.ivy'
minSdkVersion 15
targetSdkVersion 30
versionCode 4
versionName '1.4.0'
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.0.0'
implementation files('ivy.aar')
}
|
main
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/android/app/src/main/AndroidManifest.xml
|
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="org.golang.ivy"
android:installLocation="auto">
<!-- undo gradle's auto addition of unrequested permissions
http://stackoverflow.com/questions/27410382/unrequested-permissions-not-declared-in-androidmanifest-crashlytics-maybe -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" tools:node="remove" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" tools:node="remove" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" tools:node="remove" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:logo="@mipmap/ic_launcher"
android:theme="@style/IvyAppTheme"
android:windowSoftInputMode="adjustResize|stateAlwaysVisible"
android:fullBackupContent="true">
<activity
android:name=".MainActivity"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:logo="@mipmap/ic_launcher"
android:windowSoftInputMode="adjustResize|stateUnchanged|stateAlwaysVisible"
android:configChanges="orientation|screenSize"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Help"
android:label="@string/title_activity_help"
android:parentActivityName=".MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="org.golang.ivy.MainActivity" />
</activity>
<activity
android:name=".AboutIvy"
android:label="@string/title_activity_about"
android:parentActivityName=".MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="org.golang.ivy.MainActivity" />
</activity>
</application>
</manifest>
|
ivy
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/android/app/src/main/java/org/golang/ivy/AboutIvy.java
|
/*
* Copyright 2015 The Go Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
package org.golang.ivy;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.appcompat.app.AppCompatActivity;
/*
* Handles About menu item.
*/
public class AboutIvy extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.activity_about,
(ViewGroup) findViewById(R.id.about_layout));
WebView webView = (WebView) layout.findViewById(R.id.about_ivy);
webView.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url != null && (url.startsWith("https://") || url.startsWith("http://"))) {
view.getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
} else {
return false;
}
}
});
webView.getSettings().setDefaultTextEncodingName("utf-8");
webView.loadUrl("file:///android_asset/aboutivy.html");
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
onBackPressed(); // back to parent.
return true;
}
}
|
ivy
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/android/app/src/main/java/org/golang/ivy/MainActivity.java
|
/*
* Copyright 2015 The Go Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
package org.golang.ivy;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ScrollView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
// This is in ivy.aar.
import mobile.Mobile;
/*
* Main activity that consists of an edit view to accept the expression
* and a web view to display output of the expression.
*/
public class MainActivity extends AppCompatActivity {
final String DEMO_SCRIPT = "demo.ivy"; // in assets directory.
final String DEBUG_TAG = "Ivy";
private WebView mWebView;
private EditText mEditText;
private ScrollView mScroller;
private BufferedReader mDemo;
private ImageButton mOKButton; // enabled only in demo mode.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mScroller = (ScrollView) findViewById(R.id.scroller);
mWebView = (WebView) findViewById(R.id.webView);
mEditText = (EditText) findViewById(R.id.editText);
mOKButton = (ImageButton) findViewById(R.id.imageButton);
mOKButton.setVisibility(View.GONE);
if (savedInstanceState != null) {
mWebView.restoreState(savedInstanceState);
} else {
clear();
}
configureWebView(mWebView);
mEditText.requestFocus();
mEditText.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
callIvy();
return true;
}
return false;
}
});
mOKButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
callIvy();
}
});
/* For webview debugging - visit chrome://inspect/#devices */
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (0 != (getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE))
{ WebView.setWebContentsDebuggingEnabled(true); }
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
mWebView.saveState(outState);
super.onSaveInstanceState(outState);
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mWebView.restoreState(savedInstanceState);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
private long mLastPress = 0;
@Override
public void onBackPressed() {
// TODO: store and restore the state across app restarts.
long currentTime = System.currentTimeMillis();
if(currentTime - mLastPress > 6000){
Toast.makeText(getBaseContext(), "Press back again to exit.\nAll app state will be lost upon exit.", Toast.LENGTH_LONG).show();
mLastPress = currentTime;
}else{
super.onBackPressed();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_about:
startActivity(new Intent(this, AboutIvy.class));
return true;
case R.id.action_help:
startActivity(new Intent(this, Help.class));
return true;
case R.id.action_clear:
clear();
return true;
case R.id.action_demo:
loadDemo();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void clear() {
// As described in https://code.google.com/p/android/issues/detail?id=18726
// clearing the contents of the webview doesn't shrink the webview size in some
// old versions of Android. (e.g. Moto X running 4.4.4). I tried various techniques
// suggested in the Internet, but nothing worked except creating a new webview.
WebView newView = new WebView(this);
newView.setLayoutParams(mWebView.getLayoutParams());
newView.setId(R.id.webView);
configureWebView(newView);
mScroller.removeView(mWebView);
mWebView.destroy();
mWebView = newView;
mWebView.loadUrl("file:///android_asset/tape.html");
mWebView.setBackgroundColor(getResources().getColor(R.color.body));
mScroller.addView(mWebView);
mEditText.setText("");
Mobile.reset();
unloadDemo();
}
void configureWebView(WebView webView) {
// We enable javascript, but disallow any url loading.
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
// Disallow arbitrary contents loaded into our own webview.
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
}
});
webView.setFocusable(false);
webView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom,
int oldLeft, int oldTop, int oldRight, int oldBottom) {
// It's possible that the layout is not complete.
// In that case we will get all zero values for the positions. Ignore this case.
if (left == 0 && top == 0 && right == 0 && bottom == 0) {
return;
}
scrollToBottom();
}
});
}
private String escapeHtmlTags(final String s) {
// Leaves entities (&-prefixed) alone unlike TextUtils.htmlEncode
// (https://github.com/aosp-mirror/platform_frameworks_base/blob/d59921149bb5948ffbcb9a9e832e9ac1538e05a0/core/java/android/text/TextUtils.java#L1361).
// Ivy mobile.Eval result may include encoding starting with &.
StringBuilder sb = new StringBuilder();
char c;
for (int i = 0; i < s.length(); i++) {
c = s.charAt(i);
switch (c) {
case '<':
sb.append("<"); //$NON-NLS-1$
break;
case '>':
sb.append(">"); //$NON-NLS-1$
break;
case '"':
sb.append("""); //$NON-NLS-1$
break;
case '\'':
//http://www.w3.org/TR/xhtml1
// The named character reference ' (the apostrophe, U+0027) was introduced in
// XML 1.0 but does not appear in HTML. Authors should therefore use ' instead
// of ' to work as expected in HTML 4 user agents.
sb.append("'"); //$NON-NLS-1$
break;
default:
sb.append(c);
}
}
return sb.toString();
}
private void appendShowText(final String s, final String tag) {
mWebView.loadUrl("javascript:appendDiv('" + TextUtils.htmlEncode(s).replaceAll("(\r\n|\n)", "<br />") + "', '" + tag + "')");
mWebView.setBackgroundColor(getResources().getColor(R.color.body));
}
private void appendShowPreformattedText(final String s, final String tag) {
mWebView.loadUrl("javascript:appendDiv('" + escapeHtmlTags(s).replaceAll("\r?\n", "<br/>") + "', '" + tag + "')");
mWebView.setBackgroundColor(getResources().getColor(R.color.body));
}
private void callIvy() {
String s = mEditText.getText().toString().trim();
if (s != null && !s.isEmpty()) {
appendShowText(s, "expr");
}
if (mDemo != null && s.trim().equals("quit")) {
unloadDemo();
s = " "; // this will clear the text box.
}
new IvyCallTask().execute(s); // where call to Ivy backend occurs.
}
private synchronized void loadDemo() {
try {
if (mDemo == null) {
mDemo = new BufferedReader(new InputStreamReader(getAssets().open(DEMO_SCRIPT), "UTF-8"));
}
mOKButton.setVisibility(View.VISIBLE);
new IvyCallTask().execute("");
} catch (IOException e) {
Toast.makeText(this, "Failed to load Demo script.\nContact the app author.", Toast.LENGTH_SHORT);
}
}
private synchronized void unloadDemo() {
if (mDemo == null) { return; }
try {
mDemo.close();
} catch (IOException e) {
Log.d(DEBUG_TAG, e.toString());
}
mDemo = null;
mOKButton.setVisibility(View.GONE);
}
private synchronized String readDemo() {
if (mDemo == null) { return null; }
try {
return mDemo.readLine();
} catch (IOException e) {
unloadDemo();
}
return null;
}
private void scrollToBottom() {
mScroller.post(new Runnable() {
public void run() {
mScroller.smoothScrollTo(0, mWebView.getBottom());
}
});
}
// AsyncTask that evaluates the expression (string), and returns the strings
// to display in the web view and the edit view respectively.
private class IvyCallTask extends AsyncTask<String, Void, Pair<String, String> > {
private String ivyEval(final String expr) {
try {
// mobile.Mobile was generated using
// gomobile bind -javapkg=org.golang.ivy robpike.io/ivy/mobile
return Mobile.eval(expr); // Gobind-generated method.
} catch (Exception e) {
return "error: "+e.getMessage();
}
}
// doInBackground checks the demo script (if the passed-in param is empty),
// or returns the ivy evaluation result.
@Override
protected Pair<String, String> doInBackground(String ...param) {
final String expr = param[0];
// TODO: cancel, timeout
if (expr == null || expr.isEmpty()) {
return checkDemo();
}
return Pair.create(ivyEval(expr), "");
}
// checkDemo reads the demo script and returns the comment, and the next expression.
protected Pair<String, String> checkDemo() {
String showText = null;
while (true) {
String s = readDemo();
if (s == null) {
break;
}
if (s.startsWith("# ")) {
return Pair.create(s, null);
}
return Pair.create(null, s);
}
return null;
}
@Override
protected void onPostExecute(final Pair<String, String> result) {
if (result == null || (result.first == null && result.second == null)) {
return;
}
runOnUiThread(new Runnable() {
@Override
public void run() {
String showText = result.first;
if (showText != null) {
final String tag = (showText.startsWith("#")) ? "comment" : "result";
appendShowPreformattedText(showText, tag);
}
String editText = result.second;
if (editText != null) {
mEditText.setText(editText);
}
}
});
}
}
}
|
ivy
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/android/app/src/main/java/org/golang/ivy/Help.java
|
/**
* Copyright 2015 The Go Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
package org.golang.ivy;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.MenuItem;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.appcompat.app.AppCompatActivity;
import mobile.Mobile;
/*
* Displays the help message for Ivy.
*/
public class Help extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_help);
WebView webView = (WebView) findViewById(R.id.help_webview);
webView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// we are not a browser; redirect the request to proper apps.
if (url != null) {
view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
}
return true;
}
});
webView.getSettings().setDefaultTextEncodingName("utf-8");
// mobile.Mobile was generated using gomobile bind robpike.io/ivy/mobile.
String helpMsg = Mobile.help();
// loadData has a rendering bug: https://code.google.com/p/android/issues/detail?id=6965
webView.loadDataWithBaseURL("http://pkg.go.dev/robpike.io/ivy", helpMsg, "text/html", "UTF-8", null);
webView.setBackgroundColor(getResources().getColor(R.color.body));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
onBackPressed(); // back to parent.
return true;
}
}
|
assets
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/android/app/src/main/assets/tape.html
|
<!--
Copyright 2015 The Go Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
-->
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" charset="UTF-8">
<style>
body {
font-family: sans-serif;
}
div {
padding: 1;
white-space: pre-wrap;
font-family: "Roboto Mono", monospace;
}
.comment {
color: grey;
}
.expr {
font-weight: bold;
}
.flow-hide {
text-overflow: ellipsis;
word-break: break-all;
white-space: nowrap;
overflow: hidden;
}
.flow-show {
word-break: break-all;
}
</style>
<script>
function flowClick(el) {
el.classList.toggle("flow-hide");
el.classList.toggle("flow-show");
}
function appendDiv(txt, tag) {
var el = document.createElement("div");
el.innerHTML = txt;
if (tag == "comment") {
el.classList.add("comment");
} else if (tag == "expr") {
el.classList.add("expr");
} else {
el.classList.add("flow-show");
el.onclick = function() {
flowClick(el);
};
}
document.body.appendChild(el);
}
</script>
<body>
</body>
</html>
|
assets
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/android/app/src/main/assets/aboutivy.html
|
<!--
Copyright 2015 The Go Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
-->
<html>
<body>
<center>
<h2>Ivy</h2><p>
Based on <a href='https://robpike.io/ivy'>robpike.io/ivy</a>
<p>
Copyright 2015 The <a href='https://golang.org/LICENSE'>Go Authors</a>.
<br>
The Ivy mascot is designed by
<a href='https://reneefrench.blogspot.com/'>Renee French</a>
and licensed under the
<a href='https://creativecommons.org/licenses/by/3.0/us/'>Creative Commons Attribution 3.0 license</a>.
</center>
</body>
</html>
|
assets
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/android/app/src/main/assets/demo.ivy
|
# This is a demo of ivy. Type a newline to advance to each new step. Type one now.
# At any time, type the word "quit" or EOF to end the demo and return to ivy.
# Each step in the demo is one line of input followed by some output from ivy. Type a newline now to see.
2+2
# The first line you see above (2+2) is input; the next (4) is output from a running ivy.
# Comments start with # and produce no output.
# Whenever you like, you can type an expression yourself. Try typing 2*3 now, followed by two newlines:
# Keep typing newlines; the ivy demo is about to start.
# Arithmetic has the obvious operations: + - * etc. ** is exponentiation. mod is modulo.
23
23 + 45
23 * 45
23 - 45
7 ** 3
7 mod 3
# Operator precedence is unusual.
# Unary operators operate on everything to the right.
# Binary operators operate on the item immediately to the left, and everything to the right.
2*3+4 # Parsed as 2*(3+4), not the usual (2*3)+4.
2**2+3 # 2**5, not (2**2) + 3
(2**2)+3 # Use parentheses if you need to group differently.
# Ivy can do rational arithmetic, so 1/3 is really 1/3, not 0.333....
1/3
1/3 + 4/5
1/3 ** 2 # We'll see non-integral exponents later.
# Even when a number is input in floating notation, it is still an exact rational number inside.
1.2
# In fact, ivy is a "bignum" calculator that can handle huge numbers and rationals made of huge numbers.
1e10 # Still an integer.
1e100 # Still an integer.
1e10/3 # Not an integer, but an exact rational.
3/1e10 # Not an integer, but an exact rational.
2**64 # They can get big.
2**640 # They can get really big.
# They can get really really big. Type a newline to see 2**6400 scroll by.
2**6400
# Ivy also has characters, which represent a Unicode code point.
'x'
char 0x61 # char is an operator: character with given value.
char 0x1f4a9
code '💩' # char's inverse, the value of given character, here printed in decimal.
# Everything in ivy can be placed into a vector.
# Vectors are written and displayed with spaces between the elements.
1 2 3
1 4/3 5/3 (2+1/3)
# Note that without the parens this becomes (1 4/3 5/3 2)+1/3
1 4/3 5/3 2+1/3
# Vectors of characters print without quotes or spaces.
'h' 'e' 'l' 'l' 'o'
# This is a nicer way to write 'h' 'e' 'l' 'l' 'o'. It means the same.
'hello'
# Arithmetic works elementwise on vectors.
1 2 3 + 4 5 6
# Arithmetic between scalar and vector also works, either way.
23 + 1 2 3
1 2 3 + 23 # Note the grouping: vector is a single value.
# More fun with scalar and vector.
1 << 1 2 3 4 5
(1 << 1 2 3 4 5) == (2 ** 1 2 3 4 5) # Note: true is 1, false is 0.
# iota is an "index generator": It counts from 1.
iota 10
2 ** iota 5
(1 << iota 100) == 2 ** iota 100
2 ** -1 + iota 32 # Again, see how the precedence rules work.
# The take operator removes n items from the beginning of the vector.
3 take iota 10
-3 take iota 10 # Negative n takes from the end.
# Drop is the other half: it drops n from the vector.
3 drop iota 10
-3 drop iota 10 # Negative n drops from the end.
6 drop 'hello world'
# Reduction
iota 15
# Add them up:
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15
# Automate this by reducing + over the vector, like this:
+/iota 15
# We can reduce using any binary operator. This is factorial:
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10
*/iota 10
*/iota 100
# Type this: */iota 10000
# That printed using floating-point notation for manageability but it is still an integer inside.
# max and min are binary operators that do the obvious. (Use semicolons to separate expressions.)
3 max 7; 'is max and'; 3 min 7; 'is min'
# Like all binary arithmetic operators, max applies elementwise.
2 3 4 max 4 3 2
# Reduce using max to find maximum element in vector.
max/2 34 42 233 2 2 521 14 1 4 1 55 133
# Ivy allows multidimensional arrays. The binary shape operator, rho, builds them.
# Dimension (which may be a vector) on the left, data on the right.
5 rho 1
5 5 rho 1
5 5 rho 25
5 5 rho iota 25
3 5 5 rho iota 125
# Unary rho tells us the shape of an item.
x = 3 5 rho iota 15; x
rho x
x = 3 5 5 rho iota 75; x
rho x
# Arithmetic on matrices works as you would expect by now.
x/2
x**2
x**3
x**10
# Inner product is written with a . between the operators.
# This gives dot product: multiply corresponding elements and add the result.
1 2 3 4 +.* 2 3 4 5
# Any operator works. How many items are the same?
(1 2 3) +.== (1 3 3)
# How many differ?
(1 2 3) +.!= (1 3 3)
# Outer product generates a matrix of all combinations applying the binary operator.
(iota 5) o.* -1 + iota 5
# That's a letter 'o', dot, star.
# Any operator works; here is how to make an identity matrix.
x = iota 5; x o.== x
# Assignment is an operator, so you can save an intermediate expression.
x o.== x = iota 5
# Random numbers: Use a unary ? to roll an n-sided die from 1 to n.
?100
?100
?20 rho 6 # 20 rolls of a 6-sided die.
x = ?20 rho 6 # Remember one set of rolls.
x
# Indexing is easy.
x[1]
x[1 19 3] # You can index with a vector.
# The up and down operators generate index vectors that would sort the input.
up x
x[up x]
x[down x]
'hello world'[up 'hello world']
'hello world'[down 'hello world']
# More rolls of a die.
?10 rho 6
# Remember a set of rolls.
x = ?10 rho 6; x
# The outer product of == and the integers puts 1 in each row where that value appeared.
# Compare the last row of the next result to the 6s in x.
(iota 6) o.== x
# Count the number of times each value appears by reducing the matrix horizontally.
+/(iota 6) o.== x
# Do it for a much larger set of rolls: is the die fair?
+/(iota 6) o.== ?60000 rho 6
# Remember that ivy is a big number calculator.
*/iota 100
2**64
2**iota 64
-1+2**63
# Settings are made and queried with a leading right paren. )help helps with settings and other commands.
)help
# Use )base to switch input and output to base 16.
)base 16
)base # The input and output for settings is always base 10.
# _ is a variable that holds the most recently evaluated expression. It remembers our 63-bit number.
_
1<<iota 10 # 16 powers of two, base 16.
(2**40)-1 # The largest 64-bit number base 16.
)obase 10 # Output base 10, input base still 16.
)base
# The largest 63-bit number base 10.
-1+2**40 # The largest 64-bit number base 10.
-1+2**3F # The largest 63-bit number base 10.
# Go back to base 10 input and output.
)base 10
# Rationals can be very big too.
(2**1e3)/(3**1e2)
# Such output can be unwieldy. Change the output format using a Printf string.
)format '%.12g'
_
# We need more precision.
)format "%.100g" # Double quotes work too; there's no difference.
_
)format '%#x'
_
)format '%.12g' # A nice format, easily available by running ivy -g.
_
(3 4 rho iota 12)/4
# Irrational functions cannot be represented precisely by rational numbers.
# Ivy stores irrational results in high-precision (default 256-bit) floating point numbers.
sqrt 2
# pi and e are built-in, high-precision constants.
pi
e
)format "%.100g"
pi
)format '%.12g'
pi
# Exponentials and logarithms.
2**1/2 # Note: Non-integral exponent generates irrational result.
e**1e6
log e**1e6
log e**1e8
log 1e1000000 # Yes, that is 10 to the millionth power.
# Transcendentals. (The low bit isn't always right...)
sin pi/2
cos .25*pi * -1 + iota 9
log iota 6
# Successive approximations to e. (We force the calculation to use float using the "float" unary operator. Why?)
(float 1+10**-iota 9) ** 10**iota 9
# Default precision is 256 bits of mantissa. We can go up to 10000.
)prec 3350 # Units are bits, not digits. 2 log 10 == 3.321. Add a few more bits for floating point errors.
e
)format '%.1000g' # Units are digits. (Sorry for the inconsistency.)
e
pi
sqrt 2
e**1e6
log e**1e6
(2**1e3)/(3**1e2)
# User-defined operators are declared as unary or binary (or both). This one computes the (unary) average.
op avg x = (+/x)/rho x
avg iota 100
# Here is a binary operator.
op n largest x = n take x[down x]
3 largest ? 100 rho 1000
4 largest 'hello world'
# Population count. Use encode to turn the value into a string of bits. Use log to decide how many.
op a base b = ((ceil b log a) rho b) encode a
7 base 2
op popcount n = +/n base 2
popcount 7
popcount 1e6
popcount 1e100
# Here is one to sum the digits. The unary operator text turns its argument into text, like sprintf.
op sumdigits x = t = text x; +/(code (t in '0123456789') sel t) - code '0'
# Break it down: The sel operator selects from the right based on the non-zero elements in the left.
# The in operator generates a selector by choosing only the bytes that are ASCII digits.
sumdigits 99
sumdigits iota 10
sumdigits '23 skidoo' # Note: It counts only the digits.
# The binary text operator takes a format string (% optional) on the left and formats the value.
'%x' text 1234
# We can use this for another version of popcount: %b is binary.
op popcount n = +/'1' == '%b' text n
popcount 7
popcount 1e6
popcount 1e100
# A classic (expensive!) algorithm to count primes.
op primes N = (not T in T o.* T) sel T = 1 drop iota N
# The assignment to T gives 2..N. We use outer product to build an array of all products.
# Then we find all elements of T that appear in the product matrix, invert that, and select from the original.
primes 100
# A final trick.
# The binary ? operator "deals": x?y selects at random x distinct integers from 1..y inclusive.
5?10
# We can use this to shuffle a deck of cards. The suits are ♠♡♣♢, the values
# A234567890JQK (using 0 for 10, for simplicity).
# Create the deck using outer product with the ravel operator:
"A234567890JQK" o., "♠♡♣♢"
# To shuffle it, ravel into into a vector and index that by 1 through 52, shuffled.
(, "A234567890JQK" o., "♠♡♣♢")[52?52]
# There is no looping construct in ivy, but there is a conditional evaluator.
# Within a user-defined operator, one can write a condition expression
# using a binary operator, ":". If the left-hand operand is true (integer non-zero),
# the user-defined operator will return the right-hand operand as its
# result; otherwise execution continues.
op a gcd b = a == b: a; a > b: b gcd a-b; a gcd b-a
1562 gcd !11
# That's it! Have fun.
# For more information visit https://pkg.go.dev/robpike.io/ivy
|
values
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/android/app/src/main/res/values/strings.xml
|
<resources>
<string name="app_name">Ivy</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="action_help">Help</string>
<string name="action_about">About</string>
<string name="action_clear">Clear</string>
<string name="action_demo">Demo</string>
<string name="about_details">by Go Authors</string>
<string name="title_activity_about">About Ivy</string>
<string name="title_activity_help">Help</string>
<string name="ivy_sketch">ivy_sketch</string>
<string name="editTextHelp">type an expression</string>
<string name="ivysketch_desc">ivy sketch</string>
<string name="ok">OK</string>
<string-array name="expression_array">
<item>ceil</item>
<item>floor</item>
<item>rho</item>
<item>abs</item>
<item>iota</item>
<item>sgn</item>
<item>rev</item>
<item>flip</item>
<item>up</item>
<item>down</item>
<item>div</item>
<item>idiv</item>
<item>max</item>
<item>min</item>
<item>rho</item>
<item>take</item>
<item>drop</item>
<item>mod</item>
<item>imod</item>
<item>or</item>
<item>and</item>
<item>nor</item>
<item>nand</item>
<item>xor</item>
<item>def</item>
<item>) format</item>
<item>) op</item>
<item>) base</item>
<item>) origin</item>
</string-array>
</resources>
|
values
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/android/app/src/main/res/values/dimens.xml
|
<resources>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
</resources>
|
values
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/android/app/src/main/res/values/colors.xml
|
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="body">#ffffeb</color>
<color name="sky">#e2f6ff</color>
<color name="blue">#1997d4</color>
<color name="white">#f9f9f9</color>
<color name="black">#000000</color>
</resources>
|
values
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/android/app/src/main/res/values/styles.xml
|
<resources>
<style name="IvyAppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorControlActivated">@color/sky</item>
<item name="colorPrimary">@color/blue</item>
<item name="colorPrimaryDark">@color/blue</item>
<item name="actionBarStyle">@style/MyActionBarLogo</item>
</style>
<style name="MyActionBarLogo" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="background">@color/blue</item>
<item name="logo">@mipmap/ic_launcher</item>
<item name="displayOptions">useLogo|showHome</item>
</style>
</resources>
|
drawable
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/android/app/src/main/res/drawable/circle_shape.xml
|
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false">
<shape android:shape="oval">
<solid android:color="@color/blue"/>
</shape>
</item>
<item android:state_pressed="true">
<shape android:shape="oval">
<solid android:color="@color/button_material_dark"/>
</shape>
</item>
</selector>
|
values-w820dp
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/android/app/src/main/res/values-w820dp/strings.xml
|
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="ok">OK</string>
</resources>
|
values-w820dp
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/android/app/src/main/res/values-w820dp/dimens.xml
|
<resources>
<!-- Example customization of dimensions originally defined in res/values/dimens.xml
(such as screen margins) for screens with more than 820dp of available width. This
would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). -->
<dimen name="activity_horizontal_margin">64dp</dimen>
</resources>
|
menu
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/android/app/src/main/res/menu/menu_about.xml
|
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="org.golang.ivy.About">
<item
android:id="@+id/action_settings"
android:title="@string/action_settings"
android:orderInCategory="100"
app:showAsAction="never" />
</menu>
|
menu
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/android/app/src/main/res/menu/menu_main.xml
|
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ivyapp="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_clear"
android:title="@string/action_clear"
ivyapp:showAsAction="always" />
<item
android:id="@+id/action_demo"
android:title="@string/action_demo"
ivyapp:showAsAction="collapseActionView" />
<item
android:id="@+id/action_help"
android:title="@string/action_help"
ivyapp:showAsAction="collapseActionView" />
<item
android:id="@+id/action_about"
android:title="@string/action_about"
ivyapp:showAsAction="collapseActionView" />
</menu>
|
layout
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/android/app/src/main/res/layout/activity_help.xml
|
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="match_parent"
tools:context="org.golang.ivy.Help"
android:background="@color/body">
<WebView
android:id="@+id/help_webview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/body" />
</RelativeLayout>
|
layout
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/android/app/src/main/res/layout/activity_main.xml
|
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:id="@+id/layout"
android:background="@color/body">
<ScrollView
android:id="@+id/scroller"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="vertical"
android:fillViewport="false"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_above="@+id/layout_bottom"
android:padding="@dimen/abc_control_padding_material">
<WebView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/webView"
android:gravity="left|bottom"
android:textIsSelectable="true"
android:clickable="false"
android:background="@color/body" />
</ScrollView>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:id="@+id/layout_bottom"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true">
<EditText
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="@+id/editText"
android:gravity="top|left|start"
android:textStyle="normal"
android:inputType="textVisiblePassword"
android:hint="@string/editTextHelp"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:background="@drawable/circle_shape"
android:src="@drawable/ic_done_white_24dp"
android:contentDescription="@string/ok"
android:onClick="onClick"
android:clickable="true"
android:padding="@dimen/abc_control_padding_material"
android:layout_margin="@dimen/abc_control_padding_material" />
</LinearLayout>
</RelativeLayout>
|
layout
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/android/app/src/main/res/layout/activity_about.xml
|
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/about_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#EEFFFFFF"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp"
android:weightSum="1"
tools:context="org.golang.ivy.About">
<ImageView
android:id="@+id/ivysketch"
android:src="@drawable/ivyabout"
android:layout_gravity="center_horizontal"
android:layout_width="256dp"
android:layout_height="256dp"
android:contentDescription="@string/ivysketch_desc" />
<WebView
android:id="@+id/about_ivy"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="@string/app_name"
android:textSize="@dimen/abc_text_size_headline_material" />
</LinearLayout>
|
ivy
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/android/app/src/androidTest/java/org/golang/ivy/ApplicationTest.java
|
package org.golang.ivy;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
}
|
ios
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/ios/README.md
|
# Ivy iOS App source
This directory contains the source code to the Ivy iOS app.
To build, first create the Mobile.xcframework out of the Go
implementation of Ivy. Run:
```
go install golang.org/x/mobile/cmd/gomobile@latest
go install golang.org/x/mobile/cmd/gobind@latest
```
to install `gomobile` and `gobind`. Then:
```
mkdir work; cd work
go mod init work
go get -d golang.org/x/mobile/bind@latest
go get -d robpike.io/ivy/mobile
gomobile bind -target=ios,iossimulator,maccatalyst,macos robpike.io/ivy/mobile robpike.io/ivy/demo
```
Place the Mobile.xcframework directory in this directory, and
then open ivy.xcodeproj in Xcode.
You have to specify Development Team for code signing certificate in:
Project Settings -> Targets -> Signing & Capabilities -> Signing -> Team.
|
ivy
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/ios/ivy/DocsController.m
|
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#import "DocsController.h"
#import "mobile/Mobile.h"
@interface DocsController () {
WKWebView *webView;
}
@end
@implementation DocsController
- (void)viewDidLoad {
[super viewDidLoad];
webView = (WKWebView *)[self.view viewWithTag:11];
NSString *helpHTML = MobileHelp();
NSRange r = [helpHTML rangeOfString:@"<head>"];
NSString *html = [helpHTML substringToIndex:r.location];
// With the following meta tag, WKWebView displays the fonts more nicely.
NSString *meta = @"<meta name='viewport' \
content='width=device-width, "
@"initial-scale=1.0, maximum-scale=1.0, \
minimum-scale=1.0, "
@"user-scalable=no'>";
html = [html stringByAppendingString:@"<head>"];
html = [html stringByAppendingString:meta];
html = [html stringByAppendingString:[helpHTML substringFromIndex:r.location]];
[webView loadHTMLString:html baseURL:NULL];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end
|
ivy
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/ios/ivy/tape.html
|
<!--
Copyright 2015 The Go Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
-->
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" charset="UTF-8">
<style>
body {
font-family: sans-serif;
}
div {
padding: 1;
white-space: pre-wrap;
font-family: "Roboto Mono", monospace;
}
.comment {
color: grey;
}
.expr {
font-weight: bold;
}
.flow-hide {
text-overflow: ellipsis;
word-break: break-all;
white-space: nowrap;
overflow: hidden;
}
.flow-show {
word-break: break-all;
}
</style>
<script>
function flowClick(el) {
el.classList.toggle("flow-hide");
el.classList.toggle("flow-show");
}
function appendDiv(txt, tag) {
var el = document.createElement("div");
el.innerHTML = txt;
if (tag == "comment") {
el.classList.add("comment");
} else if (tag == "expr") {
el.classList.add("expr");
} else {
el.classList.add("flow-show");
el.onclick = function() {
flowClick(el);
};
}
document.body.appendChild(el);
}
</script>
<body>
</body>
</html>
|
ivy
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/ios/ivy/AppDelegate.m
|
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#import "AppDelegate.h"
#import "IvyController.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
}
- (void)applicationWillTerminate:(UIApplication *)application {
}
@end
|
ivy
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/ios/ivy/Suggestion.h
|
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#import <UIKit/UIKit.h>
@protocol SuggestionDelegate <NSObject>
@required
- (void)suggestionReplace:(NSString *)text;
@end
@interface Suggestion : UIInputView
- (instancetype)init;
- (instancetype)initWithFrame:(CGRect)frame;
- (void)suggestFor:(NSString *)text;
@property(weak) id<SuggestionDelegate> delegate;
@end
|
ivy
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/ios/ivy/IvyController.m
|
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#import "IvyController.h"
#import "mobile/Mobile.h"
@interface IvyController ()
@end
@implementation IvyController {
NSArray *demo_lines;
int demo_index;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.input.delegate = self;
self.input.autocorrectionType = UITextAutocorrectionTypeNo;
self.input.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
self.suggestionView = [[Suggestion alloc] init];
self.suggestionView.delegate = self;
self.tape.UIDelegate = self;
self->demo_lines = NULL;
[self.okButton setTitle:@"" forState:UIControlStateNormal];
[self.okButton setHidden:TRUE];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(textDidChange:)
name:UITextFieldTextDidChangeNotification
object:self.input];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
[self.input becomeFirstResponder];
[self clear:NULL];
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
if ([textField isEqual:self.input]) {
textField.inputAccessoryView = self.suggestionView;
textField.autocorrectionType = UITextAutocorrectionTypeNo;
[textField reloadInputViews];
}
return YES;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
if ([textField isEqual:self.input]) {
textField.inputAccessoryView = nil;
[textField reloadInputViews];
}
return YES;
}
- (void)textDidChange:(NSNotification *)notif {
[self.suggestionView suggestFor:self.input.text];
}
- (void)suggestionReplace:(NSString *)text {
self.input.text = text;
[self.suggestionView suggestFor:text];
}
- (void)keyboardWillShow:(NSNotification *)aNotification {
// Move the input text field up, as the keyboard has taken some of the screen.
NSDictionary *info = [aNotification userInfo];
CGRect kbFrame = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
NSNumber *duration = [info objectForKey:UIKeyboardAnimationDurationUserInfoKey];
UIViewAnimationCurve keyboardTransitionAnimationCurve;
[[info valueForKey:UIKeyboardAnimationCurveUserInfoKey]
getValue:&keyboardTransitionAnimationCurve];
UIViewAnimationOptions options =
keyboardTransitionAnimationCurve | keyboardTransitionAnimationCurve << 16;
[UIView animateWithDuration:duration.floatValue
delay:0
options:options
animations:^{
self.bottomConstraint.constant = 0 - kbFrame.size.height;
[self.view layoutIfNeeded];
}
completion:^(BOOL finished) {
[self scrollTapeToBottom];
}];
}
- (void)keyboardWillHide:(NSNotification *)aNotification {
// Move the input text field back down.
NSDictionary *info = [aNotification userInfo];
NSNumber *duration = [info objectForKey:UIKeyboardAnimationDurationUserInfoKey];
UIViewAnimationCurve keyboardTransitionAnimationCurve;
[[info valueForKey:UIKeyboardAnimationCurveUserInfoKey]
getValue:&keyboardTransitionAnimationCurve];
UIViewAnimationOptions options =
keyboardTransitionAnimationCurve | keyboardTransitionAnimationCurve << 16;
int offset = self.input.inputAccessoryView != NULL ? self.suggestionView.frame.size.height : 0;
[UIView animateWithDuration:duration.floatValue
delay:0
options:options
animations:^{
self.bottomConstraint.constant = 0 - offset;
[self.view layoutIfNeeded];
}
completion:^(BOOL finished) {
[self scrollTapeToBottom];
}];
}
- (void)enterPressed {
NSString *text = self.input.text;
if ([text isEqual:@""]) {
if (self->demo_lines == NULL) {
return;
}
while (demo_index < self->demo_lines.count) {
NSString *line = self->demo_lines[self->demo_index++];
if ([line hasPrefix:@"#"]) {
[self appendTape:line tag:@"comment"];
} else {
self.input.text = line;
break;
}
}
} else if (self->demo_lines != NULL && [text isEqual:@"quit"]) {
[self unloadDemo];
} else {
[self appendTape:text tag:@"expr"];
NSString *expr = [text stringByAppendingString:@"\n"];
NSError *err;
NSString *result = MobileEval(expr, &err);
if (err != nil) {
result = err.description;
}
result = [result stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
result = [result stringByReplacingOccurrencesOfString:@"<" withString:@"<"];
result = [result stringByReplacingOccurrencesOfString:@">" withString:@">"];
NSMutableArray *lines = (NSMutableArray *)[result componentsSeparatedByString:@"\n"];
for (NSMutableString *line in lines) {
if ([line hasPrefix:@"#"])
[self appendTape:line tag:@"comment"];
else
[self appendTape:line tag:@"result"];
}
self.input.text = @"";
}
[self.input becomeFirstResponder];
}
- (void)scrollTapeToBottom {
NSString *scroll = @"window.scrollBy(0, document.body.offsetHeight);";
[self.tape evaluateJavaScript:scroll completionHandler:nil];
}
- (void)appendTape:(NSString *)text tag:(NSString *)tag {
NSString *injectSrc = @"appendDiv('%@','%@');";
NSString *runToInject = [NSString stringWithFormat:injectSrc, text, tag];
[self.tape evaluateJavaScript:runToInject completionHandler:nil];
[self scrollTapeToBottom];
}
- (void)loadDemo {
[self.okButton setHidden:FALSE];
NSString *text = DemoText();
self->demo_lines =
[text componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
self->demo_index = 0;
self.input.text = @"";
self.input.enablesReturnKeyAutomatically = TRUE;
[self enterPressed];
}
- (void)unloadDemo {
[self.okButton setHidden:TRUE];
self.input.enablesReturnKeyAutomatically = FALSE;
self->demo_lines = NULL;
self.input.text = @"";
}
- (IBAction)okPressed:(id)sender {
[self enterPressed];
}
- (IBAction)demo:(id)sender {
if (self->demo_lines) { // demo already running
[self enterPressed];
} else {
[self loadDemo];
}
}
- (IBAction)clear:(id)sender {
[self unloadDemo];
NSString *string = [NSString
stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"tape" ofType:@"html"]
encoding:NSUTF8StringEncoding
error:NULL];
[self.tape loadHTMLString:string baseURL:NULL];
}
@end
|
ivy
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/ios/ivy/IvyController.h
|
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#import <UIKit/UIKit.h>
#import <WebKit/WebKit.h>
#import "Suggestion.h"
// IvyController displays the main app view.
@interface IvyController : UIViewController <UITextFieldDelegate, WKUIDelegate, SuggestionDelegate>
@property(weak, nonatomic) IBOutlet NSLayoutConstraint *bottomConstraint;
// A text input field coupled to an output "tape", rendered with a WKWebView.
@property(weak, nonatomic) IBOutlet UITextField *input;
@property(strong, nonatomic) Suggestion *suggestionView;
@property(weak, nonatomic) IBOutlet WKWebView *tape;
@property(weak, nonatomic) IBOutlet UIButton *okButton;
- (IBAction)clear:(id)sender;
- (IBAction)demo:(id)sender;
- (IBAction)okPressed:(id)sender;
@end
|
ivy
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/ios/ivy/DocsController.h
|
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#import <WebKit/WebKit.h>
// DocsController displays the documentation page.
@interface DocsController : UIViewController
@end
|
ivy
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/ios/ivy/Suggestion.m
|
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#import "Suggestion.h"
#define maxSuggestions 4 + 3
@implementation Suggestion {
NSString *text;
NSRange range;
NSMutableOrderedSet *options;
NSMutableArray *buttons;
NSArray *possibleSuggestions;
NSCharacterSet *breakingChars;
}
- (instancetype)init {
CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
self = [self initWithFrame:CGRectMake(0.0f, 0.0f, screenWidth, 36.0f)];
return self;
}
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame inputViewStyle:UIInputViewStyleKeyboard];
if (self) {
possibleSuggestions = @[
@")base ", @")debug ", @")format ", @")maxdigits ", @")op ", @")origin ", @")prec ",
@")prompt ", @")seed ", @"cos ", @"iota ", @"log ", @"max ", @"min ", @"pi ", @"rho ",
@"sin ", @"sqrt ", @"tan "
];
breakingChars = [NSCharacterSet characterSetWithCharactersInString:@"/+-*,^|= "];
options = [[NSMutableOrderedSet alloc] initWithCapacity:maxSuggestions];
buttons = [[NSMutableArray alloc] init];
self.backgroundColor = [UIColor colorWithWhite:0.0f alpha:0.05f];
[self setSuggestions:nil];
}
return self;
}
- (void)suggestFor:(NSString *)t {
text = t;
range = [text rangeOfCharacterFromSet:breakingChars options:NSBackwardsSearch];
if (range.location == NSNotFound) {
range.location = 0;
range.length = text.length;
} else {
if (range.location > 0 && [text characterAtIndex:range.location - 1] == ')') {
// Special case for suggestions that start with ") ".
range.location -= 1;
range.length++;
} else {
range.location += 1;
range.length -= 0;
}
}
range.length = text.length - range.location;
if (range.length == 0) {
[self setSuggestions:nil];
} else {
NSString *prefix = [text substringWithRange:range];
// TODO: make not so slow.
NSArray *suggestions = @[];
for (NSString *suggestion in possibleSuggestions) {
if ([suggestion hasPrefix:prefix] && prefix.length < suggestion.length) {
suggestions = [suggestions arrayByAddingObject:suggestion];
}
}
if (suggestions.count > 3) {
suggestions = nil;
}
[self setSuggestions:suggestions];
}
[self setNeedsLayout];
}
- (void)setSuggestions:(NSArray *)suggestions {
[options removeAllObjects];
if ([suggestions respondsToSelector:@selector(countByEnumeratingWithState:objects:count:)]) {
for (NSString *suggestion in suggestions) {
if (options.count < maxSuggestions) {
[options addObject:suggestion];
} else {
break;
}
}
}
}
- (void)layoutSubview:(NSString *)t at:(CGFloat)x width:(CGFloat)w {
UIButton *b = [[UIButton alloc] initWithFrame:CGRectMake(x, 0.0f, w, self.bounds.size.height)];
[b setTitle:t forState:UIControlStateNormal];
b.titleLabel.adjustsFontSizeToFitWidth = YES;
b.titleLabel.textAlignment = NSTextAlignmentCenter;
[b setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[b addTarget:self action:@selector(buttonTouched:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:b];
if (x > 0) {
UIView *line =
[[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 0.5f, self.bounds.size.height)];
line.backgroundColor = [UIColor colorWithRed:0.984 green:0.977 blue:0.81 alpha:1.0];
[b addSubview:line];
}
[buttons addObject:b];
}
- (void)layoutSubviews {
for (UIView *subview in buttons) {
[subview removeFromSuperview];
}
[buttons removeAllObjects];
CGFloat symbolWidth = 40.0f;
[self layoutSubview:@"+" at:0 * symbolWidth width:symbolWidth];
[self layoutSubview:@"-" at:1 * symbolWidth width:symbolWidth];
[self layoutSubview:@"*" at:2 * symbolWidth width:symbolWidth];
[self layoutSubview:@"/" at:3 * symbolWidth width:symbolWidth];
for (int i = 0; i < options.count; i++) {
NSString *suggestion = options[i];
CGFloat width = (self.bounds.size.width - (4 * symbolWidth)) / options.count;
CGFloat x = (4 * symbolWidth) + (i * width);
[self layoutSubview:suggestion at:x width:width];
}
}
- (void)buttonTouched:(UIButton *)button {
NSTimeInterval duration = 0.08f;
[UIView animateWithDuration:duration
animations:^{
[button setBackgroundColor:[UIColor whiteColor]];
if ([self.delegate respondsToSelector:@selector(suggestionReplace:)]) {
NSString *t = self->text;
if (t == nil) {
t = @"";
}
if (button.currentTitle.length == 1) {
// Special case for +, -, *, /.
t = [t stringByAppendingString:button.currentTitle];
} else {
t = [self->text stringByReplacingCharactersInRange:self->range
withString:button.currentTitle];
}
[self performSelector:@selector(suggestionReplace:)
withObject:t
afterDelay:duration * 0.8f];
}
[button performSelector:@selector(setBackgroundColor:)
withObject:[UIColor clearColor]
afterDelay:duration];
}];
}
- (void)suggestionReplace:(NSString *)t {
[self.delegate performSelector:@selector(suggestionReplace:) withObject:t];
}
@end
|
ivy
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/ios/ivy/Info.plist
|
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>UIUserInterfaceStyle</key>
<string>Light</string>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDisplayName</key>
<string>Ivy</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>com.google.$(PRODUCT_NAME:rfc1034identifier)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>6</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>Launch</string>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UIRequiredDeviceCapabilities</key>
<array/>
<key>UIRequiresFullScreen</key>
<false/>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>
|
ivy
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/ios/ivy/AppDelegate.h
|
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#import <WebKit/WebKit.h>
#import "IvyController.h"
#import "Suggestion.h"
@interface AppDelegate : UIResponder <UIApplicationDelegate, UITextFieldDelegate, WKUIDelegate>
@property(strong, nonatomic) UIWindow *window;
@end
|
ivy
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/ios/ivy/main.m
|
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
int main(int argc, char *argv[])
{
@autoreleasepool
{
return UIApplicationMain(argc, argv, nil,
NSStringFromClass([AppDelegate class]));
}
}
|
AppIcon.appiconset
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/ios/ivy/Images.xcassets/AppIcon.appiconset/Contents.json
|
{
"images" : [
{
"filename" : "icon-40.png",
"idiom" : "iphone",
"scale" : "2x",
"size" : "20x20"
},
{
"filename" : "icon-60.png",
"idiom" : "iphone",
"scale" : "3x",
"size" : "20x20"
},
{
"filename" : "icon-58.png",
"idiom" : "iphone",
"scale" : "2x",
"size" : "29x29"
},
{
"filename" : "icon-87.png",
"idiom" : "iphone",
"scale" : "3x",
"size" : "29x29"
},
{
"filename" : "icon-80.png",
"idiom" : "iphone",
"scale" : "2x",
"size" : "40x40"
},
{
"filename" : "icon-120.png",
"idiom" : "iphone",
"scale" : "3x",
"size" : "40x40"
},
{
"filename" : "icon-120.png",
"idiom" : "iphone",
"scale" : "2x",
"size" : "60x60"
},
{
"filename" : "icon-180.png",
"idiom" : "iphone",
"scale" : "3x",
"size" : "60x60"
},
{
"filename" : "icon-20.png",
"idiom" : "ipad",
"scale" : "1x",
"size" : "20x20"
},
{
"filename" : "icon-40.png",
"idiom" : "ipad",
"scale" : "2x",
"size" : "20x20"
},
{
"filename" : "icon-29.png",
"idiom" : "ipad",
"scale" : "1x",
"size" : "29x29"
},
{
"filename" : "icon-58.png",
"idiom" : "ipad",
"scale" : "2x",
"size" : "29x29"
},
{
"filename" : "icon-40.png",
"idiom" : "ipad",
"scale" : "1x",
"size" : "40x40"
},
{
"filename" : "icon-80.png",
"idiom" : "ipad",
"scale" : "2x",
"size" : "40x40"
},
{
"filename" : "icon-76.png",
"idiom" : "ipad",
"scale" : "1x",
"size" : "76x76"
},
{
"filename" : "icon-152.png",
"idiom" : "ipad",
"scale" : "2x",
"size" : "76x76"
},
{
"filename" : "icon-167.png",
"idiom" : "ipad",
"scale" : "2x",
"size" : "83.5x83.5"
},
{
"filename" : "icon-1024.png",
"idiom" : "ios-marketing",
"scale" : "1x",
"size" : "1024x1024"
},
{
"filename" : "icon-120.png",
"idiom" : "car",
"scale" : "2x",
"size" : "60x60"
},
{
"filename" : "icon-180.png",
"idiom" : "car",
"scale" : "3x",
"size" : "60x60"
},
{
"filename" : "icon-48.png",
"idiom" : "watch",
"role" : "notificationCenter",
"scale" : "2x",
"size" : "24x24",
"subtype" : "38mm"
},
{
"filename" : "icon-55.png",
"idiom" : "watch",
"role" : "notificationCenter",
"scale" : "2x",
"size" : "27.5x27.5",
"subtype" : "42mm"
},
{
"filename" : "icon-58.png",
"idiom" : "watch",
"role" : "companionSettings",
"scale" : "2x",
"size" : "29x29"
},
{
"filename" : "icon-87.png",
"idiom" : "watch",
"role" : "companionSettings",
"scale" : "3x",
"size" : "29x29"
},
{
"idiom" : "watch",
"role" : "notificationCenter",
"scale" : "2x",
"size" : "33x33",
"subtype" : "45mm"
},
{
"filename" : "icon-80.png",
"idiom" : "watch",
"role" : "appLauncher",
"scale" : "2x",
"size" : "40x40",
"subtype" : "38mm"
},
{
"filename" : "icon-88.png",
"idiom" : "watch",
"role" : "appLauncher",
"scale" : "2x",
"size" : "44x44",
"subtype" : "40mm"
},
{
"idiom" : "watch",
"role" : "appLauncher",
"scale" : "2x",
"size" : "46x46",
"subtype" : "41mm"
},
{
"filename" : "icon-100.png",
"idiom" : "watch",
"role" : "appLauncher",
"scale" : "2x",
"size" : "50x50",
"subtype" : "44mm"
},
{
"idiom" : "watch",
"role" : "appLauncher",
"scale" : "2x",
"size" : "51x51",
"subtype" : "45mm"
},
{
"filename" : "icon-172.png",
"idiom" : "watch",
"role" : "quickLook",
"scale" : "2x",
"size" : "86x86",
"subtype" : "38mm"
},
{
"filename" : "icon-196.png",
"idiom" : "watch",
"role" : "quickLook",
"scale" : "2x",
"size" : "98x98",
"subtype" : "42mm"
},
{
"filename" : "icon-216.png",
"idiom" : "watch",
"role" : "quickLook",
"scale" : "2x",
"size" : "108x108",
"subtype" : "44mm"
},
{
"idiom" : "watch",
"role" : "quickLook",
"scale" : "2x",
"size" : "117x117",
"subtype" : "45mm"
},
{
"filename" : "icon-1024.png",
"idiom" : "watch-marketing",
"scale" : "1x",
"size" : "1024x1024"
},
{
"filename" : "icon-16.png",
"idiom" : "mac",
"scale" : "1x",
"size" : "16x16"
},
{
"filename" : "icon-32.png",
"idiom" : "mac",
"scale" : "2x",
"size" : "16x16"
},
{
"filename" : "icon-32.png",
"idiom" : "mac",
"scale" : "1x",
"size" : "32x32"
},
{
"filename" : "icon-64.png",
"idiom" : "mac",
"scale" : "2x",
"size" : "32x32"
},
{
"filename" : "icon-128.png",
"idiom" : "mac",
"scale" : "1x",
"size" : "128x128"
},
{
"filename" : "icon-256.png",
"idiom" : "mac",
"scale" : "2x",
"size" : "128x128"
},
{
"filename" : "icon-256.png",
"idiom" : "mac",
"scale" : "1x",
"size" : "256x256"
},
{
"filename" : "icon-512.png",
"idiom" : "mac",
"scale" : "2x",
"size" : "256x256"
},
{
"filename" : "icon-512.png",
"idiom" : "mac",
"scale" : "1x",
"size" : "512x512"
},
{
"filename" : "icon-1024.png",
"idiom" : "mac",
"scale" : "2x",
"size" : "512x512"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
|
Base.lproj
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/ios/ivy/Base.lproj/Main.storyboard
|
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="19162" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="mTw-C8-NzX">
<device id="retina6_1" orientation="portrait" appearance="light"/>
<accessibilityOverrides isEnabled="YES"/>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="19144"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--Docs-->
<scene sceneID="qSe-m0-5Rh">
<objects>
<viewController title="Docs" id="rfr-rm-AXI" customClass="DocsController" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="TeY-hL-zeC"/>
<viewControllerLayoutGuide type="bottom" id="Yrx-qe-pYd"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="a4n-1z-obZ">
<rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<wkWebView opaque="NO" tag="11" contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="xlZ-tR-6QP">
<rect key="frame" x="20" y="96" width="374" height="758"/>
<color key="backgroundColor" white="0.0" alpha="0.0" colorSpace="calibratedWhite"/>
<wkWebViewConfiguration key="configuration">
<audiovisualMediaTypes key="mediaTypesRequiringUserActionForPlayback" none="YES"/>
<wkPreferences key="preferences"/>
</wkWebViewConfiguration>
</wkWebView>
</subviews>
<color key="backgroundColor" red="0.9882352941176471" green="0.98039215686274506" blue="0.81176470588235294" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<constraints>
<constraint firstItem="xlZ-tR-6QP" firstAttribute="trailing" secondItem="a4n-1z-obZ" secondAttribute="trailingMargin" id="GP2-Wr-Bh9"/>
<constraint firstItem="xlZ-tR-6QP" firstAttribute="top" secondItem="TeY-hL-zeC" secondAttribute="bottom" constant="8" symbolic="YES" id="Vvo-yF-z4a"/>
<constraint firstItem="Yrx-qe-pYd" firstAttribute="top" secondItem="xlZ-tR-6QP" secondAttribute="bottom" constant="8" symbolic="YES" id="afC-pF-Eom"/>
<constraint firstItem="xlZ-tR-6QP" firstAttribute="leading" secondItem="a4n-1z-obZ" secondAttribute="leadingMargin" id="wxq-1W-9XD"/>
</constraints>
</view>
<navigationItem key="navigationItem" title="Documentation" id="lf7-H3-aZF"/>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="HMz-gF-Hp5" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="1724.6305418719212" y="384.80000000000001"/>
</scene>
<!--Ivy Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController title="Ivy Controller" id="BYZ-38-t0r" customClass="IvyController" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
<viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
</layoutGuides>
<view key="view" contentMode="scaleAspectFit" id="8bC-Xf-vdC">
<rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<stackView opaque="NO" contentMode="scaleToFill" horizontalCompressionResistancePriority="1000" verticalCompressionResistancePriority="1000" alignment="center" translatesAutoresizingMaskIntoConstraints="NO" id="Cn1-rU-W3R">
<rect key="frame" x="20" y="831" width="374" height="31"/>
<subviews>
<textField opaque="NO" clipsSubviews="YES" tag="1" contentMode="scaleToFill" horizontalHuggingPriority="249" contentHorizontalAlignment="left" contentVerticalAlignment="center" borderStyle="roundedRect" placeholder="Type an expression" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="9SS-TP-C7c" userLabel="InputField">
<rect key="frame" x="0.0" y="0.0" width="301.5" height="31"/>
<color key="backgroundColor" red="0.98823529409999999" green="0.98039215690000003" blue="0.81176470590000005" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<rect key="contentStretch" x="1" y="1" width="1" height="1"/>
<fontDescription key="fontDescription" name="Menlo-Bold" family="Menlo" pointSize="14"/>
<textInputTraits key="textInputTraits" autocorrectionType="no" spellCheckingType="no" keyboardType="alphabet" keyboardAppearance="alert" enablesReturnKeyAutomatically="YES" smartDashesType="no" smartInsertDeleteType="no" smartQuotesType="no"/>
<connections>
<action selector="okPressed:" destination="BYZ-38-t0r" eventType="primaryActionTriggered" id="3BK-xS-ize"/>
<action selector="okPressed:" destination="BYZ-38-t0r" eventType="editingDidEnd" id="91o-Gh-hrf"/>
</connections>
</textField>
<button opaque="NO" contentMode="scaleToFill" horizontalCompressionResistancePriority="1000" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="system" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="eO6-bM-CwW">
<rect key="frame" x="301.5" y="0.0" width="72.5" height="31"/>
<accessibility key="accessibilityConfiguration" label="OK"/>
<constraints>
<constraint firstAttribute="height" constant="31" id="1nb-CV-bfg"/>
</constraints>
<inset key="imageEdgeInsets" minX="0.0" minY="0.0" maxX="2.2250738585072014e-308" maxY="0.0"/>
<state key="normal" title="Button" image="return" catalog="system"/>
<connections>
<action selector="okPressed:" destination="BYZ-38-t0r" eventType="touchUpInside" id="258-zN-fwW"/>
</connections>
</button>
</subviews>
<constraints>
<constraint firstItem="9SS-TP-C7c" firstAttribute="trailing" secondItem="eO6-bM-CwW" secondAttribute="leading" id="9Fe-Sf-U5p"/>
<constraint firstItem="eO6-bM-CwW" firstAttribute="top" secondItem="9SS-TP-C7c" secondAttribute="top" id="9hv-aL-4z2"/>
<constraint firstItem="eO6-bM-CwW" firstAttribute="trailing" secondItem="Cn1-rU-W3R" secondAttribute="trailing" id="A4G-YY-4Gn"/>
<constraint firstItem="9SS-TP-C7c" firstAttribute="leading" secondItem="Cn1-rU-W3R" secondAttribute="leading" id="i2m-BU-Q4a"/>
</constraints>
</stackView>
<wkWebView opaque="NO" tag="2" contentMode="scaleToFill" preservesSuperviewLayoutMargins="YES" layoutMarginsFollowReadableWidth="YES" translatesAutoresizingMaskIntoConstraints="NO" id="ga1-Py-9re">
<rect key="frame" x="20" y="88" width="374" height="737"/>
<color key="backgroundColor" white="0.0" alpha="0.0" colorSpace="calibratedWhite"/>
<wkWebViewConfiguration key="configuration">
<audiovisualMediaTypes key="mediaTypesRequiringUserActionForPlayback" none="YES"/>
<wkPreferences key="preferences"/>
</wkWebViewConfiguration>
</wkWebView>
</subviews>
<color key="backgroundColor" red="0.9882352941176471" green="0.98039215686274506" blue="0.81176470588235294" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<constraints>
<constraint firstItem="Cn1-rU-W3R" firstAttribute="trailing" secondItem="8bC-Xf-vdC" secondAttribute="trailingMargin" id="7DU-Hc-uk7"/>
<constraint firstItem="Cn1-rU-W3R" firstAttribute="bottom" secondItem="wfy-db-euE" secondAttribute="top" id="8mr-vY-R1v"/>
<constraint firstItem="ga1-Py-9re" firstAttribute="bottom" secondItem="Cn1-rU-W3R" secondAttribute="top" constant="-6" id="BX0-OH-IJ4"/>
<constraint firstItem="ga1-Py-9re" firstAttribute="trailing" secondItem="8bC-Xf-vdC" secondAttribute="trailingMargin" id="Fxh-TE-BtG"/>
<constraint firstItem="Cn1-rU-W3R" firstAttribute="leading" secondItem="8bC-Xf-vdC" secondAttribute="leadingMargin" id="LPE-LO-nct"/>
<constraint firstItem="ga1-Py-9re" firstAttribute="top" secondItem="8bC-Xf-vdC" secondAttribute="topMargin" id="p9M-sp-ZwC"/>
<constraint firstItem="ga1-Py-9re" firstAttribute="leading" secondItem="8bC-Xf-vdC" secondAttribute="leadingMargin" id="pOi-3s-hrr"/>
</constraints>
</view>
<navigationItem key="navigationItem" title="Ivy" id="9fD-A5-WTg">
<barButtonItem key="leftBarButtonItem" title="Clear" id="70x-xp-aiX">
<connections>
<action selector="clear:" destination="BYZ-38-t0r" id="n7k-fg-dil"/>
</connections>
</barButtonItem>
<rightBarButtonItems>
<barButtonItem title="Help" id="aDa-GJ-VpX">
<connections>
<segue destination="rfr-rm-AXI" kind="show" id="kuc-xA-dyM"/>
</connections>
</barButtonItem>
<barButtonItem title="Demo" id="ZN2-PQ-aPW">
<connections>
<action selector="demo:" destination="BYZ-38-t0r" id="NpG-yh-wMO"/>
</connections>
</barButtonItem>
</rightBarButtonItems>
</navigationItem>
<connections>
<outlet property="bottomConstraint" destination="8mr-vY-R1v" id="BqX-Do-vtq"/>
<outlet property="input" destination="9SS-TP-C7c" id="jUA-25-4WI"/>
<outlet property="okButton" destination="eO6-bM-CwW" id="o9U-hD-NDr"/>
<outlet property="tape" destination="ga1-Py-9re" id="00M-9S-MAl"/>
</connections>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="989.85507246376824" y="382.36607142857139"/>
</scene>
<!--Navigation Controller-->
<scene sceneID="ZgV-45-Pf8">
<objects>
<navigationController automaticallyAdjustsScrollViewInsets="NO" id="mTw-C8-NzX" sceneMemberID="viewController">
<toolbarItems/>
<navigationBar key="navigationBar" opaque="NO" contentMode="scaleToFill" id="aev-Tm-XK3">
<rect key="frame" x="0.0" y="44" width="414" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<color key="backgroundColor" red="1" green="1" blue="0.80392156859999997" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<color key="barTintColor" red="1" green="1" blue="0.80392156859999997" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<navigationBarAppearance key="standardAppearance">
<color key="backgroundColor" red="1" green="1" blue="0.80392156859999997" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
</navigationBarAppearance>
<navigationBarAppearance key="compactAppearance">
<color key="backgroundColor" red="1" green="1" blue="0.80392156859999997" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
</navigationBarAppearance>
<navigationBarAppearance key="scrollEdgeAppearance">
<color key="backgroundColor" red="1" green="1" blue="0.80392156859999997" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
</navigationBarAppearance>
</navigationBar>
<nil name="viewControllers"/>
<toolbar key="toolbar" opaque="NO" clearsContextBeforeDrawing="NO" contentMode="scaleToFill" insetsLayoutMarginsFromSafeArea="NO" id="smI-B7-WbU">
<autoresizingMask key="autoresizingMask"/>
</toolbar>
<connections>
<segue destination="BYZ-38-t0r" kind="relationship" relationship="rootViewController" id="Nyy-d4-AXi"/>
</connections>
</navigationController>
<placeholder placeholderIdentifier="IBFirstResponder" id="i1l-Sg-DC5" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="271" y="386"/>
</scene>
</scenes>
<resources>
<image name="return" catalog="system" width="128" height="101"/>
</resources>
</document>
|
en.lproj
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/ivy/ios/ivy/en.lproj/Main.strings
|
/* Class = "UITextField"; placeholder = "Type an expression"; ObjectID = "9SS-TP-C7c"; */
"9SS-TP-C7c.placeholder" = "Type an expression";
/* Class = "UIViewController"; title = "Ivy Controller"; ObjectID = "BYZ-38-t0r"; */
"BYZ-38-t0r.title" = "Ivy Controller";
/* Class = "UIBarButtonItem"; title = "Help"; ObjectID = "GSn-BW-al6"; */
"GSn-BW-al6.title" = "Help";
/* Class = "UINavigationItem"; title = "Ivy"; ObjectID = "KhW-J4-UcU"; */
"KhW-J4-UcU.title" = "Ivy";
/* Class = "UINavigationItem"; title = "Documentation"; ObjectID = "lf7-H3-aZF"; */
"lf7-H3-aZF.title" = "Documentation";
/* Class = "UIViewController"; title = "Docs"; ObjectID = "rfr-rm-AXI"; */
"rfr-rm-AXI.title" = "Docs";
|
flappy
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/flappy/game.go
|
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build darwin || linux
package main
import (
"image"
"log"
"math"
"math/rand"
_ "image/png"
"golang.org/x/mobile/asset"
"golang.org/x/mobile/exp/f32"
"golang.org/x/mobile/exp/sprite"
"golang.org/x/mobile/exp/sprite/clock"
)
const (
tileWidth, tileHeight = 16, 16 // width and height of each tile
tilesX, tilesY = 16, 16 // number of horizontal tiles
gopherTile = 1 // which tile the gopher is standing on (0-indexed)
initScrollV = 1 // initial scroll velocity
scrollA = 0.001 // scroll acceleration
gravity = 0.1 // gravity
jumpV = -5 // jump velocity
flapV = -1.5 // flap velocity
deadScrollA = -0.01 // scroll deceleration after the gopher dies
deadTimeBeforeReset = 240 // how long to wait before restarting the game
groundChangeProb = 5 // 1/probability of ground height change
groundWobbleProb = 3 // 1/probability of minor ground height change
groundMin = tileHeight * (tilesY - 2*tilesY/5)
groundMax = tileHeight * tilesY
initGroundY = tileHeight * (tilesY - 1)
climbGrace = tileHeight / 3 // gopher won't die if it hits a cliff this high
)
type Game struct {
gopher struct {
y float32 // y-offset
v float32 // velocity
atRest bool // is the gopher on the ground?
flapped bool // has the gopher flapped since it became airborne?
dead bool // is the gopher dead?
deadTime clock.Time // when the gopher died
}
scroll struct {
x float32 // x-offset
v float32 // velocity
}
groundY [tilesX + 3]float32 // ground y-offsets
groundTex [tilesX + 3]int // ground texture
lastCalc clock.Time // when we last calculated a frame
}
func NewGame() *Game {
var g Game
g.reset()
return &g
}
func (g *Game) reset() {
g.gopher.y = 0
g.gopher.v = 0
g.scroll.x = 0
g.scroll.v = initScrollV
for i := range g.groundY {
g.groundY[i] = initGroundY
g.groundTex[i] = randomGroundTexture()
}
g.gopher.atRest = false
g.gopher.flapped = false
g.gopher.dead = false
g.gopher.deadTime = 0
}
func (g *Game) Scene(eng sprite.Engine) *sprite.Node {
texs := loadTextures(eng)
scene := &sprite.Node{}
eng.Register(scene)
eng.SetTransform(scene, f32.Affine{
{1, 0, 0},
{0, 1, 0},
})
newNode := func(fn arrangerFunc) {
n := &sprite.Node{Arranger: arrangerFunc(fn)}
eng.Register(n)
scene.AppendChild(n)
}
// The ground.
for i := range g.groundY {
i := i
// The top of the ground.
newNode(func(eng sprite.Engine, n *sprite.Node, t clock.Time) {
eng.SetSubTex(n, texs[g.groundTex[i]])
eng.SetTransform(n, f32.Affine{
{tileWidth, 0, float32(i)*tileWidth - g.scroll.x},
{0, tileHeight, g.groundY[i]},
})
})
// The earth beneath.
newNode(func(eng sprite.Engine, n *sprite.Node, t clock.Time) {
eng.SetSubTex(n, texs[texEarth])
eng.SetTransform(n, f32.Affine{
{tileWidth, 0, float32(i)*tileWidth - g.scroll.x},
{0, tileHeight * tilesY, g.groundY[i] + tileHeight},
})
})
}
// The gopher.
newNode(func(eng sprite.Engine, n *sprite.Node, t clock.Time) {
a := f32.Affine{
{tileWidth * 2, 0, tileWidth*(gopherTile-1) + tileWidth/8},
{0, tileHeight * 2, g.gopher.y - tileHeight + tileHeight/4},
}
var x int
switch {
case g.gopher.dead:
x = frame(t, 16, texGopherDead1, texGopherDead2)
animateDeadGopher(&a, t-g.gopher.deadTime)
case g.gopher.v < 0:
x = frame(t, 4, texGopherFlap1, texGopherFlap2)
case g.gopher.atRest:
x = frame(t, 4, texGopherRun1, texGopherRun2)
default:
x = frame(t, 8, texGopherRun1, texGopherRun2)
}
eng.SetSubTex(n, texs[x])
eng.SetTransform(n, a)
})
return scene
}
// frame returns the frame for the given time t
// when each frame is displayed for duration d.
func frame(t, d clock.Time, frames ...int) int {
total := int(d) * len(frames)
return frames[(int(t)%total)/int(d)]
}
func animateDeadGopher(a *f32.Affine, t clock.Time) {
dt := float32(t)
a.Scale(a, 1+dt/20, 1+dt/20)
a.Translate(a, 0.5, 0.5)
a.Rotate(a, dt/math.Pi/-8)
a.Translate(a, -0.5, -0.5)
}
type arrangerFunc func(e sprite.Engine, n *sprite.Node, t clock.Time)
func (a arrangerFunc) Arrange(e sprite.Engine, n *sprite.Node, t clock.Time) { a(e, n, t) }
const (
texGopherRun1 = iota
texGopherRun2
texGopherFlap1
texGopherFlap2
texGopherDead1
texGopherDead2
texGround1
texGround2
texGround3
texGround4
texEarth
)
func randomGroundTexture() int {
return texGround1 + rand.Intn(4)
}
func loadTextures(eng sprite.Engine) []sprite.SubTex {
a, err := asset.Open("sprite.png")
if err != nil {
log.Fatal(err)
}
defer a.Close()
m, _, err := image.Decode(a)
if err != nil {
log.Fatal(err)
}
t, err := eng.LoadTexture(m)
if err != nil {
log.Fatal(err)
}
const n = 128
// The +1's and -1's in the rectangles below are to prevent colors from
// adjacent textures leaking into a given texture.
// See: http://stackoverflow.com/questions/19611745/opengl-black-lines-in-between-tiles
return []sprite.SubTex{
texGopherRun1: sprite.SubTex{t, image.Rect(n*0+1, 0, n*1-1, n)},
texGopherRun2: sprite.SubTex{t, image.Rect(n*1+1, 0, n*2-1, n)},
texGopherFlap1: sprite.SubTex{t, image.Rect(n*2+1, 0, n*3-1, n)},
texGopherFlap2: sprite.SubTex{t, image.Rect(n*3+1, 0, n*4-1, n)},
texGopherDead1: sprite.SubTex{t, image.Rect(n*4+1, 0, n*5-1, n)},
texGopherDead2: sprite.SubTex{t, image.Rect(n*5+1, 0, n*6-1, n)},
texGround1: sprite.SubTex{t, image.Rect(n*6+1, 0, n*7-1, n)},
texGround2: sprite.SubTex{t, image.Rect(n*7+1, 0, n*8-1, n)},
texGround3: sprite.SubTex{t, image.Rect(n*8+1, 0, n*9-1, n)},
texGround4: sprite.SubTex{t, image.Rect(n*9+1, 0, n*10-1, n)},
texEarth: sprite.SubTex{t, image.Rect(n*10+1, 0, n*11-1, n)},
}
}
func (g *Game) Press(down bool) {
if g.gopher.dead {
// Player can't control a dead gopher.
return
}
if down {
switch {
case g.gopher.atRest:
// Gopher may jump from the ground.
g.gopher.v = jumpV
case !g.gopher.flapped:
// Gopher may flap once in mid-air.
g.gopher.flapped = true
g.gopher.v = flapV
}
} else {
// Stop gopher rising on button release.
if g.gopher.v < 0 {
g.gopher.v = 0
}
}
}
func (g *Game) Update(now clock.Time) {
if g.gopher.dead && now-g.gopher.deadTime > deadTimeBeforeReset {
// Restart if the gopher has been dead for a while.
g.reset()
}
// Compute game states up to now.
for ; g.lastCalc < now; g.lastCalc++ {
g.calcFrame()
}
}
func (g *Game) calcFrame() {
g.calcScroll()
g.calcGopher()
}
func (g *Game) calcScroll() {
// Compute velocity.
if g.gopher.dead {
// Decrease scroll speed when the gopher dies.
g.scroll.v += deadScrollA
if g.scroll.v < 0 {
g.scroll.v = 0
}
} else {
// Increase scroll speed.
g.scroll.v += scrollA
}
// Compute offset.
g.scroll.x += g.scroll.v
// Create new ground tiles if we need to.
for g.scroll.x > tileWidth {
g.newGroundTile()
// Check whether the gopher has crashed.
// Do this for each new ground tile so that when the scroll
// velocity is >tileWidth/frame it can't pass through the ground.
if !g.gopher.dead && g.gopherCrashed() {
g.killGopher()
}
}
}
func (g *Game) calcGopher() {
// Compute velocity.
g.gopher.v += gravity
// Compute offset.
g.gopher.y += g.gopher.v
g.clampToGround()
}
func (g *Game) newGroundTile() {
// Compute next ground y-offset.
next := g.nextGroundY()
nextTex := randomGroundTexture()
// Shift ground tiles to the left.
g.scroll.x -= tileWidth
copy(g.groundY[:], g.groundY[1:])
copy(g.groundTex[:], g.groundTex[1:])
last := len(g.groundY) - 1
g.groundY[last] = next
g.groundTex[last] = nextTex
}
func (g *Game) nextGroundY() float32 {
prev := g.groundY[len(g.groundY)-1]
if change := rand.Intn(groundChangeProb) == 0; change {
return (groundMax-groundMin)*rand.Float32() + groundMin
}
if wobble := rand.Intn(groundWobbleProb) == 0; wobble {
return prev + (rand.Float32()-0.5)*climbGrace
}
return prev
}
func (g *Game) gopherCrashed() bool {
return g.gopher.y+tileHeight-climbGrace > g.groundY[gopherTile+1]
}
func (g *Game) killGopher() {
g.gopher.dead = true
g.gopher.deadTime = g.lastCalc
g.gopher.v = jumpV * 1.5 // Bounce off screen.
}
func (g *Game) clampToGround() {
if g.gopher.dead {
// Allow the gopher to fall through ground when dead.
return
}
// Compute the minimum offset of the ground beneath the gopher.
minY := g.groundY[gopherTile]
if y := g.groundY[gopherTile+1]; y < minY {
minY = y
}
// Prevent the gopher from falling through the ground.
maxGopherY := minY - tileHeight
g.gopher.atRest = false
if g.gopher.y >= maxGopherY {
g.gopher.v = 0
g.gopher.y = maxGopherY
g.gopher.atRest = true
g.gopher.flapped = false
}
}
|
flappy
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/flappy/main.go
|
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build darwin || linux
// Flappy Gopher is a simple one-button game that uses the
// mobile framework and the experimental sprite engine.
package main
import (
"math/rand"
"time"
"golang.org/x/mobile/app"
"golang.org/x/mobile/event/key"
"golang.org/x/mobile/event/lifecycle"
"golang.org/x/mobile/event/paint"
"golang.org/x/mobile/event/size"
"golang.org/x/mobile/event/touch"
"golang.org/x/mobile/exp/gl/glutil"
"golang.org/x/mobile/exp/sprite"
"golang.org/x/mobile/exp/sprite/clock"
"golang.org/x/mobile/exp/sprite/glsprite"
"golang.org/x/mobile/gl"
)
func main() {
rand.Seed(time.Now().UnixNano())
app.Main(func(a app.App) {
var glctx gl.Context
var sz size.Event
for e := range a.Events() {
switch e := a.Filter(e).(type) {
case lifecycle.Event:
switch e.Crosses(lifecycle.StageVisible) {
case lifecycle.CrossOn:
glctx, _ = e.DrawContext.(gl.Context)
onStart(glctx)
a.Send(paint.Event{})
case lifecycle.CrossOff:
onStop()
glctx = nil
}
case size.Event:
sz = e
case paint.Event:
if glctx == nil || e.External {
continue
}
onPaint(glctx, sz)
a.Publish()
a.Send(paint.Event{}) // keep animating
case touch.Event:
if down := e.Type == touch.TypeBegin; down || e.Type == touch.TypeEnd {
game.Press(down)
}
case key.Event:
if e.Code != key.CodeSpacebar {
break
}
if down := e.Direction == key.DirPress; down || e.Direction == key.DirRelease {
game.Press(down)
}
}
}
})
}
var (
startTime = time.Now()
images *glutil.Images
eng sprite.Engine
scene *sprite.Node
game *Game
)
func onStart(glctx gl.Context) {
images = glutil.NewImages(glctx)
eng = glsprite.Engine(images)
game = NewGame()
scene = game.Scene(eng)
}
func onStop() {
eng.Release()
images.Release()
game = nil
}
func onPaint(glctx gl.Context, sz size.Event) {
glctx.ClearColor(1, 1, 1, 1)
glctx.Clear(gl.COLOR_BUFFER_BIT)
now := clock.Time(time.Since(startTime) * 60 / time.Second)
game.Update(now)
eng.Render(scene, now, sz)
}
|
flappy
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/flappy/main_x.go
|
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !darwin && !linux
package main
func main() {
}
|
assets
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/flappy/assets/README
|
The sprites were created by Renee French and are distributed
under the Creative Commons Attributions 3.0 license.
|
android
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/bind/android/build.gradle
|
/* Copyright 2015 The Go Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.0'
}
}
allprojects {
repositories {
google()
jcenter()
}
}
|
android
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/bind/android/README
|
Go bind android app example
Run
$ gomobile bind -o app/hello.aar golang.org/x/mobile/example/bind/hello
and import this project in Android Studio. If you prefer the command
line, use gradle to build directly.
Note that you need to run gomobile bind again every time you make a
change to Go code.
|
android
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/bind/android/settings.gradle
|
/* Copyright 2015 The Go Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
include ':app'
|
app
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/bind/android/app/build.gradle
|
/*
* Copyright 2015 The Go Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
apply plugin: 'com.android.application'
repositories {
flatDir {
dirs '.'
}
}
android {
compileSdkVersion 27
defaultConfig {
applicationId "org.golang.example.android"
minSdkVersion 15
targetSdkVersion 27
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
}
}
}
dependencies {
implementation 'com.android.support:appcompat-v7:22.1.1'
implementation (name:'hello', ext:'aar')
}
|
main
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/bind/android/app/src/main/AndroidManifest.xml
|
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright 2015 The Go Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file. -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.golang.example.bind" >
<application
android:allowBackup="true"
android:label="GoBindExample">
<activity
android:name=".MainActivity"
android:label="GoBindExample" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
|
bind
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/bind/android/app/src/main/java/org/golang/example/bind/MainActivity.java
|
/*
* Copyright 2015 The Go Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
package org.golang.example.bind;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import hello.Hello;
public class MainActivity extends Activity {
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.mytextview);
// Call Go function.
String greetings = Hello.greetings("Android and Gopher");
mTextView.setText(greetings);
}
}
|
values
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/bind/android/app/src/main/res/values/dimens.xml
|
<!-- Copyright 2015 The Go Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file. -->
<resources>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
</resources>
|
layout
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/bind/android/app/src/main/res/layout/activity_main.xml
|
<!-- Copyright 2015 The Go Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file. -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/mytextview" />
</RelativeLayout>
|
ios
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/bind/ios/README
|
1. Use gomobile bind to bind the golang.org/x/mobile/example/bind/hello package.
The following command will create an XCFramework in the current directory.
$ gomobile bind -target=ios golang.org/x/mobile/example/bind/hello
2. Open the Xcode project by double clicking on bind.xcodeproj.
The project will not build - ViewController.m calls a function from the hello
package so requires the Hello.xcframework that gomobile bind command created
in Step 1.
3. Drag-and-drop Hello.xcframework from the desktop to the project navigation window.
This will automatically include the Hello.xcframework into the project.
4. Build.
|
bind
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/bind/ios/bind/AppDelegate.m
|
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#import "AppDelegate.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
return YES;
}
@end
|
bind
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/bind/ios/bind/ViewController.h
|
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (strong, nonatomic) IBOutlet UILabel *textLabel;
@end
|
bind
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/bind/ios/bind/Info.plist
|
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>org.golang.example.$(PRODUCT_NAME:rfc1034identifier)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>
|
bind
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/bind/ios/bind/ViewController.m
|
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#import "ViewController.h"
@import Hello; // Gomobile bind generated framework
@interface ViewController ()
@end
@implementation ViewController
@synthesize textLabel;
- (void)loadView {
[super loadView];
textLabel.text = HelloGreetings(@"iOS and Gopher");
}
@end
|
bind
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/bind/ios/bind/AppDelegate.h
|
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
|
bind
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/bind/ios/bind/main.m
|
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
int main(int argc, char * argv[]) {
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
|
Base.lproj
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/bind/ios/bind/Base.lproj/Main.storyboard
|
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="7706" systemVersion="14E46" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="BYZ-38-t0r">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="7703"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController id="BYZ-38-t0r" customClass="ViewController" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
<viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
<rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Label" lineBreakMode="tailTruncation" numberOfLines="0" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="DnT-nt-GoH">
<rect key="frame" x="0.0" y="-21" width="42" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
<variation key="heightClass=regular-widthClass=compact" fixedFrame="YES">
<rect key="frame" x="16" y="45" width="368" height="186"/>
</variation>
</label>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
<variation key="default">
<mask key="subviews">
<exclude reference="DnT-nt-GoH"/>
</mask>
</variation>
<variation key="heightClass=regular-widthClass=compact">
<mask key="subviews">
<include reference="DnT-nt-GoH"/>
</mask>
</variation>
</view>
<connections>
<outlet property="textLabel" destination="DnT-nt-GoH" id="j36-v0-1F2"/>
</connections>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="304.5" y="372"/>
</scene>
</scenes>
</document>
|
Base.lproj
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/bind/ios/bind/Base.lproj/LaunchScreen.xib
|
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="6214" systemVersion="14A314h" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="6207"/>
<capability name="Constraints with non-1.0 multipliers" minToolsVersion="5.1"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<view contentMode="scaleToFill" id="iN0-l3-epB">
<rect key="frame" x="0.0" y="0.0" width="480" height="480"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<label opaque="NO" clipsSubviews="YES" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text=" Copyright (c) 2015 Hana (Hyang-Ah) Kim. All rights reserved." textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" minimumFontSize="9" translatesAutoresizingMaskIntoConstraints="NO" id="8ie-xW-0ye">
<rect key="frame" x="20" y="439" width="441" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" clipsSubviews="YES" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="bind" textAlignment="center" lineBreakMode="middleTruncation" baselineAdjustment="alignBaselines" minimumFontSize="18" translatesAutoresizingMaskIntoConstraints="NO" id="kId-c2-rCX">
<rect key="frame" x="20" y="140" width="441" height="43"/>
<fontDescription key="fontDescription" type="boldSystem" pointSize="36"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
<constraints>
<constraint firstItem="kId-c2-rCX" firstAttribute="centerY" secondItem="iN0-l3-epB" secondAttribute="bottom" multiplier="1/3" constant="1" id="5cJ-9S-tgC"/>
<constraint firstAttribute="centerX" secondItem="kId-c2-rCX" secondAttribute="centerX" id="Koa-jz-hwk"/>
<constraint firstAttribute="bottom" secondItem="8ie-xW-0ye" secondAttribute="bottom" constant="20" id="Kzo-t9-V3l"/>
<constraint firstItem="8ie-xW-0ye" firstAttribute="leading" secondItem="iN0-l3-epB" secondAttribute="leading" constant="20" symbolic="YES" id="MfP-vx-nX0"/>
<constraint firstAttribute="centerX" secondItem="8ie-xW-0ye" secondAttribute="centerX" id="ZEH-qu-HZ9"/>
<constraint firstItem="kId-c2-rCX" firstAttribute="leading" secondItem="iN0-l3-epB" secondAttribute="leading" constant="20" symbolic="YES" id="fvb-Df-36g"/>
</constraints>
<nil key="simulatedStatusBarMetrics"/>
<freeformSimulatedSizeMetrics key="simulatedDestinationMetrics"/>
<point key="canvasLocation" x="548" y="455"/>
</view>
</objects>
</document>
|
hello
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/bind/hello/hello.go
|
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package hello is a trivial package for gomobile bind example.
package hello
import "fmt"
func Greetings(name string) string {
return fmt.Sprintf("Hello, %s!", name)
}
|
basic
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/basic/main.go
|
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build darwin || linux || windows
// An app that draws a green triangle on a red background.
//
// In order to build this program as an Android APK, using the gomobile tool.
//
// See http://godoc.org/golang.org/x/mobile/cmd/gomobile to install gomobile.
//
// Get the basic example and use gomobile to build or install it on your device.
//
// $ go get -d golang.org/x/mobile/example/basic
// $ gomobile build golang.org/x/mobile/example/basic # will build an APK
//
// # plug your Android device to your computer or start an Android emulator.
// # if you have adb installed on your machine, use gomobile install to
// # build and deploy the APK to an Android target.
// $ gomobile install golang.org/x/mobile/example/basic
//
// Switch to your device or emulator to start the Basic application from
// the launcher.
// You can also run the application on your desktop by running the command
// below. (Note: It currently doesn't work on Windows.)
//
// $ go install golang.org/x/mobile/example/basic && basic
package main
import (
"encoding/binary"
"log"
"golang.org/x/mobile/app"
"golang.org/x/mobile/event/lifecycle"
"golang.org/x/mobile/event/paint"
"golang.org/x/mobile/event/size"
"golang.org/x/mobile/event/touch"
"golang.org/x/mobile/exp/app/debug"
"golang.org/x/mobile/exp/f32"
"golang.org/x/mobile/exp/gl/glutil"
"golang.org/x/mobile/gl"
)
var (
images *glutil.Images
fps *debug.FPS
program gl.Program
position gl.Attrib
offset gl.Uniform
color gl.Uniform
buf gl.Buffer
green float32
touchX float32
touchY float32
)
func main() {
app.Main(func(a app.App) {
var glctx gl.Context
var sz size.Event
for e := range a.Events() {
switch e := a.Filter(e).(type) {
case lifecycle.Event:
switch e.Crosses(lifecycle.StageVisible) {
case lifecycle.CrossOn:
glctx, _ = e.DrawContext.(gl.Context)
onStart(glctx)
a.Send(paint.Event{})
case lifecycle.CrossOff:
onStop(glctx)
glctx = nil
}
case size.Event:
sz = e
touchX = float32(sz.WidthPx / 2)
touchY = float32(sz.HeightPx / 2)
case paint.Event:
if glctx == nil || e.External {
// As we are actively painting as fast as
// we can (usually 60 FPS), skip any paint
// events sent by the system.
continue
}
onPaint(glctx, sz)
a.Publish()
// Drive the animation by preparing to paint the next frame
// after this one is shown.
a.Send(paint.Event{})
case touch.Event:
touchX = e.X
touchY = e.Y
}
}
})
}
func onStart(glctx gl.Context) {
var err error
program, err = glutil.CreateProgram(glctx, vertexShader, fragmentShader)
if err != nil {
log.Printf("error creating GL program: %v", err)
return
}
buf = glctx.CreateBuffer()
glctx.BindBuffer(gl.ARRAY_BUFFER, buf)
glctx.BufferData(gl.ARRAY_BUFFER, triangleData, gl.STATIC_DRAW)
position = glctx.GetAttribLocation(program, "position")
color = glctx.GetUniformLocation(program, "color")
offset = glctx.GetUniformLocation(program, "offset")
images = glutil.NewImages(glctx)
fps = debug.NewFPS(images)
}
func onStop(glctx gl.Context) {
glctx.DeleteProgram(program)
glctx.DeleteBuffer(buf)
fps.Release()
images.Release()
}
func onPaint(glctx gl.Context, sz size.Event) {
glctx.ClearColor(1, 0, 0, 1)
glctx.Clear(gl.COLOR_BUFFER_BIT)
glctx.UseProgram(program)
green += 0.01
if green > 1 {
green = 0
}
glctx.Uniform4f(color, 0, green, 0, 1)
glctx.Uniform2f(offset, touchX/float32(sz.WidthPx), touchY/float32(sz.HeightPx))
glctx.BindBuffer(gl.ARRAY_BUFFER, buf)
glctx.EnableVertexAttribArray(position)
glctx.VertexAttribPointer(position, coordsPerVertex, gl.FLOAT, false, 0, 0)
glctx.DrawArrays(gl.TRIANGLES, 0, vertexCount)
glctx.DisableVertexAttribArray(position)
fps.Draw(sz)
}
var triangleData = f32.Bytes(binary.LittleEndian,
0.0, 0.4, 0.0, // top left
0.0, 0.0, 0.0, // bottom left
0.4, 0.0, 0.0, // bottom right
)
const (
coordsPerVertex = 3
vertexCount = 3
)
const vertexShader = `#version 100
uniform vec2 offset;
attribute vec4 position;
void main() {
// offset comes in with x/y values between 0 and 1.
// position bounds are -1 to 1.
vec4 offset4 = vec4(2.0*offset.x-1.0, 1.0-2.0*offset.y, 0, 0);
gl_Position = position + offset4;
}`
const fragmentShader = `#version 100
precision mediump float;
uniform vec4 color;
void main() {
gl_FragColor = color;
}`
|
basic
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/example/basic/main_x.go
|
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !darwin && !linux && !windows
package main
func main() {
}
|
bind
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/bind/bind.go
|
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package bind implements a code generator for gobind.
//
// See the documentation on the gobind command for usage details
// and the list of currently supported types.
// (http://godoc.org/golang.org/x/mobile/cmd/gobind)
package bind // import "golang.org/x/mobile/bind"
// TODO(crawshaw): slice support
// TODO(crawshaw): channel support
import (
"bytes"
"go/format"
"go/token"
"go/types"
"io"
)
const gobindPreamble = "// Code generated by gobind. DO NOT EDIT.\n\n"
type (
GeneratorConfig struct {
Writer io.Writer
Fset *token.FileSet
Pkg *types.Package
AllPkg []*types.Package
}
fileType int
)
// GenGo generates a Go stub to support foreign language APIs.
func GenGo(conf *GeneratorConfig) error {
buf := new(bytes.Buffer)
g := &goGen{
Generator: &Generator{
Printer: &Printer{Buf: buf, IndentEach: []byte("\t")},
Fset: conf.Fset,
AllPkg: conf.AllPkg,
Pkg: conf.Pkg,
},
}
g.Init()
if err := g.gen(); err != nil {
return err
}
src := buf.Bytes()
srcf, err := format.Source(src)
if err != nil {
conf.Writer.Write(src) // for debugging
return err
}
_, err = conf.Writer.Write(srcf)
return err
}
|
bind
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/bind/genobjcw.go
|
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package bind
import (
"path"
"strings"
"golang.org/x/mobile/internal/importers/objc"
)
type (
// ObjCWrapper generates Go and C stubs for ObjC interfaces and protocols.
ObjcWrapper struct {
*Printer
imported map[string]*objc.Named
// The list of ObjC types.
types []*objc.Named
// The list of Go package paths with ObjC wrappers.
pkgNames []string
modules []string
// For each ObjC module, the list of ObjC types within.
modMap map[string][]*objc.Named
// For each module/name Go package path, the ObjC type
// with static functions or constants.
typePkgs map[string]*objc.Named
// supers is the map of types that need Super methods.
supers map[string]struct{}
}
)
// Init initializes the ObjC types wrapper generator. Types is the
// list of types to wrap, genNames the list of generated type names.
func (g *ObjcWrapper) Init(types []*objc.Named, genNames []string) {
g.supers = make(map[string]struct{})
for _, s := range genNames {
g.supers[s] = struct{}{}
}
g.types = types
g.imported = make(map[string]*objc.Named)
g.modMap = make(map[string][]*objc.Named)
g.typePkgs = make(map[string]*objc.Named)
pkgSet := make(map[string]struct{})
for _, n := range types {
g.imported[n.GoName] = n
typePkg := n.Module + "/" + n.GoName
g.typePkgs[typePkg] = n
if !n.Generated {
if _, exists := g.modMap[n.Module]; !exists {
g.modules = append(g.modules, n.Module)
}
}
g.modMap[n.Module] = append(g.modMap[n.Module], n)
if _, exists := pkgSet[n.Module]; !exists {
pkgSet[n.Module] = struct{}{}
g.pkgNames = append(g.pkgNames, n.Module)
}
g.pkgNames = append(g.pkgNames, typePkg)
}
}
func (g *ObjcWrapper) GenM() {
g.Printf(gobindPreamble)
// For objc_msgSend* functions.
g.Printf("@import ObjectiveC.message;\n")
g.Printf("#include \"seq.h\"\n")
g.Printf("#include \"interfaces.h\"\n\n")
for _, n := range g.types {
g.genM(n)
}
g.Printf("\n")
for _, n := range g.types {
for _, f := range n.AllMethods {
if !g.isFuncSupported(f) {
continue
}
g.genCFuncDecl("cproxy", n.GoName, f)
g.genCFuncBody(n, f, false)
if _, exists := g.supers[n.GoName]; exists {
g.genCFuncDecl("csuper", n.GoName, f)
g.genCFuncBody(n, f, true)
}
}
}
}
func (g *ObjcWrapper) genCFuncBody(n *objc.Named, f *objc.Func, super bool) {
g.Printf(" {\n")
g.Indent()
if !f.Static {
g.Printf("%s _this = go_seq_from_refnum(this).obj;\n", n.ObjcType())
}
var errParam *objc.Param
for i, a := range f.Params {
if i == len(f.Params)-1 && g.isErrorType(a.Type) {
errParam = a
break
}
g.genCToObjC(a.Name, a.Type, modeTransient)
}
if errParam != nil {
g.Printf("NSError *%s = nil;\n", errParam.Name)
}
if f.Constructor {
g.Printf("%s _this = [%s alloc];\n", n.ObjcType(), n.Name)
}
if super {
g.Printf("struct objc_super _super = {\n")
g.Printf(" .receiver = _this,\n")
g.Printf(" .super_class = class_getSuperclass([%s class]),\n", n.Name)
g.Printf("};\n")
}
retType := "void"
if f.Ret != nil {
retType = g.objcType(f.Ret)
g.Printf("%s res = ", retType)
}
// There is no direct way to send a message to a class' super
// class from outside the class itself. Use objc_msgSendSuper instead
// which is what the compiler uses itself. To keep us honest and to exercise
// the code paths more use objc_msgSend for regular calls as well.
//
// A regular call looks like this:
//
// res = ((<return type> (*)(id, SEL, <argument_types>))objc_msgSend)(_this, @selector(...), <arguments>)
//
// a call to super looks like this:
//
// ret = ((<return type> (*)(id, SEL, <argument_types>))objc_msgSendSuper)(<struct objc_super>, <arguments>)
if f.Ret != nil {
switch f.Ret.Kind {
case objc.String, objc.Bool, objc.Data, objc.Int, objc.Uint, objc.Short, objc.Ushort, objc.Char, objc.Uchar, objc.Float, objc.Double, objc.Class, objc.Protocol:
default:
// If support for struct results is added, objc_msgSend_stret must be used
panic("unsupported type kind - use objc_msgSend_stret?")
}
}
g.Printf("((%s (*)(", retType)
if super {
g.Printf("struct objc_super *")
} else {
g.Printf("id")
}
g.Printf(", SEL")
for _, a := range f.Params {
g.Printf(", %s", g.objcType(a.Type))
}
g.Printf("))")
if super {
g.Printf("objc_msgSendSuper")
} else {
g.Printf("objc_msgSend")
}
g.Printf(")(")
if f.Static && !f.Constructor {
g.Printf("[%s class]", n.Name)
} else {
if super {
g.Printf("&_super")
} else {
g.Printf("_this")
}
}
g.Printf(", @selector(%s)", f.Sig)
for _, a := range f.Params {
arg := "_" + a.Name
if a == errParam {
arg = "&" + a.Name
}
g.Printf(", %s", arg)
}
g.Printf(");\n")
if errParam != nil {
g.Printf("NSError *_%s = nil;\n", errParam.Name)
if f.Ret != nil {
g.Printf("if (!res && %s != nil) {\n", errParam.Name)
} else {
g.Printf("if (%s != nil) {\n", errParam.Name)
}
g.Printf(" _%[1]s = %[1]s;\n", errParam.Name)
g.Printf("}\n")
g.genObjCToC("_"+errParam.Name, g.errType(), modeRetained)
}
ret := f.Ret
if ret != nil && ret.Kind == objc.Bool && errParam != nil {
ret = nil
}
if ret != nil {
g.genObjCToC("res", ret, modeRetained)
}
switch {
case ret != nil && errParam != nil:
stype := strings.Replace(g.cType(ret), " ", "_", -1)
g.Printf("ret_%s _sres = {_res, __%s};\n", stype, errParam.Name)
g.Printf("return _sres;\n")
case ret != nil:
g.Printf("return _res;\n")
case errParam != nil:
g.Printf("return __%s;\n", errParam.Name)
}
g.Outdent()
g.Printf("}\n\n")
}
func (_ *ObjcWrapper) errType() *objc.Type {
return &objc.Type{Kind: objc.Class, Name: "NSError"}
}
func (g *ObjcWrapper) genM(n *objc.Named) {
for _, f := range n.Funcs {
if !g.isFuncSupported(f) {
continue
}
g.genCFuncDecl("cproxy", n.GoName, f)
g.genCFuncBody(n, f, false)
}
}
func (g *ObjcWrapper) GenH() {
g.Printf(gobindPreamble)
g.Printf("#include \"seq.h\"\n\n")
for _, m := range g.modules {
g.Printf("@import %s;\n", m)
}
// Include header files for generated types
for _, n := range g.pkgNames {
hasGen := false
for _, t := range g.modMap[n] {
if t.Generated {
hasGen = true
break
}
}
if hasGen {
g.Printf("#import %q\n", n+".objc.h")
}
}
for _, tn := range []string{"int", "nstring", "nbyteslice", "long", "unsigned long", "short", "unsigned short", "bool", "char", "unsigned char", "float", "double"} {
sn := strings.Replace(tn, " ", "_", -1)
g.Printf("typedef struct ret_%s {\n", sn)
g.Printf(" %s res;\n", tn)
g.Printf(" int err;\n")
g.Printf("} ret_%s;\n", sn)
}
g.Printf("\n")
for _, n := range g.types {
for _, f := range n.AllMethods {
if !g.isFuncSupported(f) {
continue
}
g.Printf("extern ")
g.genCFuncDecl("cproxy", n.GoName, f)
g.Printf(";\n")
if _, exists := g.supers[n.GoName]; exists {
g.Printf("extern ")
g.genCFuncDecl("csuper", n.GoName, f)
g.Printf(";\n")
}
}
}
for _, cls := range g.types {
g.genH(cls)
}
}
func (g *ObjcWrapper) genH(n *objc.Named) {
for _, f := range n.Funcs {
if !g.isFuncSupported(f) {
continue
}
g.Printf("extern ")
g.genCFuncDecl("cproxy", n.GoName, f)
g.Printf(";\n")
}
}
func (g *ObjcWrapper) genCFuncDecl(prefix, name string, f *objc.Func) {
returnsErr := len(f.Params) > 0 && g.isErrorType(f.Params[len(f.Params)-1].Type)
ret := f.Ret
if ret != nil && returnsErr && ret.Kind == objc.Bool {
ret = nil
}
switch {
case ret != nil && returnsErr:
g.Printf("ret_%s", strings.Replace(g.cType(ret), " ", "_", -1))
case ret != nil:
g.Printf(g.cType(ret))
case returnsErr:
g.Printf("int")
default:
g.Printf("void")
}
g.Printf(" ")
g.Printf(prefix)
if f.Static {
g.Printf("_s")
}
g.Printf("_%s_%s(", name, f.GoName)
if !f.Static {
g.Printf("int this")
}
for i, p := range f.Params {
if i == len(f.Params)-1 && returnsErr {
break
}
if !f.Static || i > 0 {
g.Printf(", ")
}
g.Printf("%s %s", g.cType(p.Type), p.Name)
}
g.Printf(")")
}
func (g *ObjcWrapper) GenGo() {
g.Printf(gobindPreamble)
g.Printf("package main\n\n")
g.Printf("// #include \"interfaces.h\"\n")
g.Printf("import \"C\"\n\n")
g.Printf("import \"ObjC\"\n")
g.Printf("import _seq \"golang.org/x/mobile/bind/seq\"\n")
for _, n := range g.types {
for _, f := range n.Funcs {
if g.isFuncSupported(f) {
pkgName := n.Module + "/" + n.GoName
g.Printf("import %q\n", "ObjC/"+pkgName)
break
}
}
}
g.Printf("\n")
g.Printf("type proxy interface { Bind_proxy_refnum__() int32 }\n\n")
g.Printf("// Suppress unused package error\n\n")
g.Printf("var _ = _seq.FromRefNum\n")
g.Printf("const _ = ObjC.Dummy\n\n")
for _, n := range g.types {
g.genGo(n)
}
}
func (g *ObjcWrapper) genGo(n *objc.Named) {
g.Printf("func init() {\n")
g.Indent()
for _, f := range n.Funcs {
if !g.isFuncSupported(f) {
continue
}
g.Printf("%s.%s = func", n.GoName, f.GoName)
g.genFuncDecl(false, f)
g.genFuncBody(n, f, "cproxy")
}
g.Outdent()
g.Printf("}\n\n")
g.Printf("type proxy_class_%s _seq.Ref\n\n", n.GoName)
g.Printf("func (p *proxy_class_%s) Bind_proxy_refnum__() int32 { return (*_seq.Ref)(p).Bind_IncNum() }\n\n", n.GoName)
for _, f := range n.AllMethods {
if !g.isFuncSupported(f) {
continue
}
g.Printf("func (p *proxy_class_%s) %s", n.GoName, f.GoName)
g.genFuncDecl(false, f)
g.genFuncBody(n, f, "cproxy")
}
if _, exists := g.supers[n.GoName]; exists {
g.Printf("func (p *proxy_class_%s) Super() ObjC.%s {\n", n.GoName, n.Module+"_"+n.GoName)
g.Printf(" return &super_%s{p}\n", n.GoName)
g.Printf("}\n\n")
g.Printf("type super_%s struct {*proxy_class_%[1]s}\n\n", n.GoName)
for _, f := range n.AllMethods {
if !g.isFuncSupported(f) {
continue
}
g.Printf("func (p *super_%s) %s", n.GoName, f.GoName)
g.genFuncDecl(false, f)
g.genFuncBody(n, f, "csuper")
}
}
}
func (g *ObjcWrapper) genFuncBody(n *objc.Named, f *objc.Func, prefix string) {
g.Printf(" {\n")
g.Indent()
var errParam *objc.Param
for i, a := range f.Params {
if i == len(f.Params)-1 && g.isErrorType(a.Type) {
errParam = a
break
}
g.genWrite(a)
}
ret := f.Ret
if ret != nil && errParam != nil && ret.Kind == objc.Bool {
ret = nil
}
if ret != nil || errParam != nil {
g.Printf("res := ")
}
g.Printf("C.")
g.Printf(prefix)
if f.Static {
g.Printf("_s")
}
g.Printf("_%s_%s(", n.GoName, f.GoName)
if !f.Static {
g.Printf("C.int(p.Bind_proxy_refnum__())")
}
for i, a := range f.Params {
if a == errParam {
break
}
if !f.Static || i > 0 {
g.Printf(", ")
}
g.Printf("_%s", a.Name)
}
g.Printf(")\n")
switch {
case ret != nil && errParam != nil:
g.genRead("_res", "res.res", ret)
g.genRefRead("_"+errParam.Name, "res.err", "error", "proxy_error")
g.Printf("return _res, _%s\n", errParam.Name)
case ret != nil:
g.genRead("_res", "res", ret)
g.Printf("return _res\n")
case errParam != nil:
g.genRefRead("_"+errParam.Name, "res", "error", "proxy_error")
g.Printf("return _%s\n", errParam.Name)
}
g.Outdent()
g.Printf("}\n\n")
}
func (g *ObjcWrapper) genCToObjC(name string, t *objc.Type, mode varMode) {
switch t.Kind {
case objc.String:
g.Printf("NSString *_%s = go_seq_to_objc_string(%s);\n", name, name)
case objc.Bool:
g.Printf("BOOL _%s = %s ? YES : NO;\n", name, name)
case objc.Data:
g.Printf("NSData *_%s = go_seq_to_objc_bytearray(%s, %d);\n", name, name, toCFlag(mode == modeRetained))
case objc.Int, objc.Uint, objc.Short, objc.Ushort, objc.Char, objc.Uchar, objc.Float, objc.Double:
g.Printf("%s _%s = (%s)%s;\n", g.objcType(t), name, g.objcType(t), name)
case objc.Class, objc.Protocol:
g.Printf("GoSeqRef* %s_ref = go_seq_from_refnum(%s);\n", name, name)
g.Printf("%s _%s;\n", g.objcType(t), name)
g.Printf("if (%s_ref != NULL) {\n", name)
g.Printf(" _%s = %s_ref.obj;\n", name, name)
g.Printf("}\n")
default:
panic("invalid kind")
}
}
func (g *ObjcWrapper) genObjCToC(name string, t *objc.Type, mode varMode) {
switch t.Kind {
case objc.String:
g.Printf("nstring _%s = go_seq_from_objc_string(%s);\n", name, name)
case objc.Data:
g.Printf("nbyteslice _%s = go_seq_from_objc_bytearray(%s, %d);\n", name, name, toCFlag(mode == modeRetained))
case objc.Bool, objc.Int, objc.Uint, objc.Short, objc.Ushort, objc.Char, objc.Uchar, objc.Float, objc.Double:
g.Printf("%s _%s = (%s)%s;\n", g.cType(t), name, g.cType(t), name)
case objc.Protocol, objc.Class:
g.Printf("int _%s = go_seq_to_refnum(%s);\n", name, name)
default:
panic("invalid kind")
}
}
func (g *ObjcWrapper) genWrite(a *objc.Param) {
switch a.Type.Kind {
case objc.String:
g.Printf("_%s := encodeString(%s)\n", a.Name, a.Name)
case objc.Data:
g.Printf("_%s := fromSlice(%s, false)\n", a.Name, a.Name)
case objc.Bool:
g.Printf("_%s := %s(0)\n", a.Name, g.cgoType(a.Type))
g.Printf("if %s {\n", a.Name)
g.Printf(" _%s = %s(1)\n", a.Name, g.cgoType(a.Type))
g.Printf("}\n")
case objc.Int, objc.Uint, objc.Short, objc.Ushort, objc.Char, objc.Uchar, objc.Float, objc.Double:
g.Printf("_%s := %s(%s)\n", a.Name, g.cgoType(a.Type), a.Name)
case objc.Protocol, objc.Class:
g.Printf("var _%s %s = _seq.NullRefNum\n", a.Name, g.cgoType(a.Type))
g.Printf("if %s != nil {\n", a.Name)
g.Printf(" _%s = %s(_seq.ToRefNum(%s))\n", a.Name, g.cgoType(a.Type), a.Name)
g.Printf("}\n")
default:
panic("invalid kind")
}
}
func (g *ObjcWrapper) genRead(to, from string, t *objc.Type) {
switch t.Kind {
case objc.Int, objc.Uint, objc.Uchar, objc.Short, objc.Ushort, objc.Char, objc.Float, objc.Double:
g.Printf("%s := %s(%s)\n", to, g.goType(t, false), from)
case objc.Bool:
g.Printf("%s := %s != 0\n", to, from)
case objc.String:
g.Printf("%s := decodeString(%s)\n", to, from)
case objc.Data:
g.Printf("%s := toSlice(%s, true)\n", to, from)
case objc.Protocol, objc.Class:
var proxyName string
if n := g.lookupImported(t); n != nil {
proxyName = "proxy_class_" + n.GoName
}
g.genRefRead(to, from, g.goType(t, false), proxyName)
default:
panic("invalid kind")
}
}
func (g *ObjcWrapper) genRefRead(to, from string, intfName, proxyName string) {
g.Printf("var %s %s\n", to, intfName)
g.Printf("%s_ref := _seq.FromRefNum(int32(%s))\n", to, from)
g.Printf("if %s_ref != nil {\n", to)
g.Printf(" if %s < 0 { // go object\n", from)
g.Printf(" %s = %s_ref.Get().(%s)\n", to, to, intfName)
if proxyName != "" {
g.Printf(" } else { // foreign object\n")
g.Printf(" %s = (*%s)(%s_ref)\n", to, proxyName, to)
}
g.Printf(" }\n")
g.Printf("}\n")
}
// Packages return the list of Go packages to be generated.
func (g *ObjcWrapper) Packages() []string {
return g.pkgNames
}
func (g *ObjcWrapper) GenPackage(idx int) {
pkg := g.pkgNames[idx]
g.Printf(gobindPreamble)
g.Printf("package %s\n\n", path.Base(pkg))
g.Printf("import \"ObjC\"\n\n")
g.Printf("const _ = ObjC.Dummy\n\n")
for _, n := range g.modMap[pkg] {
g.Printf("type %s ObjC.%s\n", n.GoName, n.Module+"_"+n.GoName)
}
if n, ok := g.typePkgs[pkg]; ok {
g.Printf("var (\n")
g.Indent()
// Functions
for _, f := range n.Funcs {
if !g.isFuncSupported(f) {
continue
}
g.Printf("%s func", f.GoName)
g.genFuncDecl(false, f)
g.Printf("\n")
}
g.Outdent()
g.Printf(")\n\n")
}
}
func (g *ObjcWrapper) GenInterfaces() {
g.Printf(gobindPreamble)
g.Printf("package ObjC\n\n")
g.Printf("// Used to silence this package not used errors\n")
g.Printf("const Dummy = 0\n\n")
for _, n := range g.types {
g.genInterface(n)
}
}
func (g *ObjcWrapper) genInterface(n *objc.Named) {
g.Printf("type %s interface {\n", n.Module+"_"+n.GoName)
g.Indent()
// Methods
for _, f := range n.AllMethods {
if !g.isFuncSupported(f) {
continue
}
g.Printf(f.GoName)
g.genFuncDecl(true, f)
g.Printf("\n")
}
if _, exists := g.supers[n.GoName]; exists {
g.Printf("Super() %s\n", n.Module+"_"+n.GoName)
}
g.Outdent()
g.Printf("}\n\n")
}
func (g *ObjcWrapper) genFuncDecl(local bool, f *objc.Func) {
var returnsErr bool
g.Printf("(")
for i, p := range f.Params {
if i == len(f.Params)-1 && g.isErrorType(p.Type) {
returnsErr = true
break
}
if i > 0 {
g.Printf(", ")
}
g.Printf("%s %s", p.Name, g.goType(p.Type, local))
}
g.Printf(")")
if f.Ret != nil || returnsErr {
ret := f.Ret
if ret.Kind == objc.Bool && returnsErr {
// Skip the bool result and use the error results.
ret = nil
}
if ret != nil {
g.Printf(" (%s", g.goType(f.Ret, local))
if returnsErr {
g.Printf(", error")
}
g.Printf(")")
} else {
g.Printf(" error")
}
}
}
func (g *ObjcWrapper) isFuncSupported(f *objc.Func) bool {
for i, p := range f.Params {
if !g.isSupported(p.Type) {
if i < len(f.Params)-1 || !g.isErrorType(p.Type) {
return false
}
}
}
if f.Ret != nil {
return g.isSupported(f.Ret)
}
return true
}
func (g *ObjcWrapper) isErrorType(t *objc.Type) bool {
// Must be a NSError ** type
return t.Kind == objc.Class && t.Indirect && t.Name == "NSError"
}
func (g *ObjcWrapper) isSupported(t *objc.Type) bool {
if t.Indirect {
return false
}
switch t.Kind {
case objc.Unknown:
return false
case objc.Protocol:
// TODO: support inout parameters.
return !strings.HasSuffix(t.Decl, " *")
case objc.Class:
return t.Name != "SEL" && t.Name != "void"
default:
return true
}
}
func (g *ObjcWrapper) cgoType(t *objc.Type) string {
switch t.Kind {
case objc.Uint:
return "C.ulong"
case objc.Ushort:
return "C.ushort"
case objc.Uchar:
return "C.uchar"
default:
return "C." + g.cType(t)
}
}
func (g *ObjcWrapper) cType(t *objc.Type) string {
switch t.Kind {
case objc.Protocol, objc.Class:
return "int"
case objc.String:
return "nstring"
case objc.Data:
return "nbyteslice"
case objc.Int:
return "long"
case objc.Uint:
return "unsigned long"
case objc.Short:
return "short"
case objc.Ushort:
return "unsigned short"
case objc.Bool:
return "char"
case objc.Char:
return "char"
case objc.Uchar:
return "unsigned char"
case objc.Float:
return "float"
case objc.Double:
return "double"
default:
panic("invalid kind")
}
}
func (g *ObjcWrapper) objcType(t *objc.Type) string {
return t.Decl
}
func (g *ObjcWrapper) lookupImported(t *objc.Type) *objc.Named {
var mangled string
switch t.Kind {
case objc.Class:
mangled = t.Name + "C"
case objc.Protocol:
mangled = t.Name + "P"
default:
panic("invalid type kind")
}
if n, exists := g.imported[mangled]; exists {
return n
}
return g.imported[t.Name]
}
func (g *ObjcWrapper) goType(t *objc.Type, local bool) string {
switch t.Kind {
case objc.String:
return "string"
case objc.Data:
return "[]byte"
case objc.Int:
return "int"
case objc.Uint:
return "uint"
case objc.Short:
return "int16"
case objc.Ushort:
return "uint16"
case objc.Bool:
return "bool"
case objc.Char:
return "byte"
case objc.Uchar:
return "uint8"
case objc.Float:
return "float32"
case objc.Double:
return "float64"
case objc.Protocol, objc.Class:
var n *objc.Named
n = g.lookupImported(t)
name := n.Module + "_" + n.GoName
if !local {
name = "ObjC." + name
}
return name
default:
panic("invalid kind")
}
}
|
bind
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/bind/implicit.go
|
// This file imports implicit dependencies required by generated code.
//go:build mobile_implicit
package bind
import (
_ "golang.org/x/mobile/bind/seq"
)
|
bind
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/bind/genclasses.go
|
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package bind
import (
"fmt"
"path"
"reflect"
"strings"
"unicode"
"unicode/utf8"
"golang.org/x/mobile/internal/importers"
"golang.org/x/mobile/internal/importers/java"
)
type (
// ClassGen generates Go and C stubs for Java classes so import statements
// on the form
//
//
// import "Java/classpath/to/Class"
//
// will work.
ClassGen struct {
*Printer
// JavaPkg is the Java package prefix for the generated classes. The prefix is prepended to the Go
// package name to create the full Java package name.
JavaPkg string
imported map[string]struct{}
// The list of imported Java classes
classes []*java.Class
// The list of Go package paths with Java interfaces inside
jpkgs []string
// For each Go package path, the list of Java classes.
typePkgs map[string][]*java.Class
// For each Go package path, the Java class with static functions
// or constants.
clsPkgs map[string]*java.Class
// goClsMap is the map of Java class names to Go type names, qualified with package name. Go types
// that implement Java classes need Super methods and Unwrap methods.
goClsMap map[string]string
// goClsImports is the list of imports of user packages that contains the Go types implementing Java
// classes.
goClsImports []string
}
)
func (g *ClassGen) isSupported(t *java.Type) bool {
switch t.Kind {
case java.Array:
// TODO: Support all array types
return t.Elem.Kind == java.Byte
default:
return true
}
}
func (g *ClassGen) isFuncSetSupported(fs *java.FuncSet) bool {
for _, f := range fs.Funcs {
if g.isFuncSupported(f) {
return true
}
}
return false
}
func (g *ClassGen) isFuncSupported(f *java.Func) bool {
for _, a := range f.Params {
if !g.isSupported(a) {
return false
}
}
if f.Ret != nil {
return g.isSupported(f.Ret)
}
return true
}
func (g *ClassGen) goType(t *java.Type, local bool) string {
if t == nil {
// interface{} is used for parameters types for overloaded methods
// where no common ancestor type exists.
return "interface{}"
}
switch t.Kind {
case java.Int:
return "int32"
case java.Boolean:
return "bool"
case java.Short:
return "int16"
case java.Char:
return "uint16"
case java.Byte:
return "byte"
case java.Long:
return "int64"
case java.Float:
return "float32"
case java.Double:
return "float64"
case java.String:
return "string"
case java.Array:
return "[]" + g.goType(t.Elem, local)
case java.Object:
name := goClsName(t.Class)
if !local {
name = "Java." + name
}
return name
default:
panic("invalid kind")
}
}
// Init initializes the class wrapper generator. Classes is the
// list of classes to wrap, goClasses is the list of Java classes
// implemented in Go.
func (g *ClassGen) Init(classes []*java.Class, goClasses []importers.Struct) {
g.goClsMap = make(map[string]string)
impMap := make(map[string]struct{})
for _, s := range goClasses {
n := s.Pkg + "." + s.Name
jn := n
if g.JavaPkg != "" {
jn = g.JavaPkg + "." + jn
}
g.goClsMap[jn] = n
if _, exists := impMap[s.PkgPath]; !exists {
impMap[s.PkgPath] = struct{}{}
g.goClsImports = append(g.goClsImports, s.PkgPath)
}
}
g.classes = classes
g.imported = make(map[string]struct{})
g.typePkgs = make(map[string][]*java.Class)
g.clsPkgs = make(map[string]*java.Class)
pkgSet := make(map[string]struct{})
for _, cls := range classes {
g.imported[cls.Name] = struct{}{}
clsPkg := strings.Replace(cls.Name, ".", "/", -1)
g.clsPkgs[clsPkg] = cls
typePkg := path.Dir(clsPkg)
g.typePkgs[typePkg] = append(g.typePkgs[typePkg], cls)
if _, exists := pkgSet[clsPkg]; !exists {
pkgSet[clsPkg] = struct{}{}
g.jpkgs = append(g.jpkgs, clsPkg)
}
if _, exists := pkgSet[typePkg]; !exists {
pkgSet[typePkg] = struct{}{}
g.jpkgs = append(g.jpkgs, typePkg)
}
}
}
// Packages return the list of Go packages to be generated.
func (g *ClassGen) Packages() []string {
return g.jpkgs
}
func (g *ClassGen) GenPackage(idx int) {
jpkg := g.jpkgs[idx]
g.Printf(gobindPreamble)
g.Printf("package %s\n\n", path.Base(jpkg))
g.Printf("import \"Java\"\n\n")
g.Printf("const _ = Java.Dummy\n\n")
for _, cls := range g.typePkgs[jpkg] {
g.Printf("type %s Java.%s\n", cls.PkgName, goClsName(cls.Name))
}
if cls, ok := g.clsPkgs[jpkg]; ok {
g.Printf("const (\n")
g.Indent()
// Constants
for _, v := range cls.Vars {
if g.isSupported(v.Type) && v.Constant() {
g.Printf("%s = %s\n", initialUpper(v.Name), v.Val)
}
}
g.Outdent()
g.Printf(")\n\n")
g.Printf("var (\n")
g.Indent()
// Functions
loop:
for _, fs := range cls.Funcs {
for _, f := range fs.Funcs {
if f.Public && g.isFuncSupported(f) {
g.Printf("%s func", fs.GoName)
g.genFuncDecl(false, fs)
g.Printf("\n")
continue loop
}
}
}
g.Printf("// Cast takes a proxy for a Java object and converts it to a %s proxy.\n", cls.Name)
g.Printf("// Cast panics if the argument is not a proxy or if the underlying object does\n")
g.Printf("// not extend or implement %s.\n", cls.Name)
g.Printf("Cast func(v interface{}) Java.%s\n", goClsName(cls.Name))
g.Outdent()
g.Printf(")\n\n")
}
}
func (g *ClassGen) GenGo() {
g.Printf(classesGoHeader)
for _, cls := range g.classes {
pkgName := strings.Replace(cls.Name, ".", "/", -1)
g.Printf("import %q\n", "Java/"+pkgName)
}
for _, imp := range g.goClsImports {
g.Printf("import %q\n", imp)
}
if len(g.classes) > 0 {
g.Printf("import \"unsafe\"\n\n")
g.Printf("import \"reflect\"\n\n")
g.Printf("import \"fmt\"\n\n")
}
g.Printf("type proxy interface { Bind_proxy_refnum__() int32 }\n\n")
g.Printf("// Suppress unused package error\n\n")
g.Printf("var _ = _seq.FromRefNum\n")
g.Printf("const _ = Java.Dummy\n\n")
g.Printf("//export initClasses\n")
g.Printf("func initClasses() {\n")
g.Indent()
g.Printf("C.init_proxies()\n")
for _, cls := range g.classes {
g.Printf("init_%s()\n", cls.JNIName)
}
g.Outdent()
g.Printf("}\n\n")
for _, cls := range g.classes {
g.genGo(cls)
}
}
func (g *ClassGen) GenH() {
g.Printf(classesHHeader)
for _, tn := range []string{"jint", "jboolean", "jshort", "jchar", "jbyte", "jlong", "jfloat", "jdouble", "nstring", "nbyteslice"} {
g.Printf("typedef struct ret_%s {\n", tn)
g.Printf(" %s res;\n", tn)
g.Printf(" jint exc;\n")
g.Printf("} ret_%s;\n", tn)
}
g.Printf("\n")
for _, cls := range g.classes {
for _, fs := range cls.AllMethods {
for _, f := range fs.Funcs {
if !g.isFuncSupported(f) {
continue
}
g.Printf("extern ")
g.genCMethodDecl("cproxy", cls.JNIName, f)
g.Printf(";\n")
if _, ok := g.goClsMap[cls.Name]; ok {
g.Printf("extern ")
g.genCMethodDecl("csuper", cls.JNIName, f)
g.Printf(";\n")
}
}
}
}
for _, cls := range g.classes {
g.genH(cls)
}
}
func (g *ClassGen) GenC() {
g.Printf(classesCHeader)
for _, cls := range g.classes {
g.Printf("static jclass class_%s;\n", cls.JNIName)
if _, ok := g.goClsMap[cls.Name]; ok {
g.Printf("static jclass sclass_%s;\n", cls.JNIName)
}
for _, fs := range cls.Funcs {
for _, f := range fs.Funcs {
if !f.Public || !g.isFuncSupported(f) {
continue
}
g.Printf("static jmethodID m_s_%s_%s;\n", cls.JNIName, f.JNIName)
}
}
for _, fs := range cls.AllMethods {
for _, f := range fs.Funcs {
if g.isFuncSupported(f) {
g.Printf("static jmethodID m_%s_%s;\n", cls.JNIName, f.JNIName)
if _, ok := g.goClsMap[cls.Name]; ok {
g.Printf("static jmethodID sm_%s_%s;\n", cls.JNIName, f.JNIName)
}
}
}
}
g.genC(cls)
}
g.Printf("\n")
g.Printf("void init_proxies() {\n")
g.Indent()
g.Printf("JNIEnv *env = go_seq_push_local_frame(%d);\n", len(g.classes))
g.Printf("jclass clazz;\n")
for _, cls := range g.classes {
g.Printf("clazz = go_seq_find_class(%q);\n", strings.Replace(cls.FindName, ".", "/", -1))
g.Printf("if (clazz != NULL) {\n")
g.Indent()
g.Printf("class_%s = (*env)->NewGlobalRef(env, clazz);\n", cls.JNIName)
if _, ok := g.goClsMap[cls.Name]; ok {
g.Printf("sclass_%s = (*env)->GetSuperclass(env, clazz);\n", cls.JNIName)
g.Printf("sclass_%s = (*env)->NewGlobalRef(env, sclass_%s);\n", cls.JNIName, cls.JNIName)
}
for _, fs := range cls.Funcs {
for _, f := range fs.Funcs {
if !f.Public || !g.isFuncSupported(f) {
continue
}
g.Printf("m_s_%s_%s = ", cls.JNIName, f.JNIName)
if f.Constructor {
g.Printf("go_seq_get_method_id(clazz, \"<init>\", %q);\n", f.Desc)
} else {
g.Printf("go_seq_get_static_method_id(clazz, %q, %q);\n", f.Name, f.Desc)
}
}
}
for _, fs := range cls.AllMethods {
for _, f := range fs.Funcs {
if g.isFuncSupported(f) {
g.Printf("m_%s_%s = go_seq_get_method_id(clazz, %q, %q);\n", cls.JNIName, f.JNIName, f.Name, f.Desc)
if _, ok := g.goClsMap[cls.Name]; ok {
g.Printf("sm_%s_%s = go_seq_get_method_id(sclass_%s, %q, %q);\n", cls.JNIName, f.JNIName, cls.JNIName, f.Name, f.Desc)
}
}
}
}
g.Outdent()
g.Printf("}\n")
}
g.Printf("go_seq_pop_local_frame(env);\n")
g.Outdent()
g.Printf("}\n\n")
for _, cls := range g.classes {
for _, fs := range cls.AllMethods {
for _, f := range fs.Funcs {
if !g.isFuncSupported(f) {
continue
}
g.genCMethodDecl("cproxy", cls.JNIName, f)
g.genCMethodBody(cls, f, false)
if _, ok := g.goClsMap[cls.Name]; ok {
g.genCMethodDecl("csuper", cls.JNIName, f)
g.genCMethodBody(cls, f, true)
}
}
}
}
}
func (g *ClassGen) GenInterfaces() {
g.Printf(classesPkgHeader)
for _, cls := range g.classes {
g.genInterface(cls)
}
}
func (g *ClassGen) genCMethodBody(cls *java.Class, f *java.Func, virtual bool) {
g.Printf(" {\n")
g.Indent()
// Add 1 for the 'this' argument
g.Printf("JNIEnv *env = go_seq_push_local_frame(%d);\n", len(f.Params)+1)
g.Printf("// Must be a Java object\n")
g.Printf("jobject _this = go_seq_from_refnum(env, this, NULL, NULL);\n")
for i, a := range f.Params {
g.genCToJava(fmt.Sprintf("a%d", i), a)
}
if f.Ret != nil {
g.Printf("%s res = ", f.Ret.JNIType())
}
g.Printf("(*env)->Call")
if virtual {
g.Printf("Nonvirtual")
}
if f.Ret != nil {
g.Printf(f.Ret.JNICallType())
} else {
g.Printf("Void")
}
g.Printf("Method(env, _this, ")
if virtual {
g.Printf("sclass_%s, sm_%s_%s", cls.JNIName, cls.JNIName, f.JNIName)
} else {
g.Printf("m_%s_%s", cls.JNIName, f.JNIName)
}
for i := range f.Params {
g.Printf(", _a%d", i)
}
g.Printf(");\n")
g.Printf("jobject _exc = go_seq_get_exception(env);\n")
g.Printf("int32_t _exc_ref = go_seq_to_refnum(env, _exc);\n")
if f.Ret != nil {
g.genCRetClear("res", f.Ret, "_exc")
g.genJavaToC("res", f.Ret)
}
g.Printf("go_seq_pop_local_frame(env);\n")
if f.Ret != nil {
g.Printf("ret_%s __res = {_res, _exc_ref};\n", f.Ret.CType())
g.Printf("return __res;\n")
} else {
g.Printf("return _exc_ref;\n")
}
g.Outdent()
g.Printf("}\n\n")
}
func initialUpper(s string) string {
if s == "" {
return ""
}
r, n := utf8.DecodeRuneInString(s)
return string(unicode.ToUpper(r)) + s[n:]
}
func (g *ClassGen) genFuncDecl(local bool, fs *java.FuncSet) {
g.Printf("(")
for i, a := range fs.Params {
if i > 0 {
g.Printf(", ")
}
g.Printf("a%d ", i)
if i == len(fs.Params)-1 && fs.Variadic {
g.Printf("...")
}
g.Printf(g.goType(a, local))
}
g.Printf(")")
if fs.Throws {
if fs.HasRet {
g.Printf(" (%s, error)", g.goType(fs.Ret, local))
} else {
g.Printf(" error")
}
} else if fs.HasRet {
g.Printf(" %s", g.goType(fs.Ret, local))
}
}
func (g *ClassGen) genC(cls *java.Class) {
for _, fs := range cls.Funcs {
for _, f := range fs.Funcs {
if !f.Public || !g.isFuncSupported(f) {
continue
}
g.genCFuncDecl(cls.JNIName, f)
g.Printf(" {\n")
g.Indent()
g.Printf("JNIEnv *env = go_seq_push_local_frame(%d);\n", len(f.Params))
for i, a := range f.Params {
g.genCToJava(fmt.Sprintf("a%d", i), a)
}
if f.Constructor {
g.Printf("jobject res = (*env)->NewObject(env")
} else if f.Ret != nil {
g.Printf("%s res = (*env)->CallStatic%sMethod(env", f.Ret.JNIType(), f.Ret.JNICallType())
} else {
g.Printf("(*env)->CallStaticVoidMethod(env")
}
g.Printf(", class_%s, m_s_%s_%s", cls.JNIName, cls.JNIName, f.JNIName)
for i := range f.Params {
g.Printf(", _a%d", i)
}
g.Printf(");\n")
g.Printf("jobject _exc = go_seq_get_exception(env);\n")
g.Printf("int32_t _exc_ref = go_seq_to_refnum(env, _exc);\n")
if f.Ret != nil {
g.genCRetClear("res", f.Ret, "_exc")
g.genJavaToC("res", f.Ret)
}
g.Printf("go_seq_pop_local_frame(env);\n")
if f.Ret != nil {
g.Printf("ret_%s __res = {_res, _exc_ref};\n", f.Ret.CType())
g.Printf("return __res;\n")
} else {
g.Printf("return _exc_ref;\n")
}
g.Outdent()
g.Printf("}\n\n")
}
}
}
func (g *ClassGen) genH(cls *java.Class) {
for _, fs := range cls.Funcs {
for _, f := range fs.Funcs {
if !f.Public || !g.isFuncSupported(f) {
continue
}
g.Printf("extern ")
g.genCFuncDecl(cls.JNIName, f)
g.Printf(";\n")
}
}
}
func (g *ClassGen) genCMethodDecl(prefix, jniName string, f *java.Func) {
if f.Ret != nil {
g.Printf("ret_%s", f.Ret.CType())
} else {
// Return only the exception, if any
g.Printf("jint")
}
g.Printf(" %s_%s_%s(jint this", prefix, jniName, f.JNIName)
for i, a := range f.Params {
g.Printf(", %s a%d", a.CType(), i)
}
g.Printf(")")
}
func (g *ClassGen) genCFuncDecl(jniName string, f *java.Func) {
if f.Ret != nil {
g.Printf("ret_%s", f.Ret.CType())
} else {
// Return only the exception, if any
g.Printf("jint")
}
g.Printf(" cproxy_s_%s_%s(", jniName, f.JNIName)
for i, a := range f.Params {
if i > 0 {
g.Printf(", ")
}
g.Printf("%s a%d", a.CType(), i)
}
g.Printf(")")
}
func (g *ClassGen) genGo(cls *java.Class) {
g.Printf("var class_%s C.jclass\n\n", cls.JNIName)
g.Printf("func init_%s() {\n", cls.JNIName)
g.Indent()
g.Printf("cls := C.CString(%q)\n", strings.Replace(cls.FindName, ".", "/", -1))
g.Printf("clazz := C.go_seq_find_class(cls)\n")
g.Printf("C.free(unsafe.Pointer(cls))\n")
// Before Go 1.11 clazz was a pointer value, an uintptr after.
g.Printf("if uintptr(clazz) == 0 {\n")
g.Printf(" return\n")
g.Printf("}\n")
g.Printf("class_%s = clazz\n", cls.JNIName)
for _, fs := range cls.Funcs {
var supported bool
for _, f := range fs.Funcs {
if f.Public && g.isFuncSupported(f) {
supported = true
break
}
}
if !supported {
continue
}
g.Printf("%s.%s = func", cls.PkgName, fs.GoName)
g.genFuncDecl(false, fs)
g.genFuncBody(cls, fs, "cproxy_s", true)
}
g.Printf("%s.Cast = func(v interface{}) Java.%s {\n", cls.PkgName, goClsName(cls.Name))
g.Indent()
g.Printf("t := reflect.TypeOf((*proxy_class_%s)(nil))\n", cls.JNIName)
g.Printf("cv := reflect.ValueOf(v).Convert(t).Interface().(*proxy_class_%s)\n", cls.JNIName)
g.Printf("ref := C.jint(_seq.ToRefNum(cv))\n")
g.Printf("if C.go_seq_isinstanceof(ref, class_%s) != 1 {\n", cls.JNIName)
g.Printf(" panic(fmt.Errorf(\"%%T is not an instance of %%s\", v, %q))\n", cls.Name)
g.Printf("}\n")
g.Printf("return cv\n")
g.Outdent()
g.Printf("}\n")
g.Outdent()
g.Printf("}\n\n")
g.Printf("type proxy_class_%s _seq.Ref\n\n", cls.JNIName)
g.Printf("func (p *proxy_class_%s) Bind_proxy_refnum__() int32 {\n", cls.JNIName)
g.Indent()
g.Printf("return (*_seq.Ref)(p).Bind_IncNum()\n")
g.Outdent()
g.Printf("}\n\n")
for _, fs := range cls.AllMethods {
if !g.isFuncSetSupported(fs) {
continue
}
g.Printf("func (p *proxy_class_%s) %s", cls.JNIName, fs.GoName)
g.genFuncDecl(false, fs)
g.genFuncBody(cls, fs, "cproxy", false)
}
if cls.Throwable {
g.Printf("func (p *proxy_class_%s) Error() string {\n", cls.JNIName)
g.Printf(" return p.ToString()\n")
g.Printf("}\n")
}
if goName, ok := g.goClsMap[cls.Name]; ok {
g.Printf("func (p *proxy_class_%s) Super() Java.%s {\n", cls.JNIName, goClsName(cls.Name))
g.Printf(" return &super_%s{p}\n", cls.JNIName)
g.Printf("}\n\n")
g.Printf("type super_%s struct {*proxy_class_%[1]s}\n\n", cls.JNIName)
g.Printf("func (p *proxy_class_%s) Unwrap() interface{} {\n", cls.JNIName)
g.Indent()
g.Printf("goRefnum := C.go_seq_unwrap(C.jint(p.Bind_proxy_refnum__()))\n")
g.Printf("return _seq.FromRefNum(int32(goRefnum)).Get().(*%s)\n", goName)
g.Outdent()
g.Printf("}\n\n")
for _, fs := range cls.AllMethods {
if !g.isFuncSetSupported(fs) {
continue
}
g.Printf("func (p *super_%s) %s", cls.JNIName, fs.GoName)
g.genFuncDecl(false, fs)
g.genFuncBody(cls, fs, "csuper", false)
}
}
}
// genFuncBody generated a Go function body for a FuncSet. It resolves overloading dynamically,
// by inspecting the number of arguments (if the FuncSet contains varying parameter counts),
// and their types.
func (g *ClassGen) genFuncBody(cls *java.Class, fs *java.FuncSet, prefix string, static bool) {
maxp := len(fs.Funcs[0].Params)
minp := maxp
// sort the function variants into argument sizes.
buckets := make(map[int][]*java.Func)
numF := 0
for _, f := range fs.Funcs {
if !g.isFuncSupported(f) {
continue
}
numF++
n := len(f.Params)
if n < minp {
minp = n
} else if n > maxp {
maxp = n
}
buckets[n] = append(buckets[n], f)
}
g.Printf(" {\n")
g.Indent()
if len(buckets) != 1 {
// Switch over the number of arguments.
g.Printf("switch %d + len(a%d) {\n", minp, minp)
}
for i := minp; i <= maxp; i++ {
funcs := buckets[i]
if len(funcs) == 0 {
continue
}
if len(buckets) != 1 {
g.Printf("case %d:\n", i)
g.Indent()
}
for _, f := range funcs {
if len(funcs) > 1 {
g.Printf("{\n")
g.Indent()
}
var argNames []string
var preds []string
for i, a := range f.Params {
var ct *java.Type
var argName string
if i >= minp {
argName = fmt.Sprintf("a%d[%d]", minp, i-minp)
ct = fs.Params[minp]
} else {
argName = fmt.Sprintf("a%d", i)
ct = fs.Params[i]
}
if !reflect.DeepEqual(ct, a) {
g.Printf("_a%d, ok%d := %s.(%s)\n", i, i, argName, g.goType(a, false))
argName = fmt.Sprintf("_a%d", i)
preds = append(preds, fmt.Sprintf("ok%d", i))
}
argNames = append(argNames, argName)
}
if len(preds) > 0 {
g.Printf("if %s {\n", strings.Join(preds, " && "))
g.Indent()
}
for i, a := range f.Params {
g.genWrite(fmt.Sprintf("__a%d", i), argNames[i], a, modeTransient)
}
g.Printf("res := C.%s_%s_%s(", prefix, cls.JNIName, f.JNIName)
if !static {
g.Printf("C.jint(p.Bind_proxy_refnum__())")
}
for i := range f.Params {
if !static || i > 0 {
g.Printf(", ")
}
g.Printf("__a%d", i)
}
g.Printf(")\n")
g.genFuncRet(fs, f, numF > 1)
if len(preds) > 0 {
g.Outdent()
g.Printf("}\n")
}
if len(funcs) > 1 {
g.Outdent()
g.Printf("}\n")
}
}
if len(buckets) != 1 {
g.Outdent()
}
}
if len(buckets) != 1 {
g.Printf("}\n")
}
if numF > 1 {
g.Printf("panic(\"no overloaded method found for %s.%s that matched the arguments\")\n", cls.Name, fs.Name)
}
g.Outdent()
g.Printf("}\n\n")
}
func (g *ClassGen) genFuncRet(fs *java.FuncSet, f *java.Func, mustReturn bool) {
if f.Ret != nil {
g.genRead("_res", "res.res", f.Ret, modeRetained)
g.genRefRead("_exc", "res.exc", "error", "proxy_error", true)
} else {
g.genRefRead("_exc", "res", "error", "proxy_error", true)
}
if !fs.Throws {
g.Printf("if (_exc != nil) { panic(_exc) }\n")
if fs.HasRet {
if f.Ret != nil {
g.Printf("return _res\n")
} else {
// The variant doesn't return a value, but the common
// signature does. Use nil as a placeholder return value.
g.Printf("return nil\n")
}
} else if mustReturn {
// If there are overloaded variants, return here to avoid the fallback
// panic generated in genFuncBody.
g.Printf("return\n")
}
} else {
if fs.HasRet {
if f.Ret != nil {
g.Printf("return _res, _exc\n")
} else {
// As above, use a nil placeholder return value.
g.Printf("return nil, _exc\n")
}
} else {
g.Printf("return _exc\n")
}
}
}
func (g *ClassGen) genRead(to, from string, t *java.Type, mode varMode) {
switch t.Kind {
case java.Int, java.Short, java.Char, java.Byte, java.Long, java.Float, java.Double:
g.Printf("%s := %s(%s)\n", to, g.goType(t, false), from)
case java.Boolean:
g.Printf("%s := %s != C.JNI_FALSE\n", to, from)
case java.String:
g.Printf("%s := decodeString(%s)\n", to, from)
case java.Array:
if t.Elem.Kind != java.Byte {
panic("unsupported array type")
}
g.Printf("%s := toSlice(%s, %v)\n", to, from, mode == modeRetained)
case java.Object:
_, hasProxy := g.imported[t.Class]
g.genRefRead(to, from, g.goType(t, false), "proxy_class_"+flattenName(t.Class), hasProxy)
default:
panic("invalid kind")
}
}
func (g *ClassGen) genRefRead(to, from string, intfName, proxyName string, hasProxy bool) {
g.Printf("var %s %s\n", to, intfName)
g.Printf("%s_ref := _seq.FromRefNum(int32(%s))\n", to, from)
g.Printf("if %s_ref != nil {\n", to)
g.Printf(" if %s < 0 { // go object\n", from)
g.Printf(" %s = %s_ref.Get().(%s)\n", to, to, intfName)
g.Printf(" } else { // foreign object\n")
if hasProxy {
g.Printf(" %s = (*%s)(%s_ref)\n", to, proxyName, to)
} else {
g.Printf(" %s = %s_ref\n", to, to)
}
g.Printf(" }\n")
g.Printf("}\n")
}
func (g *ClassGen) genWrite(dst, v string, t *java.Type, mode varMode) {
switch t.Kind {
case java.Int, java.Short, java.Char, java.Byte, java.Long, java.Float, java.Double:
g.Printf("%s := C.%s(%s)\n", dst, t.CType(), v)
case java.Boolean:
g.Printf("%s := C.jboolean(C.JNI_FALSE)\n", dst)
g.Printf("if %s {\n", v)
g.Printf(" %s = C.jboolean(C.JNI_TRUE)\n", dst)
g.Printf("}\n")
case java.String:
g.Printf("%s := encodeString(%s)\n", dst, v)
case java.Array:
if t.Elem.Kind != java.Byte {
panic("unsupported array type")
}
g.Printf("%s := fromSlice(%s, %v)\n", dst, v, mode == modeRetained)
case java.Object:
g.Printf("var %s C.jint = _seq.NullRefNum\n", dst)
g.Printf("if %s != nil {\n", v)
g.Printf(" %s = C.jint(_seq.ToRefNum(%s))\n", dst, v)
g.Printf("}\n")
default:
panic("invalid kind")
}
}
// genCRetClear clears the result value from a JNI call if an exception was
// raised.
func (g *ClassGen) genCRetClear(v string, t *java.Type, exc string) {
g.Printf("if (%s != NULL) {\n", exc)
g.Indent()
switch t.Kind {
case java.Int, java.Short, java.Char, java.Byte, java.Long, java.Float, java.Double, java.Boolean:
g.Printf("%s = 0;\n", v)
default:
// Assume a nullable type. It will break if we missed a type.
g.Printf("%s = NULL;\n", v)
}
g.Outdent()
g.Printf("}\n")
}
func (g *ClassGen) genJavaToC(v string, t *java.Type) {
switch t.Kind {
case java.Int, java.Short, java.Char, java.Byte, java.Long, java.Float, java.Double, java.Boolean:
g.Printf("%s _%s = %s;\n", t.JNIType(), v, v)
case java.String:
g.Printf("nstring _%s = go_seq_from_java_string(env, %s);\n", v, v)
case java.Array:
if t.Elem.Kind != java.Byte {
panic("unsupported array type")
}
g.Printf("nbyteslice _%s = go_seq_from_java_bytearray(env, %s, 1);\n", v, v)
case java.Object:
g.Printf("jint _%s = go_seq_to_refnum(env, %s);\n", v, v)
default:
panic("invalid kind")
}
}
func (g *ClassGen) genCToJava(v string, t *java.Type) {
switch t.Kind {
case java.Int, java.Short, java.Char, java.Byte, java.Long, java.Float, java.Double, java.Boolean:
g.Printf("%s _%s = %s;\n", t.JNIType(), v, v)
case java.String:
g.Printf("jstring _%s = go_seq_to_java_string(env, %s);\n", v, v)
case java.Array:
if t.Elem.Kind != java.Byte {
panic("unsupported array type")
}
g.Printf("jbyteArray _%s = go_seq_to_java_bytearray(env, %s, 0);\n", v, v)
case java.Object:
g.Printf("jobject _%s = go_seq_from_refnum(env, %s, NULL, NULL);\n", v, v)
default:
panic("invalid kind")
}
}
func goClsName(n string) string {
return initialUpper(strings.Replace(n, ".", "_", -1))
}
func (g *ClassGen) genInterface(cls *java.Class) {
g.Printf("type %s interface {\n", goClsName(cls.Name))
g.Indent()
// Methods
for _, fs := range cls.AllMethods {
if !g.isFuncSetSupported(fs) {
continue
}
g.Printf(fs.GoName)
g.genFuncDecl(true, fs)
g.Printf("\n")
}
if goName, ok := g.goClsMap[cls.Name]; ok {
g.Printf("Super() %s\n", goClsName(cls.Name))
g.Printf("// Unwrap returns the Go object this Java instance\n")
g.Printf("// is wrapping.\n")
g.Printf("// The return value is a %s, but the delclared type is\n", goName)
g.Printf("// interface{} to avoid import cycles.\n")
g.Printf("Unwrap() interface{}\n")
}
if cls.Throwable {
g.Printf("Error() string\n")
}
g.Outdent()
g.Printf("}\n\n")
}
// Flatten java class names. "java.package.Class$Inner" is converted to
// "java_package_Class_Inner"
func flattenName(n string) string {
return strings.Replace(strings.Replace(n, ".", "_", -1), "$", "_", -1)
}
var (
classesPkgHeader = gobindPreamble + `
package Java
// Used to silence this package not used errors
const Dummy = 0
`
classesCHeader = gobindPreamble + `
#include <jni.h>
#include "seq.h"
#include "classes.h"
`
classesHHeader = gobindPreamble + `
#include <jni.h>
#include "seq.h"
extern void init_proxies();
`
javaImplHeader = gobindPreamble
classesGoHeader = gobindPreamble + `
package main
/*
#include <stdlib.h> // for free()
#include <jni.h>
#include "seq.h"
#include "classes.h"
*/
import "C"
import (
"Java"
_seq "golang.org/x/mobile/bind/seq"
)
`
)
|
bind
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/bind/types.go
|
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package bind
import (
"fmt"
"go/types"
"log"
"strings"
)
type ifaceSummary struct {
iface *types.Interface
callable []*types.Func
implementable bool
}
func makeIfaceSummary(iface *types.Interface) ifaceSummary {
summary := ifaceSummary{
iface: iface,
implementable: true,
}
methodset := types.NewMethodSet(iface)
for i := 0; i < methodset.Len(); i++ {
obj := methodset.At(i).Obj()
if !obj.Exported() {
summary.implementable = false
continue
}
m, ok := obj.(*types.Func)
if !ok {
log.Panicf("unexpected methodset obj: %s (%T)", obj, obj)
}
if !isImplementable(m.Type().(*types.Signature)) {
summary.implementable = false
}
if isCallable(m) {
summary.callable = append(summary.callable, m)
}
}
return summary
}
func isCallable(t *types.Func) bool {
// TODO(crawshaw): functions that are not implementable from
// another language may still be callable (for example, a
// returned value with an unexported type can be treated as
// an opaque value by the caller). This restriction could be
// lifted.
return isImplementable(t.Type().(*types.Signature))
}
func isImplementable(sig *types.Signature) bool {
params := sig.Params()
for i := 0; i < params.Len(); i++ {
if !isExported(params.At(i).Type()) {
return false
}
}
res := sig.Results()
for i := 0; i < res.Len(); i++ {
if !isExported(res.At(i).Type()) {
return false
}
}
return true
}
func exportedMethodSet(T types.Type) []*types.Func {
var methods []*types.Func
methodset := types.NewMethodSet(T)
for i := 0; i < methodset.Len(); i++ {
obj := methodset.At(i).Obj()
if !obj.Exported() {
continue
}
// Skip methods from the embedded classes, so that
// only methods that are implemented in Go are included.
if pref := pkgFirstElem(obj.Pkg()); pref == "Java" || pref == "ObjC" {
continue
}
switch obj := obj.(type) {
case *types.Func:
methods = append(methods, obj)
default:
log.Panicf("unexpected methodset obj: %s", obj)
}
}
return methods
}
func exportedFields(T *types.Struct) []*types.Var {
var fields []*types.Var
for i := 0; i < T.NumFields(); i++ {
f := T.Field(i)
if !f.Exported() {
continue
}
fields = append(fields, f)
}
return fields
}
func isErrorType(t types.Type) bool {
return types.Identical(t, types.Universe.Lookup("error").Type())
}
func isExported(t types.Type) bool {
if isErrorType(t) {
return true
}
switch t := t.(type) {
case *types.Basic:
return true
case *types.Named:
return t.Obj().Exported()
case *types.Pointer:
return isExported(t.Elem())
default:
return true
}
}
func isRefType(t types.Type) bool {
if isErrorType(t) {
return false
}
switch t := t.(type) {
case *types.Named:
switch u := t.Underlying().(type) {
case *types.Interface:
return true
default:
panic(fmt.Sprintf("unsupported named type: %s / %T", u, u))
}
case *types.Pointer:
return isRefType(t.Elem())
default:
return false
}
}
func isNullableType(t types.Type) bool {
return types.AssignableTo(types.Typ[types.UntypedNil].Underlying(), t) || t.String() == "string" // string is mapped to NSString*, which is nullable
}
func typePkgFirstElem(t types.Type) string {
nt, ok := t.(*types.Named)
if !ok {
return ""
}
return pkgFirstElem(nt.Obj().Pkg())
}
func pkgFirstElem(p *types.Package) string {
if p == nil {
return ""
}
path := p.Path()
idx := strings.Index(path, "/")
if idx == -1 {
return path
}
return path[:idx]
}
func isWrapperType(t types.Type) bool {
e := typePkgFirstElem(t)
return e == "Java" || e == "ObjC"
}
|
bind
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/bind/genjava.go
|
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package bind
import (
"fmt"
"go/constant"
"go/types"
"html"
"math"
"reflect"
"regexp"
"strings"
"golang.org/x/mobile/internal/importers/java"
)
// TODO(crawshaw): disallow basic android java type names in exported symbols.
// TODO(crawshaw): consider introducing Java functions for casting to and from interfaces at runtime.
type JavaGen struct {
// JavaPkg is the Java package prefix for the generated classes. The prefix is prepended to the Go
// package name to create the full Java package name.
JavaPkg string
*Generator
jstructs map[*types.TypeName]*javaClassInfo
clsMap map[string]*java.Class
// Constructors is a map from Go struct types to a list
// of exported constructor functions for the type, on the form
// func New<Type>(...) *Type
constructors map[*types.TypeName][]*types.Func
}
type javaClassInfo struct {
// The Java class this class extends.
extends *java.Class
// All Java classes and interfaces this class extends and implements.
supers []*java.Class
methods map[string]*java.FuncSet
// Does the class need a default no-arg constructor
genNoargCon bool
}
// Init intializes the embedded Generator and initializes the Java class information
// needed to generate structs that extend Java classes and interfaces.
func (g *JavaGen) Init(classes []*java.Class) {
g.Generator.Init()
g.clsMap = make(map[string]*java.Class)
for _, cls := range classes {
g.clsMap[cls.Name] = cls
}
g.jstructs = make(map[*types.TypeName]*javaClassInfo)
g.constructors = make(map[*types.TypeName][]*types.Func)
for _, s := range g.structs {
classes := embeddedJavaClasses(s.t)
if len(classes) == 0 {
continue
}
inf := &javaClassInfo{
methods: make(map[string]*java.FuncSet),
genNoargCon: true, // java.lang.Object has a no-arg constructor
}
for _, n := range classes {
cls := g.clsMap[n]
for _, fs := range cls.AllMethods {
hasMeth := false
for _, f := range fs.Funcs {
if !f.Final {
hasMeth = true
}
}
if hasMeth {
inf.methods[fs.GoName] = fs
}
}
inf.supers = append(inf.supers, cls)
if !cls.Interface {
if inf.extends != nil {
g.errorf("%s embeds more than one Java class; only one is allowed.", s.obj)
}
if cls.Final {
g.errorf("%s embeds final Java class %s", s.obj, cls.Name)
}
inf.extends = cls
inf.genNoargCon = cls.HasNoArgCon
}
}
g.jstructs[s.obj] = inf
}
for _, f := range g.funcs {
if t := g.constructorType(f); t != nil {
jinf := g.jstructs[t]
if jinf != nil {
sig := f.Type().(*types.Signature)
jinf.genNoargCon = jinf.genNoargCon && sig.Params().Len() > 0
}
g.constructors[t] = append(g.constructors[t], f)
}
}
}
func (j *javaClassInfo) toJavaType(T types.Type) *java.Type {
switch T := T.(type) {
case *types.Basic:
var kind java.TypeKind
switch T.Kind() {
case types.Bool, types.UntypedBool:
kind = java.Boolean
case types.Uint8:
kind = java.Byte
case types.Int16:
kind = java.Short
case types.Int32, types.UntypedRune: // types.Rune
kind = java.Int
case types.Int64, types.UntypedInt:
kind = java.Long
case types.Float32:
kind = java.Float
case types.Float64, types.UntypedFloat:
kind = java.Double
case types.String, types.UntypedString:
kind = java.String
default:
return nil
}
return &java.Type{Kind: kind}
case *types.Slice:
switch e := T.Elem().(type) {
case *types.Basic:
switch e.Kind() {
case types.Uint8: // Byte.
return &java.Type{Kind: java.Array, Elem: &java.Type{Kind: java.Byte}}
}
}
return nil
case *types.Named:
if isJavaType(T) {
return &java.Type{Kind: java.Object, Class: classNameFor(T)}
}
}
return nil
}
// lookupMethod searches the Java class descriptor for a method
// that matches the Go method.
func (j *javaClassInfo) lookupMethod(m *types.Func, hasThis bool) *java.Func {
jm := j.methods[m.Name()]
if jm == nil {
// If an exact match is not found, try the method with trailing underscores
// stripped. This way, name clashes can be avoided when overriding multiple
// overloaded methods from Go.
base := strings.TrimRight(m.Name(), "_")
jm = j.methods[base]
if jm == nil {
return nil
}
}
// A name match was found. Now use the parameter and return types to locate
// the correct variant.
sig := m.Type().(*types.Signature)
params := sig.Params()
// Convert Go parameter types to their Java counterparts, if possible.
var jparams []*java.Type
i := 0
if hasThis {
i = 1
}
for ; i < params.Len(); i++ {
jparams = append(jparams, j.toJavaType(params.At(i).Type()))
}
var ret *java.Type
var throws bool
if results := sig.Results(); results.Len() > 0 {
ret = j.toJavaType(results.At(0).Type())
if results.Len() > 1 {
throws = isErrorType(results.At(1).Type())
}
}
loop:
for _, f := range jm.Funcs {
if len(f.Params) != len(jparams) {
continue
}
if throws != (f.Throws != "") {
continue
}
if !reflect.DeepEqual(ret, f.Ret) {
continue
}
for i, p := range f.Params {
if !reflect.DeepEqual(p, jparams[i]) {
continue loop
}
}
return f
}
return nil
}
// ClassNames returns the list of names of the generated Java classes and interfaces.
func (g *JavaGen) ClassNames() []string {
var names []string
for _, s := range g.structs {
names = append(names, g.javaTypeName(s.obj.Name()))
}
for _, iface := range g.interfaces {
names = append(names, g.javaTypeName(iface.obj.Name()))
}
return names
}
func (g *JavaGen) GenClass(idx int) error {
ns := len(g.structs)
if idx < ns {
s := g.structs[idx]
g.genStruct(s)
} else {
iface := g.interfaces[idx-ns]
g.genInterface(iface)
}
if len(g.err) > 0 {
return g.err
}
return nil
}
func (g *JavaGen) genProxyImpl(name string) {
g.Printf("private final int refnum;\n\n")
g.Printf("@Override public final int incRefnum() {\n")
g.Printf(" Seq.incGoRef(refnum, this);\n")
g.Printf(" return refnum;\n")
g.Printf("}\n\n")
}
func (g *JavaGen) genStruct(s structInfo) {
pkgPath := ""
if g.Pkg != nil {
pkgPath = g.Pkg.Path()
}
n := g.javaTypeName(s.obj.Name())
g.Printf(javaPreamble, g.javaPkgName(g.Pkg), n, g.gobindOpts(), pkgPath)
fields := exportedFields(s.t)
methods := exportedMethodSet(types.NewPointer(s.obj.Type()))
var impls []string
jinf := g.jstructs[s.obj]
if jinf != nil {
impls = append(impls, "Seq.GoObject")
for _, cls := range jinf.supers {
if cls.Interface {
impls = append(impls, g.javaTypeName(cls.Name))
}
}
} else {
impls = append(impls, "Seq.Proxy")
}
pT := types.NewPointer(s.obj.Type())
for _, iface := range g.allIntf {
if types.AssignableTo(pT, iface.obj.Type()) {
n := iface.obj.Name()
if p := iface.obj.Pkg(); p != g.Pkg {
if n == JavaClassName(p) {
n = n + "_"
}
n = fmt.Sprintf("%s.%s", g.javaPkgName(p), n)
} else {
n = g.javaTypeName(n)
}
impls = append(impls, n)
}
}
doc := g.docs[n]
g.javadoc(doc.Doc())
g.Printf("public final class %s", n)
if jinf != nil {
if jinf.extends != nil {
g.Printf(" extends %s", g.javaTypeName(jinf.extends.Name))
}
}
if len(impls) > 0 {
g.Printf(" implements %s", strings.Join(impls, ", "))
}
g.Printf(" {\n")
g.Indent()
g.Printf("static { %s.touch(); }\n\n", g.className())
g.genProxyImpl(n)
cons := g.constructors[s.obj]
for _, f := range cons {
if !g.isConsSigSupported(f.Type()) {
g.Printf("// skipped constructor %s.%s with unsupported parameter or return types\n\n", n, f.Name())
continue
}
g.genConstructor(f, n, jinf != nil)
}
if jinf == nil || jinf.genNoargCon {
// constructor for Go instantiated instances.
g.Printf("%s(int refnum) { this.refnum = refnum; Seq.trackGoRef(refnum, this); }\n\n", n)
if len(cons) == 0 {
// Generate default no-arg constructor
g.Printf("public %s() { this.refnum = __New(); Seq.trackGoRef(refnum, this); }\n\n", n)
g.Printf("private static native int __New();\n\n")
}
}
for _, f := range fields {
if t := f.Type(); !g.isSupported(t) {
g.Printf("// skipped field %s.%s with unsupported type: %s\n\n", n, f.Name(), t)
continue
}
fdoc := doc.Member(f.Name())
g.javadoc(fdoc)
g.Printf("public final native %s get%s();\n", g.javaType(f.Type()), f.Name())
g.javadoc(fdoc)
g.Printf("public final native void set%s(%s v);\n\n", f.Name(), g.javaType(f.Type()))
}
var isStringer bool
for _, m := range methods {
if !g.isSigSupported(m.Type()) {
g.Printf("// skipped method %s.%s with unsupported parameter or return types\n\n", n, m.Name())
continue
}
g.javadoc(doc.Member(m.Name()))
var jm *java.Func
hasThis := false
if jinf != nil {
hasThis = g.hasThis(n, m)
jm = jinf.lookupMethod(m, hasThis)
if jm != nil {
g.Printf("@Override ")
}
}
g.Printf("public native ")
g.genFuncSignature(m, jm, hasThis)
t := m.Type().(*types.Signature)
isStringer = isStringer || (m.Name() == "String" && t.Params().Len() == 0 && t.Results().Len() == 1 &&
types.Identical(t.Results().At(0).Type(), types.Typ[types.String]))
}
if jinf == nil {
g.genObjectMethods(n, fields, isStringer)
}
g.Outdent()
g.Printf("}\n\n")
}
// isConsSigSupported reports whether the generators can handle a given
// constructor signature.
func (g *JavaGen) isConsSigSupported(t types.Type) bool {
if !g.isSigSupported(t) {
return false
}
// Skip constructors taking a single int32 argument
// since they clash with the proxy constructors that
// take a refnum.
params := t.(*types.Signature).Params()
if params.Len() != 1 {
return true
}
if t, ok := params.At(0).Type().(*types.Basic); ok {
switch t.Kind() {
case types.Int32, types.Uint32:
return false
}
}
return true
}
// javaTypeName returns the class name of a given Go type name. If
// the type name clashes with the package class name, an underscore is
// appended.
func (g *JavaGen) javaTypeName(n string) string {
if n == JavaClassName(g.Pkg) {
return n + "_"
}
return n
}
func (g *JavaGen) javadoc(doc string) {
if doc == "" {
return
}
// JavaDoc expects HTML-escaped documentation.
g.Printf("/**\n * %s */\n", html.EscapeString(doc))
}
// hasThis reports whether a method has an implicit "this" parameter.
func (g *JavaGen) hasThis(sName string, m *types.Func) bool {
sig := m.Type().(*types.Signature)
params := sig.Params()
if params.Len() == 0 {
return false
}
v := params.At(0)
if v.Name() != "this" {
return false
}
t, ok := v.Type().(*types.Named)
if !ok {
return false
}
obj := t.Obj()
pkg := obj.Pkg()
if pkgFirstElem(pkg) != "Java" {
return false
}
clsName := classNameFor(t)
exp := g.javaPkgName(g.Pkg) + "." + sName
if clsName != exp {
g.errorf("the type %s of the `this` argument to method %s.%s is not %s", clsName, sName, m.Name(), exp)
return false
}
return true
}
func (g *JavaGen) genConstructor(f *types.Func, n string, jcls bool) {
g.javadoc(g.docs[f.Name()].Doc())
g.Printf("public %s(", n)
g.genFuncArgs(f, nil, false)
g.Printf(") {\n")
g.Indent()
sig := f.Type().(*types.Signature)
params := sig.Params()
if jcls {
g.Printf("super(")
for i := 0; i < params.Len(); i++ {
if i > 0 {
g.Printf(", ")
}
g.Printf(g.paramName(params, i))
}
g.Printf(");\n")
}
g.Printf("this.refnum = ")
g.Printf("__%s(", f.Name())
for i := 0; i < params.Len(); i++ {
if i > 0 {
g.Printf(", ")
}
g.Printf(g.paramName(params, i))
}
g.Printf(");\n")
g.Printf("Seq.trackGoRef(refnum, this);\n")
g.Outdent()
g.Printf("}\n\n")
g.Printf("private static native int __%s(", f.Name())
g.genFuncArgs(f, nil, false)
g.Printf(");\n\n")
}
// genFuncArgs generated Java function arguments declaration for the function f.
// If the supplied overridden java function is supplied, genFuncArgs omits the implicit
// this argument.
func (g *JavaGen) genFuncArgs(f *types.Func, jm *java.Func, hasThis bool) {
sig := f.Type().(*types.Signature)
params := sig.Params()
first := 0
if hasThis {
// Skip the implicit this argument to the Go method
first = 1
}
for i := first; i < params.Len(); i++ {
if i > first {
g.Printf(", ")
}
v := params.At(i)
name := g.paramName(params, i)
jt := g.javaType(v.Type())
g.Printf("%s %s", jt, name)
}
}
func (g *JavaGen) genObjectMethods(n string, fields []*types.Var, isStringer bool) {
g.Printf("@Override public boolean equals(Object o) {\n")
g.Indent()
g.Printf("if (o == null || !(o instanceof %s)) {\n return false;\n}\n", n)
g.Printf("%s that = (%s)o;\n", n, n)
for _, f := range fields {
if t := f.Type(); !g.isSupported(t) {
g.Printf("// skipped field %s.%s with unsupported type: %s\n\n", n, f.Name(), t)
continue
}
nf := f.Name()
g.Printf("%s this%s = get%s();\n", g.javaType(f.Type()), nf, nf)
g.Printf("%s that%s = that.get%s();\n", g.javaType(f.Type()), nf, nf)
if isJavaPrimitive(f.Type()) {
g.Printf("if (this%s != that%s) {\n return false;\n}\n", nf, nf)
} else {
g.Printf("if (this%s == null) {\n", nf)
g.Indent()
g.Printf("if (that%s != null) {\n return false;\n}\n", nf)
g.Outdent()
g.Printf("} else if (!this%s.equals(that%s)) {\n return false;\n}\n", nf, nf)
}
}
g.Printf("return true;\n")
g.Outdent()
g.Printf("}\n\n")
g.Printf("@Override public int hashCode() {\n")
g.Printf(" return java.util.Arrays.hashCode(new Object[] {")
idx := 0
for _, f := range fields {
if t := f.Type(); !g.isSupported(t) {
continue
}
if idx > 0 {
g.Printf(", ")
}
idx++
g.Printf("get%s()", f.Name())
}
g.Printf("});\n")
g.Printf("}\n\n")
g.Printf("@Override public String toString() {\n")
g.Indent()
if isStringer {
g.Printf("return string();\n")
} else {
g.Printf("StringBuilder b = new StringBuilder();\n")
g.Printf(`b.append("%s").append("{");`, n)
g.Printf("\n")
for _, f := range fields {
if t := f.Type(); !g.isSupported(t) {
continue
}
n := f.Name()
g.Printf(`b.append("%s:").append(get%s()).append(",");`, n, n)
g.Printf("\n")
}
g.Printf(`return b.append("}").toString();`)
g.Printf("\n")
}
g.Outdent()
g.Printf("}\n")
}
func (g *JavaGen) genInterface(iface interfaceInfo) {
pkgPath := ""
if g.Pkg != nil {
pkgPath = g.Pkg.Path()
}
g.Printf(javaPreamble, g.javaPkgName(g.Pkg), g.javaTypeName(iface.obj.Name()), g.gobindOpts(), pkgPath)
var exts []string
numM := iface.t.NumMethods()
for _, other := range g.allIntf {
// Only extend interfaces with fewer methods to avoid circular references
if other.t.NumMethods() < numM && types.AssignableTo(iface.t, other.t) {
n := other.obj.Name()
if p := other.obj.Pkg(); p != g.Pkg {
if n == JavaClassName(p) {
n = n + "_"
}
n = fmt.Sprintf("%s.%s", g.javaPkgName(p), n)
} else {
n = g.javaTypeName(n)
}
exts = append(exts, n)
}
}
doc := g.docs[iface.obj.Name()]
g.javadoc(doc.Doc())
g.Printf("public interface %s", g.javaTypeName(iface.obj.Name()))
if len(exts) > 0 {
g.Printf(" extends %s", strings.Join(exts, ", "))
}
g.Printf(" {\n")
g.Indent()
for _, m := range iface.summary.callable {
if !g.isSigSupported(m.Type()) {
g.Printf("// skipped method %s.%s with unsupported parameter or return types\n\n", iface.obj.Name(), m.Name())
continue
}
g.javadoc(doc.Member(m.Name()))
g.Printf("public ")
g.genFuncSignature(m, nil, false)
}
g.Printf("\n")
g.Outdent()
g.Printf("}\n\n")
}
func isJavaPrimitive(T types.Type) bool {
b, ok := T.(*types.Basic)
if !ok {
return false
}
switch b.Kind() {
case types.Bool, types.Uint8, types.Float32, types.Float64,
types.Int, types.Int8, types.Int16, types.Int32, types.Int64:
return true
}
return false
}
// jniType returns a string that can be used as a JNI type.
func (g *JavaGen) jniType(T types.Type) string {
switch T := T.(type) {
case *types.Basic:
switch T.Kind() {
case types.Bool, types.UntypedBool:
return "jboolean"
case types.Int:
return "jlong"
case types.Int8:
return "jbyte"
case types.Int16:
return "jshort"
case types.Int32, types.UntypedRune: // types.Rune
return "jint"
case types.Int64, types.UntypedInt:
return "jlong"
case types.Uint8: // types.Byte
// TODO(crawshaw): Java bytes are signed, so this is
// questionable, but vital.
return "jbyte"
// TODO(crawshaw): case types.Uint, types.Uint16, types.Uint32, types.Uint64:
case types.Float32:
return "jfloat"
case types.Float64, types.UntypedFloat:
return "jdouble"
case types.String, types.UntypedString:
return "jstring"
default:
g.errorf("unsupported basic type: %s", T)
return "TODO"
}
case *types.Slice:
return "jbyteArray"
case *types.Pointer:
if _, ok := T.Elem().(*types.Named); ok {
return g.jniType(T.Elem())
}
g.errorf("unsupported pointer to type: %s", T)
case *types.Named:
return "jobject"
default:
g.errorf("unsupported jniType: %#+v, %s\n", T, T)
}
return "TODO"
}
func (g *JavaGen) javaBasicType(T *types.Basic) string {
switch T.Kind() {
case types.Bool, types.UntypedBool:
return "boolean"
case types.Int:
return "long"
case types.Int8:
return "byte"
case types.Int16:
return "short"
case types.Int32, types.UntypedRune: // types.Rune
return "int"
case types.Int64, types.UntypedInt:
return "long"
case types.Uint8: // types.Byte
// TODO(crawshaw): Java bytes are signed, so this is
// questionable, but vital.
return "byte"
// TODO(crawshaw): case types.Uint, types.Uint16, types.Uint32, types.Uint64:
case types.Float32:
return "float"
case types.Float64, types.UntypedFloat:
return "double"
case types.String, types.UntypedString:
return "String"
default:
g.errorf("unsupported basic type: %s", T)
return "TODO"
}
}
// javaType returns a string that can be used as a Java type.
func (g *JavaGen) javaType(T types.Type) string {
if isErrorType(T) {
// The error type is usually translated into an exception in
// Java, however the type can be exposed in other ways, such
// as an exported field.
return "java.lang.Exception"
} else if isJavaType(T) {
return classNameFor(T)
}
switch T := T.(type) {
case *types.Basic:
return g.javaBasicType(T)
case *types.Slice:
elem := g.javaType(T.Elem())
return elem + "[]"
case *types.Pointer:
if _, ok := T.Elem().(*types.Named); ok {
return g.javaType(T.Elem())
}
g.errorf("unsupported pointer to type: %s", T)
case *types.Named:
n := T.Obj()
nPkg := n.Pkg()
if !isErrorType(T) && !g.validPkg(nPkg) {
g.errorf("type %s is in %s, which is not bound", n.Name(), nPkg)
break
}
// TODO(crawshaw): more checking here
clsName := n.Name()
if nPkg != g.Pkg {
if clsName == JavaClassName(nPkg) {
clsName += "_"
}
return fmt.Sprintf("%s.%s", g.javaPkgName(nPkg), clsName)
} else {
return g.javaTypeName(clsName)
}
default:
g.errorf("unsupported javaType: %#+v, %s\n", T, T)
}
return "TODO"
}
func (g *JavaGen) genJNIFuncSignature(o *types.Func, sName string, jm *java.Func, proxy, isjava bool) {
sig := o.Type().(*types.Signature)
res := sig.Results()
var ret string
switch res.Len() {
case 2:
ret = g.jniType(res.At(0).Type())
case 1:
if isErrorType(res.At(0).Type()) {
ret = "void"
} else {
ret = g.jniType(res.At(0).Type())
}
case 0:
ret = "void"
default:
g.errorf("too many result values: %s", o)
return
}
g.Printf("JNIEXPORT %s JNICALL\n", ret)
g.Printf("Java_%s_", g.jniPkgName())
if sName != "" {
if proxy {
g.Printf(java.JNIMangle(g.className()))
// 0024 is the mangled form of $, for naming inner classes.
g.Printf("_00024proxy%s", sName)
} else {
g.Printf(java.JNIMangle(g.javaTypeName(sName)))
}
} else {
g.Printf(java.JNIMangle(g.className()))
}
g.Printf("_")
if jm != nil {
g.Printf(jm.JNIName)
} else {
oName := javaNameReplacer(lowerFirst(o.Name()))
g.Printf(java.JNIMangle(oName))
}
g.Printf("(JNIEnv* env, ")
if sName != "" {
g.Printf("jobject __this__")
} else {
g.Printf("jclass _clazz")
}
params := sig.Params()
i := 0
if isjava && params.Len() > 0 && params.At(0).Name() == "this" {
// Skip the implicit this argument, if any.
i = 1
}
for ; i < params.Len(); i++ {
g.Printf(", ")
v := sig.Params().At(i)
name := g.paramName(params, i)
jt := g.jniType(v.Type())
g.Printf("%s %s", jt, name)
}
g.Printf(")")
}
func (g *JavaGen) jniPkgName() string {
return strings.Replace(java.JNIMangle(g.javaPkgName(g.Pkg)), ".", "_", -1)
}
var javaLetterDigitRE = regexp.MustCompile(`[0-9a-zA-Z$_]`)
func (g *JavaGen) paramName(params *types.Tuple, pos int) string {
name := basicParamName(params, pos)
if !javaLetterDigitRE.MatchString(name) {
name = fmt.Sprintf("p%d", pos)
}
return javaNameReplacer(name)
}
func (g *JavaGen) genFuncSignature(o *types.Func, jm *java.Func, hasThis bool) {
sig := o.Type().(*types.Signature)
res := sig.Results()
var returnsError bool
var ret string
switch res.Len() {
case 2:
if !isErrorType(res.At(1).Type()) {
g.errorf("second result value must be of type error: %s", o)
return
}
returnsError = true
ret = g.javaType(res.At(0).Type())
case 1:
if isErrorType(res.At(0).Type()) {
returnsError = true
ret = "void"
} else {
ret = g.javaType(res.At(0).Type())
}
case 0:
ret = "void"
default:
g.errorf("too many result values: %s", o)
return
}
g.Printf("%s ", ret)
if jm != nil {
g.Printf(jm.Name)
} else {
g.Printf(javaNameReplacer(lowerFirst(o.Name())))
}
g.Printf("(")
g.genFuncArgs(o, jm, hasThis)
g.Printf(")")
if returnsError {
if jm != nil {
if jm.Throws == "" {
g.errorf("%s declares an error return value but the overridden method does not throw", o)
return
}
g.Printf(" throws %s", jm.Throws)
} else {
g.Printf(" throws Exception")
}
}
g.Printf(";\n")
}
func (g *JavaGen) genVar(o *types.Var) {
if t := o.Type(); !g.isSupported(t) {
g.Printf("// skipped variable %s with unsupported type: %s\n\n", o.Name(), t)
return
}
jType := g.javaType(o.Type())
doc := g.docs[o.Name()].Doc()
// setter
g.javadoc(doc)
g.Printf("public static native void set%s(%s v);\n", o.Name(), jType)
// getter
g.javadoc(doc)
g.Printf("public static native %s get%s();\n\n", jType, o.Name())
}
// genCRetClear clears the result value from a JNI call if an exception was
// raised.
func (g *JavaGen) genCRetClear(varName string, t types.Type, exc string) {
g.Printf("if (%s != NULL) {\n", exc)
g.Indent()
switch t := t.(type) {
case *types.Basic:
switch t.Kind() {
case types.String:
g.Printf("%s = NULL;\n", varName)
default:
g.Printf("%s = 0;\n", varName)
}
case *types.Slice, *types.Named, *types.Pointer:
g.Printf("%s = NULL;\n", varName)
}
g.Outdent()
g.Printf("}\n")
}
func (g *JavaGen) genJavaToC(varName string, t types.Type, mode varMode) {
switch t := t.(type) {
case *types.Basic:
switch t.Kind() {
case types.String:
g.Printf("nstring _%s = go_seq_from_java_string(env, %s);\n", varName, varName)
default:
g.Printf("%s _%s = (%s)%s;\n", g.cgoType(t), varName, g.cgoType(t), varName)
}
case *types.Slice:
switch e := t.Elem().(type) {
case *types.Basic:
switch e.Kind() {
case types.Uint8: // Byte.
g.Printf("nbyteslice _%s = go_seq_from_java_bytearray(env, %s, %d);\n", varName, varName, toCFlag(mode == modeRetained))
default:
g.errorf("unsupported type: %s", t)
}
default:
g.errorf("unsupported type: %s", t)
}
case *types.Named:
switch u := t.Underlying().(type) {
case *types.Interface:
g.Printf("int32_t _%s = go_seq_to_refnum(env, %s);\n", varName, varName)
default:
g.errorf("unsupported named type: %s / %T", u, u)
}
case *types.Pointer:
g.Printf("int32_t _%s = go_seq_to_refnum(env, %s);\n", varName, varName)
default:
g.Printf("%s _%s = (%s)%s;\n", g.cgoType(t), varName, g.cgoType(t), varName)
}
}
func (g *JavaGen) genCToJava(toName, fromName string, t types.Type, mode varMode) {
switch t := t.(type) {
case *types.Basic:
switch t.Kind() {
case types.String:
g.Printf("jstring %s = go_seq_to_java_string(env, %s);\n", toName, fromName)
case types.Bool:
g.Printf("jboolean %s = %s ? JNI_TRUE : JNI_FALSE;\n", toName, fromName)
default:
g.Printf("%s %s = (%s)%s;\n", g.jniType(t), toName, g.jniType(t), fromName)
}
case *types.Slice:
switch e := t.Elem().(type) {
case *types.Basic:
switch e.Kind() {
case types.Uint8: // Byte.
g.Printf("jbyteArray %s = go_seq_to_java_bytearray(env, %s, %d);\n", toName, fromName, toCFlag(mode == modeRetained))
default:
g.errorf("unsupported type: %s", t)
}
default:
g.errorf("unsupported type: %s", t)
}
case *types.Pointer:
// TODO(crawshaw): test *int
// TODO(crawshaw): test **Generator
switch t := t.Elem().(type) {
case *types.Named:
g.genFromRefnum(toName, fromName, t, t.Obj())
default:
g.errorf("unsupported type %s", t)
}
case *types.Named:
switch t.Underlying().(type) {
case *types.Interface, *types.Pointer:
g.genFromRefnum(toName, fromName, t, t.Obj())
default:
g.errorf("unsupported, direct named type %s", t)
}
default:
g.Printf("%s %s = (%s)%s;\n", g.jniType(t), toName, g.jniType(t), fromName)
}
}
func (g *JavaGen) genFromRefnum(toName, fromName string, t types.Type, o *types.TypeName) {
oPkg := o.Pkg()
isJava := isJavaType(o.Type())
if !isErrorType(o.Type()) && !g.validPkg(oPkg) && !isJava {
g.errorf("type %s is defined in package %s, which is not bound", t, oPkg)
return
}
p := pkgPrefix(oPkg)
g.Printf("jobject %s = go_seq_from_refnum(env, %s, ", toName, fromName)
if isJava {
g.Printf("NULL, NULL")
} else {
g.Printf("proxy_class_%s_%s, proxy_class_%s_%s_cons", p, o.Name(), p, o.Name())
}
g.Printf(");\n")
}
func (g *JavaGen) gobindOpts() string {
opts := []string{"-lang=java"}
if g.JavaPkg != "" {
opts = append(opts, "-javapkg="+g.JavaPkg)
}
return strings.Join(opts, " ")
}
var javaNameReplacer = newNameSanitizer([]string{
"abstract", "assert", "boolean", "break", "byte", "case", "catch", "char",
"class", "const", "continue", "default", "do", "double", "else", "enum",
"extends", "final", "finally", "float", "for", "goto", "if", "implements",
"import", "instanceof", "int", "interface", "long", "native", "new", "package",
"private", "protected", "public", "return", "short", "static", "strictfp",
"super", "switch", "synchronized", "this", "throw", "throws", "transient",
"try", "void", "volatile", "while", "false", "null", "true"})
func (g *JavaGen) javaPkgName(pkg *types.Package) string {
return JavaPkgName(g.JavaPkg, pkg)
}
// JavaPkgName returns the Java package name for a Go package
// given a pkg prefix. If the prefix is empty, "go" is used
// instead.
func JavaPkgName(pkgPrefix string, pkg *types.Package) string {
if pkg == nil {
return "go"
}
s := javaNameReplacer(pkg.Name())
if pkgPrefix == "" {
return s
}
return pkgPrefix + "." + s
}
func (g *JavaGen) className() string {
return JavaClassName(g.Pkg)
}
// JavaClassName returns the name of the Java class that
// contains Go package level identifiers.
func JavaClassName(pkg *types.Package) string {
if pkg == nil {
return "Universe"
}
return javaNameReplacer(strings.Title(pkg.Name()))
}
func (g *JavaGen) genConst(o *types.Const) {
if _, ok := o.Type().(*types.Basic); !ok || !g.isSupported(o.Type()) {
g.Printf("// skipped const %s with unsupported type: %s\n\n", o.Name(), o.Type())
return
}
// TODO(hyangah): should const names use upper cases + "_"?
// TODO(hyangah): check invalid names.
jType := g.javaType(o.Type())
val := o.Val().ExactString()
switch b := o.Type().(*types.Basic); b.Kind() {
case types.Int64, types.UntypedInt:
i, exact := constant.Int64Val(o.Val())
if !exact {
g.errorf("const value %s for %s cannot be represented as %s", val, o.Name(), jType)
return
}
val = fmt.Sprintf("%dL", i)
case types.Float32:
f, _ := constant.Float32Val(o.Val())
val = fmt.Sprintf("%gf", f)
case types.Float64, types.UntypedFloat:
f, _ := constant.Float64Val(o.Val())
if math.IsInf(f, 0) || math.Abs(f) > math.MaxFloat64 {
g.errorf("const value %s for %s cannot be represented as %s", val, o.Name(), jType)
return
}
val = fmt.Sprintf("%g", f)
}
g.javadoc(g.docs[o.Name()].Doc())
g.Printf("public static final %s %s = %s;\n", g.javaType(o.Type()), o.Name(), val)
}
func (g *JavaGen) genJNIField(o *types.TypeName, f *types.Var) {
if t := f.Type(); !g.isSupported(t) {
g.Printf("// skipped field %s with unsupported type: %s\n\n", o.Name(), t)
return
}
n := java.JNIMangle(g.javaTypeName(o.Name()))
// setter
g.Printf("JNIEXPORT void JNICALL\n")
g.Printf("Java_%s_%s_set%s(JNIEnv *env, jobject this, %s v) {\n", g.jniPkgName(), n, java.JNIMangle(f.Name()), g.jniType(f.Type()))
g.Indent()
g.Printf("int32_t o = go_seq_to_refnum_go(env, this);\n")
g.genJavaToC("v", f.Type(), modeRetained)
g.Printf("proxy%s_%s_%s_Set(o, _v);\n", g.pkgPrefix, o.Name(), f.Name())
g.genRelease("v", f.Type(), modeRetained)
g.Outdent()
g.Printf("}\n\n")
// getter
g.Printf("JNIEXPORT %s JNICALL\n", g.jniType(f.Type()))
g.Printf("Java_%s_%s_get%s(JNIEnv *env, jobject this) {\n", g.jniPkgName(), n, java.JNIMangle(f.Name()))
g.Indent()
g.Printf("int32_t o = go_seq_to_refnum_go(env, this);\n")
g.Printf("%s r0 = ", g.cgoType(f.Type()))
g.Printf("proxy%s_%s_%s_Get(o);\n", g.pkgPrefix, o.Name(), f.Name())
g.genCToJava("_r0", "r0", f.Type(), modeRetained)
g.Printf("return _r0;\n")
g.Outdent()
g.Printf("}\n\n")
}
func (g *JavaGen) genJNIVar(o *types.Var) {
if t := o.Type(); !g.isSupported(t) {
g.Printf("// skipped variable %s with unsupported type: %s\n\n", o.Name(), t)
return
}
n := java.JNIMangle(g.javaTypeName(o.Name()))
// setter
g.Printf("JNIEXPORT void JNICALL\n")
g.Printf("Java_%s_%s_set%s(JNIEnv *env, jclass clazz, %s v) {\n", g.jniPkgName(), java.JNIMangle(g.className()), n, g.jniType(o.Type()))
g.Indent()
g.genJavaToC("v", o.Type(), modeRetained)
g.Printf("var_set%s_%s(_v);\n", g.pkgPrefix, o.Name())
g.genRelease("v", o.Type(), modeRetained)
g.Outdent()
g.Printf("}\n\n")
// getter
g.Printf("JNIEXPORT %s JNICALL\n", g.jniType(o.Type()))
g.Printf("Java_%s_%s_get%s(JNIEnv *env, jclass clazz) {\n", g.jniPkgName(), java.JNIMangle(g.className()), n)
g.Indent()
g.Printf("%s r0 = ", g.cgoType(o.Type()))
g.Printf("var_get%s_%s();\n", g.pkgPrefix, o.Name())
g.genCToJava("_r0", "r0", o.Type(), modeRetained)
g.Printf("return _r0;\n")
g.Outdent()
g.Printf("}\n\n")
}
func (g *JavaGen) genJNIConstructor(f *types.Func, sName string) {
if !g.isConsSigSupported(f.Type()) {
return
}
sig := f.Type().(*types.Signature)
res := sig.Results()
g.Printf("JNIEXPORT jint JNICALL\n")
g.Printf("Java_%s_%s_%s(JNIEnv *env, jclass clazz", g.jniPkgName(), java.JNIMangle(g.javaTypeName(sName)), java.JNIMangle("__"+f.Name()))
params := sig.Params()
for i := 0; i < params.Len(); i++ {
v := params.At(i)
jt := g.jniType(v.Type())
g.Printf(", %s %s", jt, g.paramName(params, i))
}
g.Printf(") {\n")
g.Indent()
for i := 0; i < params.Len(); i++ {
name := g.paramName(params, i)
g.genJavaToC(name, params.At(i).Type(), modeTransient)
}
// Constructors always return a mandatory *T and an optional error
if res.Len() == 1 {
g.Printf("int32_t refnum = proxy%s__%s(", g.pkgPrefix, f.Name())
} else {
g.Printf("struct proxy%s__%s_return res = proxy%s__%s(", g.pkgPrefix, f.Name(), g.pkgPrefix, f.Name())
}
for i := 0; i < params.Len(); i++ {
if i > 0 {
g.Printf(", ")
}
g.Printf("_%s", g.paramName(params, i))
}
g.Printf(");\n")
for i := 0; i < params.Len(); i++ {
g.genRelease(g.paramName(params, i), params.At(i).Type(), modeTransient)
}
// Extract multi returns and handle errors
if res.Len() == 2 {
g.Printf("int32_t refnum = res.r0;\n")
g.genCToJava("_err", "res.r1", res.At(1).Type(), modeRetained)
g.Printf("go_seq_maybe_throw_exception(env, _err);\n")
}
g.Printf("return refnum;\n")
g.Outdent()
g.Printf("}\n\n")
}
func (g *JavaGen) genJNIFunc(o *types.Func, sName string, jm *java.Func, proxy, isjava bool) {
if !g.isSigSupported(o.Type()) {
n := o.Name()
if sName != "" {
n = sName + "." + n
}
g.Printf("// skipped function %s with unsupported parameter or return types\n\n", n)
return
}
g.genJNIFuncSignature(o, sName, jm, proxy, isjava)
g.Printf(" {\n")
g.Indent()
g.genJNIFuncBody(o, sName, jm, isjava)
g.Outdent()
g.Printf("}\n\n")
}
func (g *JavaGen) genJNIFuncBody(o *types.Func, sName string, jm *java.Func, isjava bool) {
sig := o.Type().(*types.Signature)
res := sig.Results()
if sName != "" {
g.Printf("int32_t o = go_seq_to_refnum_go(env, __this__);\n")
}
params := sig.Params()
first := 0
if isjava && params.Len() > 0 && params.At(0).Name() == "this" {
// Start after the implicit this argument.
first = 1
g.Printf("int32_t _%s = go_seq_to_refnum(env, __this__);\n", g.paramName(params, 0))
}
for i := first; i < params.Len(); i++ {
name := g.paramName(params, i)
g.genJavaToC(name, params.At(i).Type(), modeTransient)
}
resPrefix := ""
if res.Len() > 0 {
if res.Len() == 1 {
g.Printf("%s r0 = ", g.cgoType(res.At(0).Type()))
} else {
resPrefix = "res."
g.Printf("struct proxy%s_%s_%s_return res = ", g.pkgPrefix, sName, o.Name())
}
}
g.Printf("proxy%s_%s_%s(", g.pkgPrefix, sName, o.Name())
if sName != "" {
g.Printf("o")
}
// Pass all arguments, including the implicit this argument.
for i := 0; i < params.Len(); i++ {
if i > 0 || sName != "" {
g.Printf(", ")
}
g.Printf("_%s", g.paramName(params, i))
}
g.Printf(");\n")
for i := first; i < params.Len(); i++ {
g.genRelease(g.paramName(params, i), params.At(i).Type(), modeTransient)
}
for i := 0; i < res.Len(); i++ {
tn := fmt.Sprintf("_r%d", i)
t := res.At(i).Type()
g.genCToJava(tn, fmt.Sprintf("%sr%d", resPrefix, i), t, modeRetained)
}
// Go backwards so that any exception is thrown before
// the return.
for i := res.Len() - 1; i >= 0; i-- {
t := res.At(i).Type()
if !isErrorType(t) {
g.Printf("return _r%d;\n", i)
} else {
g.Printf("go_seq_maybe_throw_exception(env, _r%d);\n", i)
}
}
}
// genRelease cleans up arguments that weren't copied in genJavaToC.
func (g *JavaGen) genRelease(varName string, t types.Type, mode varMode) {
switch t := t.(type) {
case *types.Basic:
case *types.Slice:
switch e := t.Elem().(type) {
case *types.Basic:
switch e.Kind() {
case types.Uint8: // Byte.
if mode == modeTransient {
g.Printf("go_seq_release_byte_array(env, %s, _%s.ptr);\n", varName, varName)
}
}
}
}
}
func (g *JavaGen) genMethodInterfaceProxy(oName string, m *types.Func) {
if !g.isSigSupported(m.Type()) {
g.Printf("// skipped method %s with unsupported parameter or return types\n\n", oName)
return
}
sig := m.Type().(*types.Signature)
params := sig.Params()
res := sig.Results()
g.genInterfaceMethodSignature(m, oName, false, g.paramName)
g.Indent()
g.Printf("JNIEnv *env = go_seq_push_local_frame(%d);\n", params.Len())
g.Printf("jobject o = go_seq_from_refnum(env, refnum, proxy_class_%s_%s, proxy_class_%s_%s_cons);\n", g.pkgPrefix, oName, g.pkgPrefix, oName)
for i := 0; i < params.Len(); i++ {
pn := g.paramName(params, i)
g.genCToJava("_"+pn, pn, params.At(i).Type(), modeTransient)
}
if res.Len() > 0 && !isErrorType(res.At(0).Type()) {
t := res.At(0).Type()
g.Printf("%s res = (*env)->Call%sMethod(env, o, ", g.jniType(t), g.jniCallType(t))
} else {
g.Printf("(*env)->CallVoidMethod(env, o, ")
}
g.Printf("mid_%s_%s", oName, m.Name())
for i := 0; i < params.Len(); i++ {
g.Printf(", _%s", g.paramName(params, i))
}
g.Printf(");\n")
var retName string
if res.Len() > 0 {
t := res.At(0).Type()
if res.Len() == 2 || isErrorType(t) {
g.Printf("jobject exc = go_seq_get_exception(env);\n")
errType := types.Universe.Lookup("error").Type()
g.genJavaToC("exc", errType, modeRetained)
retName = "_exc"
}
if !isErrorType(t) {
if res.Len() == 2 {
g.genCRetClear("res", t, "exc")
}
g.genJavaToC("res", t, modeRetained)
retName = "_res"
}
if res.Len() > 1 {
g.Printf("cproxy%s_%s_%s_return sres = {\n", g.pkgPrefix, oName, m.Name())
g.Printf(" _res, _exc\n")
g.Printf("};\n")
retName = "sres"
}
}
g.Printf("go_seq_pop_local_frame(env);\n")
if retName != "" {
g.Printf("return %s;\n", retName)
}
g.Outdent()
g.Printf("}\n\n")
}
func (g *JavaGen) GenH() error {
pkgPath := ""
if g.Pkg != nil {
pkgPath = g.Pkg.Path()
}
g.Printf(hPreamble, g.gobindOpts(), pkgPath, g.className())
for _, iface := range g.interfaces {
g.Printf("extern jclass proxy_class_%s_%s;\n", g.pkgPrefix, iface.obj.Name())
g.Printf("extern jmethodID proxy_class_%s_%s_cons;\n", g.pkgPrefix, iface.obj.Name())
g.Printf("\n")
for _, m := range iface.summary.callable {
if !g.isSigSupported(m.Type()) {
g.Printf("// skipped method %s.%s with unsupported parameter or return types\n\n", iface.obj.Name(), m.Name())
continue
}
g.genInterfaceMethodSignature(m, iface.obj.Name(), true, g.paramName)
g.Printf("\n")
}
}
for _, s := range g.structs {
g.Printf("extern jclass proxy_class_%s_%s;\n", g.pkgPrefix, s.obj.Name())
g.Printf("extern jmethodID proxy_class_%s_%s_cons;\n", g.pkgPrefix, s.obj.Name())
}
g.Printf("#endif\n")
if len(g.err) > 0 {
return g.err
}
return nil
}
func (g *JavaGen) jniCallType(t types.Type) string {
switch t := t.(type) {
case *types.Basic:
switch t.Kind() {
case types.Bool, types.UntypedBool:
return "Boolean"
case types.Int:
return "Long"
case types.Int8, types.Uint8: // types.Byte
return "Byte"
case types.Int16:
return "Short"
case types.Int32, types.UntypedRune: // types.Rune
return "Int"
case types.Int64, types.UntypedInt:
return "Long"
case types.Float32:
return "Float"
case types.Float64, types.UntypedFloat:
return "Double"
case types.String, types.UntypedString:
return "Object"
default:
g.errorf("unsupported basic type: %s", t)
}
case *types.Slice:
return "Object"
case *types.Pointer:
if _, ok := t.Elem().(*types.Named); ok {
return g.jniCallType(t.Elem())
}
g.errorf("unsupported pointer to type: %s", t)
case *types.Named:
return "Object"
default:
return "Object"
}
return "TODO"
}
func (g *JavaGen) jniClassSigPrefix(pkg *types.Package) string {
return strings.Replace(g.javaPkgName(pkg), ".", "/", -1) + "/"
}
func (g *JavaGen) jniSigType(T types.Type) string {
if isErrorType(T) {
return "Ljava/lang/Exception;"
}
switch T := T.(type) {
case *types.Basic:
switch T.Kind() {
case types.Bool, types.UntypedBool:
return "Z"
case types.Int:
return "J"
case types.Int8:
return "B"
case types.Int16:
return "S"
case types.Int32, types.UntypedRune: // types.Rune
return "I"
case types.Int64, types.UntypedInt:
return "J"
case types.Uint8: // types.Byte
return "B"
case types.Float32:
return "F"
case types.Float64, types.UntypedFloat:
return "D"
case types.String, types.UntypedString:
return "Ljava/lang/String;"
default:
g.errorf("unsupported basic type: %s", T)
return "TODO"
}
case *types.Slice:
return "[" + g.jniSigType(T.Elem())
case *types.Pointer:
if _, ok := T.Elem().(*types.Named); ok {
return g.jniSigType(T.Elem())
}
g.errorf("unsupported pointer to type: %s", T)
case *types.Named:
return "L" + g.jniClassSigPrefix(T.Obj().Pkg()) + g.javaTypeName(T.Obj().Name()) + ";"
default:
g.errorf("unsupported jniType: %#+v, %s\n", T, T)
}
return "TODO"
}
func (g *JavaGen) GenC() error {
var pkgName, pkgPath string
if g.Pkg != nil {
pkgName = g.Pkg.Name()
pkgPath = g.Pkg.Path()
} else {
pkgName = "universe"
}
g.Printf(cPreamble, g.gobindOpts(), pkgPath)
g.Printf("#include %q\n", pkgName+".h")
if g.Pkg != nil {
for _, pkg := range g.Pkg.Imports() {
if g.validPkg(pkg) {
g.Printf("#include \"%s.h\"\n", pkg.Name())
}
}
}
g.Printf("\n")
for _, iface := range g.interfaces {
g.Printf("jclass proxy_class_%s_%s;\n", g.pkgPrefix, iface.obj.Name())
g.Printf("jmethodID proxy_class_%s_%s_cons;\n", g.pkgPrefix, iface.obj.Name())
for _, m := range iface.summary.callable {
if !g.isSigSupported(m.Type()) {
g.Printf("// skipped method %s.%s with unsupported parameter or return types\n\n", iface.obj.Name(), m.Name())
continue
}
g.Printf("static jmethodID mid_%s_%s;\n", iface.obj.Name(), m.Name())
}
}
for _, s := range g.structs {
g.Printf("jclass proxy_class_%s_%s;\n", g.pkgPrefix, s.obj.Name())
g.Printf("jmethodID proxy_class_%s_%s_cons;\n", g.pkgPrefix, s.obj.Name())
}
g.Printf("\n")
g.Printf("JNIEXPORT void JNICALL\n")
g.Printf("Java_%s_%s__1init(JNIEnv *env, jclass _unused) {\n", g.jniPkgName(), java.JNIMangle(g.className()))
g.Indent()
g.Printf("jclass clazz;\n")
for _, s := range g.structs {
if jinf, ok := g.jstructs[s.obj]; ok {
// Leave the class and constructor NULL for Java classes with no
// default constructor.
if !jinf.genNoargCon {
continue
}
}
g.Printf("clazz = (*env)->FindClass(env, %q);\n", g.jniClassSigPrefix(s.obj.Pkg())+g.javaTypeName(s.obj.Name()))
g.Printf("proxy_class_%s_%s = (*env)->NewGlobalRef(env, clazz);\n", g.pkgPrefix, s.obj.Name())
g.Printf("proxy_class_%s_%s_cons = (*env)->GetMethodID(env, clazz, \"<init>\", \"(I)V\");\n", g.pkgPrefix, s.obj.Name())
}
for _, iface := range g.interfaces {
pkg := iface.obj.Pkg()
g.Printf("clazz = (*env)->FindClass(env, %q);\n", g.jniClassSigPrefix(pkg)+JavaClassName(pkg)+"$proxy"+iface.obj.Name())
g.Printf("proxy_class_%s_%s = (*env)->NewGlobalRef(env, clazz);\n", g.pkgPrefix, iface.obj.Name())
g.Printf("proxy_class_%s_%s_cons = (*env)->GetMethodID(env, clazz, \"<init>\", \"(I)V\");\n", g.pkgPrefix, iface.obj.Name())
if isErrorType(iface.obj.Type()) {
// As a special case, Java Exceptions are passed to Go pretending to implement the Go error interface.
// To complete the illusion, use the Throwable.getMessage method for proxied calls to the error.Error method.
g.Printf("clazz = (*env)->FindClass(env, \"java/lang/Throwable\");\n")
g.Printf("mid_error_Error = (*env)->GetMethodID(env, clazz, \"getMessage\", \"()Ljava/lang/String;\");\n")
continue
}
g.Printf("clazz = (*env)->FindClass(env, %q);\n", g.jniClassSigPrefix(pkg)+g.javaTypeName(iface.obj.Name()))
for _, m := range iface.summary.callable {
if !g.isSigSupported(m.Type()) {
g.Printf("// skipped method %s.%s with unsupported parameter or return types\n\n", iface.obj.Name(), m.Name())
continue
}
sig := m.Type().(*types.Signature)
res := sig.Results()
retSig := "V"
if res.Len() > 0 {
if t := res.At(0).Type(); !isErrorType(t) {
retSig = g.jniSigType(t)
}
}
var jniParams string
params := sig.Params()
for i := 0; i < params.Len(); i++ {
jniParams += g.jniSigType(params.At(i).Type())
}
g.Printf("mid_%s_%s = (*env)->GetMethodID(env, clazz, %q, \"(%s)%s\");\n",
iface.obj.Name(), m.Name(), javaNameReplacer(lowerFirst(m.Name())), jniParams, retSig)
}
g.Printf("\n")
}
g.Outdent()
g.Printf("}\n\n")
for _, f := range g.funcs {
g.genJNIFunc(f, "", nil, false, false)
}
for _, s := range g.structs {
sName := s.obj.Name()
cons := g.constructors[s.obj]
jinf := g.jstructs[s.obj]
for _, f := range cons {
g.genJNIConstructor(f, sName)
}
if len(cons) == 0 && (jinf == nil || jinf.genNoargCon) {
g.Printf("JNIEXPORT jint JNICALL\n")
g.Printf("Java_%s_%s_%s(JNIEnv *env, jclass clazz) {\n", g.jniPkgName(), java.JNIMangle(g.javaTypeName(sName)), java.JNIMangle("__New"))
g.Indent()
g.Printf("return new_%s_%s();\n", g.pkgPrefix, sName)
g.Outdent()
g.Printf("}\n\n")
}
for _, m := range exportedMethodSet(types.NewPointer(s.obj.Type())) {
var jm *java.Func
if jinf != nil {
jm = jinf.lookupMethod(m, g.hasThis(s.obj.Name(), m))
}
g.genJNIFunc(m, sName, jm, false, jinf != nil)
}
for _, f := range exportedFields(s.t) {
g.genJNIField(s.obj, f)
}
}
for _, iface := range g.interfaces {
for _, m := range iface.summary.callable {
g.genJNIFunc(m, iface.obj.Name(), nil, true, false)
g.genMethodInterfaceProxy(iface.obj.Name(), m)
}
}
for _, v := range g.vars {
g.genJNIVar(v)
}
if len(g.err) > 0 {
return g.err
}
return nil
}
func (g *JavaGen) GenJava() error {
pkgPath := ""
if g.Pkg != nil {
pkgPath = g.Pkg.Path()
}
g.Printf(javaPreamble, g.javaPkgName(g.Pkg), g.className(), g.gobindOpts(), pkgPath)
g.Printf("public abstract class %s {\n", g.className())
g.Indent()
g.Printf("static {\n")
g.Indent()
g.Printf("Seq.touch(); // for loading the native library\n")
if g.Pkg != nil {
for _, p := range g.Pkg.Imports() {
if g.validPkg(p) {
g.Printf("%s.%s.touch();\n", g.javaPkgName(p), JavaClassName(p))
}
}
}
g.Printf("_init();\n")
g.Outdent()
g.Printf("}\n\n")
g.Printf("private %s() {} // uninstantiable\n\n", g.className())
g.Printf("// touch is called from other bound packages to initialize this package\n")
g.Printf("public static void touch() {}\n\n")
g.Printf("private static native void _init();\n\n")
for _, iface := range g.interfaces {
n := iface.obj.Name()
g.Printf("private static final class proxy%s", n)
if isErrorType(iface.obj.Type()) {
g.Printf(" extends Exception")
}
g.Printf(" implements Seq.Proxy, %s {\n", g.javaTypeName(n))
g.Indent()
g.genProxyImpl("proxy" + n)
g.Printf("proxy%s(int refnum) { this.refnum = refnum; Seq.trackGoRef(refnum, this); }\n\n", n)
if isErrorType(iface.obj.Type()) {
g.Printf("@Override public String getMessage() { return error(); }\n\n")
}
for _, m := range iface.summary.callable {
if !g.isSigSupported(m.Type()) {
g.Printf("// skipped method %s.%s with unsupported parameter or return types\n\n", n, m.Name())
continue
}
g.Printf("public native ")
g.genFuncSignature(m, nil, false)
}
g.Outdent()
g.Printf("}\n")
}
g.Printf("\n")
for _, c := range g.constants {
g.genConst(c)
}
g.Printf("\n")
for _, v := range g.vars {
g.genVar(v)
}
for _, f := range g.funcs {
if !g.isSigSupported(f.Type()) {
g.Printf("// skipped function %s with unsupported parameter or return types\n\n", f.Name())
continue
}
g.javadoc(g.docs[f.Name()].Doc())
g.Printf("public static native ")
g.genFuncSignature(f, nil, false)
}
g.Outdent()
g.Printf("}\n")
if len(g.err) > 0 {
return g.err
}
return nil
}
// embeddedJavaClasses returns the possible empty list of Java types embedded
// in the given struct type.
func embeddedJavaClasses(t *types.Struct) []string {
clsSet := make(map[string]struct{})
var classes []string
for i := 0; i < t.NumFields(); i++ {
f := t.Field(i)
if !f.Exported() {
continue
}
if t := f.Type(); isJavaType(t) {
cls := classNameFor(t)
if _, exists := clsSet[cls]; !exists {
clsSet[cls] = struct{}{}
classes = append(classes, cls)
}
}
}
return classes
}
func classNameFor(t types.Type) string {
obj := t.(*types.Named).Obj()
pkg := obj.Pkg()
return strings.Replace(pkg.Path()[len("Java/"):], "/", ".", -1) + "." + obj.Name()
}
func isJavaType(t types.Type) bool {
return typePkgFirstElem(t) == "Java"
}
const (
javaPreamble = gobindPreamble + `// Java class %[1]s.%[2]s is a proxy for talking to a Go program.
//
// autogenerated by gobind %[3]s %[4]s
package %[1]s;
import go.Seq;
`
cPreamble = gobindPreamble + `// JNI functions for the Go <=> Java bridge.
//
// autogenerated by gobind %[1]s %[2]s
#include <android/log.h>
#include <stdint.h>
#include "seq.h"
#include "_cgo_export.h"
`
hPreamble = gobindPreamble + `// JNI function headers for the Go <=> Java bridge.
//
// autogenerated by gobind %[1]s %[2]s
#ifndef __%[3]s_H__
#define __%[3]s_H__
#include <jni.h>
`
)
|
bind
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/bind/genobjc.go
|
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package bind
import (
"fmt"
"go/constant"
"go/types"
"math"
"strings"
"golang.org/x/mobile/internal/importers/objc"
)
// TODO(hyangah): handle method name conflicts.
// - struct with SetF method and exported F field.
// - method names conflicting with NSObject methods. e.g. Init
// - interface type with InitWithRef.
// TODO(hyangah): error code/domain propagation
type ObjcGen struct {
Prefix string // prefix arg passed by flag.
*Generator
// fields set by init.
namePrefix string
// Map of all wrapped Objc types
wrapMap map[string]*objc.Named
// Structs that embeds Objc wrapper types.
ostructs map[*types.TypeName]*objcClassInfo
modules []string
// Constructors is a map from Go struct types to a list
// of exported constructor functions for the type, on the form
// func New<Type>(...) *Type
constructors map[*types.TypeName][]*types.Func
}
type objcClassInfo struct {
// The Objc class this class extends.
extends *objc.Named
// All classes and protocols this class extends and conforms to.
supers []*objc.Named
methods map[string]*objc.Func
}
func (g *ObjcGen) Init(wrappers []*objc.Named) {
g.Generator.Init()
g.namePrefix = g.namePrefixOf(g.Pkg)
g.wrapMap = make(map[string]*objc.Named)
g.constructors = make(map[*types.TypeName][]*types.Func)
modMap := make(map[string]struct{})
for _, w := range wrappers {
g.wrapMap[w.GoName] = w
if _, exists := modMap[w.Module]; !exists {
if !w.Generated {
g.modules = append(g.modules, w.Module)
}
modMap[w.Module] = struct{}{}
}
}
if _, exists := modMap["Foundation"]; !exists {
g.modules = append(g.modules, "Foundation")
}
g.ostructs = make(map[*types.TypeName]*objcClassInfo)
for _, s := range g.structs {
embds := embeddedObjcTypes(s.t)
if len(embds) == 0 {
continue
}
inf := &objcClassInfo{
methods: make(map[string]*objc.Func),
}
for _, n := range embds {
t := g.wrapMap[n]
for _, f := range t.AllMethods {
inf.methods[f.GoName] = f
}
inf.supers = append(inf.supers, t)
if !t.Protocol {
if inf.extends != nil {
g.errorf("%s embeds more than one ObjC class; only one is allowed.", s.obj)
}
inf.extends = t
}
}
g.ostructs[s.obj] = inf
}
for _, f := range g.funcs {
if t := g.constructorType(f); t != nil {
g.constructors[t] = append(g.constructors[t], f)
}
}
}
func (g *ObjcGen) namePrefixOf(pkg *types.Package) string {
if pkg == nil {
return "Universe"
}
p := g.Prefix
return p + strings.Title(pkg.Name())
}
func (g *ObjcGen) GenGoH() error {
var pkgPath string
if g.Pkg != nil {
pkgPath = g.Pkg.Path()
}
g.Printf(objcPreamble, pkgPath, g.gobindOpts(), pkgPath)
g.Printf("#ifndef __GO_%s_H__\n", g.pkgName)
g.Printf("#define __GO_%s_H__\n\n", g.pkgName)
g.Printf("#include <stdint.h>\n")
g.Printf("#include <objc/objc.h>\n")
for _, i := range g.interfaces {
if !i.summary.implementable {
continue
}
for _, m := range i.summary.callable {
if !g.isSigSupported(m.Type()) {
g.Printf("// skipped method %s.%s with unsupported parameter or return types\n\n", i.obj.Name(), m.Name())
continue
}
g.genInterfaceMethodSignature(m, i.obj.Name(), true, g.paramName)
g.Printf("\n")
}
}
g.Printf("#endif\n")
if len(g.err) > 0 {
return g.err
}
return nil
}
func (g *ObjcGen) GenH() error {
var pkgPath string
if g.Pkg != nil {
pkgPath = g.Pkg.Path()
}
g.Printf(objcPreamble, pkgPath, g.gobindOpts(), pkgPath)
g.Printf("#ifndef __%s_H__\n", g.namePrefix)
g.Printf("#define __%s_H__\n", g.namePrefix)
g.Printf("\n")
for _, m := range g.modules {
g.Printf("@import %s;\n", m)
}
g.Printf("#include \"ref.h\"\n")
if g.Pkg != nil {
g.Printf("#include \"Universe.objc.h\"\n\n")
}
if g.Pkg != nil {
for _, pkg := range g.Pkg.Imports() {
if g.validPkg(pkg) {
g.Printf("#include %q\n", g.namePrefixOf(pkg)+".objc.h")
}
}
}
g.Printf("\n")
// Forward declaration of @class and @protocol
for _, s := range g.structs {
g.Printf("@class %s%s;\n", g.namePrefix, s.obj.Name())
}
for _, i := range g.interfaces {
g.Printf("@protocol %s%s;\n", g.namePrefix, i.obj.Name())
if i.summary.implementable {
g.Printf("@class %s%s;\n", g.namePrefix, i.obj.Name())
// Forward declaration for other cases will be handled at the beginning of GenM.
}
}
if len(g.structs) > 0 || len(g.interfaces) > 0 {
g.Printf("\n")
}
// @interfaces
for _, i := range g.interfaces {
g.genInterfaceH(i.obj, i.t)
g.Printf("\n")
}
for _, s := range g.structs {
g.genStructH(s.obj, s.t)
g.Printf("\n")
}
// const
// TODO: prefix with k?, or use a class method?
for _, obj := range g.constants {
if _, ok := obj.Type().(*types.Basic); !ok || !g.isSupported(obj.Type()) {
g.Printf("// skipped const %s with unsupported type: %s\n\n", obj.Name(), obj.Type())
continue
}
g.objcdoc(g.docs[obj.Name()].Doc())
switch b := obj.Type().(*types.Basic); b.Kind() {
case types.String, types.UntypedString:
g.Printf("FOUNDATION_EXPORT NSString* _Nonnull const %s%s;\n", g.namePrefix, obj.Name())
default:
g.Printf("FOUNDATION_EXPORT const %s %s%s;\n", g.objcType(obj.Type()), g.namePrefix, obj.Name())
}
}
if len(g.constants) > 0 {
g.Printf("\n")
}
// var
if len(g.vars) > 0 {
g.Printf("@interface %s : NSObject\n", g.namePrefix)
for _, obj := range g.vars {
if t := obj.Type(); !g.isSupported(t) {
g.Printf("// skipped variable %s with unsupported type: %s\n\n", obj.Name(), t)
continue
}
objcType := g.objcType(obj.Type())
g.objcdoc(g.docs[obj.Name()].Doc())
g.Printf("+ (%s) %s;\n", objcType, objcNameReplacer(lowerFirst(obj.Name())))
g.Printf("+ (void) set%s:(%s)v;\n", obj.Name(), objcType)
g.Printf("\n")
}
g.Printf("@end\n\n")
}
// static functions.
for _, obj := range g.funcs {
g.genFuncH(obj)
g.Printf("\n")
}
for _, i := range g.interfaces {
if i.summary.implementable {
g.Printf("@class %s%s;\n\n", g.namePrefix, i.obj.Name())
}
}
for _, i := range g.interfaces {
if i.summary.implementable {
// @interface Interface -- similar to what genStructH does.
g.genInterfaceInterface(i.obj, i.summary, true)
g.Printf("\n")
}
}
g.Printf("#endif\n")
if len(g.err) > 0 {
return g.err
}
return nil
}
func (g *ObjcGen) gobindOpts() string {
opts := []string{"-lang=objc"}
if g.Prefix != "" {
opts = append(opts, fmt.Sprintf("-prefix=%q", g.Prefix))
}
return strings.Join(opts, " ")
}
func (g *ObjcGen) GenM() error {
var pkgPath string
if g.Pkg != nil {
pkgPath = g.Pkg.Path()
}
g.Printf(objcPreamble, pkgPath, g.gobindOpts(), pkgPath)
g.Printf("#include <Foundation/Foundation.h>\n")
g.Printf("#include \"seq.h\"\n")
g.Printf("#include \"_cgo_export.h\"\n")
g.Printf("#include %q\n", g.namePrefix+".objc.h")
g.Printf("\n")
// struct
for _, s := range g.structs {
g.genStructM(s.obj, s.t)
g.Printf("\n")
}
// interface
var needProxy []*types.TypeName
for _, i := range g.interfaces {
if g.genInterfaceM(i.obj, i.t) {
needProxy = append(needProxy, i.obj)
}
g.Printf("\n")
}
// const
for _, o := range g.constants {
g.genConstM(o)
}
if len(g.constants) > 0 {
g.Printf("\n")
}
// vars
if len(g.vars) > 0 {
g.Printf("@implementation %s\n", g.namePrefix)
for _, o := range g.vars {
g.genVarM(o)
}
g.Printf("@end\n\n")
}
g.Printf("\n")
for _, obj := range g.funcs {
if !g.isSigSupported(obj.Type()) {
g.Printf("// skipped function %s with unsupported parameter or return types\n\n", obj.Name())
continue
}
g.genFuncM(obj)
g.Printf("\n")
}
for _, i := range g.interfaces {
for _, m := range i.summary.callable {
if !g.isSigSupported(m.Type()) {
g.Printf("// skipped method %s.%s with unsupported parameter or return types\n\n", i.obj.Name(), m.Name())
continue
}
g.genInterfaceMethodProxy(i.obj, m)
}
}
g.Printf("__attribute__((constructor)) static void init() {\n")
g.Indent()
g.Printf("init_seq();\n")
g.Outdent()
g.Printf("}\n")
if len(g.err) > 0 {
return g.err
}
return nil
}
func (g *ObjcGen) genVarM(o *types.Var) {
if t := o.Type(); !g.isSupported(t) {
g.Printf("// skipped variable %s with unsupported type: %s\n\n", o.Name(), t)
return
}
objcType := g.objcType(o.Type())
// setter
g.Printf("+ (void) set%s:(%s)v {\n", o.Name(), objcType)
g.Indent()
g.genWrite("v", o.Type(), modeRetained)
g.Printf("var_set%s_%s(_v);\n", g.pkgPrefix, o.Name())
g.genRelease("v", o.Type(), modeRetained)
g.Outdent()
g.Printf("}\n\n")
// getter
g.Printf("+ (%s) %s {\n", objcType, objcNameReplacer(lowerFirst(o.Name())))
g.Indent()
g.Printf("%s r0 = ", g.cgoType(o.Type()))
g.Printf("var_get%s_%s();\n", g.pkgPrefix, o.Name())
g.genRead("_r0", "r0", o.Type(), modeRetained)
g.Printf("return _r0;\n")
g.Outdent()
g.Printf("}\n\n")
}
func (g *ObjcGen) genConstM(o *types.Const) {
if _, ok := o.Type().(*types.Basic); !ok || !g.isSupported(o.Type()) {
g.Printf("// skipped const %s with unsupported type: %s\n\n", o.Name(), o.Type())
return
}
cName := fmt.Sprintf("%s%s", g.namePrefix, o.Name())
objcType := g.objcType(o.Type())
switch b := o.Type().(*types.Basic); b.Kind() {
case types.Bool, types.UntypedBool:
v := "NO"
if constant.BoolVal(o.Val()) {
v = "YES"
}
g.Printf("const BOOL %s = %s;\n", cName, v)
case types.String, types.UntypedString:
g.Printf("NSString* const %s = @%s;\n", cName, o.Val().ExactString())
case types.Int, types.Int8, types.Int16, types.Int32:
g.Printf("const %s %s = %s;\n", objcType, cName, o.Val())
case types.Int64, types.UntypedInt:
i, exact := constant.Int64Val(o.Val())
if !exact {
g.errorf("const value %s for %s cannot be represented as %s", o.Val(), o.Name(), objcType)
return
}
if i == math.MinInt64 {
// -9223372036854775808LL does not work because 922337203685477508 is
// larger than max int64.
g.Printf("const int64_t %s = %dLL-1;\n", cName, i+1)
} else {
g.Printf("const int64_t %s = %dLL;\n", cName, i)
}
case types.Float32, types.Float64, types.UntypedFloat:
f, _ := constant.Float64Val(o.Val())
if math.IsInf(f, 0) || math.Abs(f) > math.MaxFloat64 {
g.errorf("const value %s for %s cannot be represented as double", o.Val(), o.Name())
return
}
g.Printf("const %s %s = %g;\n", objcType, cName, f)
default:
g.errorf("unsupported const type %s for %s", b, o.Name())
}
}
type funcSummary struct {
name string
goname string
ret string
sig *types.Signature
params, retParams []paramInfo
hasself bool
initName string
}
type paramInfo struct {
typ types.Type
name string
}
func (g *ObjcGen) funcSummary(obj *types.TypeName, f *types.Func) *funcSummary {
sig := f.Type().(*types.Signature)
s := &funcSummary{goname: f.Name(), sig: sig}
var om *objc.Func
var sigElems []string
oinf := g.ostructs[obj]
if oinf != nil {
om = oinf.methods[f.Name()]
}
if om != nil {
sigElems = strings.Split(om.Sig, ":")
s.name = sigElems[0]
} else {
s.name = f.Name()
}
params := sig.Params()
first := 0
if oinf != nil {
if params.Len() > 0 {
v := params.At(0)
if v.Name() == "self" {
t := v.Type()
if t, ok := t.(*types.Named); ok {
if pkg := t.Obj().Pkg(); pkgFirstElem(pkg) == "ObjC" {
s.hasself = true
module := pkg.Path()[len("ObjC/"):]
typName := module + "." + t.Obj().Name()
exp := g.namePrefix + "." + obj.Name()
if typName != exp {
g.errorf("the type %s of the `this` argument to method %s is not %s", typName, f.Name(), exp)
}
}
}
}
}
}
for i := first; i < params.Len(); i++ {
p := params.At(i)
v := paramInfo{
typ: p.Type(),
}
if om != nil {
v.name = sigElems[i-first]
} else {
v.name = g.paramName(params, i)
}
s.params = append(s.params, v)
}
if obj != nil {
if pref := "New" + obj.Name(); strings.Index(f.Name(), pref) != -1 {
s.initName = "init" + f.Name()[len(pref):]
}
}
res := sig.Results()
switch res.Len() {
case 0:
s.ret = "void"
case 1:
p := res.At(0)
if isErrorType(p.Type()) {
s.retParams = append(s.retParams, paramInfo{
typ: p.Type(),
name: "error",
})
s.ret = "BOOL"
} else {
name := p.Name()
if name == "" || paramRE.MatchString(name) {
name = "ret0_"
}
typ := p.Type()
s.retParams = append(s.retParams, paramInfo{typ: typ, name: name})
s.ret = g.objcType(typ)
}
case 2:
name := res.At(0).Name()
if name == "" || paramRE.MatchString(name) {
name = "ret0_"
}
typ := res.At(0).Type()
s.retParams = append(s.retParams, paramInfo{
typ: typ,
name: name,
})
if isNullableType(typ) {
s.ret = g.objcType(typ) // Return is nullable, so satisfies the ObjC/Swift error protocol
} else {
s.ret = "BOOL" // Return is not nullable, must use an output parameter and return bool
}
if !isErrorType(res.At(1).Type()) {
g.errorf("second result value must be of type error: %s", f)
return nil
}
s.retParams = append(s.retParams, paramInfo{
typ: res.At(1).Type(),
name: "error", // TODO(hyangah): name collision check.
})
default:
// TODO(hyangah): relax the constraint on multiple return params.
g.errorf("too many result values: %s", f)
return nil
}
return s
}
func (s *funcSummary) asFunc(g *ObjcGen) string {
var params []string
for _, p := range s.params {
params = append(params, g.objcParamType(p.typ)+" "+p.name)
}
skip := 0
if s.returnsVal() {
skip = 1
}
for _, p := range s.retParams[skip:] {
params = append(params, g.objcType(p.typ)+"* _Nullable "+p.name)
}
paramContents := "void"
if len(params) > 0 {
paramContents = strings.Join(params, ", ")
}
return fmt.Sprintf("%s %s%s(%s)", s.ret, g.namePrefix, s.name, paramContents)
}
func (s *funcSummary) asMethod(g *ObjcGen) string {
return fmt.Sprintf("(%s)%s%s", s.ret, objcNameReplacer(lowerFirst(s.name)), s.asSignature(g))
}
func (s *funcSummary) asSignature(g *ObjcGen) string {
var params []string
skip := 0
if s.hasself {
skip = 1
}
for i, p := range s.params[skip:] {
var key string
if i != 0 {
key = p.name
}
params = append(params, fmt.Sprintf("%s:(%s)%s", key, g.objcParamType(p.typ), p.name))
}
skip = 0
if s.returnsVal() {
skip = 1
}
for _, p := range s.retParams[skip:] {
var key string
if len(params) > 0 {
key = p.name
}
params = append(params, fmt.Sprintf("%s:(%s)%s", key, g.objcType(p.typ)+"* _Nullable", p.name))
}
return strings.Join(params, " ")
}
func (s *funcSummary) asInitSignature(g *ObjcGen) string {
var params []string
for i, p := range s.params {
var key string
if i > 0 {
key = p.name
}
params = append(params, fmt.Sprintf("%s:(%s)%s", key, g.objcParamType(p.typ), p.name))
}
return strings.Join(params, " ")
}
func (s *funcSummary) callMethod(g *ObjcGen) string {
var params []string
for i, p := range s.params {
var key string
if i != 0 {
key = p.name
}
params = append(params, fmt.Sprintf("%s:_%s", key, p.name))
}
skip := 0
if s.returnsVal() {
skip = 1
}
for _, p := range s.retParams[skip:] {
var key string
if len(params) > 0 {
key = p.name
}
params = append(params, fmt.Sprintf("%s:&%s", key, p.name))
}
return fmt.Sprintf("%s%s", objcNameReplacer(lowerFirst(s.name)), strings.Join(params, " "))
}
func (s *funcSummary) returnsVal() bool {
return (len(s.retParams) == 1 && !isErrorType(s.retParams[0].typ)) || (len(s.retParams) == 2 && isNullableType(s.retParams[0].typ))
}
func (g *ObjcGen) paramName(params *types.Tuple, pos int) string {
name := basicParamName(params, pos)
return objcNameReplacer(name)
}
func (g *ObjcGen) genFuncH(obj *types.Func) {
if !g.isSigSupported(obj.Type()) {
g.Printf("// skipped function %s with unsupported parameter or return types\n\n", obj.Name())
return
}
if s := g.funcSummary(nil, obj); s != nil {
g.objcdoc(g.docs[obj.Name()].Doc())
g.Printf("FOUNDATION_EXPORT %s;\n", s.asFunc(g))
}
}
func (g *ObjcGen) genFuncM(obj *types.Func) {
s := g.funcSummary(nil, obj)
if s == nil {
return
}
g.Printf("%s {\n", s.asFunc(g))
g.Indent()
g.genFunc(s, "")
g.Outdent()
g.Printf("}\n")
}
func (g *ObjcGen) genGetter(oName string, f *types.Var) {
t := f.Type()
g.Printf("- (%s)%s {\n", g.objcType(t), objcNameReplacer(lowerFirst(f.Name())))
g.Indent()
g.Printf("int32_t refnum = go_seq_go_to_refnum(self._ref);\n")
g.Printf("%s r0 = ", g.cgoType(f.Type()))
g.Printf("proxy%s_%s_%s_Get(refnum);\n", g.pkgPrefix, oName, f.Name())
g.genRead("_r0", "r0", f.Type(), modeRetained)
g.Printf("return _r0;\n")
g.Outdent()
g.Printf("}\n\n")
}
func (g *ObjcGen) genSetter(oName string, f *types.Var) {
t := f.Type()
g.Printf("- (void)set%s:(%s)v {\n", f.Name(), g.objcType(t))
g.Indent()
g.Printf("int32_t refnum = go_seq_go_to_refnum(self._ref);\n")
g.genWrite("v", f.Type(), modeRetained)
g.Printf("proxy%s_%s_%s_Set(refnum, _v);\n", g.pkgPrefix, oName, f.Name())
g.genRelease("v", f.Type(), modeRetained)
g.Outdent()
g.Printf("}\n\n")
}
func (g *ObjcGen) genWrite(varName string, t types.Type, mode varMode) {
switch t := t.(type) {
case *types.Basic:
switch t.Kind() {
case types.String:
g.Printf("nstring _%s = go_seq_from_objc_string(%s);\n", varName, varName)
default:
g.Printf("%s _%s = (%s)%s;\n", g.cgoType(t), varName, g.cgoType(t), varName)
}
case *types.Slice:
switch e := t.Elem().(type) {
case *types.Basic:
switch e.Kind() {
case types.Uint8: // Byte.
g.Printf("nbyteslice _%s = go_seq_from_objc_bytearray(%s, %d);\n", varName, varName, toCFlag(mode == modeRetained))
default:
g.errorf("unsupported type: %s", t)
}
default:
g.errorf("unsupported type: %s", t)
}
case *types.Named:
switch u := t.Underlying().(type) {
case *types.Interface:
g.genRefWrite(varName)
default:
g.errorf("unsupported named type: %s / %T", u, u)
}
case *types.Pointer:
g.genRefWrite(varName)
default:
g.Printf("%s _%s = (%s)%s;\n", g.cgoType(t), varName, g.cgoType(t), varName)
}
}
func (g *ObjcGen) genRefWrite(varName string) {
g.Printf("int32_t _%s;\n", varName)
g.Printf("if ([%s conformsToProtocol:@protocol(goSeqRefInterface)]) {\n", varName)
g.Indent()
g.Printf("id<goSeqRefInterface> %[1]s_proxy = (id<goSeqRefInterface>)(%[1]s);\n", varName)
g.Printf("_%s = go_seq_go_to_refnum(%s_proxy._ref);\n", varName, varName)
g.Outdent()
g.Printf("} else {\n")
g.Indent()
g.Printf("_%s = go_seq_to_refnum(%s);\n", varName, varName)
g.Outdent()
g.Printf("}\n")
}
func (g *ObjcGen) genRefRead(toName, fromName string, t types.Type) {
ptype := g.refTypeBase(t)
g.Printf("%s* %s = nil;\n", ptype, toName)
g.Printf("GoSeqRef* %s_ref = go_seq_from_refnum(%s);\n", toName, fromName)
g.Printf("if (%s_ref != NULL) {\n", toName)
g.Printf(" %s = %s_ref.obj;\n", toName, toName)
g.Printf(" if (%s == nil) {\n", toName)
if isObjcType(t) {
g.Printf(" LOG_FATAL(@\"unexpected NULL reference\");\n")
} else {
g.Printf(" %s = [[%s alloc] initWithRef:%s_ref];\n", toName, ptype, toName)
}
g.Printf(" }\n")
g.Printf("}\n")
}
func (g *ObjcGen) genRead(toName, fromName string, t types.Type, mode varMode) {
switch t := t.(type) {
case *types.Basic:
switch t.Kind() {
case types.String:
g.Printf("NSString *%s = go_seq_to_objc_string(%s);\n", toName, fromName)
case types.Bool:
g.Printf("BOOL %s = %s ? YES : NO;\n", toName, fromName)
default:
g.Printf("%s %s = (%s)%s;\n", g.objcType(t), toName, g.objcType(t), fromName)
}
case *types.Slice:
switch e := t.Elem().(type) {
case *types.Basic:
switch e.Kind() {
case types.Uint8: // Byte.
g.Printf("NSData *%s = go_seq_to_objc_bytearray(%s, %d);\n", toName, fromName, toCFlag(mode == modeRetained))
default:
g.errorf("unsupported type: %s", t)
}
default:
g.errorf("unsupported type: %s", t)
}
case *types.Pointer:
switch t := t.Elem().(type) {
case *types.Named:
g.genRefRead(toName, fromName, types.NewPointer(t))
default:
g.errorf("unsupported type %s", t)
}
case *types.Named:
switch t.Underlying().(type) {
case *types.Interface, *types.Pointer:
g.genRefRead(toName, fromName, t)
default:
g.errorf("unsupported, direct named type %s", t)
}
default:
g.Printf("%s %s = (%s)%s;\n", g.objcType(t), toName, g.objcType(t), fromName)
}
}
func (g *ObjcGen) genFunc(s *funcSummary, objName string) {
skip := 0
if objName != "" {
g.Printf("int32_t refnum = go_seq_go_to_refnum(self._ref);\n")
if s.hasself {
skip = 1
g.Printf("int32_t _self = go_seq_to_refnum(self);\n")
}
}
for _, p := range s.params[skip:] {
g.genWrite(p.name, p.typ, modeTransient)
}
resPrefix := ""
if len(s.retParams) > 0 {
if len(s.retParams) == 1 {
g.Printf("%s r0 = ", g.cgoType(s.retParams[0].typ))
} else {
resPrefix = "res."
g.Printf("struct proxy%s_%s_%s_return res = ", g.pkgPrefix, objName, s.goname)
}
}
g.Printf("proxy%s_%s_%s(", g.pkgPrefix, objName, s.goname)
if objName != "" {
g.Printf("refnum")
if s.hasself {
g.Printf(", _self")
}
}
for i, p := range s.params[skip:] {
if i > 0 || objName != "" {
g.Printf(", ")
}
g.Printf("_%s", p.name)
}
g.Printf(");\n")
for _, p := range s.params {
g.genRelease(p.name, p.typ, modeTransient)
}
for i, r := range s.retParams {
g.genRead("_"+r.name, fmt.Sprintf("%sr%d", resPrefix, i), r.typ, modeRetained)
}
skip = 0
if s.returnsVal() {
skip = 1
}
for _, p := range s.retParams[skip:] {
if isErrorType(p.typ) {
g.Printf("if (_%s != nil && %s != nil) {\n", p.name, p.name)
g.Indent()
g.Printf("*%s = _%s;\n", p.name, p.name)
g.Outdent()
g.Printf("}\n")
} else {
g.Printf("*%s = _%s;\n", p.name, p.name)
}
}
if n := len(s.retParams); n > 0 {
var (
first = s.retParams[0]
last = s.retParams[n-1]
)
if (n == 1 && isErrorType(last.typ)) || (n == 2 && !isNullableType(first.typ) && isErrorType(last.typ)) {
g.Printf("return (_%s == nil);\n", last.name)
} else {
if s.returnsVal() && isErrorType(last.typ) {
g.Printf("if (_%s != nil) {\n", last.name)
g.Indent()
g.Printf("return nil;\n")
g.Outdent()
g.Printf("}\n")
}
g.Printf("return _%s;\n", first.name)
}
}
}
func (g *ObjcGen) genInterfaceInterface(obj *types.TypeName, summary ifaceSummary, isProtocol bool) {
doc := g.docs[obj.Name()]
g.objcdoc(doc.Doc())
g.Printf("@interface %[1]s%[2]s : ", g.namePrefix, obj.Name())
if isErrorType(obj.Type()) {
g.Printf("NSError")
} else {
g.Printf("NSObject")
}
prots := []string{"goSeqRefInterface"}
if isProtocol {
prots = append(prots, fmt.Sprintf("%[1]s%[2]s", g.namePrefix, obj.Name()))
}
g.Printf(" <%s>", strings.Join(prots, ", "))
g.Printf(" {\n}\n")
g.Printf("@property(strong, readonly) _Nonnull id _ref;\n")
g.Printf("\n")
g.Printf("- (nonnull instancetype)initWithRef:(_Nonnull id)ref;\n")
for _, m := range summary.callable {
if !g.isSigSupported(m.Type()) {
g.Printf("// skipped method %s.%s with unsupported parameter or return types\n\n", obj.Name(), m.Name())
continue
}
s := g.funcSummary(nil, m)
g.objcdoc(doc.Member(m.Name()))
g.Printf("- %s;\n", s.asMethod(g))
}
g.Printf("@end\n")
}
func (g *ObjcGen) genInterfaceH(obj *types.TypeName, t *types.Interface) {
doc := g.docs[obj.Name()]
summary := makeIfaceSummary(t)
if !summary.implementable {
g.genInterfaceInterface(obj, summary, false)
return
}
g.Printf("@protocol %s%s <NSObject>\n", g.namePrefix, obj.Name())
for _, m := range makeIfaceSummary(t).callable {
if !g.isSigSupported(m.Type()) {
g.Printf("// skipped method %s.%s with unsupported parameter or return types\n\n", obj.Name(), m.Name())
continue
}
s := g.funcSummary(nil, m)
g.objcdoc(doc.Member(m.Name()))
g.Printf("- %s;\n", s.asMethod(g))
}
g.Printf("@end\n")
}
func (g *ObjcGen) genInterfaceM(obj *types.TypeName, t *types.Interface) bool {
summary := makeIfaceSummary(t)
// @implementation Interface -- similar to what genStructM does.
g.Printf("@implementation %s%s {\n", g.namePrefix, obj.Name())
g.Printf("}\n")
g.Printf("\n")
g.Printf("- (nonnull instancetype)initWithRef:(id)ref {\n")
g.Indent()
if isErrorType(obj.Type()) {
g.Printf("if (self) {\n")
g.Printf(" __ref = ref;\n")
g.Printf(" self = [super initWithDomain:@\"go\" code:1 userInfo:@{NSLocalizedDescriptionKey: [self error]}];\n")
g.Printf("}\n")
} else {
g.Printf("self = [super init];\n")
g.Printf("if (self) { __ref = ref; }\n")
}
g.Printf("return self;\n")
g.Outdent()
g.Printf("}\n")
g.Printf("\n")
for _, m := range summary.callable {
if !g.isSigSupported(m.Type()) {
g.Printf("// skipped method %s.%s with unsupported parameter or return types\n\n", obj.Name(), m.Name())
continue
}
s := g.funcSummary(nil, m)
g.Printf("- %s {\n", s.asMethod(g))
g.Indent()
g.genFunc(s, obj.Name())
g.Outdent()
g.Printf("}\n\n")
}
g.Printf("@end\n")
g.Printf("\n")
return summary.implementable
}
func (g *ObjcGen) genInterfaceMethodProxy(obj *types.TypeName, m *types.Func) {
oName := obj.Name()
s := g.funcSummary(nil, m)
g.genInterfaceMethodSignature(m, oName, false, g.paramName)
g.Indent()
g.Printf("@autoreleasepool {\n")
g.Indent()
g.Printf("%s* o = go_seq_objc_from_refnum(refnum);\n", g.refTypeBase(obj.Type()))
for _, p := range s.params {
g.genRead("_"+p.name, p.name, p.typ, modeTransient)
}
// call method
for _, p := range s.retParams {
if isErrorType(p.typ) {
g.Printf("NSError* %s = nil;\n", p.name)
} else {
g.Printf("%s %s;\n", g.objcType(p.typ), p.name)
}
}
if isErrorType(obj.Type()) && m.Name() == "Error" {
// As a special case, ObjC NSErrors are passed to Go pretending to implement the Go error interface.
// They don't actually have an Error method, so calls to it needs to be rerouted.
g.Printf("%s = [o localizedDescription];\n", s.retParams[0].name)
} else {
if s.ret == "void" {
g.Printf("[o %s];\n", s.callMethod(g))
} else if !s.returnsVal() {
g.Printf("%s returnVal = [o %s];\n", s.ret, s.callMethod(g))
} else {
g.Printf("%s = [o %s];\n", s.retParams[0].name, s.callMethod(g))
}
}
if len(s.retParams) > 0 {
if len(s.retParams) == 1 && !isErrorType(s.retParams[0].typ) {
p := s.retParams[0]
g.genWrite(p.name, p.typ, modeRetained)
g.Printf("return _%s;\n", p.name)
} else {
var rets []string
for _, p := range s.retParams {
if isErrorType(p.typ) {
g.Printf("NSError *_%s = nil;\n", p.name)
if !s.returnsVal() {
g.Printf("if (!returnVal) {\n")
} else {
g.Printf("if (%s != nil) {\n", p.name)
}
g.Indent()
g.Printf("_%[1]s = %[1]s;\n", p.name)
g.Outdent()
g.Printf("}\n")
g.genWrite("_"+p.name, p.typ, modeRetained)
rets = append(rets, "__"+p.name)
} else {
g.genWrite(p.name, p.typ, modeRetained)
rets = append(rets, "_"+p.name)
}
}
if len(rets) > 1 {
g.Printf("cproxy%s_%s_%s_return _sres = {\n", g.pkgPrefix, oName, m.Name())
g.Printf(" %s\n", strings.Join(rets, ", "))
g.Printf("};\n")
g.Printf("return _sres;\n")
} else {
g.Printf("return %s;\n", rets[0])
}
}
}
g.Outdent()
g.Printf("}\n")
g.Outdent()
g.Printf("}\n\n")
}
// genRelease cleans up arguments that weren't copied in genWrite.
func (g *ObjcGen) genRelease(varName string, t types.Type, mode varMode) {
switch t := t.(type) {
case *types.Slice:
switch e := t.Elem().(type) {
case *types.Basic:
switch e.Kind() {
case types.Uint8: // Byte.
if mode == modeTransient {
// If the argument was not mutable, go_seq_from_objc_bytearray created a copy.
// Free it here.
g.Printf("if (![%s isKindOfClass:[NSMutableData class]]) {\n", varName)
g.Printf(" free(_%s.ptr);\n", varName)
g.Printf("}\n")
}
}
}
}
}
func (g *ObjcGen) genStructH(obj *types.TypeName, t *types.Struct) {
doc := g.docs[obj.Name()]
g.objcdoc(doc.Doc())
g.Printf("@interface %s%s : ", g.namePrefix, obj.Name())
oinf := g.ostructs[obj]
var prots []string
if oinf != nil {
for _, sup := range oinf.supers {
if !sup.Protocol {
g.Printf(sup.Name)
} else {
prots = append(prots, sup.Name)
}
}
} else {
g.Printf("NSObject")
prots = append(prots, "goSeqRefInterface")
}
pT := types.NewPointer(obj.Type())
for _, iface := range g.allIntf {
p := iface.obj.Pkg()
if g.Pkg != nil && g.Pkg != p {
// To avoid header include cycles, only declare implementation of interfaces
// from imported packages. TODO(elias.naur): Include every interface that
// doesn't introduce an include cycle.
found := false
for _, imp := range g.Pkg.Imports() {
if imp == p {
found = true
break
}
}
if !found {
continue
}
}
obj := iface.obj
if types.AssignableTo(pT, obj.Type()) {
n := fmt.Sprintf("%s%s", g.namePrefixOf(obj.Pkg()), obj.Name())
prots = append(prots, n)
}
}
if len(prots) > 0 {
g.Printf(" <%s>", strings.Join(prots, ", "))
}
g.Printf(" {\n")
g.Printf("}\n")
g.Printf("@property(strong, readonly) _Nonnull id _ref;\n")
g.Printf("\n")
g.Printf("- (nonnull instancetype)initWithRef:(_Nonnull id)ref;\n")
cons := g.constructors[obj]
if oinf == nil {
for _, f := range cons {
if !g.isSigSupported(f.Type()) {
g.Printf("// skipped constructor %s.%s with unsupported parameter or return types\n\n", obj.Name(), f.Name())
continue
}
g.genInitH(obj, f)
}
}
if oinf != nil || len(cons) == 0 {
// default constructor won't return nil
g.Printf("- (nonnull instancetype)init;\n")
}
// accessors to exported fields.
for _, f := range exportedFields(t) {
if t := f.Type(); !g.isSupported(t) {
g.Printf("// skipped field %s.%s with unsupported type: %s\n\n", obj.Name(), f.Name(), t)
continue
}
name, typ := f.Name(), g.objcType(f.Type())
g.objcdoc(doc.Member(f.Name()))
// properties are atomic by default so explicitly say otherwise
g.Printf("@property (nonatomic) %s %s;\n", typ, objcNameReplacer(lowerFirst(name)))
}
// exported methods
for _, m := range exportedMethodSet(types.NewPointer(obj.Type())) {
if !g.isSigSupported(m.Type()) {
g.Printf("// skipped method %s.%s with unsupported parameter or return types\n\n", obj.Name(), m.Name())
continue
}
s := g.funcSummary(obj, m)
g.objcdoc(doc.Member(m.Name()))
g.Printf("- %s;\n", s.asMethod(g))
}
g.Printf("@end\n")
}
func (g *ObjcGen) objcdoc(doc string) {
if doc == "" {
return
}
g.Printf("/**\n * %s */\n", doc)
}
func (g *ObjcGen) genStructM(obj *types.TypeName, t *types.Struct) {
fields := exportedFields(t)
methods := exportedMethodSet(types.NewPointer(obj.Type()))
g.Printf("\n")
oinf := g.ostructs[obj]
g.Printf("@implementation %s%s {\n", g.namePrefix, obj.Name())
g.Printf("}\n\n")
g.Printf("- (nonnull instancetype)initWithRef:(_Nonnull id)ref {\n")
g.Indent()
g.Printf("self = [super init];\n")
g.Printf("if (self) { __ref = ref; }\n")
g.Printf("return self;\n")
g.Outdent()
g.Printf("}\n\n")
cons := g.constructors[obj]
if oinf == nil {
for _, f := range cons {
if !g.isSigSupported(f.Type()) {
g.Printf("// skipped constructor %s.%s with unsupported parameter or return types\n\n", obj, f.Name())
continue
}
g.genInitM(obj, f)
}
}
if oinf != nil || len(cons) == 0 {
g.Printf("- (nonnull instancetype)init {\n")
g.Indent()
g.Printf("self = [super init];\n")
g.Printf("if (self) {\n")
g.Indent()
g.Printf("__ref = go_seq_from_refnum(new_%s_%s());\n", g.pkgPrefix, obj.Name())
g.Outdent()
g.Printf("}\n")
g.Printf("return self;\n")
g.Outdent()
g.Printf("}\n\n")
}
for _, f := range fields {
if !g.isSupported(f.Type()) {
g.Printf("// skipped unsupported field %s with type %s\n\n", f.Name(), f.Type())
continue
}
g.genGetter(obj.Name(), f)
g.genSetter(obj.Name(), f)
}
for _, m := range methods {
if !g.isSigSupported(m.Type()) {
g.Printf("// skipped method %s.%s with unsupported parameter or return types\n\n", obj.Name(), m.Name())
continue
}
s := g.funcSummary(obj, m)
g.Printf("- %s {\n", s.asMethod(g))
g.Indent()
g.genFunc(s, obj.Name())
g.Outdent()
g.Printf("}\n\n")
}
g.Printf("@end\n\n")
}
func (g *ObjcGen) genInitH(obj *types.TypeName, f *types.Func) {
s := g.funcSummary(obj, f)
doc := g.docs[f.Name()]
g.objcdoc(doc.Doc())
// custom inits can return nil in Go so make them nullable
g.Printf("- (nullable instancetype)%s%s;\n", s.initName, s.asInitSignature(g))
}
func (g *ObjcGen) genInitM(obj *types.TypeName, f *types.Func) {
s := g.funcSummary(obj, f)
g.Printf("- (instancetype)%s%s {\n", s.initName, s.asInitSignature(g))
g.Indent()
g.Printf("self = [super init];\n")
g.Printf("if (!self) return nil;\n")
for _, p := range s.params {
g.genWrite(p.name, p.typ, modeTransient)
}
// Constructors always return a mandatory *T and an optional error
if len(s.retParams) == 1 {
g.Printf("%s refnum = ", g.cgoType(s.retParams[0].typ))
} else {
g.Printf("struct proxy%s__%s_return res = ", g.pkgPrefix, s.goname)
}
g.Printf("proxy%s__%s(", g.pkgPrefix, s.goname)
for i, p := range s.params {
if i > 0 {
g.Printf(", ")
}
g.Printf("_%s", p.name)
}
g.Printf(");\n")
for _, p := range s.params {
g.genRelease(p.name, p.typ, modeTransient)
}
if len(s.retParams) == 2 {
g.Printf("int32_t refnum = res.r0;\n")
g.Printf("GoSeqRef *_err = go_seq_from_refnum(res.r1);\n")
}
g.Printf("__ref = go_seq_from_refnum(refnum);\n")
if len(s.retParams) == 2 {
g.Printf("if (_err != NULL)\n")
g.Printf(" return nil;\n")
}
g.Printf("return self;\n")
g.Outdent()
g.Printf("}\n\n")
}
func (g *ObjcGen) errorf(format string, args ...interface{}) {
g.err = append(g.err, fmt.Errorf(format, args...))
}
func (g *ObjcGen) refTypeBase(typ types.Type) string {
switch typ := typ.(type) {
case *types.Pointer:
if _, ok := typ.Elem().(*types.Named); ok {
return g.objcType(typ.Elem())
}
case *types.Named:
n := typ.Obj()
if isObjcType(typ) {
return g.wrapMap[n.Name()].Name
}
if isErrorType(typ) || g.validPkg(n.Pkg()) {
switch typ.Underlying().(type) {
case *types.Interface, *types.Struct:
return g.namePrefixOf(n.Pkg()) + n.Name()
}
}
}
// fallback to whatever objcType returns. This must not happen.
return g.objcType(typ)
}
func (g *ObjcGen) objcParamType(t types.Type) string {
switch typ := t.(type) {
case *types.Basic:
switch typ.Kind() {
case types.String, types.UntypedString:
return "NSString* _Nullable"
}
}
return g.objcType(t)
}
func (g *ObjcGen) objcType(typ types.Type) string {
if isErrorType(typ) {
return "NSError* _Nullable"
}
switch typ := typ.(type) {
case *types.Basic:
switch typ.Kind() {
case types.Bool, types.UntypedBool:
return "BOOL"
case types.Int:
return "long"
case types.Int8:
return "int8_t"
case types.Int16:
return "int16_t"
case types.Int32, types.UntypedRune: // types.Rune
return "int32_t"
case types.Int64, types.UntypedInt:
return "int64_t"
case types.Uint8:
// byte is an alias of uint8, and the alias is lost.
return "byte"
case types.Uint16:
return "uint16_t"
case types.Uint32:
return "uint32_t"
case types.Uint64:
return "uint64_t"
case types.Float32:
return "float"
case types.Float64, types.UntypedFloat:
return "double"
case types.String, types.UntypedString:
return "NSString* _Nonnull"
default:
g.errorf("unsupported type: %s", typ)
return "TODO"
}
case *types.Slice:
elem := g.objcType(typ.Elem())
// Special case: NSData seems to be a better option for byte slice.
if elem == "byte" {
return "NSData* _Nullable"
}
// TODO(hyangah): support other slice types: NSArray or CFArrayRef.
// Investigate the performance implication.
g.errorf("unsupported type: %s", typ)
return "TODO"
case *types.Pointer:
if _, ok := typ.Elem().(*types.Named); ok {
return g.objcType(typ.Elem()) + "* _Nullable"
}
g.errorf("unsupported pointer to type: %s", typ)
return "TODO"
case *types.Named:
n := typ.Obj()
if isObjcType(typ) {
w := g.wrapMap[n.Name()]
return w.ObjcType()
}
if !isErrorType(typ) && !g.validPkg(n.Pkg()) {
g.errorf("type %s is in package %s, which is not bound", n.Name(), n.Pkg().Name())
return "TODO"
}
switch t := typ.Underlying().(type) {
case *types.Interface:
if makeIfaceSummary(t).implementable {
return "id<" + g.namePrefixOf(n.Pkg()) + n.Name() + "> _Nullable"
} else {
return g.namePrefixOf(n.Pkg()) + n.Name() + "* _Nullable"
}
case *types.Struct:
return g.namePrefixOf(n.Pkg()) + n.Name()
}
g.errorf("unsupported, named type %s", typ)
return "TODO"
default:
g.errorf("unsupported type: %#+v, %s", typ, typ)
return "TODO"
}
}
// embeddedObjcTypes returns the possible empty list of Objc types embedded
// in the given struct type.
func embeddedObjcTypes(t *types.Struct) []string {
typeSet := make(map[string]struct{})
var typs []string
for i := 0; i < t.NumFields(); i++ {
f := t.Field(i)
if !f.Exported() {
continue
}
if ft := f.Type(); isObjcType(ft) {
name := ft.(*types.Named).Obj().Name()
if _, exists := typeSet[name]; !exists {
typeSet[name] = struct{}{}
typs = append(typs, name)
}
}
}
return typs
}
func isObjcType(t types.Type) bool {
return typePkgFirstElem(t) == "ObjC"
}
var objcNameReplacer = newNameSanitizer([]string{
"bool", "bycopy", "byref", "char", "const", "double", "float",
"id", "in", "init", "inout", "int", "long", "nil", "oneway",
"out", "self", "short", "signed", "super", "unsigned", "void",
"volatile"})
const (
objcPreamble = `// Objective-C API for talking to %[1]s Go package.
// gobind %[2]s %[3]s
//
// File is generated by gobind. Do not edit.
`
)
|
bind
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/bind/gengo.go
|
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package bind
import (
"bytes"
"fmt"
"go/types"
"strings"
)
type goGen struct {
*Generator
// imports is the list of imports, in the form
// "the/package/path"
//
// or
//
// name "the/package/path"
//
// in case of duplicates.
imports []string
// The set of taken import names.
importNames map[string]struct{}
// importMap is a map from packages to their names. The name of a package is the last
// segment of its path, with duplicates resolved by appending a underscore and a unique
// number.
importMap map[*types.Package]string
}
const (
goPreamble = gobindPreamble + `// Package main is an autogenerated binder stub for package %[1]s.
//
// autogenerated by gobind -lang=go %[2]s
package main
/*
#include <stdlib.h>
#include <stdint.h>
#include "seq.h"
#include "%[1]s.h"
*/
import "C"
`
)
func (g *goGen) genFuncBody(o *types.Func, selectorLHS string) {
sig := o.Type().(*types.Signature)
params := sig.Params()
for i := 0; i < params.Len(); i++ {
p := params.At(i)
pn := "param_" + g.paramName(params, i)
g.genRead("_"+pn, pn, p.Type(), modeTransient)
}
res := sig.Results()
if res.Len() > 2 || res.Len() == 2 && !isErrorType(res.At(1).Type()) {
g.errorf("functions and methods must return either zero or one values, and optionally an error")
return
}
if res.Len() > 0 {
for i := 0; i < res.Len(); i++ {
if i > 0 {
g.Printf(", ")
}
g.Printf("res_%d", i)
}
g.Printf(" := ")
}
g.Printf("%s%s(", selectorLHS, o.Name())
for i := 0; i < params.Len(); i++ {
if i > 0 {
g.Printf(", ")
}
g.Printf("_param_%s", g.paramName(params, i))
}
g.Printf(")\n")
for i := 0; i < res.Len(); i++ {
pn := fmt.Sprintf("res_%d", i)
g.genWrite("_"+pn, pn, res.At(i).Type(), modeRetained)
}
if res.Len() > 0 {
g.Printf("return ")
for i := 0; i < res.Len(); i++ {
if i > 0 {
g.Printf(", ")
}
g.Printf("_res_%d", i)
}
g.Printf("\n")
}
}
func (g *goGen) genWrite(toVar, fromVar string, t types.Type, mode varMode) {
switch t := t.(type) {
case *types.Basic:
switch t.Kind() {
case types.String:
g.Printf("%s := encodeString(%s)\n", toVar, fromVar)
case types.Bool:
g.Printf("var %s C.%s = 0\n", toVar, g.cgoType(t))
g.Printf("if %s { %s = 1 }\n", fromVar, toVar)
default:
g.Printf("%s := C.%s(%s)\n", toVar, g.cgoType(t), fromVar)
}
case *types.Slice:
switch e := t.Elem().(type) {
case *types.Basic:
switch e.Kind() {
case types.Uint8: // Byte.
g.Printf("%s := fromSlice(%s, %v)\n", toVar, fromVar, mode == modeRetained)
default:
g.errorf("unsupported type: %s", t)
}
default:
g.errorf("unsupported type: %s", t)
}
case *types.Pointer:
// TODO(crawshaw): test *int
// TODO(crawshaw): test **Generator
switch t := t.Elem().(type) {
case *types.Named:
g.genToRefNum(toVar, fromVar)
default:
g.errorf("unsupported type %s", t)
}
case *types.Named:
switch u := t.Underlying().(type) {
case *types.Interface, *types.Pointer:
g.genToRefNum(toVar, fromVar)
default:
g.errorf("unsupported, direct named type %s: %s", t, u)
}
default:
g.errorf("unsupported type %s", t)
}
}
// genToRefNum generates Go code for converting a variable to its refnum.
// Note that the nil-check cannot be lifted into seq.ToRefNum, because a nil
// struct pointer does not convert to a nil interface.
func (g *goGen) genToRefNum(toVar, fromVar string) {
g.Printf("var %s C.int32_t = _seq.NullRefNum\n", toVar)
g.Printf("if %s != nil {\n", fromVar)
g.Printf(" %s = C.int32_t(_seq.ToRefNum(%s))\n", toVar, fromVar)
g.Printf("}\n")
}
func (g *goGen) genFuncSignature(o *types.Func, objName string) {
g.Printf("//export proxy%s_%s_%s\n", g.pkgPrefix, objName, o.Name())
g.Printf("func proxy%s_%s_%s(", g.pkgPrefix, objName, o.Name())
if objName != "" {
g.Printf("refnum C.int32_t")
}
sig := o.Type().(*types.Signature)
params := sig.Params()
for i := 0; i < params.Len(); i++ {
if objName != "" || i > 0 {
g.Printf(", ")
}
p := params.At(i)
g.Printf("param_%s C.%s", g.paramName(params, i), g.cgoType(p.Type()))
}
g.Printf(") ")
res := sig.Results()
if res.Len() > 0 {
g.Printf("(")
for i := 0; i < res.Len(); i++ {
if i > 0 {
g.Printf(", ")
}
g.Printf("C.%s", g.cgoType(res.At(i).Type()))
}
g.Printf(") ")
}
g.Printf("{\n")
}
func (g *goGen) paramName(params *types.Tuple, pos int) string {
return basicParamName(params, pos)
}
func (g *goGen) genFunc(o *types.Func) {
if !g.isSigSupported(o.Type()) {
g.Printf("// skipped function %s with unsupported parameter or result types\n", o.Name())
return
}
g.genFuncSignature(o, "")
g.Indent()
g.genFuncBody(o, g.pkgName(g.Pkg))
g.Outdent()
g.Printf("}\n\n")
}
func (g *goGen) genStruct(obj *types.TypeName, T *types.Struct) {
fields := exportedFields(T)
methods := exportedMethodSet(types.NewPointer(obj.Type()))
for _, f := range fields {
if t := f.Type(); !g.isSupported(t) {
g.Printf("// skipped field %s.%s with unsupported type: %s\n\n", obj.Name(), f.Name(), t)
continue
}
g.Printf("//export proxy%s_%s_%s_Set\n", g.pkgPrefix, obj.Name(), f.Name())
g.Printf("func proxy%s_%s_%s_Set(refnum C.int32_t, v C.%s) {\n", g.pkgPrefix, obj.Name(), f.Name(), g.cgoType(f.Type()))
g.Indent()
g.Printf("ref := _seq.FromRefNum(int32(refnum))\n")
g.genRead("_v", "v", f.Type(), modeRetained)
g.Printf("ref.Get().(*%s%s).%s = _v\n", g.pkgName(g.Pkg), obj.Name(), f.Name())
g.Outdent()
g.Printf("}\n\n")
g.Printf("//export proxy%s_%s_%s_Get\n", g.pkgPrefix, obj.Name(), f.Name())
g.Printf("func proxy%s_%s_%s_Get(refnum C.int32_t) C.%s {\n", g.pkgPrefix, obj.Name(), f.Name(), g.cgoType(f.Type()))
g.Indent()
g.Printf("ref := _seq.FromRefNum(int32(refnum))\n")
g.Printf("v := ref.Get().(*%s%s).%s\n", g.pkgName(g.Pkg), obj.Name(), f.Name())
g.genWrite("_v", "v", f.Type(), modeRetained)
g.Printf("return _v\n")
g.Outdent()
g.Printf("}\n\n")
}
for _, m := range methods {
if !g.isSigSupported(m.Type()) {
g.Printf("// skipped method %s.%s with unsupported parameter or return types\n\n", obj.Name(), m.Name())
continue
}
g.genFuncSignature(m, obj.Name())
g.Indent()
g.Printf("ref := _seq.FromRefNum(int32(refnum))\n")
g.Printf("v := ref.Get().(*%s%s)\n", g.pkgName(g.Pkg), obj.Name())
g.genFuncBody(m, "v.")
g.Outdent()
g.Printf("}\n\n")
}
// Export constructor for ObjC and Java default no-arg constructors
g.Printf("//export new_%s_%s\n", g.Pkg.Name(), obj.Name())
g.Printf("func new_%s_%s() C.int32_t {\n", g.Pkg.Name(), obj.Name())
g.Indent()
g.Printf("return C.int32_t(_seq.ToRefNum(new(%s%s)))\n", g.pkgName(g.Pkg), obj.Name())
g.Outdent()
g.Printf("}\n")
}
func (g *goGen) genVar(o *types.Var) {
if t := o.Type(); !g.isSupported(t) {
g.Printf("// skipped variable %s with unsupported type %s\n\n", o.Name(), t)
return
}
// TODO(hyangah): non-struct pointer types (*int), struct type.
v := fmt.Sprintf("%s%s", g.pkgName(g.Pkg), o.Name())
// var I int
//
// func var_setI(v int)
g.Printf("//export var_set%s_%s\n", g.pkgPrefix, o.Name())
g.Printf("func var_set%s_%s(v C.%s) {\n", g.pkgPrefix, o.Name(), g.cgoType(o.Type()))
g.Indent()
g.genRead("_v", "v", o.Type(), modeRetained)
g.Printf("%s = _v\n", v)
g.Outdent()
g.Printf("}\n")
// func var_getI() int
g.Printf("//export var_get%s_%s\n", g.pkgPrefix, o.Name())
g.Printf("func var_get%s_%s() C.%s {\n", g.pkgPrefix, o.Name(), g.cgoType(o.Type()))
g.Indent()
g.Printf("v := %s\n", v)
g.genWrite("_v", "v", o.Type(), modeRetained)
g.Printf("return _v\n")
g.Outdent()
g.Printf("}\n")
}
func (g *goGen) genInterface(obj *types.TypeName) {
iface := obj.Type().(*types.Named).Underlying().(*types.Interface)
summary := makeIfaceSummary(iface)
// Define the entry points.
for _, m := range summary.callable {
if !g.isSigSupported(m.Type()) {
g.Printf("// skipped method %s.%s with unsupported parameter or return types\n\n", obj.Name(), m.Name())
continue
}
g.genFuncSignature(m, obj.Name())
g.Indent()
g.Printf("ref := _seq.FromRefNum(int32(refnum))\n")
g.Printf("v := ref.Get().(%s%s)\n", g.pkgName(g.Pkg), obj.Name())
g.genFuncBody(m, "v.")
g.Outdent()
g.Printf("}\n\n")
}
// Define a proxy interface.
if !summary.implementable {
// The interface defines an unexported method or a method that
// uses an unexported type. We cannot generate a proxy object
// for such a type.
return
}
g.Printf("type proxy%s_%s _seq.Ref\n\n", g.pkgPrefix, obj.Name())
g.Printf("func (p *proxy%s_%s) Bind_proxy_refnum__() int32 {\n", g.pkgPrefix, obj.Name())
g.Indent()
g.Printf("return (*_seq.Ref)(p).Bind_IncNum()\n")
g.Outdent()
g.Printf("}\n\n")
for _, m := range summary.callable {
if !g.isSigSupported(m.Type()) {
g.Printf("// skipped method %s.%s with unsupported parameter or result types\n", obj.Name(), m.Name())
continue
}
sig := m.Type().(*types.Signature)
params := sig.Params()
res := sig.Results()
if res.Len() > 2 ||
(res.Len() == 2 && !isErrorType(res.At(1).Type())) {
g.errorf("functions and methods must return either zero or one value, and optionally an error: %s.%s", obj.Name(), m.Name())
continue
}
g.Printf("func (p *proxy%s_%s) %s(", g.pkgPrefix, obj.Name(), m.Name())
for i := 0; i < params.Len(); i++ {
if i > 0 {
g.Printf(", ")
}
g.Printf("param_%s %s", g.paramName(params, i), g.typeString(params.At(i).Type()))
}
g.Printf(") ")
if res.Len() == 1 {
g.Printf(g.typeString(res.At(0).Type()))
} else if res.Len() == 2 {
g.Printf("(%s, error)", g.typeString(res.At(0).Type()))
}
g.Printf(" {\n")
g.Indent()
for i := 0; i < params.Len(); i++ {
pn := "param_" + g.paramName(params, i)
g.genWrite("_"+pn, pn, params.At(i).Type(), modeTransient)
}
if res.Len() > 0 {
g.Printf("res := ")
}
g.Printf("C.cproxy%s_%s_%s(C.int32_t(p.Bind_proxy_refnum__())", g.pkgPrefix, obj.Name(), m.Name())
for i := 0; i < params.Len(); i++ {
g.Printf(", _param_%s", g.paramName(params, i))
}
g.Printf(")\n")
var retName string
if res.Len() > 0 {
if res.Len() == 1 {
T := res.At(0).Type()
g.genRead("_res", "res", T, modeRetained)
retName = "_res"
} else {
var rvs []string
for i := 0; i < res.Len(); i++ {
rv := fmt.Sprintf("res_%d", i)
g.genRead(rv, fmt.Sprintf("res.r%d", i), res.At(i).Type(), modeRetained)
rvs = append(rvs, rv)
}
retName = strings.Join(rvs, ", ")
}
g.Printf("return %s\n", retName)
}
g.Outdent()
g.Printf("}\n\n")
}
}
func (g *goGen) genRead(toVar, fromVar string, typ types.Type, mode varMode) {
switch t := typ.(type) {
case *types.Basic:
switch t.Kind() {
case types.String:
g.Printf("%s := decodeString(%s)\n", toVar, fromVar)
case types.Bool:
g.Printf("%s := %s != 0\n", toVar, fromVar)
default:
g.Printf("%s := %s(%s)\n", toVar, t.Underlying().String(), fromVar)
}
case *types.Slice:
switch e := t.Elem().(type) {
case *types.Basic:
switch e.Kind() {
case types.Uint8: // Byte.
g.Printf("%s := toSlice(%s, %v)\n", toVar, fromVar, mode == modeRetained)
default:
g.errorf("unsupported type: %s", t)
}
default:
g.errorf("unsupported type: %s", t)
}
case *types.Pointer:
switch u := t.Elem().(type) {
case *types.Named:
o := u.Obj()
oPkg := o.Pkg()
if !g.validPkg(oPkg) {
g.errorf("type %s is defined in %s, which is not bound", u, oPkg)
return
}
g.Printf("// Must be a Go object\n")
g.Printf("var %s *%s%s\n", toVar, g.pkgName(oPkg), o.Name())
g.Printf("if %s_ref := _seq.FromRefNum(int32(%s)); %s_ref != nil {\n", toVar, fromVar, toVar)
g.Printf(" %s = %s_ref.Get().(*%s%s)\n", toVar, toVar, g.pkgName(oPkg), o.Name())
g.Printf("}\n")
default:
g.errorf("unsupported pointer type %s", t)
}
case *types.Named:
switch t.Underlying().(type) {
case *types.Interface, *types.Pointer:
hasProxy := true
if iface, ok := t.Underlying().(*types.Interface); ok {
hasProxy = makeIfaceSummary(iface).implementable
}
pkgFirst := typePkgFirstElem(t)
isWrapper := pkgFirst == "Java" || pkgFirst == "ObjC"
o := t.Obj()
oPkg := o.Pkg()
if !isErrorType(t) && !g.validPkg(oPkg) && !isWrapper {
g.errorf("type %s is defined in %s, which is not bound", t, oPkg)
return
}
g.Printf("var %s %s\n", toVar, g.typeString(t))
g.Printf("%s_ref := _seq.FromRefNum(int32(%s))\n", toVar, fromVar)
g.Printf("if %s_ref != nil {\n", toVar)
g.Printf(" if %s < 0 { // go object \n", fromVar)
g.Printf(" %s = %s_ref.Get().(%s%s)\n", toVar, toVar, g.pkgName(oPkg), o.Name())
if hasProxy {
g.Printf(" } else { // foreign object \n")
if isWrapper {
var clsName string
switch pkgFirst {
case "Java":
clsName = flattenName(classNameFor(t))
case "ObjC":
clsName = t.Obj().Name()
}
g.Printf(" %s = (*proxy_class_%s)(%s_ref)\n", toVar, clsName, toVar)
} else {
g.Printf(" %s = (*proxy%s_%s)(%s_ref)\n", toVar, pkgPrefix(oPkg), o.Name(), toVar)
}
}
g.Printf(" }\n")
g.Printf("}\n")
default:
g.errorf("unsupported named type %s", t)
}
default:
g.errorf("unsupported type: %s", typ)
}
}
func (g *goGen) typeString(typ types.Type) string {
pkg := g.Pkg
switch t := typ.(type) {
case *types.Named:
obj := t.Obj()
if obj.Pkg() == nil { // e.g. error type is *types.Named.
return types.TypeString(typ, types.RelativeTo(pkg))
}
oPkg := obj.Pkg()
if !g.validPkg(oPkg) && !isWrapperType(t) {
g.errorf("type %s is defined in %s, which is not bound", t, oPkg)
return "TODO"
}
switch t.Underlying().(type) {
case *types.Interface, *types.Struct:
return fmt.Sprintf("%s%s", g.pkgName(oPkg), types.TypeString(typ, types.RelativeTo(oPkg)))
default:
g.errorf("unsupported named type %s / %T", t, t)
}
case *types.Pointer:
switch t := t.Elem().(type) {
case *types.Named:
return fmt.Sprintf("*%s", g.typeString(t))
default:
g.errorf("not yet supported, pointer type %s / %T", t, t)
}
default:
return types.TypeString(typ, types.RelativeTo(pkg))
}
return ""
}
// genPreamble generates the preamble. It is generated after everything
// else, where we know which bound packages to import.
func (g *goGen) genPreamble() {
pkgName := ""
pkgPath := ""
if g.Pkg != nil {
pkgName = g.Pkg.Name()
pkgPath = g.Pkg.Path()
} else {
pkgName = "universe"
}
g.Printf(goPreamble, pkgName, pkgPath)
g.Printf("import (\n")
g.Indent()
g.Printf("_seq \"golang.org/x/mobile/bind/seq\"\n")
for _, imp := range g.imports {
g.Printf("%s\n", imp)
}
g.Outdent()
g.Printf(")\n\n")
}
func (g *goGen) gen() error {
g.importNames = make(map[string]struct{})
g.importMap = make(map[*types.Package]string)
// Switch to a temporary buffer so the preamble can be
// written last.
oldBuf := g.Printer.Buf
newBuf := new(bytes.Buffer)
g.Printer.Buf = newBuf
g.Printf("// suppress the error if seq ends up unused\n")
g.Printf("var _ = _seq.FromRefNum\n")
for _, s := range g.structs {
g.genStruct(s.obj, s.t)
}
for _, intf := range g.interfaces {
g.genInterface(intf.obj)
}
for _, v := range g.vars {
g.genVar(v)
}
for _, f := range g.funcs {
g.genFunc(f)
}
// Switch to the original buffer, write the preamble
// and append the rest of the file.
g.Printer.Buf = oldBuf
g.genPreamble()
g.Printer.Buf.Write(newBuf.Bytes())
if len(g.err) > 0 {
return g.err
}
return nil
}
// pkgName returns the package name and adds the package to the list of
// imports.
func (g *goGen) pkgName(pkg *types.Package) string {
// The error type has no package
if pkg == nil {
return ""
}
if name, exists := g.importMap[pkg]; exists {
return name + "."
}
i := 0
pname := pkg.Name()
name := pkg.Name()
for {
if _, exists := g.importNames[name]; !exists {
g.importNames[name] = struct{}{}
g.importMap[pkg] = name
var imp string
if pname != name {
imp = fmt.Sprintf("%s %q", name, pkg.Path())
} else {
imp = fmt.Sprintf("%q", pkg.Path())
}
g.imports = append(g.imports, imp)
break
}
i++
name = fmt.Sprintf("%s_%d", pname, i)
}
g.importMap[pkg] = name
return name + "."
}
|
bind
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/bind/printer.go
|
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package bind
import (
"bytes"
"fmt"
)
type Printer struct {
Buf *bytes.Buffer
IndentEach []byte
indentText []byte
needIndent bool
}
func (p *Printer) writeIndent() error {
if !p.needIndent {
return nil
}
p.needIndent = false
_, err := p.Buf.Write(p.indentText)
return err
}
func (p *Printer) Write(b []byte) (n int, err error) {
wrote := 0
for len(b) > 0 {
if err := p.writeIndent(); err != nil {
return wrote, err
}
i := bytes.IndexByte(b, '\n')
if i < 0 {
break
}
n, err = p.Buf.Write(b[0 : i+1])
wrote += n
if err != nil {
return wrote, err
}
b = b[i+1:]
p.needIndent = true
}
if len(b) > 0 {
n, err = p.Buf.Write(b)
wrote += n
}
return wrote, err
}
func (p *Printer) Printf(format string, args ...interface{}) {
if _, err := fmt.Fprintf(p, format, args...); err != nil {
panic(fmt.Sprintf("printer: %v", err))
}
}
func (p *Printer) Indent() {
p.indentText = append(p.indentText, p.IndentEach...)
}
func (p *Printer) Outdent() {
if len(p.indentText) > len(p.IndentEach)-1 {
p.indentText = p.indentText[len(p.IndentEach):]
}
}
|
bind
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/bind/seq.go.support
|
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
// Go support functions for generated Go bindings. This file is
// copied into the generated main package, and compiled along
// with the bindings.
// #cgo android CFLAGS: -D__GOBIND_ANDROID__
// #cgo darwin CFLAGS: -D__GOBIND_DARWIN__
// #include <stdlib.h>
// #include "seq.h"
import "C"
import (
"fmt"
"os"
"os/signal"
"syscall"
_ "golang.org/x/mobile/bind/java"
_seq "golang.org/x/mobile/bind/seq"
)
func init() {
_seq.FinalizeRef = func(ref *_seq.Ref) {
refnum := ref.Bind_Num
if refnum < 0 {
panic(fmt.Sprintf("not a foreign ref: %d", refnum))
}
C.go_seq_dec_ref(C.int32_t(refnum))
}
_seq.IncForeignRef = func(refnum int32) {
if refnum < 0 {
panic(fmt.Sprintf("not a foreign ref: %d", refnum))
}
C.go_seq_inc_ref(C.int32_t(refnum))
}
// Workaround for issue #17393.
signal.Notify(make(chan os.Signal), syscall.SIGPIPE)
}
// IncGoRef is called by foreign code to pin a Go object while its refnum is crossing
// the language barrier
//export IncGoRef
func IncGoRef(refnum C.int32_t) {
_seq.Inc(int32(refnum))
}
func main() {}
|
bind
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/bind/gen.go
|
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package bind
import (
"bytes"
"fmt"
"go/ast"
"go/token"
"go/types"
"io"
"regexp"
"strings"
"unicode"
"unicode/utf8"
)
type (
ErrorList []error
// varMode describes the lifetime of an argument or
// return value. Modes are used to guide the conversion
// of string and byte slice values across the language
// barrier. The same conversion mode must be used for
// both the conversion before a foreign call and the
// corresponding conversion after the call.
// See the mode* constants for a description of
// each mode.
varMode int
)
const (
// modeTransient are for function arguments that
// are not used after the function returns.
// Transient byte slices don't need copying
// when passed across the language barrier.
modeTransient varMode = iota
// modeRetained are for returned values and for function
// arguments that are used after the function returns.
// Retained byte slices need an intermediate copy.
modeRetained
)
func (list ErrorList) Error() string {
buf := new(bytes.Buffer)
for i, err := range list {
if i > 0 {
buf.WriteRune('\n')
}
io.WriteString(buf, err.Error())
}
return buf.String()
}
// interfaceInfo comes from Init and collects the auxiliary information
// needed to generate bindings for an exported Go interface in a bound
// package.
type interfaceInfo struct {
obj *types.TypeName
t *types.Interface
summary ifaceSummary
}
// structInfo comes from Init and collects the auxiliary information
// needed to generate bindings for an exported Go struct in a bound
// package.
type structInfo struct {
obj *types.TypeName
t *types.Struct
}
// Generator contains the common Go package information
// needed for the specific Go, Java, ObjC generators.
//
// After setting Printer, Fset, AllPkg, Pkg, the Init
// method is used to initialize the auxiliary information
// about the package to be generated, Pkg.
type Generator struct {
*Printer
Fset *token.FileSet
AllPkg []*types.Package
Files []*ast.File
Pkg *types.Package
err ErrorList
// fields set by init.
pkgName string
pkgPrefix string
funcs []*types.Func
constants []*types.Const
vars []*types.Var
interfaces []interfaceInfo
structs []structInfo
otherNames []*types.TypeName
// allIntf contains interfaces from all bound packages.
allIntf []interfaceInfo
docs pkgDocs
}
// A pkgDocs maps the name of each exported package-level declaration to its extracted documentation.
type pkgDocs map[string]*pkgDoc
type pkgDoc struct {
doc string
// Struct or interface fields and methods.
members map[string]string
}
// pkgPrefix returns a prefix that disambiguates symbol names for binding
// multiple packages.
//
// TODO(elias.naur): Avoid (and test) name clashes from multiple packages
// with the same name. Perhaps use the index from the order the package is
// generated.
func pkgPrefix(pkg *types.Package) string {
// The error type has no package
if pkg == nil {
return ""
}
return pkg.Name()
}
func (g *Generator) Init() {
if g.Pkg != nil {
g.pkgName = g.Pkg.Name()
}
g.pkgPrefix = pkgPrefix(g.Pkg)
if g.Pkg != nil {
g.parseDocs()
scope := g.Pkg.Scope()
hasExported := false
for _, name := range scope.Names() {
obj := scope.Lookup(name)
if !obj.Exported() {
continue
}
hasExported = true
switch obj := obj.(type) {
case *types.Func:
if isCallable(obj) {
g.funcs = append(g.funcs, obj)
}
case *types.TypeName:
named, ok := obj.Type().(*types.Named)
if !ok {
continue
}
switch t := named.Underlying().(type) {
case *types.Struct:
g.structs = append(g.structs, structInfo{obj, t})
case *types.Interface:
g.interfaces = append(g.interfaces, interfaceInfo{obj, t, makeIfaceSummary(t)})
default:
g.otherNames = append(g.otherNames, obj)
}
case *types.Const:
g.constants = append(g.constants, obj)
case *types.Var:
g.vars = append(g.vars, obj)
default:
g.errorf("unsupported exported type for %s: %T", obj.Name(), obj)
}
}
if !hasExported {
g.errorf("no exported names in the package %q", g.Pkg.Path())
}
} else {
// Bind the single supported type from the universe scope, error.
errType := types.Universe.Lookup("error").(*types.TypeName)
t := errType.Type().Underlying().(*types.Interface)
g.interfaces = append(g.interfaces, interfaceInfo{errType, t, makeIfaceSummary(t)})
}
for _, p := range g.AllPkg {
scope := p.Scope()
for _, name := range scope.Names() {
obj := scope.Lookup(name)
if !obj.Exported() {
continue
}
if obj, ok := obj.(*types.TypeName); ok {
named, ok := obj.Type().(*types.Named)
if !ok {
continue
}
if t, ok := named.Underlying().(*types.Interface); ok {
g.allIntf = append(g.allIntf, interfaceInfo{obj, t, makeIfaceSummary(t)})
}
}
}
}
}
// parseDocs extracts documentation from a package in a form useful for lookups.
func (g *Generator) parseDocs() {
d := make(pkgDocs)
for _, f := range g.Files {
for _, decl := range f.Decls {
switch decl := decl.(type) {
case *ast.GenDecl:
for _, spec := range decl.Specs {
switch spec := spec.(type) {
case *ast.TypeSpec:
d.addType(spec, decl.Doc)
case *ast.ValueSpec:
d.addValue(spec, decl.Doc)
}
}
case *ast.FuncDecl:
d.addFunc(decl)
}
}
}
g.docs = d
}
func (d pkgDocs) addValue(t *ast.ValueSpec, outerDoc *ast.CommentGroup) {
for _, n := range t.Names {
if !ast.IsExported(n.Name) {
continue
}
doc := t.Doc
if doc == nil {
doc = outerDoc
}
if doc != nil {
d[n.Name] = &pkgDoc{doc: doc.Text()}
}
}
}
func (d pkgDocs) addFunc(f *ast.FuncDecl) {
doc := f.Doc
if doc == nil {
return
}
fn := f.Name.Name
if !ast.IsExported(fn) {
return
}
if r := f.Recv; r != nil {
// f is a method.
n := typeName(r.List[0].Type)
pd, exists := d[n]
if !exists {
pd = &pkgDoc{members: make(map[string]string)}
d[n] = pd
}
pd.members[fn] = doc.Text()
} else {
// f is a function.
d[fn] = &pkgDoc{doc: doc.Text()}
}
}
func (d pkgDocs) addType(t *ast.TypeSpec, outerDoc *ast.CommentGroup) {
if !ast.IsExported(t.Name.Name) {
return
}
doc := t.Doc
if doc == nil {
doc = outerDoc
}
pd := d[t.Name.Name]
pd = &pkgDoc{members: make(map[string]string)}
d[t.Name.Name] = pd
if doc != nil {
pd.doc = doc.Text()
}
var fields *ast.FieldList
switch t := t.Type.(type) {
case *ast.StructType:
fields = t.Fields
case *ast.InterfaceType:
fields = t.Methods
}
if fields != nil {
for _, field := range fields.List {
if field.Doc != nil {
if field.Names == nil {
// Anonymous field. Extract name from its type.
if n := typeName(field.Type); ast.IsExported(n) {
pd.members[n] = field.Doc.Text()
}
}
for _, n := range field.Names {
if ast.IsExported(n.Name) {
pd.members[n.Name] = field.Doc.Text()
}
}
}
}
}
}
// typeName returns the type name T for expressions on the
// T, *T, **T (etc.) form.
func typeName(t ast.Expr) string {
switch t := t.(type) {
case *ast.StarExpr:
return typeName(t.X)
case *ast.Ident:
return t.Name
case *ast.SelectorExpr:
return t.Sel.Name
default:
return ""
}
}
func (d *pkgDoc) Doc() string {
if d == nil {
return ""
}
return d.doc
}
func (d *pkgDoc) Member(n string) string {
if d == nil {
return ""
}
return d.members[n]
}
// constructorType returns the type T for a function of the forms:
//
// func NewT...(...) *T
// func NewT...(...) (*T, error)
func (g *Generator) constructorType(f *types.Func) *types.TypeName {
sig := f.Type().(*types.Signature)
res := sig.Results()
if res.Len() != 1 && !(res.Len() == 2 && isErrorType(res.At(1).Type())) {
return nil
}
rt := res.At(0).Type()
pt, ok := rt.(*types.Pointer)
if !ok {
return nil
}
nt, ok := pt.Elem().(*types.Named)
if !ok {
return nil
}
obj := nt.Obj()
if !strings.HasPrefix(f.Name(), "New"+obj.Name()) {
return nil
}
return obj
}
func toCFlag(v bool) int {
if v {
return 1
}
return 0
}
func (g *Generator) errorf(format string, args ...interface{}) {
g.err = append(g.err, fmt.Errorf(format, args...))
}
// cgoType returns the name of a Cgo type suitable for converting a value of
// the given type.
func (g *Generator) cgoType(t types.Type) string {
switch t := t.(type) {
case *types.Basic:
switch t.Kind() {
case types.Bool, types.UntypedBool:
return "char"
case types.Int:
return "nint"
case types.Int8:
return "int8_t"
case types.Int16:
return "int16_t"
case types.Int32, types.UntypedRune: // types.Rune
return "int32_t"
case types.Int64, types.UntypedInt:
return "int64_t"
case types.Uint8: // types.Byte
return "uint8_t"
// TODO(crawshaw): case types.Uint, types.Uint16, types.Uint32, types.Uint64:
case types.Float32:
return "float"
case types.Float64, types.UntypedFloat:
return "double"
case types.String:
return "nstring"
default:
g.errorf("unsupported basic type: %s", t)
}
case *types.Slice:
switch e := t.Elem().(type) {
case *types.Basic:
switch e.Kind() {
case types.Uint8: // Byte.
return "nbyteslice"
default:
g.errorf("unsupported slice type: %s", t)
}
default:
g.errorf("unsupported slice type: %s", t)
}
case *types.Pointer:
if _, ok := t.Elem().(*types.Named); ok {
return g.cgoType(t.Elem())
}
g.errorf("unsupported pointer to type: %s", t)
case *types.Named:
return "int32_t"
default:
g.errorf("unsupported type: %s", t)
}
return "TODO"
}
func (g *Generator) genInterfaceMethodSignature(m *types.Func, iName string, header bool, g_paramName func(*types.Tuple, int) string) {
sig := m.Type().(*types.Signature)
params := sig.Params()
res := sig.Results()
if res.Len() == 0 {
g.Printf("void ")
} else {
if res.Len() == 1 {
g.Printf("%s ", g.cgoType(res.At(0).Type()))
} else {
if header {
g.Printf("typedef struct cproxy%s_%s_%s_return {\n", g.pkgPrefix, iName, m.Name())
g.Indent()
for i := 0; i < res.Len(); i++ {
t := res.At(i).Type()
g.Printf("%s r%d;\n", g.cgoType(t), i)
}
g.Outdent()
g.Printf("} cproxy%s_%s_%s_return;\n", g.pkgPrefix, iName, m.Name())
}
g.Printf("struct cproxy%s_%s_%s_return ", g.pkgPrefix, iName, m.Name())
}
}
g.Printf("cproxy%s_%s_%s(int32_t refnum", g.pkgPrefix, iName, m.Name())
for i := 0; i < params.Len(); i++ {
t := params.At(i).Type()
g.Printf(", %s %s", g.cgoType(t), g_paramName(params, i))
}
g.Printf(")")
if header {
g.Printf(";\n")
} else {
g.Printf(" {\n")
}
}
func (g *Generator) validPkg(pkg *types.Package) bool {
for _, p := range g.AllPkg {
if p == pkg {
return true
}
}
return false
}
// isSigSupported reports whether the generators can handle a given
// function signature.
func (g *Generator) isSigSupported(t types.Type) bool {
sig := t.(*types.Signature)
params := sig.Params()
for i := 0; i < params.Len(); i++ {
if !g.isSupported(params.At(i).Type()) {
return false
}
}
res := sig.Results()
for i := 0; i < res.Len(); i++ {
if !g.isSupported(res.At(i).Type()) {
return false
}
}
return true
}
// isSupported reports whether the generators can handle the type.
func (g *Generator) isSupported(t types.Type) bool {
if isErrorType(t) || isWrapperType(t) {
return true
}
switch t := t.(type) {
case *types.Basic:
switch t.Kind() {
case types.Bool, types.UntypedBool,
types.Int,
types.Int8, types.Uint8, // types.Byte
types.Int16,
types.Int32, types.UntypedRune, // types.Rune
types.Int64, types.UntypedInt,
types.Float32,
types.Float64, types.UntypedFloat,
types.String, types.UntypedString:
return true
}
return false
case *types.Slice:
switch e := t.Elem().(type) {
case *types.Basic:
return e.Kind() == types.Uint8
}
case *types.Pointer:
switch t := t.Elem().(type) {
case *types.Named:
return g.validPkg(t.Obj().Pkg())
}
case *types.Named:
switch t.Underlying().(type) {
case *types.Interface, *types.Pointer:
return g.validPkg(t.Obj().Pkg())
}
}
return false
}
var paramRE = regexp.MustCompile(`^p[0-9]*$`)
// basicParamName replaces incompatible name with a p0-pN name.
// Missing names, or existing names of the form p[0-9] are incompatible.
func basicParamName(params *types.Tuple, pos int) string {
name := params.At(pos).Name()
if name == "" || name[0] == '_' || paramRE.MatchString(name) {
name = fmt.Sprintf("p%d", pos)
}
return name
}
func lowerFirst(s string) string {
if s == "" {
return ""
}
var conv []rune
for len(s) > 0 {
r, n := utf8.DecodeRuneInString(s)
if !unicode.IsUpper(r) {
if l := len(conv); l > 1 {
conv[l-1] = unicode.ToUpper(conv[l-1])
}
return string(conv) + s
}
conv = append(conv, unicode.ToLower(r))
s = s[n:]
}
return string(conv)
}
// newNameSanitizer returns a functions that replaces all dashes and dots
// with underscores, as well as avoiding reserved words by suffixing such
// identifiers with underscores.
func newNameSanitizer(res []string) func(s string) string {
reserved := make(map[string]bool)
for _, word := range res {
reserved[word] = true
}
symbols := strings.NewReplacer(
"-", "_",
".", "_",
)
return func(s string) string {
if reserved[s] {
return s + "_"
}
return symbols.Replace(s)
}
}
|
bind
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/bind/bind_test.go
|
package bind
import (
"bytes"
"flag"
"go/ast"
"go/build"
"go/format"
"go/importer"
"go/parser"
"go/token"
"go/types"
"io"
"io/ioutil"
"log"
"os"
"os/exec"
"path"
"path/filepath"
"runtime"
"strings"
"testing"
"golang.org/x/mobile/internal/importers"
"golang.org/x/mobile/internal/importers/java"
"golang.org/x/mobile/internal/importers/objc"
)
func init() {
log.SetFlags(log.Lshortfile)
}
var updateFlag = flag.Bool("update", false, "Update the golden files.")
var tests = []string{
"", // The universe package with the error type.
"testdata/basictypes.go",
"testdata/structs.go",
"testdata/interfaces.go",
"testdata/issue10788.go",
"testdata/issue12328.go",
"testdata/issue12403.go",
"testdata/issue29559.go",
"testdata/keywords.go",
"testdata/try.go",
"testdata/vars.go",
"testdata/ignore.go",
"testdata/doc.go",
"testdata/underscores.go",
}
var javaTests = []string{
"testdata/java.go",
"testdata/classes.go",
}
var objcTests = []string{
"testdata/objc.go",
"testdata/objcw.go",
}
var fset = token.NewFileSet()
func fileRefs(t *testing.T, filename string, pkgPrefix string) *importers.References {
f, err := parser.ParseFile(fset, filename, nil, parser.AllErrors)
if err != nil {
t.Fatalf("%s: %v", filename, err)
}
refs, err := importers.AnalyzeFile(f, pkgPrefix)
if err != nil {
t.Fatalf("%s: %v", filename, err)
}
fakePath := path.Dir(filename)
for i := range refs.Embedders {
refs.Embedders[i].PkgPath = fakePath
}
return refs
}
func typeCheck(t *testing.T, filename string, gopath string) (*types.Package, *ast.File) {
f, err := parser.ParseFile(fset, filename, nil, parser.AllErrors|parser.ParseComments)
if err != nil {
t.Fatalf("%s: %v", filename, err)
}
pkgName := filepath.Base(filename)
pkgName = strings.TrimSuffix(pkgName, ".go")
// typecheck and collect typechecker errors
var conf types.Config
conf.Error = func(err error) {
t.Error(err)
}
if gopath != "" {
conf.Importer = importer.Default()
oldDefault := build.Default
defer func() { build.Default = oldDefault }()
build.Default.GOPATH = gopath
}
pkg, err := conf.Check(pkgName, fset, []*ast.File{f}, nil)
if err != nil {
t.Fatal(err)
}
return pkg, f
}
// diff runs the command "diff a b" and returns its output
func diff(a, b string) string {
var buf bytes.Buffer
var cmd *exec.Cmd
switch runtime.GOOS {
case "plan9":
cmd = exec.Command("/bin/diff", "-c", a, b)
default:
cmd = exec.Command("/usr/bin/diff", "-u", a, b)
}
cmd.Stdout = &buf
cmd.Stderr = &buf
cmd.Run()
return buf.String()
}
func writeTempFile(t *testing.T, name string, contents []byte) string {
f, err := ioutil.TempFile("", name)
if err != nil {
t.Fatal(err)
}
if _, err := f.Write(contents); err != nil {
t.Fatal(err)
}
if err := f.Close(); err != nil {
t.Fatal(err)
}
return f.Name()
}
func TestGenObjc(t *testing.T) {
for _, filename := range tests {
var pkg *types.Package
var file *ast.File
if filename != "" {
pkg, file = typeCheck(t, filename, "")
}
var buf bytes.Buffer
g := &ObjcGen{
Generator: &Generator{
Printer: &Printer{Buf: &buf, IndentEach: []byte("\t")},
Fset: fset,
Files: []*ast.File{file},
Pkg: pkg,
},
}
if pkg != nil {
g.AllPkg = []*types.Package{pkg}
}
g.Init(nil)
testcases := []struct {
suffix string
gen func() error
}{
{
".objc.h.golden",
g.GenH,
},
{
".objc.m.golden",
g.GenM,
},
{
".objc.go.h.golden",
g.GenGoH,
},
}
for _, tc := range testcases {
buf.Reset()
if err := tc.gen(); err != nil {
t.Errorf("%s: %v", filename, err)
continue
}
out := writeTempFile(t, "generated"+tc.suffix, buf.Bytes())
defer os.Remove(out)
var golden string
if filename != "" {
golden = filename[:len(filename)-len(".go")]
} else {
golden = "testdata/universe"
}
golden += tc.suffix
if diffstr := diff(golden, out); diffstr != "" {
t.Errorf("%s: does not match Objective-C golden:\n%s", filename, diffstr)
if *updateFlag {
t.Logf("Updating %s...", golden)
err := exec.Command("/bin/cp", out, golden).Run()
if err != nil {
t.Errorf("Update failed: %s", err)
}
}
}
}
}
}
func genObjcPackages(t *testing.T, dir string, cg *ObjcWrapper) {
pkgBase := filepath.Join(dir, "src", "ObjC")
if err := os.MkdirAll(pkgBase, 0700); err != nil {
t.Fatal(err)
}
for i, jpkg := range cg.Packages() {
pkgDir := filepath.Join(pkgBase, jpkg)
if err := os.MkdirAll(pkgDir, 0700); err != nil {
t.Fatal(err)
}
pkgFile := filepath.Join(pkgDir, "package.go")
cg.Buf.Reset()
cg.GenPackage(i)
if err := ioutil.WriteFile(pkgFile, cg.Buf.Bytes(), 0600); err != nil {
t.Fatal(err)
}
}
cg.Buf.Reset()
cg.GenInterfaces()
clsFile := filepath.Join(pkgBase, "interfaces.go")
if err := ioutil.WriteFile(clsFile, cg.Buf.Bytes(), 0600); err != nil {
t.Fatal(err)
}
gocmd := filepath.Join(runtime.GOROOT(), "bin", "go")
cmd := exec.Command(
gocmd,
"install",
"-pkgdir="+filepath.Join(dir, "pkg", build.Default.GOOS+"_"+build.Default.GOARCH),
"ObjC/...",
)
cmd.Env = append(os.Environ(), "GOPATH="+dir, "GO111MODULE=off")
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("failed to go install the generated ObjC wrappers: %v: %s", err, string(out))
}
}
func genJavaPackages(t *testing.T, dir string, cg *ClassGen) {
buf := cg.Buf
cg.Buf = new(bytes.Buffer)
pkgBase := filepath.Join(dir, "src", "Java")
if err := os.MkdirAll(pkgBase, 0700); err != nil {
t.Fatal(err)
}
for i, jpkg := range cg.Packages() {
pkgDir := filepath.Join(pkgBase, jpkg)
if err := os.MkdirAll(pkgDir, 0700); err != nil {
t.Fatal(err)
}
pkgFile := filepath.Join(pkgDir, "package.go")
cg.Buf.Reset()
cg.GenPackage(i)
if err := ioutil.WriteFile(pkgFile, cg.Buf.Bytes(), 0600); err != nil {
t.Fatal(err)
}
io.Copy(buf, cg.Buf)
}
cg.Buf.Reset()
cg.GenInterfaces()
clsFile := filepath.Join(pkgBase, "interfaces.go")
if err := ioutil.WriteFile(clsFile, cg.Buf.Bytes(), 0600); err != nil {
t.Fatal(err)
}
io.Copy(buf, cg.Buf)
cg.Buf = buf
gocmd := filepath.Join(runtime.GOROOT(), "bin", "go")
cmd := exec.Command(
gocmd,
"install",
"-pkgdir="+filepath.Join(dir, "pkg", build.Default.GOOS+"_"+build.Default.GOARCH),
"Java/...",
)
cmd.Env = append(os.Environ(), "GOPATH="+dir, "GO111MODULE=off")
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("failed to go install the generated Java wrappers: %v: %s", err, string(out))
}
}
func TestGenJava(t *testing.T) {
allTests := tests
if java.IsAvailable() {
allTests = append(append([]string{}, allTests...), javaTests...)
}
for _, filename := range allTests {
var pkg *types.Package
var file *ast.File
var buf bytes.Buffer
var cg *ClassGen
var classes []*java.Class
if filename != "" {
refs := fileRefs(t, filename, "Java/")
imp := &java.Importer{}
var err error
classes, err = imp.Import(refs)
if err != nil {
t.Fatal(err)
}
tmpGopath := ""
if len(classes) > 0 {
tmpGopath, err = ioutil.TempDir(os.TempDir(), "gomobile-bind-test-")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpGopath)
cg = &ClassGen{
Printer: &Printer{
IndentEach: []byte("\t"),
Buf: new(bytes.Buffer),
},
}
cg.Init(classes, refs.Embedders)
genJavaPackages(t, tmpGopath, cg)
cg.Buf = &buf
}
pkg, file = typeCheck(t, filename, tmpGopath)
}
g := &JavaGen{
Generator: &Generator{
Printer: &Printer{Buf: &buf, IndentEach: []byte(" ")},
Fset: fset,
Files: []*ast.File{file},
Pkg: pkg,
},
}
if pkg != nil {
g.AllPkg = []*types.Package{pkg}
}
g.Init(classes)
testCases := []struct {
suffix string
gen func() error
}{
{
".java.golden",
func() error {
for i := range g.ClassNames() {
if err := g.GenClass(i); err != nil {
return err
}
}
return g.GenJava()
},
},
{
".java.c.golden",
func() error {
if cg != nil {
cg.GenC()
}
return g.GenC()
},
},
{
".java.h.golden",
func() error {
if cg != nil {
cg.GenH()
}
return g.GenH()
},
},
}
for _, tc := range testCases {
buf.Reset()
if err := tc.gen(); err != nil {
t.Errorf("%s: %v", filename, err)
continue
}
out := writeTempFile(t, "generated"+tc.suffix, buf.Bytes())
defer os.Remove(out)
var golden string
if filename != "" {
golden = filename[:len(filename)-len(".go")]
} else {
golden = "testdata/universe"
}
golden += tc.suffix
if diffstr := diff(golden, out); diffstr != "" {
t.Errorf("%s: does not match Java golden:\n%s", filename, diffstr)
if *updateFlag {
t.Logf("Updating %s...", golden)
if err := exec.Command("/bin/cp", out, golden).Run(); err != nil {
t.Errorf("Update failed: %s", err)
}
}
}
}
}
}
func TestGenGo(t *testing.T) {
for _, filename := range tests {
var buf bytes.Buffer
var pkg *types.Package
if filename != "" {
pkg, _ = typeCheck(t, filename, "")
}
testGenGo(t, filename, &buf, pkg)
}
}
func TestGenGoJavaWrappers(t *testing.T) {
if !java.IsAvailable() {
t.Skipf("java is not available")
}
for _, filename := range javaTests {
var buf bytes.Buffer
refs := fileRefs(t, filename, "Java/")
imp := &java.Importer{}
classes, err := imp.Import(refs)
if err != nil {
t.Fatal(err)
}
tmpGopath, err := ioutil.TempDir(os.TempDir(), "gomobile-bind-test-")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpGopath)
cg := &ClassGen{
Printer: &Printer{
IndentEach: []byte("\t"),
Buf: &buf,
},
}
cg.Init(classes, refs.Embedders)
genJavaPackages(t, tmpGopath, cg)
pkg, _ := typeCheck(t, filename, tmpGopath)
cg.GenGo()
testGenGo(t, filename, &buf, pkg)
}
}
func TestGenGoObjcWrappers(t *testing.T) {
if runtime.GOOS != "darwin" {
t.Skipf("can only generate objc wrappers on darwin")
}
for _, filename := range objcTests {
var buf bytes.Buffer
refs := fileRefs(t, filename, "ObjC/")
types, err := objc.Import(refs)
if err != nil {
t.Fatal(err)
}
tmpGopath, err := ioutil.TempDir(os.TempDir(), "gomobile-bind-test-")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpGopath)
cg := &ObjcWrapper{
Printer: &Printer{
IndentEach: []byte("\t"),
Buf: &buf,
},
}
var genNames []string
for _, emb := range refs.Embedders {
genNames = append(genNames, emb.Name)
}
cg.Init(types, genNames)
genObjcPackages(t, tmpGopath, cg)
pkg, _ := typeCheck(t, filename, tmpGopath)
cg.GenGo()
testGenGo(t, filename, &buf, pkg)
}
}
func testGenGo(t *testing.T, filename string, buf *bytes.Buffer, pkg *types.Package) {
conf := &GeneratorConfig{
Writer: buf,
Fset: fset,
Pkg: pkg,
}
if pkg != nil {
conf.AllPkg = []*types.Package{pkg}
}
if err := GenGo(conf); err != nil {
t.Errorf("%s: %v", filename, err)
return
}
// TODO(hyangah): let GenGo format the generated go files.
out := writeTempFile(t, "go", gofmt(t, buf.Bytes()))
defer os.Remove(out)
golden := filename
if golden == "" {
golden = "testdata/universe"
}
golden += ".golden"
goldenContents, err := ioutil.ReadFile(golden)
if err != nil {
t.Fatalf("failed to read golden file: %v", err)
}
// format golden file using the current go version's formatting rule.
formattedGolden := writeTempFile(t, "go", gofmt(t, goldenContents))
defer os.Remove(formattedGolden)
if diffstr := diff(formattedGolden, out); diffstr != "" {
t.Errorf("%s: does not match Go golden:\n%s", filename, diffstr)
if *updateFlag {
t.Logf("Updating %s...", golden)
if err := exec.Command("/bin/cp", out, golden).Run(); err != nil {
t.Errorf("Update failed: %s", err)
}
}
}
}
// gofmt formats the collection of Go source files auto-generated by gobind.
func gofmt(t *testing.T, src []byte) []byte {
t.Helper()
buf := &bytes.Buffer{}
mark := []byte(gobindPreamble)
for i, c := range bytes.Split(src, mark) {
if i == 0 {
buf.Write(c)
continue
}
tmp := append(mark, c...)
out, err := format.Source(tmp)
if err != nil {
t.Fatalf("failed to format Go file: error=%v\n----\n%s\n----", err, tmp)
}
if _, err := buf.Write(out); err != nil {
t.Fatalf("failed to write formatted file to buffer: %v", err)
}
}
return buf.Bytes()
}
func TestCustomPrefix(t *testing.T) {
const datafile = "testdata/customprefix.go"
pkg, file := typeCheck(t, datafile, "")
type testCase struct {
golden string
gen func(w io.Writer) error
}
var buf bytes.Buffer
jg := &JavaGen{
JavaPkg: "com.example",
Generator: &Generator{
Printer: &Printer{Buf: &buf, IndentEach: []byte(" ")},
Fset: fset,
AllPkg: []*types.Package{pkg},
Files: []*ast.File{file},
Pkg: pkg,
},
}
jg.Init(nil)
testCases := []testCase{
{
"testdata/customprefix.java.golden",
func(w io.Writer) error {
buf.Reset()
for i := range jg.ClassNames() {
if err := jg.GenClass(i); err != nil {
return err
}
}
if err := jg.GenJava(); err != nil {
return err
}
_, err := io.Copy(w, &buf)
return err
},
},
{
"testdata/customprefix.java.h.golden",
func(w io.Writer) error {
buf.Reset()
if err := jg.GenH(); err != nil {
return err
}
_, err := io.Copy(w, &buf)
return err
},
},
{
"testdata/customprefix.java.c.golden",
func(w io.Writer) error {
buf.Reset()
if err := jg.GenC(); err != nil {
return err
}
_, err := io.Copy(w, &buf)
return err
},
},
}
for _, pref := range []string{"EX", ""} {
og := &ObjcGen{
Prefix: pref,
Generator: &Generator{
Printer: &Printer{Buf: &buf, IndentEach: []byte(" ")},
Fset: fset,
AllPkg: []*types.Package{pkg},
Pkg: pkg,
},
}
og.Init(nil)
testCases = append(testCases, []testCase{
{
"testdata/customprefix" + pref + ".objc.go.h.golden",
func(w io.Writer) error {
buf.Reset()
if err := og.GenGoH(); err != nil {
return err
}
_, err := io.Copy(w, &buf)
return err
},
},
{
"testdata/customprefix" + pref + ".objc.h.golden",
func(w io.Writer) error {
buf.Reset()
if err := og.GenH(); err != nil {
return err
}
_, err := io.Copy(w, &buf)
return err
},
},
{
"testdata/customprefix" + pref + ".objc.m.golden",
func(w io.Writer) error {
buf.Reset()
if err := og.GenM(); err != nil {
return err
}
_, err := io.Copy(w, &buf)
return err
},
},
}...)
}
for _, tc := range testCases {
var buf bytes.Buffer
if err := tc.gen(&buf); err != nil {
t.Errorf("generating %s: %v", tc.golden, err)
continue
}
out := writeTempFile(t, "generated", buf.Bytes())
defer os.Remove(out)
if diffstr := diff(tc.golden, out); diffstr != "" {
t.Errorf("%s: generated file does not match:\b%s", tc.golden, diffstr)
if *updateFlag {
t.Logf("Updating %s...", tc.golden)
err := exec.Command("/bin/cp", out, tc.golden).Run()
if err != nil {
t.Errorf("Update failed: %s", err)
}
}
}
}
}
func TestLowerFirst(t *testing.T) {
testCases := []struct {
in, want string
}{
{"", ""},
{"Hello", "hello"},
{"HelloGopher", "helloGopher"},
{"hello", "hello"},
{"ID", "id"},
{"IDOrName", "idOrName"},
{"ΓειαΣας", "γειαΣας"},
}
for _, tc := range testCases {
if got := lowerFirst(tc.in); got != tc.want {
t.Errorf("lowerFirst(%q) = %q; want %q", tc.in, got, tc.want)
}
}
}
// Test that typeName work for anonymous qualified fields.
func TestSelectorExprTypeName(t *testing.T) {
e, err := parser.ParseExprFrom(fset, "", "struct { bytes.Buffer }", 0)
if err != nil {
t.Fatal(err)
}
ft := e.(*ast.StructType).Fields.List[0].Type
if got, want := typeName(ft), "Buffer"; got != want {
t.Errorf("got: %q; want %q", got, want)
}
}
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/bind/testdata/try.go.golden
|
// Code generated by gobind. DO NOT EDIT.
// Package main is an autogenerated binder stub for package try.
//
// autogenerated by gobind -lang=go try
package main
/*
#include <stdlib.h>
#include <stdint.h>
#include "seq.h"
#include "try.h"
*/
import "C"
import (
_seq "golang.org/x/mobile/bind/seq"
"try"
)
// suppress the error if seq ends up unused
var _ = _seq.FromRefNum
//export proxytry__This
func proxytry__This() C.nstring {
res_0 := try.This()
_res_0 := encodeString(res_0)
return _res_0
}
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/bind/testdata/basictypes.java.golden
|
// Code generated by gobind. DO NOT EDIT.
// Java class basictypes.Basictypes is a proxy for talking to a Go program.
//
// autogenerated by gobind -lang=java basictypes
package basictypes;
import go.Seq;
public abstract class Basictypes {
static {
Seq.touch(); // for loading the native library
_init();
}
private Basictypes() {} // uninstantiable
// touch is called from other bound packages to initialize this package
public static void touch() {}
private static native void _init();
public static final boolean ABool = true;
public static final double AFloat = 0.2015;
public static final String ALongString = "LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString";
public static final int ARune = 32;
public static final String AString = "a string";
public static final long AnInt = 7L;
public static final long AnInt2 = 9223372036854775807L;
public static native boolean bool(boolean p0);
public static native byte[] byteArrays(byte[] x);
public static native void error() throws Exception;
public static native long errorPair() throws Exception;
public static native void ints(byte x, short y, int z, long t, long u);
}
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/bind/testdata/issue29559.go
|
package issue29559
type AString = string
func TakesAString(s AString) {}
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/bind/testdata/structs.java.h.golden
|
// Code generated by gobind. DO NOT EDIT.
// JNI function headers for the Go <=> Java bridge.
//
// autogenerated by gobind -lang=java structs
#ifndef __Structs_H__
#define __Structs_H__
#include <jni.h>
extern jclass proxy_class_structs_I;
extern jmethodID proxy_class_structs_I_cons;
void cproxystructs_I_M(int32_t refnum);
extern jclass proxy_class_structs_S;
extern jmethodID proxy_class_structs_S_cons;
extern jclass proxy_class_structs_S2;
extern jmethodID proxy_class_structs_S2_cons;
extern jclass proxy_class_structs_Structs;
extern jmethodID proxy_class_structs_Structs_cons;
#endif
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/bind/testdata/doc.objc.h.golden
|
// Objective-C API for talking to doc Go package.
// gobind -lang=objc doc
//
// File is generated by gobind. Do not edit.
#ifndef __Doc_H__
#define __Doc_H__
@import Foundation;
#include "ref.h"
#include "Universe.objc.h"
@class DocNoDoc;
@class DocS;
@class DocS2;
@protocol DocI;
@class DocI;
@protocol DocI <NSObject>
/**
* IM is a method.
*/
- (void)im;
@end
/**
* A generic comment with <HTML>.
*/
@interface DocNoDoc : NSObject <goSeqRefInterface> {
}
@property(strong, readonly) _Nonnull id _ref;
- (nonnull instancetype)initWithRef:(_Nonnull id)ref;
- (nonnull instancetype)init;
@end
/**
* S is a struct.
*/
@interface DocS : NSObject <goSeqRefInterface> {
}
@property(strong, readonly) _Nonnull id _ref;
- (nonnull instancetype)initWithRef:(_Nonnull id)ref;
/**
* NewS is a constructor.
*/
- (nullable instancetype)init;
/**
* SF is a field.
*/
@property (nonatomic) NSString* _Nonnull sf;
/**
* Anonymous field.
*/
@property (nonatomic) DocS2* _Nullable s2;
/**
* Multiple fields.
*/
@property (nonatomic) NSString* _Nonnull f1;
/**
* Multiple fields.
*/
@property (nonatomic) NSString* _Nonnull f2;
/**
* After is another method.
*/
- (void)after;
- (void)before;
@end
/**
* S2 is a struct.
*/
@interface DocS2 : NSObject <goSeqRefInterface> {
}
@property(strong, readonly) _Nonnull id _ref;
- (nonnull instancetype)initWithRef:(_Nonnull id)ref;
- (nonnull instancetype)init;
@end
/**
* C is a constant.
*/
FOUNDATION_EXPORT const BOOL DocC;
@interface Doc : NSObject
/**
* A group of vars.
*/
+ (double) noDocVar;
+ (void) setNoDocVar:(double)v;
/**
* A specific var.
*/
+ (NSString* _Nonnull) specific;
+ (void) setSpecific:(NSString* _Nonnull)v;
/**
* V is a var.
*/
+ (NSString* _Nonnull) v;
+ (void) setV:(NSString* _Nonnull)v;
@end
/**
* F is a function.
*/
FOUNDATION_EXPORT void DocF(void);
/**
* NewS is a constructor.
*/
FOUNDATION_EXPORT DocS* _Nullable DocNewS(void);
@class DocI;
/**
* I is an interface.
*/
@interface DocI : NSObject <goSeqRefInterface, DocI> {
}
@property(strong, readonly) _Nonnull id _ref;
- (nonnull instancetype)initWithRef:(_Nonnull id)ref;
/**
* IM is a method.
*/
- (void)im;
@end
#endif
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/bind/testdata/interfaces.java.h.golden
|
// Code generated by gobind. DO NOT EDIT.
// JNI function headers for the Go <=> Java bridge.
//
// autogenerated by gobind -lang=java interfaces
#ifndef __Interfaces_H__
#define __Interfaces_H__
#include <jni.h>
extern jclass proxy_class_interfaces_Error;
extern jmethodID proxy_class_interfaces_Error_cons;
int32_t cproxyinterfaces_Error_Err(int32_t refnum);
extern jclass proxy_class_interfaces_I;
extern jmethodID proxy_class_interfaces_I_cons;
int32_t cproxyinterfaces_I_Rand(int32_t refnum);
extern jclass proxy_class_interfaces_I1;
extern jmethodID proxy_class_interfaces_I1_cons;
void cproxyinterfaces_I1_J(int32_t refnum);
extern jclass proxy_class_interfaces_I2;
extern jmethodID proxy_class_interfaces_I2_cons;
void cproxyinterfaces_I2_G(int32_t refnum);
extern jclass proxy_class_interfaces_I3;
extern jmethodID proxy_class_interfaces_I3_cons;
int32_t cproxyinterfaces_I3_F(int32_t refnum);
extern jclass proxy_class_interfaces_Interfaces;
extern jmethodID proxy_class_interfaces_Interfaces_cons;
void cproxyinterfaces_Interfaces_SomeMethod(int32_t refnum);
extern jclass proxy_class_interfaces_LargerI;
extern jmethodID proxy_class_interfaces_LargerI_cons;
void cproxyinterfaces_LargerI_AnotherFunc(int32_t refnum);
int32_t cproxyinterfaces_LargerI_Rand(int32_t refnum);
extern jclass proxy_class_interfaces_SameI;
extern jmethodID proxy_class_interfaces_SameI_cons;
int32_t cproxyinterfaces_SameI_Rand(int32_t refnum);
extern jclass proxy_class_interfaces_WithParam;
extern jmethodID proxy_class_interfaces_WithParam_cons;
void cproxyinterfaces_WithParam_HasParam(int32_t refnum, char p0);
#endif
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/bind/testdata/issue10788.go.golden
|
// Code generated by gobind. DO NOT EDIT.
// Package main is an autogenerated binder stub for package issue10788.
//
// autogenerated by gobind -lang=go issue10788
package main
/*
#include <stdlib.h>
#include <stdint.h>
#include "seq.h"
#include "issue10788.h"
*/
import "C"
import (
_seq "golang.org/x/mobile/bind/seq"
"issue10788"
)
// suppress the error if seq ends up unused
var _ = _seq.FromRefNum
//export proxyissue10788_TestStruct_Value_Set
func proxyissue10788_TestStruct_Value_Set(refnum C.int32_t, v C.nstring) {
ref := _seq.FromRefNum(int32(refnum))
_v := decodeString(v)
ref.Get().(*issue10788.TestStruct).Value = _v
}
//export proxyissue10788_TestStruct_Value_Get
func proxyissue10788_TestStruct_Value_Get(refnum C.int32_t) C.nstring {
ref := _seq.FromRefNum(int32(refnum))
v := ref.Get().(*issue10788.TestStruct).Value
_v := encodeString(v)
return _v
}
//export new_issue10788_TestStruct
func new_issue10788_TestStruct() C.int32_t {
return C.int32_t(_seq.ToRefNum(new(issue10788.TestStruct)))
}
//export proxyissue10788_TestInterface_DoSomeWork
func proxyissue10788_TestInterface_DoSomeWork(refnum C.int32_t, param_s C.int32_t) {
ref := _seq.FromRefNum(int32(refnum))
v := ref.Get().(issue10788.TestInterface)
// Must be a Go object
var _param_s *issue10788.TestStruct
if _param_s_ref := _seq.FromRefNum(int32(param_s)); _param_s_ref != nil {
_param_s = _param_s_ref.Get().(*issue10788.TestStruct)
}
v.DoSomeWork(_param_s)
}
//export proxyissue10788_TestInterface_MultipleUnnamedParams
func proxyissue10788_TestInterface_MultipleUnnamedParams(refnum C.int32_t, param_p0 C.nint, param_p1 C.nstring, param_日本 C.int64_t) {
ref := _seq.FromRefNum(int32(refnum))
v := ref.Get().(issue10788.TestInterface)
_param_p0 := int(param_p0)
_param_p1 := decodeString(param_p1)
_param_日本 := int64(param_日本)
v.MultipleUnnamedParams(_param_p0, _param_p1, _param_日本)
}
type proxyissue10788_TestInterface _seq.Ref
func (p *proxyissue10788_TestInterface) Bind_proxy_refnum__() int32 {
return (*_seq.Ref)(p).Bind_IncNum()
}
func (p *proxyissue10788_TestInterface) DoSomeWork(param_s *issue10788.TestStruct) {
var _param_s C.int32_t = _seq.NullRefNum
if param_s != nil {
_param_s = C.int32_t(_seq.ToRefNum(param_s))
}
C.cproxyissue10788_TestInterface_DoSomeWork(C.int32_t(p.Bind_proxy_refnum__()), _param_s)
}
func (p *proxyissue10788_TestInterface) MultipleUnnamedParams(param_p0 int, param_p1 string, param_日本 int64) {
_param_p0 := C.nint(param_p0)
_param_p1 := encodeString(param_p1)
_param_日本 := C.int64_t(param_日本)
C.cproxyissue10788_TestInterface_MultipleUnnamedParams(C.int32_t(p.Bind_proxy_refnum__()), _param_p0, _param_p1, _param_日本)
}
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/bind/testdata/universe.objc.go.h.golden
|
// Objective-C API for talking to Go package.
// gobind -lang=objc
//
// File is generated by gobind. Do not edit.
#ifndef __GO__H__
#define __GO__H__
#include <stdint.h>
#include <objc/objc.h>
nstring cproxy_error_Error(int32_t refnum);
#endif
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/bind/testdata/issue12403.go.golden
|
// Code generated by gobind. DO NOT EDIT.
// Package main is an autogenerated binder stub for package issue12403.
//
// autogenerated by gobind -lang=go issue12403
package main
/*
#include <stdlib.h>
#include <stdint.h>
#include "seq.h"
#include "issue12403.h"
*/
import "C"
import (
_seq "golang.org/x/mobile/bind/seq"
"issue12403"
)
// suppress the error if seq ends up unused
var _ = _seq.FromRefNum
//export proxyissue12403_Parsable_FromJSON
func proxyissue12403_Parsable_FromJSON(refnum C.int32_t, param_jstr C.nstring) C.nstring {
ref := _seq.FromRefNum(int32(refnum))
v := ref.Get().(issue12403.Parsable)
_param_jstr := decodeString(param_jstr)
res_0 := v.FromJSON(_param_jstr)
_res_0 := encodeString(res_0)
return _res_0
}
//export proxyissue12403_Parsable_ToJSON
func proxyissue12403_Parsable_ToJSON(refnum C.int32_t) (C.nstring, C.int32_t) {
ref := _seq.FromRefNum(int32(refnum))
v := ref.Get().(issue12403.Parsable)
res_0, res_1 := v.ToJSON()
_res_0 := encodeString(res_0)
var _res_1 C.int32_t = _seq.NullRefNum
if res_1 != nil {
_res_1 = C.int32_t(_seq.ToRefNum(res_1))
}
return _res_0, _res_1
}
type proxyissue12403_Parsable _seq.Ref
func (p *proxyissue12403_Parsable) Bind_proxy_refnum__() int32 {
return (*_seq.Ref)(p).Bind_IncNum()
}
func (p *proxyissue12403_Parsable) FromJSON(param_jstr string) string {
_param_jstr := encodeString(param_jstr)
res := C.cproxyissue12403_Parsable_FromJSON(C.int32_t(p.Bind_proxy_refnum__()), _param_jstr)
_res := decodeString(res)
return _res
}
func (p *proxyissue12403_Parsable) ToJSON() (string, error) {
res := C.cproxyissue12403_Parsable_ToJSON(C.int32_t(p.Bind_proxy_refnum__()))
res_0 := decodeString(res.r0)
var res_1 error
res_1_ref := _seq.FromRefNum(int32(res.r1))
if res_1_ref != nil {
if res.r1 < 0 { // go object
res_1 = res_1_ref.Get().(error)
} else { // foreign object
res_1 = (*proxy_error)(res_1_ref)
}
}
return res_0, res_1
}
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/bind/testdata/customprefixEX.objc.go.h.golden
|
// Objective-C API for talking to customprefix Go package.
// gobind -lang=objc -prefix="EX" customprefix
//
// File is generated by gobind. Do not edit.
#ifndef __GO_customprefix_H__
#define __GO_customprefix_H__
#include <stdint.h>
#include <objc/objc.h>
#endif
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/bind/testdata/objcw.go
|
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package objc
import (
"ObjC/Foundation"
"ObjC/Foundation/NSMutableString"
"ObjC/NetworkExtension/NEPacket"
"ObjC/UIKit"
)
type GoNSDate struct {
Foundation.NSDate
this Foundation.NSDate
}
func (d *GoNSDate) Hash(this Foundation.NSDate) int {
return 0
}
type GoNSObject struct {
C Foundation.NSObjectC // The class
P Foundation.NSObjectP // The protocol
}
func (o *GoNSObject) Description(this Foundation.NSObjectC) string {
return ""
}
func DupNSDate(date Foundation.NSDate) Foundation.NSDate {
return date
}
type GoUIResponder struct {
UIKit.UIResponder
}
func (r *GoUIResponder) PressesBegan(_ Foundation.NSSet, _ UIKit.UIPressesEvent) {
}
const NSUTF8StringEncoding = 8
func CreateReadNSMutableString() {
myData := []byte{'A', 'B'}
// Test byte slices. Use NSMutableString because NSString is
// represented as Go strings in bindings.
// Pass slice from Go to native.
mString := NSMutableString.NewWithData(myData, uint(NSUTF8StringEncoding))
// Pass slice from native to Go.
_ = mString.DataUsingEncoding(uint(NSUTF8StringEncoding))
}
// From <sys/socket.h>
const PF_INET = 2
func CallUcharFunction() {
_ = NEPacket.NewWithData(nil, uint8(PF_INET))
}
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/bind/testdata/basictypes.go.golden
|
// Code generated by gobind. DO NOT EDIT.
// Package main is an autogenerated binder stub for package basictypes.
//
// autogenerated by gobind -lang=go basictypes
package main
/*
#include <stdlib.h>
#include <stdint.h>
#include "seq.h"
#include "basictypes.h"
*/
import "C"
import (
"basictypes"
_seq "golang.org/x/mobile/bind/seq"
)
// suppress the error if seq ends up unused
var _ = _seq.FromRefNum
//export proxybasictypes__Bool
func proxybasictypes__Bool(param_p0 C.char) C.char {
_param_p0 := param_p0 != 0
res_0 := basictypes.Bool(_param_p0)
var _res_0 C.char = 0
if res_0 {
_res_0 = 1
}
return _res_0
}
//export proxybasictypes__ByteArrays
func proxybasictypes__ByteArrays(param_x C.nbyteslice) C.nbyteslice {
_param_x := toSlice(param_x, false)
res_0 := basictypes.ByteArrays(_param_x)
_res_0 := fromSlice(res_0, true)
return _res_0
}
//export proxybasictypes__Error
func proxybasictypes__Error() C.int32_t {
res_0 := basictypes.Error()
var _res_0 C.int32_t = _seq.NullRefNum
if res_0 != nil {
_res_0 = C.int32_t(_seq.ToRefNum(res_0))
}
return _res_0
}
//export proxybasictypes__ErrorPair
func proxybasictypes__ErrorPair() (C.nint, C.int32_t) {
res_0, res_1 := basictypes.ErrorPair()
_res_0 := C.nint(res_0)
var _res_1 C.int32_t = _seq.NullRefNum
if res_1 != nil {
_res_1 = C.int32_t(_seq.ToRefNum(res_1))
}
return _res_0, _res_1
}
//export proxybasictypes__Ints
func proxybasictypes__Ints(param_x C.int8_t, param_y C.int16_t, param_z C.int32_t, param_t C.int64_t, param_u C.nint) {
_param_x := int8(param_x)
_param_y := int16(param_y)
_param_z := int32(param_z)
_param_t := int64(param_t)
_param_u := int(param_u)
basictypes.Ints(_param_x, _param_y, _param_z, _param_t, _param_u)
}
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/bind/testdata/issue29559.java.h.golden
|
// Code generated by gobind. DO NOT EDIT.
// JNI function headers for the Go <=> Java bridge.
//
// autogenerated by gobind -lang=java issue29559
#ifndef __Issue29559_H__
#define __Issue29559_H__
#include <jni.h>
#endif
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/bind/testdata/keywords.objc.m.golden
|
// Objective-C API for talking to keywords Go package.
// gobind -lang=objc keywords
//
// File is generated by gobind. Do not edit.
#include <Foundation/Foundation.h>
#include "seq.h"
#include "_cgo_export.h"
#include "Keywords.objc.h"
@implementation KeywordsKeywordCaller {
}
- (nonnull instancetype)initWithRef:(id)ref {
self = [super init];
if (self) { __ref = ref; }
return self;
}
- (void)abstract {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Abstract(refnum);
}
- (void)assert {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Assert(refnum);
}
- (void)bool_ {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Bool(refnum);
}
- (void)boolean {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Boolean(refnum);
}
- (void)break {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Break(refnum);
}
- (void)byte {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Byte(refnum);
}
- (void)case {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Case(refnum);
}
- (void)catch {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Catch(refnum);
}
- (void)char_ {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Char(refnum);
}
- (void)class {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Class(refnum);
}
- (void)const_ {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Const(refnum);
}
- (void)continue {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Continue(refnum);
}
- (void)default {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Default(refnum);
}
- (void)do {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Do(refnum);
}
- (void)double_ {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Double(refnum);
}
- (void)else {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Else(refnum);
}
- (void)enum {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Enum(refnum);
}
- (void)extends {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Extends(refnum);
}
- (void)false {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_False(refnum);
}
- (void)final {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Final(refnum);
}
- (void)finally {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Finally(refnum);
}
- (void)float_ {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Float(refnum);
}
- (void)for {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_For(refnum);
}
- (void)goto {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Goto(refnum);
}
- (void)if {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_If(refnum);
}
- (void)implements {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Implements(refnum);
}
- (void)import {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Import(refnum);
}
- (void)instanceof {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Instanceof(refnum);
}
- (void)int_ {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Int(refnum);
}
- (void)interface {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Interface(refnum);
}
- (void)long_ {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Long(refnum);
}
- (void)native {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Native(refnum);
}
- (void)new {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_New(refnum);
}
- (void)nil_ {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Nil(refnum);
}
- (void)null {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Null(refnum);
}
- (void)package {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Package(refnum);
}
- (void)private {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Private(refnum);
}
- (void)protected {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Protected(refnum);
}
- (void)public {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Public(refnum);
}
- (void)return {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Return(refnum);
}
- (void)short_ {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Short(refnum);
}
- (void)static {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Static(refnum);
}
- (void)strictfp {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Strictfp(refnum);
}
- (void)super_ {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Super(refnum);
}
- (void)switch {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Switch(refnum);
}
- (void)synchronized {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Synchronized(refnum);
}
- (void)this {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_This(refnum);
}
- (void)throw {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Throw(refnum);
}
- (void)throws {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Throws(refnum);
}
- (void)transient {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Transient(refnum);
}
- (void)true {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_True(refnum);
}
- (void)try {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Try(refnum);
}
- (void)void_ {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Void(refnum);
}
- (void)volatile_ {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_Volatile(refnum);
}
- (void)while {
int32_t refnum = go_seq_go_to_refnum(self._ref);
proxykeywords_KeywordCaller_While(refnum);
}
@end
void KeywordsConst(NSString* _Nullable id_) {
nstring _id_ = go_seq_from_objc_string(id_);
proxykeywords__Const(_id_);
}
void KeywordsStatic(NSString* _Nullable strictfp) {
nstring _strictfp = go_seq_from_objc_string(strictfp);
proxykeywords__Static(_strictfp);
}
void cproxykeywords_KeywordCaller_Abstract(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o abstract];
}
}
void cproxykeywords_KeywordCaller_Assert(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o assert];
}
}
void cproxykeywords_KeywordCaller_Bool(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o bool_];
}
}
void cproxykeywords_KeywordCaller_Boolean(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o boolean];
}
}
void cproxykeywords_KeywordCaller_Break(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o break];
}
}
void cproxykeywords_KeywordCaller_Byte(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o byte];
}
}
void cproxykeywords_KeywordCaller_Case(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o case];
}
}
void cproxykeywords_KeywordCaller_Catch(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o catch];
}
}
void cproxykeywords_KeywordCaller_Char(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o char_];
}
}
void cproxykeywords_KeywordCaller_Class(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o class];
}
}
void cproxykeywords_KeywordCaller_Const(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o const_];
}
}
void cproxykeywords_KeywordCaller_Continue(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o continue];
}
}
void cproxykeywords_KeywordCaller_Default(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o default];
}
}
void cproxykeywords_KeywordCaller_Do(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o do];
}
}
void cproxykeywords_KeywordCaller_Double(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o double_];
}
}
void cproxykeywords_KeywordCaller_Else(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o else];
}
}
void cproxykeywords_KeywordCaller_Enum(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o enum];
}
}
void cproxykeywords_KeywordCaller_Extends(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o extends];
}
}
void cproxykeywords_KeywordCaller_False(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o false];
}
}
void cproxykeywords_KeywordCaller_Final(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o final];
}
}
void cproxykeywords_KeywordCaller_Finally(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o finally];
}
}
void cproxykeywords_KeywordCaller_Float(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o float_];
}
}
void cproxykeywords_KeywordCaller_For(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o for];
}
}
void cproxykeywords_KeywordCaller_Goto(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o goto];
}
}
void cproxykeywords_KeywordCaller_If(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o if];
}
}
void cproxykeywords_KeywordCaller_Implements(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o implements];
}
}
void cproxykeywords_KeywordCaller_Import(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o import];
}
}
void cproxykeywords_KeywordCaller_Instanceof(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o instanceof];
}
}
void cproxykeywords_KeywordCaller_Int(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o int_];
}
}
void cproxykeywords_KeywordCaller_Interface(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o interface];
}
}
void cproxykeywords_KeywordCaller_Long(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o long_];
}
}
void cproxykeywords_KeywordCaller_Native(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o native];
}
}
void cproxykeywords_KeywordCaller_New(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o new];
}
}
void cproxykeywords_KeywordCaller_Nil(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o nil_];
}
}
void cproxykeywords_KeywordCaller_Null(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o null];
}
}
void cproxykeywords_KeywordCaller_Package(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o package];
}
}
void cproxykeywords_KeywordCaller_Private(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o private];
}
}
void cproxykeywords_KeywordCaller_Protected(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o protected];
}
}
void cproxykeywords_KeywordCaller_Public(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o public];
}
}
void cproxykeywords_KeywordCaller_Return(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o return];
}
}
void cproxykeywords_KeywordCaller_Short(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o short_];
}
}
void cproxykeywords_KeywordCaller_Static(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o static];
}
}
void cproxykeywords_KeywordCaller_Strictfp(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o strictfp];
}
}
void cproxykeywords_KeywordCaller_Super(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o super_];
}
}
void cproxykeywords_KeywordCaller_Switch(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o switch];
}
}
void cproxykeywords_KeywordCaller_Synchronized(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o synchronized];
}
}
void cproxykeywords_KeywordCaller_This(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o this];
}
}
void cproxykeywords_KeywordCaller_Throw(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o throw];
}
}
void cproxykeywords_KeywordCaller_Throws(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o throws];
}
}
void cproxykeywords_KeywordCaller_Transient(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o transient];
}
}
void cproxykeywords_KeywordCaller_True(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o true];
}
}
void cproxykeywords_KeywordCaller_Try(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o try];
}
}
void cproxykeywords_KeywordCaller_Void(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o void_];
}
}
void cproxykeywords_KeywordCaller_Volatile(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o volatile_];
}
}
void cproxykeywords_KeywordCaller_While(int32_t refnum) {
@autoreleasepool {
KeywordsKeywordCaller* o = go_seq_objc_from_refnum(refnum);
[o while];
}
}
__attribute__((constructor)) static void init() {
init_seq();
}
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/bind/testdata/basictypes.go
|
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package basictypes
const (
AString = "a string"
AnInt = 7
AnInt2 = 1<<63 - 1
AFloat = 0.2015
ARune = rune(32)
ABool = true
ALongString = "LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString,LongString"
)
func Ints(x int8, y int16, z int32, t int64, u int) {}
func Error() error { return nil }
func ErrorPair() (int, error) { return 0, nil }
func ByteArrays(x []byte) []byte { return nil }
func Bool(bool) bool { return true }
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/bind/testdata/customprefixEX.objc.h.golden
|
// Objective-C API for talking to customprefix Go package.
// gobind -lang=objc -prefix="EX" customprefix
//
// File is generated by gobind. Do not edit.
#ifndef __EXCustomprefix_H__
#define __EXCustomprefix_H__
@import Foundation;
#include "ref.h"
#include "Universe.objc.h"
FOUNDATION_EXPORT void EXCustomprefixF(void);
#endif
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/bind/testdata/customprefix.go
|
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Data for -pkgpath and -prefix options.
package customprefix
func F() {
}
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/bind/testdata/java.java.golden
|
// Code generated by gobind. DO NOT EDIT.
// Java class java.F is a proxy for talking to a Go program.
//
// autogenerated by gobind -lang=java java
package java;
import go.Seq;
public interface F extends R {
public String toString();
}
// Code generated by gobind. DO NOT EDIT.
// Java class java.L is a proxy for talking to a Go program.
//
// autogenerated by gobind -lang=java java
package java;
import go.Seq;
public interface L extends R {
public String toString();
}
// Code generated by gobind. DO NOT EDIT.
// Java class java.O is a proxy for talking to a Go program.
//
// autogenerated by gobind -lang=java java
package java;
import go.Seq;
public interface O extends R {
public String toString();
}
// Code generated by gobind. DO NOT EDIT.
// Java class java.R is a proxy for talking to a Go program.
//
// autogenerated by gobind -lang=java java
package java;
import go.Seq;
public interface R {
}
// Code generated by gobind. DO NOT EDIT.
// Java class java.Java is a proxy for talking to a Go program.
//
// autogenerated by gobind -lang=java java
package java;
import go.Seq;
public abstract class Java {
static {
Seq.touch(); // for loading the native library
_init();
}
private Java() {} // uninstantiable
// touch is called from other bound packages to initialize this package
public static void touch() {}
private static native void _init();
private static final class proxyF implements Seq.Proxy, F {
private final int refnum;
@Override public final int incRefnum() {
Seq.incGoRef(refnum, this);
return refnum;
}
proxyF(int refnum) { this.refnum = refnum; Seq.trackGoRef(refnum, this); }
public native String toString();
}
private static final class proxyL implements Seq.Proxy, L {
private final int refnum;
@Override public final int incRefnum() {
Seq.incGoRef(refnum, this);
return refnum;
}
proxyL(int refnum) { this.refnum = refnum; Seq.trackGoRef(refnum, this); }
public native String toString();
}
private static final class proxyO implements Seq.Proxy, O {
private final int refnum;
@Override public final int incRefnum() {
Seq.incGoRef(refnum, this);
return refnum;
}
proxyO(int refnum) { this.refnum = refnum; Seq.trackGoRef(refnum, this); }
public native String toString();
}
private static final class proxyR implements Seq.Proxy, R {
private final int refnum;
@Override public final int incRefnum() {
Seq.incGoRef(refnum, this);
return refnum;
}
proxyR(int refnum) { this.refnum = refnum; Seq.trackGoRef(refnum, this); }
}
}
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/bind/testdata/underscores.java.h.golden
|
// Code generated by gobind. DO NOT EDIT.
// JNI function headers for the Go <=> Java bridge.
//
// autogenerated by gobind -lang=java underscores
#ifndef __Underscore_pkg_H__
#define __Underscore_pkg_H__
#include <jni.h>
extern jclass proxy_class_underscore_pkg_Underscore_struct;
extern jmethodID proxy_class_underscore_pkg_Underscore_struct_cons;
#endif
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/bind/testdata/basictypes.java.h.golden
|
// Code generated by gobind. DO NOT EDIT.
// JNI function headers for the Go <=> Java bridge.
//
// autogenerated by gobind -lang=java basictypes
#ifndef __Basictypes_H__
#define __Basictypes_H__
#include <jni.h>
#endif
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/mobile/bind/testdata/ignore.java.h.golden
|
// Code generated by gobind. DO NOT EDIT.
// JNI function headers for the Go <=> Java bridge.
//
// autogenerated by gobind -lang=java ignore
#ifndef __Ignore_H__
#define __Ignore_H__
#include <jni.h>
extern jclass proxy_class_ignore_I;
extern jmethodID proxy_class_ignore_I_cons;
// skipped method I.Argument with unsupported parameter or return types
// skipped method I.Result with unsupported parameter or return types
extern jclass proxy_class_ignore_S;
extern jmethodID proxy_class_ignore_S_cons;
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.