gob-lang 1.0.0-aarch64-linux
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/README.md +17 -0
- data/exe/gob +8 -0
- data/exe/stree-go +12 -0
- data/ext/gipper/gipper.go +172 -0
- data/ext/gipper/libgipper.h +95 -0
- data/ext/gipper/libgipper.so +0 -0
- data/ext/goformatter/format/LICENSE +27 -0
- data/ext/goformatter/format/format.go +132 -0
- data/ext/goformatter/format/internal.go +174 -0
- data/ext/goformatter/go.mod +3 -0
- data/ext/goformatter/libgoformatter.h +95 -0
- data/ext/goformatter/libgoformatter.so +0 -0
- data/ext/goformatter/main.go +34 -0
- data/gob-lang.gemspec +57 -0
- data/lib/gipper.rb +24 -0
- data/lib/go_formatter.rb +33 -0
- data/lib/gob/cli/base.rb +53 -0
- data/lib/gob/cli/commands/build.rb +29 -0
- data/lib/gob/cli/commands/fmt.rb +31 -0
- data/lib/gob/cli/commands/run.rb +21 -0
- data/lib/gob/cli/commands/transpile.rb +20 -0
- data/lib/gob/cli/commands/version.rb +19 -0
- data/lib/gob/cli/commands/vet.rb +33 -0
- data/lib/gob/cli/errors.rb +50 -0
- data/lib/gob/cli.rb +53 -0
- data/lib/gob/go/dsl.rb +196 -0
- data/lib/gob/go/printer.rb +412 -0
- data/lib/gob/go/runner.rb +42 -0
- data/lib/gob/matcher.rb +34 -0
- data/lib/gob/transpilation/rules/core.rb +1184 -0
- data/lib/gob/transpiler.rb +815 -0
- data/lib/gob/validation/offence.rb +24 -0
- data/lib/gob/validation/rules/class_rules.rb +78 -0
- data/lib/gob/validation/rules/config.yml +16 -0
- data/lib/gob/validation/rules/cop.rb +15 -0
- data/lib/gob/validation/rules/function_rules.rb +33 -0
- data/lib/gob/validation/rules/module_rules.rb +78 -0
- data/lib/gob/validation/rules/program_rules.rb +72 -0
- data/lib/gob/validation/rules.rb +93 -0
- data/lib/gob/version.rb +5 -0
- data/lib/gob.rb +41 -0
- data/lib/syntax_tree/go/format.rb +176 -0
- data/lib/syntax_tree/go/json_visitor.rb +34 -0
- data/lib/syntax_tree/go/match_visitor.rb +103 -0
- data/lib/syntax_tree/go/materializer.rb +92 -0
- data/lib/syntax_tree/go/node.rb +50 -0
- data/lib/syntax_tree/go/nodes.rb +2147 -0
- data/lib/syntax_tree/go/pretty_print_visitor.rb +76 -0
- data/lib/syntax_tree/go/schema.json +1455 -0
- data/lib/syntax_tree/go/visitor.rb +71 -0
- data/lib/syntax_tree/go.rb +55 -0
- data/lib/thor/help_header.rb +23 -0
- metadata +292 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: 8fc36804881d330bb86146e98af5531e4c5d1f6153bbb63077a664412b8f11de
|
|
4
|
+
data.tar.gz: 5e505ad2c26838959cfeacddea184071ac9bb96d42fc8bdd25e3f0721ef38190
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: 1c28a30dd272f206fd356557159d647ad348f1a6d769eb794639e32a65acee27c6d8562b1edc90365bf0c5356db21f1dfe693a3c290c8de4fe24e79006b9858f
|
|
7
|
+
data.tar.gz: db7015a2a0c93b6e5f1129cd61f6910420d019b0dd8ce77748a7a7d3af38d7fea5c432f9ffb2196f7adae77da6bc823b1939be02a1f26e47f014fba462cd6547
|
data/README.md
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
<img src="./res/gobby-the-vole.jpg" alt="Gobby the vole" style="width: 100%;">
|
|
2
|
+
|
|
3
|
+
## Etymology: *gobber*
|
|
4
|
+
|
|
5
|
+
**gobber** /ˈɡɒb.ə/ *noun* — regional slang (Northern England, Yorkshire & the North Midlands; also Irish English)
|
|
6
|
+
|
|
7
|
+
1. a mouthy one; a talker, a loudmouth — from *gob*, "mouth"
|
|
8
|
+
2. a familiar form of address between mates: *ey up, gobbah!*
|
|
9
|
+
|
|
10
|
+
> "Ey up gobbah! What's cookin'?"
|
|
11
|
+
> "Nowt, mate — just clanging pans."
|
|
12
|
+
|
|
13
|
+
*(Translation for southerners: "Hello, mouthy. What's happening?" / "Nothing, mate — just making a racket.")*
|
|
14
|
+
|
|
15
|
+
*gobber* is *gob* + *-er*, literally "one who gobs". *Gob* has meant "mouth" in Scottish, northern English and Irish English since the 16th century, probably from Irish and Scottish Gaelic *gob*, "beak, bill" — a bird's mouth. *Gobber* is someone who is all mouth, and by the usual alchemy of northern banter the insult wears down into a term of endearment, the way *bugger* and *daft ha'porth* do. *Ey up* and *nowt* ("nothing") belong to the same dialect layer.
|
|
16
|
+
|
|
17
|
+
For this project the pun is deliberate: a **gobber** is one who *gobs* — takes Ruby and emits Go. The mascot, [Gobby the vole](./res/gobby-the-vole.jpg), is named from the same root: *gobby*, "mouthy, opinionated".
|
data/exe/gob
ADDED
data/exe/stree-go
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
set -euo pipefail
|
|
3
|
+
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
|
4
|
+
export RUBYLIB="$ROOT/lib${RUBYLIB:+:$RUBYLIB}"
|
|
5
|
+
|
|
6
|
+
if [ $# -eq 0 ]; then
|
|
7
|
+
exec bundle exec stree --plugins=go
|
|
8
|
+
fi
|
|
9
|
+
|
|
10
|
+
cmd="$1"
|
|
11
|
+
shift
|
|
12
|
+
exec bundle exec stree "$cmd" --plugins=go "$@"
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
package main
|
|
2
|
+
|
|
3
|
+
/*
|
|
4
|
+
#include <stdlib.h>
|
|
5
|
+
*/
|
|
6
|
+
import "C"
|
|
7
|
+
|
|
8
|
+
import (
|
|
9
|
+
"encoding/json"
|
|
10
|
+
"go/ast"
|
|
11
|
+
"go/parser"
|
|
12
|
+
"go/token"
|
|
13
|
+
"reflect"
|
|
14
|
+
"unsafe"
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
func pos(fset *token.FileSet, p token.Pos) any {
|
|
18
|
+
if !p.IsValid() {
|
|
19
|
+
return nil
|
|
20
|
+
}
|
|
21
|
+
pp := fset.Position(p)
|
|
22
|
+
return map[string]any{
|
|
23
|
+
"offset": pp.Offset,
|
|
24
|
+
"line": pp.Line,
|
|
25
|
+
"column": pp.Column,
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
func convertValue(fset *token.FileSet, v reflect.Value) any {
|
|
30
|
+
if !v.IsValid() {
|
|
31
|
+
return nil
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
t := v.Type()
|
|
35
|
+
posType := reflect.TypeOf(token.NoPos)
|
|
36
|
+
tokType := reflect.TypeOf(token.ILLEGAL)
|
|
37
|
+
nodeType := reflect.TypeOf((*ast.Node)(nil)).Elem()
|
|
38
|
+
|
|
39
|
+
switch {
|
|
40
|
+
case t == posType:
|
|
41
|
+
return pos(fset, v.Interface().(token.Pos))
|
|
42
|
+
case t == tokType:
|
|
43
|
+
tok := v.Interface().(token.Token)
|
|
44
|
+
return tok.String()
|
|
45
|
+
case t.Kind() == reflect.Bool:
|
|
46
|
+
return v.Bool()
|
|
47
|
+
case t.Kind() == reflect.String:
|
|
48
|
+
return v.String()
|
|
49
|
+
case t.Kind() == reflect.Int, t.Kind() == reflect.Int8, t.Kind() == reflect.Int16, t.Kind() == reflect.Int32, t.Kind() == reflect.Int64:
|
|
50
|
+
return v.Int()
|
|
51
|
+
case t.Kind() == reflect.Uint, t.Kind() == reflect.Uint8, t.Kind() == reflect.Uint16, t.Kind() == reflect.Uint32, t.Kind() == reflect.Uint64, t.Kind() == reflect.Uintptr:
|
|
52
|
+
return v.Uint()
|
|
53
|
+
case t.Kind() == reflect.Slice:
|
|
54
|
+
if v.IsNil() {
|
|
55
|
+
return []any{}
|
|
56
|
+
}
|
|
57
|
+
out := make([]any, v.Len())
|
|
58
|
+
for i := 0; i < v.Len(); i++ {
|
|
59
|
+
out[i] = convertValue(fset, v.Index(i))
|
|
60
|
+
}
|
|
61
|
+
return out
|
|
62
|
+
case t.Kind() == reflect.Map:
|
|
63
|
+
if v.IsNil() {
|
|
64
|
+
return map[string]any{}
|
|
65
|
+
}
|
|
66
|
+
out := map[string]any{}
|
|
67
|
+
iter := v.MapRange()
|
|
68
|
+
for iter.Next() {
|
|
69
|
+
k := fmtSprint(iter.Key())
|
|
70
|
+
out[k] = convertValue(fset, iter.Value())
|
|
71
|
+
}
|
|
72
|
+
return out
|
|
73
|
+
case t.Kind() == reflect.Interface:
|
|
74
|
+
if v.IsNil() {
|
|
75
|
+
return nil
|
|
76
|
+
}
|
|
77
|
+
return convertValue(fset, v.Elem())
|
|
78
|
+
case t.Kind() == reflect.Pointer:
|
|
79
|
+
if v.IsNil() {
|
|
80
|
+
return nil
|
|
81
|
+
}
|
|
82
|
+
if t.Implements(nodeType) {
|
|
83
|
+
return convertNode(fset, v.Interface().(ast.Node))
|
|
84
|
+
}
|
|
85
|
+
// *ast.Scope, *ast.Object etc - skip semantic/internal pointers
|
|
86
|
+
return nil
|
|
87
|
+
default:
|
|
88
|
+
return nil
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
func fmtSprint(v reflect.Value) string {
|
|
93
|
+
if !v.IsValid() {
|
|
94
|
+
return "<invalid>"
|
|
95
|
+
}
|
|
96
|
+
switch v.Kind() {
|
|
97
|
+
case reflect.String:
|
|
98
|
+
return v.String()
|
|
99
|
+
default:
|
|
100
|
+
b, err := json.Marshal(convertPlain(v))
|
|
101
|
+
if err == nil {
|
|
102
|
+
return string(b)
|
|
103
|
+
}
|
|
104
|
+
return "<key>"
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
func convertPlain(v reflect.Value) any {
|
|
109
|
+
if !v.IsValid() {
|
|
110
|
+
return nil
|
|
111
|
+
}
|
|
112
|
+
switch v.Kind() {
|
|
113
|
+
case reflect.String:
|
|
114
|
+
return v.String()
|
|
115
|
+
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
|
116
|
+
return v.Int()
|
|
117
|
+
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
|
|
118
|
+
return v.Uint()
|
|
119
|
+
case reflect.Bool:
|
|
120
|
+
return v.Bool()
|
|
121
|
+
default:
|
|
122
|
+
return v.String()
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
func convertNode(fset *token.FileSet, n ast.Node) any {
|
|
127
|
+
if n == nil {
|
|
128
|
+
return nil
|
|
129
|
+
}
|
|
130
|
+
rv := reflect.ValueOf(n)
|
|
131
|
+
if rv.Kind() == reflect.Pointer {
|
|
132
|
+
rv = rv.Elem()
|
|
133
|
+
}
|
|
134
|
+
rt := rv.Type()
|
|
135
|
+
fields := map[string]any{}
|
|
136
|
+
for i := 0; i < rt.NumField(); i++ {
|
|
137
|
+
f := rt.Field(i)
|
|
138
|
+
if !f.IsExported() {
|
|
139
|
+
continue
|
|
140
|
+
}
|
|
141
|
+
fields[f.Name] = convertValue(fset, rv.Field(i))
|
|
142
|
+
}
|
|
143
|
+
return map[string]any{
|
|
144
|
+
"type": rt.Name(),
|
|
145
|
+
"fields": fields,
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
//export ParseFileJSON
|
|
150
|
+
func ParseFileJSON(filename *C.char, src *C.char) *C.char {
|
|
151
|
+
fset := token.NewFileSet()
|
|
152
|
+
file, err := parser.ParseFile(fset, C.GoString(filename), C.GoString(src), parser.ParseComments|parser.SkipObjectResolution)
|
|
153
|
+
if err != nil && file == nil {
|
|
154
|
+
b, _ := json.Marshal(map[string]any{"error": err.Error()})
|
|
155
|
+
return C.CString(string(b))
|
|
156
|
+
}
|
|
157
|
+
out := map[string]any{"file": convertNode(fset, file)}
|
|
158
|
+
if err != nil {
|
|
159
|
+
out["error"] = err.Error()
|
|
160
|
+
}
|
|
161
|
+
b, _ := json.Marshal(out)
|
|
162
|
+
return C.CString(string(b))
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
//export FreeString
|
|
166
|
+
func FreeString(str *C.char) {
|
|
167
|
+
if str != nil {
|
|
168
|
+
C.free(unsafe.Pointer(str))
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
func main() {}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/* Code generated by cmd/cgo; DO NOT EDIT. */
|
|
2
|
+
|
|
3
|
+
/* package command-line-arguments */
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
#line 1 "cgo-builtin-export-prolog"
|
|
7
|
+
|
|
8
|
+
#include <stddef.h>
|
|
9
|
+
|
|
10
|
+
#ifndef GO_CGO_EXPORT_PROLOGUE_H
|
|
11
|
+
#define GO_CGO_EXPORT_PROLOGUE_H
|
|
12
|
+
|
|
13
|
+
#ifndef GO_CGO_GOSTRING_TYPEDEF
|
|
14
|
+
typedef struct { const char *p; ptrdiff_t n; } _GoString_;
|
|
15
|
+
extern size_t _GoStringLen(_GoString_ s);
|
|
16
|
+
extern const char *_GoStringPtr(_GoString_ s);
|
|
17
|
+
#endif
|
|
18
|
+
|
|
19
|
+
#endif
|
|
20
|
+
|
|
21
|
+
/* Start of preamble from import "C" comments. */
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
#line 3 "gipper.go"
|
|
25
|
+
|
|
26
|
+
#include <stdlib.h>
|
|
27
|
+
|
|
28
|
+
#line 1 "cgo-generated-wrapper"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
/* End of preamble from import "C" comments. */
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
/* Start of boilerplate cgo prologue. */
|
|
35
|
+
#line 1 "cgo-gcc-export-header-prolog"
|
|
36
|
+
|
|
37
|
+
#ifndef GO_CGO_PROLOGUE_H
|
|
38
|
+
#define GO_CGO_PROLOGUE_H
|
|
39
|
+
|
|
40
|
+
typedef signed char GoInt8;
|
|
41
|
+
typedef unsigned char GoUint8;
|
|
42
|
+
typedef short GoInt16;
|
|
43
|
+
typedef unsigned short GoUint16;
|
|
44
|
+
typedef int GoInt32;
|
|
45
|
+
typedef unsigned int GoUint32;
|
|
46
|
+
typedef long long GoInt64;
|
|
47
|
+
typedef unsigned long long GoUint64;
|
|
48
|
+
typedef GoInt64 GoInt;
|
|
49
|
+
typedef GoUint64 GoUint;
|
|
50
|
+
typedef size_t GoUintptr;
|
|
51
|
+
typedef float GoFloat32;
|
|
52
|
+
typedef double GoFloat64;
|
|
53
|
+
#ifdef _MSC_VER
|
|
54
|
+
#if !defined(__cplusplus) || _MSVC_LANG <= 201402L
|
|
55
|
+
#include <complex.h>
|
|
56
|
+
typedef _Fcomplex GoComplex64;
|
|
57
|
+
typedef _Dcomplex GoComplex128;
|
|
58
|
+
#else
|
|
59
|
+
#include <complex>
|
|
60
|
+
typedef std::complex<float> GoComplex64;
|
|
61
|
+
typedef std::complex<double> GoComplex128;
|
|
62
|
+
#endif
|
|
63
|
+
#else
|
|
64
|
+
typedef float _Complex GoComplex64;
|
|
65
|
+
typedef double _Complex GoComplex128;
|
|
66
|
+
#endif
|
|
67
|
+
|
|
68
|
+
/*
|
|
69
|
+
static assertion to make sure the file is being used on architecture
|
|
70
|
+
at least with matching size of GoInt.
|
|
71
|
+
*/
|
|
72
|
+
typedef char _check_for_64_bit_pointer_matching_GoInt[sizeof(void*)==64/8 ? 1:-1];
|
|
73
|
+
|
|
74
|
+
#ifndef GO_CGO_GOSTRING_TYPEDEF
|
|
75
|
+
typedef _GoString_ GoString;
|
|
76
|
+
#endif
|
|
77
|
+
typedef void *GoMap;
|
|
78
|
+
typedef void *GoChan;
|
|
79
|
+
typedef struct { void *t; void *v; } GoInterface;
|
|
80
|
+
typedef struct { void *data; GoInt len; GoInt cap; } GoSlice;
|
|
81
|
+
|
|
82
|
+
#endif
|
|
83
|
+
|
|
84
|
+
/* End of boilerplate cgo prologue. */
|
|
85
|
+
|
|
86
|
+
#ifdef __cplusplus
|
|
87
|
+
extern "C" {
|
|
88
|
+
#endif
|
|
89
|
+
|
|
90
|
+
extern char* ParseFileJSON(char* filename, char* src);
|
|
91
|
+
extern void FreeString(char* str);
|
|
92
|
+
|
|
93
|
+
#ifdef __cplusplus
|
|
94
|
+
}
|
|
95
|
+
#endif
|
|
Binary file
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
Copyright 2009 The Go Authors.
|
|
2
|
+
|
|
3
|
+
Redistribution and use in source and binary forms, with or without
|
|
4
|
+
modification, are permitted provided that the following conditions are
|
|
5
|
+
met:
|
|
6
|
+
|
|
7
|
+
* Redistributions of source code must retain the above copyright
|
|
8
|
+
notice, this list of conditions and the following disclaimer.
|
|
9
|
+
* Redistributions in binary form must reproduce the above
|
|
10
|
+
copyright notice, this list of conditions and the following disclaimer
|
|
11
|
+
in the documentation and/or other materials provided with the
|
|
12
|
+
distribution.
|
|
13
|
+
* Neither the name of Google LLC nor the names of its
|
|
14
|
+
contributors may be used to endorse or promote products derived from
|
|
15
|
+
this software without specific prior written permission.
|
|
16
|
+
|
|
17
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
|
18
|
+
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
|
19
|
+
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
|
20
|
+
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
|
21
|
+
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
|
22
|
+
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
|
23
|
+
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
|
24
|
+
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
|
25
|
+
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
26
|
+
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
27
|
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
// Copyright 2012 The Go Authors. All rights reserved.
|
|
2
|
+
// Use of this source code is governed by a BSD-style
|
|
3
|
+
// license that can be found in the LICENSE file.
|
|
4
|
+
|
|
5
|
+
// Package format implements standard formatting of Go source.
|
|
6
|
+
//
|
|
7
|
+
// Note that formatting of Go source code changes over time, so tools relying on
|
|
8
|
+
// consistent formatting should execute a specific version of the gofmt binary
|
|
9
|
+
// instead of using this package. That way, the formatting will be stable, and
|
|
10
|
+
// the tools won't need to be recompiled each time gofmt changes.
|
|
11
|
+
//
|
|
12
|
+
// For example, pre-submit checks that use this package directly would behave
|
|
13
|
+
// differently depending on what Go version each developer uses, causing the
|
|
14
|
+
// check to be inherently fragile.
|
|
15
|
+
package format
|
|
16
|
+
|
|
17
|
+
import (
|
|
18
|
+
"bytes"
|
|
19
|
+
"fmt"
|
|
20
|
+
"go/ast"
|
|
21
|
+
"go/parser"
|
|
22
|
+
"go/printer"
|
|
23
|
+
"go/token"
|
|
24
|
+
"io"
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
// Keep these in sync with cmd/gofmt/gofmt.go.
|
|
28
|
+
const (
|
|
29
|
+
tabWidth = 8
|
|
30
|
+
printerMode = printer.UseSpaces | printer.TabIndent | printerNormalizeNumbers
|
|
31
|
+
|
|
32
|
+
// printerNormalizeNumbers means to canonicalize number literal prefixes
|
|
33
|
+
// and exponents while printing. See https://golang.org/doc/go1.13#gofmt.
|
|
34
|
+
//
|
|
35
|
+
// This value is defined in go/printer specifically for go/format and cmd/gofmt.
|
|
36
|
+
printerNormalizeNumbers = 1 << 30
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
var config = printer.Config{Mode: printerMode, Tabwidth: tabWidth}
|
|
40
|
+
|
|
41
|
+
const parserMode = parser.ParseComments | parser.SkipObjectResolution
|
|
42
|
+
|
|
43
|
+
// Node formats node in canonical gofmt style and writes the result to dst.
|
|
44
|
+
//
|
|
45
|
+
// The node type must be *[ast.File], *[printer.CommentedNode], [][ast.Decl],
|
|
46
|
+
// [][ast.Stmt], or assignment-compatible to [ast.Expr], [ast.Decl], [ast.Spec],
|
|
47
|
+
// or [ast.Stmt]. Node does not modify node. Imports are not sorted for
|
|
48
|
+
// nodes representing partial source files (for instance, if the node
|
|
49
|
+
// is not an *[ast.File] or a *[printer.CommentedNode] not wrapping an *[ast.File]).
|
|
50
|
+
//
|
|
51
|
+
// The function may return early (before the entire result is written)
|
|
52
|
+
// and return a formatting error, for instance due to an incorrect AST.
|
|
53
|
+
func Node(dst io.Writer, fset *token.FileSet, node any) error {
|
|
54
|
+
// Determine if we have a complete source file (file != nil).
|
|
55
|
+
var file *ast.File
|
|
56
|
+
var cnode *printer.CommentedNode
|
|
57
|
+
switch n := node.(type) {
|
|
58
|
+
case *ast.File:
|
|
59
|
+
file = n
|
|
60
|
+
case *printer.CommentedNode:
|
|
61
|
+
if f, ok := n.Node.(*ast.File); ok {
|
|
62
|
+
file = f
|
|
63
|
+
cnode = n
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Sort imports if necessary.
|
|
68
|
+
if file != nil && hasUnsortedImports(file) {
|
|
69
|
+
// Make a copy of the AST because ast.SortImports is destructive.
|
|
70
|
+
// TODO(gri): Consider doing this more efficiently.
|
|
71
|
+
var buf bytes.Buffer
|
|
72
|
+
err := config.Fprint(&buf, fset, file)
|
|
73
|
+
if err != nil {
|
|
74
|
+
return err
|
|
75
|
+
}
|
|
76
|
+
file, err = parser.ParseFile(fset, "", buf.Bytes(), parserMode)
|
|
77
|
+
if err != nil {
|
|
78
|
+
// We should never get here. If we do, provide good diagnostic.
|
|
79
|
+
return fmt.Errorf("format.Node internal error (%s)", err)
|
|
80
|
+
}
|
|
81
|
+
ast.SortImports(fset, file)
|
|
82
|
+
|
|
83
|
+
// Use new file with sorted imports.
|
|
84
|
+
node = file
|
|
85
|
+
if cnode != nil {
|
|
86
|
+
node = &printer.CommentedNode{Node: file, Comments: cnode.Comments}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
return config.Fprint(dst, fset, node)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Source formats src in canonical gofmt style and returns the result
|
|
94
|
+
// or an (I/O or syntax) error. src is expected to be a syntactically
|
|
95
|
+
// correct Go source file, or a list of Go declarations or statements.
|
|
96
|
+
//
|
|
97
|
+
// If src is a partial source file, the leading and trailing space of src
|
|
98
|
+
// is applied to the result (such that it has the same leading and trailing
|
|
99
|
+
// space as src), and the result is indented by the same amount as the first
|
|
100
|
+
// line of src containing code. Imports are not sorted for partial source files.
|
|
101
|
+
func Source(src []byte) ([]byte, error) {
|
|
102
|
+
fset := token.NewFileSet()
|
|
103
|
+
file, sourceAdj, indentAdj, err := parse(fset, "", src, true)
|
|
104
|
+
if err != nil {
|
|
105
|
+
return nil, err
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
if sourceAdj == nil {
|
|
109
|
+
// Complete source file.
|
|
110
|
+
// TODO(gri): consider doing this always.
|
|
111
|
+
ast.SortImports(fset, file)
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
return format(fset, file, sourceAdj, indentAdj, src, config)
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
func hasUnsortedImports(file *ast.File) bool {
|
|
118
|
+
for _, d := range file.Decls {
|
|
119
|
+
d, ok := d.(*ast.GenDecl)
|
|
120
|
+
if !ok || d.Tok != token.IMPORT {
|
|
121
|
+
// Imports are always first.
|
|
122
|
+
return false
|
|
123
|
+
}
|
|
124
|
+
if d.Lparen.IsValid() {
|
|
125
|
+
// For now assume grouped imports are unsorted.
|
|
126
|
+
// TODO(gri): Should check if imports are sorted already.
|
|
127
|
+
return true
|
|
128
|
+
}
|
|
129
|
+
// Ungrouped imports are sorted by default.
|
|
130
|
+
}
|
|
131
|
+
return false
|
|
132
|
+
}
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
// Copyright 2015 The Go Authors. All rights reserved.
|
|
2
|
+
// Use of this source code is governed by a BSD-style
|
|
3
|
+
// license that can be found in the LICENSE file.
|
|
4
|
+
|
|
5
|
+
// TODO(gri): This file and the file src/cmd/gofmt/internal.go are
|
|
6
|
+
// the same (but for this comment and the package name). Do not modify
|
|
7
|
+
// one without the other. Determine if we can factor out functionality
|
|
8
|
+
// in a public API. See also #11844 for context.
|
|
9
|
+
|
|
10
|
+
package format
|
|
11
|
+
|
|
12
|
+
import (
|
|
13
|
+
"bytes"
|
|
14
|
+
"go/ast"
|
|
15
|
+
"go/parser"
|
|
16
|
+
"go/printer"
|
|
17
|
+
"go/token"
|
|
18
|
+
"strings"
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
// parse parses src, which was read from the named file,
|
|
22
|
+
// as a Go source file, declaration, or statement list.
|
|
23
|
+
func parse(fset *token.FileSet, filename string, src []byte, fragmentOk bool) (
|
|
24
|
+
file *ast.File,
|
|
25
|
+
sourceAdj func(src []byte, indent int) []byte,
|
|
26
|
+
indentAdj int,
|
|
27
|
+
err error,
|
|
28
|
+
) {
|
|
29
|
+
// Try as whole source file.
|
|
30
|
+
file, err = parser.ParseFile(fset, filename, src, parserMode)
|
|
31
|
+
// If there's no error, return. If the error is that the source file didn't begin with a
|
|
32
|
+
// package line and source fragments are ok, fall through to
|
|
33
|
+
// try as a source fragment. Stop and return on any other error.
|
|
34
|
+
if err == nil || !fragmentOk || !strings.Contains(err.Error(), "expected 'package'") {
|
|
35
|
+
return
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// If it's a declaration list, make it a source file
|
|
39
|
+
// by inserting a package clause.
|
|
40
|
+
// Insert using a ';', not a newline, so that the line numbers in psrc match the ones in src.
|
|
41
|
+
psrc := append([]byte("package p;"), src...)
|
|
42
|
+
file, err = parser.ParseFile(fset, filename, psrc, parserMode)
|
|
43
|
+
if err == nil {
|
|
44
|
+
sourceAdj = func(src []byte, indent int) []byte {
|
|
45
|
+
// Remove the package clause.
|
|
46
|
+
// Gofmt has turned the ';' into a '\n'.
|
|
47
|
+
src = src[indent+len("package p\n"):]
|
|
48
|
+
return bytes.TrimSpace(src)
|
|
49
|
+
}
|
|
50
|
+
return
|
|
51
|
+
}
|
|
52
|
+
// If the error is that the source file didn't begin with a
|
|
53
|
+
// declaration, fall through to try as a statement list.
|
|
54
|
+
// Stop and return on any other error.
|
|
55
|
+
if !strings.Contains(err.Error(), "expected declaration") {
|
|
56
|
+
return
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// If it's a statement list, make it a source file by
|
|
60
|
+
// inserting a package clause and turning the list into
|
|
61
|
+
// a function body. This handles expressions too.
|
|
62
|
+
// Insert using a ';', not a newline, so that the line numbers in fsrc match the ones in src.
|
|
63
|
+
// Add an extra '\n' before the '}' to make sure comments are flushed before the '}'.
|
|
64
|
+
fsrc := append(append([]byte("package p; func _() {"), src...), '\n', '\n', '}')
|
|
65
|
+
file, err = parser.ParseFile(fset, filename, fsrc, parserMode)
|
|
66
|
+
if err == nil {
|
|
67
|
+
sourceAdj = func(src []byte, indent int) []byte {
|
|
68
|
+
// Cap adjusted indent to zero.
|
|
69
|
+
if indent < 0 {
|
|
70
|
+
indent = 0
|
|
71
|
+
}
|
|
72
|
+
// Remove the wrapping.
|
|
73
|
+
// Gofmt has turned the "; " into a "\n\n".
|
|
74
|
+
// There will be two non-blank lines with indent, hence 2*indent.
|
|
75
|
+
src = src[2*indent+len("package p\n\nfunc _() {"):]
|
|
76
|
+
// Remove only the "}\n" suffix: remaining whitespaces will be trimmed anyway
|
|
77
|
+
src = src[:len(src)-len("}\n")]
|
|
78
|
+
return bytes.TrimSpace(src)
|
|
79
|
+
}
|
|
80
|
+
// Gofmt also indented the function body one level.
|
|
81
|
+
// Adjust that with indentAdj.
|
|
82
|
+
indentAdj = -1
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Succeeded, or out of options.
|
|
86
|
+
return
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// format formats the given package file originally obtained from src
|
|
90
|
+
// and adjusts the result based on the original source via sourceAdj
|
|
91
|
+
// and indentAdj.
|
|
92
|
+
func format(
|
|
93
|
+
fset *token.FileSet,
|
|
94
|
+
file *ast.File,
|
|
95
|
+
sourceAdj func(src []byte, indent int) []byte,
|
|
96
|
+
indentAdj int,
|
|
97
|
+
src []byte,
|
|
98
|
+
cfg printer.Config,
|
|
99
|
+
) ([]byte, error) {
|
|
100
|
+
if sourceAdj == nil {
|
|
101
|
+
// Complete source file.
|
|
102
|
+
var buf bytes.Buffer
|
|
103
|
+
err := cfg.Fprint(&buf, fset, file)
|
|
104
|
+
if err != nil {
|
|
105
|
+
return nil, err
|
|
106
|
+
}
|
|
107
|
+
return buf.Bytes(), nil
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// Partial source file.
|
|
111
|
+
// Determine and prepend leading space.
|
|
112
|
+
i, j := 0, 0
|
|
113
|
+
for j < len(src) && isSpace(src[j]) {
|
|
114
|
+
if src[j] == '\n' {
|
|
115
|
+
i = j + 1 // byte offset of last line in leading space
|
|
116
|
+
}
|
|
117
|
+
j++
|
|
118
|
+
}
|
|
119
|
+
var res []byte
|
|
120
|
+
res = append(res, src[:i]...)
|
|
121
|
+
|
|
122
|
+
// Determine and prepend indentation of first code line.
|
|
123
|
+
// Spaces are ignored unless there are no tabs,
|
|
124
|
+
// in which case spaces count as one tab.
|
|
125
|
+
indent := 0
|
|
126
|
+
hasSpace := false
|
|
127
|
+
for _, b := range src[i:j] {
|
|
128
|
+
switch b {
|
|
129
|
+
case ' ':
|
|
130
|
+
hasSpace = true
|
|
131
|
+
case '\t':
|
|
132
|
+
indent++
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
if indent == 0 && hasSpace {
|
|
136
|
+
indent = 1
|
|
137
|
+
}
|
|
138
|
+
for i = 0; i < indent; i++ {
|
|
139
|
+
res = append(res, '\t')
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// Format the source.
|
|
143
|
+
// Write it without any leading and trailing space.
|
|
144
|
+
cfg.Indent = indent + indentAdj
|
|
145
|
+
var buf bytes.Buffer
|
|
146
|
+
err := cfg.Fprint(&buf, fset, file)
|
|
147
|
+
if err != nil {
|
|
148
|
+
return nil, err
|
|
149
|
+
}
|
|
150
|
+
out := sourceAdj(buf.Bytes(), cfg.Indent)
|
|
151
|
+
|
|
152
|
+
// If the adjusted output is empty, the source
|
|
153
|
+
// was empty but (possibly) for white space.
|
|
154
|
+
// The result is the incoming source.
|
|
155
|
+
if len(out) == 0 {
|
|
156
|
+
return src, nil
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// Otherwise, append output to leading space.
|
|
160
|
+
res = append(res, out...)
|
|
161
|
+
|
|
162
|
+
// Determine and append trailing space.
|
|
163
|
+
i = len(src)
|
|
164
|
+
for i > 0 && isSpace(src[i-1]) {
|
|
165
|
+
i--
|
|
166
|
+
}
|
|
167
|
+
return append(res, src[i:]...), nil
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// isSpace reports whether the byte is a space character.
|
|
171
|
+
// isSpace defines a space as being among the following bytes: ' ', '\t', '\n' and '\r'.
|
|
172
|
+
func isSpace(b byte) bool {
|
|
173
|
+
return b == ' ' || b == '\t' || b == '\n' || b == '\r'
|
|
174
|
+
}
|