Merge remote-tracking branch 'origin/main' into rebranch

This commit is contained in:
swift-ci
2024-09-21 11:14:00 -07:00
20 changed files with 10 additions and 1934 deletions

View File

@@ -356,8 +356,6 @@ provide greater clarity to contributors wanting to add new documentation.
- [Testing.md](/docs/Testing.md):
TODO: Consider splitting into a how-to guide on writing a new test case
and an explanation for how the compiler is tested.
- [SwiftIndent.md](/docs/SwiftIndent.md):
TODO: Unclear if this is intended to be an explanation or a reference guide.
- [Random.md](/docs/Random.md): Stub.
### Archive

View File

@@ -1,56 +0,0 @@
# Swift-indent
## Introduction
Note: This tool is still a work in progress.
swift-indent is a tool for automatically indenting your Swift files according to a
set of rules. It is implemented as another driver kind, like swiftc, the batch
compiler, so swift-indent is actually a symbolic link to swift. This tool uses
libIDE to indent code, so it can be leveraged from multiple systems and editors.
## Usage
To print all the available options:
swift-indent -help
By default, swift-indent will output the indented file to the standard output:
swift-indent sample.swift
You can either output the result to a separate file:
swift-indent sample.swift -o result.swift
Or you can indent in-place (the original file will be overwritten):
swift-indent -in-place sample.swift
If you want to indent using tabs instead of spaces, use the `-use-tabs` option:
swift-indent -use-tabs sample.swift
You can set the number of tabs or spaces using the `-tab-width` and
`-indent-width` options, respectively.
If you want to indent cases in switch statements, use the "-indent-switch-case"
option. The result would be something like this:
switch aSwitch {
case .some(let s):
print(s)
swift-indent supports indenting a range of lines from a file:
swift-indent -line-range 2:45 sample.swift
This will indent the file from lines 2 to 45, inclusive.
You can indent several files, but the `-line-range` option is not supported in
that case.
You can also provide several line ranges by using multiple `-line-range` options:
swift-indent -line-range 2:45 -line-range 100:120 sample.swift

View File

@@ -180,7 +180,6 @@ public:
SwiftDependencyTool, // swift-dependency-tool
SwiftLLVMOpt, // swift-llvm-opt
AutolinkExtract, // swift-autolink-extract
SwiftIndent, // swift-indent
SymbolGraph, // swift-symbolgraph
APIDigester, // swift-api-digester
CacheTool, // swift-cache-tool

View File

@@ -29,7 +29,7 @@ namespace options {
DoesNotAffectIncrementalBuild = (1 << 8),
AutolinkExtractOption = (1 << 9),
ModuleWrapOption = (1 << 10),
SwiftIndentOption = (1 << 11),
// 1 << 11 was previously `SwiftIndentOption`
ArgumentIsPath = (1 << 12),
ModuleInterfaceOption = (1 << 13),
SupplementaryOutput = (1 << 14),

View File

@@ -29,9 +29,6 @@ def AutolinkExtractOption : OptionFlag;
// The option should be accepted by swift -modulewrap
def ModuleWrapOption : OptionFlag;
// The option should be accepted by swift-indent
def SwiftIndentOption : OptionFlag;
// The option should not be accepted by the driver.
def NoDriverOption : OptionFlag;
@@ -218,7 +215,6 @@ def driver_mode : Joined<["--"], "driver-mode=">, Flags<[HelpHidden]>,
def help : Flag<["-", "--"], "help">,
Flags<[FrontendOption, AutolinkExtractOption, ModuleWrapOption,
SwiftIndentOption,
SwiftSymbolGraphExtractOption, SwiftAPIDigesterOption]>,
HelpText<"Display available options">;
def h : Flag<["-"], "h">, Alias<help>;
@@ -268,8 +264,8 @@ def _DASH_DASH : Option<["--"], "", KIND_REMAINING_ARGS>,
def o : JoinedOrSeparate<["-"], "o">,
Flags<[FrontendOption, AutolinkExtractOption, ModuleWrapOption,
NoInteractiveOption, SwiftIndentOption, ArgumentIsPath,
SwiftAPIDigesterOption, CacheInvariant]>,
NoInteractiveOption, ArgumentIsPath, SwiftAPIDigesterOption,
CacheInvariant]>,
HelpText<"Write output to <file>">, MetaVarName<"<file>">;
def j : JoinedOrSeparate<["-"], "j">, Flags<[DoesNotAffectIncrementalBuild]>,
@@ -1146,28 +1142,28 @@ def AssertConfig : Separate<["-"], "assert-config">,
def code_formatting_Group : OptionGroup<"<code formatting options>">;
def use_tabs : Flag<["-"], "use-tabs">, Group<code_formatting_Group>,
Flags<[NoInteractiveOption, NoBatchOption, SwiftIndentOption]>,
Flags<[NoInteractiveOption, NoBatchOption]>,
HelpText<"Use tabs for indentation.">;
def indent_switch_case : Flag<["-"], "indent-switch-case">,
Group<code_formatting_Group>,
Flags<[NoInteractiveOption, NoBatchOption, SwiftIndentOption]>,
Flags<[NoInteractiveOption, NoBatchOption]>,
HelpText<"Indent cases in switch statements.">;
def in_place : Flag<["-"], "in-place">, Group<code_formatting_Group>,
Flags<[NoInteractiveOption, NoBatchOption, SwiftIndentOption]>,
Flags<[NoInteractiveOption, NoBatchOption]>,
HelpText<"Overwrite input file with formatted file.">;
def tab_width : Separate<["-"], "tab-width">, Group<code_formatting_Group>,
Flags<[NoInteractiveOption, NoBatchOption, SwiftIndentOption]>,
Flags<[NoInteractiveOption, NoBatchOption]>,
HelpText<"Width of tab character.">, MetaVarName<"<n>">;
def indent_width : Separate<["-"], "indent-width">, Group<code_formatting_Group>,
Flags<[NoInteractiveOption, NoBatchOption, SwiftIndentOption]>,
Flags<[NoInteractiveOption, NoBatchOption]>,
HelpText<"Number of characters to indent.">, MetaVarName<"<n>">;
def line_range : Separate<["-"], "line-range">, Group<code_formatting_Group>,
Flags<[NoInteractiveOption, NoBatchOption, SwiftIndentOption]>,
Flags<[NoInteractiveOption, NoBatchOption]>,
HelpText<"<start line>:<end line>. Formats a range of lines (1-based). "
"Can only be used with one input file.">, MetaVarName<"<n:n>">;

View File

@@ -108,7 +108,6 @@ void Driver::parseDriverKind(ArrayRef<const char *> Args) {
.Case("swift-dependency-tool", DriverKind::SwiftDependencyTool)
.Case("swift-llvm-opt", DriverKind::SwiftLLVMOpt)
.Case("swift-autolink-extract", DriverKind::AutolinkExtract)
.Case("swift-indent", DriverKind::SwiftIndent)
.Case("swift-symbolgraph-extract", DriverKind::SymbolGraph)
.Case("swift-api-digester", DriverKind::APIDigester)
.Case("swift-cache-tool", DriverKind::CacheTool)
@@ -3108,7 +3107,6 @@ void Driver::printHelp(bool ShowHidden) const {
case DriverKind::SwiftDependencyTool:
case DriverKind::SwiftLLVMOpt:
case DriverKind::AutolinkExtract:
case DriverKind::SwiftIndent:
case DriverKind::SymbolGraph:
case DriverKind::APIDigester:
case DriverKind::CacheTool:

View File

@@ -94,10 +94,6 @@ extern int autolink_extract_main(ArrayRef<const char *> Args, const char *Argv0,
extern int modulewrap_main(ArrayRef<const char *> Args, const char *Argv0,
void *MainAddr);
/// Run 'swift-indent'
extern int swift_indent_main(ArrayRef<const char *> Args, const char *Argv0,
void *MainAddr);
/// Run 'swift-symbolgraph-extract'
extern int swift_symbolgraph_extract_main(ArrayRef<const char *> Args, const char *Argv0,
void *MainAddr);
@@ -389,10 +385,6 @@ static int run_driver(StringRef ExecName,
return autolink_extract_main(
TheDriver.getArgsWithoutProgramNameAndDriverMode(argv),
argv[0], (void *)(intptr_t)getExecutablePath);
case Driver::DriverKind::SwiftIndent:
return swift_indent_main(
TheDriver.getArgsWithoutProgramNameAndDriverMode(argv),
argv[0], (void *)(intptr_t)getExecutablePath);
case Driver::DriverKind::SymbolGraph:
return swift_symbolgraph_extract_main(TheDriver.getArgsWithoutProgramNameAndDriverMode(argv), argv[0], (void *)(intptr_t)getExecutablePath);
case Driver::DriverKind::APIDigester:

View File

@@ -76,193 +76,3 @@ public:
return *SM.getLLVMSourceMgr().getMemoryBuffer(BufferID);
}
};
class SwiftIndentInvocation {
private:
std::string MainExecutablePath;
std::string OutputFilename = "-";
std::vector<std::string> InputFilenames;
CodeFormatOptions FormatOptions;
bool InPlace = false;
std::vector<std::string> LineRanges;
bool parseLineRange(StringRef Input, unsigned &FromLine, unsigned &ToLine) {
std::pair<StringRef, StringRef> LineRange = Input.split(":");
return LineRange.first.getAsInteger(0, FromLine) ||
LineRange.second.getAsInteger(0, ToLine);
}
public:
SwiftIndentInvocation(const std::string &ExecPath)
: MainExecutablePath(ExecPath) {}
const std::string &getOutputFilename() { return OutputFilename; }
const std::vector<std::string> &getInputFilenames() { return InputFilenames; }
const std::vector<std::string> &getLineRanges() { return LineRanges; }
int parseArgs(ArrayRef<const char *> Args, DiagnosticEngine &Diags) {
using namespace options;
std::unique_ptr<llvm::opt::OptTable> Table = createSwiftOptTable();
unsigned MissingIndex;
unsigned MissingCount;
llvm::opt::InputArgList ParsedArgs =
Table->ParseArgs(Args, MissingIndex, MissingCount, SwiftIndentOption);
if (MissingCount) {
Diags.diagnose(SourceLoc(), diag::error_missing_arg_value,
ParsedArgs.getArgString(MissingIndex), MissingCount);
return 1;
}
if (ParsedArgs.getLastArg(OPT_use_tabs))
FormatOptions.UseTabs = true;
if (ParsedArgs.getLastArg(OPT_indent_switch_case))
FormatOptions.IndentSwitchCase = true;
if (ParsedArgs.getLastArg(OPT_in_place))
InPlace = true;
if (const Arg *A = ParsedArgs.getLastArg(OPT_tab_width))
if (StringRef(A->getValue()).getAsInteger(10, FormatOptions.TabWidth))
Diags.diagnose(SourceLoc(), diag::error_invalid_arg_value,
A->getAsString(ParsedArgs), A->getValue());
if (const Arg *A = ParsedArgs.getLastArg(OPT_indent_width))
if (StringRef(A->getValue()).getAsInteger(10, FormatOptions.IndentWidth))
Diags.diagnose(SourceLoc(), diag::error_invalid_arg_value,
A->getAsString(ParsedArgs), A->getValue());
for (const Arg *A : ParsedArgs.filtered(OPT_line_range))
LineRanges.push_back(A->getValue());
if (ParsedArgs.hasArg(OPT_UNKNOWN)) {
for (const Arg *A : ParsedArgs.filtered(OPT_UNKNOWN)) {
Diags.diagnose(SourceLoc(), diag::error_unknown_arg,
A->getAsString(ParsedArgs));
}
return true;
}
if (ParsedArgs.getLastArg(OPT_help)) {
std::string ExecutableName =
llvm::sys::path::stem(MainExecutablePath).str();
Table->printHelp(llvm::outs(), ExecutableName.c_str(),
"Swift Format Tool", options::SwiftIndentOption, 0,
/*ShowAllAliases*/false);
return 1;
}
for (const Arg *A : ParsedArgs.filtered(OPT_INPUT)) {
InputFilenames.push_back(A->getValue());
}
if (const Arg *A = ParsedArgs.getLastArg(OPT_o)) {
OutputFilename = A->getValue();
}
return 0;
}
/// Formats a filename and returns false if successful, true otherwise.
bool format(StringRef Filename, DiagnosticEngine &Diags) {
auto ErrOrBuf = llvm::MemoryBuffer::getFileOrSTDIN(Filename);
if (!ErrOrBuf) {
Diags.diagnose(SourceLoc(), diag::error_no_such_file_or_directory,
Filename);
return true;
}
std::unique_ptr<llvm::MemoryBuffer> Code = std::move(ErrOrBuf.get());
if (Code->getBufferSize() == 0) {
// Assume empty files are formatted successfully.
return false;
}
FormatterDocument Doc(std::move(Code));
if (LineRanges.empty()) {
LineRanges.push_back("1:" + std::to_string(UINT_MAX));
}
std::string Output = Doc.memBuffer().getBuffer().str();
for (unsigned Range = 0; Range < LineRanges.size(); ++Range) {
unsigned FromLine;
unsigned ToLine;
if (parseLineRange(LineRanges[Range], FromLine, ToLine)) {
Diags.diagnose(SourceLoc(), diag::error_formatting_invalid_range);
return true;
}
if (FromLine > ToLine) {
Diags.diagnose(SourceLoc(), diag::error_formatting_invalid_range);
return true;
}
for (unsigned Line = FromLine; Line <= ToLine; ++Line) {
size_t Offset = getOffsetOfLine(Line, Output);
ssize_t Length = getOffsetOfLine(Line + 1, Output) - 1 - Offset;
if (Length < 0)
break;
std::string Formatted =
Doc.reformat(LineRange(Line, 1), FormatOptions).second;
if (Formatted.find_first_not_of(" \t\v\f", 0) == StringRef::npos)
Formatted = "";
Output.replace(Offset, Length, Formatted);
Doc.updateCode(llvm::MemoryBuffer::getMemBufferCopy(Output));
}
if (Filename == "-" || (!InPlace && OutputFilename == "-")) {
llvm::outs() << Output;
return false;
}
std::error_code EC;
StringRef Destination;
if (InPlace)
Destination = Filename;
else
Destination = OutputFilename;
llvm::raw_fd_ostream out(Destination, EC, llvm::sys::fs::OF_None);
if (out.has_error() || EC) {
Diags.diagnose(SourceLoc(), diag::error_opening_output, Filename,
EC.message());
out.clear_error();
return true;
}
out << Output;
}
return false;
}
};
int swift_indent_main(ArrayRef<const char *> Args, const char *Argv0,
void *MainAddr) {
CompilerInstance Instance;
PrintingDiagnosticConsumer PDC;
Instance.addDiagnosticConsumer(&PDC);
SwiftIndentInvocation Invocation(
llvm::sys::fs::getMainExecutable(Argv0, MainAddr));
DiagnosticEngine &Diags = Instance.getDiags();
if (Invocation.parseArgs(Args, Diags) != 0)
return EXIT_FAILURE;
std::vector<std::string> InputFiles = Invocation.getInputFilenames();
unsigned NumInputFiles = InputFiles.size();
if (NumInputFiles == 0) {
// Read source code from standard input.
Invocation.format("-", Diags);
} else if (NumInputFiles == 1) {
Invocation.format(InputFiles[0], Diags);
} else {
if (!Invocation.getLineRanges().empty()) {
// We don't support formatting file ranges for multiple files.
Instance.getDiags().diagnose(SourceLoc(),
diag::error_formatting_multiple_file_ranges);
return EXIT_FAILURE;
}
for (unsigned i = 0; i < NumInputFiles; ++i)
Invocation.format(InputFiles[i], Diags);
}
return EXIT_SUCCESS;
}

View File

@@ -1078,7 +1078,6 @@ static void printSingleFrontendOpt(llvm::opt::OptTable &table, options::ID id,
if (table.getOption(id).hasFlag(options::FrontendOption) ||
table.getOption(id).hasFlag(options::AutolinkExtractOption) ||
table.getOption(id).hasFlag(options::ModuleWrapOption) ||
table.getOption(id).hasFlag(options::SwiftIndentOption) ||
table.getOption(id).hasFlag(options::SwiftSymbolGraphExtractOption) ||
table.getOption(id).hasFlag(options::SwiftAPIDigesterOption)) {
auto name = StringRef(table.getOptionName(id));

View File

@@ -323,7 +323,6 @@ config.swift_ide_test = inferSwiftBinary('swift-ide-test')
config.swift_dependency_tool = inferSwiftBinary('swift-dependency-tool')
config.swift_reflection_dump = inferSwiftBinary('swift-reflection-dump')
config.swift_remoteast_test = inferSwiftBinary('swift-remoteast-test')
config.swift_indent = inferSwiftBinary('swift-indent')
config.swift_symbolgraph_extract = inferSwiftBinary('swift-symbolgraph-extract')
config.clang = inferSwiftBinary('clang')
config.clangxx = inferSwiftBinary('clang++')
@@ -680,7 +679,6 @@ config.substitutions.append( ('%swift-dump-pcm', "%r -dump-pcm" % config.swiftc)
config.substitutions.append( ('%swift-ide-test_plain', config.swift_ide_test) )
config.substitutions.append( ('%swift-ide-test', "%r %s %s -swift-version %s %s" % (config.swift_ide_test, mcp_opt, ccp_opt, swift_version, config.resource_dir_opt)) )
config.substitutions.append( ('%swift-dependency-tool', config.swift_dependency_tool) )
config.substitutions.append( ('%swift-indent', config.swift_indent) )
config.substitutions.append( ('%llvm-link', config.llvm_link) )
config.substitutions.append( ('%swift-llvm-opt', config.swift_llvm_opt) )
config.substitutions.append( ('%llvm-dwarfdump', config.llvm_dwarfdump) )

File diff suppressed because it is too large Load Diff

View File

@@ -1,44 +0,0 @@
// RUN: %swift-indent %s >%t.response
// RUN: diff -u %s.response %t.response
// RUN: %swift-indent -indent-width 2 %s >%t.response
// RUN: diff -u %s.indent2.response %t.response
// RUN: %swift-indent -use-tabs %s >%t.response
// RUN: diff -u %s.tabs.response %t.response
// RUN: %swift-indent -line-range 24:29 %s >%t.response
// RUN: diff -u %s.lines.response %t.response
// RUN: %swift-indent -indent-switch-case %s >%t.response
// RUN: diff -u %s.indentswitch.response %t.response
import Foundation
func collatz(n: Int, m: String?) {
switch m {
case .some(let s):
print(s)
case .none:
print("nothing")
default:
print("not possible")
break
}
var r: Int
if n%2 == 0 {
r = n/2
} else {
r = 3*n+1
}
print("Number: \(r)")
if r == 1 {
print("Reached one!")
} else {
collatz(r)
}
}
#if true
func foo() -> Int {
0
}
#else
1
#endif

View File

@@ -1,44 +0,0 @@
// RUN: %swift-indent %s >%t.response
// RUN: diff -u %s.response %t.response
// RUN: %swift-indent -indent-width 2 %s >%t.response
// RUN: diff -u %s.indent2.response %t.response
// RUN: %swift-indent -use-tabs %s >%t.response
// RUN: diff -u %s.tabs.response %t.response
// RUN: %swift-indent -line-range 24:29 %s >%t.response
// RUN: diff -u %s.lines.response %t.response
// RUN: %swift-indent -indent-switch-case %s >%t.response
// RUN: diff -u %s.indentswitch.response %t.response
import Foundation
func collatz(n: Int, m: String?) {
switch m {
case .some(let s):
print(s)
case .none:
print("nothing")
default:
print("not possible")
break
}
var r: Int
if n%2 == 0 {
r = n/2
} else {
r = 3*n+1
}
print("Number: \(r)")
if r == 1 {
print("Reached one!")
} else {
collatz(r)
}
}
#if true
func foo() -> Int {
0
}
#else
1
#endif

View File

@@ -1,44 +0,0 @@
// RUN: %swift-indent %s >%t.response
// RUN: diff -u %s.response %t.response
// RUN: %swift-indent -indent-width 2 %s >%t.response
// RUN: diff -u %s.indent2.response %t.response
// RUN: %swift-indent -use-tabs %s >%t.response
// RUN: diff -u %s.tabs.response %t.response
// RUN: %swift-indent -line-range 24:29 %s >%t.response
// RUN: diff -u %s.lines.response %t.response
// RUN: %swift-indent -indent-switch-case %s >%t.response
// RUN: diff -u %s.indentswitch.response %t.response
import Foundation
func collatz(n: Int, m: String?) {
switch m {
case .some(let s):
print(s)
case .none:
print("nothing")
default:
print("not possible")
break
}
var r: Int
if n%2 == 0 {
r = n/2
} else {
r = 3*n+1
}
print("Number: \(r)")
if r == 1 {
print("Reached one!")
} else {
collatz(r)
}
}
#if true
func foo() -> Int {
0
}
#else
1
#endif

View File

@@ -1,44 +0,0 @@
// RUN: %swift-indent %s >%t.response
// RUN: diff -u %s.response %t.response
// RUN: %swift-indent -indent-width 2 %s >%t.response
// RUN: diff -u %s.indent2.response %t.response
// RUN: %swift-indent -use-tabs %s >%t.response
// RUN: diff -u %s.tabs.response %t.response
// RUN: %swift-indent -line-range 24:29 %s >%t.response
// RUN: diff -u %s.lines.response %t.response
// RUN: %swift-indent -indent-switch-case %s >%t.response
// RUN: diff -u %s.indentswitch.response %t.response
import Foundation
func collatz(n: Int, m: String?) {
switch m {
case .some(let s):
print(s)
case .none:
print("nothing")
default:
print("not possible")
break
}
var r: Int
if n%2 == 0 {
r = n/2
} else {
r = 3*n+1
}
print("Number: \(r)")
if r == 1 {
print("Reached one!")
} else {
collatz(r)
}
}
#if true
func foo() -> Int {
0
}
#else
1
#endif

View File

@@ -1,44 +0,0 @@
// RUN: %swift-indent %s >%t.response
// RUN: diff -u %s.response %t.response
// RUN: %swift-indent -indent-width 2 %s >%t.response
// RUN: diff -u %s.indent2.response %t.response
// RUN: %swift-indent -use-tabs %s >%t.response
// RUN: diff -u %s.tabs.response %t.response
// RUN: %swift-indent -line-range 24:29 %s >%t.response
// RUN: diff -u %s.lines.response %t.response
// RUN: %swift-indent -indent-switch-case %s >%t.response
// RUN: diff -u %s.indentswitch.response %t.response
import Foundation
func collatz(n: Int, m: String?) {
switch m {
case .some(let s):
print(s)
case .none:
print("nothing")
default:
print("not possible")
break
}
var r: Int
if n%2 == 0 {
r = n/2
} else {
r = 3*n+1
}
print("Number: \(r)")
if r == 1 {
print("Reached one!")
} else {
collatz(r)
}
}
#if true
func foo() -> Int {
0
}
#else
1
#endif

View File

@@ -1,44 +0,0 @@
// RUN: %swift-indent %s >%t.response
// RUN: diff -u %s.response %t.response
// RUN: %swift-indent -indent-width 2 %s >%t.response
// RUN: diff -u %s.indent2.response %t.response
// RUN: %swift-indent -use-tabs %s >%t.response
// RUN: diff -u %s.tabs.response %t.response
// RUN: %swift-indent -line-range 24:29 %s >%t.response
// RUN: diff -u %s.lines.response %t.response
// RUN: %swift-indent -indent-switch-case %s >%t.response
// RUN: diff -u %s.indentswitch.response %t.response
import Foundation
func collatz(n: Int, m: String?) {
switch m {
case .some(let s):
print(s)
case .none:
print("nothing")
default:
print("not possible")
break
}
var r: Int
if n%2 == 0 {
r = n/2
} else {
r = 3*n+1
}
print("Number: \(r)")
if r == 1 {
print("Reached one!")
} else {
collatz(r)
}
}
#if true
func foo() -> Int {
0
}
#else
1
#endif

View File

@@ -1,227 +0,0 @@
// RUN: %swift-indent %s >%t.response
// RUN: diff -u %s %t.response
foo(c: 12, d: 34) {
print("foo")
}
foo(c: 12, d: 34)
{
print("foo")
}
someCall(c: 12, d: 34) {
print("foo")
} e: {
print("foo")
} f: {
print("bar")
}
someCall(c: 12, d: 34) {
print("foo")
}
e: {
print("foo")
}
f: {
print("bar")
}
someCall(c: 12, d: 34)
{
print("foo")
}
e:
{
print("foo")
}
f:
{
print("bar")
}
someCall(c: 12, d: 34) { print("foo") }
e: { print("foo") }
f: {
print("bar")
}
someCall(c: 12,
d: 34) { print("foo") }
e: { print("bar") }
.other { print("foo") }
a: { print("foo") }
.next() {
print("bar")
}
base
.someCall(c: 12,
d: 34) { print("foo") }
e: { print("bar") }
.other { print("foo") }
a: { print("foo") }
.next() {
print("bar")
}
someCall(
c: 12,
d: 34
) { print("foo") }
e: { print("bar") }
base
.someCall(
x: 10,
y: 10
) { $0 }
next: { $0 }
base
.foo(
x: 10,
y: 10) { } next: {
}
other: {}
base
.someCall(x: 120,
y: 3030) { print("foo") } next:
{
print("foo")
}
other: {}
someCall {
print("foo")
} e: {
print("foo")
} f: {
print("bar")
}
someCall {
print("foo")
}
e: {
print("foo")
}
f: {
print("bar")
}
someCall
{
print("foo")
}
e:
{
print("foo")
}
f:
{
print("bar")
}
someCall { print("foo") }
e: { print("foo") }
f: {
print("bar")
}
doSomethingWith(someCall { print("foo") }
e: { print("foo") }
f: {
print("bar")
})
doSomethingWith(someCall {
print("foo")
}
e: { print("foo") }
f: {
print("bar")
})
func containIncomplete1() {
someCall {
print("foo")
}
e
}
func containIncomplete2() {
someCall {
print("foo")
}
e:
}
func containIncomplete3() {
someCall
{
print("foo")
}
e
}
func containIncomplete4() {
someCall
{
print("foo")
}
e:
}
func containIncomplete5() {
someCall { print("foo") }
e
}
func containIncomplete6() {
someCall { print("foo") }
e:
}
someCall(c: 12, d: 34) {{
print("foo")
}()} b: {{
print("bar")
}()}
someCall(c: 12, d: 34) { print("foo") }
/*comment*/e: { print("bar") }
/*comment*/f: {
print("hi")
}
someCall[c: 12,
d: 34] { print("foo") }
b: {
print("bar")
}
someSub[c: 12,
d: 34] {
print("foo")
} b: {
print("bar")
}
someSub[c: 12,
d: 34] {
print("foo")
} b: {
print("bar")
}
someCall(c: 12, d: 34) { print("foo") }
// comment
b: {
print("bar")
}

View File

@@ -148,11 +148,6 @@ swift_create_post_build_symlink(swift-frontend
DESTINATION "swift-llvm-opt${CMAKE_EXECUTABLE_SUFFIX}"
WORKING_DIRECTORY "${SWIFT_RUNTIME_OUTPUT_INTDIR}")
swift_create_post_build_symlink(swift-frontend
SOURCE "swift-frontend${CMAKE_EXECUTABLE_SUFFIX}"
DESTINATION "swift-indent${CMAKE_EXECUTABLE_SUFFIX}"
WORKING_DIRECTORY "${SWIFT_RUNTIME_OUTPUT_INTDIR}")
swift_create_post_build_symlink(swift-frontend
SOURCE "swift-frontend${CMAKE_EXECUTABLE_SUFFIX}"
DESTINATION "swift-symbolgraph-extract${CMAKE_EXECUTABLE_SUFFIX}"
@@ -198,10 +193,7 @@ add_dependencies(autolink-driver swift-frontend)
swift_install_in_component(FILES "${SWIFT_RUNTIME_OUTPUT_INTDIR}/swift-autolink-extract${CMAKE_EXECUTABLE_SUFFIX}"
DESTINATION "bin"
COMPONENT autolink-driver)
add_dependencies(editor-integration swift-frontend)
swift_install_in_component(FILES "${SWIFT_RUNTIME_OUTPUT_INTDIR}/swift-indent${CMAKE_EXECUTABLE_SUFFIX}"
DESTINATION "bin"
COMPONENT editor-integration)
if(EXISTS "${SWIFT_RUNTIME_OUTPUT_INTDIR}/swift-driver${CMAKE_EXECUTABLE_SUFFIX}" AND EXISTS "${SWIFT_RUNTIME_OUTPUT_INTDIR}/swift-help${CMAKE_EXECUTABLE_SUFFIX}")
swift_install_in_component(PROGRAMS "${SWIFT_RUNTIME_OUTPUT_INTDIR}/swift-driver${CMAKE_EXECUTABLE_SUFFIX}"
DESTINATION "bin"

View File

@@ -1,94 +0,0 @@
# This file is a minimal swift-indent vim-integration. To install:
# - Change 'binary' if swift-indent is not on the path (see below).
# - Add to your .vimrc:
#
# map <C-I> :pyf <path-to-this-file>/swift-indent.py<cr>
# imap <C-I> <c-o>:pyf <path-to-this-file>/swift-indent.py<cr>
#
# The first line enables swift-indent for NORMAL and VISUAL mode, the second
# line adds support for INSERT mode. Change "C-I" to another binding if you
# need swift-indent on a different key (C-I stands for Ctrl+i).
#
# With this integration you can press the bound key and swift-indent will
# indent the current line in NORMAL and INSERT mode or the selected region in
# VISUAL mode. The line or region is extended to the next bigger syntactic
# entity.
#
# You can also pass in the variable "l:lines" to choose the range for
# indenting. This variable can either contain "<start line>:<end line> or
# "all" to indent the full file. So, to indent the full file, write a function
# like:
#
# :function IndentFile()
# : let l:lines="all"
# : pyf <path-to-this-file>/swift-indent.py
# :endfunction
#
# It operates on the current, potentially unsaved buffer and does not create or
# save any files. To revert a indenting, just undo.
import difflib
import platform
import subprocess
import sys
import vim
binary = 'swift-indent'
if vim.eval('exists("g:swift_indent_path")') == "1":
binary = vim.eval('g:swift_indent_path')
def get_buffer(encoding):
if platform.python_version_tuple()[0] == "3":
return vim.current.buffer
return [line.decode(encoding) for line in vim.current.buffer]
def main(argc, argv):
encoding = vim.eval("&encoding")
buf = get_buffer(encoding)
if vim.eval('exists("l:lines")') == '1':
lines = vim.eval('l:lines')
else:
lines = '%s:%s' % (vim.current.range.start + 1,
vim.current.range.end + 1)
cursor = int(vim.eval('line2byte(line(".")) + col(".")')) - 2
if cursor < 0:
print("Couldn't determine cursor position. Is your file empty?")
return
# avoid the cmd prompt on windows
SI = None
if sys.platform.startswith('win32'):
SI = subprocess.STARTUPINFO()
SI.dwFlags |= subprocess.STARTF_USESHOWWINDOW
SI.wShowWindow = subprocess.SW_HIDE
command = [binary]
if lines != 'all':
command.extend(['-line-range', lines])
p = subprocess.Popen(command,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
stdin=subprocess.PIPE, startupinfo=SI)
stdout, stderr = p.communicate(input='\n'.join(buf).encode(encoding))
if stderr:
print(stderr)
if not stdout:
print('No output from swift-indent (crashed?).')
return
lines = stdout.decode(encoding).split('\n')
sequence = difflib.SequenceMatcher(None, buf, lines)
for op in reversed(sequence.get_opcodes()):
if op[0] != 'equal':
vim.current.buffer[op[1]:op[2]] = lines[op[3]:op[4]]
if __name__ == '__main__':
main(len(sys.argv), sys.argv)