$ swift -Xfrontend -emit-ir -Xllvm -debug a.swift
-Xllvm -debug
をつけると、 LLVM_DEBUG
で吐かれてるいろんなデバッグ情報が、出てくるんですね。Guaranteed Optimization
無しでコンパイルするオプションみたいなの無いですか?protocol P { associatedtype T func f(_ g: @escaping (T) -> Void) } class C<S>: P { typealias T = S private let _f: ((S) -> Void) -> Void init<Q: P>(q: Q) where Q.T == T { // Error: cannot assign value of type '((S) -> Void) -> Void' to type '((S) -> Void) -> Void' self._f = { g -> Void in q.f(g) } } func f(_ g: @escaping (S) -> Void) { self._f(g) } }
でエラーメッセージが不親切な件の原因を探している過程で、意図のわからないコードがあったので質問させてください // Try to simplify irrelevant details of function types. For example, if // someone passes a "() -> Float" function to a "() throws -> Int" // parameter, then uttering the "throws" may confuse them into thinking that // that is the problem, even though there is a clear subtype relation. if (auto srcFT = exprType->getAs<FunctionType>()) if (auto destFT = contextualType->getAs<FunctionType>()) { auto destExtInfo = destFT->getExtInfo(); if (!srcFT->isNoEscape()) destExtInfo = destExtInfo.withNoEscape(false); // 👈
ですが、これコメントの通り関数の型の不一致に escaping とか throws とか混ぜるとややこしいので出さない的な意図であってそうでしょうか? https://github.com/apple/swift/blob/5e7da0e3dcf13c603233c1f2aad1f1aded8821df/lib/Sema/CSDiag.cpp#L3250AnyFunctionType exprType
が構成された時点でもう発生していて[omochi@omochi-iMac-PC43 warn]$ swift aaa.swift aaa.swift:16:9: error: cannot assign value of type '(@escaping (Int) -> Void) -> Void' to type '((Int) -> Void) -> Void' f = { (g) -> Void in ^~~~~~~~~~~~~~~~
@escaping
が暗黙に確定しているんだけど@escaping
が、明示された形で表示されるようになってしまう副作用が出てきた・・・[&]
なラムダ式ってことでいいんでしょか?Type Solution::simplifyType(Type type) const { if (!type->hasTypeVariable()) return type; // Map type variables to fixed types from bindings. return simplifyTypeImpl( getConstraintSystem(), type, [&](TypeVariableType *tvt) -> Type { auto known = typeBindings.find(tvt); assert(known != typeBindings.end()); return known->second; }); }
[&]
でのthisの暗黙ミュータブルキャプチャですね、fr variable
だと思うので、ちょっと違うんですよねーFunctionType
の入力が TupleType/ParenType
だったのを FunctionType
にパラメータリストを持たせるようにしていく過渡期なので、ここに手をだすのは危険だったかもしれないですね。// RefBox.value.modify sil hidden [transparent] @$S1a6RefBoxC5valuexvM : $@yield_once @convention(method) <T> (@guaranteed RefBox<T>) -> @yields @inout T { // %0 // users: %2, %1 bb0(%0 : $RefBox<T>): debug_value %0 : $RefBox<T>, let, name "self", argno 1 // id: %1 %2 = ref_element_addr %0 : $RefBox<T>, #RefBox.value // user: %3 %3 = begin_access [modify] [dynamic] %2 : $*T // users: %5, %8, %4 yield %3 : $*T, resume bb1, unwind bb2 // id: %4 bb1: // Preds: bb0 end_access %3 : $*T // id: %5 %6 = tuple () // user: %7 return %6 : $() // id: %7 bb2: // Preds: bb0 end_access %3 : $*T // id: %8 unwind // id: %9 } // end sil function '$S1a6RefBoxC5valuexvM'
modify(&x.b)
で modify
内で結局書き換わらなかったときかな?struct IntBox { var value: Int = 3 } func mod(_ value: inout Int) { value *= 2 } var box = IntBox() mod(&box.value)
protocol HasInt { var intValue : Int {get set} } func mod(_ val: inout Int) throws {} func testing<T: HasInt>(x: inout T) throws { try mod(&x.intValue) }
// testing<A>(x:) sil hidden @$S4test7testing1xyxz_tKAA6HasIntRzlF : $@convention(thin) <T where T : HasInt> (@inout T) -> @error Error { // %0 // users: %3, %1 bb0(%0 : $*T): %3 = begin_access [modify] [static] %0 : $*T // users: %11, %16, %5 %4 = witness_method $T, #HasInt.intValue!modify.1 : <Self where Self : HasInt> (inout Self) -> () -> () : $@yield_once @convention(witness_method: HasInt) <τ_0_0 where τ_0_0 : HasInt> (@inout τ_0_0) -> @yields @inout Int // user: %5 (%5, %6) = begin_apply %4<T>(%3) : $@yield_once @convention(witness_method: HasInt) <τ_0_0 where τ_0_0 : HasInt> (@inout τ_0_0) -> @yields @inout Int // users: %8, %10, %15 // function_ref mod(_:) %7 = function_ref @$S4test3modyySizKF : $@convention(thin) (@inout Int) -> @error Error // user: %8 try_apply %7(%5) : $@convention(thin) (@inout Int) -> @error Error, normal bb1, error bb2 // id: %8 bb1(%9 : $()): // Preds: bb0 end_apply %6 // id: %10 end_access %3 : $*T // id: %11 %12 = tuple () // user: %13 return %12 : $() // id: %13 // %14 // user: %17 bb2(%14 : $Error): // Preds: bb0 abort_apply %6 // id: %15 end_access %3 : $*T // id: %16 throw %14 : $Error // id: %17 } // end sil function '$S4test7testing1xyxz_tKAA6HasIntRzlF'
なので、アクセス中に throw したときみたいです。struct Stone { var _x: Int = 3 var x: Int { get { return _x } _modify { yield &_x } } } func mod(_ x: inout Int) { x = 8 } func main() { var a = Stone() mod(&a.x) }
define hidden swiftcc void @"$S1a4mainyyF"() #0 { entry: %a = alloca %T1a5StoneV, align 8 %0 = bitcast %T1a5StoneV* %a to %swift.opaque** store %swift.opaque* null, %swift.opaque** %0, align 8 %1 = alloca [32 x i8], align 8 %2 = bitcast %T1a5StoneV* %a to i8* call void @llvm.lifetime.start.p0i8(i64 8, i8* %2) %3 = call swiftcc i64 @"$S1a5StoneVACycfC"() %a._x = getelementptr inbounds %T1a5StoneV, %T1a5StoneV* %a, i32 0, i32 0 %a._x._value = getelementptr inbounds %TSi, %TSi* %a._x, i32 0, i32 0 store i64 %3, i64* %a._x._value, align 8 %4 = getelementptr inbounds [32 x i8], [32 x i8]* %1, i32 0, i32 0 call void @llvm.lifetime.start.p0i8(i64 32, i8* %4) %5 = call swiftcc { i8*, %TSi* } @"$S1a5StoneV1xSivM"(i8* noalias dereferenceable(32) %4, %T1a5StoneV* nocapture swiftself dereferenceable(8) %a) %6 = extractvalue { i8*, %TSi* } %5, 0 %7 = extractvalue { i8*, %TSi* } %5, 1 call swiftcc void @"$S1a3modyySizF"(%TSi* nocapture dereferenceable(8) %7) %8 = bitcast i8* %6 to void (i8*, i1)* call swiftcc void %8(i8* noalias dereferenceable(32) %4, i1 false) call void @llvm.lifetime.end.p0i8(i64 32, i8* %4) %9 = bitcast %T1a5StoneV* %a to i8* call void @llvm.lifetime.end.p0i8(i64 8, i8* %9) ret void }
define hidden swiftcc { i8*, %TSi* } @"$S1a5StoneV1xSivM"(i8* noalias dereferenceable(32), %T1a5StoneV* nocapture swiftself dereferenceable(8)) #1 { entry: %._x = getelementptr inbounds %T1a5StoneV, %T1a5StoneV* %1, i32 0, i32 0 %2 = insertvalue { i8*, %TSi* } { i8* bitcast (void (i8*, i1)* @"$S1a5StoneV1xSivM.resume.0" to i8*), %TSi* undef }, %TSi* %._x, 1 ret { i8*, %TSi* } %2 } define internal swiftcc void @"$S1a5StoneV1xSivM.resume.0"(i8* noalias nonnull dereferenceable(32), i1) #0 { entryresume.0: %FramePtr = bitcast i8* %0 to %"$S1a5StoneV1xSivM.Frame"* %vFrame = bitcast %"$S1a5StoneV1xSivM.Frame"* %FramePtr to i8* ret void }
_modify
でもうお試しできるとわかったstruct Stone { var x: Int { get { return 1 } _modify { var x: Int = 3 yield &x y = x } } var y: Int = 0 } func mod(_ x: inout Int) { x = 8 } func main() { var a = Stone() mod(&a.x) print(a.y) } main()
/Users/hiragram/Development/swift-source/swift/stdlib/public/SDK/Intents/INIntent.swift:25:19: error: value of type 'INIntent' has no member '__setImage'; did you mean 'setImage'? (self as! INIntent).__setImage(image, forParameterNamed: keyPathString) ~~~~~~^~~~~~~~~~~~~ ~~~~~~~~~~ setImage Intents.INIntent:10:15: note: 'setImage' declared here open func setImage(_ image: INImage?, forParameterNamed parameterName: String) ^ /Users/hiragram/Development/swift-source/swift/stdlib/public/SDK/Intents/INIntent.swift:23:17: note: 'setImage' declared here public func setImage<Value>(_ image: INImage?, forParameterNamed parameterName: KeyPath<Self, Value>) { ^ /Users/hiragram/Development/swift-source/swift/stdlib/public/SDK/Intents/INIntent.swift:32:26: error: value of type 'INIntent' has no member '__image'; did you mean 'image'? return (self as! INIntent).__image(forParameterNamed: keyPathString) ~~~~~~^~~~~~~~~~~~~ ~~~~~~~ image Intents.INIntent:12:15: note: 'image' declared here open func image(forParameterNamed parameterName: String) -> INImage? ^ /Users/hiragram/Development/swift-source/swift/stdlib/public/SDK/Intents/INIntent.swift:30:17: note: 'image' declared here public func image<Value>(forParameterNamed parameterName: KeyPath<Self, Value>) -> INImage? { ^ [973/1575] Compiling /Users/hiragram/Development/swift-source/build/Ninja-ReleaseAssert/swift-macosx-x86_64/stdlib/public/SDK/Foundation/macosx/x86_64/Foundation.o ninja: build stopped: subcommand failed. utils/build-script: fatal error: command terminated with a non-zero exit status 1, aborting
utils/build-script -Rt
これでこうなるVersion 10.0 beta (10L176w)
error: value of type 'INIntent' has no member '__image'
こういうのは並列関係なさそうな気がするけどそういうもん?$ xcode-select -p
の出力は?$ xcode-select -p /Applications/Xcode-beta.app/Contents/Developer
-Rt
だったなら、 releaseビルドだから、 XcodeでビルドするときはXcodeのconfigurationをreleaseにしないといけないよmutableAddressWithNativeOwner
から_modify
へ https://github.com/apple/swift/pull/19154@sil_name(hoge)
みたいな、「SIL上に現れる名前はこっちにする」的なやつなかったでしたっけ(前にどっかで見たような気がするけど見つけられない)@_silgen_name("hoge") func f() {}
sil_stage canonical import Builtin import Swift import SwiftShims @_silgen_name("hoge") func f() // main sil @main : $@convention(c) (Int32, UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>) -> Int32 { bb0(%0 : $Int32, %1 : $UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>): %2 = integer_literal $Builtin.Int32, 0 // user: %3 %3 = struct $Int32 (%2 : $Builtin.Int32) // user: %4 return %3 : $Int32 // id: %4 } // end sil function 'main' // hoge sil hidden @hoge : $@convention(thin) () -> () { bb0: %0 = tuple () // user: %1 return %0 : $() // id: %1 } // end sil function 'hoge'
@_silgen_name("hoge.storage")
したらおかしくならないかな〜と思ってやりたくなったけど型のプロパティに対して付けられなかったstruct A { var b: Int = 1 @_silgen_name("_T04hoge1AV1bSivg") func itazura() -> Int { return 2 } }
struct A { var b: Int = 1 @_silgen_name("_T04hoge1AV1bSivg") func itazura() -> Int { return 2 } }
struct A { var b: Int { return 1 } @_silgen_name("_T04hoge1AV1bSivg") func itazura() -> Int { return 2 } } print(A().b) print(A().itazura())
struct A { var b: Int { return 1 } @_silgen_name("_T04hoge1AV1bSivg") func itazura() -> Int { return 2 } } print(A().b) print(A().itazura())
no such file or directory: '/Users/hiragram/Development/swift-source/build/Xcode-RelWithDebInfoAssert/cmark-macosx-x86_64/src/Release/libcmark.a'
utils/build-script --xcode --release-debuginfo
がこういう死に方するの何だろう Assertion failed: (FD >= 0 && "File not yet open!"), function preferred_buffer_size, file /Users/hiragram/Development/swift-source/llvm/lib/Support/raw_ostream.cpp, line 701.
/usr/local/bin/python /Users/omochi/work/swift-source/swift/utils/line-directive \ @/Users/omochi/work/swift-source/build/Ninja-DebugAssert/swift-macosx-x86_64/stdlib/public/core/WkKut.txt -- \ /Users/omochi/work/swift-source/build/Ninja-DebugAssert/swift-macosx-x86_64/./bin/swiftc -c \ -sdk /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk \ -target x86_64-apple-macosx10.9 \ -resource-dir /Users/omochi/work/swift-source/build/Ninja-DebugAssert/swift-macosx-x86_64/./lib/swift \ -F /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/../../../Developer/Library/Frameworks \ -Onone -g -D INTERNAL_CHECKS_ENABLED -D SWIFT_ENABLE_RUNTIME_FUNCTION_COUNTERS \ -I /Users/omochi/work/swift-source/build/Ninja-DebugAssert/swift-macosx-x86_64/./lib/swift/macosx/x86_64 \ -module-cache-path /Users/omochi/work/swift-source/build/Ninja-DebugAssert/swift-macosx-x86_64/./module-cache -no-link-objc-runtime \ -Xfrontend -enable-resilience -nostdimport -parse-stdlib -module-name Swift \ -Xfrontend -group-info-path -Xfrontend /Users/omochi/work/swift-source/swift/stdlib/public/core/GroupInfo.json \ -swift-version 5 -warn-swift3-objc-inference-complete -Xfrontend -verify-syntax-tree \ -Xllvm -sil-inline-generics -Xllvm -sil-partial-specialization -Xfrontend -enable-sil-ownership \ -Xcc -DswiftCore_EXPORTS -warn-implicit-overrides -module-link-name swiftCore -force-single-frontend-invocation \ -Xcc -D__SWIFT_CURRENT_DYLIB=swiftCore -parse-as-library \ -o Swift.o \ @/Users/omochi/work/swift-source/build/Ninja-DebugAssert/swift-macosx-x86_64/stdlib/public/core/WkKut.txt
(edited)#0 0x00000001033edfaa in swift::sys::Task::execute() at /Users/omochi/work/swift-source/swift/lib/Basic/Unix/TaskQueue.inc:198 #1 0x00000001033f0301 in TaskMonitor::beginExecutingATask(swift::sys::Task&) at /Users/omochi/work/swift-source/swift/lib/Basic/Unix/TaskQueue.inc:504 #2 0x00000001033eebf3 in TaskMonitor::startUpSomeTasks() at /Users/omochi/work/swift-source/swift/lib/Basic/Unix/TaskQueue.inc:477 #3 0x00000001033ee7a3 in TaskMonitor::executeTasks() at /Users/omochi/work/swift-source/swift/lib/Basic/Unix/TaskQueue.inc:451 #4 0x00000001033f106f in swift::sys::TaskQueue::execute(std::__1::function<void (int, void*)>, std::__1::function<swift::sys::TaskFinishedResponse (int, int, llvm::StringRef, llvm::StringRef, swift::sys::TaskProcessInformation, void*)>, std::__1::function<swift::sys::TaskFinishedResponse (int, llvm::StringRef, llvm::StringRef, llvm::StringRef, void*, llvm::Optional<int>, swift::sys::TaskProcessInformation)>) at /Users/omochi/work/swift-source/swift/lib/Basic/Unix/TaskQueue.inc:678 #5 0x000000010036431a in swift::driver::PerformJobsState::runTaskQueueToCompletion() at /Users/omochi/work/swift-source/swift/lib/Driver/Compilation.cpp:1089 #6 0x0000000100361333 in swift::driver::Compilation::performJobsImpl(bool&, std::__1::unique_ptr<swift::sys::TaskQueue, std::__1::default_delete<swift::sys::TaskQueue> >&&) at /Users/omochi/work/swift-source/swift/lib/Driver/Compilation.cpp:1388 #7 0x00000001003675ec in swift::driver::Compilation::performJobs(std::__1::unique_ptr<swift::sys::TaskQueue, std::__1::default_delete<swift::sys::TaskQueue> >&&) at /Users/omochi/work/swift-source/swift/lib/Driver/Compilation.cpp:1501 #8 0x0000000100334d61 in run_driver(llvm::StringRef, llvm::ArrayRef<char const*>) at /Users/omochi/work/swift-source/swift/tools/driver/driver.cpp:176 #9 0x0000000100332632 in main at /Users/omochi/work/swift-source/swift/tools/driver/driver.cpp:246
// Spawn the subtask. int spawnErr = posix_spawn(&Pid, ExecPath, &FileActions, nullptr, const_cast<char **>(argvp), const_cast<char **>(envp));
int Compilation::performJobs(std::unique_ptr<TaskQueue> &&TQ) {
において、冒頭のperformSingleCommandに突入するif文をすり抜けるのが/Users/omochi/work/swift-source/build/Ninja-DebugAssert/swift-macosx-x86_64/bin/swift -frontend -c -filelist /var/folders/1v/_s33fkpj07g9y3zvdfs9cz9m0000gn/T/sources-ffe05d -supplementary-output-file-map /var/folders/1v/_s33fkpj07g9y3zvdfs9cz9m0000gn/T/supplementaryOutputs-7c1c06 -disable-objc-attr-requires-foundation-module -target x86_64-apple-macosx10.9 -enable-objc-interop -sdk /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk -I /Users/omochi/work/swift-source/build/Ninja-DebugAssert/swift-macosx-x86_64/./lib/swift/macosx/x86_64 -F /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/../../../Developer/Library/Frameworks -warn-swift3-objc-inference-complete -warn-implicit-overrides -g -module-cache-path /Users/omochi/work/swift-source/build/Ninja-DebugAssert/swift-macosx-x86_64/./module-cache -module-link-name swiftCore -nostdimport -parse-stdlib -resource-dir /Users/omochi/work/swift-source/build/Ninja-DebugAssert/swift-macosx-x86_64/./lib/swift -swift-version 5 -Onone -D INTERNAL_CHECKS_ENABLED -D SWIFT_ENABLE_RUNTIME_FUNCTION_COUNTERS -enable-resilience -group-info-path /Users/omochi/work/swift-source/swift/stdlib/public/core/GroupInfo.json -verify-syntax-tree -enable-sil-ownership -Xllvm -sil-inline-generics -Xllvm -sil-partial-specialization -Xcc -DswiftCore_EXPORTS -Xcc -D__SWIFT_CURRENT_DYLIB=swiftCore -parse-as-library -module-name Swift -o Swift.o
$S
から $s
に!int swift::Demangle::getManglingPrefixLength(llvm::StringRef mangledName) { if (mangledName.empty()) return 0; llvm::StringRef prefixes[] = { /*Swift 4*/ "_T0", /*Swift 4.x*/ "$S", "_$S", /*Swift 5+*/ "$s", "_$s"}; // Look for any of the known prefixes for (auto prefix : prefixes) { if (mangledName.startswith(prefix)) return prefix.size(); } return 0; }
bool swift::Demangle::isOldFunctionTypeMangling(llvm::StringRef mangledName) { return mangledName.startswith("_T"); }
_T
, _T0
, $S
, $s
の 4つがこれまでにあるっぽい$s
から代わる事は今後無いと・・・#define MANGLING_PREFIX $s
になるってことはDemangling for $S1a3CatC4nameSSvg kind=Global kind=Getter kind=Variable kind=Class kind=Module, text="a" kind=Identifier, text="Cat" kind=Identifier, text="name" kind=Type kind=Structure kind=Module, text="Swift" kind=Identifier, text="String" $S1a3CatC4nameSSvg ---> a.Cat.name.getter : Swift.String
is
とかisa
って使えますか?protocol SomeProtocol{ // required method func r() // optional method func o() } extension SomeProtocol { // optional methods func o() { print("o() in SomeProtocol") } func p() { print("p() in SomeProtocol") } } class SomeClass: SomeProtocol { func r() { print("r() in SomeClass") } func o() { print("o() in SomeClass") } func p() { print("p() in SomeClass") } } let sc: SomeClass = SomeClass() sc.r() // 出力 "r() in SomeClass" sc.o() // 出力 "o() in SomeClass" sc.p() // 出力 "p() in SomeClass" let sp: SomeProtocol = sc sp.r() // 出力 "r() in SomeClass" sp.o() // 出力 "o() in SomeClass" sp.p() // 出力 "p() in SomeProtocol"
r() in SomeClass o() in SomeClass p() in SomeClass r() in SomeClass o() in SomeClass p() in SomeProtocol
func r()
と func o()
は、プロトコル定義にエントリがあるからfunc p()
はプロトコル定義にエントリがないからlet sc: SomeClass = SomeClass() sc.r() // 出力 "r() in SomeClass" ただのSomeClassのメソッド呼び出し sc.o() // 出力 "o() in SomeClass" ただのSomeClassのメソッド呼び出し sc.p() // 出力 "p() in SomeClass" ただのSomeClassのメソッド呼び出し let sp: SomeProtocol = sc sp.r() // 出力 "r() in SomeClass" 動的、SomeClass.rがテーブルから出てくる sp.o() // 出力 "o() in SomeClass" 動的、SomeClass.oがテーブルから出てくる sp.p() // 出力 "p() in SomeProtocol" 静的、式がSomeProtocolなのでSomeProtocol.pになる
(edited)protocol P { func a() -> String func b() -> String } extension P { func a() -> String { return "P" } func b() -> String { return "P" } } class C: P { func a() -> String { return "C" } } class SC: C { override func a() -> String { return "SC" } func b() -> String { return "SC" } } let sc: SC = SC() print(sc.a()) // SC print(sc.b()) // SC let c: C = sc print(c.a()) // SC print(c.b()) // P
SC SC SC P
c.b()
はwitness tableを見にいくけどb()がcから取り出せず、静的DispatchでP.bになる。(あってます?) c.a()
は実体はSCのインスタンスなので、SCのvTableを見にいって、SC.a()になる(あってます?) (edited)b
は SC
の VTable にはあるけど C
の VTable にはなくて、 C
として呼ばれたときには SC
の b
とは同名同型の別の関数として静的ディスパッチされる、だと思います。/usr/local/Cellar/llvm/HEAD-3898e47/include/c++/v1/stdlib.h:94:15: fatal error: 'stdlib.h' file not found #include_next <stdlib.h>
llvmのチュートリアルのコンパイルができない・・・・前はできたのに・・・・. brewでllvmインストールして,コンパイルしてたのだが・・・・・# Compile clang++ -g -O3 toy.cpp `llvm-config --cxxflags` # Run ./a.out
これをやると,stdlib.hが見つからないって言われて,あるのに・・・・って格闘中・・・・. LLVMチュートリアルのソースコードのコンパイルはこうすればいいよーってのがあったら教えてください・・・・・. ちょっと前までできてたのに・・・・・. (edited)brew link
あたりで修復してみるとか。/use/include
はある?Command Line Toolsを入れてもMojave標準だと存在しません。/use/include
が存在するのが前提で作られてるモノのために、別途インストールできる様になっています。DEVELOPMENT-SNAPSHOT-2018-11-01-a
のデバッガアタッチできましたswiftc
を指定してAttachしてから、TOOLCHAINS=org.swift.4220181113a swiftc
で起動したらアタッチできました。xcrun --toolchain org.swift.4220181113a swiftc
だとデバッガが見つけてくれなかった。swiftc
?util/build-script --debug --xcode --skip-build-benchmarks
でビルドしたswift, swiftc/Library/Developer/Toolchains/
にインストールしたツールチェインのswiftc
でもアタッチ出来るから、自前ビルドでも何か手順がありそうだけど… (edited)TOOLCHAINS=org.swift.42120181030a xcrun swift
使って起動したswift
にアタッチ出来た。/Library/Developer/Toolchains/swift-4.2.1-RELEASE.xctoolchain/usr/bin/swift
で起動してもアタッチ出来るから、自分でビルドしたものもいけそう。$ swift --version
とかを、wait for executable... で引っ掛けるのができないです。Driver::MainLoop
にシンボリックブレークポイント置いてちゃんと止まりました。 (edited)main
にシンボリックブレークポイント置いて、/Library/Developer/Toolchains/swift-4.2.1-RELEASE.xctoolchain/usr/bin/swift --version
で止まりました。getSwiftFullVersion
にシンボリックブレークポイントもいけました。swift
にしてる。xcscheme
ファイルを見ると/Library/Developer/Toolchains/swift-4.2.1-RELEASE.xctoolchain/usr/bin/swift
と記述されてる。 <BuildableProductRunnable runnableDebuggingMode = "0"> <BuildableReference BuildableIdentifier = "primary" BlueprintIdentifier = "C6F405DB688E4209BE9944BB" BuildableName = "swift" BlueprintName = "swift" ReferencedContainer = "container:../build/Xcode-DebugAssert/swift-macosx-x86_64/Swift.xcodeproj"> </BuildableReference> </BuildableProductRunnable>
<PathRunnable runnableDebuggingMode = "0" FilePath = "/Users/omochi/work/swift-source/build/Xcode-DebugAssert/swift-macosx-x86_64/Debug/bin/swift"> </PathRunnable>
直指定したらこうなったけど駄目でした、反応無し・・・/Library/Developer/Toolchains/swift-4.2.1-RELEASE.xctoolchain/usr/bin/swift
にアタッチ出来るかどうかで、ツールチェインとしてインストールしているかどうかの違いが原因か判るはず。/Library/Developer/Toolchains/swift-4.2.1-RELEASE.xctoolchain/usr/bin/swift
Could not attach to name : “swift” Problems with launching via XPC. XPC error : Connection invalid
Swift 4.2.1 Release 2018-10-30 (a)
を選択してても、問題なく/Library/Developer/Toolchains/swift-4.2.1-RELEASE.xctoolchain/usr/bin/swift
にアタッチ出来る。Wait for…もDebug Process As rootすればアタッチ出来るのも変わらず。 (edited)swift
を設定して試してた。 (edited)swift
にして試してみて欲しいかも。None
にしてデバッガを実行すると動く。 (edited)None
は、プロジェクトを閉じて再度開くと、None
からSchemeのターゲットに戻ってしまう。Yams.xcodeproj
は、ここに過去存在して今は存在しないターゲットが設定されたままになってるため、None
に戻らない。/Library/Developer/Toolchains/swift-4.2.1-RELEASE.xctoolchain/usr/bin/swift
/Library/Developer/Toolchains/swift-4.2.1-RELEASE.xctoolchain/usr/bin/swift -version
実行
/Library/Developer/Toolchains/swift-4.2.1-RELEASE.xctoolchain/usr/bin/swift
をアタッチする手順dummy
追加 2. メインのschemeのBuildアクションにdummy
を追加。 3. RunアクションのExpand Variables Base Onをdummy
に。 4. dummyターゲット削除、Buildアクションにはdummy (missing)
が残り、Expand Variables Base Onもdummy (missing)
のままになり、プロジェクトを再度開いてもそのまま残る。swift
にアタッチ出来ない問題も、このExpand Variables Base Onの影響を受けているのならば、missingで回避出来るかも?${SRCROOT}
などを使う時に、元となる設定をどのターゲットから持ってくるか、を設定するものかと。root
で、Stopping due to fatal error: DllNotFoundException: libc.dylibStopping due to fatal error: DllNotFoundException: libc.dylib
が出て,プロセスにアタッチできない・・・・.誰か,同じような現象にあったことがある方いらっしゃいませんか?text
がinternalじゃなくてpublicだと嬉しいんですが、なにか困ることありますか? https://github.com/apple/swift-syntax/blob/master/Sources/SwiftSyntax/TokenKind.swift.gyb#L35StringLiteralExprSyntax
の値が空文字かどうか判定するのに下記のコード書く時にstringQuote
やmultilineStringQuote
のtext
使いたかったです。まあ無くても別に問題ないのであったら良いなぐらいですね。 public override func visit(_ node: StringLiteralExprSyntax) { let value = node.stringLiteral.text guard value != "\"\"", value != "\"\"\"\"\"\"" else { return } ... }
(edited)Syntax.swift
に関する変更は入らないのか... https://github.com/apple/swift-syntax/pull/94/files#define DEBUG_TYPE "sil-inliner"
ってタグの定義がついてて$ swiftc -emit-sil -Xllvm -debug-only=sil-inliner
ってやると.swiftmodule
と.swiftdoc
の中身を見たりダンプするコマンドってありますか?llvm-bcanalyzer -dump
で llvm ビットコード全般ダンプできるんですが、Swift向けに作られているわけでは無く、独自のコンテナの中身は見られないので、あまり参考にはならないです。 (edited)<BLOCKINFO_BLOCK/> <MODULE_DOC_BLOCK NumWords=813176 BlockCodeSize=2> <CONTROL_BLOCK NumWords=32 BlockCodeSize=3> <METADATA abbrevid=5 op0=1 op1=1 op2=0 op3=0/> blob data = 'Swift version 5.0-dev (LLVM 06f1615069, Swift edb924f743)' <MODULE_NAME abbrevid=4/> blob data = 'Swift' <TARGET abbrevid=6/> blob data = 'x86_64-apple-macosx10.9' </CONTROL_BLOCK> <COMMENT_BLOCK NumWords=813139 BlockCodeSize=4> <DECL_COMMENTS abbrevid=4 op0=3181980/> blob data = unprintable, 3247524 bytes. <GROUP_NAMES abbrevid=5/> blob data = unprintable, 5004 bytes. </COMMENT_BLOCK> </MODULE_DOC_BLOCK>
BLOCKINFO#0 { } BLOCKINFO#0 MODULE_BLOCK#8 { CONTROL_BLOCK#9 { MODULE_NAME#2 METADATA#1 TARGET#3 OPTIONS_BLOCK#16 { IS_SIB#3 IS_TESTABLE#4 SDK_PATH#1 XCC#2 XCC#2 } OPTIONS_BLOCK#16 } CONTROL_BLOCK#9 ...
import Foundation let interface = try! String(contentsOfFile: "/usr/lib/swift/linux/x86_64/Swift.swiftinterface") print(interface)
// swift-interface-format-version: 1.0 // swift-tools-version: Swift version 5.0-dev (LLVM 06f1615069, Swift 844d4df31a) // swift-module-flags: -disable-objc-attr-requires-foundation-module -target x86_64-unknown-linux-gnu -disable-objc-interop -enable-library-evolution -module-link-name swiftCore -parse-stdlib -swift-version 5 -O -enforce-exclusivity=unchecked -module-name Swift import SwiftShims @inlinable public func min<T>(_ x: T, _ y: T) -> T where T : Swift.Comparable { // In case `x == y` we pick `x`. // This preserves any pre-existing order in case `T` has identity, // which is important for e.g. the stability of sorting algorithms. // `(min(x, y), max(x, y))` should return `(x, y)` in case `x == y`. return y < x ? y : x } @inlinable public func min<T>(_ x: T, _ y: T, _ z: T, _ rest: T...) -> T where T : Swift.Comparable { var minValue = min(min(x, y), z) // In case `value == minValue`, we pick `minValue`. See min(_:_:). for value in rest where value < minValue { minValue = value } return minValue } @inlinable public func max<T>(_ x: T, _ y: T) -> T where T : Swift.Comparable { // In case `x == y`, we pick `y`. See min(_:_:). return y >= x ? y : x } @inlinable public func max<T>(_ x: T, _ y: T, _ z: T, _ rest: T...) -> T where T : Swift.Comparable { var maxValue = max(max(x, y), z) // In case `value == maxValue`, we pick `value`. See min(_:_:). for value in rest where value >= maxValue { maxValue = value } return maxValue } @_fixed_layout public struct EnumeratedSequence<Base> where Base : Swift.Sequence { @usableFromInline internal var _base: Base @inlinable internal init(_base: Base) { self._base = _base } } extension EnumeratedSequence { @_fixed_layout public struct Iterator { @usableFromInline internal var _base: Base.Iterator @usableFromInline internal var _count: Int @inlinable internal init(_base: Base.Iterator) { self._base = _base self._count = 0 } }
.swiftinterface
入ってるのか。-dump-ast
のParserの部分を独立させて、現行の環境で動くようにしました。よかったら参考にしてください。 https://github.com/kishikawakatsumi/SwiftAST 使い方は swift-ast parse [FILE_PATH_TO_PARSE] -buildCommand [BUILD_COMMAND_TO_BUILD_THE_PROJECT]
例えば path/to/swift-ast parse "./Framework/Sources/SpreadsheetView.swift" -buildCommand xcodebuild -scheme SpreadsheetView
や、 path/to/swift-ast parse ./Lib/KeychainAccess/Keychain.swift -buildCommand xcodebuild -scheme KeychainAccess -sdk iphonesimulator -destination "name=iPhone Xs,OS=12.2"
です。 以下、思い出したことを書きます。 (edited)swift -dump-ast
produces - kishikawakatsumi/SwiftAST-dump-ast
は全ての型が解決しているので原則としてコンパイルが成功する必要があります。簡単な(依存関係がない)ファイルなら簡単ですが、他のファイルやモジュールを参照している場合は同じモジュールのファイルの場合はそれを一緒に渡す、別モジュールの場合はそれを先にビルドする必要があります。 なので、時間は余計にかかるのですが、 https://github.com/kishikawakatsumi/SwiftAST/blob/master/Sources/SwiftAST/XcodebuildTool.swift#L37-L42 のように swift -dump-ast
を実行する前にまずビルドしています。 ビルドエラーが起こる状態で swift -dump-ast
を実行した場合、単に失敗するか不完全なASTが出力されます。 swift -dump-ast
の出力自体が謎であるのにさらに不完全なASTを相手にするのは無理なので、最初のキモは確実にビルドできるパラメータを組み立てることです。 (edited)swift -dump-ast
produces - kishikawakatsumi/SwiftASTconstructor_decl
や brace_stmt
assign_expr
といったノードの種類がよくわからないことと、それぞれがどういう属性を持っているかが当然Undocumentedでよくわからないところで、Parse自体はそれほど難しくないはず(目的にもよりますが)です。private func process(sourceFile: URL, verbose: Bool = false) throws -> AST { let arguments = buildArguments(source: sourceFile) let rawAST = try dumpAST(arguments: arguments) let tokens = tokenize(rawAST: rawAST) let node = lex(tokens: tokens) let root = parse(node: node) return root }
dumpAST(arguments:)
はswift -dump-ast
を実行します。 得られたテキストをtokenize(rawAST:)
でトークンに分割して、lex(tokens:)
でツリー構造を作ります。 最後にparse(node:)
でツリー構造のデータに意味を持たせます。swift -dump-ast
produces - kishikawakatsumi/SwiftAST-dump-ast
の出力はS式のように見えるのでカッコを頼りにしたくなりますが、別の意味のカッコが普通に("
や'
に囲まれることなく)出てくるのでそれは難しいです。 代わりに行とインデントを使います。func tokenize(source: String) -> [ASTToken] { var lines = [String]() for line in source.split(separator: "\n", omittingEmptySubsequences: false) { let trimmed = line.trimmingCharacters(in: .whitespaces) if trimmed.hasPrefix("(inherited_conformance") || trimmed.hasPrefix("(normal_conformance") || trimmed.hasPrefix("(abstract_conformance") || trimmed.hasPrefix("(specialized_conformance") || trimmed.hasPrefix("(assoc_type") || trimmed.hasPrefix("(value req") || !trimmed.hasPrefix("(") { continue } lines.append(String(line)) } ...
-dump-ast
の出力をまず行ごとに分割します。このとき、いくつかのプロジェクトでノイズになる行(実行コードには関係なく見える上にインデントがおかしい)が発見されたのでそれを取り除いています。indent
(先頭の空白)、symbol
(シングルクオートで囲まれた文字列)、string
(ダブルクオートで囲まれた文字列)、token
(それ以外の文字列や記号)に分類しました。 class ASTToken { enum TokenType { case token case symbol case string case indent(Int) }
▿ 1498 elements ▿ 0 : ( ▿ 1 : source_file ▿ 2 : "/Users/katsumi/Documents/XcodeProjects/SwiftPowerAssert/Fixtures/Atlas/Sources/Atlas/Atlas.swift" ▿ 3 : __ ▿ 4 : ( ▿ 5 : struct_decl ▿ 6 : range ▿ 7 : = ▿ 8 : /Users/katsumi/Documents/XcodeProjects/SwiftPowerAssert/Fixtures/Atlas/Sources/Atlas/Atlas.swift:1:8 - line:17:1 ▿ 9 : "Country" ▿ 10 : interface ▿ 11 : type ▿ 12 : = ▿ 13 : 'Country.Type' ...
ASTLexer
がこのトークンの配列をツリー構造にします。Lexerといってますが、ツリー構造に変換するだけです。[(, source_file, "/Users/katsumi/Documents/XcodeProjects/SwiftPowerAssert/Fixtures/Atlas/Sources/Atlas/Atlas.swift"] [(, struct_decl, range, =, /Users/katsumi/Documents/XcodeProjects/SwiftPowerAssert/Fixtures/Atlas/Sources/Atlas/Atlas.swift:1:8 - line:17:1, "Country", interface, type, =, 'Country.Type', access, =, public, non-resilient] [(, pattern_binding_decl, range, =, /Users/katsumi/Documents/XcodeProjects/SwiftPowerAssert/Fixtures/Atlas/Sources/Atlas/Atlas.swift:2:12 - line:2:22] [(, pattern_typed, type, =, 'String'] [(, pattern_named, type, =, 'String', 'code', )] [(, type_ident] [(, component, id, =, 'String', bind, =, Swift.(file).String))))] [(, var_decl, range, =, /Users/katsumi/Documents/XcodeProjects/SwiftPowerAssert/Fixtures/Atlas/Sources/Atlas/Atlas.swift:2:16 - line:2:16, "code", type, =, 'String', interface, type, =, 'String', access, =, public, let, readImpl, =, stored, immutable] [(, accessor_decl, implicit, range, =, /Users/katsumi/Documents/XcodeProjects/SwiftPowerAssert/Fixtures/Atlas/Sources/Atlas/Atlas.swift:2:16 - line:2:16, 'anonname=0x10a8205a8', interface, type, =, '(Country) -> () -> String', access, =, public, get_for, =, code] [(, parameter, "self", interface, type, =, 'Country', )] [(, parameter_list, )] [(, brace_stmt, implicit, range, =, /Users/katsumi/Documents/XcodeProjects/SwiftPowerAssert/Fixtures/Atlas/Sources/Atlas/Atlas.swift:2:16 - line:2:16] [(, return_stmt, implicit] ...
こんな感じです。これでツリー構造とノードの種別や属性情報がプログラムから扱える形になりました。struct_decl
とかvar_decl
、call_expr
、member_ref_expr
、dot_syntax_call_expr
などです。それ以外に膨大な種類のノードがあるので、全部に対応するのはとても大変なので、必要に応じてノードをフィルタして使っていく、というのが良いかと私は考えています。private func parseSourceFileNode(node sourceFileNode: ASTNode<[ASTToken]>) -> AST { var declarations = [Declaration]() for node in sourceFileNode.children { for token in node.value { switch (token.type, token.value) { case (.token, "top_level_code_decl"): declarations.append(.topLevelCode(parseTopLevelCodeDeclarationNode(node: node))) case (.token, "import_decl"): declarations.append(.import(parseImportDeclarationNode(node: node))) case (.token, "struct_decl"): declarations.append(.struct(parseStructDeclarationNode(node: node))) case (.token, "class_decl"): declarations.append(.class(parseClassDeclarationNode(node: node))) case (.token, "enum_decl"): declarations.append(.enum(parseEnumDeclarationNode(node: node))) case (.token, "extension_decl"): declarations.append(.extension(parseExtensionDeclarationNode(node: node))) case (.token, "func_decl"): declarations.append(.function(parseFunctionDeclarationNode(node: node))) default: break } } } return AST(declarations: declarations) }
のようにまずStructやClass宣言を拾って、そのあと例えば関数だったらprivate func parseFunctionDeclarationNode(node: ASTNode<[ASTToken]>) -> FunctionDeclaration { let tokens = node.value let name = parseString(tokens: tokens) ?? parseSymbol(tokens: tokens) let accessLevel = parseAccessLevel(tokens: tokens) var parameters = [Parameter]() var body = [Statement]() for node in node.children { for token in node.value { switch (token.type, token.value) { case (.token, "parameter_list"): parameters.append(contentsOf: parseParameterListNode(node: node)) case (.token, "brace_stmt"): body.append(.expression(parseExpressionNode(node: node))) default: break } } } return FunctionDeclaration(accessLevel: accessLevel, name: name!, parameters: parameters, body: body) }
パラメータやステートメントをさらに拾っていく、としています。 一番大変なのがこのParser部分を作っていくところだと思います。ここは自分が利用する情報を探しながらトライアルアンドエラーで書いていくことになります。swift-ast
をいくつかのプロジェクトで試しましたが、clangモジュールのインポートをするためのパラメータが足りていない様です。 output: <unknown>:0: error: missing required module 'clibc'
あと、-showBuildSettings
の出力は-json
を使うとパースが簡単になると思います。 (edited)(parameter_list (parameter "i" interface type='Int') range=[foo.swift:1:17 - line:1:17])
https://github.com/kateinoigakukun/TouchTypist/blob/master/Sources/TypeCheckedAST/Parser/CanonicalTransformer.swift#L22-L29 (edited)(constructor_decl range=[/Users/katsumi/Documents/XcodeProjects/KeychainAccess/Lib/KeychainAccess/Keychain.swift:229:12 - line:231:5] "init(rawValue:)" interface type='(AuthenticationPolicy.Type) -> (UInt) -> AuthenticationPolicy' access=public designated (parameter "self" interface type='AuthenticationPolicy' inout) (parameter_list (parameter "rawValue" apiName=rawValue interface type='UInt') range=[/Users/katsumi/Documents/XcodeProjects/KeychainAccess/Lib/KeychainAccess/Keychain.swift:229:16 - line:229:31])
問題なさそうに見えますけど、どういう風に違いますか?xcodebuild -showBuildSettings -json -scheme KeychainAccess
みたいに書けるんですね。。。(parameter_list range=[foo.swift:1:17 - line:1:17] (parameter "i" interface type='Int'))
(parameter_list (parameter "i" interface type='Int') range=[foo.swift:1:17 - line:1:17]) // ここまでparameterの要素としてパースされる
(edited)XcodebuildTool.constructSwiftOptions(xcodebuildLog:)
で-fmodule-map-file=
も使う必要がある。
swiftc
へ渡されてるパラメータに含まれていますよ。 (edited)swift package generate-xcodeproj
してswift run swift-ast parse Sources/SwiftAST/main.swift -buildCommand xcodebuild -scheme SwiftAST
で言われます。$ swift package generate-xcodeproj warning: invalid duplicate target dependency declaration 'swift-build' in target 'FunctionalPerformanceTests' warning: invalid duplicate target dependency declaration 'swift-package' in target 'FunctionalPerformanceTests' generated: ./SwiftAST.xcodeproj $ swift run swift-ast parse Sources/SwiftAST/main.swift -buildCommand xcodebuild -scheme SwiftAST warning: invalid duplicate target dependency declaration 'swift-build' in target 'FunctionalPerformanceTests' warning: invalid duplicate target dependency declaration 'swift-package' in target 'FunctionalPerformanceTests' Reading project settings... Building dependencies... Parsing... failed to run the following command: '/usr/bin/xcrun swift -frontend -suppress-warnings -dump-ast -sdk /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk -F /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/../../../Developer/Library/Frameworks -target x86_64-apple-macosx10.10 -I /Users/norio/Library/Developer/Xcode/DerivedData/SwiftAST-gglvpwfxcdqcbehkwkywmelahzns/Build/Products/Debug -F /Users/norio/Library/Developer/Xcode/DerivedData/SwiftAST-gglvpwfxcdqcbehkwkywmelahzns/Build/Products/Debug -F /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/Library/Frameworks -primary-file /Users/norio/github/SwiftAST/Sources/SwiftAST/main.swift /Users/norio/github/SwiftAST/Sources/SwiftAST/Errors.swift /Users/norio/github/SwiftAST/Sources/SwiftAST/ParseTool.swift /Users/norio/github/SwiftAST/Sources/SwiftAST/SwiftASTTool.swift /Users/norio/github/SwiftAST/Sources/SwiftAST/SwiftBuildTool.swift /Users/norio/github/SwiftAST/Sources/SwiftAST/XcodebuildTool.swift' output: <unknown>:0: error: missing required module 'clibc'
swiftc
パラメータの構築をやっていて、 swiftc
へ渡されるパラメータを取得DerivedData
内に作成するllbuildマニフェストから取得debug.yml
から取得llbuildSwift
とか使えるのかな? https://github.com/jpsim/SourceKitten/blob/67b93b83bafa83306fbb9dd201d4dfd22661a53a/Source/SourceKittenFramework/Xcode.swift#L287-L322Cloning 'sourcekit-lsp' Cloning 'libcxx' Cloning 'indexstore-db' Cloning 'swift-stress-tester' Cloning 'swift-syntax' Cloning 'clang-tools-extra'
def CC_X86_64_C : CallingConv<[ // Pass SwiftSelf in a callee saved register. CCIfSwiftSelf<CCIfType<[i64], CCAssignToReg<[R13]>>>, // A SwiftError is passed in R12. CCIfSwiftError<CCIfType<[i64], CCAssignToReg<[R12]>>>,
// build/Xcode-DebugAssert/llvm-macosx-x86_64/lib/Target/X86/X86GenCallingConv.inc static bool CC_X86_64_C(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, CCState &State) { if (ArgFlags.isSwiftSelf()) { if (LocVT == MVT::i64) { if (unsigned Reg = State.AllocateReg(X86::R13)) { State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); return false; } } } if (ArgFlags.isSwiftError()) { if (LocVT == MVT::i64) { if (unsigned Reg = State.AllocateReg(X86::R12)) { State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); return false; } } } }
SyntaxParseActions
を HiddenLibSyntaxAction
でラップする感じ。SyntaxParsingContext
だけでも最初は意味不明だしASTContext
とそこまでやってること違わない気はする。SyntaxParsingContext
-> Syntax Tree ASTContext
-> AST objectsSyntaxParsingContext
と ASTContext
への値注入を同じ場所でやってるのが今回のモチベーションのはず1 + 2 * 3
みたいな式が演算子の優先度関係なくフラットになっちゃってるんだけど、これを階層付けするのってparserで解析したoperator precedenceだけでできるから、parserのlibASTで組み替えてるのかな?var body: some view {}
をSwiftSyntaxに渡すと意図してないようなシンタックスで返ってきます。たぶんswiftc側の修正が必要? some view
が someView
になってしまう。 ▿ typeAnnotation : Optional<TypeAnnotationSyntax> ▿ some : SwiftSyntax.TypeAnnotationSyntax ▿ colon : SwiftSyntax.TokenSyntax - text : ":" ▿ leadingTrivia : Trivia - pieces : 0 elements ▿ trailingTrivia : Trivia ▿ pieces : 1 element ▿ 0 : TriviaPiece - spaces : 1 - tokenKind : SwiftSyntax.TokenKind.colon ▿ type : SwiftSyntax.SimpleTypeIdentifierSyntax ▿ name : SwiftSyntax.TokenSyntax - text : "someView" ▿ leadingTrivia : Trivia - pieces : 0 elements ▿ trailingTrivia : Trivia ▿ pieces : 1 element ▿ 0 : TriviaPiece - spaces : 1 ▿ tokenKind : TokenKind - identifier : "someView" - genericArgumentClause : nil - initializer : nil
SomeTypeSyntax
になってるのを確認しました。+
とか-
。 そもそもlexerではそこまで判定する必要ないのかな https://github.com/apple/swift/blob/master/utils/gyb_syntax_support/Token.py (edited)Qol
ってなんだろうIn file included from /Users/omochi/work/swift-source/llvm/include/llvm/ADT/STLExtras.h:20: /Users/omochi/work/swift-source/llvm/include/llvm/ADT/Optional.h:141:3: error: unknown type name 'constexpr' constexpr Optional() {} ^ /Users/omochi/work/swift-source/llvm/include/llvm/ADT/Optional.h:141:13: error: constructor cannot have a return type constexpr Optional() {} ^~~~~~~~
$ brew upgrade cmake
で解決しました。-- The C compiler identification is unknown -- The CXX compiler identification is unknown
↑こんなメッセージが出ていた-std=c+11
が追加されてるわ。CMake Error in cmake/modules/CMakeLists.txt: export called with target "swiftSwiftLang-macosx-x86_64" which requires target "sourcekitd" that is not in any export set.
(edited)1.7G ./Ninja-ReleaseAssert/swift-linux-x86_64 3.9M ./Ninja-ReleaseAssert/cmark-linux-x86_64 2.2G ./Ninja-ReleaseAssert/llvm-linux-x86_64 3.9G ./Ninja-ReleaseAssert 27G ./Ninja-DebugAssert/swift-linux-x86_64 5.1M ./Ninja-DebugAssert/cmark-linux-x86_64 42G ./Ninja-DebugAssert/llvm-linux-x86_64 68G ./Ninja-DebugAssert
-###
って何の機能ですかclang
にはそのオプションがあるみたいですね。 $ clang -help OVERVIEW: clang LLVM compiler USAGE: clang [options] file... OPTIONS: -### Print (but do not run) the commands to run for this compilation
swift/utils/update-checkout
で取得できるリポジトリ達を置くディレクトリ全体で検索するのがポイントですかね。 (edited)swift/utils/update-checkout
はLLVM monorepo transitionを自動で処理してくれるのかな? https://forums.swift.org/t/llvm-monorepo-transition-happening-on-thursday-the-17th-of-october/29674llvm-project
をクローンしてclang
, clang-tools-extra
, compiler-rt
, libcxx
, lldb
, llvm
を削除してからswift/utils/update-checkout --scheme master
を実行したら、削除したモノ達と同名のシンボリックリンク達が作られた。 (edited)utils/update-checkout --scheme master
したらシンボリックリンクが作られたと記憶。 (edited)./clang -> /Users/norio/github/swift-dev/llvm-project/clang ./clang-tools-extra -> /Users/norio/github/swift-dev/llvm-project/clang-tools-extra ./compiler-rt -> /Users/norio/github/swift-dev/llvm-project/compiler-rt ./libcxx -> /Users/norio/github/swift-dev/llvm-project/libcxx ./lldb -> /Users/norio/github/swift-dev/llvm-project/lldb ./llvm -> /Users/norio/github/swift-dev/llvm-project/llvm
swift/utils/update_checkout/update_checkout/update_checkout.py
はsymlink作る処理入ってない。 (edited)--scheme master
だとその処理に行く前に、--tag swift-5.1.2-RELEASE
?(cd swift; git checkout swift-5.1.2-RELEASE)
swift/utils/update-checkout --tag swift-5.1.2-RELEASE
で良いのでは。swift-5.1.2-RELEASE
はswift-5.1-branch
からではなくswift-5.1-branch-08-28-2019
から作られたのだろう。swift-5.1-branch
に入ってて、swift-5.1.2-RELEASE
に入ってない変更たくさんある。 https://github.com/apple/swift/compare/swift-5.1.2-RELEASE...swift-5.1-branch[5.1]
ってつけて別PRなんですね。swift-5.1.2-RELEASE
タグ、付け直されてる… https://github.com/apple/swift/commits/swift-5.1.2-RELEASEswift-5.1.2-RELEASE
までと違い、swift-5.1.3-RELEASE
は ちゃんとswift-5.1-branch
から作られてた。 https://github.com/apple/swift/compare/swift-5.1-branch...swift-5.1.3-RELEASEswiftc
コマンドにソースファイルを引数として与える場合に、 トップレベルに実行文が書けるモードになるのって、 「引数が1ファイルの場合」または「ファイル名がmain.swift」 っぽく読めるんですけど、そうなん? (edited)__start_<section>
と __stop_<section>
というシンボルを生成する。__attribute__((__constructor__))
を付けた関数を定義しておくことで、 イメージがロードされた時にこれが呼び出され・・・ (edited)#define DECLARE_SWIFT_SECTION(name) \ __asm__("\t.section " #name ",\"a\"\n"); \ __attribute__((__visibility__("hidden"),__aligned__(1))) extern const char __start_##name; \ __attribute__((__visibility__("hidden"),__aligned__(1))) extern const char __stop_##name; extern "C" { DECLARE_SWIFT_SECTION(swift5_protocols)
__start_section
と __stop_section
のシンボルをリンクさせて・・・ (edited)#define SWIFT_SECTION_RANGE(name) \ { reinterpret_cast<uintptr_t>(&__start_##name), \ static_cast<uintptr_t>(&__stop_##name - &__start_##name) } ... SWIFT_SECTION_RANGE(swift5_protocols),
__start
__stop
はLLVMが出力するんじゃなくて lldが全てのオブジェクトファイルをリンクするときに作りますnamespace { static const swift::MetadataSections *registered = nullptr; void record(const swift::MetadataSections *sections) { if (registered == nullptr) { registered = sections; sections->next = sections->prev = sections; } else { registered->prev->next = sections; sections->next = registered; sections->prev = registered->prev; registered->prev = sections; } } }
これでリンクリストに追加してた。 (edited)swift::MetadataSections * swift::(anon ns)::registered
が __attribute__((__visibility__("hidden"),__aligned__(1))) extern const char __start_##name;
swift_image_constructor
は同じobjectの中だからこれが見えて、スタートシンボルが取れて、その場でグローバルに登録しちゃうけど(lldb) image lookup -s __stop_swift5_protocols 1 symbols match '__stop_swift5_protocols' in /home/katei/swift-work/reloc/link-elf/main: Address: main[0x0000000000001a60] (main.PT_LOAD[0].swift5_protocols + 0) Summary: main.PT_LOAD[0].swift5_protocols + 0 1 symbols match '__stop_swift5_protocols' in /home/katei/swift-source/build/Ninja-DebugAssert/swift-linux-x86_64/lib/swift/linux/x86_64/libswiftGlibc.so: Address: libswiftGlibc.so[0x0000000000010815] (libswiftGlibc.so.PT_LOAD[0].swift5_protocols + 0) Summary: 1 symbols match '__stop_swift5_protocols' in /home/katei/swift-source/build/Ninja-DebugAssert/swift-linux-x86_64/lib/swift/linux/x86_64/libswiftCore.so: Address: libswiftCore.so[0x0000000000986300] (libswiftCore.so.PT_LOAD[1].swift5_protocols + 428) Summary: libswiftCore.so.PT_LOAD[1].swift5_protocols + 428 1 symbols match '__stop_swift5_protocols' in /home/katei/swift-source/build/Ninja-DebugAssert/swift-linux-x86_64/lib/swift/linux/x86_64/libswiftSwiftOnoneSupport.so: Address: libswiftSwiftOnoneSupport.so[0x00000000000009ac] (libswiftSwiftOnoneSupport.so.PT_LOAD[0].swift5_protocols + 0) Summary:
swift5_protocols
達は__visibility__("hidden")
になってるね。 https://github.com/apple/swift/blob/master/stdlib/public/runtime/SwiftRT-ELF.cpp#L21-L28 (edited)terminal.sh-session root@5b642bfaddfb:~# objdump -t /usr/lib/swift/linux/libswiftCore.so|grep swift5_protocols 0000000000518b08 l O swift5_protocols 00000000000001a8 l_protocols 0000000000518b08 l swift5_protocols 0000000000000000 .hidden __start_swift5_protocols 0000000000518cb0 l swift5_protocols 0000000000000000 .hidden __stop_swift5_protocols
(edited)objdump
で見えるシンボルにいくつかdlsym
を試してみると、どうやらローカルl
になってるものは取得出来ないらしい。 terminal.sh-session 0000000000518b08 l swift5_protocols 0000000000000000 .hidden __start_swift5_protocols ^ ローカルを意味するらしい。
terminal.sh-session root@5b642bfaddfb:~# objdump -t /usr/lib/swift/linux/libswiftCore.so|grep "swift_copyPOD" 00000000003c7b00 g F .text 0000000000000016 .protected swift_copyPOD
(edited)import Glibc let s = dlsym(nil, "swift_copyPOD") print(s!)
0x00007f440c511b00
g
になってればdlsym
で取得できる。objdump -t
の出力詳細は https://linuxcommand.net/objdump/#_-t を参考にした。// expected-error {{}}
を実行結果から自動で生成するツールってないかしら-verify-apply-fixes
というのがあるのですが、現在のところエラー文言の修正や fix-it の不一致の修正くらいしかできないです。 $ cat /tmp/t.swift guard false { // expected-error {{...}} {{none}} fatalError() } $ swift -frontend -typecheck -verify-apply-fixes /tmp/t.swift -sdk $(xcrun -show-sdk-path -sdk macosx) /tmp/t.swift:1:35: error: incorrect message found guard false { // expected-error {{...}} {{none}} ^~~ expected 'else' after 'guard' condition $ cat /tmp/t.swift guard false { // expected-error {{expected 'else' after 'guard' condition}} {{none}} fatalError() } $ swift -frontend -typecheck -verify-apply-fixes /tmp/t.swift -sdk $(xcrun -show-sdk-path -sdk macosx) /tmp/t.swift:1:77: error: expected no fix-its; actual fix-it seen: {{12-12=else }} guard false { // expected-error {{expected 'else' after 'guard' condition}} {{none}} ^~~~~~~ {{12-12=else }} $ cat /tmp/t.swift guard false { // expected-error {{expected 'else' after 'guard' condition}} {{12-12=else }}} fatalError() }
つまりは -verify
モードで出る fix-it をオリジナルファイルに適用するというモードです。$ cat /tmp/t.swift guard false { fatalError() } $ swift -frontend -typecheck -verify /tmp/t.swift -sdk $(xcrun -show-sdk-path -sdk macosx) /tmp/t.swift:1:13: error: unexpected error produced: expected 'else' after 'guard' condition guard false { ^
みたいなときに、 // expected-error {{expected 'else' after 'guard' condition}}
を挿入するようなfix-it が出れば良いのですが、現状そうなってないです -verify
/-verify-apply-fixes
の実装はここにあります https://github.com/apple/swift/blob/master/lib/Frontend/DiagnosticVerifier.cpp-M
とかはあるけど、 GitHubでの表示では隠し設定だし、 XcodeのGitサポートでは対応無さそうだし。xcrun
はSandboxが有効のアプリからは実行できない。$ xcrun -sdk iphoneos lipo
とか。xcrun
がsandboxで使えないかは知らないけど、sourcekit-lsp
は依存してるsourcekitd
がsandboxで使えないのは確か。sourcekitten
とswiftlint
のHomebrewのボトル作成テストがsandbox下で動かなくて、回避コードを書いたことがある。xcrun
を動かしてみたけど、ちゃんと動いた。git@
になってる。https
の方が良いと思う。 (edited)Precondition failed: tried to send message before calling start(messageHandler:): file /Users/rintaro/Library/Developer/Xcode/DerivedData/SourceKitForSafari-exmylkeuqkdqunbichifwiexymed/SourcePackages/checkouts/sourcekit-lsp/Sources/LanguageServerProtocolJSONRPC/JSONRPCConnection.swift, line 152
https://github.com/kishikawakatsumi/SourceKitForSafari/blob/master/file:/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSTask.h#L32
みたいなパスを開こうとして404になりますね。 (edited)import UIKit
のエラーが取れない、、、というところで結構苦しみました。func f(a) {} // expected-error {{unnamed parameters must be written with the empty name '_'}} \ // expected-error {{use of undeclared type 'a'}}
@-1
が要らない・・・$ ninja swift
でやってるけど、ブランチ切替時とか構成の変更がある時はダメな場合もありそうなので気になります。$ cmake --build ../build/Ninja-ReleaseAssert/swift-macosx-x86_64/ -- -j8 swift swift-ide-test $ utils/run-test --build-dir ../build/Ninja-ReleaseAssert/ --build=skip test/IDE
みたいな感じです。--reconfigure
はアレはなんで必要なんですか?--release-debuginfo
を使うんですけど、 Swiftコンパイラの中をデバッグしたい事もあって、そのときは --release-debuginfo --debug-swift
が必要で、-R
で、debuginfo も無しで、printデバッグなので-R
は debuginfoなしの --release
でしたっけ。-R --debug-swift
でビルドして、頑張りますが、普段からビルドしてないと当然時間かかりまくるので、最終手段ですね。SafariExtensionHandler
が受け取ったinitialize
を処理しきる前に別スレッドでdidOpen
を受け取って、SourceKitServiceProxy
内のconnection.resume()
呼び出しが_xpc_api_misuse
でクラッシュするパターンがよくある。 (edited)bundle.js
側で同期とるのは面倒そうだから、その方が良さそう。if let task = SecTaskCreateFromSelf(nil), let groups = SecTaskCopyValueForEntitlement(task, NSString("com.apple.security.application-groups"), nil) as? [String] { print("App Groups:", groups) }
(edited)com.
がない箇所がある...@IBDesignable
をいろいろ練習しました。public func expect<T>(_ expression: @autoclosure () -> T) -> T { print("First") return expression() } let x = expect { 1 } print("x: \(x)") // x: (Function)
↑trailing closureとautoclosureが連動すると、T
が関数型に推論される。func f(aa: () -> Int, bb: Int = 0, cc: Int = 0) { print(1) } func f(bb: Int = 0, cc: Int = 0, aa: () -> Int) { print(2) } f { 0 } // Xcode11.3 => 2 // master => ambiguous use of 'f'
func foo<T>(_ f: T) { print(T.self) } foo(1) foo { 1 }
これと同じはずでT
から () -> T
だね。func f(aa: () -> Int, bb: Int = 0) { } f { 1 }
public func expect<T>(_ expression: @autoclosure () -> T) -> T { print("First") return expression() } let x = expect { 1 } print("x: \(x)")
First x: (Function)
func f(aa: () -> Int, bb: Int = 0, cc: Int = 0) { } f { 1 }
↑ここまでだと俺のも入ってるfunc foo(_ f: @autoclosure () -> Int) { } foo { 1 }
これはコンパイルエラーなので。func foo<T>(_ f: T) { print(1) } func foo<T>(_ f: () -> T) { print(2) } foo { 1 }
は Swift 5.2 だと Ambiguous だけど、2の方に解決されるべき。func foo<T>(_ f: T) { print(1) } func foo<T>(_ f: () -> T) { print(2) } foo { 1 }
<stdin>:3:1: error: ambiguous use of 'foo' foo { 1 } ^ <stdin>:1:6: note: found this candidate func foo<T>(_ f: T) { print(1) } ^ <stdin>:2:6: note: found this candidate func foo<T>(_ f: () -> T) { print(2) } ^
func foo<T>(_ f: T) { print(1) } func foo<T>(_ f: () -> T) { print(2) } foo { 1 }
<stdin>:3:1: error: ambiguous use of 'foo' foo { 1 } ^ <stdin>:1:6: note: found this candidate func foo<T>(_ f: T) { print(1) } ^ <stdin>:2:6: note: found this candidate func foo<T>(_ f: () -> T) { print(2) } ^
func foo<T>(_ f: T) { print(1) } func foo<T>(_ f: () -> T) { print(2) } func bar() -> Int { 1 } foo(bar)
ようするにこういう事か() -> Int <bind> $T1
と () -> Int <bind> () -> $T2
に差を付けるのはアリなのかなぁ なんか思わぬケースで生じて別の問題が起きそうな気もfunc foo<T>(_ f: T) { print(1) } func foo<T>(_ f: () -> T, opt: Int = 1) { print(2) } func bar() -> Int { 1 } foo(bar)
(edited)func foo<T>(_ f: T) { print(1) } func foo<T>(_ f: () -> T) { print(2) } func bar() -> Int { 1 } foo(bar)
<stdin>:4:1: error: ambiguous use of 'foo' foo(bar) ^ <stdin>:1:6: note: found this candidate func foo<T>(_ f: T) { print(1) } ^ <stdin>:2:6: note: found this candidate func foo<T>(_ f: () -> T) { print(2) } ^
swift-subcommand
っていうルールで名前をつけたものをPATHの通ったところに置いておくと、 $ swift subcommand
という形で呼び出せることを今さら知った。 https://github.com/apple/swift/blob/f34c97069a43aa2295c6a63627c15e224be6d30a/tools/driver/driver.cpp#L83-L122 ^ ここの処理がやってるんだと思う。 (edited)$ss5print_9separator10terminatoryypd_S2StFfA0_ ---> default argument 1 of Swift.print(_: Any..., separator: Swift.String, terminator: Swift.String) -> ()
[omochi@omochi-iMacPro bin]$ clang -o swift-aaa aaa.c [omochi@omochi-iMacPro bin]$ ./swift-aaa [0] ./swift-aaa [omochi@omochi-iMacPro bin]$ swift aaa [0] /Users/omochi/Dropbox/bin/swift-aaa [omochi@omochi-iMacPro bin]$ swift aaa x y z [0] /Users/omochi/Dropbox/bin/swift-aaa [1] x [2] y [3] z [omochi@omochi-iMacPro bin]$ cat aaa.c #include <stdio.h> int main(int argc, char *argv[]) { for (int i = 0; i < argc; i++) { printf("[%d] %s\n", i, argv[i]); } return 0; }
ParameterList
と ParameterListInfo
と ArrayRef<AnyFunctionType::Param>
と TupleType
が微妙に違うものとしてバラバラに使われていて厳しい-verify-apply-fixes
を改良して、 func f(aa: Int, bb: Int) -> String { "f" } f(aax: 0, bb: 1)
を func f(aa: Int, bb: Int) -> String { "f" } f(aax: 0, bb: 1) // unexpected-error {{incorrect argument label in call (have 'aax:', expected 'aa:')}}
に書き換える機能を実装しようと思ったんだけどlet a = """ \(f(aax: 0, bb: 1)) """
↑こういう入力が与えられると let a = """ \(f(aax: 0, bb: 1)) // unexpected-error {{...}} """
↑になってしまって、元コードを壊してしまう(コメントじゃなくて文字列リテラルになってる)let a = "expected-error {{foo}}"
↑これをverify-apply-fixesするとぶっ壊れるしまあいっか・・・?class A: B {} class B: A {}
↑これのRequestダンプしたらクソデカ画像出た $ swift -frontend -typecheck a.swift -build-request-dependency-graph -output-request-graphviz req.graph
$ dot -Tpng
じゃ厳しいな、なんか良いツールあるんだろうかbrew cask install gephi
してみたけど、Javaで書かれてると気づいて起動する事なく削除した。 https://github.com/gephi/gephi#include
されるものを、プロジェクトツリーペインで表示しないという仕様が問題なのかなあ 不便で仕方ない[ FAIL ] StringDeconstructTests.deconstruct cocoa
これで落ちるのなんだろう・・・commit 0c403fe766c7bb9c85bda3a9e64d37a8c02e0909 (HEAD -> master, origin/master, origin/HEAD) Author: Eric Miotto <1094986+edymtt@users.noreply.github.com> Date: Mon May 18 08:14:59 2020 -0700
commit 8aceb038587961345a49ade56f280c27b5bb4a67 Merge: 30b5fd52e8f 97e32abc3c6 Author: Artem Chikin <achikin@apple.com> Date: Wed May 13 06:17:26 2020 -0700 Merge pull request #31716 from artemcm/UnlabeledKeypathFix [Type-checker] Improve diagnostic for keypath used without 'keyPath:' label
StringUTF8Tests.Contiguous Access
でコケました$ utils/update-checkout --scheme master $ utils/build-script --release --validation-test --jobs 32
↑詳しければお好みで良いですがそうじゃなかったらこんな感じが良いと思います (jobsのところはお好み)[omochi@omochi-iMacPro swift (master=)]$ brew list clang-format cmake gettext git ninja pcre2
にしたら直った。brew list
見たい。 (edited)$ brew list|wc -l 122
brew list -1
かな?$ cmake --version cmake version 3.17.2 CMake suite maintained and supported by Kitware (kitware.com/cmake).
$ find /usr/local -name 'cmake*' -type d|awk -F '/' '{print $5}'|sort|uniq cmake harfbuzz leptonica libxml2 msgpack qt sdl2 snappy
build-script ... --clean
/usr/local/lib/cmake
を隠せばいいのか?MacOSX10.15.sdk
をリネームして無理やりビルド通した気がする…-- Found LibEdit: /Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk/usr/include (found version ".")
$ brew list -1
の出力結果を全部 $ brew uninstall
に突っ込むんやcmake/modules/FindLibEdit.cmake
$ pkg-config --cflags libedit -I/Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk/usr/include/editline
/usr/local/Homebrew/Library/Homebrew/os/mac/pkgconfig/10.15/libedit.pc
cmake/modules/FindLibEdit.cmake
をパッチする/usr/local/Homebrew/Library/Homebrew/os/mac/pkgconfig/10.15/libedit.pc
を隠したらビルドできた./utils/run-test --build-dir ../build/Ninja-ReleaseAssert/swift-macosx-x86_64 test/stdlib/StringDeconstruction.swift
Testing Time: 8.12s Expected Passes : 1
Testing Time: 900.47s ******************** Failing Tests (2): Swift(macosx-x86_64) :: Python/update_checkout.swift Swift(macosx-x86_64) :: Python/python_lint.swift Expected Passes : 12961 Expected Failures : 26 Unsupported Tests : 220 Unexpected Failures: 2
The flake8 and flake8-import-order Python packages are required for linting, but these were not found on your system. You can install these using: python -m pip install flake8 python -m pip install flake8-import-order For more help, see http://flake8.pycqa.org.
******************** TEST 'Swift(macosx-x86_64) :: Python/update_checkout.swift' FAILED ******************** Script: -- : 'RUN: at line 8'; /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python /Users/niw/Documents/Projects/apple/swift/utils/update_checkout/run_tests.py -- Exit Code: 1
[ FAIL ] StringDeconstructTests.deconstruct cocoa StringDeconstructTests: Some tests failed, aborting UXPASS: [] FAIL: ["deconstruct cocoa"] SKIP: [] To debug, run: $ /Users/niw/Documents/Projects/apple/build/Ninja-RelWithDebInfoAssert/swift-macosx-x86_64/test-macosx-x86_64/stdlib/Output/StringDeconstruction.swift.tmp/a.out --stdlib-unittest-in-process --stdlib-unittest-filter "deconstruct cocoa" -- Command Output (stderr): -- /Users/niw/Documents/Projects/apple/swift/test/stdlib/StringDeconstruction.swift:22:7: warning: variable 'stackTrace' was never mutated; consider changing to 'let' constant var stackTrace = stackTrace.pushIf(showFrame, file: file, line: line) ~~~ ^ let /Users/niw/Documents/Projects/apple/build/Ninja-RelWithDebInfoAssert/swift-macosx-x86_64/test-macosx-x86_64/stdlib/Output/StringDeconstruction.swift.script: line 1: 71979 Abort trap: 6 /usr/bin/env DYLD_LIBRARY_PATH='/Users/niw/Documents/Projects/apple/build/Ninja-RelWithDebInfoAssert/swift-macosx-x86_64/lib/swift/macosx' LD_LIBRARY_PATH='/Users/niw/Documents/Projects/apple/build/Ninja-RelWithDebInfoAssert/swift-macosx-x86_64/lib/swift/macosx:' SIMCTL_CHILD_DYLD_LIBRARY_PATH='/Users/niw/Documents/Projects/apple/build/Ninja-RelWithDebInfoAssert/swift-macosx-x86_64/lib/swift/macosx' /Users/niw/Documents/Projects/apple/build/Ninja-RelWithDebInfoAssert/swift-macosx-x86_64/test-macosx-x86_64/stdlib/Output/StringDeconstruction.swift.tmp/a.out -- ******************** Testing Time: 4.66s ******************** Failing Tests (1): Swift(macosx-x86_64) :: stdlib/StringDeconstruction.swift Unexpected Failures: 1 ERROR: command terminated with a non-zero exit status 1, aborting
validation-test/stdlib/StringUTF8.swift
の方だFAIL: ["deconstruct cocoa"]
は SR-12835ですね@swift-ci Please smoke test Windows
で再度実行してみてください。IRGen/framepointer_arm64.sil
が壊れてるのは既知IRGen/framepointer_arm64.sil
が Mac OS X でも落ちてて、 機械的にブロックされててマージできない・・・Swift(linux-x86_64) :: Runtime/linux-fatal-backtrace.swift
が落ちてるみたいだなswift
がなくて、なにか間違えてたと勘違いして何度もやりなおしてたんだけど、swift-frontend に変わっているのね。。。。kateiくんとの話ともやっとつながった/swift/utils/build-script --release
でビルドを試みています。 不足していると言われたライブラリを加えながら /swift/utils/build-script --release
を実行しているところですが、どうしても -- armv7 ICU i18n INCLUDE: ICU_I18N_INCLUDE_DIRS-NOTFOUND -- armv7 ICU i18n LIB: ICU_I18N_LIBRARIES-NOTFOUND -- armv7 ICU unicode INCLUDE: ICU_UC_INCLUDE_DIRS-NOTFOUND -- armv7 ICU unicode LIB: ICU_UC_LIBRARIES-NOTFOUND
と言われてしまい CMake Generate step failed.
となってしまいます。sudo apt-get install icu-devtools libicu-dev
で ICU はすでに入っているはずなのですが、何か見落としていると思われる点はありませんでしょうか。pkg-config icu-uc --libs
で見つからなければ.pcがちゃんとした場所に入ってないとかがありそう$ pkg-config icu-uc --libs -licuuc -licudata
/swift/utils/build-script --release
の結果はこのようになっています https://gist.github.com/treastrain/53ca52112bbc17aa90c234590179a819build/Ninja-ReleaseAssert/swift-linux-armv7/CMakeCache.txt
ですbuild/Ninja-ReleaseAssert/swift-linux-armv7/CMakeCache.txt
を削除して /swift/utils/build-script --release
してみます。-- armv7 ICU i18n INCLUDE: -- armv7 ICU i18n LIB: -- armv7 ICU unicode INCLUDE: -- armv7 ICU unicode LIB:
のように見事 -NOTFOUND
と表示されなくなり、実行が始まりました…! https://twitter.com/treastrain/status/1342427924603883521CMAKE_CXX_COMPILER:PATH
が CMAKE_CXX_COMPILER:STRING
になったり… という変化もありました https://twitter.com/treastrain/status/1342433382949552128/swift/utils/build-script --release
を実行してみて、 0. Program arguments: /home/treastrain/Developer/Libraries/swift-source/build/Ninja-ReleaseAssert/swift-linux-armv7/bin/swift-frontend……… 1. Swift version 5.3-dev (LLVM bcee1b98f3b26c5, Swift dbcf7fe1bf76226) 2. Contents of /tmp/sources-c177c7: ………… 3. While evaluating request TypeCheckSourceFileRequest(source_file "/home/treastrain/Developer/Libraries/swift-source/swift/stdlib/public/core/KeyPath.swift") 4. While type-checking 'AnyKeyPath' (at /home/treastrain/Developer/Libraries/swift-source/swift/stdlib/public/core/KeyPath.swift:37:8) 5. While evaluating request SemanticMembersRequest(Swift.(file).AnyKeyPath@/home/treastrain/Developer/Libraries/swift-source/swift/stdlib/public/core/KeyPath.swift:37:14) 6. While type-checking protocol conformance to 'Hashable' (at /home/treastrain/Developer/Libraries/swift-source/swift/stdlib/public/core/Hashable.swift:104:8) for type 'AnyKeyPath' (declared at [/home/treastrain/Developer/Libraries/swift-source/swift/stdlib/public/core/KeyPath.swift:37:8 - line:193:1] RangeText="class AnyKeyPath: Hashable, _AppendKeyPath { ………… 7. While evaluating request AbstractGenericSignatureRequest(NULL, {τ_0_0}, {τ_0_0 : AnyKeyPath, τ_0_0 : Hashable}) <unknown>:0: error: unable to execute command: Aborted <unknown>:0: error: compile command failed due to signal 6 (use -v to see invocation)
となってしまいました。 https://gist.github.com/treastrain/fa9b507b3a66ed578108b8a6c5330a0d (edited)swift::Type
と swift::LayoutConstraint
の NumLowBitsAvailable
が実態にそぐわない値になっているっぽい動きなんですけど、それ以上はよくわからない‥swift package init --type executable
で Swift と C++ の混合プロジェクトを作成し、C++ 側のコードから OpenCV を使用しようとしているのですが、「OpenCV 側のクラスが未定義」というエラーが返ってきてしまいビルドすることができずに困っています。 C++ 単体での OpenCV の利用の場合、 $ clang++ main.cpp -I/usr/local/include/opencv4 -lopencv_core
でビルド・実行できるため、 $ swift run -Xcxx=-I/usr/local/include/opencv4 -Xcxx=-lopencv_core
としてみたのですが、どうにもビルドできずに困っています。 オプションの指定の仕方が間違っていたり、何か別な方法があったりするでしょうか。 (edited)-l
みたいなリンカオプションは-Xlinkerで渡さないと行けない気がします (edited)$ swift run -Xcxx=-I/usr/local/include/opencv4 -Xlinker=opencv_core
のような感じでしょうかopencv_core
が無いというエラーが返ってきてしまいました。C++ のみの場合で $ clang++ main.cpp -I/usr/local/include/opencv4 -lopencv_core
は成功するのですが、この -l
と swift build
の -Xlinker
では何か違いはありますか。 $ swift run -Xcxx=-I/usr/local/include/opencv4 -Xlinker=opencv_core /usr/bin/ld.gold: エラー: opencv_core を開けません: そのようなファイルやディレクトリはありません Sources/CXXWrapper/sources/cxx_lib.cpp:16: error: undefined reference to 'cv::Mat::Mat()' Sources/CXXWrapper/sources/cxx_lib.cpp:17: error: undefined reference to 'cv::Mat::~Mat()' clang-10: error: linker command failed with exit code 1 (use -v to see invocation) error: link command failed with exit code 1 (use -v to see invocation) [3/4] Linking OpenCVSwiftCXX
(edited)$ swift run -Xcxx=-I/usr/local/include/opencv4 -Xlinker=opencv_core
のような感じでしょうか -Xlinker=-lopencv_core
ですね$ swift run -Xcxx=-I/usr/local/include/opencv4 -Xlinker=-lopencv_core /usr/bin/ld.gold: エラー: -lopencv_core が見つかりません Sources/CXXWrapper/sources/cxx_lib.cpp:16: error: undefined reference to 'cv::Mat::Mat()' Sources/CXXWrapper/sources/cxx_lib.cpp:17: error: undefined reference to 'cv::Mat::~Mat()' clang-10: error: linker command failed with exit code 1 (use -v to see invocation) error: link command failed with exit code 1 (use -v to see invocation) [5/6] Linking OpenCVSwiftCXX
libopencv_core.so
が /usr/local/lib
にインストールされてると思うので、 -Xlinker=-L/usr/local/lib
も付けないとだめかな?$ swift build -Xcxx=-I/usr/local/include/opencv4 -Xlinker=-L/usr/local/lib -Xlinker=-lopencv_core -Xlinker=-lopencv_imgproc -Xlinker=-lopencv_imgcodecs …省略
.systemLibrary(...)
をPackage.swiftに記述すれば swift build
のオプション群は必要なくなると思います https://github.com/apple/swift-package-manager/blob/main/Documentation/PackageDescription.md#methods-5print(f("a")) let dict: [String: String] = [:] func f(_ s: String) -> String { dict[s] ?? s } // print(f("a")) // ここだとOK
<stdin>:1:7: error: use of unresolved identifier 'f' print(f("a")) ^
Stack dump: 0. Program arguments: /usr/bin/swift -frontend -interpret - -disable-objc-interop -I /Libraries/.build/x86_64-unknown-linux-gnu/debug -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include -I /Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOSHA1/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOHTTPParser/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOAtomics/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOWindows/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIODarwin/include -I /Libraries/.build/checkouts/swift-nio/Sources/CNIOLinux/include -module-cache-path /Libraries/.build/x86_64-unknown-linux-gnu/debug/ModuleCache -D DEBUG -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/CSwiftBacktrace/include/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/checkouts/SwiftBacktrace/Sources/Clibunwind/include/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOSHA1.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOHTTPParser.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOAtomics.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/checkouts/swift-nio/Sources/CNIOWindows/include/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIODarwin.build/module.modulemap -Xcc -fmodule-map-file=/Libraries/.build/x86_64-unknown-linux-gnu/debug/CNIOLinux.build/module.modulemap -module-name main -lLibraries 1. Swift version 5.2.5 (swift-5.2.5-RELEASE) 2. While running user code "<stdin>" /usr/bin/swift[0x50d8054] /usr/bin/swift[0x50d5b00] /usr/bin/swift[0x50d8320] /lib/x86_64-linux-gnu/libpthread.so.0(+0x11390)[0x7f6a4d396390] /usr/lib/swift/linux/libswiftCore.so($sSD8_Variant
error: Multiple commands produce '/Users/omochi/work/swift-source/build/Xcode-ReleaseAssert+swift-DebugAssert/llvm-macosx-x86_64/include/llvm/Support': 1) CreateBuildDirectory /Users/omochi/work/swift-source/build/Xcode-ReleaseAssert+swift-DebugAssert/llvm-macosx-x86_64/include/llvm/Support 2) That command depends on command in Target 'llvm_vcsrevision_h' (project 'LLVM'): script phase “Generate include/llvm/Support” warning: duplicate output file '/Users/omochi/work/swift-source/build/Xcode-ReleaseAssert+swift-DebugAssert/llvm-macosx-x86_64/include/llvm/Support' on task: PhaseScriptExecution Generate include/llvm/Support /Users/omochi/work/swift-source/build/Xcode-ReleaseAssert+swift-DebugAssert/llvm-macosx-x86_64/include/llvm/Support/LLVM.build/Release/llvm_vcsrevision_h.build/Script-7FD889A2C0CC1336ED00F240.sh (in target 'llvm_vcsrevision_h' from project 'LLVM') ** BUILD FAILED **
Build Preparation Build task concurrency set to 30 via user default IDEBuildOperationMaxNumberOfConcurrentCompileTasks note: Using new build system note: Building targets in parallel note: Planning build note: Analyzing workspace note: Constructing build description note: Build preparation complete error: Multiple commands produce '/Users/omochi/work/swift-source/build/Xcode-ReleaseAssert+swift-DebugAssert/llvm-macosx-x86_64/include/llvm/Support': 1) CreateBuildDirectory /Users/omochi/work/swift-source/build/Xcode-ReleaseAssert+swift-DebugAssert/llvm-macosx-x86_64/include/llvm/Support 2) That command depends on command in Target 'llvm_vcsrevision_h' (project 'LLVM'): script phase “Generate include/llvm/Support”
--xcode
だと駄目なのかなswift-5.4.2-RELEASE
だめ swift-5.4.1-RELEASE
だめswift-5.4-RELEASE
だめ あれえ〜error: using unsupported Xcode version: Xcode 12.5 Build version 12E262 Install one of: 12.2 beta 3 (12B5035g) 12.2 Release Candidate (12B5044c) 12.2 (12B45b) 12.3 (12C33) 12.4 (12D4e) 12.5 beta 3 (12E5244e)
note: Using new build system note: Building targets in parallel note: Planning build note: Constructing build description Build system information error: Multiple commands produce '/Users/omochi/work/swift-source/build/Xcode-ReleaseAssert+swift-DebugAssert/swift-macosx-x86_64/Debug/lib/libBlocksRuntime.dylib': 1) Target 'BlocksRuntimeStub-macosx-arm64' has link command with output '/Users/omochi/work/swift-source/build/Xcode-ReleaseAssert+swift-DebugAssert/swift-macosx-x86_64/Debug/lib/libBlocksRuntime.dylib' 2) Target 'BlocksRuntimeStub-macosx-arm64e' has link command with output '/Users/omochi/work/swift-source/build/Xcode-ReleaseAssert+swift-DebugAssert/swift-macosx-x86_64/Debug/lib/libBlocksRuntime.dylib' 3) Target 'BlocksRuntimeStub-macosx-x86_64' has link command with output '/Users/omochi/work/swift-source/build/Xcode-ReleaseAssert+swift-DebugAssert/swift-macosx-x86_64/Debug/lib/libBlocksRuntime.dylib'
--build-stdlib-deployment-targets BUILD_STDLIB_DEPLOYMENT_TARGETS A space-separated list that filters which of the configured targets to build the Swift standard library for, or "all". --swift-darwin-supported-archs ARCHS Semicolon-separated list of architectures to configure on Darwin platforms. If left empty all default architectures are configured. --swift-darwin-module-archs ARCHS Semicolon-separated list of architectures to configure Swift module-only targets on Darwin platforms. These targets are in addition to the full library targets.
--swift-darwin-supported-archs=x86_64
macos-
なくていいのかswift/utils/build-script --xcode --release --debug-swift --swift-darwin-supported-archs x86_64 --jobs 30 --clean
5.4
だと調べたい内容がマージされてねえ。--debug-swift
だと Generate\ stdlib/public/core/OSX/x86_64/Swift.o
の遅さヤバいなあSKIP_XCODE_VERSION_CHECK
してたのがよくなくて./SwiftCompilerSources
のモジュール達--- Build Script Analyzer --- Build Script Log: /home/katei/ghq/work.katei.dev/swiftwasm-source/host-build/.build_script_log Build Percentage Build Duration (sec) Build Phase ================ ==================== =========== 50.9% 1838.55 linux-x86_64-llvm-build 29.9% 1079.17 linux-x86_64-swift-build 4.6% 166.47 Building swiftpm 3.3% 117.58 Building sourcekitlsp 2.1% 76.49 Installing swiftpm 2.0% 72.1 Building earlyswiftdriver
[Freestanding]
で task-to-thread model 向けの修正というのがされていてpublic static func runInline(_ body: () async throws -> Success) rethrows -> Success
(edited)Via Xcode: utils/build-script --skip-build-benchmarks \ --skip-ios --skip-watchos --skip-tvos --swift-darwin-supported-archs "$(uname -m)" \ --sccache --release-debuginfo --swift-disable-dead-stripping \ --xcode
func takeAny(_ v: Any) { print(v is Sendable) } class Box {} takeAny(1) takeAny(Box())
func takeAny(_ v: Any) { print(v is Sendable) } class Box {} takeAny(1) takeAny(Box())
<stdin>:2:11: warning: 'is' test is always true print(v is Sendable) ^ <stdin>:2:11: error: marker protocol 'Sendable' cannot be used in a conditional cast print(v is Sendable) ^
protocol P { } struct S<T> {} extension S: P where T: Sendable {} func main(a: Any) { ... }
func takeAny(_ v: Any) { print(v is Sendable) } class Box {} takeAny(1) takeAny(Box())
<stdin>:2:11: warning: 'is' test is always true <stdin>:2:11: error: marker protocol 'Sendable' cannot be used in a conditional cast
↑2行で矛盾してて凄いなprotocol P { } struct S<T> {} extension S: P where T: Sendable {} func main(_ a: Any) { if let p = a as? any P { print(1) } else { print(2) } } main((1, 2))
protocol P { } struct S<T> {} extension S: P where T: Sendable {} func main(_ a: Any) { if let p = a as? any P { print(1) } else { print(2) } } main((1, 2))
<stdin>:3:1: error: conditional conformance to non-marker protocol 'P' cannot depend on conformance of 'T' to non-marker protocol 'Sendable' extension S: P where T: Sendable {} ^ <stdin>:5:10: warning: value 'p' was defined but never used; consider replacing with boolean test if let p = a as? any P { ~~~~^~~~ ~~~ is
extension S: Sendable where T: Sendable
なら実行時に見えるコンフォーマンス作らないからOKというわけかstruct S<T> {} extension S: Sendable where T: Sendable {}
struct S<T> {} extension S: Sendable where T: Sendable {}
conditional conformance to non-marker protocol 'P' cannot depend on conformance of 'T' to non-marker protocol 'Sendable'
marker protocol 'Sendable'
じゃないのか?swift_conformsToProtocol
を使って取得するようにするとかかなぁdlsym
とかを直接使う場合もあるから。dlsym
を使う場合はどうなるんだっけdlopen
したときに動的リンカが動作してGOTを更新してくれて、 dlsym
は GOTのエントリを返り値として返すのかなと想像したputs
を 自力で dlopen するようなコードを書いていた場合、 自力のdlopenと、コンパイラが生成したPLT経由のputsの呼び出しの2つの初期化経路が存在していて.dynamic
セクションにシンボル名とGOTオフセットの対応情報が入ってるらしいstruct dso
にマップしていくのか じゃあ普通に動的ライブラリのバイナリレイアウトを読んでるだけなのか /* Search for the name to see if it's already loaded */ for (p=head->next; p; p=p->next) { if (p->shortname && !strcmp(p->shortname, name)) { return p; } }
static struct dso ldso; static struct dso *head, *tail, *fini_head, *syms_tail, *lazy_head; static char *env_path, *sys_path;
head
とか tail
でリストにしてあって、そこから探すだけ・・・Swift.Int
とかのメタデータと何が違うんだ? (edited)Swift.Int
の Equatable
に対するconformanceは stdlib には含まれてない?#if defined(__arm__) " .section __DATA, __nl_symbol_ptr, non_lazy_symbol_pointers\n" #elif defined(__i386__) " .section __IMPORT, __pointers, non_lazy_symbol_pointers\n" #endif
(edited) " .globl " TUPLE_HASHABLE_CONF "\n" " .p2align 2\n" TUPLE_HASHABLE_CONF ":\n" // This is an indirectable relative reference to the GOT entry for the // Hashable protocol descriptor. " .long " INDIRECT_RELREF_GOTPCREL(HASHABLE_DESCRIPTOR_SYMBOL) "\n" // 769 is the MetadataKind::Tuple " .long 769\n" // This indicates that we have no witness table pattern. We use a generic // witness table for builtin conformances. " .long 0\n"
(edited)// 64 bit arm MachO #if defined(__aarch64__) #define INDIRECT_RELREF_GOTPCREL(SYMBOL) SYMBOL "@GOT - . + 1"
(edited)struct ProtocolConformance { int f0; }; void *TupleEquatable_witness_method(void); static struct ProtocolConformance TupleEquatable = { .f0 = (void *)&TupleEquatable - (void *)TupleEquatable_witness_method, };
foo.c:8:9: error: initializer element is not a compile-time constant .f0 = (void *)&TupleEquatable - (void *)TupleEquatable_witness_method, ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1 error generated.
__attribute__ ((section ("__TEXT, __const")))
みたいなのを付けてもコンパイラはcompile-time constantとみなしてくれない Part 1: Nuts and Bolts
しか書かれてなかった。 (edited)swift_getTypeByMangledNameInContext
でmetatypeをロードして処理してる。TypeDecl::getDeclaredInterfaceType()
→ TypeDecl::getInterfaceType() -> getMetatypeInstanceType()
→ InterfaceTypeRequest::evaluate()
→ MetatypeType::get(NominalTypeDecl::getDeclaredInterfaceType())
(edited)lib/AST
は全然 virtual
見かけないし、基本的に仮想関数呼び出しは使ってないっぽいなTypeBase::getContextSubstitutionMap
これか? あー式のtypeから一意に復元できるんかな。GenericParamList
が outerParameters をチェーンできるようになっていて、 ネストしたジェネリック型のextensionのみにおいて利用するらしいんだけど、 なんでそんなものが必要になるのかがいまいち読んでてもわからないinout
するといろいろおかしくなる (Swift 5.8 だとランライムでクラッシュ、Swift 5.9 だと assertion crash) Swift 5.7 は大丈夫だったっぽい // function_ref closure #2 in f() %16 = function_ref @$s1a1fyyFyyyczXEfU0_ : $@convention(thin) @substituted <τ_0_0> (@inout τ_0_0, @guaranteed String) -> () for <() -> ()> // user: %18 retain_value %14 : $String // id: %17 %18 = partial_apply [callee_guaranteed] [on_stack] %16(%14) : $@convention(thin) @substituted <τ_0_0> (@inout τ_0_0, @guaranteed String) -> () for <() -> ()> // users: %22, %19 %19 = mark_dependence %18 : $@noescape @callee_guaranteed @substituted <τ_0_0> (@inout τ_0_0) -> () for <() -> ()> on %14 : $String // user: %21 %20 = class_method %6 : $Box<() -> ()>, #Box.mutate : <T> (Box<T>) -> ((inout T) -> ()) -> (), $@convention(method) <τ_0_0> (@noescape @callee_guaranteed @substituted <τ_0_0> (@inout τ_0_0) -> () for <τ_0_0>, @guaranteed Box<τ_0_0>) -> () // user: %21 %21 = apply %20<() -> ()>(%19, %6) : $@convention(method) <τ_0_0> (@noescape @callee_guaranteed @substituted <τ_0_0> (@inout τ_0_0) -> () for <τ_0_0>, @guaranteed Box<τ_0_0>) -> () dealloc_stack %18 : $@noescape @callee_guaranteed @substituted <τ_0_0> (@inout τ_0_0) -> () for <() -> ()> // id: %22 release_value %14 : $String // id: %23 release_value %14 : $String // id: %24 strong_release %6 : $Box<() -> ()> // id: %25
#if SWIFT_SWIFT_PARSER
のフラグでSwiftParser+ASTGenを使い分けてるけど、Macroのテストでは REQUIRES: swift_swift_parser
で常に使ってるように見えるので。C++のParser.cpp等は念のためか特定の用途のために残してるのかな。 (edited)REQUIRES: swift_swift_parser
は SwiftParser が有効になっている時にだけ実行されるテストで、フラグがある通り全てのビルドで有効になっているわけではありません。具体的には Linux, Windows など Darwin 以外では様々な理由で有効にできていません。 (edited)copy_value
のオペランドが参照型の時 strong_retain
と strong_release
が生えて、その後最適化で冗長なやつは消える (edited)-emit-pure-sil
という読みやすさ重視の SIL を出力する新たなフラグを追加しようとしているみたいですね. https://github.com/swiftlang/swift/pull/77714--- Build Script Analyzer --- Build Script Log: /Users/omochi/swift/build/.build_script_log Build Percentage Build Duration (sec) Build Phase ================ ==================== =========== 55.4% 1185.66 Building llvm 40.9% 875.38 macosx-arm64-swift-build 3.4% 73.01 Building earlyswiftdriver 0.4% 7.76 Building cmark 0.0% 0.06 macosx-arm64-swift-test 0.0% 0.05 macosx-arm64-swift-install 0.0% 0.04 merged-hosts-lipo-core 0.0% 0.04 macosx-arm64-extractsymbols 0.0% 0.04 macosx-arm64-package 0.0% 0.04 merged-hosts-lipo Total Duration: 2142.08 seconds (35m 42s)
Failed Tests (3): Swift-validation(macosx-arm64) :: Sema/SwiftUI/rdar57201781.swift Swift-validation(macosx-arm64) :: Sema/SwiftUI/rdar70880670.swift Swift-validation(macosx-arm64) :: Sema/SwiftUI/rdar72771072.swift Testing Time: 223.11s Total Discovered Tests: 251 Unsupported: 8 (3.19%) Passed : 240 (95.62%) Failed : 3 (1.20%)
// RUN: %target-typecheck-verify-swift -target %target-cpu-apple-macosx10.15 -swift-version 5 // REQUIRES: objc_interop // REQUIRES: OS=macosx import SwiftUI var foo = doesntExist // expected-error {{cannot find 'doesntExist' in scope}} struct ContentView: View { var body: some View { VStack { Text(verbatim: foo) } } }
Assertion failed: (!Name || (Name.getArgumentNames().size() == BodyParams->size())), function setParameters, file Decl.cpp, line 9961.
Failed Tests (1): Swift(windows-x86_64) :: ModuleInterface/swift_build_sdk_interfaces/find-modules.test-sh
Failed Tests (1): lldb-api :: functionalities/stats_api/TestStatisticsAPI.py
なんだこりゃ (edited)+ /tmp/jenkins-139bce29/workspace/swift-PR-Linux-smoke-test/branch-main/swift/utils/update-checkout --clone --clean --reset-to-remote --scheme main --skip-repository swift --github-comment '@swift-ci please smoke test'
< llvm-project : f1aa8683e3bc543edecaf99e4fcb45035072d598 --- > llvm-project : a2bfdac7a4695b08ddab1a73d6649f74ac68dbcb 11c11 < swift : 171269781fa901aa497077488b29c91cdfb6fc03 --- > swift : 8bedf538e8a458fbcac09cc265c3ea51cf319dcb 19c19 < swift-corelibs-foundation : 4c3228c00a17aca68d1a83d35dbd156a8aa169ee --- > swift-corelibs-foundation : 238130a6224340ca373b2a6c8fe1abd49c470935
f1aa8683e3bc543edecaf99e4fcb45035072d598
が git上に存在しないコミットだ・・・lldb version 17.0.0 (https://github.com/swiftlang/llvm-project.git revision f1aa8683e3bc543edecaf99e4fcb45035072d598) Swift version 6.2-dev (LLVM f1aa8683e3bc543, Swift 171269781fa901a)
+ env AWS_DEFAULT_REGION=us-west-2 'BUILD_DISPLAY_NAME=#16570' BUILD_ID=16570 BUILD_NUMBER=16570 BUILD_TAG=jenkins-swift-PR-Linux-smoke-test-16570 'BUILD_TIMESTAMP=2024-12-17 11:57:37 UTC' BUILD_URL=https://ci.swift.org/job/swift-PR-Linux-smoke-test/16570/ CI=true EXECUTOR_NUMBER=0 GIT_BRANCH=rename-pointer-bounds GIT_TERMINAL_PROMPT=0 HOME=/root HUDSON_COOKIE=0dc6b276-f15d-45be-8821-4e189bbbbf37 HUDSON_HOME=/var/lib/jenkins HUDSON_SERVER_COOKIE=65153606917a1e90 HUDSON_URL=https://ci.swift.org/ JENKINS_HOME=/var/lib/jenkins JENKINS_NODE_COOKIE=ee76ab5f-09c6-42e6-9512-4b8d185de759 JENKINS_SERVER_COOKIE=durable-1a733d488801f78433f1ac5afdde4a0e4e2248a13418d8d14af9a6f455f5f093 JENKINS_URL=https://ci.swift.org/ JOB_BASE_NAME=swift-PR-Linux-smoke-test JOB_DISPLAY_URL=https://ci.swift.org/job/swift-PR-Linux-smoke-test/display/redirect JOB_NAME=swift-PR-Linux-smoke-test JOB_URL=https://ci.swift.org/job/swift-PR-Linux-smoke-test/ LANG=en_US.UTF-8 'LESSOPEN=||/usr/bin/lesspipe.sh %s' LOGNAME=root MAIL=/var/mail/root 'NODE_LABELS=i-0eeac12dd81f5143d linux-x86_64' NODE_NAME=i-0eeac12dd81f5143d PATH=/root/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin PWD=/tmp/jenkins-139bce29/workspace/swift-PR-Linux-smoke-test 'RUN_ARTIFACTS_DISPLAY_URL=https://ci.swift.org/job/swift-PR-Linux-smoke-test/16570/display/redirect?page=artifacts' 'RUN_CHANGES_DISPLAY_URL=https://ci.swift.org/job/swift-PR-Linux-smoke-test/16570/display/redirect?page=changes' RUN_DISPLAY_URL=https://ci.swift.org/job/swift-PR-Linux-smoke-test/16570/display/redirect 'RUN_TESTS_DISPLAY_URL=https://ci.swift.org/job/swift-PR-Linux-smoke-test/16570/display/redirect?page=tests' SHELL=/bin/bash SHLVL=3 'SSH_CLIENT=172.31.242.3 52376 22' 'SSH_CONNECTION=172.31.242.3 52376 172.31.246.239 22' STAGE_NAME=Checkout USER=root WORKSPACE=/tmp/jenkins-139bce29/workspace/swift-PR-Linux-smoke-test/branch-main WORKSPACE_TMP=/tmp/jenkins-139bce29/workspace/swift-PR-Linux-smoke-test@tmp XDG_RUNTIME_DIR=/run/user/0 XDG_SESSION_ID=2 _=/tmp/jenkins-139bce29/workspace/swift-PR-Linux-smoke-test/branch-main/swift/utils/update-checkout ghprbActualCommit=fa5fbfa1bfb64c94f5f82325dd82ddb09580cd68 ghprbAuthorRepoGitUrl=https://github.com/hnrklssn/swift.git 'ghprbCommentBody=@swift-ci please smoke test' ghprbCredentialsId=token-github ghprbGhRepository=swiftlang/swift ghprbPullAuthorEmail=hnrklssn@gmail.com ghprbPullAuthorLogin=hnrklssn ghprbPullAuthorLoginMention=@hnrklssn 'ghprbPullDescription=GitHub pull request #78210 of commit fa5fbfa1bfb64c94f5f82325dd82ddb09580cd68, no merge conflicts.' ghprbPullId=78210 ghprbPullLink=https://github.com/swiftlang/swift/pull/78210 'ghprbPullLongDescription=Renames the `@PointerBounds` macro to `@_SwiftifyImport` and makes it generally available in the standard library. The API is expected to change drastically without accompanying release notes or backwards compatibility, as the macro is intended to be applied by ClangImporter only, which will be updated in tandem with the macro.' 'ghprbPullTitle=Rename pointer bounds' ghprbSourceBranch=rename-pointer-bounds ghprbTargetBranch=main 'ghprbTriggerAuthor=Henrik G. Olsson' ghprbTriggerAuthorEmail=hnrklssn@gmail.com ghprbTriggerAuthorLogin=hnrklssn ghprbTriggerAuthorLoginMention=@hnrklssn http_proxy=http://proxy.config.pcp.local:3128 https_proxy=http://proxy.config.pcp.local:3128 library.swift-ci.version=1.0 no_proxy=169.254.169.254 sha1=origin/pr/78210/merge git clone --recursive https://github.com/swiftlang/llvm-project.git llvm-project
jni.h
が共通だからABIなんじゃないか?c++ static bool isSpecifierImmutableInFunctionBody(Specifier sp) { switch (sp) { case Specifier::Default: case Specifier::Borrowing: case Specifier::LegacyShared: case Specifier::LegacyOwned: return true; case Specifier::Consuming: case Specifier::InOut: case Specifier::ImplicitlyCopyableConsuming: return false; } llvm_unreachable("unhandled specifier"); }
c++ /// Does a var or subscript produce an l-value? /// /// \param baseType - the type of the base on which this object /// is being accessed; must be null if and only if this is not /// a type member static bool doesStorageProduceLValue( ... if (!baseType) { return true; }
(edited)var
が LValue を提供できるかどうかを調べてそうですね&
も付けられないので、やっぱり (たとえローレベルで間接アクセスできるとしても)Swiftの型システムレベルでLValue に評価されてるのがおかしい気がするfunc foo(a: consuming Int) { take(&a) } func take(_ x: inout Int) {}
func foo(a: Int) { // ERROR: Cannot pass immutable value as inout argument: 'a' is a 'let' constant take(&a) } func take(_ x: inout Int) {}
if (auto sending = dyn_cast<SendingTypeRepr>(nestedRepr)) { auto *base = sending->getBase(); if (!param->getInterfaceType()->isNoEscape() && !isa<OwnershipTypeRepr>(base)) { return ParamSpecifier::ImplicitlyCopyableConsuming; } }
で、なぜsendingにこういう処理にしてるのかを次に調べる必要があるかなと思いました。// `inout` and `consuming` parameters are locally mutable.
なのですね。 https://github.com/swiftlang/swift/blob/4937d0a24291857470e23bb2dc685c823e9a4ecc/lib/AST/Decl.cpp#L8118func foo(a: Int) { // ERROR: Cannot pass immutable value as inout argument: 'a' is a 'let' constant take(&a) } func take(_ x: inout Int) {}
if (auto sending = dyn_cast<SendingTypeRepr>(nestedRepr)) { auto *base = sending->getBase(); if (!param->getInterfaceType()->isNoEscape() && !isa<OwnershipTypeRepr>(base)) { return ParamSpecifier::ImplicitlyCopyableConsuming; } }
で、なぜsendingにこういう処理にしてるのかを次に調べる必要があるかなと思いました。 ImplicitlyCopyableConsuming
はかつてTransferring
と呼ばれており、sending用のcaseみたいですね... consumingは暗黙的にno implicit copyableで、implicit copyableなconsuming ということをsending用に表したもののようです。 I cannot use consuming for this purpose since consuming today implies no implicit copy semantics, which we do not want unless the user specifically asks for it by writing consuming.
https://github.com/swiftlang/swift/pull/71567/commits/1f0527d47f347a9737f37592f99e15832b034f8a isNoEscapeに関しては 1. We don't support no escaping closure parameters today and would like to leave the design space open.
という理由からでした。 https://github.com/swiftlang/swift/commit/4d7af7be25d99f453a732c4ed732edf64bdf137a (edited)A transferring parameter is a consuming like param modifier that can be used to transfer values to an async function such that you can transfer the value further.
https://github.com/swiftlang/swift/pull/70836 ただ、 I preserve the consuming behavior by making it so that the type checker changes the ParamSpecifier to ImplicitlyCopyableConsuming if we have a default param specifier and transferring is set.
https://github.com/swiftlang/swift/pull/71567 ともあるのでconsumingだと言われればそうなのかもしれませんが...w func send( operation: consuming @escaping () async -> Void ) async { await withoutActuallyEscaping(operation) { (_) in } }
func send( operation: consuming @escaping () async -> Void ) async { let x = operation await withoutActuallyEscaping(x) { (_) in } }
↑これはコンパイルできるのにfunc send( operation: consuming @escaping () async -> Void ) async { var x = operation await withoutActuallyEscaping(x) { (_) in } }
↑これはクラッシュしますvar x
は、内部で lvalue として扱われるはずなので、var x
を lvalue 扱いするのが間違いってことはないはずなんで。RValue RValueEmitter::visitMakeTemporarilyEscapableExpr( MakeTemporarilyEscapableExpr *E, SGFContext C) { // Emit the non-escaping function value. auto functionValue = visit(E->getNonescapingClosureValue()).getAsSingleValue(SGF, E);
なので、RValueを期待しているのかなあと。
RValue RValueEmitter::visitMakeTemporarilyEscapableExpr( MakeTemporarilyEscapableExpr *E, SGFContext C) { // Emit the non-escaping function value. auto functionValue = visit(E->getNonescapingClosureValue()).getAsSingleValue(SGF, E);
なので、RValueを期待しているのかなあと。
RValue RValueEmitter::visitMakeTemporarilyEscapableExpr( MakeTemporarilyEscapableExpr *E, SGFContext C) { // Emit the non-escaping function value. auto functionValue = visit(E->getNonescapingClosureValue()).getAsSingleValue(SGF, E);
なので、RValueを期待しているのかなあと。
var x
を通常の関数引数に渡す場合がどうなってるか は気になりますねwithoutActuallyEscaping
だけ問題が起きているのかがわかると思いました。今日の夜調べてみます。 coerceToRValueしている箇所はたくさんあるので、どういうときにそれを行っているのかも見てみます。 ありがとうございます。
coerceCallArguments
の中でRValueにしているようでした。 https://github.com/swiftlang/swift/blob/e22c09c05546bc638169da0dfc8c8996f160f168/lib/Sema/CSApply.cpp#L8399
(argument (declref_expr type="@lvalue Int" location=79078.swift:19:6
が (argument (load_expr implicit type="Int" location=79078.swift:19:6
に変わります。クロージャ(例えば、var a = {}
)も同じでした。 2. coerceToRValue
はっきりとこの場合だというのはわからなかったのですが、参照を実態化するために使われているようです。Exprを新しく生成(Rewrite)するときに必要なのかなあ?と思いました 3. withoutActuallyEscaping
The body closure receives a copy of the argument closure that is temporarily made @escaping.
とコピーが渡されていることを想定していることからも、RValueが期待されているのかなと思いました。 https://github.com/swiftlang/swift/blob/3787044e8349bf4933ae43f16cbbb44344785e04/lib/Sema/TypeOfReference.cpp#L2245 そうすると、LValueをRValueに変換し忘れていたということかと思うのですが、一個気になるのが、sending
とconsuming
は比較的新しいものの、 inout
でもクラッシュするのは、なんで今まで誰も気づかなかったのかという点ですね...w (あるいはユースケースがないから放置されていたのか...) func send( operation: inout () async -> Void ) async { _ = await withoutActuallyEscaping(operation) { escapingClosure in await escapingClosure() } }
coerceCallArguments
の中でRValueにしているようでした。 https://github.com/swiftlang/swift/blob/e22c09c05546bc638169da0dfc8c8996f160f168/lib/Sema/CSApply.cpp#L8399
(argument (declref_expr type="@lvalue Int" location=79078.swift:19:6
が (argument (load_expr implicit type="Int" location=79078.swift:19:6
に変わります。クロージャ(例えば、var a = {}
)も同じでした。 2. coerceToRValue
はっきりとこの場合だというのはわからなかったのですが、参照を実態化するために使われているようです。Exprを新しく生成(Rewrite)するときに必要なのかなあ?と思いました 3. withoutActuallyEscaping
The body closure receives a copy of the argument closure that is temporarily made @escaping.
とコピーが渡されていることを想定していることからも、RValueが期待されているのかなと思いました。 https://github.com/swiftlang/swift/blob/3787044e8349bf4933ae43f16cbbb44344785e04/lib/Sema/TypeOfReference.cpp#L2245 そうすると、LValueをRValueに変換し忘れていたということかと思うのですが、一個気になるのが、sending
とconsuming
は比較的新しいものの、 inout
でもクラッシュするのは、なんで今まで誰も気づかなかったのかという点ですね...w (あるいはユースケースがないから放置されていたのか...) func send( operation: inout () async -> Void ) async { _ = await withoutActuallyEscaping(operation) { escapingClosure in await escapingClosure() } }
coerceCallArguments
の中でRValueにしているようでした。 https://github.com/swiftlang/swift/blob/e22c09c05546bc638169da0dfc8c8996f160f168/lib/Sema/CSApply.cpp#L8399
(argument (declref_expr type="@lvalue Int" location=79078.swift:19:6
が (argument (load_expr implicit type="Int" location=79078.swift:19:6
に変わります。クロージャ(例えば、var a = {}
)も同じでした。 2. coerceToRValue
はっきりとこの場合だというのはわからなかったのですが、参照を実態化するために使われているようです。Exprを新しく生成(Rewrite)するときに必要なのかなあ?と思いました 3. withoutActuallyEscaping
The body closure receives a copy of the argument closure that is temporarily made @escaping.
とコピーが渡されていることを想定していることからも、RValueが期待されているのかなと思いました。 https://github.com/swiftlang/swift/blob/3787044e8349bf4933ae43f16cbbb44344785e04/lib/Sema/TypeOfReference.cpp#L2245 そうすると、LValueをRValueに変換し忘れていたということかと思うのですが、一個気になるのが、sending
とconsuming
は比較的新しいものの、 inout
でもクラッシュするのは、なんで今まで誰も気づかなかったのかという点ですね...w (あるいはユースケースがないから放置されていたのか...) func send( operation: inout () async -> Void ) async { _ = await withoutActuallyEscaping(operation) { escapingClosure in await escapingClosure() } }
func test(f: inout () -> Void) { withoutActuallyEscaping(f) { $0() } }
に対して SIL verification failed: cannot call an async function from a non async function:
というcrashが発生したのでなんだろうと思ったら、 withoutActuallyEscaping(f)
がなぜかasyncになるようです。 (call_expr type="<null>" isolation_crossing="none" (declref_expr type="(@escaping () -> Void, (@escaping () -> Void) async -> Void) async -> Void" location=79078.swift:37:5 range=[79078.swift:37:5 - line:37:5] decl="Swift.(file).withoutActuallyEscaping(_:do:)" function_ref=single apply)
新しい謎が出てきましたw 次の課題ですね。 (edited)public func withoutActuallyEscaping<ClosureType, ResultType, Failure>(_ closure: ClosureType, do body: (_ escapingClosure: ClosureType) throws(Failure) -> ResultType) throws(Failure) -> ResultType where Failure : Error
(edited)func send( f: sending @escaping () async -> Void ) async { await withoutActuallyEscaping(f) { await $0() } }
auto refType = FunctionType::get(arg, result, FunctionType::ExtInfoBuilder() .withNoEscape(true) .withAsync(true) // 👈🏻 .withThrows(true, thrownError) .build());
https://github.com/swiftlang/swift/blob/main/lib/Sema/TypeOfReference.cpp#L2278 その後スコアを加算して、最終的にasyncが選ばれています https://github.com/swiftlang/swift/blob/main/lib/Sema/CSSimplify.cpp#L1919
---Solution--- Fixed score: [sync-in-asynchronous(s), weight: 17, impact: 1] Type variables: $T0 as Void @ locator@0x127053000 [DiscardAssignment@79078.swift:4:5] $T1 as (@escaping () async -> Void, (@escaping () async -> Void) async -> Void) async -> Void @ locator@0x127053068 [DeclRef@79078.swift:4:15] $T2 as () async -> Void @ locator@0x1270530b0 [DeclRef@79078.swift:4:15 → function argument] $T3 as () async -> Void @ locator@0x1270530b0 [DeclRef@79078.swift:4:15 → function argument] Overload choices: locator@0x127053068 [DeclRef@79078.swift:4:15] with Swift.(file).withoutActuallyEscaping(_:do:) as withoutActuallyEscaping: ($T2, ($T3) async throws($T5) -> $T4) async throws($T5) -> $T4
withAsyncをtrueにしないようにする方向かなと思っています。 (edited)Meanwhile maybe there is a way to workaround in SILGen the fact that there is always a async as a temporary fix?
と言われたので、asyncをなくすのではなく、すべてをasyncとして扱う方法を模索してみます。 https://github.com/swiftlang/swift/pull/79238#discussion_r1953450650utils/update-checkout
を実行するとrebase中にコンフリクトが発生するのですがこれは僕のローカル環境が何かおかしいですか? swift-DEVELOPMENT-SNAPSHOT-2025-02-09-a
で作業していたのをswift-DEVELOPMENT-SNAPSHOT-2025-02-20-a
で作業するように更新したいのですが... (edited)swift/utils/update-checkout --tag swift-DEVELOPMENT-SNAPSHOT-2025-02-09-a
してから swift/utils/update-checkout --tag swift-DEVELOPMENT-SNAPSHOT-2025-02-20-a
してみましたがconflictは起きませんでした。swift/utils/update-checkout --tag swift-DEVELOPMENT-SNAPSHOT-2025-02-20-a
後に出力されたハッシュ一覧(使われなくなったリポジトリも含まれる)を貼っておきます。utils/update-checkout --tag swift-DEVELOPMENT-SNAPSHOT-2025-02-09-a
→utils/update-checkout --tag swift-DEVELOPMENT-SNAPSHOT-2025-02-20-a
で順番に実行したらうまくいきましたimport SwiftSyntax
と書くとerror: no such module 'SwiftSyntax'
とエラーになります。 ドキュメントを見落としているだけかもしれませんが、何か方法はありますでしょうか?let sourceFile = Parser.parse( source: """ let numbers = [1, 2, 3, 4, 5] #assert(numbers[2] == 4) """ ) let macros: [String: any Macro.Type] = [ "assert": PowerAssertMacro.self, ] let context = BasicMacroExpansionContext( sourceFiles: [sourceFile: .init(moduleName: testModuleName, fullFilePath: testFileName)] ) let expanded = "\(sourceFile.expand(macros: macros, in: context))" ...
PowerAssertMacro.self
を追加してるからマクロプラグインターゲットもテストターゲットに追加するのかな... .testTarget( name: "PowerAssertTests", dependencies: [ "PowerAssertPlugin", "PowerAssert", .product(name: "SwiftSyntaxMacrosTestSupport", package: "swift-syntax"), ] ),
テストの依存関係はこういうふうに構成しますね。テスト対象はPowerAssertモジュール。lazy_parsing.swift
はなんかマクロ処理の複雑なことをやってるんじゃないですかね// RUN: %host-build-swift -swift-version 5 -emit-library -o %t/%target-library-name(MacroDefinition) -module-name=MacroDefinition %S/Inputs/syntax_macro_definitions.swift -g -no-toolchain-stdlib-rpath
... .testTarget( name: "PowerAssertTests", dependencies: [ "PowerAssertPlugin", "PowerAssert", .product(name: "SwiftSyntaxMacrosTestSupport", package: "swift-syntax"), ] ),
テストの依存関係はこういうふうに構成しますね。テスト対象はPowerAssertモジュール。 import PowerAssert
は不要なはず。import Foundation
/import FoundationEssentials
してないswiftc -sdk /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX15.2.sdk -target arm64-apple-macosx13.0 -I /Users/myname/swift-project/build/Ninja-RelWithDebInfoAssert/swift-macosx-arm64/lib/swift/host -L /Users/myname/swift-project/build/Ninja-RelWithDebInfoAssert/swift-macosx-arm64/lib/swift/host -emit-library -o /Users/myname/swift-project/work/libMacroDefinition.dylib -parse-as-library -module-name=MacroDefinition /Users/myname/swift-project/work/macro.swift -g -no-toolchain-stdlib-rpath -swift-version 5
-load-plugin-library
で読み込めました ↓ は swift-frontend scheme の Arguments Passed on Launch の中身です -load-plugin-library /Users/myname/swift-project/work/libMacroDefinition.dylib -parse-as-library -module-name=MacroDefinition -emit-ir test.swift
(edited)